Diff for /loncom/auth/lonauth.pm between versions 1.129 and 1.162

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

Removed from v.1.129  
changed lines
  Added in v.1.162


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