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

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


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