Diff for /loncom/auth/lonauth.pm between versions 1.121.2.11 and 1.166

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


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