Diff for /loncom/auth/lonauth.pm between versions 1.121.2.19 and 1.172

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

Removed from v.1.121.2.19  
changed lines
  Added in v.1.172


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