Diff for /loncom/auth/lonauth.pm between versions 1.121.2.11 and 1.163

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


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