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

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

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


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