Diff for /loncom/auth/lonauth.pm between versions 1.121.2.22 and 1.159

version 1.121.2.22, 2021/12/12 01:48:40 version 1.159, 2020/03/15 23:04:10
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   
 sub success {  # ------------------------------------------------------------ Successful login
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,  sub success {
  $form,$cid,$expirepub) = @_;      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
    $form,$skipcritical,$cid) = @_;
 # ------------------------------------------------------------ Get cookie ready  
     my $cookie =  # ------------------------------------------------------------ Get cookie ready
  &Apache::loncommon::init_user_environment($r, $username, $domain,      my $cookie =
   $authhost, $form,   &Apache::loncommon::init_user_environment($r, $username, $domain,
   {'extra_env' => $extra_env,});    $authhost, $form,
     {'extra_env' => $extra_env,});
     my $public=($username eq 'public' && $domain eq 'public');  
       my $public=($username eq 'public' && $domain eq 'public');
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }  
       if ($public or $lowerurl eq 'noredirect') { return $cookie; }
 # -------------------------------------------------------------------- Log this  
   # -------------------------------------------------------------------- Log this
     my $ip = &Apache::lonnet::get_requestor_ip();  
     &Apache::lonnet::log($domain,$username,$authhost,      &Apache::lonnet::log($domain,$username,$authhost,
                          "Login $ip");                           "Login $ENV{'REMOTE_ADDR'}");
   
 # ------------------------------------------------- Check for critical messages  # ------------------------------------------------- Check for critical messages
   
     my @what=&Apache::lonnet::dump('critical',$domain,$username);      unless ($skipcritical) {
     if ($what[0]) {          my @what=&Apache::lonnet::dump('critical',$domain,$username);
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {          if ($what[0]) {
     $lowerurl='/adm/email?critical=display';      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');  # ----------------------------------------------------------- Get cookies ready
     if ($ssl) {      my ($securecookie,$defaultcookie);
         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";      my $ssl = $r->subprocess_env('https');
         my $lonidsdir=$r->dir_config('lonIDsDir');      if ($ssl) {
         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {          $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';          my $lonidsdir=$r->dir_config('lonIDsDir');
             if (-e "$lonidsdir/$linkname.id") {          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
                 unlink("$lonidsdir/$linkname.id");              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
             }              if (-e "$lonidsdir/$linkname.id") {
             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",                  unlink("$lonidsdir/$linkname.id");
                                               "$lonidsdir/$linkname.id"); 1 };              }
             if ($made_symlink) {              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";                                                "$lonidsdir/$linkname.id"); 1 };
                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});              if ($made_symlink) {
             }                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
         }                  &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
     } else {              }
         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";          }
     }      } else {
 # -------------------------------------------------------- Menu script and info          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
     my $destination = $lowerurl;      }
   # -------------------------------------------------------- Menu script and info
     if (defined($form->{role})) {      my $destination = $lowerurl;
         my $envkey = 'user.role.'.$form->{role};      if ($env{'request.lti.login'}) {
         my $now=time;          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         my $then=$env{'user.login.time'};              &Apache::loncommon::content_type($r,'text/html');
         my $refresh=$env{'user.refresh.time'};              if ($securecookie) {
         my $update=$env{'user.update.time'};                  $r->headers_out->add('Set-cookie' => $securecookie);
         if (!$update) {              }
             $update = $then;              if ($defaultcookie) {
         }                  $r->headers_out->add('Set-cookie' => $defaultcookie);
         if (exists($env{$envkey})) {              }
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              $r->send_http_header;
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,              if (ref($form) eq 'HASH') {
                                          \$trolecode,\$tstatus,\$tstart,\$tend);                  $form->{'lti.login'} = $env{'request.lti.login'};
             if ($tstatus eq 'is') {                  $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');                  $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
                 $destination .= 'selectrole=1&'.$newrole.'=1';              }
             }              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
         }              return;
     }          }
     if (defined($form->{symb})) {          if ($env{'request.lti.selfenrollrole'}) {
         my $destsymb = $form->{symb};              if (&Apache::ltiauth::lti_enroll($username,$domain,
         my $encrypted;                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
         if ($destsymb =~ m{^/enc/}) {                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
             $encrypted = 1;                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
             if ($cid) {              } else {
                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);                  &Apache::ltiauth::invalid_request($r,24);
             }              }
         }          }
         $destination  .= ($destination =~ /\?/) ? '&' : '?';      }
         if ($destsymb =~ /___/) {      if (defined($form->{role})) {
             my ($map,$resid,$desturl)=split(/___/,$destsymb);          my $envkey = 'user.role.'.$form->{role};
             $desturl = &Apache::lonnet::clutter($desturl);          my $now=time;
             if ($encrypted) {          my $then=$env{'user.login.time'};
                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);          my $refresh=$env{'user.refresh.time'};
                 $destsymb = $form->{symb};          my $update=$env{'user.update.time'};
             }          if (!$update) {
             $desturl = &HTML::Entities::encode($desturl,'"<>&');              $update = $then;
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');          }
             $destination .= 'destinationurl='.$desturl.          if (exists($env{$envkey})) {
                             '&destsymb='.$destsymb;              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
         } elsif (!$encrypted) {              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');                                           \$trolecode,\$tstatus,\$tstart,\$tend);
             $destination .= 'destinationurl='.$destsymb;              if ($tstatus eq 'is') {
         }                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
     }                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
     if ($destination =~ m{^/adm/roles}) {                  $destination .= 'selectrole=1&'.$newrole.'=1';
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              }
         $destination .= 'source=login';          }
     }      }
       if (defined($form->{symb})) {
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});          my $destsymb = $form->{symb};
     my $startupremote=&Apache::lonmenu::startupremote($destination);          my $encrypted;
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);          if ($destsymb =~ m{^/enc/}) {
     my $setflags=&Apache::lonmenu::setflags();              $encrypted = 1;
     my $maincall=&Apache::lonmenu::maincall();              if ($cid) {
     my $brcrum = [{'href' => '',                  $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);
                    'text' => 'Successful Login'},];              }
     my $start_page=&Apache::loncommon::start_page('Successful Login',          }
                                                   $startupremote,          $destination  .= ($destination =~ /\?/) ? '&' : '?';
                                                   {'no_inline_link' => 1,          if ($destsymb =~ /___/) {
                                                    'bread_crumbs' => $brcrum,});              my ($map,$resid,$desturl)=split(/___/,$destsymb);
     my $end_page  =&Apache::loncommon::end_page();              $desturl = &Apache::lonnet::clutter($desturl);
               if ($encrypted) {
     my $continuelink;                  $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);
     if ($env{'environment.remote'} eq 'off') {                  $destsymb = $form->{symb};
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';              }
     }              $desturl = &HTML::Entities::encode($desturl,'"<>&');
 # ------------------------------------------------- Output for successful login              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
               $destination .= 'destinationurl='.$desturl.
     &Apache::loncommon::content_type($r,'text/html');                              '&destsymb='.$destsymb;
     if ($securecookie) {          } elsif (!$encrypted) {
         $r->headers_out->add('Set-cookie' => $securecookie);              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     }              $destination .= 'destinationurl='.$destsymb;
     if ($defaultcookie) {          }
         $r->headers_out->add('Set-cookie' => $defaultcookie);      }
     }      if ($destination =~ m{^/adm/roles}) {
     if ($expirepub) {          $destination  .= ($destination =~ /\?/) ? '&' : '?';
         my $c = new CGI::Cookie(-name    => 'lonPubID',          $destination .= 'source=login';
                                 -value   => '',      }
                                 -expires => '-10y',);  
         $r->headers_out->add('Set-cookie' => $c);      my $windowname = 'loncapaclient';
     }      if ($env{'request.lti.login'}) {
     $r->send_http_header;          $windowname .= 'lti';
       }
     my %lt=&Apache::lonlocal::texthash(      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
        'wel' => 'Welcome',      my $brcrum = [{'href' => '',
        'pro' => 'Login problems?',                     'text' => 'Successful Login'},];
        );      my $args = {'bread_crumbs' => $brcrum,};
     my $loginhelp = &loginhelpdisplay($domain);      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     if ($loginhelp) {          my $update=$env{'user.update.time'};
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';          if (!$update) {
     }              $update = $env{'user.login.time'};
           }
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');           my %roles_in_env;
     $r->print(<<ENDSUCCESS);          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
 $start_page          if ($showcount == 1) {
 $setflags              foreach my $rolecode (keys(%roles_in_env)) {
 $windowinfo                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
 <h1>$lt{'wel'}</h1>                  if ($cid) {
 $welcome                      my %coursedescription =
 $loginhelp                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
 $remoteinfo                      if ($coursedescription{'type'} eq 'Placement') {
 $maincall                          $args->{'crstype'} = 'Placement';
 $continuelink                      }
 $end_page                      last;
 ENDSUCCESS                  }
     return;              }
 }          }
       }
 # --------------------------------------------------------------- Failed login!  
   # ------------------------------------------------- Output for successful login
 sub failed {  
     my ($r,$message,$form,$authhost) = @_;      &Apache::loncommon::content_type($r,'text/html');
     (undef,undef,undef,my $clientmathml,my $clientunicode) =      if ($securecookie) {
         &Apache::loncommon::decode_user_agent();          $r->headers_out->add('Set-cookie' => $securecookie);
     my $args = {};      }
     if ($clientunicode && !$clientmathml) {      if ($defaultcookie) {
         $args = {'browser.unicode' => 1};          $r->headers_out->add('Set-cookie' => $defaultcookie);
     }      }
       $r->send_http_header;
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);  
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});      my ($start_page,$js,$pagebody,$end_page);
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});      if ($env{'request.lti.login'}) {
     if (&Apache::lonnet::domain($udom,'description') eq '') {          $args = {'only_body' => 1};
         undef($udom);          if ($env{'request.lti.target'} eq '') {
     }              my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
     my $retry = '/adm/login';                              'ltitarget=iframe';
     if ($uname eq $form->{'uname'}) {              $js = <<"ENDJS";
         $retry .= '?username='.$uname;  
     }  <script type="text/javascript">
     if ($udom) {  // <![CDATA[
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;  function setLTItarget() {
     }      var newloc = '$destination';
     my $lonhost = $r->dir_config('lonHostID');      if (parent !== window) {
     my $querystr;          newloc += '$ltitarget';
     my $result = &set_retry_token($form,$lonhost,\$querystr);      }
     if ($result eq 'fail') {      window.location.href=newloc;
         if (exists($form->{role})) {  }
             my $role = &Apache::loncommon::cleanup_html($form->{role});  // ]]>
             if ($role ne '') {  </script>
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;  
             }  ENDJS
         }              $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
         if (exists($form->{symb})) {              $pagebody =  '<noscript><span class="LC_warning">'
             my $symb = &Apache::loncommon::cleanup_html($form->{symb});                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
             if ($symb ne '') {                          .'</span></noscript>';
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;          } else {
             }              $args->{'redirect'} = [0,$destination,1];
         }          }
         if (exists($form->{firsturl})) {          $start_page=&Apache::loncommon::start_page('',$js,$args);
             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});      } else {
             if ($firsturl ne '') {          $args->{'redirect'} = [0,$destination];
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;          $start_page=&Apache::loncommon::start_page('Successful Login',
                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {                                                     $js,$args);
                     unless (exists($form->{linkprot})) {  
                         if (exists($form->{linkkey})) {          my %lt=&Apache::lonlocal::texthash(
                             $retry .= 'linkkey='.$form->{linkkey};             'wel' => 'Welcome',
                         }             'pro' => 'Login problems?',
                     }            );
                 }          $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>');
         }          my $loginhelp = &loginhelpdisplay($domain);
     } elsif ($querystr ne '') {          if ($loginhelp) {
         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
     }          }
     my $end_page = &Apache::loncommon::end_page();      }
     &Apache::loncommon::content_type($r,'text/html');      $end_page = &Apache::loncommon::end_page();
     $r->send_http_header;      $r->print(<<ENDSUCCESS);
     my @actions =  $start_page
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));  $windowinfo
     my $loginhelp = &loginhelpdisplay($udom);  $pagebody
     if ($loginhelp) {  $end_page
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');  ENDSUCCESS
     }      return;
     #FIXME: link to helpdesk might be added here  }
   
     $r->print(  # --------------------------------------------------------------- Failed login!
        $start_page  
       .'<h2>'.&mt('Sorry ...').'</h2>'  sub failed {
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'      my ($r,$message,$form) = @_;
       .&Apache::lonhtmlcommon::actionbox(\@actions)      (undef,undef,undef,my $clientmathml,my $clientunicode) =
       .$end_page          &Apache::loncommon::decode_user_agent();
     );      my $args = {};
  }      if ($clientunicode && !$clientmathml) {
           $args = {'browser.unicode' => 1};
 # ------------------------------------------------------------------ Rerouting!      }
   
 sub reroute {      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
     my ($r) = @_;      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
     &Apache::loncommon::content_type($r,'text/html');      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
     $r->send_http_header;      if (&Apache::lonnet::domain($udom,'description') eq '') {
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'          undef($udom);
            .&mt('Please [_1]log in again[_2].');      }
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});      my $retry = '/adm/login';
 }      if ($uname eq $form->{'uname'}) {
           $retry .= '?username='.$uname;
 # ---------------------------------------------------------------- Main handler      }
       if ($udom) {
 sub handler {          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
     my $r = shift;      }
     my $londocroot = $r->dir_config('lonDocRoot');      if (exists($form->{role})) {
 # Are we re-routing?          my $role = &Apache::loncommon::cleanup_html($form->{role});
     if (-e "$londocroot/lon-status/reroute.txt") {          if ($role ne '') {
  &reroute($r);              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
  return OK;          }
     }      }
       if (exists($form->{symb})) {
     &Apache::lonlocal::get_language_handle($r);          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
           if ($symb ne '') {
 # -------------------------------- Prevent users from attempting to login twice              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
     my $handle = &Apache::lonnet::check_for_valid_session($r);          }
     if ($handle ne '') {      }
         my $lonidsdir=$r->dir_config('lonIDsDir');      if (exists($form->{firsturl})) {
         if ($handle=~/^publicuser\_/) {          my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
 # For "public user" - remove it, we apparently really want to login          if ($firsturl ne '') {
             unlink($r->dir_config('lonIDsDir')."/$handle.id");              $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
         } else {              if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
 # Indeed, a valid token is found                  unless (exists($form->{linkprot})) {
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);                      if (exists($form->{linkkey})) {
     &Apache::loncommon::content_type($r,'text/html');                          $retry .= 'linkkey='.$form->{linkkey};
     $r->send_http_header;                      }
     my $start_page =                   }
         &Apache::loncommon::start_page('Already logged in');              }
     my $end_page =           }
         &Apache::loncommon::end_page();      }
             my $dest = '/adm/roles';      if (exists($form->{linkprot})) {
             my %form = &get_form_items($r);          my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
             if ($form{'logtoken'}) {                                               $r->dir_config('lonHostID'));
                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},          if ($ltoken) {
                                                      $form{'serverid'});              $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||          }
                         ($tmpinfo eq 'no_such_host')) {      }
                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo)l      my $end_page = &Apache::loncommon::end_page();
                     $firsturl = &unescape($firsturl);      &Apache::loncommon::content_type($r,'text/html');
                     my %info;      $r->send_http_header;
                     foreach my $item (@rest) {      my @actions =
                         my ($key,$value) = split(/=/,$item);           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
                         $info{$key} = &unescape($value);      my $loginhelp = &loginhelpdisplay($udom);
                     }      if ($loginhelp) {
                     if ($firsturl ne '') {          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
                         $info{'firsturl'} = $firsturl;      }
                         $dest = $firsturl;      #FIXME: link to helpdesk might be added here
                     }  
                 }      $r->print(
             }         $start_page
             $r->print(        .'<h2>'.&mt('Sorry ...').'</h2>'
                $start_page        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'        .&Apache::lonhtmlcommon::actionbox(\@actions)
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'        .$end_page
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')      );
               .'</p>'   }
               .$end_page  
             );  # ------------------------------------------------------------------ Rerouting!
             return OK;  
         }  sub reroute {
     }      my ($r) = @_;
       &Apache::loncommon::content_type($r,'text/html');
 # ---------------------------------------------------- No valid token, continue      $r->send_http_header;
       my $msg='<b>'.&mt('Sorry ...').'</b><br />'
     my %form = &get_form_items($r);             .&mt('Please [_1]log in again[_2].');
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
  &failed($r,'Username, password and domain need to be specified.',  }
  \%form);  
         return OK;  # ---------------------------------------------------------------- Main handler
     }  
   sub handler {
 # split user logging in and "su"-user      my $r = shift;
       my $londocroot = $r->dir_config('lonDocRoot');
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});  # Are we re-routing?
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});      if (-e "$londocroot/lon-status/reroute.txt") {
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});   &reroute($r);
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});   return OK;
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});      }
   
     my $role   = $r->dir_config('lonRole');      &Apache::lonlocal::get_language_handle($r);
     my $domain = $r->dir_config('lonDefDomain');  
     my $prodir = $r->dir_config('lonUsersDir');  # -------------------------------- Prevent users from attempting to login twice
     my $contact_name = &mt('LON-CAPA helpdesk');      my $handle = &Apache::lonnet::check_for_valid_session($r);
       if ($handle ne '') {
 # ---------------------------------------- Get the information from login token          my $lonidsdir=$r->dir_config('lonIDsDir');
           if ($handle=~/^publicuser\_/) {
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},  # For "public user" - remove it, we apparently really want to login
                                       $form{'serverid'});              unlink($r->dir_config('lonIDsDir')."/$handle.id");
           } else {
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||   # Indeed, a valid token is found
         ($tmpinfo eq 'no_such_host')) {              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);      &Apache::loncommon::content_type($r,'text/html');
         return OK;      $r->send_http_header;
     } else {      my $start_page =
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},          &Apache::loncommon::start_page('Already logged in');
    $form{'serverid'});      my $end_page =
         if ( $reply ne 'ok' ) {          &Apache::loncommon::end_page();
             &failed($r,'Session could not be opened.',\%form);              my $dest = '/adm/roles';
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");              if ($env{'form.firsturl'} ne '') {
     return OK;                  $dest = $env{'form.firsturl'};
  }                  if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     }                      &Apache::lonnet::appenv({'request.deeplink.login' => $env{'form.firsturl'}});
                   }
     if (!&Apache::lonnet::domain($form{'udom'})) {              }
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);              $r->print(
         return OK;                 $start_page
     }                .'<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 ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
     $firsturl = &unescape($firsturl);                .'</p>'
     foreach my $item (@rest) {                .$end_page
         my ($key,$value) = split(/=/,$item);              );
         $form{$key} = &unescape($value);              return OK;
     }          }
     my $upass = &Apache::loncommon::des_decrypt($key,$form{'upass0'});      }
   
 # ---------------------------------------------------------------- Authenticate  # ---------------------------------------------------- No valid token, continue
   
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  
     my ($cancreate,$statustocreate) =      my $buffer;
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});      if ($r->header_in('Content-length') > 0) {
     my $defaultauth;   $r->read($buffer,$r->header_in('Content-length'),0);
     if (ref($cancreate) eq 'ARRAY') {      }
         if (grep(/^login$/,@{$cancreate})) {      my %form;
             $defaultauth = 1;      foreach my $pair (split(/&/,$buffer)) {
         }         my ($name,$value) = split(/=/,$pair);
     }         $value =~ tr/+/ /;
     my $clientcancheckhost = 1;         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,         $form{$name}=$value;
                                               $form{'udom'},$defaultauth,      }
                                               $clientcancheckhost);  
           if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
 # --------------------------------------------------------------------- Failed?   &failed($r,'Username, password and domain need to be specified.',
    \%form);
     if ($authhost eq 'no_host') {          return OK;
  &failed($r,'Username and/or password could not be authenticated.',      }
  \%form);  
         return OK;  # split user logging in and "su"-user
     } elsif ($authhost eq 'no_account_on_host') {  
         if ($defaultauth) {      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
                 return OK;      $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
             }      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
             my $start_page =   
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',      my $role   = $r->dir_config('lonRole');
                                                '',{'no_inline_link'   => 1,});      my $domain = $r->dir_config('lonDefDomain');
             my $lonhost = $r->dir_config('lonHostID');      my $prodir = $r->dir_config('lonUsersDir');
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      my $contact_name = &mt('LON-CAPA helpdesk');
             my $contacts =   
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',  # ---------------------------------------- Get the information from login token
                                                         $form{'udom'},$origmail);  
             my ($contact_email) = split(',',$contacts);       my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
             my $output =                                         $form{'serverid'});
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},  
                                                        $domdesc,'',$lonhost,      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
                                                        $contact_email,$contact_name,          ($tmpinfo eq 'no_such_host')) {
                                                        undef,$statustocreate);   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
             &Apache::loncommon::content_type($r,'text/html');          return OK;
             $r->send_http_header;      } else {
             &Apache::createaccount::print_header($r,$start_page);   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
             $r->print('<h3>'.&mt('Account creation').'</h3>'.     $form{'serverid'});
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.          if ( $reply ne 'ok' ) {
                       $output.&Apache::loncommon::end_page());              &failed($r,'Session could not be opened.',\%form);
             return OK;      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
         } else {      return OK;
             &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);   }
             return OK;      }
         }  
     }      if (!&Apache::lonnet::domain($form{'udom'})) {
           &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
     if (($firsturl eq '') ||           return OK;
  ($firsturl=~/^\/adm\/(logout|remote)/)) {      }
  $firsturl='/adm/roles';  
     }      my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr,$linkstr)=split(/&/,$tmpinfo);
       if ($rolestr) {
     my $hosthere;          $rolestr = &unescape($rolestr);
     if ($form{'iptoken'}) {      }
         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});      if ($symbstr) {
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});          $symbstr= &unescape($symbstr);
         if (($sessiondata{'domain'} eq $form{'udom'}) &&      }
             ($sessiondata{'username'} eq $form{'uname'})) {      if ($iptokenstr) {
             $hosthere = 1;          $iptokenstr = &unescape($iptokenstr);
         }      }
     }      if ($linkstr) {
           $linkstr = &unescape($linkstr);
 # --------------------------------- Are we attempting to login as somebody else?      }
     if ($form{'suname'}) {      if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
         my ($suname,$sudom,$sudomref);          $form{'firsturl'} = $firsturl;
         $suname = $form{'suname'};      }
         $sudom = $form{'udom'};      if ($rolestr =~ /^role=/) {
         if ($form{'sudom'}) {          (undef,$form{'role'}) = split('=',$rolestr);
             unless ($sudom eq $form{'sudom'}) {      }
                 if (&Apache::lonnet::domain($form{'sudom'})) {      if ($symbstr =~ /^symb=/) {
                     $sudomref = [$form{'sudom'}];          (undef,$form{'symb'}) = split('=',$symbstr);
                     $sudom = $form{'sudom'};      }
                 }      if ($iptokenstr =~ /^iptoken=/) {
             }          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
         }      }
 # ------------ see if the original user has enough privileges to pull this stunt      if ($linkstr =~ /^linkprot=/) {
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {          (undef,$form{'linkprot'}) = split('=',$linkstr);
 # ---------------------------------------------------- see if the su-user exists      } elsif ($linkstr =~ /^linkkey=/) {
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {          (undef,$form{'linkkey'}) = split('=',$linkstr);
 # ------------------------------ see if the su-user is not too highly privileged      }
  if (&Apache::lonnet::privileged($suname,$sudom)) {  
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');      my $upass = $ENV{HTTPS} ? $form{'upass0'}
                 } else {          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
                     my $noprivswitch;  
 #  # ---------------------------------------------------------------- Authenticate
 # su-user's home server and user's home server must have one of:  
 # (a) same domain      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
 # (b) same primary library server for the two domains      my ($cancreate,$statustocreate) =
 # (c) same "internet domain" for primary library server(s) for home servers' domains          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
 #      my $defaultauth;
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');      if (ref($cancreate) eq 'ARRAY') {
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);          if (grep(/^login$/,@{$cancreate})) {
                     unless ($sudom eq $form{'udom'}) {              $defaultauth = 1;
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');          }
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);      }
                         unless ($suprim eq $uprim) {      my $clientcancheckhost = 1;
                             unless ($suintdom eq $uintdom) {      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
                                 &Apache::lonnet::logthis('Attempted switch user '                                                $form{'udom'},$defaultauth,
                                    .'to user with different "internet domain".');                                                $clientcancheckhost);
                                 $noprivswitch = 1;  
                             }  # --------------------------------------------------------------------- Failed?
                         }  
                     }      if ($authhost eq 'no_host') {
    &failed($r,'Username and/or password could not be authenticated.',
                     unless ($noprivswitch) {   \%form);
 #          return OK;
 # server where log-in occurs must have same "internet domain" as su-user's home      } elsif ($authhost eq 'no_account_on_host') {
 # server          if ($defaultauth) {
 #              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
                         my $lonhost = $r->dir_config('lonHostID');              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);                  return OK;
                         if ($hostintdom ne $suintdom) {              }
                             &Apache::lonnet::logthis('Attempted switch user on a '              my $start_page =
                                 .'server with a different "internet domain".');                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
                         } else {              my $lonhost = $r->dir_config('lonHostID');
               my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
 # -------------------------------------------------------- actually switch users              my $contacts =
                   &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.                                                          $form{'udom'},$origmail);
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);              my ($contact_email) = split(',',$contacts);
     $form{'uname'}=$suname;              my $output =
                             if ($form{'udom'} ne $sudom) {                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                                 $form{'udom'}=$sudom;                                                         $domdesc,'',$lonhost,
                             }                                                         $contact_email,$contact_name,
                         }                                                         undef,$statustocreate);
                     }              &Apache::loncommon::content_type($r,'text/html');
  }              $r->send_http_header;
     }              &Apache::createaccount::print_header($r,$start_page);
  } else {              $r->print('<h3>'.&mt('Account creation').'</h3>'.
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
  }                        $output.&Apache::loncommon::end_page());
     }              return OK;
           } else {
     my ($is_balancer,$otherserver);              &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);
               return OK;
     unless ($hosthere) {          }
         ($is_balancer,$otherserver) =      }
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');  
         if ($is_balancer) {      if (($firsturl eq '') ||
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)   ($firsturl=~/^\/adm\/(logout|remote)/)) {
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);   $firsturl='/adm/roles';
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {      }
                 $otherserver = $found_server;  
             }      my $hosthere;
             if ($otherserver eq '') {      if ($form{'iptoken'}) {
                 my $lowest_load;          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
                 if ($lowest_load > 100) {          if (($sessiondata{'domain'} eq $form{'udom'}) &&
                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});              ($sessiondata{'username'} eq $form{'uname'})) {
                 }              $hosthere = 1;
             }          }
             if ($otherserver ne '') {      }
                 my @hosts = &Apache::lonnet::current_machine_ids();  
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {  # --------------------------------- Are we attempting to login as somebody else?
                     $hosthere = $otherserver;      if ($form{'suname'}) {
                 }          my ($suname,$sudom,$sudomref);
             }          $suname = $form{'suname'};
         }          $sudom = $form{'udom'};
     }          if ($form{'sudom'}) {
               unless ($sudom eq $form{'sudom'}) {
     if (($is_balancer) && (!$hosthere)) {                  if (&Apache::lonnet::domain($form{'sudom'})) {
         if ($otherserver) {                      $sudomref = [$form{'sudom'}];
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                      $sudom = $form{'sudom'};
                      \%form);                  }
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;              }
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {          }
                 $switchto .= '&origurl='.$firsturl;  # ------------ see if the original user has enough privileges to pull this stunt
             }   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
             if ($form{'role'}) {  # ---------------------------------------------------- see if the su-user exists
                 $switchto .= '&role='.$form{'role'};      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
             }  # ------------------------------ see if the su-user is not too highly privileged
             if ($form{'symb'}) {   if (&Apache::lonnet::privileged($suname,$sudom)) {
                 $switchto .= '&symb='.$form{'symb'};                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
             }                  } else {
             $r->internal_redirect($switchto);                      my $noprivswitch;
         } else {  #
             &Apache::loncommon::content_type($r,'text/html');  # su-user's home server and user's home server must have one of:
             $r->send_http_header;  # (a) same domain
             $r->print(&noswitch());  # (b) same primary library server for the two domains
         }  # (c) same "internet domain" for primary library server(s) for home servers' domains
         return OK;  #
     } else {                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
         if (!&check_can_host($r,\%form,$authhost)) {                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});                      unless ($sudom eq $form{'udom'}) {
             if ($otherserver) {                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
                          \%form);                          unless ($suprim eq $uprim) {
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;                              unless ($suintdom eq $uintdom) {
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {                                  &Apache::lonnet::logthis('Attempted switch user '
                     $switchto .= '&origurl='.$firsturl;                                     .'to user with different "internet domain".');                        
                 }                                  $noprivswitch = 1;
                 if ($form{'role'}) {                              }
                     $switchto .= '&role='.$form{'role'};                          }
                 }                      }
                 if ($form{'symb'}) {  
                     $switchto .= '&symb='.$form{'symb'};                      unless ($noprivswitch) {
                 }  #
                 $r->internal_redirect($switchto);  # server where log-in occurs must have same "internet domain" as su-user's home
             } else {  # server
                 &Apache::loncommon::content_type($r,'text/html');  #
                 $r->send_http_header;                          my $lonhost = $r->dir_config('lonHostID');
                 $r->print(&noswitch());                          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 {
 # ------------------------------------------------------- Do the load balancing  
   # -------------------------------------------------------- actually switch users
 # ---------------------------------------------------------- Determine own load  
         my $loadlim = $r->dir_config('lonLoadLim');              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
         my $loadavg;                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
         {              $form{'uname'}=$suname;
             my $loadfile=Apache::File->new('/proc/loadavg');                              if ($form{'udom'} ne $sudom) {
             $loadavg=<$loadfile>;                                  $form{'udom'}=$sudom;
         }                              }
         $loadavg =~ s/\s.*//g;                          }
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);                      }
         my $userloadpercent=&Apache::lonnet::userload();   }
       }
 # ---------------------------------------------------------- Are we overloaded?   } else {
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});   }
             if (!$unloaded) {      }
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});  
             }      my ($is_balancer,$otherserver);
             if ($unloaded) {  
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',      unless ($hosthere) {
                          undef,\%form);          ($is_balancer,$otherserver) =
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
                 return OK;          if ($is_balancer) {
             }              if ($otherserver eq '') {
         }                  my $lowest_load;
         if (($is_balancer) && ($hosthere)) {                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
             $form{'noloadbalance'} = $hosthere;                  if ($lowest_load > 100) {
         }                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
         my $extra_env;                  }
         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {              }
             if ($sessiondata{'origurl'} ne '') {              if ($otherserver ne '') {
                 $firsturl = $sessiondata{'origurl'};                  my @hosts = &Apache::lonnet::current_machine_ids();
                 $form{'firsturl'} = $sessiondata{'origurl'};                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
                 my @names = ('role','symb','linkprot','linkkey');                      $hosthere = $otherserver;
                 foreach my $item (@names) {                  }
                     if ($sessiondata{$item} ne '') {              }
                         $form{$item} = $sessiondata{$item};          }
                     }      }
                 }  
             }      if (($is_balancer) && (!$hosthere)) {
         }          if ($otherserver) {
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                  \%form);                       \%form);
         return OK;              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
     }              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
 }                  $switchto .= '&origurl='.$firsturl; #should escape
               }
 sub get_form_items {              if ($form{'role'}) {
     my ($r) = @_;                  $switchto .= '&role='.$form{'role'};
     my $buffer;              }
     if ($r->header_in('Content-length') > 0) {              if ($form{'symb'}) {
         $r->read($buffer,$r->header_in('Content-length'),0);                  $switchto .= '&symb='.$form{'symb'};
     }              }
     my %form;              if ($form{'linkprot'}) {
     foreach my $pair (split(/&/,$buffer)) {                  $env{'request.linkprot'} = $form{'linkprot'};
        my ($name,$value) = split(/=/,$pair);              } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
        $value =~ tr/+/ /;                  if ($form{'linkkey'}) {
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;                      $env{'request.linkkey'} = $form{'linkkey'};
        $form{$name}=$value;                  }
     }                  $env{'request.deeplink.login'} = $form{'firsturl'};
     return %form;              }
 }              $r->internal_redirect($switchto);
           } else {
 sub set_retry_token {              $r->print(&noswitch());
     my ($form,$lonhost,$querystr) = @_;          }
     if (ref($form) eq 'HASH') {          return OK;
         my ($firsturl,$token,$extras,@names);      } else {
         @names = ('role','symb','iptoken');          if (!&check_can_host($r,\%form,$authhost)) {
         foreach my $name (@names) {              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
             if ($form->{$name} ne '') {              if ($otherserver) {
                 $extras .= '&'.$name.'='.&escape($form->{$name});                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                 last if ($name eq 'linkprot');                           \%form);
             }                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
         }                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
         my $firsturl = $form->{'firsturl'};                      $switchto .= '&origurl='.$firsturl; #should escape
         if (($firsturl ne '') || ($extras ne '')) {                  }
             $extras .= ':retry';                  if ($form{'role'}) {
             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).                      $switchto .= '&role='.$form{'role'};
                                             $extras,$lonhost);                  }
             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {                  if ($form{'symb'}) {
                 return 'fail';                      $switchto .= '&symb='.$form{'symb'};
             } else {                  }
                 if (ref($querystr)) {                  if ($form{'linkprot'}) {
                     $$querystr = 'retry='.$token;                      $env{'request.linkprot'} = $form{'linkprot'};
                 }                  } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                 return 'ok';                      if ($form{'linkkey'}) {
             }                          $env{'request.linkkey'} = $form{'linkkey'};
         }                      }
     }                      $env{'request.deeplink.login'} = $form{'firsturl'};
     return;  
 }                  }
                   $r->internal_redirect($switchto);
 sub check_can_host {              } else {
     my ($r,$form,$authhost,$domdesc) = @_;                  $r->print(&noswitch());
     return unless (ref($form) eq 'HASH');              }
     my $canhost = 1;              return OK;
     my $lonhost = $r->dir_config('lonHostID');          }
     my $udom = $form->{'udom'};  
     my @intdoms;  # ------------------------------------------------------- Do the load balancing
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);  
     if (ref($internet_names) eq 'ARRAY') {  # ---------------------------------------------------------- Determine own load
         @intdoms = @{$internet_names};          my $loadlim = $r->dir_config('lonLoadLim');
     }          my $loadavg;
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');          {
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);              my $loadfile=Apache::File->new('/proc/loadavg');
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {              $loadavg=<$loadfile>;
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);          }
         my $hostname = &Apache::lonnet::hostname($lonhost);          $loadavg =~ s/\s.*//g;
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);          my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);          my $userloadpercent=&Apache::lonnet::userload();
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);  
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);  # ---------------------------------------------------------- Are we overloaded?
         my $loncaparev;          if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
         if ($authhost eq 'no_account_on_host') {              my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);              if (!$unloaded) {
         } else {                  ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);              }
         }              if ($unloaded) {
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                                                      $udomdefaults{'remotesessions'},                           undef,\%form);
                                                      $defdomdefaults{'hostedsessions'});                  if ($form{'linkprot'}) {
     }                      $env{'request.linkprot'} = $form{'linkprot'};
     unless ($canhost) {                  } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
         if ($authhost eq 'no_account_on_host') {                      if ($form{'linkkey'}) {
             my $checkloginvia = 1;                          $env{'request.linkkey'} = $form{'linkkey'};
             my ($login_host,$hostname) =                       }
                 &Apache::lonnet::choose_server($udom,$checkloginvia);                      $env{'request.deeplink.login'} = $form{'firsturl'};
             &Apache::loncommon::content_type($r,'text/html');                  }
             $r->send_http_header;                  $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
             if ($login_host ne '') {                  return OK;
                 my $protocol = $Apache::lonnet::protocol{$login_host};              }
                 $protocol = 'http' if ($protocol ne 'https');          }
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);          if (($is_balancer) && ($hosthere)) {
                 $hostname = $alias if ($alias ne '');              $form{'noloadbalance'} = $hosthere;
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';          }
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').          my $extra_env;
                           '<h3>'.&mt('Account creation').'</h3>'.          if ($form{'linkprot'}) {
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.              my ($linkprotector,$uri) = split(/:/,$form{'linkprot'},2);
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.              if ($linkprotector) {
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').                  $extra_env = {'user.linkprotector' => $linkprotector,
                           &Apache::loncommon::end_page());                                'user.linkproturi'   => $uri,};
             } else {              }
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').          } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.              if ($form{'linkkey'}) {
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.                  $extra_env = {'user.deeplinkkey' => $form{'linkkey'},
                           '<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>'.                                'user.keyedlinkuri' => $form{'firsturl'},
                           &Apache::loncommon::end_page());                                'request.deeplink.login' => $form{'firsturl'}};
             }              } else {
         } else {                  $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,              }
                      $form);          }
             my ($otherserver) = &Apache::lonnet::choose_server($udom);          &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);                   \%form);
         }          return OK;
     }      }
     return $canhost;  }
 }  
   sub check_can_host {
 sub noswitch {      my ($r,$form,$authhost,$domdesc) = @_;
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').      return unless (ref($form) eq 'HASH');
                  '<h3>'.&mt('Session unavailable').'</h3>'.      my $canhost = 1;
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.      my $lonhost = $r->dir_config('lonHostID');
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.      my $udom = $form->{'udom'};
                  &Apache::loncommon::end_page();      my @intdoms;
     return $result;      my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
 }      if (ref($internet_names) eq 'ARRAY') {
           @intdoms = @{$internet_names};
 sub loginhelpdisplay {      }
     my ($authdomain) = @_;      my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
     my $login_help = 1;      my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
     my $lang = &Apache::lonlocal::current_language();      unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
     if ($login_help) {          my $machine_dom = &Apache::lonnet::host_domain($lonhost);
         my $dom = $authdomain;          my $hostname = &Apache::lonnet::hostname($lonhost);
         if ($dom eq '') {          my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
             $dom = &Apache::lonnet::default_login_domain();          my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
         }          my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);          my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
         my $loginhelp_url;          my $loncaparev;
         if ($lang) {          if ($authhost eq 'no_account_on_host') {
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
             if ($loginhelp_url ne '') {          } else {
                 return $loginhelp_url;              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
             }          }
         }          $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};                                                       $udomdefaults{'remotesessions'},
         if ($loginhelp_url ne '') {                                                       $defdomdefaults{'hostedsessions'});
             return $loginhelp_url;      }
         } else {      unless ($canhost) {
             return '/adm/loginproblems.html';          if ($authhost eq 'no_account_on_host') {
         }              my $checkloginvia = 1;
     }              my ($login_host,$hostname) =
     return;                  &Apache::lonnet::choose_server($udom,$checkloginvia);
 }              &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
 1;              if ($login_host ne '') {
 __END__                  my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   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->{'linkprot'}) {
                   $env{'request.linkprot'} = $form->{'linkprot'};
               } elsif ($form->{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                   if ($form->{'linkkey'}) {
                       $env{'request.linkkey'} = $form->{'linkkey'};
                   }
                   $env{'request.deeplink.login'} = $form->{'firsturl'};
               }
               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;
   }
   
   1;
   __END__
   
   

Removed from v.1.121.2.22  
changed lines
  Added in v.1.159


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