Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.2 and 1.143

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


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