Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.3 and 1.151

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

Removed from v.1.121.2.24.2.3  
changed lines
  Added in v.1.151


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