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

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


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