Diff for /loncom/auth/lonauth.pm between versions 1.121.2.23 and 1.175

version 1.121.2.23, 2021/12/16 21:48:19 version 1.175, 2022/06/26 04:03:47
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # User Authentication Module  # User Authentication Module
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonauth;  package Apache::lonauth;
   
 use strict;  use strict;
 use LONCAPA;  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::lonmenu();  use Apache::lonmenu();
 use Apache::createaccount;  use Apache::createaccount;
 use Fcntl qw(:flock);  use Apache::ltiauth;
 use Apache::lonlocal;  use Fcntl qw(:flock);
 use Apache::File();  use Apache::lonlocal;
 use HTML::Entities;  use Apache::File();
 use Digest::MD5;  use HTML::Entities;
    use Digest::MD5;
 # ------------------------------------------------------------ Successful login  use CGI::Cookie();
 sub success {   
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,  # ------------------------------------------------------------ Successful login
  $form,$cid,$expirepub) = @_;  sub success {
       my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
 # ------------------------------------------------------------ Get cookie ready   $form,$skipcritical,$cid,$expirepub) = @_;
     my $cookie =  
  &Apache::loncommon::init_user_environment($r, $username, $domain,  # ------------------------------------------------------------ Get cookie ready
   $authhost, $form,      my $cookie =
   {'extra_env' => $extra_env,});   &Apache::loncommon::init_user_environment($r, $username, $domain,
     $authhost, $form,
     my $public=($username eq 'public' && $domain eq 'public');    {'extra_env' => $extra_env,});
   
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }      my $public=($username eq 'public' && $domain eq 'public');
   
 # -------------------------------------------------------------------- Log this      if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   
     my $ip = &Apache::lonnet::get_requestor_ip();  # -------------------------------------------------------------------- Log this
     &Apache::lonnet::log($domain,$username,$authhost,  
                          "Login $ip");      my $ip = &Apache::lonnet::get_requestor_ip();
       &Apache::lonnet::log($domain,$username,$authhost,
 # ------------------------------------------------- Check for critical messages                           "Login $ip");
   
     my @what=&Apache::lonnet::dump('critical',$domain,$username);  # ------------------------------------------------- Check for critical messages
     if ($what[0]) {  
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {      unless ($skipcritical) {
     $lowerurl='/adm/email?critical=display';          my @what=&Apache::lonnet::dump('critical',$domain,$username);
         }          if ($what[0]) {
     }      if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
           $lowerurl='/adm/email?critical=display';
 # ------------------------------------------------------------ Get cookies ready              }
     my ($securecookie,$defaultcookie);          }
     my $ssl = $r->subprocess_env('https');      }
     if ($ssl) {  
         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";  # ----------------------------------------------------------- Get cookies ready
         my $lonidsdir=$r->dir_config('lonIDsDir');      my ($securecookie,$defaultcookie);
         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {      my $ssl = $r->subprocess_env('https');
             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';      if ($ssl) {
             if (-e "$lonidsdir/$linkname.id") {          $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
                 unlink("$lonidsdir/$linkname.id");          my $lonidsdir=$r->dir_config('lonIDsDir');
             }          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
                                               "$lonidsdir/$linkname.id"); 1 };              if (-e "$lonidsdir/$linkname.id") {
             if ($made_symlink) {                  unlink("$lonidsdir/$linkname.id");
                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";              }
                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
             }                                                "$lonidsdir/$linkname.id"); 1 };
         }              if ($made_symlink) {
     } else {                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";                  &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
     }              }
 # -------------------------------------------------------- Menu script and info          }
     my $destination = $lowerurl;      } else {
           $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
     if (defined($form->{role})) {      }
         my $envkey = 'user.role.'.$form->{role};  # -------------------------------------------------------- Menu script and info
         my $now=time;      my $destination = $lowerurl;
         my $then=$env{'user.login.time'};      if ($env{'request.lti.login'}) {
         my $refresh=$env{'user.refresh.time'};          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         my $update=$env{'user.update.time'};              &Apache::loncommon::content_type($r,'text/html');
         if (!$update) {              if ($securecookie) {
             $update = $then;                  $r->headers_out->add('Set-cookie' => $securecookie);
         }              }
         if (exists($env{$envkey})) {              if ($defaultcookie) {
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);                  $r->headers_out->add('Set-cookie' => $defaultcookie);
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,              }
                                          \$trolecode,\$tstatus,\$tstart,\$tend);              $r->send_http_header;
             if ($tstatus eq 'is') {              if (ref($form) eq 'HASH') {
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $form->{'lti.login'} = $env{'request.lti.login'};
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');                  $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
                 $destination .= 'selectrole=1&'.$newrole.'=1';                  $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
             }                  $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
         }              }
     }              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
     if (defined($form->{symb})) {              return;
         my $destsymb = $form->{symb};          }
         my $encrypted;          if ($env{'request.lti.selfenrollrole'}) {
         if ($destsymb =~ m{^/enc/}) {              if (&Apache::ltiauth::lti_enroll($username,$domain,
             $encrypted = 1;                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
             if ($cid) {                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
             }              } else {
         }                  &Apache::ltiauth::invalid_request($r,24);
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              }
         if ($destsymb =~ /___/) {          }
             my ($map,$resid,$desturl)=split(/___/,$destsymb);      }
             $desturl = &Apache::lonnet::clutter($desturl);      if (defined($form->{role})) {
             if ($encrypted) {          my $envkey = 'user.role.'.$form->{role};
                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);          my $now=time;
                 $destsymb = $form->{symb};          my $then=$env{'user.login.time'};
             }          my $refresh=$env{'user.refresh.time'};
             $desturl = &HTML::Entities::encode($desturl,'"<>&');          my $update=$env{'user.update.time'};
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');          if (!$update) {
             $destination .= 'destinationurl='.$desturl.              $update = $then;
                             '&destsymb='.$destsymb;          }
         } elsif (!$encrypted) {          if (exists($env{$envkey})) {
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
             $destination .= 'destinationurl='.$destsymb;              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
         }                                           \$trolecode,\$tstatus,\$tstart,\$tend);
     }              if ($tstatus eq 'is') {
     if ($destination =~ m{^/adm/roles}) {                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
         $destination  .= ($destination =~ /\?/) ? '&' : '?';                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
         $destination .= 'source=login';                  $destination .= 'selectrole=1&'.$newrole.'=1';
     }              }
           }
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});      }
     my $startupremote=&Apache::lonmenu::startupremote($destination);      if (defined($form->{symb})) {
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);          my $destsymb = $form->{symb};
     my $setflags=&Apache::lonmenu::setflags();          my $encrypted;
     my $maincall=&Apache::lonmenu::maincall();          if ($destsymb =~ m{^/enc/}) {
     my $brcrum = [{'href' => '',              $encrypted = 1;
                    'text' => 'Successful Login'},];              if ($cid) {
     my $start_page=&Apache::loncommon::start_page('Successful Login',                  $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
                                                   $startupremote,              }
                                                   {'no_inline_link' => 1,          }
                                                    'bread_crumbs' => $brcrum,});          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     my $end_page  =&Apache::loncommon::end_page();          if ($destsymb =~ /___/) {
               my ($map,$resid,$desturl)=split(/___/,$destsymb);
     my $continuelink;              $desturl = &Apache::lonnet::clutter($desturl);
     if ($env{'environment.remote'} eq 'off') {              if ($encrypted) {
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';                  $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
     }                  $destsymb = $form->{symb};
 # ------------------------------------------------- Output for successful login              }
               $desturl = &HTML::Entities::encode($desturl,'"<>&');
     &Apache::loncommon::content_type($r,'text/html');              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     if ($securecookie) {              $destination .= 'destinationurl='.$desturl.
         $r->headers_out->add('Set-cookie' => $securecookie);                              '&destsymb='.$destsymb;
     }          } elsif (!$encrypted) {
     if ($defaultcookie) {              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
         $r->headers_out->add('Set-cookie' => $defaultcookie);              $destination .= 'destinationurl='.$destsymb;
     }          }
     if ($expirepub) {      }
         my $c = new CGI::Cookie(-name    => 'lonPubID',      if ($destination =~ m{^/adm/roles}) {
                                 -value   => '',          $destination  .= ($destination =~ /\?/) ? '&' : '?';
                                 -expires => '-10y',);          $destination .= 'source=login';
         $r->headers_out->add('Set-cookie' => $c);      }
     }  
     $r->send_http_header;      my $brcrum = [{'href' => '',
                      'text' => 'Successful Login'},];
     my %lt=&Apache::lonlocal::texthash(      my $args = {'no_inline_link' => 1,
        'wel' => 'Welcome',                  'bread_crumbs' => $brcrum,};
        'pro' => 'Login problems?',      if (($env{'request.deeplink.login'} eq $lowerurl) &&
        );          (($env{'request.linkprot'}) || ($env{'request.linkkey'} ne ''))) {
     my $loginhelp = &loginhelpdisplay($domain);          my %info;
     if ($loginhelp) {          if ($env{'request.linkprot'}) {
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';              $info{'linkprot'} = $env{'request.linkprot'};
     }              if ($form->{'linkprotuser'}) {
                   $info{'linkprotuser'} = $form->{'linkprotuser'};
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');               }
     $r->print(<<ENDSUCCESS);              $args = {'only_body' => 1,};
 $start_page          } elsif ($env{'request.linkkey'} ne '') {
 $setflags              $info{'linkkey'} = $env{'request.linkkey'};
 $windowinfo          }
 <h1>$lt{'wel'}</h1>          $info{'origurl'} = $lowerurl;
 $welcome          my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
 $loginhelp          unless (($token eq 'con_lost') || ($token eq 'refused') ||
 $remoteinfo                  ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
 $maincall              $destination .= (($destination =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
 $continuelink          }
 $end_page      }
 ENDSUCCESS  
     return;      my $windowname = 'loncapaclient';
 }      if ($env{'request.lti.login'}) {
           $windowname .= 'lti';
 # --------------------------------------------------------------- Failed login!      }
       my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
 sub failed {      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     my ($r,$message,$form,$authhost) = @_;          my $update=$env{'user.update.time'};
     (undef,undef,undef,my $clientmathml,my $clientunicode) =          if (!$update) {
         &Apache::loncommon::decode_user_agent();              $update = $env{'user.login.time'};
     my $args = {};          }
     if ($clientunicode && !$clientmathml) {          my %roles_in_env;
         $args = {'browser.unicode' => 1};          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
     }          if ($showcount == 1) {
               foreach my $rolecode (keys(%roles_in_env)) {
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});                  if ($cid) {
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});                      my %coursedescription =
     if (&Apache::lonnet::domain($udom,'description') eq '') {                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
         undef($udom);                      if ($coursedescription{'type'} eq 'Placement') {
     }                          $args->{'crstype'} = 'Placement';
     my $retry = '/adm/login';                      }
     if ($uname eq $form->{'uname'}) {                      last;
         $retry .= '?username='.$uname;                  }
     }              }
     if ($udom) {          }
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;      }
     }  
     my $lonhost = $r->dir_config('lonHostID');  # ------------------------------------------------- Output for successful login
     my $querystr;  
     my $result = &set_retry_token($form,$lonhost,\$querystr);      &Apache::loncommon::content_type($r,'text/html');
     if ($result eq 'fail') {      if ($securecookie) {
         if (exists($form->{role})) {          $r->headers_out->add('Set-cookie' => $securecookie);
             my $role = &Apache::loncommon::cleanup_html($form->{role});      }
             if ($role ne '') {      if ($defaultcookie) {
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;          $r->headers_out->add('Set-cookie' => $defaultcookie);
             }      }
         }      if ($expirepub) {
         if (exists($form->{symb})) {          my $c = new CGI::Cookie(-name    => 'lonPubID',
             my $symb = &Apache::loncommon::cleanup_html($form->{symb});                                  -value   => '',
             if ($symb ne '') {                                  -expires => '-10y',);
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;          $r->headers_out->add('Set-cookie' => $c);
             }      }
         }      $r->send_http_header;
         if (exists($form->{firsturl})) {  
             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});      my ($start_page,$js,$pagebody,$end_page);
             if ($firsturl ne '') {      if ($env{'request.lti.login'}) {
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;          $args = {'only_body' => 1};
             }          if ($env{'request.lti.target'} eq '') {
         }              my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
     } elsif ($querystr ne '') {                              'ltitarget=iframe';
         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;              &js_escape(\$destination);
     }              $js = <<"ENDJS";
     my $end_page = &Apache::loncommon::end_page();  
     &Apache::loncommon::content_type($r,'text/html');  <script type="text/javascript">
     $r->send_http_header;  // <![CDATA[
     my @actions =  function setLTItarget() {
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));      var newloc = '$destination';
     my $loginhelp = &loginhelpdisplay($udom);      if (parent !== window) {
     if ($loginhelp) {          newloc += '$ltitarget';
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');      }
     }      window.location.href=newloc;
     #FIXME: link to helpdesk might be added here  }
   // ]]>
     $r->print(  </script>
        $start_page  
       .'<h2>'.&mt('Sorry ...').'</h2>'  ENDJS
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'              $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
       .&Apache::lonhtmlcommon::actionbox(\@actions)              $pagebody =  '<noscript><span class="LC_warning">'
       .$end_page                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
     );                          .'</span></noscript>';
  }          } else {
               $args->{'redirect'} = [0,$destination,1];
 # ------------------------------------------------------------------ Rerouting!          }
           $start_page=&Apache::loncommon::start_page('',$js,$args);
 sub reroute {      } else {
     my ($r) = @_;          $args->{'redirect'} = [0,$destination];
     &Apache::loncommon::content_type($r,'text/html');          $start_page=&Apache::loncommon::start_page('Successful Login',
     $r->send_http_header;                                                     $js,$args);
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'          unless ($env{'request.linkprot'}) {
            .&mt('Please [_1]log in again[_2].');              my %lt=&Apache::lonlocal::texthash(
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});                     'wel' => 'Welcome',
 }                 'pro' => 'Login problems?',
             );
 # ---------------------------------------------------------------- Main handler              $pagebody = "<h1>$lt{'wel'}</h1>\n".
                           &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
 sub handler {              my $loginhelp = &loginhelpdisplay($domain);
     my $r = shift;              if ($loginhelp) {
     my $londocroot = $r->dir_config('lonDocRoot');                  $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
 # Are we re-routing?              }
     if (-e "$londocroot/lon-status/reroute.txt") {          }
  &reroute($r);      }
  return OK;      $end_page = &Apache::loncommon::end_page();
     }      $r->print(<<ENDSUCCESS);
   $start_page
     &Apache::lonlocal::get_language_handle($r);  $windowinfo
   $pagebody
 # -------------------------------- Prevent users from attempting to login twice  $end_page
     my $handle = &Apache::lonnet::check_for_valid_session($r);  ENDSUCCESS
     if ($handle ne '') {      return;
         my $lonidsdir=$r->dir_config('lonIDsDir');  }
         if ($handle=~/^publicuser\_/) {  
 # For "public user" - remove it, we apparently really want to login  # --------------------------------------------------------------- Failed login!
             unlink($r->dir_config('lonIDsDir')."/$handle.id");  
         } else {  sub failed {
 # Indeed, a valid token is found      my ($r,$message,$form,$authhost) = @_;
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);      (undef,undef,undef,my $clientmathml,my $clientunicode) =
     &Apache::loncommon::content_type($r,'text/html');          &Apache::loncommon::decode_user_agent();
     $r->send_http_header;      my $args = {};
     my $start_page =       if ($clientunicode && !$clientmathml) {
         &Apache::loncommon::start_page('Already logged in');          $args = {'browser.unicode' => 1};
     my $end_page =       }
         &Apache::loncommon::end_page();      if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
             my $dest = '/adm/roles';          if ($form->{linkprot}) {
             my %form = &get_form_items($r);              $args->{only_body} = 1;
             if ($form{'logtoken'}) {          }
                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},      }
                                                      $form{'serverid'});  
                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||      my @actions;
                         ($tmpinfo eq 'no_such_host')) {      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
                     $firsturl = &unescape($firsturl);      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
                     my %info;      if (&Apache::lonnet::domain($udom,'description') eq '') {
                     foreach my $item (@rest) {          undef($udom);
                         my ($key,$value) = split(/=/,$item);      }
                         $info{$key} = &unescape($value);      my $authtype;
                     }      if (($udom ne '') && ($uname ne '') && ($authhost eq 'no_host')) {
                     if ($firsturl ne '') {          $authtype = &Apache::lonnet::queryauthenticate($uname,$udom);
                         $info{'firsturl'} = $firsturl;      }
                         $dest = $firsturl;      my $retry = '/adm/login';
                     }      if (($uname eq $form->{'uname'}) && ($authtype !~ /^lti:/)) {
                 }          $retry .= '?username='.$uname;
             }      }
             $r->print(      if ($udom) {
                $start_page          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'      }
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'      my $lonhost = $r->dir_config('lonHostID');
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')      my $querystr;
               .'</p>'      my $result = &set_retry_token($form,$lonhost,\$querystr);
               .$end_page      if ($result eq 'fail') {
             );          if (exists($form->{role})) {
             return OK;              my $role = &Apache::loncommon::cleanup_html($form->{role});
         }              if ($role ne '') {
     }                  $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
               }
 # ---------------------------------------------------- No valid token, continue          }
           if (exists($form->{symb})) {
     my %form = &get_form_items($r);              my $symb = &Apache::loncommon::cleanup_html($form->{symb});
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {              if ($symb ne '') {
  &failed($r,'Username, password and domain need to be specified.',                  $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
  \%form);              }
         return OK;          }
     }          if (exists($form->{firsturl})) {
               my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
 # split user logging in and "su"-user              if ($firsturl ne '') {
                   $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});                  if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});                      unless (exists($form->{linkprot})) {
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});                          if (exists($form->{linkkey})) {
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});                              $retry .= 'linkkey='.$form->{linkkey};
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});                          }
                       }
     my $role   = $r->dir_config('lonRole');                  }
     my $domain = $r->dir_config('lonDefDomain');              }
     my $prodir = $r->dir_config('lonUsersDir');          }
     my $contact_name = &mt('LON-CAPA helpdesk');          if (exists($form->{linkprot})) {
               my %info = (
 # ---------------------------------------- Get the information from login token                           'linkprot' => $form->{'linkprot'},
                          );
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},              if ($form->{linkprotuser} ne '') {
                                       $form{'serverid'});                  $info{'linkprotuser'} = $form->{linkprotuser};
               }
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||               my $ltoken = &Apache::lonnet::tmpput(\%info,
         ($tmpinfo eq 'no_such_host')) {                                                   $r->dir_config('lonHostID'),'retry');
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);              if ($ltoken) {
         return OK;                  $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
     } else {              }
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},          }
    $form{'serverid'});      } elsif ($querystr ne '') {
         if ( $reply ne 'ok' ) {          $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;
             &failed($r,'Session could not be opened.',\%form);      }
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");      my $end_page = &Apache::loncommon::end_page();
     return OK;      &Apache::loncommon::content_type($r,'text/html');
  }      $r->send_http_header;
     }      if ($authtype =~ /^lti:/) {
           $message = &mt('Direct login is not supported with the username you entered.').
     if (!&Apache::lonnet::domain($form{'udom'})) {                     '<br /><br />'.
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);                     &mt('You likely need to launch LON-CAPA from within a course in a different Learning Management System.').
         return OK;                     '<br />'.
     }                     &mt('You can also try to log in with a different username.');
           @actions =
     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);              (&mt('Try your [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
     $firsturl = &unescape($firsturl);      } else {
     foreach my $item (@rest) {          $message = &mt($message);
         my ($key,$value) = split(/=/,$item);          @actions =
         $form{$key} = &unescape($value);              (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
     }      }
     my $upass = &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});      my $loginhelp = &loginhelpdisplay($udom);
       if ($loginhelp) {
 # ---------------------------------------------------------------- Authenticate          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
       }
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});      #FIXME: link to helpdesk might be added here
     my ($cancreate,$statustocreate) =      $r->print(
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});         $start_page
     my $defaultauth;        .'<h2>'.&mt('Sorry ...').'</h2>'
     if (ref($cancreate) eq 'ARRAY') {        .&Apache::lonhtmlcommon::confirm_success($message,1).'<br /><br />'
         if (grep(/^login$/,@{$cancreate})) {        .&Apache::lonhtmlcommon::actionbox(\@actions)
             $defaultauth = 1;        .$end_page
         }      );
     }   }
     my $clientcancheckhost = 1;  
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,  # ------------------------------------------------------------------ Rerouting!
                                               $form{'udom'},$defaultauth,  
                                               $clientcancheckhost);  sub reroute {
           my ($r) = @_;
 # --------------------------------------------------------------------- Failed?      &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
     if ($authhost eq 'no_host') {      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  &failed($r,'Username and/or password could not be authenticated.',             .&mt('Please [_1]log in again[_2].');
  \%form);      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
         return OK;  }
     } elsif ($authhost eq 'no_account_on_host') {  
         if ($defaultauth) {  # ---------------------------------------------------------------- Main handler
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');  
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {  sub handler {
                 return OK;      my $r = shift;
             }      my $londocroot = $r->dir_config('lonDocRoot');
             my $start_page =   # Are we re-routing?
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',      if (-e "$londocroot/lon-status/reroute.txt") {
                                                '',{'no_inline_link'   => 1,});   &reroute($r);
             my $lonhost = $r->dir_config('lonHostID');   return OK;
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      }
             my $contacts =   
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',      &Apache::lonlocal::get_language_handle($r);
                                                         $form{'udom'},$origmail);  
             my ($contact_email) = split(',',$contacts);   # -------------------------------- Prevent users from attempting to login twice
             my $output =       my $handle = &Apache::lonnet::check_for_valid_session($r);
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},      if ($handle ne '') {
                                                        $domdesc,'',$lonhost,          my $lonidsdir=$r->dir_config('lonIDsDir');
                                                        $contact_email,$contact_name,          if ($handle=~/^publicuser\_/) {
                                                        undef,$statustocreate);  # For "public user" - remove it, we apparently really want to login
             &Apache::loncommon::content_type($r,'text/html');              unlink($r->dir_config('lonIDsDir')."/$handle.id");
             $r->send_http_header;          } else {
             &Apache::createaccount::print_header($r,$start_page);  # Indeed, a valid token is found
             $r->print('<h3>'.&mt('Account creation').'</h3>'.              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.      &Apache::loncommon::content_type($r,'text/html');
                       $output.&Apache::loncommon::end_page());      $r->send_http_header;
             return OK;      my $start_page =
         } else {          &Apache::loncommon::start_page('Already logged in');
             &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);      my $end_page =
             return OK;          &Apache::loncommon::end_page();
         }              my $dest = '/adm/roles';
     }              my %form = &get_form_items($r);
               if ($form{'logtoken'}) {
     if (($firsturl eq '') ||                   my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  ($firsturl=~/^\/adm\/(logout|remote)/)) {                                                       $form{'serverid'});
  $firsturl='/adm/roles';                  unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
     }                          ($tmpinfo eq 'no_such_host')) {
                       my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
     my ($hosthere,%sessiondata);                      $firsturl = &unescape($firsturl);
     if ($form{'iptoken'}) {                      my %info;
         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});                      foreach my $item (@rest) {
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});                          my ($key,$value) = split(/=/,$item);
         if (($sessiondata{'domain'} eq $form{'udom'}) &&                          $info{$key} = &unescape($value);
             ($sessiondata{'username'} eq $form{'uname'})) {                      }
             $hosthere = 1;                      if ($firsturl ne '') {
         }                          $info{'firsturl'} = $firsturl;
     }                          $dest = $firsturl;
                           my $relogin;
 # --------------------------------- Are we attempting to login as somebody else?                          if ($dest =~ m{^/tiny/$match_domain/\w+$}) {
     if ($form{'suname'}) {                              if ($env{'request.course.id'}) {
         my ($suname,$sudom,$sudomref);                                  my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
         $suname = $form{'suname'};                                  my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
         $sudom = $form{'udom'};                                  my $symb = &Apache::loncommon::symb_from_tinyurl($dest,$cnum,$cdom);
         if ($form{'sudom'}) {                                  if ($symb) {
             unless ($sudom eq $form{'sudom'}) {                                      unless (&set_deeplink_login(%info) eq 'ok') {
                 if (&Apache::lonnet::domain($form{'sudom'})) {                                          $relogin = 1;
                     $sudomref = [$form{'sudom'}];                                      }
                     $sudom = $form{'sudom'};                                  }
                 }                              }
             }                              if ($relogin) {
         }                                  $r->print(
 # ------------ see if the original user has enough privileges to pull this stunt                                        $start_page
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {                                       .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
 # ---------------------------------------------------- see if the su-user exists                                       .'<p>'.&mt('Please [_1]log out[_2] first, and then try your access again',
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {                                                  '<a href="/adm/logout">','</a>')
 # ------------------------------ see if the su-user is not too highly privileged                                       .'</p>'
  if (&Apache::lonnet::privileged($suname,$sudom)) {                                       .$end_page);
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');                              } else {
                 } else {                                  if (($info{'linkprot'}) || ($info{'linkkey'} ne '')) {
                     my $noprivswitch;                                      if (($info{'linkprot'}) && ($info{'linkprotuser'} ne '')) {
 #                                          unless ($info{'linkprotuser'} eq $env{'user.name'}.':'.$env{'user.domain'}) {
 # su-user's home server and user's home server must have one of:                                              $r->print(
 # (a) same domain                                                        $start_page
 # (b) same primary library server for the two domains                                                        .'<p class="LC_warning">'.&mt('You are already logged in, but as a different user from the one expected for the link you followed from another system').'</p>'
 # (c) same "internet domain" for primary library server(s) for home servers' domains                                                        .'<p>'.&mt('Please [_1]log out[_2] first, and then try following the link again from the other system',
 #                                                                   '<a href="/adm/logout">','</a>')
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');  
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);                                                        .'</p>'
                     unless ($sudom eq $form{'udom'}) {                                                        .$end_page);
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');                                              return OK;
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);                                          }
                         unless ($suprim eq $uprim) {                                      }
                             unless ($suintdom eq $uintdom) {                                      my $token = &Apache::lonnet::tmpput(\%info,$r->dir_config('lonHostID'),'link');
                                 &Apache::lonnet::logthis('Attempted switch user '                                      unless (($token eq 'con_lost') || ($token eq 'refused') ||
                                    .'to user with different "internet domain".');                                              ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                                 $noprivswitch = 1;                                          $dest .= (($dest =~ /\?/) ? '&' : '?') . 'ttoken='.$token;
                             }                                      }
                         }                                  }
                     }                                  $r->print(
                                         $start_page
                     unless ($noprivswitch) {                                       .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
 #                                       .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4] first, and then try your access again',
 # server where log-in occurs must have same "internet domain" as su-user's home                                                  '<a href="'.$dest.'">','</a>',
 # server                                                  '<a href="/adm/logout">','</a>')
 #                                       .'</p>'
                         my $lonhost = $r->dir_config('lonHostID');                                       .$end_page);
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);                              }
                         if ($hostintdom ne $suintdom) {                              return OK;
                             &Apache::lonnet::logthis('Attempted switch user on a '                          }
                                 .'server with a different "internet domain".');                      }
                         } else {                  }
               }
 # -------------------------------------------------------- actually switch users              $r->print(
                     $start_page
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);                   .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
     $form{'uname'}=$suname;                            ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
                             if ($form{'udom'} ne $sudom) {                   .'</p>'
                                 $form{'udom'}=$sudom;                   .$end_page
                             }              );
                         }              return OK;
                     }          }
  }      }
     }  
  } else {  # ---------------------------------------------------- No valid token, continue
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');  
  }      my %form = &get_form_items($r);
     }      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
    &failed($r,'Username, password and domain need to be specified.',
     my ($is_balancer,$otherserver);   \%form);
           return OK;
     unless ($hosthere) {      }
         ($is_balancer,$otherserver) =  
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');  # split user logging in and "su"-user
         if ($is_balancer) {  
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
                 $otherserver = $found_server;      $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
             }      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
             if ($otherserver eq '') {  
                 my $lowest_load;      my $role   = $r->dir_config('lonRole');
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});      my $domain = $r->dir_config('lonDefDomain');
                 if ($lowest_load > 100) {      my $prodir = $r->dir_config('lonUsersDir');
                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});      my $contact_name = &mt('LON-CAPA helpdesk');
                 }  
             }  # ---------------------------------------- Get the information from login token
             if ($otherserver ne '') {  
                 my @hosts = &Apache::lonnet::current_machine_ids();      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {                                        $form{'serverid'});
                     $hosthere = $otherserver;  
                 }      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
             }          ($tmpinfo eq 'no_such_host')) {
         }   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
     }          return OK;
       } else {
     if (($is_balancer) && (!$hosthere)) {   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
         if ($otherserver) {     $form{'serverid'});
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,          if ( $reply ne 'ok' ) {
                      \%form);              &failed($r,'Session could not be opened.',\%form);
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {      return OK;
                 $switchto .= '&origurl='.$firsturl;   }
             }      }
             if ($form{'role'}) {  
                 $switchto .= '&role='.$form{'role'};      if (!&Apache::lonnet::domain($form{'udom'})) {
             }          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
             if ($form{'symb'}) {          return OK;
                 $switchto .= '&symb='.$form{'symb'};      }
             }  
             $r->internal_redirect($switchto);      my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);
         } else {      $firsturl = &unescape($firsturl);
             &Apache::loncommon::content_type($r,'text/html');      foreach my $item (@rest) {
             $r->send_http_header;          my ($key,$value) = split(/=/,$item);
             $r->print(&noswitch());          $form{$key} = &unescape($value);
         }      }
         return OK;      if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
     } else {          $form{'firsturl'} = $firsturl;
         if (!&check_can_host($r,\%form,$authhost)) {      }
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});      my $upass = $ENV{HTTPS} ? $form{'upass0'}
             if ($otherserver) {          : &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,  
                          \%form);  # ---------------------------------------------------------------- Authenticate
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;  
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
                     $switchto .= '&origurl='.$firsturl;      my ($cancreate,$statustocreate) =
                 }          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
                 if ($form{'role'}) {      my $defaultauth;
                     $switchto .= '&role='.$form{'role'};      if (ref($cancreate) eq 'ARRAY') {
                 }          if (grep(/^login$/,@{$cancreate})) {
                 if ($form{'symb'}) {              $defaultauth = 1;
                     $switchto .= '&symb='.$form{'symb'};          }
                 }      }
                 $r->internal_redirect($switchto);      my $clientcancheckhost = 1;
             } else {      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
                 &Apache::loncommon::content_type($r,'text/html');                                                $form{'udom'},$defaultauth,
                 $r->send_http_header;                                                $clientcancheckhost);
                 $r->print(&noswitch());  
             }  # --------------------------------------------------------------------- Failed?
             return OK;  
         }      if ($authhost eq 'no_host') {
           my $pwdverify;
 # ------------------------------------------------------- Do the load balancing          if (&Apache::lonnet::homeserver($form{'uname'},$form{'udom'}) eq 'no_host') {
               my %possunames = &alternate_unames_check($form{'uname'},$form{'udom'});
 # ---------------------------------------------------------- Determine own load              if (keys(%possunames) > 0) {
         my $loadlim = $r->dir_config('lonLoadLim');                  foreach my $rulematch (keys(%possunames)) {
         my $loadavg;                      my $possuname = $possunames{$rulematch};
         {                      if (($possuname ne '') && ($possuname =~ /^$match_username$/)) {
             my $loadfile=Apache::File->new('/proc/loadavg');                          $authhost=Apache::lonnet::authenticate($possuname,$upass,
             $loadavg=<$loadfile>;                                                                 $form{'udom'},undef,
         }                                                                 $clientcancheckhost);
         $loadavg =~ s/\s.*//g;                          if (($authhost eq 'no_host') || ($authhost eq 'no_account_on_host')) {
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);                              next;
         my $userloadpercent=&Apache::lonnet::userload();                          } elsif (($authhost ne '') && (&Apache::lonnet::hostname($authhost) ne '')) {
                               $pwdverify = 1;
 # ---------------------------------------------------------- Are we overloaded?                              &Apache::lonnet::logthis("Authenticated user: $possuname was submitted as: $form{'uname'}");
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {                              $form{'uname'} = $possuname;
             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});                              last;
             if (!$unloaded) {                          }
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});                      }
             }                  }
             if ($unloaded) {              }
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',          }
                          undef,\%form);          unless ($pwdverify) {
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);              &failed($r,'Username and/or password could not be authenticated.',
                 return OK;                      \%form,$authhost);
             }              return OK;
         }          }
         if (($is_balancer) && ($hosthere)) {      } elsif ($authhost eq 'no_account_on_host') {
             $form{'noloadbalance'} = $hosthere;          if ($defaultauth) {
         }              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
         my $extra_env;              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {                  return OK;
             if ($sessiondata{'origurl'} ne '') {              }
                 $firsturl = $sessiondata{'origurl'};              my $start_page =
                 $form{'firsturl'} = $sessiondata{'origurl'};                  &Apache::loncommon::start_page('Create a user account in LON-CAPA',
                 my @names = ('role','symb','linkprot','linkkey');                                                 '',{'no_inline_link'   => 1,});
                 foreach my $item (@names) {              my $lonhost = $r->dir_config('lonHostID');
                     if ($sessiondata{$item} ne '') {              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                         $form{$item} = $sessiondata{$item};              my $contacts =
                     }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                 }                                                          $form{'udom'},$origmail);
             }              my ($contact_email) = split(',',$contacts);
         }              my $output =
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                  \%form);                                                         $domdesc,'',$lonhost,
         return OK;                                                         $contact_email,$contact_name,
     }                                                         undef,$statustocreate);
 }              &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
 sub get_form_items {              &Apache::createaccount::print_header($r,$start_page);
     my ($r) = @_;              $r->print('<h3>'.&mt('Account creation').'</h3>'.
     my $buffer;                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
     if ($r->header_in('Content-length') > 0) {                        $output.&Apache::loncommon::end_page());
         $r->read($buffer,$r->header_in('Content-length'),0);              return OK;
     }          } else {
     my %form;              &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);
     foreach my $pair (split(/&/,$buffer)) {              return OK;
        my ($name,$value) = split(/=/,$pair);          }
        $value =~ tr/+/ /;      }
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;  
        $form{$name}=$value;      if (($firsturl eq '') ||
     }   ($firsturl=~/^\/adm\/(logout|remote)/)) {
     return %form;   $firsturl='/adm/roles';
 }      }
   
 sub set_retry_token {      my ($hosthere,%sessiondata);
     my ($form,$lonhost,$querystr) = @_;      if ($form{'iptoken'}) {
     if (ref($form) eq 'HASH') {          %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
         my ($firsturl,$token,$extras,@names);          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
         @names = ('role','symb','iptoken');          if (($sessiondata{'domain'} eq $form{'udom'}) &&
         foreach my $name (@names) {              ($sessiondata{'username'} eq $form{'uname'})) {
             if ($form->{$name} ne '') {              $hosthere = 1;
                 $extras .= '&'.$name.'='.&escape($form->{$name});          }
                 last if ($name eq 'linkprot');      }
             }  
         }  # --------------------------------- Are we attempting to login as somebody else?
         my $firsturl = $form->{'firsturl'};      if ($form{'suname'}) {
         if (($firsturl ne '') || ($extras ne '')) {          my ($suname,$sudom,$sudomref);
             $extras .= ':retry';          $suname = $form{'suname'};
             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).          $sudom = $form{'udom'};
                                             $extras,$lonhost);          if ($form{'sudom'}) {
             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {              unless ($sudom eq $form{'sudom'}) {
                 return 'fail';                  if (&Apache::lonnet::domain($form{'sudom'})) {
             } else {                      $sudomref = [$form{'sudom'}];
                 if (ref($querystr)) {                      $sudom = $form{'sudom'};
                     $$querystr = 'retry='.$token;                  }
                 }              }
                 return 'ok';          }
             }  # ------------ see if the original user has enough privileges to pull this stunt
         }   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
     }  # ---------------------------------------------------- see if the su-user exists
     return;      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
 }  # ------------------------------ see if the su-user is not too highly privileged
    if (&Apache::lonnet::privileged($suname,$sudom)) {
 sub check_can_host {                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
     my ($r,$form,$authhost,$domdesc) = @_;                  } else {
     return unless (ref($form) eq 'HASH');                      my $noprivswitch;
     my $canhost = 1;  #
     my $lonhost = $r->dir_config('lonHostID');  # su-user's home server and user's home server must have one of:
     my $udom = $form->{'udom'};  # (a) same domain
     my @intdoms;  # (b) same primary library server for the two domains
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);  # (c) same "internet domain" for primary library server(s) for home servers' domains
     if (ref($internet_names) eq 'ARRAY') {  #
         @intdoms = @{$internet_names};                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
     }                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');                      unless ($sudom eq $form{'udom'}) {
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);                          unless ($suprim eq $uprim) {
         my $hostname = &Apache::lonnet::hostname($lonhost);                              unless ($suintdom eq $uintdom) {
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);                                  &Apache::lonnet::logthis('Attempted switch user '
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);                                     .'to user with different "internet domain".');
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);                                  $noprivswitch = 1;
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);                              }
         my $loncaparev;                          }
         if ($authhost eq 'no_account_on_host') {                      }
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);  
         } else {                      unless ($noprivswitch) {
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);  #
         }  # server where log-in occurs must have same "internet domain" as su-user's home
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,  # server
                                                      $udomdefaults{'remotesessions'},  #
                                                      $defdomdefaults{'hostedsessions'});                          my $lonhost = $r->dir_config('lonHostID');
     }                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
     unless ($canhost) {                          if ($hostintdom ne $suintdom) {
         if ($authhost eq 'no_account_on_host') {                              &Apache::lonnet::logthis('Attempted switch user on a '
             my $checkloginvia = 1;                                  .'server with a different "internet domain".');
             my ($login_host,$hostname) =                           } else {
                 &Apache::lonnet::choose_server($udom,$checkloginvia);  
             &Apache::loncommon::content_type($r,'text/html');  # -------------------------------------------------------- actually switch users
             $r->send_http_header;  
             if ($login_host ne '') {              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
                 my $protocol = $Apache::lonnet::protocol{$login_host};                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
                 $protocol = 'http' if ($protocol ne 'https');              $form{'uname'}=$suname;
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);                              if ($form{'udom'} ne $sudom) {
                 $hostname = $alias if ($alias ne '');                                  $form{'udom'}=$sudom;
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';                              }
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').                          }
                           '<h3>'.&mt('Account creation').'</h3>'.                      }
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.   }
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.      }
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').   } else {
                           &Apache::loncommon::end_page());      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
             } else {   }
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').      }
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.  
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.      if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                           '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.          if (($form{'linkprot'}) && ($form{'linkprotuser'} ne '')) {
                           &Apache::loncommon::end_page());              unless($form{'linkprotuser'} eq $form{'uname'}.':'.$form{'udom'}) {
             }                  delete($form{'udom'});
         } else {                  delete($form{'uname'});
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,                  &failed($r,'Username and/or domain are different to that expected for the link you followed from another system',
                      $form);                          \%form,$authhost);
             my ($otherserver) = &Apache::lonnet::choose_server($udom);                  return OK;
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);              }
         }          }
     }      }
     return $canhost;  
 }      my ($is_balancer,$otherserver);
   
 sub noswitch {      unless ($hosthere) {
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').          ($is_balancer,$otherserver) =
                  '<h3>'.&mt('Session unavailable').'</h3>'.              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.          if ($is_balancer) {
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.              # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
                  &Apache::loncommon::end_page();              my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);
     return $result;              if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {
 }                  $otherserver = $found_server;
               }
 sub loginhelpdisplay {              if ($otherserver eq '') {
     my ($authdomain) = @_;                  my $lowest_load;
     my $login_help = 1;                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
     my $lang = &Apache::lonlocal::current_language();                  if ($lowest_load > 100) {
     if ($login_help) {                      $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});
         my $dom = $authdomain;                  }
         if ($dom eq '') {              }
             $dom = &Apache::lonnet::default_login_domain();              if ($otherserver ne '') {
         }                  my @hosts = &Apache::lonnet::current_machine_ids();
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
         my $loginhelp_url;                      $hosthere = $otherserver;
         if ($lang) {                  }
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};              }
             if ($loginhelp_url ne '') {          }
                 return $loginhelp_url;      }
             }  
         }      if (($is_balancer) && (!$hosthere)) {
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};          if ($otherserver) {
         if ($loginhelp_url ne '') {              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
             return $loginhelp_url;                       \%form);
         } else {              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
             return '/adm/loginproblems.html';              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
         }                  $switchto .= '&origurl='.$firsturl;
     }              }
     return;              if ($form{'role'}) {
 }                  $switchto .= '&role='.$form{'role'};
               }
 1;              if ($form{'symb'}) {
 __END__                  $switchto .= '&symb='.$form{'symb'};
               }
               if ($form{'linkprot'}) {
                   $env{'request.linkprot'} = $form{'linkprot'};
                   if ($form{'linkprotuser'}) {
                       $env{'request.linkprotuser'} = $form{'linkprotuser'};
                   }
               } elsif ($form{'linkkey'} ne '') {
                   $env{'request.linkkey'} = $form{'linkkey'};
               }
               if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                   &set_deeplink_login(%form);
               }
               $r->internal_redirect($switchto);
           } else {
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               $r->print(&noswitch());
           }
           return OK;
       } else {
           if (!&check_can_host($r,\%form,$authhost)) {
               my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
               if ($otherserver) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                            \%form);
                   my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                   if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                       $switchto .= '&origurl='.$firsturl;
                   }
                   if ($form{'role'}) {
                       $switchto .= '&role='.$form{'role'};
                   }
                   if ($form{'symb'}) {
                       $switchto .= '&symb='.$form{'symb'};
                   }
                   if ($form{'linkprot'}) {
                       $env{'request.linkprot'} = $form{'linkprot'};
                       if ($form{'linkprotuser'}) {
                           $env{'request.linkprotuser'} = $form{'linkprotuser'};
                       }
                   } elsif ($form{'linkkey'} ne '') {
                       $env{'request.linkkey'} = $form{'linkkey'};
                   }
                   if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                       &set_deeplink_login(%form);
                   }
                   $r->internal_redirect($switchto);
               } else {
                   &Apache::loncommon::content_type($r,'text/html');
                   $r->send_http_header;
                   $r->print(&noswitch());
               }
               return OK;
           }
   
   # ------------------------------------------------------- Do the load balancing
   
   # ---------------------------------------------------------- Determine own load
           my $loadlim = $r->dir_config('lonLoadLim');
           my $loadavg;
           {
               my $loadfile=Apache::File->new('/proc/loadavg');
               $loadavg=<$loadfile>;
           }
           $loadavg =~ s/\s.*//g;
           my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
           my $userloadpercent=&Apache::lonnet::userload();
   
   # ---------------------------------------------------------- Are we overloaded?
           if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
               my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});
               if (!$unloaded) {
                   ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
               }
               if ($unloaded) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                            undef,\%form);
                   if ($form{'linkprot'}) {
                       $env{'request.linkprot'} = $form{'linkprot'};
                   } elsif ($form{'linkkey'} ne '') {
                       $env{'request.linkkey'} = $form{'linkkey'};
                   }
                   if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                       &set_deeplink_login(%form);
                   }
                   $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                   return OK;
               }
           }
           if (($is_balancer) && ($hosthere)) {
               $form{'noloadbalance'} = $hosthere;
           }
           my $extra_env;
           if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {
               if ($sessiondata{'origurl'} ne '') {
                   $firsturl = $sessiondata{'origurl'};
                   $form{'firsturl'} = $sessiondata{'origurl'};
                   my @names = ('role','symb','linkprot','linkkey');
                   foreach my $item (@names) {
                       if ($sessiondata{$item} ne '') {
                           $form{$item} = $sessiondata{$item};
                       }
                   }
               }
           }
           if ($form{'linkprot'}) {
               my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
               if ($linkprotector) {
                   $extra_env = {'user.linkprotector' => $linkprotector,
                                 'user.linkproturi'   => $uri};
               }
           } elsif ($form{'linkkey'} ne '') {
               $extra_env = {'user.deeplinkkey'  => $form{'linkkey'},
                             'user.keyedlinkuri' => $form{'firsturl'}};
           }
           if ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
               &set_deeplink_login(%form);
               if ($form{'linkprot'}) {
                   if (ref($extra_env) eq 'HASH') {
                       %{$extra_env} = ( %{$extra_env}, 'request.linkprot' => $form{'linkprot'} );
                   } else {
                       $extra_env = {'request.linkprot' => $form{'linkprot'}};
                   }
               } elsif ($form{'linkkey'} ne '') {
                   if (ref($extra_env) eq 'HASH') {
                       %{$extra_env} = ( %{$extra_env}, 'request.linkkey' => $form{'linkkey'} );
                   } else {
                       $extra_env = {'request.linkkey' => $form{'linkkey'}};
                   }
               }
               if ($env{'request.deeplink.login'}) {
                   if (ref($extra_env) eq 'HASH') {
                       %{$extra_env} = ( %{$extra_env}, 'request.deeplink.login' => $form{'firsturl'} );
                   } else {
                       $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
                   }
               }
           }
           &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
                    \%form);
           return OK;
       }
   }
   
   sub get_form_items {
       my ($r) = @_;
       my $buffer;
       if ($r->header_in('Content-length') > 0) {
           $r->read($buffer,$r->header_in('Content-length'),0);
       }
       my %form;
       foreach my $pair (split(/&/,$buffer)) {
          my ($name,$value) = split(/=/,$pair);
          $value =~ tr/+/ /;
          $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
          $form{$name}=$value;
       }
       return %form;
   }
   
   sub set_deeplink_login {
       my (%form) = @_;
       my $disallow;
       if ($form{'firsturl'} =~ m{^/tiny/($match_domain)/\w+$}) {
           my $cdom = $1;
           my ($cnum,$symb) = &Apache::loncommon::symb_from_tinyurl($form{'firsturl'},'',$cdom);
           if ($symb) {
               if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   my $deeplink;
                   if ($symb =~ /\.(page|sequence)$/) {
                       my $mapname = &Apache::lonnet::deversion((&Apache::lonnet::decode_symb($symb))[2]);
                       my $navmap = Apache::lonnavmaps::navmap->new();
                       if (ref($navmap)) {
                           $deeplink = $navmap->get_mapparam(undef,$mapname,'0.deeplink');
                       }
                   } else {
                       $deeplink = &Apache::lonnet::EXT('resource.0.deeplink',$symb);
                   }
                   if ($deeplink ne '') {
                       my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                       if (($protect ne 'none') && ($protect ne '')) {
                           my ($acctype,$item) = split(/:/,$protect);
                           if ($acctype =~ /lti(c|d)$/) {
                               unless ($form{'linkprot'} eq $item.$1.':'.$env{'request.deeplink.login'}) {
                                   $disallow = 1;
                               }
                           } elsif ($acctype eq 'key') {
                               unless ($form{'linkkey'} eq $item) {
                                   $disallow = 1;
                               }
                           }
                       }
                   }
                   unless ($disallow) {
                       $env{'request.deeplink.login'} = $form{'firsturl'};
                   }
               } else {
                   $env{'request.deeplink.login'} = $form{'firsturl'};
               }
           }
       }
       if ($disallow) {
           return;
       }
       return 'ok';
   }
   
   sub set_retry_token {
       my ($form,$lonhost,$querystr) = @_;
       if (ref($form) eq 'HASH') {
           my ($firsturl,$token,$extras,@names);
           @names = ('role','symb','linkprotuser','linkprot','linkkey','iptoken');
           foreach my $name (@names) {
               if ($form->{$name} ne '') {
                   $extras .= '&'.$name.'='.&escape($form->{$name});
                   last if ($name eq 'linkprot');
               }
           }
           my $firsturl = $form->{'firsturl'};
           if (($firsturl ne '') || ($extras ne '')) {
               $extras .= ':retry';
               $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).
                                               $extras,$lonhost);
               if (($token eq 'con_lost') || ($token eq 'no_such_host')) {
                   return 'fail';
               } else {
                   if (ref($querystr)) {
                       $$querystr = 'retry='.$token;
                   }
                   return 'ok';
               }
           }
       }
       return;
   }
   
   sub check_can_host {
       my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
       my $canhost = 1;
       my $lonhost = $r->dir_config('lonHostID');
       my $udom = $form->{'udom'};
       my @intdoms;
       my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
       if (ref($internet_names) eq 'ARRAY') {
           @intdoms = @{$internet_names};
       }
       my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
       my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
       unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
           my $machine_dom = &Apache::lonnet::host_domain($lonhost);
           my $hostname = &Apache::lonnet::hostname($lonhost);
           my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
           my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
           my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
           my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
           my $loncaparev;
           if ($authhost eq 'no_account_on_host') {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
           } else {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
           }
           $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                                                        $udomdefaults{'remotesessions'},
                                                        $defdomdefaults{'hostedsessions'});
       }
       unless ($canhost) {
           if ($authhost eq 'no_account_on_host') {
               my $checkloginvia = 1;
               my ($login_host,$hostname) =
                   &Apache::lonnet::choose_server($udom,$checkloginvia);
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               if ($login_host ne '') {
                   my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);
                   $hostname = $alias if ($alias ne '');
                   my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
   #FIXME Should preserve where user was going and linkprot by setting ltoken at $login_host
                   $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                             '<h3>'.&mt('Account creation').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                             '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                             &Apache::loncommon::end_page());
               } else {
                   $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                             '<h3>'.&mt('Account creation unavailable').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.
                             &Apache::loncommon::end_page());
               }
           } else {
               &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                        $form);
               if ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                   $env{'request.deeplink.login'} = $form->{'firsturl'};
               }
               if ($form->{'linkprot'}) {
                   $env{'request.linkprot'} = $form->{'linkprot'};
               } elsif ($form->{'linkkey'} ne '') {
                   $env{'request.linkkey'} = $form->{'linkkey'};
               }
               my ($otherserver) = &Apache::lonnet::choose_server($udom);
               $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
           }
       }
       return $canhost;
   }
   
   sub noswitch {
       my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    '<h3>'.&mt('Session unavailable').'</h3>'.
                    &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                    '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                    &Apache::loncommon::end_page();
       return $result;
   }
   
   sub loginhelpdisplay {
       my ($authdomain) = @_;
       my $login_help = 1;
       my $lang = &Apache::lonlocal::current_language();
       if ($login_help) {
           my $dom = $authdomain;
           if ($dom eq '') {
               $dom = &Apache::lonnet::default_login_domain();
           }
           my %domconfhash = &Apache::loncommon::get_domainconf($dom);
           my $loginhelp_url;
           if ($lang) {
               $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
               if ($loginhelp_url ne '') {
                   return $loginhelp_url;
               }
           }
           $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
           if ($loginhelp_url ne '') {
               return $loginhelp_url;
           } else {
               return '/adm/loginproblems.html';
           }
       }
       return;
   }
   
   sub alternate_unames_check {
       my ($uname,$udom) = @_;
       my %possunames;
       my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
       if (ref($domdefs{'unamemap_rule'}) eq 'ARRAY') {
           if (@{$domdefs{'unamemap_rule'}} > 0) {
               %possunames =
                   &Apache::lonnet::inst_rulecheck($udom,$uname,undef,
                                                   'unamemap',$domdefs{'unamemap_rule'});
           }
       }
       return %possunames;
   }
   
   1;
   __END__
   
   

Removed from v.1.121.2.23  
changed lines
  Added in v.1.175


FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>