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

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


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