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

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


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