Diff for /loncom/auth/lonauth.pm between versions 1.121.2.12 and 1.151

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


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