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

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


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