Diff for /loncom/auth/lonauth.pm between versions 1.121.2.4 and 1.165

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


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