Diff for /loncom/auth/lonauth.pm between versions 1.121.2.24.2.2 and 1.162

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


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