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

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


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