Diff for /loncom/auth/lonauth.pm between versions 1.121.2.17 and 1.159

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


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