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

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


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