Diff for /loncom/auth/lonauth.pm between versions 1.121.2.22 and 1.151

version 1.121.2.22, 2021/12/12 01:48:40 version 1.151, 2018/04/21 21:29:31
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # User Authentication Module  # User Authentication Module
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonauth;  package Apache::lonauth;
   
 use strict;  use strict;
 use LONCAPA;  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::lonmenu();  use Apache::lonmenu();
 use Apache::createaccount;  use Apache::createaccount;
 use Fcntl qw(:flock);  use Apache::ltiauth;
 use Apache::lonlocal;  use Fcntl qw(:flock);
 use Apache::File();  use Apache::lonlocal;
 use HTML::Entities;  use Apache::File();
 use Digest::MD5;  use HTML::Entities;
    use Digest::MD5;
 # ------------------------------------------------------------ Successful login   
 sub success {  # ------------------------------------------------------------ Successful login
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,  sub success {
  $form,$cid,$expirepub) = @_;      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
    $form,$skipcritical) = @_;
 # ------------------------------------------------------------ Get cookie ready  
     my $cookie =  # ------------------------------------------------------------ Get cookie ready
  &Apache::loncommon::init_user_environment($r, $username, $domain,      my $cookie =
   $authhost, $form,   &Apache::loncommon::init_user_environment($r, $username, $domain,
   {'extra_env' => $extra_env,});    $authhost, $form,
     {'extra_env' => $extra_env,});
     my $public=($username eq 'public' && $domain eq 'public');  
       my $public=($username eq 'public' && $domain eq 'public');
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }  
       if ($public or $lowerurl eq 'noredirect') { return $cookie; }
 # -------------------------------------------------------------------- Log this  
   # -------------------------------------------------------------------- Log this
     my $ip = &Apache::lonnet::get_requestor_ip();  
     &Apache::lonnet::log($domain,$username,$authhost,      &Apache::lonnet::log($domain,$username,$authhost,
                          "Login $ip");                           "Login $ENV{'REMOTE_ADDR'}");
   
 # ------------------------------------------------- Check for critical messages  # ------------------------------------------------- Check for critical messages
   
     my @what=&Apache::lonnet::dump('critical',$domain,$username);      unless ($skipcritical) {
     if ($what[0]) {          my @what=&Apache::lonnet::dump('critical',$domain,$username);
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {          if ($what[0]) {
     $lowerurl='/adm/email?critical=display';      if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
         }          $lowerurl='/adm/email?critical=display';
     }              }
           }
 # ------------------------------------------------------------ Get cookies ready      }
     my ($securecookie,$defaultcookie);  
     my $ssl = $r->subprocess_env('https');  # ----------------------------------------------------------- Get cookies ready
     if ($ssl) {      my ($securecookie,$defaultcookie);
         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";      if ($ENV{'SERVER_PORT'} == 443) {
         my $lonidsdir=$r->dir_config('lonIDsDir');          $securecookie="lonID=$cookie; path=/; HttpOnly; secure";
         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {          my $lonidsdir=$r->dir_config('lonIDsDir');
             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
             if (-e "$lonidsdir/$linkname.id") {              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
                 unlink("$lonidsdir/$linkname.id");              if (-e "$lonidsdir/$linkname.id") {
             }                  unlink("$lonidsdir/$linkname.id");
             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",              }
                                               "$lonidsdir/$linkname.id"); 1 };              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
             if ($made_symlink) {                                                "$lonidsdir/$linkname.id"); 1 };
                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";              if ($made_symlink) {
                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
             }                  &Apache::lonnet::appenv({'user.linkedenv' => "$lonidsdir/$linkname.id"});
         }              }
     } else {          }
         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";      } else {
     }          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
 # -------------------------------------------------------- Menu script and info      }
     my $destination = $lowerurl;  # -------------------------------------------------------- Menu script and info
       my $destination = $lowerurl;
     if (defined($form->{role})) {      if ($env{'request.lti.login'}) {
         my $envkey = 'user.role.'.$form->{role};          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         my $now=time;              &Apache::loncommon::content_type($r,'text/html');
         my $then=$env{'user.login.time'};              if ($securecookie) {
         my $refresh=$env{'user.refresh.time'};                  $r->headers_out->add('Set-cookie' => $securecookie);
         my $update=$env{'user.update.time'};              }
         if (!$update) {              if ($defaultcookie) {
             $update = $then;                  $r->headers_out->add('Set-cookie' => $defaultcookie);
         }              }
         if (exists($env{$envkey})) {              $r->send_http_header;
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,              return;
                                          \$trolecode,\$tstatus,\$tstart,\$tend);          }
             if ($tstatus eq 'is') {          if ($env{'request.lti.selfenrollrole'}) {
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';              if (&Apache::ltiauth::lti_enroll($username,$domain,
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
                 $destination .= 'selectrole=1&'.$newrole.'=1';                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
             }                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
         }              } else {
     }                  &Apache::ltiauth::invalid_request($r,24);
     if (defined($form->{symb})) {              }
         my $destsymb = $form->{symb};          }
         my $encrypted;      }
         if ($destsymb =~ m{^/enc/}) {      if (defined($form->{role})) {
             $encrypted = 1;          my $envkey = 'user.role.'.$form->{role};
             if ($cid) {          my $now=time;
                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);          my $then=$env{'user.login.time'};
             }          my $refresh=$env{'user.refresh.time'};
         }          my $update=$env{'user.update.time'};
         $destination  .= ($destination =~ /\?/) ? '&' : '?';          if (!$update) {
         if ($destsymb =~ /___/) {              $update = $then;
             my ($map,$resid,$desturl)=split(/___/,$destsymb);          }
             $desturl = &Apache::lonnet::clutter($desturl);          if (exists($env{$envkey})) {
             if ($encrypted) {              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
                 $destsymb = $form->{symb};                                           \$trolecode,\$tstatus,\$tstart,\$tend);
             }              if ($tstatus eq 'is') {
             $desturl = &HTML::Entities::encode($desturl,'"<>&');                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
             $destination .= 'destinationurl='.$desturl.                  $destination .= 'selectrole=1&'.$newrole.'=1';
                             '&destsymb='.$destsymb;              }
         } elsif (!$encrypted) {          }
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');      }
             $destination .= 'destinationurl='.$destsymb;      if (defined($form->{symb})) {
         }          my $destsymb = $form->{symb};
     }          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     if ($destination =~ m{^/adm/roles}) {          if ($destsymb =~ /___/) {
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              # FIXME Need to deal with encrypted symbs and urls as needed.
         $destination .= 'source=login';              my ($map,$resid,$desturl)=split(/___/,$destsymb);
     }              $desturl = &Apache::lonnet::clutter($desturl);
               $desturl = &HTML::Entities::encode($desturl,'"<>&');
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     my $startupremote=&Apache::lonmenu::startupremote($destination);              $destination .= 'destinationurl='.$desturl.
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);                              '&destsymb='.$destsymb;
     my $setflags=&Apache::lonmenu::setflags();          } else {
     my $maincall=&Apache::lonmenu::maincall();              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     my $brcrum = [{'href' => '',              $destination .= 'destinationurl='.$destsymb;
                    'text' => 'Successful Login'},];          }
     my $start_page=&Apache::loncommon::start_page('Successful Login',      }
                                                   $startupremote,      if ($destination =~ m{^/adm/roles}) {
                                                   {'no_inline_link' => 1,          $destination  .= ($destination =~ /\?/) ? '&' : '?';
                                                    'bread_crumbs' => $brcrum,});          $destination .= 'source=login';
     my $end_page  =&Apache::loncommon::end_page();      }
   
     my $continuelink;      my $windowname = 'loncapaclient';
     if ($env{'environment.remote'} eq 'off') {      if ($env{'request.lti.login'}) {
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';          $windowname .= 'lti';
     }      }
 # ------------------------------------------------- Output for successful login      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
       my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
     &Apache::loncommon::content_type($r,'text/html');      my $brcrum = [{'href' => '',
     if ($securecookie) {                     'text' => 'Successful Login'},];
         $r->headers_out->add('Set-cookie' => $securecookie);      my $args = {'bread_crumbs' => $brcrum,};
     }      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     if ($defaultcookie) {          my $update=$env{'user.update.time'};
         $r->headers_out->add('Set-cookie' => $defaultcookie);          if (!$update) {
     }              $update = $env{'user.login.time'};
     if ($expirepub) {          }
         my $c = new CGI::Cookie(-name    => 'lonPubID',          my %roles_in_env;
                                 -value   => '',          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
                                 -expires => '-10y',);          if ($showcount == 1) {
         $r->headers_out->add('Set-cookie' => $c);              foreach my $rolecode (keys(%roles_in_env)) {
     }                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
     $r->send_http_header;                  if ($cid) {
                       my %coursedescription =
     my %lt=&Apache::lonlocal::texthash(                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
        'wel' => 'Welcome',                      if ($coursedescription{'type'} eq 'Placement') {
        'pro' => 'Login problems?',                          $args->{'crstype'} = 'Placement';
        );                      }
     my $loginhelp = &loginhelpdisplay($domain);                      last;
     if ($loginhelp) {                  }
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';              }
     }          }
       }
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');   
     $r->print(<<ENDSUCCESS);  # ------------------------------------------------- Output for successful login
 $start_page  
 $setflags      &Apache::loncommon::content_type($r,'text/html');
 $windowinfo      if ($securecookie) {
 <h1>$lt{'wel'}</h1>          $r->headers_out->add('Set-cookie' => $securecookie);
 $welcome      }
 $loginhelp      if ($defaultcookie) {
 $remoteinfo          $r->headers_out->add('Set-cookie' => $defaultcookie);
 $maincall      }
 $continuelink      $r->send_http_header;
 $end_page  
 ENDSUCCESS      my $start_page;
     return;      if ($env{'request.lti.login'}) {
 }          $args = {'only_body' => 1,};
           $start_page=&Apache::loncommon::start_page('',$header,$args);
 # --------------------------------------------------------------- Failed login!      } else {
           $start_page=&Apache::loncommon::start_page('Successful Login',
 sub failed {                                                     $header,$args);
     my ($r,$message,$form,$authhost) = @_;      }
     (undef,undef,undef,my $clientmathml,my $clientunicode) =      my $end_page  =&Apache::loncommon::end_page();
         &Apache::loncommon::decode_user_agent();  
     my $args = {};      my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
     if ($clientunicode && !$clientmathml) {  
         $args = {'browser.unicode' => 1};      my $pagebody;
     }      unless ($env{'request.lti.login'}) {
           my %lt=&Apache::lonlocal::texthash(
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);             'wel' => 'Welcome',
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});             'pro' => 'Login problems?',
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});            );
     if (&Apache::lonnet::domain($udom,'description') eq '') {          $pagebody = "<h1>$lt{'wel'}</h1>\n".
         undef($udom);                      &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
     }          my $loginhelp = &loginhelpdisplay($domain);
     my $retry = '/adm/login';          if ($loginhelp) {
     if ($uname eq $form->{'uname'}) {              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
         $retry .= '?username='.$uname;          }
     }      }
     if ($udom) {      $r->print(<<ENDSUCCESS);
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;  $start_page
     }  $windowinfo
     my $lonhost = $r->dir_config('lonHostID');  $pagebody
     my $querystr;  $continuelink
     my $result = &set_retry_token($form,$lonhost,\$querystr);  $end_page
     if ($result eq 'fail') {  ENDSUCCESS
         if (exists($form->{role})) {      return;
             my $role = &Apache::loncommon::cleanup_html($form->{role});  }
             if ($role ne '') {  
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;  # --------------------------------------------------------------- Failed login!
             }  
         }  sub failed {
         if (exists($form->{symb})) {      my ($r,$message,$form) = @_;
             my $symb = &Apache::loncommon::cleanup_html($form->{symb});      (undef,undef,undef,my $clientmathml,my $clientunicode) =
             if ($symb ne '') {          &Apache::loncommon::decode_user_agent();
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;      my $args = {};
             }      if ($clientunicode && !$clientmathml) {
         }          $args = {'browser.unicode' => 1};
         if (exists($form->{firsturl})) {      }
             my $firsturl = &Apache::loncommon::cleanup_html($form->{firsturl});  
             if ($firsturl ne '') {      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
                 $retry .= (($retry=~/\?/)?'&amp;':'?').'firsturl='.$firsturl;      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
                 if ($form->{firsturl} =~ m{^/tiny/$match_domain/\w+$}) {      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
                     unless (exists($form->{linkprot})) {      if (&Apache::lonnet::domain($udom,'description') eq '') {
                         if (exists($form->{linkkey})) {          undef($udom);
                             $retry .= 'linkkey='.$form->{linkkey};      }
                         }      my $retry = '/adm/login';
                     }      if ($uname eq $form->{'uname'}) {
                 }          $retry .= '?username='.$uname;
             }      }
         }      if ($udom) {
     } elsif ($querystr ne '') {          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
         $retry .= (($retry=~/\?/)?'&amp;':'?').$querystr;      }
     }      if (exists($form->{role})) {
     my $end_page = &Apache::loncommon::end_page();          my $role = &Apache::loncommon::cleanup_html($form->{role});
     &Apache::loncommon::content_type($r,'text/html');          if ($role ne '') {
     $r->send_http_header;              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
     my @actions =          }
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));      }
     my $loginhelp = &loginhelpdisplay($udom);      if (exists($form->{symb})) {
     if ($loginhelp) {          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');          if ($symb ne '') {
     }              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
     #FIXME: link to helpdesk might be added here          }
       }
     $r->print(      my $end_page = &Apache::loncommon::end_page();
        $start_page      &Apache::loncommon::content_type($r,'text/html');
       .'<h2>'.&mt('Sorry ...').'</h2>'      $r->send_http_header;
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'      my @actions =
       .&Apache::lonhtmlcommon::actionbox(\@actions)           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
       .$end_page      my $loginhelp = &loginhelpdisplay($udom);
     );      if ($loginhelp) {
  }          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
       }
 # ------------------------------------------------------------------ Rerouting!      #FIXME: link to helpdesk might be added here
   
 sub reroute {      $r->print(
     my ($r) = @_;         $start_page
     &Apache::loncommon::content_type($r,'text/html');        .'<h2>'.&mt('Sorry ...').'</h2>'
     $r->send_http_header;        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'        .&Apache::lonhtmlcommon::actionbox(\@actions)
            .&mt('Please [_1]log in again[_2].');        .$end_page
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});      );
 }   }
   
 # ---------------------------------------------------------------- Main handler  # ------------------------------------------------------------------ Rerouting!
   
 sub handler {  sub reroute {
     my $r = shift;      my ($r) = @_;
     my $londocroot = $r->dir_config('lonDocRoot');      &Apache::loncommon::content_type($r,'text/html');
 # Are we re-routing?      $r->send_http_header;
     if (-e "$londocroot/lon-status/reroute.txt") {      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
  &reroute($r);             .&mt('Please [_1]log in again[_2].');
  return OK;      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
     }  }
   
     &Apache::lonlocal::get_language_handle($r);  # ---------------------------------------------------------------- Main handler
   
 # -------------------------------- Prevent users from attempting to login twice  sub handler {
     my $handle = &Apache::lonnet::check_for_valid_session($r);      my $r = shift;
     if ($handle ne '') {      my $londocroot = $r->dir_config('lonDocRoot');
         my $lonidsdir=$r->dir_config('lonIDsDir');  # Are we re-routing?
         if ($handle=~/^publicuser\_/) {      if (-e "$londocroot/lon-status/reroute.txt") {
 # For "public user" - remove it, we apparently really want to login   &reroute($r);
             unlink($r->dir_config('lonIDsDir')."/$handle.id");   return OK;
         } else {      }
 # Indeed, a valid token is found  
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);      &Apache::lonlocal::get_language_handle($r);
     &Apache::loncommon::content_type($r,'text/html');  
     $r->send_http_header;  # -------------------------------- Prevent users from attempting to login twice
     my $start_page =       my $handle = &Apache::lonnet::check_for_valid_session($r);
         &Apache::loncommon::start_page('Already logged in');      if ($handle ne '') {
     my $end_page =           my $lonidsdir=$r->dir_config('lonIDsDir');
         &Apache::loncommon::end_page();          if ($handle=~/^publicuser\_/) {
             my $dest = '/adm/roles';  # For "public user" - remove it, we apparently really want to login
             my %form = &get_form_items($r);              unlink($r->dir_config('lonIDsDir')."/$handle.id");
             if ($form{'logtoken'}) {          } else {
                 my $tmpinfo = &Apache::lonnet::reply('tmpget:'.$form{'logtoken'},  # Indeed, a valid token is found
                                                      $form{'serverid'});              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||      &Apache::loncommon::content_type($r,'text/html');
                         ($tmpinfo eq 'no_such_host')) {      $r->send_http_header;
                     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo)l      my $start_page =
                     $firsturl = &unescape($firsturl);          &Apache::loncommon::start_page('Already logged in');
                     my %info;      my $end_page =
                     foreach my $item (@rest) {          &Apache::loncommon::end_page();
                         my ($key,$value) = split(/=/,$item);              my $dest = '/adm/roles';
                         $info{$key} = &unescape($value);              if ($env{'form.firsturl'} ne '') {
                     }                  $dest = $env{'form.firsturl'};
                     if ($firsturl ne '') {              }
                         $info{'firsturl'} = $firsturl;              $r->print(
                         $dest = $firsturl;                 $start_page
                     }                .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
                 }                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
             }                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
             $r->print(                .'</p>'
                $start_page                .$end_page
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'              );
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'              return OK;
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')          }
               .'</p>'      }
               .$end_page  
             );  # ---------------------------------------------------- No valid token, continue
             return OK;  
         }  
     }      my $buffer;
       if ($r->header_in('Content-length') > 0) {
 # ---------------------------------------------------- No valid token, continue   $r->read($buffer,$r->header_in('Content-length'),0);
       }
     my %form = &get_form_items($r);      my %form;
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {      foreach my $pair (split(/&/,$buffer)) {
  &failed($r,'Username, password and domain need to be specified.',         my ($name,$value) = split(/=/,$pair);
  \%form);         $value =~ tr/+/ /;
         return OK;         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
     }         $form{$name}=$value;
       }
 # split user logging in and "su"-user  
       if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});   &failed($r,'Username, password and domain need to be specified.',
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});   \%form);
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});          return OK;
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});      }
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});  
   # split user logging in and "su"-user
     my $role   = $r->dir_config('lonRole');  
     my $domain = $r->dir_config('lonDefDomain');      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
     my $prodir = $r->dir_config('lonUsersDir');      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
     my $contact_name = &mt('LON-CAPA helpdesk');      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
       $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
 # ---------------------------------------- Get the information from login token      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
   
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},      my $role   = $r->dir_config('lonRole');
                                       $form{'serverid'});      my $domain = $r->dir_config('lonDefDomain');
       my $prodir = $r->dir_config('lonUsersDir');
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||       my $contact_name = &mt('LON-CAPA helpdesk');
         ($tmpinfo eq 'no_such_host')) {  
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);  # ---------------------------------------- Get the information from login token
         return OK;  
     } else {      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},                                        $form{'serverid'});
    $form{'serverid'});  
         if ( $reply ne 'ok' ) {      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
             &failed($r,'Session could not be opened.',\%form);          ($tmpinfo eq 'no_such_host')) {
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
     return OK;          return OK;
  }      } else {
     }   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
      $form{'serverid'});
     if (!&Apache::lonnet::domain($form{'udom'})) {          if ( $reply ne 'ok' ) {
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);              &failed($r,'Session could not be opened.',\%form);
         return OK;      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
     }      return OK;
    }
     my ($des_key,$firsturl,@rest)=split(/&/,$tmpinfo);      }
     $firsturl = &unescape($firsturl);  
     foreach my $item (@rest) {      if (!&Apache::lonnet::domain($form{'udom'})) {
         my ($key,$value) = split(/=/,$item);          &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
         $form{$key} = &unescape($value);          return OK;
     }      }
     my $upass = &Apache::loncommon::des_decrypt($key,$form{'upass0'});  
       my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
 # ---------------------------------------------------------------- Authenticate      if ($rolestr) {
           $rolestr = &unescape($rolestr);
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});      }
     my ($cancreate,$statustocreate) =      if ($symbstr) {
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});          $symbstr= &unescape($symbstr);
     my $defaultauth;      }
     if (ref($cancreate) eq 'ARRAY') {      if ($iptokenstr) {
         if (grep(/^login$/,@{$cancreate})) {          $iptokenstr = &unescape($iptokenstr);
             $defaultauth = 1;      }
         }      if ($rolestr =~ /^role=/) {
     }          (undef,$form{'role'}) = split('=',$rolestr);
     my $clientcancheckhost = 1;      }
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,      if ($symbstr =~ /^symb=/) {
                                               $form{'udom'},$defaultauth,          (undef,$form{'symb'}) = split('=',$symbstr);
                                               $clientcancheckhost);      }
           if ($iptokenstr =~ /^iptoken=/) {
 # --------------------------------------------------------------------- Failed?          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
       }
     if ($authhost eq 'no_host') {  
  &failed($r,'Username and/or password could not be authenticated.',      my $upass = $ENV{HTTPS} ? $form{'upass0'}
  \%form);          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
         return OK;  
     } elsif ($authhost eq 'no_account_on_host') {  # ---------------------------------------------------------------- Authenticate
         if ($defaultauth) {  
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {      my ($cancreate,$statustocreate) =
                 return OK;          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
             }      my $defaultauth;
             my $start_page =       if (ref($cancreate) eq 'ARRAY') {
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',          if (grep(/^login$/,@{$cancreate})) {
                                                '',{'no_inline_link'   => 1,});              $defaultauth = 1;
             my $lonhost = $r->dir_config('lonHostID');          }
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      }
             my $contacts =       my $clientcancheckhost = 1;
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
                                                         $form{'udom'},$origmail);                                                $form{'udom'},$defaultauth,
             my ($contact_email) = split(',',$contacts);                                                 $clientcancheckhost);
             my $output =   
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},  # --------------------------------------------------------------------- Failed?
                                                        $domdesc,'',$lonhost,  
                                                        $contact_email,$contact_name,      if ($authhost eq 'no_host') {
                                                        undef,$statustocreate);   &failed($r,'Username and/or password could not be authenticated.',
             &Apache::loncommon::content_type($r,'text/html');   \%form);
             $r->send_http_header;          return OK;
             &Apache::createaccount::print_header($r,$start_page);      } elsif ($authhost eq 'no_account_on_host') {
             $r->print('<h3>'.&mt('Account creation').'</h3>'.          if ($defaultauth) {
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
                       $output.&Apache::loncommon::end_page());              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
             return OK;                  return OK;
         } else {              }
             &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);              my $start_page =
             return OK;                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
         }              my $lonhost = $r->dir_config('lonHostID');
     }              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
               my $contacts =
     if (($firsturl eq '') ||                   &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
  ($firsturl=~/^\/adm\/(logout|remote)/)) {                                                          $form{'udom'},$origmail);
  $firsturl='/adm/roles';              my ($contact_email) = split(',',$contacts);
     }              my $output =
                   &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
     my $hosthere;                                                         $domdesc,'',$lonhost,
     if ($form{'iptoken'}) {                                                         $contact_email,$contact_name,
         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});                                                         undef,$statustocreate);
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});              &Apache::loncommon::content_type($r,'text/html');
         if (($sessiondata{'domain'} eq $form{'udom'}) &&              $r->send_http_header;
             ($sessiondata{'username'} eq $form{'uname'})) {              &Apache::createaccount::print_header($r,$start_page);
             $hosthere = 1;              $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 />'.
     }                        $output.&Apache::loncommon::end_page());
               return OK;
 # --------------------------------- Are we attempting to login as somebody else?          } else {
     if ($form{'suname'}) {              &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);
         my ($suname,$sudom,$sudomref);              return OK;
         $suname = $form{'suname'};          }
         $sudom = $form{'udom'};      }
         if ($form{'sudom'}) {  
             unless ($sudom eq $form{'sudom'}) {      if (($firsturl eq '') ||
                 if (&Apache::lonnet::domain($form{'sudom'})) {   ($firsturl=~/^\/adm\/(logout|remote)/)) {
                     $sudomref = [$form{'sudom'}];   $firsturl='/adm/roles';
                     $sudom = $form{'sudom'};      }
                 }  
             }      my $hosthere;
         }      if ($form{'iptoken'}) {
 # ------------ see if the original user has enough privileges to pull this stunt          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
 # ---------------------------------------------------- see if the su-user exists          if (($sessiondata{'domain'} eq $form{'udom'}) &&
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {              ($sessiondata{'username'} eq $form{'uname'})) {
 # ------------------------------ see if the su-user is not too highly privileged              $hosthere = 1;
  if (&Apache::lonnet::privileged($suname,$sudom)) {          }
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');      }
                 } else {  
                     my $noprivswitch;  # --------------------------------- Are we attempting to login as somebody else?
 #      if ($form{'suname'}) {
 # su-user's home server and user's home server must have one of:          my ($suname,$sudom,$sudomref);
 # (a) same domain          $suname = $form{'suname'};
 # (b) same primary library server for the two domains          $sudom = $form{'udom'};
 # (c) same "internet domain" for primary library server(s) for home servers' domains          if ($form{'sudom'}) {
 #              unless ($sudom eq $form{'sudom'}) {
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');                  if (&Apache::lonnet::domain($form{'sudom'})) {
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);                      $sudomref = [$form{'sudom'}];
                     unless ($sudom eq $form{'udom'}) {                      $sudom = $form{'sudom'};
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');                  }
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);              }
                         unless ($suprim eq $uprim) {          }
                             unless ($suintdom eq $uintdom) {  # ------------ see if the original user has enough privileges to pull this stunt
                                 &Apache::lonnet::logthis('Attempted switch user '   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
                                    .'to user with different "internet domain".');  # ---------------------------------------------------- see if the su-user exists
                                 $noprivswitch = 1;      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
                             }  # ------------------------------ see if the su-user is not too highly privileged
                         }   if (&Apache::lonnet::privileged($suname,$sudom)) {
                     }                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
                   } else {
                     unless ($noprivswitch) {                      my $noprivswitch;
 #  #
 # server where log-in occurs must have same "internet domain" as su-user's home  # su-user's home server and user's home server must have one of:
 # server  # (a) same domain
 #  # (b) same primary library server for the two domains
                         my $lonhost = $r->dir_config('lonHostID');  # (c) same "internet domain" for primary library server(s) for home servers' domains
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);  #
                         if ($hostintdom ne $suintdom) {                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
                             &Apache::lonnet::logthis('Attempted switch user on a '                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
                                 .'server with a different "internet domain".');                      unless ($sudom eq $form{'udom'}) {
                         } else {                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
                           my $uintdom = &Apache::lonnet::internet_dom($uprim);
 # -------------------------------------------------------- actually switch users                          unless ($suprim eq $uprim) {
                               unless ($suintdom eq $uintdom) {
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.                                  &Apache::lonnet::logthis('Attempted switch user '
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);                                     .'to user with different "internet domain".');                        
     $form{'uname'}=$suname;                                  $noprivswitch = 1;
                             if ($form{'udom'} ne $sudom) {                              }
                                 $form{'udom'}=$sudom;                          }
                             }                      }
                         }  
                     }                      unless ($noprivswitch) {
  }  #
     }  # server where log-in occurs must have same "internet domain" as su-user's home
  } else {  # server
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');  #
  }                          my $lonhost = $r->dir_config('lonHostID');
     }                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
                           if ($hostintdom ne $suintdom) {
     my ($is_balancer,$otherserver);                              &Apache::lonnet::logthis('Attempted switch user on a '
                                   .'server with a different "internet domain".');
     unless ($hosthere) {                          } else {
         ($is_balancer,$otherserver) =  
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');  # -------------------------------------------------------- actually switch users
         if ($is_balancer) {  
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {              $form{'uname'}=$suname;
                 $otherserver = $found_server;                              if ($form{'udom'} ne $sudom) {
             }                                  $form{'udom'}=$sudom;
             if ($otherserver eq '') {                              }
                 my $lowest_load;                          }
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});                      }
                 if ($lowest_load > 100) {   }
                     $otherserver = &Apache::lonnet::spareserver($r,$lowest_load,$lowest_load,1,$form{'udom'});      }
                 }   } else {
             }      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
             if ($otherserver ne '') {   }
                 my @hosts = &Apache::lonnet::current_machine_ids();      }
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {  
                     $hosthere = $otherserver;      my ($is_balancer,$otherserver);
                 }  
             }      unless ($hosthere) {
         }          ($is_balancer,$otherserver) =
     }              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
           if ($is_balancer) {
     if (($is_balancer) && (!$hosthere)) {              if ($otherserver eq '') {
         if ($otherserver) {                  my $lowest_load;
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
                      \%form);                  if ($lowest_load > 100) {
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {                  }
                 $switchto .= '&origurl='.$firsturl;              }
             }              if ($otherserver ne '') {
             if ($form{'role'}) {                  my @hosts = &Apache::lonnet::current_machine_ids();
                 $switchto .= '&role='.$form{'role'};                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
             }                      $hosthere = $otherserver;
             if ($form{'symb'}) {                  }
                 $switchto .= '&symb='.$form{'symb'};              }
             }          }
             $r->internal_redirect($switchto);      }
         } else {  
             &Apache::loncommon::content_type($r,'text/html');      if (($is_balancer) && (!$hosthere)) {
             $r->send_http_header;          if ($otherserver) {
             $r->print(&noswitch());              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
         }                       \%form);
         return OK;              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
     } else {              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
         if (!&check_can_host($r,\%form,$authhost)) {                  $switchto .= '&origurl='.$firsturl;
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});              }
             if ($otherserver) {              if ($form{'role'}) {
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                  $switchto .= '&role='.$form{'role'};
                          \%form);              }
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;              if ($form{'symb'}) {
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {                  $switchto .= '&symb='.$form{'symb'};
                     $switchto .= '&origurl='.$firsturl;              }
                 }              $r->internal_redirect($switchto);
                 if ($form{'role'}) {          } else {
                     $switchto .= '&role='.$form{'role'};              $r->print(&noswitch());
                 }          }
                 if ($form{'symb'}) {          return OK;
                     $switchto .= '&symb='.$form{'symb'};      } else {
                 }          if (!&check_can_host($r,\%form,$authhost)) {
                 $r->internal_redirect($switchto);              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
             } else {              if ($otherserver) {
                 &Apache::loncommon::content_type($r,'text/html');                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
                 $r->send_http_header;                           \%form);
                 $r->print(&noswitch());                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
             }                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
             return OK;                      $switchto .= '&origurl='.$firsturl;
         }                  }
                   if ($form{'role'}) {
 # ------------------------------------------------------- Do the load balancing                      $switchto .= '&role='.$form{'role'};
                   }
 # ---------------------------------------------------------- Determine own load                  if ($form{'symb'}) {
         my $loadlim = $r->dir_config('lonLoadLim');                      $switchto .= '&symb='.$form{'symb'};
         my $loadavg;                  }
         {                  $r->internal_redirect($switchto);
             my $loadfile=Apache::File->new('/proc/loadavg');              } else {
             $loadavg=<$loadfile>;                  $r->print(&noswitch());
         }              }
         $loadavg =~ s/\s.*//g;              return OK;
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);          }
         my $userloadpercent=&Apache::lonnet::userload();  
   # ------------------------------------------------------- Do the load balancing
 # ---------------------------------------------------------- Are we overloaded?  
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {  # ---------------------------------------------------------- Determine own load
             my $unloaded=Apache::lonnet::spareserver($r,$loadpercent,$userloadpercent,1,$form{'udom'});          my $loadlim = $r->dir_config('lonLoadLim');
             if (!$unloaded) {          my $loadavg;
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});          {
             }              my $loadfile=Apache::File->new('/proc/loadavg');
             if ($unloaded) {              $loadavg=<$loadfile>;
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',          }
                          undef,\%form);          $loadavg =~ s/\s.*//g;
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);          my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
                 return OK;          my $userloadpercent=&Apache::lonnet::userload();
             }  
         }  # ---------------------------------------------------------- Are we overloaded?
         if (($is_balancer) && ($hosthere)) {          if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
             $form{'noloadbalance'} = $hosthere;              my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
         }              if (!$unloaded) {
         my $extra_env;                  ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
         if (($hosthere) && ($sessiondata{'sessionserver'} ne '')) {              }
             if ($sessiondata{'origurl'} ne '') {              if ($unloaded) {
                 $firsturl = $sessiondata{'origurl'};                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                 $form{'firsturl'} = $sessiondata{'origurl'};                           undef,\%form);
                 my @names = ('role','symb','linkprot','linkkey');                  $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                 foreach my $item (@names) {                  return OK;
                     if ($sessiondata{$item} ne '') {              }
                         $form{$item} = $sessiondata{$item};          }
                     }          if (($is_balancer) && ($hosthere)) {
                 }              $form{'noloadbalance'} = $hosthere;
             }          }
         }          &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,                   \%form);
                  \%form);          return OK;
         return OK;      }
     }  }
 }  
   sub check_can_host {
 sub get_form_items {      my ($r,$form,$authhost,$domdesc) = @_;
     my ($r) = @_;      return unless (ref($form) eq 'HASH');
     my $buffer;      my $canhost = 1;
     if ($r->header_in('Content-length') > 0) {      my $lonhost = $r->dir_config('lonHostID');
         $r->read($buffer,$r->header_in('Content-length'),0);      my $udom = $form->{'udom'};
     }      my @intdoms;
     my %form;      my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
     foreach my $pair (split(/&/,$buffer)) {      if (ref($internet_names) eq 'ARRAY') {
        my ($name,$value) = split(/=/,$pair);          @intdoms = @{$internet_names};
        $value =~ tr/+/ /;      }
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;      my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
        $form{$name}=$value;      my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
     }      unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
     return %form;          my $machine_dom = &Apache::lonnet::host_domain($lonhost);
 }          my $hostname = &Apache::lonnet::hostname($lonhost);
           my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
 sub set_retry_token {          my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
     my ($form,$lonhost,$querystr) = @_;          my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
     if (ref($form) eq 'HASH') {          my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
         my ($firsturl,$token,$extras,@names);          my $loncaparev;
         @names = ('role','symb','iptoken');          if ($authhost eq 'no_account_on_host') {
         foreach my $name (@names) {              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
             if ($form->{$name} ne '') {          } else {
                 $extras .= '&'.$name.'='.&escape($form->{$name});              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
                 last if ($name eq 'linkprot');          }
             }          $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
         }                                                       $udomdefaults{'remotesessions'},
         my $firsturl = $form->{'firsturl'};                                                       $defdomdefaults{'hostedsessions'});
         if (($firsturl ne '') || ($extras ne '')) {      }
             $extras .= ':retry';      unless ($canhost) {
             $token = &Apache::lonnet::reply('tmpput:'.&escape($firsturl).          if ($authhost eq 'no_account_on_host') {
                                             $extras,$lonhost);              my $checkloginvia = 1;
             if (($token eq 'con_lost') || ($token eq 'no_such_host')) {              my ($login_host,$hostname) =
                 return 'fail';                  &Apache::lonnet::choose_server($udom,$checkloginvia);
             } else {              &Apache::loncommon::content_type($r,'text/html');
                 if (ref($querystr)) {              $r->send_http_header;
                     $$querystr = 'retry='.$token;              if ($login_host ne '') {
                 }                  my $protocol = $Apache::lonnet::protocol{$login_host};
                 return 'ok';                  $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').
     }                            '<h3>'.&mt('Account creation').'</h3>'.
     return;                            &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>').
 sub check_can_host {                            &Apache::loncommon::end_page());
     my ($r,$form,$authhost,$domdesc) = @_;              } else {
     return unless (ref($form) eq 'HASH');                  $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
     my $canhost = 1;                            '<h3>'.&mt('Account creation unavailable').'</h3>'.
     my $lonhost = $r->dir_config('lonHostID');                            &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
     my $udom = $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>'.
     my @intdoms;                            &Apache::loncommon::end_page());
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);              }
     if (ref($internet_names) eq 'ARRAY') {          } else {
         @intdoms = @{$internet_names};              &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
     }                       $form);
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');              my ($otherserver) = &Apache::lonnet::choose_server($udom);
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);              $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {          }
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);      }
         my $hostname = &Apache::lonnet::hostname($lonhost);      return $canhost;
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);  }
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);  
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);  sub noswitch {
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);      my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
         my $loncaparev;                   '<h3>'.&mt('Session unavailable').'</h3>'.
         if ($authhost eq 'no_account_on_host') {                   &mt('This LON-CAPA server is unable to host your session.').'<br />'.
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);                   '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
         } else {                   &Apache::loncommon::end_page();
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);      return $result;
         }  }
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,  
                                                      $udomdefaults{'remotesessions'},  sub loginhelpdisplay {
                                                      $defdomdefaults{'hostedsessions'});      my ($authdomain) = @_;
     }      my $login_help = 1;
     unless ($canhost) {      my $lang = &Apache::lonlocal::current_language();
         if ($authhost eq 'no_account_on_host') {      if ($login_help) {
             my $checkloginvia = 1;          my $dom = $authdomain;
             my ($login_host,$hostname) =           if ($dom eq '') {
                 &Apache::lonnet::choose_server($udom,$checkloginvia);              $dom = &Apache::lonnet::default_login_domain();
             &Apache::loncommon::content_type($r,'text/html');          }
             $r->send_http_header;          my %domconfhash = &Apache::loncommon::get_domainconf($dom);
             if ($login_host ne '') {          my $loginhelp_url;
                 my $protocol = $Apache::lonnet::protocol{$login_host};          if ($lang) {
                 $protocol = 'http' if ($protocol ne 'https');              $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$login_host);              if ($loginhelp_url ne '') {
                 $hostname = $alias if ($alias ne '');                  return $loginhelp_url;
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';              }
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').          }
                           '<h3>'.&mt('Account creation').'</h3>'.          $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.          if ($loginhelp_url ne '') {
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.              return $loginhelp_url;
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').          } else {
                           &Apache::loncommon::end_page());              return '/adm/loginproblems.html';
             } else {          }
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').      }
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.      return;
                           &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());  1;
             }  __END__
         } else {  
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,  
                      $form);  
             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.22  
changed lines
  Added in v.1.151


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