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

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

Removed from v.1.121.2.22  
changed lines
  Added in v.1.154


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