Diff for /loncom/auth/lonauth.pm between versions 1.121.2.26 and 1.142

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

Removed from v.1.121.2.26  
changed lines
  Added in v.1.142


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