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

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

Removed from v.1.121.2.15  
changed lines
  Added in v.1.151


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