Diff for /loncom/auth/lonauth.pm between versions 1.121.2.21 and 1.168

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

Removed from v.1.121.2.21  
changed lines
  Added in v.1.168


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