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

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

Removed from v.1.121.2.21  
changed lines
  Added in v.1.151


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