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

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


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