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

version 1.121.2.23, 2021/12/16 21:48:19 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',
             }                                                     $js,$args);
         }  
     } elsif ($querystr ne '') {          my %lt=&Apache::lonlocal::texthash(
         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;             'wel' => 'Welcome',
     }             'pro' => 'Login problems?',
     my $end_page = &Apache::loncommon::end_page();            );
     &Apache::loncommon::content_type($r,'text/html');          $pagebody = "<h1>$lt{'wel'}</h1>\n".
     $r->send_http_header;                      &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
     my @actions =          my $loginhelp = &loginhelpdisplay($domain);
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));          if ($loginhelp) {
     my $loginhelp = &loginhelpdisplay($udom);              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
     if ($loginhelp) {          }
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');      }
     }      $end_page = &Apache::loncommon::end_page();
     #FIXME: link to helpdesk might be added here      $r->print(<<ENDSUCCESS);
   $start_page
     $r->print(  $windowinfo
        $start_page  $pagebody
       .'<h2>'.&mt('Sorry ...').'</h2>'  $end_page
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'  ENDSUCCESS
       .&Apache::lonhtmlcommon::actionbox(\@actions)      return;
       .$end_page  }
     );  
  }  # --------------------------------------------------------------- Failed login!
   
 # ------------------------------------------------------------------ Rerouting!  sub failed {
       my ($r,$message,$form) = @_;
 sub reroute {      (undef,undef,undef,my $clientmathml,my $clientunicode) =
     my ($r) = @_;          &Apache::loncommon::decode_user_agent();
     &Apache::loncommon::content_type($r,'text/html');      my $args = {};
     $r->send_http_header;      if ($clientunicode && !$clientmathml) {
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'          $args = {'browser.unicode' => 1};
            .&mt('Please [_1]log in again[_2].');      }
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});  
 }      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
       my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
 # ---------------------------------------------------------------- Main handler      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
       if (&Apache::lonnet::domain($udom,'description') eq '') {
 sub handler {          undef($udom);
     my $r = shift;      }
     my $londocroot = $r->dir_config('lonDocRoot');      my $retry = '/adm/login';
 # Are we re-routing?      if ($uname eq $form->{'uname'}) {
     if (-e "$londocroot/lon-status/reroute.txt") {          $retry .= '?username='.$uname;
  &reroute($r);      }
  return OK;      if ($udom) {
     }          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
       }
     &Apache::lonlocal::get_language_handle($r);      if (exists($form->{role})) {
           my $role = &Apache::loncommon::cleanup_html($form->{role});
 # -------------------------------- Prevent users from attempting to login twice          if ($role ne '') {
     my $handle = &Apache::lonnet::check_for_valid_session($r);              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
     if ($handle ne '') {          }
         my $lonidsdir=$r->dir_config('lonIDsDir');      }
         if ($handle=~/^publicuser\_/) {      if (exists($form->{symb})) {
 # For "public user" - remove it, we apparently really want to login          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
             unlink($r->dir_config('lonIDsDir')."/$handle.id");          if ($symb ne '') {
         } else {              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
 # Indeed, a valid token is found          }
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);      }
     &Apache::loncommon::content_type($r,'text/html');      if (exists($form->{firsturl})) {
     $r->send_http_header;          my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
     my $start_page =           if ($firsturl ne '') {
         &Apache::loncommon::start_page('Already logged in');              $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
     my $end_page =               if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
         &Apache::loncommon::end_page();                  unless (exists($form->{linkprot})) {
             my $dest = '/adm/roles';                      if (exists($form->{linkkey})) {
             my %form = &get_form_items($r);                          $retry .= 'linkkey='.$form->{linkkey};
             if ($form{'logtoken'}) {                      }
                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},                  }
                                                      $form{'serverid'});              }
                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||          }
                         ($tmpinfo eq 'no_such_host')) {      }
                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);      if (exists($form->{linkprot})) {
                     $firsturl = &unescape($firsturl);          my $ltoken = &Apache::lonnet::tmpput({linkprot => $form->{'linkprot'}},
                     my %info;                                               $r->dir_config('lonHostID'));
                     foreach my $item (@rest) {          if ($ltoken) {
                         my ($key,$value) = split(/=/,$item);              $retry .= (($retry =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
                         $info{$key} = &unescape($value);          }
                     }      }
                     if ($firsturl ne '') {      my $end_page = &Apache::loncommon::end_page();
                         $info{'firsturl'} = $firsturl;      &Apache::loncommon::content_type($r,'text/html');
                         $dest = $firsturl;      $r->send_http_header;
                     }      my @actions =
                 }           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
             }      my $loginhelp = &loginhelpdisplay($udom);
             $r->print(      if ($loginhelp) {
                $start_page          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
               .'<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].'      #FIXME: link to helpdesk might be added here
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')  
               .'</p>'      $r->print(
               .$end_page         $start_page
             );        .'<h2>'.&mt('Sorry ...').'</h2>'
             return OK;        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
         }        .&Apache::lonhtmlcommon::actionbox(\@actions)
     }        .$end_page
       );
 # ---------------------------------------------------- No valid token, continue   }
   
     my %form = &get_form_items($r);  # ------------------------------------------------------------------ Rerouting!
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {  
  &failed($r,'Username, password and domain need to be specified.',  sub reroute {
  \%form);      my ($r) = @_;
         return OK;      &Apache::loncommon::content_type($r,'text/html');
     }      $r->send_http_header;
       my $msg='<b>'.&mt('Sorry ...').'</b><br />'
 # split user logging in and "su"-user             .&mt('Please [_1]log in again[_2].');
       &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});  }
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});  
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});  # ---------------------------------------------------------------- Main handler
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});  
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});  sub handler {
       my $r = shift;
     my $role   = $r->dir_config('lonRole');      my $londocroot = $r->dir_config('lonDocRoot');
     my $domain = $r->dir_config('lonDefDomain');  # Are we re-routing?
     my $prodir = $r->dir_config('lonUsersDir');      if (-e "$londocroot/lon-status/reroute.txt") {
     my $contact_name = &mt('LON-CAPA helpdesk');   &reroute($r);
    return OK;
 # ---------------------------------------- Get the information from login token      }
   
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},      &Apache::lonlocal::get_language_handle($r);
                                       $form{'serverid'});  
   # -------------------------------- Prevent users from attempting to login twice
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||       my $handle = &Apache::lonnet::check_for_valid_session($r);
         ($tmpinfo eq 'no_such_host')) {      if ($handle ne '') {
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);          my $lonidsdir=$r->dir_config('lonIDsDir');
         return OK;          if ($handle=~/^publicuser\_/) {
     } else {  # For "public user" - remove it, we apparently really want to login
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},              unlink($r->dir_config('lonIDsDir')."/$handle.id");
    $form{'serverid'});          } else {
         if ( $reply ne 'ok' ) {  # Indeed, a valid token is found
             &failed($r,'Session could not be opened.',\%form);              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");      &Apache::loncommon::content_type($r,'text/html');
     return OK;      $r->send_http_header;
  }      my $start_page =
     }          &Apache::loncommon::start_page('Already logged in');
       my $end_page =
     if (!&Apache::lonnet::domain($form{'udom'})) {          &Apache::loncommon::end_page();
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);              my $dest = '/adm/roles';
         return OK;              if ($env{'form.firsturl'} ne '') {
     }                  $dest = $env{'form.firsturl'};
                   if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);                      &Apache::lonnet::appenv({'request.deeplink.login' => $env{'form.firsturl'}});
     $firsturl = &unescape($firsturl);                  }
     foreach my $item (@rest) {              }
         my ($key,$value) = split(/=/,$item);              $r->print(
         $form{$key} = &unescape($value);                 $start_page
     }                .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
     my $upass = &Apache::loncommon::des_decrypt($des_key,$form{'upass0'});                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
                       ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
 # ---------------------------------------------------------------- Authenticate                .'</p>'
                 .$end_page
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});              );
     my ($cancreate,$statustocreate) =              return OK;
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});          }
     my $defaultauth;      }
     if (ref($cancreate) eq 'ARRAY') {  
         if (grep(/^login$/,@{$cancreate})) {  # ---------------------------------------------------- No valid token, continue
             $defaultauth = 1;  
         }  
     }      my $buffer;
     my $clientcancheckhost = 1;      if ($r->header_in('Content-length') > 0) {
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,   $r->read($buffer,$r->header_in('Content-length'),0);
                                               $form{'udom'},$defaultauth,      }
                                               $clientcancheckhost);      my %form;
           foreach my $pair (split(/&/,$buffer)) {
 # --------------------------------------------------------------------- Failed?         my ($name,$value) = split(/=/,$pair);
          $value =~ tr/+/ /;
     if ($authhost eq 'no_host') {         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  &failed($r,'Username and/or password could not be authenticated.',         $form{$name}=$value;
  \%form);      }
         return OK;  
     } elsif ($authhost eq 'no_account_on_host') {      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
         if ($defaultauth) {   &failed($r,'Username, password and domain need to be specified.',
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');   \%form);
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {          return OK;
                 return OK;      }
             }  
             my $start_page =   # split user logging in and "su"-user
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',  
                                                '',{'no_inline_link'   => 1,});      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
             my $lonhost = $r->dir_config('lonHostID');      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
             my $contacts =       $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
                                                         $form{'udom'},$origmail);  
             my ($contact_email) = split(',',$contacts);       my $role   = $r->dir_config('lonRole');
             my $output =       my $domain = $r->dir_config('lonDefDomain');
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},      my $prodir = $r->dir_config('lonUsersDir');
                                                        $domdesc,'',$lonhost,      my $contact_name = &mt('LON-CAPA helpdesk');
                                                        $contact_email,$contact_name,  
                                                        undef,$statustocreate);  # ---------------------------------------- Get the information from login token
             &Apache::loncommon::content_type($r,'text/html');  
             $r->send_http_header;      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
             &Apache::createaccount::print_header($r,$start_page);                                        $form{'serverid'});
             $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 />'.      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
                       $output.&Apache::loncommon::end_page());          ($tmpinfo eq 'no_such_host')) {
             return OK;   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
         } 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);      } else {
             return OK;   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
         }     $form{'serverid'});
     }          if ( $reply ne 'ok' ) {
               &failed($r,'Session could not be opened.',\%form);
     if (($firsturl eq '') ||       &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
  ($firsturl=~/^\/adm\/(logout|remote)/)) {      return OK;
  $firsturl='/adm/roles';   }
     }      }
   
     my ($hosthere,%sessiondata);      if (!&Apache::lonnet::domain($form{'udom'})) {
     if ($form{'iptoken'}) {          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});          return OK;
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});      }
         if (($sessiondata{'domain'} eq $form{'udom'}) &&  
             ($sessiondata{'username'} eq $form{'uname'})) {      my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr,$linkstr)=split(/&/,$tmpinfo);
             $hosthere = 1;      if ($rolestr) {
         }          $rolestr = &unescape($rolestr);
     }      }
       if ($symbstr) {
 # --------------------------------- Are we attempting to login as somebody else?          $symbstr= &unescape($symbstr);
     if ($form{'suname'}) {      }
         my ($suname,$sudom,$sudomref);      if ($iptokenstr) {
         $suname = $form{'suname'};          $iptokenstr = &unescape($iptokenstr);
         $sudom = $form{'udom'};      }
         if ($form{'sudom'}) {      if ($linkstr) {
             unless ($sudom eq $form{'sudom'}) {          $linkstr = &unescape($linkstr);
                 if (&Apache::lonnet::domain($form{'sudom'})) {      }
                     $sudomref = [$form{'sudom'}];      if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
                     $sudom = $form{'sudom'};          $form{'firsturl'} = $firsturl;
                 }      }
             }      if ($rolestr =~ /^role=/) {
         }          (undef,$form{'role'}) = split('=',$rolestr);
 # ------------ see if the original user has enough privileges to pull this stunt      }
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {      if ($symbstr =~ /^symb=/) {
 # ---------------------------------------------------- see if the su-user exists          (undef,$form{'symb'}) = split('=',$symbstr);
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {      }
 # ------------------------------ see if the su-user is not too highly privileged      if ($iptokenstr =~ /^iptoken=/) {
  if (&Apache::lonnet::privileged($suname,$sudom)) {          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');      }
                 } else {      if ($linkstr =~ /^linkprot=/) {
                     my $noprivswitch;          (undef,$form{'linkprot'}) = split('=',$linkstr);
 #      } elsif ($linkstr =~ /^linkkey=/) {
 # su-user's home server and user's home server must have one of:          (undef,$form{'linkkey'}) = split('=',$linkstr);
 # (a) same domain      }
 # (b) same primary library server for the two domains  
 # (c) same "internet domain" for primary library server(s) for home servers' domains      my $upass = $ENV{HTTPS} ? $form{'upass0'}
 #          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');  
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);  # ---------------------------------------------------------------- Authenticate
                     unless ($sudom eq $form{'udom'}) {  
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);      my ($cancreate,$statustocreate) =
                         unless ($suprim eq $uprim) {          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
                             unless ($suintdom eq $uintdom) {      my $defaultauth;
                                 &Apache::lonnet::logthis('Attempted switch user '      if (ref($cancreate) eq 'ARRAY') {
                                    .'to user with different "internet domain".');          if (grep(/^login$/,@{$cancreate})) {
                                 $noprivswitch = 1;              $defaultauth = 1;
                             }          }
                         }      }
                     }      my $clientcancheckhost = 1;
       my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
                     unless ($noprivswitch) {                                                $form{'udom'},$defaultauth,
 #                                                $clientcancheckhost);
 # server where log-in occurs must have same "internet domain" as su-user's home  
 # server  # --------------------------------------------------------------------- Failed?
 #  
                         my $lonhost = $r->dir_config('lonHostID');      if ($authhost eq 'no_host') {
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);   &failed($r,'Username and/or password could not be authenticated.',
                         if ($hostintdom ne $suintdom) {   \%form);
                             &Apache::lonnet::logthis('Attempted switch user on a '          return OK;
                                 .'server with a different "internet domain".');      } elsif ($authhost eq 'no_account_on_host') {
                         } else {          if ($defaultauth) {
               my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
 # -------------------------------------------------------- actually switch users              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
                   return OK;
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.              }
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);              my $start_page =
     $form{'uname'}=$suname;                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
                             if ($form{'udom'} ne $sudom) {              my $lonhost = $r->dir_config('lonHostID');
                                 $form{'udom'}=$sudom;              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                             }              my $contacts =
                         }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                     }                                                          $form{'udom'},$origmail);
  }              my ($contact_email) = split(',',$contacts);
     }              my $output =
  } else {                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');                                                         $domdesc,'',$lonhost,
  }                                                         $contact_email,$contact_name,
     }                                                         undef,$statustocreate);
               &Apache::loncommon::content_type($r,'text/html');
     my ($is_balancer,$otherserver);              $r->send_http_header;
               &Apache::createaccount::print_header($r,$start_page);
     unless ($hosthere) {              $r->print('<h3>'.&mt('Account creation').'</h3>'.
         ($is_balancer,$otherserver) =                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');                        $output.&Apache::loncommon::end_page());
         if ($is_balancer) {              return OK;
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)          } else {
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);              &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);
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {              return OK;
                 $otherserver = $found_server;          }
             }      }
             if ($otherserver eq '') {  
                 my $lowest_load;      if (($firsturl eq '') ||
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});   ($firsturl=~/^\/adm\/(logout|remote)/)) {
                 if ($lowest_load > 100) {   $firsturl='/adm/roles';
                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});      }
                 }  
             }      my $hosthere;
             if ($otherserver ne '') {      if ($form{'iptoken'}) {
                 my @hosts = &Apache::lonnet::current_machine_ids();          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
                     $hosthere = $otherserver;          if (($sessiondata{'domain'} eq $form{'udom'}) &&
                 }              ($sessiondata{'username'} eq $form{'uname'})) {
             }              $hosthere = 1;
         }          }
     }      }
   
     if (($is_balancer) && (!$hosthere)) {  # --------------------------------- Are we attempting to login as somebody else?
         if ($otherserver) {      if ($form{'suname'}) {
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,          my ($suname,$sudom,$sudomref);
                      \%form);          $suname = $form{'suname'};
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;          $sudom = $form{'udom'};
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {          if ($form{'sudom'}) {
                 $switchto .= '&origurl='.$firsturl;              unless ($sudom eq $form{'sudom'}) {
             }                  if (&Apache::lonnet::domain($form{'sudom'})) {
             if ($form{'role'}) {                      $sudomref = [$form{'sudom'}];
                 $switchto .= '&role='.$form{'role'};                      $sudom = $form{'sudom'};
             }                  }
             if ($form{'symb'}) {              }
                 $switchto .= '&symb='.$form{'symb'};          }
             }  # ------------ see if the original user has enough privileges to pull this stunt
             $r->internal_redirect($switchto);   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
         } else {  # ---------------------------------------------------- see if the su-user exists
             &Apache::loncommon::content_type($r,'text/html');      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
             $r->send_http_header;  # ------------------------------ see if the su-user is not too highly privileged
             $r->print(&noswitch());   if (&Apache::lonnet::privileged($suname,$sudom)) {
         }                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
         return OK;                  } else {
     } else {                      my $noprivswitch;
         if (!&check_can_host($r,\%form,$authhost)) {  #
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});  # su-user's home server and user's home server must have one of:
             if ($otherserver) {  # (a) same domain
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,  # (b) same primary library server for the two domains
                          \%form);  # (c) same "internet domain" for primary library server(s) for home servers' domains
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;  #
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
                     $switchto .= '&origurl='.$firsturl;                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
                 }                      unless ($sudom eq $form{'udom'}) {
                 if ($form{'role'}) {                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
                     $switchto .= '&role='.$form{'role'};                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
                 }                          unless ($suprim eq $uprim) {
                 if ($form{'symb'}) {                              unless ($suintdom eq $uintdom) {
                     $switchto .= '&symb='.$form{'symb'};                                  &Apache::lonnet::logthis('Attempted switch user '
                 }                                     .'to user with different "internet domain".');                        
                 $r->internal_redirect($switchto);                                  $noprivswitch = 1;
             } else {                              }
                 &Apache::loncommon::content_type($r,'text/html');                          }
                 $r->send_http_header;                      }
                 $r->print(&noswitch());  
             }                      unless ($noprivswitch) {
             return OK;  #
         }  # server where log-in occurs must have same "internet domain" as su-user's home
   # server
 # ------------------------------------------------------- Do the load balancing  #
                           my $lonhost = $r->dir_config('lonHostID');
 # ---------------------------------------------------------- Determine own load                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
         my $loadlim = $r->dir_config('lonLoadLim');                          if ($hostintdom ne $suintdom) {
         my $loadavg;                              &Apache::lonnet::logthis('Attempted switch user on a '
         {                                  .'server with a different "internet domain".');
             my $loadfile=Apache::File->new('/proc/loadavg');                          } else {
             $loadavg=<$loadfile>;  
         }  # -------------------------------------------------------- actually switch users
         $loadavg =~ s/\s.*//g;  
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
         my $userloadpercent=&Apache::lonnet::userload();                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
               $form{'uname'}=$suname;
 # ---------------------------------------------------------- Are we overloaded?                              if ($form{'udom'} ne $sudom) {
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {                                  $form{'udom'}=$sudom;
             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});                              }
             if (!$unloaded) {                          }
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});                      }
             }   }
             if ($unloaded) {      }
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',   } else {
                          undef,\%form);      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);   }
                 return OK;      }
             }  
         }      my ($is_balancer,$otherserver);
         if (($is_balancer) && ($hosthere)) {  
             $form{'noloadbalance'} = $hosthere;      unless ($hosthere) {
         }          ($is_balancer,$otherserver) =
         my $extra_env;              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {          if ($is_balancer) {
             if ($sessiondata{'origurl'} ne '') {              if ($otherserver eq '') {
                 $firsturl = $sessiondata{'origurl'};                  my $lowest_load;
                 $form{'firsturl'} = $sessiondata{'origurl'};                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                 my @names = ('role','symb','linkprot','linkkey');                  if ($lowest_load > 100) {
                 foreach my $item (@names) {                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
                     if ($sessiondata{$item} ne '') {                  }
                         $form{$item} = $sessiondata{$item};              }
                     }              if ($otherserver ne '') {
                 }                  my @hosts = &Apache::lonnet::current_machine_ids();
             }                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
         }                      $hosthere = $otherserver;
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,                  }
                  \%form);              }
         return OK;          }
     }      }
 }  
       if (($is_balancer) && (!$hosthere)) {
 sub get_form_items {          if ($otherserver) {
     my ($r) = @_;              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
     my $buffer;                       \%form);
     if ($r->header_in('Content-length') > 0) {              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
         $r->read($buffer,$r->header_in('Content-length'),0);              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
     }                  $switchto .= '&origurl='.$firsturl; #should escape
     my %form;              }
     foreach my $pair (split(/&/,$buffer)) {              if ($form{'role'}) {
        my ($name,$value) = split(/=/,$pair);                  $switchto .= '&role='.$form{'role'};
        $value =~ tr/+/ /;              }
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;              if ($form{'symb'}) {
        $form{$name}=$value;                  $switchto .= '&symb='.$form{'symb'};
     }              }
     return %form;              if ($form{'linkprot'}) {
 }                  $env{'request.linkprot'} = $form{'linkprot'};
               } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
 sub set_retry_token {                  if ($form{'linkkey'}) {
     my ($form,$lonhost,$querystr) = @_;                      $env{'request.linkkey'} = $form{'linkkey'};
     if (ref($form) eq 'HASH') {                  }
         my ($firsturl,$token,$extras,@names);                  $env{'request.deeplink.login'} = $form{'firsturl'};
         @names = ('role','symb','iptoken');              }
         foreach my $name (@names) {              $r->internal_redirect($switchto);
             if ($form->{$name} ne '') {          } else {
                 $extras .= '&'.$name.'='.&escape($form->{$name});              $r->print(&noswitch());
                 last if ($name eq 'linkprot');          }
             }          return OK;
         }      } else {
         my $firsturl = $form->{'firsturl'};          if (!&check_can_host($r,\%form,$authhost)) {
         if (($firsturl ne '') || ($extras ne '')) {              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
             $extras .= ':retry';              if ($otherserver) {
             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                                             $extras,$lonhost);                           \%form);
             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
                 return 'fail';                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
             } else {                      $switchto .= '&origurl='.$firsturl; #should escape
                 if (ref($querystr)) {                  }
                     $$querystr = 'retry='.$token;                  if ($form{'role'}) {
                 }                      $switchto .= '&role='.$form{'role'};
                 return 'ok';                  }
             }                  if ($form{'symb'}) {
         }                      $switchto .= '&symb='.$form{'symb'};
     }                  }
     return;                  if ($form{'linkprot'}) {
 }                      $env{'request.linkprot'} = $form{'linkprot'};
                   } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
 sub check_can_host {                      if ($form{'linkkey'}) {
     my ($r,$form,$authhost,$domdesc) = @_;                          $env{'request.linkkey'} = $form{'linkkey'};
     return unless (ref($form) eq 'HASH');                      }
     my $canhost = 1;                      $env{'request.deeplink.login'} = $form{'firsturl'};
     my $lonhost = $r->dir_config('lonHostID');  
     my $udom = $form->{'udom'};                  }
     my @intdoms;                  $r->internal_redirect($switchto);
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);              } else {
     if (ref($internet_names) eq 'ARRAY') {                  $r->print(&noswitch());
         @intdoms = @{$internet_names};              }
     }              return OK;
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');          }
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);  
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {  # ------------------------------------------------------- Do the load balancing
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);  
         my $hostname = &Apache::lonnet::hostname($lonhost);  # ---------------------------------------------------------- Determine own load
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);          my $loadlim = $r->dir_config('lonLoadLim');
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);          my $loadavg;
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);          {
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);              my $loadfile=Apache::File->new('/proc/loadavg');
         my $loncaparev;              $loadavg=<$loadfile>;
         if ($authhost eq 'no_account_on_host') {          }
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);          $loadavg =~ s/\s.*//g;
         } else {          my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);          my $userloadpercent=&Apache::lonnet::userload();
         }  
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,  # ---------------------------------------------------------- Are we overloaded?
                                                      $udomdefaults{'remotesessions'},          if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
                                                      $defdomdefaults{'hostedsessions'});              my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
     }              if (!$unloaded) {
     unless ($canhost) {                  ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
         if ($authhost eq 'no_account_on_host') {              }
             my $checkloginvia = 1;              if ($unloaded) {
             my ($login_host,$hostname) =                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                 &Apache::lonnet::choose_server($udom,$checkloginvia);                           undef,\%form);
             &Apache::loncommon::content_type($r,'text/html');                  if ($form{'linkprot'}) {
             $r->send_http_header;                      $env{'request.linkprot'} = $form{'linkprot'};
             if ($login_host ne '') {                  } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                 my $protocol = $Apache::lonnet::protocol{$login_host};                      if ($form{'linkkey'}) {
                 $protocol = 'http' if ($protocol ne 'https');                          $env{'request.linkkey'} = $form{'linkkey'};
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);                      }
                 $hostname = $alias if ($alias ne '');                      $env{'request.deeplink.login'} = $form{'firsturl'};
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';                  }
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').                  $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                           '<h3>'.&mt('Account creation').'</h3>'.                  return OK;
                           &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>').          if (($is_balancer) && ($hosthere)) {
                           &Apache::loncommon::end_page());              $form{'noloadbalance'} = $hosthere;
             } else {          }
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').          my $extra_env;
                           '<h3>'.&mt('Account creation unavailable').'</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('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.              if ($linkprotector) {
                           &Apache::loncommon::end_page());                  $extra_env = {'user.linkprotector' => $linkprotector,
             }                                'user.linkproturi'   => $uri,};
         } else {              }
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,          } elsif ($form{'firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                      $form);              if ($form{'linkkey'}) {
             my ($otherserver) = &Apache::lonnet::choose_server($udom);                  $extra_env = {'user.deeplinkkey' => $form{'linkkey'},
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);                                'user.keyedlinkuri' => $form{'firsturl'},
         }                                'request.deeplink.login' => $form{'firsturl'}};
     }              } else {
     return $canhost;                  $extra_env = {'request.deeplink.login' => $form{'firsturl'}};
 }              }
           }
 sub noswitch {          &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,$extra_env,
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').                   \%form);
                  '<h3>'.&mt('Session unavailable').'</h3>'.          return OK;
                  &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 check_can_host {
 }      my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
 sub loginhelpdisplay {      my $canhost = 1;
     my ($authdomain) = @_;      my $lonhost = $r->dir_config('lonHostID');
     my $login_help = 1;      my $udom = $form->{'udom'};
     my $lang = &Apache::lonlocal::current_language();      my @intdoms;
     if ($login_help) {      my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
         my $dom = $authdomain;      if (ref($internet_names) eq 'ARRAY') {
         if ($dom eq '') {          @intdoms = @{$internet_names};
             $dom = &Apache::lonnet::default_login_domain();      }
         }      my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);      my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
         my $loginhelp_url;      unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
         if ($lang) {          my $machine_dom = &Apache::lonnet::host_domain($lonhost);
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};          my $hostname = &Apache::lonnet::hostname($lonhost);
             if ($loginhelp_url ne '') {          my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                 return $loginhelp_url;          my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
             }          my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
         }          my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};          my $loncaparev;
         if ($loginhelp_url ne '') {          if ($authhost eq 'no_account_on_host') {
             return $loginhelp_url;              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
         } else {          } else {
             return '/adm/loginproblems.html';              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
         }          }
     }          $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
     return;                                                       $udomdefaults{'remotesessions'},
 }                                                       $defdomdefaults{'hostedsessions'});
       }
 1;      unless ($canhost) {
 __END__          if ($authhost eq 'no_account_on_host') {
               my $checkloginvia = 1;
               my ($login_host,$hostname) =
                   &Apache::lonnet::choose_server($udom,$checkloginvia);
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               if ($login_host ne '') {
                   my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   my $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.23  
changed lines
  Added in v.1.159


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