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

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


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