Diff for /loncom/auth/lonauth.pm between versions 1.121.2.25 and 1.168

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

Removed from v.1.121.2.25  
changed lines
  Added in v.1.168


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