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

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

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


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