Diff for /loncom/auth/lonauth.pm between versions 1.121.2.23 and 1.153

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


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