Diff for /loncom/auth/lonauth.pm between versions 1.121.2.20 and 1.141

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


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