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

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


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