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

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


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