Diff for /loncom/auth/lonauth.pm between versions 1.121.2.6 and 1.151

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

Removed from v.1.121.2.6  
changed lines
  Added in v.1.151


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