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

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

Removed from v.1.121.2.20  
changed lines
  Added in v.1.140


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