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

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

Removed from v.1.121.2.18  
changed lines
  Added in v.1.159


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