Diff for /loncom/auth/lonauth.pm between versions 1.134 and 1.159

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


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