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

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


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