Diff for /loncom/auth/lonauth.pm between versions 1.121.2.11 and 1.155

version 1.121.2.11, 2014/05/04 15:16:10 version 1.155, 2018/11/10 10:53:01
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # User Authentication Module  # User Authentication Module
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonauth;  package Apache::lonauth;
   
 use strict;  use strict;
 use LONCAPA;  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use DynaLoader; # for Crypt::DES version  use Apache::loncommon();
 use Crypt::DES;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::lonmenu();
 use Apache::lonnet;  use Apache::createaccount;
 use Apache::lonmenu();  use Apache::ltiauth;
 use Apache::createaccount;  use Fcntl qw(:flock);
 use Fcntl qw(:flock);  use Apache::lonlocal;
 use Apache::lonlocal;  use Apache::File();
 use Apache::File();  use HTML::Entities;
 use HTML::Entities;  use Digest::MD5;
     
 # ------------------------------------------------------------ Successful login  # ------------------------------------------------------------ Successful login
 sub success {  sub success {
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
  $form) = @_;   $form,$skipcritical) = @_;
   
 # ------------------------------------------------------------ Get cookie ready  # ------------------------------------------------------------ Get cookie ready
     my $cookie =      my $cookie =
  &Apache::loncommon::init_user_environment($r, $username, $domain,   &Apache::loncommon::init_user_environment($r, $username, $domain,
   $authhost, $form,    $authhost, $form,
   {'extra_env' => $extra_env,});    {'extra_env' => $extra_env,});
   
     my $public=($username eq 'public' && $domain eq 'public');      my $public=($username eq 'public' && $domain eq 'public');
   
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }      if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   
 # -------------------------------------------------------------------- Log this  # -------------------------------------------------------------------- Log this
   
     &Apache::lonnet::log($domain,$username,$authhost,      &Apache::lonnet::log($domain,$username,$authhost,
                          "Login $ENV{'REMOTE_ADDR'}");                           "Login $ENV{'REMOTE_ADDR'}");
   
 # ------------------------------------------------- Check for critical messages  # ------------------------------------------------- Check for critical messages
   
     my @what=&Apache::lonnet::dump('critical',$domain,$username);      unless ($skipcritical) {
     if ($what[0]) {          my @what=&Apache::lonnet::dump('critical',$domain,$username);
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {          if ($what[0]) {
     $lowerurl='/adm/email?critical=display';      if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
         }          $lowerurl='/adm/email?critical=display';
     }              }
           }
 # ------------------------------------------------------------ Get cookie ready      }
     $cookie="lonID=$cookie; path=/";  
 # -------------------------------------------------------- Menu script and info  # ----------------------------------------------------------- Get cookies ready
     my $destination = $lowerurl;      my ($securecookie,$defaultcookie);
       my $ssl = $r->subprocess_env('https');
     if (defined($form->{role})) {      if ($ssl) {
         my $envkey = 'user.role.'.$form->{role};          $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";
         my $now=time;          my $lonidsdir=$r->dir_config('lonIDsDir');
         my $then=$env{'user.login.time'};          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
         my $refresh=$env{'user.refresh.time'};              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
         my $update=$env{'user.update.time'};              if (-e "$lonidsdir/$linkname.id") {
         if (!$update) {                  unlink("$lonidsdir/$linkname.id");
             $update = $then;              }
         }              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
         if (exists($env{$envkey})) {                                                "$lonidsdir/$linkname.id"); 1 };
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              if ($made_symlink) {
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
                                          \$trolecode,\$tstatus,\$tstart,\$tend);                  &Apache::lonnet::appenv({'user.linkedenv' => $linkname});
             if ($tstatus eq 'is') {              }
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';          }
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');      } else {
                 $destination .= 'selectrole=1&'.$newrole.'=1';          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
             }      }
         }  # -------------------------------------------------------- Menu script and info
     }      my $destination = $lowerurl;
     if (defined($form->{symb})) {      if ($env{'request.lti.login'}) {
         my $destsymb = $form->{symb};          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              &Apache::loncommon::content_type($r,'text/html');
         if ($destsymb =~ /___/) {              if ($securecookie) {
             # FIXME Need to deal with encrypted symbs and urls as needed.                  $r->headers_out->add('Set-cookie' => $securecookie);
             my ($map,$resid,$desturl)=split(/___/,$destsymb);              }
             unless ($desturl=~/^(adm|editupload|public)/) {              if ($defaultcookie) {
                 $desturl = &Apache::lonnet::clutter($desturl);                  $r->headers_out->add('Set-cookie' => $defaultcookie);
             }              }
             $desturl = &HTML::Entities::encode($desturl,'"<>&');              $r->send_http_header;
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              if (ref($form) eq 'HASH') {
             $destination .= 'destinationurl='.$desturl.                  $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
                             '&destsymb='.$destsymb;                  $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
         } else {                  $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              }
             $destination .= 'destinationurl='.$destsymb;              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
         }              return;
     }          }
     if ($destination =~ m{^/adm/roles}) {          if ($env{'request.lti.selfenrollrole'}) {
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              if (&Apache::ltiauth::lti_enroll($username,$domain,
         $destination .= 'source=login';                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
     }                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
                   &Apache::lonnet::delenv('request.lti.selfenrollrole');
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});              } else {
     my $startupremote=&Apache::lonmenu::startupremote($destination);                  &Apache::ltiauth::invalid_request($r,24);
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);              }
     my $setflags=&Apache::lonmenu::setflags();          }
     my $maincall=&Apache::lonmenu::maincall();      }
     my $brcrum = [{'href' => '',      if (defined($form->{role})) {
                    'text' => 'Successful Login'},];          my $envkey = 'user.role.'.$form->{role};
     my $start_page=&Apache::loncommon::start_page('Successful Login',          my $now=time;
                                                   $startupremote,          my $then=$env{'user.login.time'};
                                                   {'no_inline_link' => 1,          my $refresh=$env{'user.refresh.time'};
                                                    'bread_crumbs' => $brcrum,});          my $update=$env{'user.update.time'};
     my $end_page  =&Apache::loncommon::end_page();          if (!$update) {
               $update = $then;
     my $continuelink;          }
     if ($env{'environment.remote'} eq 'off') {          if (exists($env{$envkey})) {
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
     }              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
 # ------------------------------------------------- Output for successful login                                           \$trolecode,\$tstatus,\$tstart,\$tend);
               if ($tstatus eq 'is') {
     &Apache::loncommon::content_type($r,'text/html');                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
     $r->header_out('Set-cookie' => $cookie);                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
     $r->send_http_header;                  $destination .= 'selectrole=1&'.$newrole.'=1';
               }
     my %lt=&Apache::lonlocal::texthash(          }
        'wel' => 'Welcome',      }
        'pro' => 'Login problems?',      if (defined($form->{symb})) {
        );          my $destsymb = $form->{symb};
     my $loginhelp = &loginhelpdisplay($domain);          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     if ($loginhelp) {          if ($destsymb =~ /___/) {
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';              # FIXME Need to deal with encrypted symbs and urls as needed.
     }              my ($map,$resid,$desturl)=split(/___/,$destsymb);
               $desturl = &Apache::lonnet::clutter($desturl);
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');               $desturl = &HTML::Entities::encode($desturl,'"<>&');
     $r->print(<<ENDSUCCESS);              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
 $start_page              $destination .= 'destinationurl='.$desturl.
 $setflags                              '&destsymb='.$destsymb;
 $windowinfo          } else {
 <h1>$lt{'wel'}</h1>              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
 $welcome              $destination .= 'destinationurl='.$destsymb;
 $loginhelp          }
 $remoteinfo      }
 $maincall      if ($destination =~ m{^/adm/roles}) {
 $continuelink          $destination  .= ($destination =~ /\?/) ? '&' : '?';
 $end_page          $destination .= 'source=login';
 ENDSUCCESS      }
     return;  
 }      my $windowname = 'loncapaclient';
       if ($env{'request.lti.login'}) {
 # --------------------------------------------------------------- Failed login!          $windowname .= 'lti';
       }
 sub failed {      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
     my ($r,$message,$form) = @_;      my $brcrum = [{'href' => '',
     (undef,undef,undef,my $clientmathml,my $clientunicode) =                     'text' => 'Successful Login'},];
         &Apache::loncommon::decode_user_agent();      my $args = {'bread_crumbs' => $brcrum,};
     my $args = {};      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     if ($clientunicode && !$clientmathml) {          my $update=$env{'user.update.time'};
         $args = {'browser.unicode' => 1};          if (!$update) {
     }              $update = $env{'user.login.time'};
           }
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);          my %roles_in_env;
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});          if ($showcount == 1) {
     if (&Apache::lonnet::domain($udom,'description') eq '') {              foreach my $rolecode (keys(%roles_in_env)) {
         undef($udom);                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
     }                  if ($cid) {
     my $retry = '/adm/login';                      my %coursedescription =
     if ($uname eq $form->{'uname'}) {                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
         $retry .= '?username='.$uname;                      if ($coursedescription{'type'} eq 'Placement') {
     }                          $args->{'crstype'} = 'Placement';
     if ($udom) {                      }
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;                      last;
     }                  }
     if (exists($form->{role})) {              }
         my $role = &Apache::loncommon::cleanup_html($form->{role});          }
         if ($role ne '') {      }
             $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;  
         }  # ------------------------------------------------- Output for successful login
     }  
     if (exists($form->{symb})) {      &Apache::loncommon::content_type($r,'text/html');
         my $symb = &Apache::loncommon::cleanup_html($form->{symb});      if ($securecookie) {
         if ($symb ne '') {          $r->headers_out->add('Set-cookie' => $securecookie);
             $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;      }
         }      if ($defaultcookie) {
     }          $r->headers_out->add('Set-cookie' => $defaultcookie);
     my $end_page = &Apache::loncommon::end_page();      }
     &Apache::loncommon::content_type($r,'text/html');      $r->send_http_header;
     $r->send_http_header;  
     my @actions =      my ($start_page,$js,$pagebody,$end_page);
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));      if ($env{'request.lti.login'}) {
     my $loginhelp = &loginhelpdisplay($udom);          $args = {'only_body' => 1};
     if ($loginhelp) {          if ($env{'request.lti.target'} eq '') {
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');              my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
     }                              'ltitarget=iframe';
     #FIXME: link to helpdesk might be added here              $js = <<"ENDJS";
   
     $r->print(  <script type="text/javascript">
        $start_page  // <![CDATA[
       .'<h2>'.&mt('Sorry ...').'</h2>'  function setLTItarget() {
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'      var newloc = '$destination';
       .&Apache::lonhtmlcommon::actionbox(\@actions)      if (parent !== window) {
       .$end_page          newloc += '$ltitarget';
     );      }
  }      window.location.href=newloc;
   }
 # ------------------------------------------------------------------ Rerouting!  // ]]>
   </script>
 sub reroute {  
     my ($r) = @_;  ENDJS
     &Apache::loncommon::content_type($r,'text/html');              $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
     $r->send_http_header;              $pagebody =  '<noscript><span class="LC_warning">'
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
            .&mt('Please [_1]log in again[_2].');                          .'</span></noscript>';
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});          } else {
 }              $args->{'redirect'} = [0,$destination,1];
           }
 # ---------------------------------------------------------------- Main handler          $start_page=&Apache::loncommon::start_page('',$js,$args);
       } else {
 sub handler {          $args->{'redirect'} = [0,$destination];
     my $r = shift;          $start_page=&Apache::loncommon::start_page('Successful Login',
     my $londocroot = $r->dir_config('lonDocRoot');                                                     $js,$args);
     my $form;  
 # Are we re-routing?          my %lt=&Apache::lonlocal::texthash(
     if (-e "$londocroot/lon-status/reroute.txt") {             'wel' => 'Welcome',
  &reroute($r);             'pro' => 'Login problems?',
  return OK;            );
     }          $pagebody = "<h1>$lt{'wel'}</h1>\n".
                       &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
     &Apache::lonlocal::get_language_handle($r);          my $loginhelp = &loginhelpdisplay($domain);
           if ($loginhelp) {
 # -------------------------------- Prevent users from attempting to login twice              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
     my $handle = &Apache::lonnet::check_for_valid_session($r);          }
     if ($handle ne '') {      }
         my $lonidsdir=$r->dir_config('lonIDsDir');      $end_page = &Apache::loncommon::end_page();
         if ($handle=~/^publicuser\_/) {      $r->print(<<ENDSUCCESS);
 # For "public user" - remove it, we apparently really want to login  $start_page
             unlink($r->dir_config('lonIDsDir')."/$handle.id");  $windowinfo
         } else {  $pagebody
 # Indeed, a valid token is found  $end_page
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);  ENDSUCCESS
     &Apache::loncommon::content_type($r,'text/html');      return;
     $r->send_http_header;  }
     my $start_page =   
         &Apache::loncommon::start_page('Already logged in');  # --------------------------------------------------------------- Failed login!
     my $end_page =   
         &Apache::loncommon::end_page();  sub failed {
             my $dest = '/adm/roles';      my ($r,$message,$form) = @_;
             if ($env{'form.firsturl'} ne '') {      (undef,undef,undef,my $clientmathml,my $clientunicode) =
                 $dest = $env{'form.firsturl'};          &Apache::loncommon::decode_user_agent();
             }      my $args = {};
             $r->print(      if ($clientunicode && !$clientmathml) {
                $start_page          $args = {'browser.unicode' => 1};
               .'<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 $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
               .'</p>'      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
               .$end_page      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
             );      if (&Apache::lonnet::domain($udom,'description') eq '') {
             return OK;          undef($udom);
         }      }
     }      my $retry = '/adm/login';
       if ($uname eq $form->{'uname'}) {
 # ---------------------------------------------------- No valid token, continue          $retry .= '?username='.$uname;
       }
       if ($udom) {
     my $buffer;          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
     if ($r->header_in('Content-length') > 0) {      }
  $r->read($buffer,$r->header_in('Content-length'),0);      if (exists($form->{role})) {
     }          my $role = &Apache::loncommon::cleanup_html($form->{role});
     my %form;          if ($role ne '') {
     foreach my $pair (split(/&/,$buffer)) {              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
        my ($name,$value) = split(/=/,$pair);          }
        $value =~ tr/+/ /;      }
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;      if (exists($form->{symb})) {
        $form{$name}=$value;          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
     }          if ($symb ne '') {
               $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {          }
  &failed($r,'Username, password and domain need to be specified.',      }
  \%form);      if (exists($form->{firsturl})) {
         return OK;          my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});
     }          if ($firsturl ne '') {
               $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;
 # split user logging in and "su"-user          }
       }
     ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});      my $end_page = &Apache::loncommon::end_page();
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});      &Apache::loncommon::content_type($r,'text/html');
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});      $r->send_http_header;
     $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});      my @actions =
            (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
     my $role   = $r->dir_config('lonRole');      my $loginhelp = &loginhelpdisplay($udom);
     my $domain = $r->dir_config('lonDefDomain');      if ($loginhelp) {
     my $prodir = $r->dir_config('lonUsersDir');          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
     my $contact_name = &mt('LON-CAPA helpdesk');      }
       #FIXME: link to helpdesk might be added here
 # ---------------------------------------- Get the information from login token  
       $r->print(
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},         $start_page
                                       $form{'serverid'});        .'<h2>'.&mt('Sorry ...').'</h2>'
         .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
     my %sessiondata;        .&Apache::lonhtmlcommon::actionbox(\@actions)
     if ($form{'iptoken'}) {        .$end_page
         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});      );
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});   }
     }  
   # ------------------------------------------------------------------ Rerouting!
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||   
         ($tmpinfo eq 'no_such_host')) {  sub reroute {
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);      my ($r) = @_;
         return OK;      &Apache::loncommon::content_type($r,'text/html');
     } else {      $r->send_http_header;
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
    $form{'serverid'});             .&mt('Please [_1]log in again[_2].');
         if ( $reply ne 'ok' ) {      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
             &failed($r,'Session could not be opened.',\%form);  }
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");  
     return OK;  # ---------------------------------------------------------------- Main handler
  }  
     }  sub handler {
       my $r = shift;
     if (!&Apache::lonnet::domain($form{'udom'})) {      my $londocroot = $r->dir_config('lonDocRoot');
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);  # Are we re-routing?
         return OK;      if (-e "$londocroot/lon-status/reroute.txt") {
     }   &reroute($r);
    return OK;
     my ($key,$firsturl,$rolestr,$symbstr)=split(/&/,$tmpinfo);      }
     if ($rolestr) {  
         $rolestr = &unescape($rolestr);      &Apache::lonlocal::get_language_handle($r);
     }  
     if ($symbstr) {  # -------------------------------- Prevent users from attempting to login twice
         $symbstr= &unescape($symbstr);      my $handle = &Apache::lonnet::check_for_valid_session($r);
     }      if ($handle ne '') {
     if ($rolestr =~ /^role=/) {          my $lonidsdir=$r->dir_config('lonIDsDir');
         (undef,$form{'role'}) = split('=',$rolestr);          if ($handle=~/^publicuser\_/) {
     }  # For "public user" - remove it, we apparently really want to login
     if ($symbstr =~ /^symb=/) {               unlink($r->dir_config('lonIDsDir')."/$handle.id");
         (undef,$form{'symb'}) = split('=',$symbstr);          } else {
     }  # Indeed, a valid token is found
               &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     my $keybin=pack("H16",$key);      &Apache::loncommon::content_type($r,'text/html');
       $r->send_http_header;
     my $cipher;      my $start_page =
     if ($Crypt::DES::VERSION>=2.03) {          &Apache::loncommon::start_page('Already logged in');
  $cipher=new Crypt::DES $keybin;      my $end_page =
     }          &Apache::loncommon::end_page();
     else {              my $dest = '/adm/roles';
  $cipher=new DES $keybin;              if ($env{'form.firsturl'} ne '') {
     }                  $dest = $env{'form.firsturl'};
     my $upass='';              }
     for (my $i=0;$i<=2;$i++) {              $r->print(
  my $chunk=                 $start_page
     $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},0,16))));                .'<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].'
  $chunk.=                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
     $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},16,16))));                .'</p>'
                 .$end_page
  $chunk=substr($chunk,1,ord(substr($chunk,0,1)));              );
  $upass.=$chunk;              return OK;
     }          }
       }
 # ---------------------------------------------------------------- Authenticate  
   # ---------------------------------------------------- No valid token, continue
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  
     my ($cancreate,$statustocreate) =  
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});      my $buffer;
     my $defaultauth;      if ($r->header_in('Content-length') > 0) {
     if (ref($cancreate) eq 'ARRAY') {   $r->read($buffer,$r->header_in('Content-length'),0);
         if (grep(/^login$/,@{$cancreate})) {      }
             $defaultauth = 1;      my %form;
         }      foreach my $pair (split(/&/,$buffer)) {
     }         my ($name,$value) = split(/=/,$pair);
     my $clientcancheckhost = 1;         $value =~ tr/+/ /;
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                                               $form{'udom'},$defaultauth,         $form{$name}=$value;
                                               $clientcancheckhost);      }
       
 # --------------------------------------------------------------------- Failed?      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
    &failed($r,'Username, password and domain need to be specified.',
     if ($authhost eq 'no_host') {   \%form);
  &failed($r,'Username and/or password could not be authenticated.',          return OK;
  \%form);      }
         return OK;  
     } elsif ($authhost eq 'no_account_on_host') {  # split user logging in and "su"-user
         if ($defaultauth) {  
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
                 return OK;      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
             }      $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
             my $start_page =       $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',  
                                                '',{'no_inline_link'   => 1,});      my $role   = $r->dir_config('lonRole');
             my $lonhost = $r->dir_config('lonHostID');      my $domain = $r->dir_config('lonDefDomain');
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      my $prodir = $r->dir_config('lonUsersDir');
             my $contacts =       my $contact_name = &mt('LON-CAPA helpdesk');
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',  
                                                         $form{'udom'},$origmail);  # ---------------------------------------- Get the information from login token
             my ($contact_email) = split(',',$contacts);   
             my $output =       my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},                                        $form{'serverid'});
                                                        $domdesc,'',$lonhost,  
                                                        $contact_email,$contact_name,      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
                                                        undef,$statustocreate);          ($tmpinfo eq 'no_such_host')) {
             &Apache::loncommon::content_type($r,'text/html');   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
             $r->send_http_header;          return OK;
             &Apache::createaccount::print_header($r,$start_page);      } else {
             $r->print('<h3>'.&mt('Account creation').'</h3>'.   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.     $form{'serverid'});
                       $output.&Apache::loncommon::end_page());          if ( $reply ne 'ok' ) {
             return OK;              &failed($r,'Session could not be opened.',\%form);
         } else {      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
             &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;
             return OK;   }
         }      }
     }  
       if (!&Apache::lonnet::domain($form{'udom'})) {
     if (($firsturl eq '') ||           &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
  ($firsturl=~/^\/adm\/(logout|remote)/)) {          return OK;
  $firsturl='/adm/roles';      }
     }  
       my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
     my $hosthere;      if ($rolestr) {
     if ($form{'iptoken'}) {          $rolestr = &unescape($rolestr);
         if (($sessiondata{'domain'} eq $form{'udom'}) &&      }
             ($sessiondata{'username'} eq $form{'uname'})) {      if ($symbstr) {
             $hosthere = 1;          $symbstr= &unescape($symbstr);
         }      }
     }      if ($iptokenstr) {
           $iptokenstr = &unescape($iptokenstr);
 # --------------------------------- Are we attempting to login as somebody else?      }
     if ($form{'suname'}) {      if ($firsturl =~ m{^/tiny/$match_domain/\w+$}) {
 # ------------ see if the original user has enough privileges to pull this stunt          $form{'firsturl'} = $firsturl;
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {      }
 # ---------------------------------------------------- see if the su-user exists      if ($rolestr =~ /^role=/) {
     unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})          (undef,$form{'role'}) = split('=',$rolestr);
  eq 'no_host') {      }
  &Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));      if ($symbstr =~ /^symb=/) {
 # ------------------------------ see if the su-user is not too highly privileged          (undef,$form{'symb'}) = split('=',$symbstr);
  unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {      }
 # -------------------------------------------------------- actually switch users      if ($iptokenstr =~ /^iptoken=/) {
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
  ' logging in as '.$form{'suname'});      }
     $form{'uname'}=$form{'suname'};  
  } else {      my $upass = $ENV{HTTPS} ? $form{'upass0'}
     &Apache::lonnet::logthis('Attempted switch user to privileged user');          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
  }  
     }  # ---------------------------------------------------------------- Authenticate
  } else {  
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
  }      my ($cancreate,$statustocreate) =
     }          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
       my $defaultauth;
     my ($is_balancer,$otherserver);      if (ref($cancreate) eq 'ARRAY') {
           if (grep(/^login$/,@{$cancreate})) {
     unless ($hosthere) {              $defaultauth = 1;
         ($is_balancer,$otherserver) =          }
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'});      }
     }      my $clientcancheckhost = 1;
       my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
     if ($is_balancer) {                                                $form{'udom'},$defaultauth,
         if (!$otherserver) {                                                 $clientcancheckhost);
             ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});  
         }  # --------------------------------------------------------------------- Failed?
         if ($otherserver) {  
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,      if ($authhost eq 'no_host') {
                      \%form);   &failed($r,'Username and/or password could not be authenticated.',
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;   \%form);
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {          return OK;
                 $switchto .= '&origurl='.$firsturl;      } elsif ($authhost eq 'no_account_on_host') {
             }          if ($defaultauth) {
             if ($form{'role'}) {              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
                 $switchto .= '&role='.$form{'role'};              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
             }                  return OK;
             if ($form{'symb'}) {              }
                 $switchto .= '&symb='.$form{'symb'};              my $start_page =
             }                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
             $r->internal_redirect($switchto);              my $lonhost = $r->dir_config('lonHostID');
         } else {              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
             $r->print(&noswitch());              my $contacts =
         }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
         return OK;                                                          $form{'udom'},$origmail);
     } else {              my ($contact_email) = split(',',$contacts);
         if (!&check_can_host($r,\%form,$authhost)) {              my $output =
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
             if ($otherserver) {                                                         $domdesc,'',$lonhost,
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                                                         $contact_email,$contact_name,
                          \%form);                                                         undef,$statustocreate);
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;              &Apache::loncommon::content_type($r,'text/html');
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {              $r->send_http_header;
                     $switchto .= '&origurl='.$firsturl;              &Apache::createaccount::print_header($r,$start_page);
                 }              $r->print('<h3>'.&mt('Account creation').'</h3>'.
                 if ($form{'role'}) {                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
                     $switchto .= '&role='.$form{'role'};                        $output.&Apache::loncommon::end_page());
                 }              return OK;
                 if ($form{'symb'}) {          } else {
                     $switchto .= '&symb='.$form{'symb'};              &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;
                 $r->internal_redirect($switchto);          }
             } else {      }
                 $r->print(&noswitch());  
             }      if (($firsturl eq '') ||
             return OK;   ($firsturl=~/^\/adm\/(logout|remote)/)) {
         }   $firsturl='/adm/roles';
       }
 # ------------------------------------------------------- Do the load balancing  
       my $hosthere;
 # ---------------------------------------------------------- Determine own load      if ($form{'iptoken'}) {
         my $loadlim = $r->dir_config('lonLoadLim');          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
         my $loadavg;          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
         {          if (($sessiondata{'domain'} eq $form{'udom'}) &&
             my $loadfile=Apache::File->new('/proc/loadavg');              ($sessiondata{'username'} eq $form{'uname'})) {
             $loadavg=<$loadfile>;              $hosthere = 1;
         }          }
         $loadavg =~ s/\s.*//g;      }
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);  
         my $userloadpercent=&Apache::lonnet::userload();  # --------------------------------- Are we attempting to login as somebody else?
       if ($form{'suname'}) {
 # ---------------------------------------------------------- Are we overloaded?          my ($suname,$sudom,$sudomref);
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {          $suname = $form{'suname'};
             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});          $sudom = $form{'udom'};
             if (!$unloaded) {          if ($form{'sudom'}) {
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});              unless ($sudom eq $form{'sudom'}) {
             }                  if (&Apache::lonnet::domain($form{'sudom'})) {
             if ($unloaded) {                      $sudomref = [$form{'sudom'}];
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',                      $sudom = $form{'sudom'};
                          undef,\%form);                  }
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);              }
                 return OK;          }
             }  # ------------ see if the original user has enough privileges to pull this stunt
         }   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,  # ---------------------------------------------------- see if the su-user exists
                  \%form);      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
         return OK;  # ------------------------------ see if the su-user is not too highly privileged
     }   if (&Apache::lonnet::privileged($suname,$sudom)) {
 }                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
                   } else {
 sub check_can_host {                      my $noprivswitch;
     my ($r,$form,$authhost,$domdesc) = @_;  #
     return unless (ref($form) eq 'HASH');  # su-user's home server and user's home server must have one of:
     my $canhost = 1;  # (a) same domain
     my $lonhost = $r->dir_config('lonHostID');  # (b) same primary library server for the two domains
     my $udom = $form->{'udom'};  # (c) same "internet domain" for primary library server(s) for home servers' domains
     my @intdoms;  #
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
     if (ref($internet_names) eq 'ARRAY') {                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
         @intdoms = @{$internet_names};                      unless ($sudom eq $form{'udom'}) {
     }                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);                          unless ($suprim eq $uprim) {
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {                              unless ($suintdom eq $uintdom) {
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);                                  &Apache::lonnet::logthis('Attempted switch user '
         my $hostname = &Apache::lonnet::hostname($lonhost);                                     .'to user with different "internet domain".');                        
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);                                  $noprivswitch = 1;
         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') {                      unless ($noprivswitch) {
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);  #
         } else {  # server where log-in occurs must have same "internet domain" as su-user's home
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);  # server
         }  #
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,                          my $lonhost = $r->dir_config('lonHostID');
                                                      $udomdefaults{'remotesessions'},                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
                                                      $defdomdefaults{'hostedsessions'});                          if ($hostintdom ne $suintdom) {
     }                              &Apache::lonnet::logthis('Attempted switch user on a '
     unless ($canhost) {                                  .'server with a different "internet domain".');
         if ($authhost eq 'no_account_on_host') {                          } else {
             my $checkloginvia = 1;  
             my ($login_host,$hostname) =   # -------------------------------------------------------- actually switch users
                 &Apache::lonnet::choose_server($udom,$checkloginvia);  
             &Apache::loncommon::content_type($r,'text/html');              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
             $r->send_http_header;                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
             if ($login_host ne '') {              $form{'uname'}=$suname;
                 my $protocol = $Apache::lonnet::protocol{$login_host};                              if ($form{'udom'} ne $sudom) {
                 $protocol = 'http' if ($protocol ne 'https');                                  $form{'udom'}=$sudom;
                 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>').   } else {
                           &Apache::loncommon::end_page());      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
             } 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 />'.      my ($is_balancer,$otherserver);
                           '<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());      unless ($hosthere) {
             }          ($is_balancer,$otherserver) =
         } else {              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,          if ($is_balancer) {
                      $form);              if ($otherserver eq '') {
             my ($otherserver) = &Apache::lonnet::choose_server($udom);                  my $lowest_load;
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
         }                  if ($lowest_load > 100) {
     }                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
     return $canhost;                  }
 }              }
               if ($otherserver ne '') {
 sub noswitch {                  my @hosts = &Apache::lonnet::current_machine_ids();
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
                  '<h3>'.&mt('Session unavailable').'</h3>'.                      $hosthere = $otherserver;
                  &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;      }
 }  
       if (($is_balancer) && (!$hosthere)) {
 sub loginhelpdisplay {          if ($otherserver) {
     my ($authdomain) = @_;              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
     my $login_help = 1;                       \%form);
     my $lang = &Apache::lonlocal::current_language();              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
     if ($login_help) {              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
         my $dom = $authdomain;                  $switchto .= '&origurl='.$firsturl;
         if ($dom eq '') {              }
             $dom = &Apache::lonnet::default_login_domain();              if ($form{'role'}) {
         }                  $switchto .= '&role='.$form{'role'};
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);              }
         my $loginhelp_url;              if ($form{'symb'}) {
         if ($lang) {                  $switchto .= '&symb='.$form{'symb'};
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};              }
             if ($loginhelp_url ne '') {              $r->internal_redirect($switchto);
                 return $loginhelp_url;          } else {
             }              $r->print(&noswitch());
         }          }
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};          return OK;
         if ($loginhelp_url ne '') {      } else {
             return $loginhelp_url;          if (!&check_can_host($r,\%form,$authhost)) {
         } else {              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
             return '/adm/loginproblems.html';              if ($otherserver) {
         }                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
     }                           \%form);
     return;                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
 }                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                       $switchto .= '&origurl='.$firsturl;
 1;                  }
 __END__                  if ($form{'role'}) {
                       $switchto .= '&role='.$form{'role'};
                   }
                   if ($form{'symb'}) {
                       $switchto .= '&symb='.$form{'symb'};
                   }
                   $r->internal_redirect($switchto);
               } else {
                   $r->print(&noswitch());
               }
               return OK;
           }
   
   # ------------------------------------------------------- Do the load balancing
   
   # ---------------------------------------------------------- Determine own load
           my $loadlim = $r->dir_config('lonLoadLim');
           my $loadavg;
           {
               my $loadfile=Apache::File->new('/proc/loadavg');
               $loadavg=<$loadfile>;
           }
           $loadavg =~ s/\s.*//g;
           my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
           my $userloadpercent=&Apache::lonnet::userload();
   
   # ---------------------------------------------------------- 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'});
               }
               if ($unloaded) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                            undef,\%form);
                   $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                   return OK;
               }
           }
           if (($is_balancer) && ($hosthere)) {
               $form{'noloadbalance'} = $hosthere;
           }
           &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
                    \%form);
           return OK;
       }
   }
   
   sub check_can_host {
       my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
       my $canhost = 1;
       my $lonhost = $r->dir_config('lonHostID');
       my $udom = $form->{'udom'};
       my @intdoms;
       my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
       if (ref($internet_names) eq 'ARRAY') {
           @intdoms = @{$internet_names};
       }
       my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
       my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
       unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
           my $machine_dom = &Apache::lonnet::host_domain($lonhost);
           my $hostname = &Apache::lonnet::hostname($lonhost);
           my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
           my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
           my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
           my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
           my $loncaparev;
           if ($authhost eq 'no_account_on_host') {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
           } else {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
           }
           $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                                                        $udomdefaults{'remotesessions'},
                                                        $defdomdefaults{'hostedsessions'});
       }
       unless ($canhost) {
           if ($authhost eq 'no_account_on_host') {
               my $checkloginvia = 1;
               my ($login_host,$hostname) =
                   &Apache::lonnet::choose_server($udom,$checkloginvia);
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               if ($login_host ne '') {
                   my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
                   $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                             '<h3>'.&mt('Account creation').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                             '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                             &Apache::loncommon::end_page());
               } else {
                   $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                             '<h3>'.&mt('Account creation unavailable').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.
                             &Apache::loncommon::end_page());
               }
           } else {
               &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                        $form);
               my ($otherserver) = &Apache::lonnet::choose_server($udom);
               $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
           }
       }
       return $canhost;
   }
   
   sub noswitch {
       my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    '<h3>'.&mt('Session unavailable').'</h3>'.
                    &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                    '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                    &Apache::loncommon::end_page();
       return $result;
   }
   
   sub loginhelpdisplay {
       my ($authdomain) = @_;
       my $login_help = 1;
       my $lang = &Apache::lonlocal::current_language();
       if ($login_help) {
           my $dom = $authdomain;
           if ($dom eq '') {
               $dom = &Apache::lonnet::default_login_domain();
           }
           my %domconfhash = &Apache::loncommon::get_domainconf($dom);
           my $loginhelp_url;
           if ($lang) {
               $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
               if ($loginhelp_url ne '') {
                   return $loginhelp_url;
               }
           }
           $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
           if ($loginhelp_url ne '') {
               return $loginhelp_url;
           } else {
               return '/adm/loginproblems.html';
           }
       }
       return;
   }
   
   1;
   __END__
   
   

Removed from v.1.121.2.11  
changed lines
  Added in v.1.155


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