Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.9.2.1 and 1.183

version 1.158.2.9.2.1, 2020/01/22 16:43:52 version 1.183, 2021/05/03 15:27:44
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Login Screen  # Login Screen
 #  #
 # $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::lonlogin;  package Apache::lonlogin;
   
 use strict;  use strict;
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use Apache::File ();  use Apache::File ();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonauth();  use Apache::lonauth();
 use Apache::lonlocal;  use Apache::lonlocal;
 use Apache::migrateuser();  use Apache::migrateuser();
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
 use CGI::Cookie();  use CGI::Cookie();
     
 sub handler {  sub handler {
     my $r = shift;      my $r = shift;
   
     &Apache::loncommon::get_unprocessed_cgi      &Apache::loncommon::get_unprocessed_cgi
  (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},   (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},
       $ENV{'REDIRECT_QUERY_STRING'}),        $ENV{'REDIRECT_QUERY_STRING'}),
  ['interface','username','domain','firsturl','localpath','localres',   ['interface','username','domain','firsturl','localpath','localres',
   'token','role','symb','iptoken','btoken']);    'token','role','symb','iptoken','btoken','ltoken','linkkey']);
     if (!defined($env{'form.firsturl'})) {      if (!defined($env{'form.firsturl'})) {
         &Apache::lonacc::get_posted_cgi($r,['firsturl']);          &Apache::lonacc::get_posted_cgi($r,['firsturl']);
     }      }
     if (!defined($env{'form.firsturl'})) {      if (!defined($env{'form.firsturl'})) {
         if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {          if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {
             $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};              $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};
         }          }
     }      }
       if (($env{'form.firsturl'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) &&
 # -- check if they are a migrating user          (!$env{'form.ltoken'}) && (!$env{'form.linkkey'})) {
     if (defined($env{'form.token'})) {          &Apache::lonacc::get_posted_cgi($r,['linkkey']);
  return &Apache::migrateuser::handler($r);      }
     }  
   # -- check if they are a migrating user
 # For "public user" - remove any exising "public" cookie, as user really wants to log-in      if (defined($env{'form.token'})) {
     my ($handle,$lonidsdir,$expirepub,$userdom);   return &Apache::migrateuser::handler($r);
     $lonidsdir=$r->dir_config('lonIDsDir');      }
     unless ($r->header_only) {  
         $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);  # For "public user" - remove any exising "public" cookie, as user really wants to log-in
         if ($handle ne '') {      my ($handle,$lonidsdir,$expirepub,$userdom);
             if ($handle=~/^publicuser\_/) {      $lonidsdir=$r->dir_config('lonIDsDir');
                 unlink($r->dir_config('lonIDsDir')."/$handle.id");      unless ($r->header_only) {
                 undef($handle);          $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);
                 undef($userdom);          if ($handle ne '') {
                 $expirepub = 1;              if ($handle=~/^publicuser\_/) {
             }                  unlink($r->dir_config('lonIDsDir')."/$handle.id");
         }                  undef($handle);
     }                  undef($userdom);
                   $expirepub = 1;
     &Apache::loncommon::no_cache($r);              }
     &Apache::lonlocal::get_language_handle($r);          }
     &Apache::loncommon::content_type($r,'text/html');      }
     if ($expirepub) {  
         my $c = new CGI::Cookie(-name    => 'lonPubID',      &Apache::loncommon::no_cache($r);
                                 -value   => '',      &Apache::lonlocal::get_language_handle($r);
                                 -expires => '-10y',);      &Apache::loncommon::content_type($r,'text/html');
         $r->header_out('Set-cookie' => $c);      if ($expirepub) {
     } elsif (($handle eq '') && ($userdom ne '')) {          my $c = new CGI::Cookie(-name    => 'lonPubID',
         my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));                                  -value   => '',
         foreach my $name (keys(%cookies)) {                                  -expires => '-10y',);
             next unless ($name =~ /^lon(|S|Link|Pub)ID$/);          $r->header_out('Set-cookie' => $c);
             my $c = new CGI::Cookie(-name    => $name,      } elsif (($handle eq '') && ($userdom ne '')) {
                                     -value   => '',          my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                                     -expires => '-10y',);          foreach my $name (keys(%cookies)) {
             $r->headers_out->add('Set-cookie' => $c);              next unless ($name =~ /^lon(|S|Link|Pub)ID$/);
         }              my $c = new CGI::Cookie(-name    => $name,
     }                                      -value   => '',
     $r->send_http_header;                                      -expires => '-10y',);
     return OK if $r->header_only;              $r->headers_out->add('Set-cookie' => $c);
           }
       }
 # Are we re-routing?      $r->send_http_header;
     my $londocroot = $r->dir_config('lonDocRoot');       return OK if $r->header_only;
     if (-e "$londocroot/lon-status/reroute.txt") {  
  &Apache::lonauth::reroute($r);  
  return OK;  # Are we re-routing?
     }      my $londocroot = $r->dir_config('lonDocRoot');
       if (-e "$londocroot/lon-status/reroute.txt") {
     my $lonhost = $r->dir_config('lonHostID');   &Apache::lonauth::reroute($r);
     $env{'form.firsturl'} =~ s/(`)/'/g;   return OK;
       }
 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)  
       my $lonhost = $r->dir_config('lonHostID');
     my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);      $env{'form.firsturl'} =~ s/(`)/'/g;
     if ($found_server) {  
         my $hostname = &Apache::lonnet::hostname($found_server);  # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
         if ($hostname ne '') {  
             my $protocol = $Apache::lonnet::protocol{$found_server};      my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);
             $protocol = 'http' if ($protocol ne 'https');      if ($found_server) {
             my $dest = '/adm/roles';          my $hostname = &Apache::lonnet::hostname($found_server);
             if ($env{'form.firsturl'} ne '') {          if ($hostname ne '') {
                 $dest = $env{'form.firsturl'};              my $protocol = $Apache::lonnet::protocol{$found_server};
             }              $protocol = 'http' if ($protocol ne 'https');
             my %info = (              my $dest = '/adm/roles';
                          balcookie => $lonhost.':'.$balancer_cookie,              if ($env{'form.firsturl'} ne '') {
                        );                  $dest = $env{'form.firsturl'};
             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);              }
             if ($balancer_token) {              my %info = (
                 $dest .=  (($dest=~/\?/)?'&;':'?') . 'btoken='.$balancer_token;                           balcookie => $lonhost.':'.$balancer_cookie,
             }                         );
             my $url = $protocol.'://'.$hostname.$dest;              if ($env{'form.ltoken'}) {
             my $start_page =                  my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
                 &Apache::loncommon::start_page('Switching Server ...',undef,                  if ($link_info{'linkprot'}) {
                                                {'redirect'       => [0,$url],});                      $info{'linkprot'} = $link_info{'linkprot'};
             my $end_page   = &Apache::loncommon::end_page();                  }
             $r->print($start_page.$end_page);                  &Apache::lonnet::tmpdel($env{'form.ltoken'});
             return OK;                  delete($env{'form.ltoken'});
         }              } elsif ($env{'form.linkkey'}) {
     }                  $info{'linkkey'} = $env{'form.linkkey'};
                   delete($env{'form.linkkey'});
 #              }
 # Check if a LON-CAPA load balancer sent user here because user's browser sent              my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);
 # it a balancer cookie for an active session on this server.              if ($balancer_token) {
 #                  $dest .=  (($dest=~/\?/)?'&;':'?') . 'btoken='.$balancer_token;
               }
     my $balcookie;              unless ($found_server eq $lonhost) {
     if ($env{'form.btoken'}) {                  my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);
         my %info = &Apache::lonnet::tmpget($env{'form.btoken'});                  $hostname = $alias if ($alias ne '');
         $balcookie = $info{'balcookie'};              }
         &Apache::lonnet::tmpdel($env{'form.btoken'});              my $url = $protocol.'://'.$hostname.$dest;
         delete($env{'form.btoken'});              my $start_page =
     }                  &Apache::loncommon::start_page('Switching Server ...',undef,
                                                  {'redirect'       => [0,$url],});
 #              my $end_page   = &Apache::loncommon::end_page();
 # If browser sent an old cookie for which the session file had been removed              $r->print($start_page.$end_page);
 # check if configuration for user's domain has a portal URL set.  If so              return OK;
 # switch user's log-in to the portal.          }
 #      }
   
     if (($handle eq '') && ($userdom ne '')) {  #
         my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);  # Check if a LON-CAPA load balancer sent user here because user's browser sent
         if ($domdefaults{'portal_def'} =~ /^https?\:/) {  # it a balancer cookie for an active session on this server.
             my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,  #
                                           {'redirect' => [0,$domdefaults{'portal_def'}],});  
             my $end_page   = &Apache::loncommon::end_page();      my ($balcookie,$linkprot,$linkkey);
             $r->print($start_page.$end_page);      if ($env{'form.btoken'}) {
             return OK;          my %info = &Apache::lonnet::tmpget($env{'form.btoken'});
         }          $balcookie = $info{'balcookie'};
     }          if ($balcookie) {
               if ($info{'linkprot'}) {
     $env{'form.firsturl'} =~ s/(`)/'/g;                  $linkprot = $info{'linkprot'};
               } elsif ($info{'linkkey'}) {
 # -------------------------------- Prevent users from attempting to login twice                  $linkkey = $info{'linkkey'};
     if ($handle ne '') {              }
         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);          }    
  my $start_page =           &Apache::lonnet::tmpdel($env{'form.btoken'});
     &Apache::loncommon::start_page('Already logged in');          delete($env{'form.btoken'});
  my $end_page =       }
     &Apache::loncommon::end_page();  
         my $dest = '/adm/roles';  #
         if ($env{'form.firsturl'} ne '') {  # If browser sent an old cookie for which the session file had been removed
             $dest = $env{'form.firsturl'};   # check if configuration for user's domain has a portal URL set.  If so
         }  # switch user's log-in to the portal.
  $r->print(  #
               $start_page  
              .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'      if (($handle eq '') && ($userdom ne '')) {
              .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',          my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);
               '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'          if ($domdefaults{'portal_def'} =~ /^https?\:/) {
              .$end_page              my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
              );                                            {'redirect' => [0,$domdefaults{'portal_def'}],});
         return OK;              my $end_page   = &Apache::loncommon::end_page();
     }              $r->print($start_page.$end_page);
               return OK;
 # ---------------------------------------------------- No valid token, continue          }
       }
 # ---------------------------- Not possible to really login to domain "public"  
     if ($env{'form.domain'} eq 'public') {  # -------------------------------- Prevent users from attempting to login twice
  $env{'form.domain'}='';      if ($handle ne '') {
  $env{'form.username'}='';          &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     }   my $start_page =
       &Apache::loncommon::start_page('Already logged in');
 # ------ Is this page requested because /adm/migrateuser detected an IP change?   my $end_page =
     my %sessiondata;      &Apache::loncommon::end_page();
     if ($env{'form.iptoken'}) {          my $dest = '/adm/roles';
         %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});          if ($env{'form.firsturl'} ne '') {
         unless ($sessiondata{'sessionserver'}) {              $dest = $env{'form.firsturl'};
             my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});          }
             delete($env{'form.iptoken'});          if (($env{'form.ltoken'}) || ($linkprot)) {
         }              unless ($linkprot) {
     }                  my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});
 # ----------------------------------------------------------- Process Interface                  $linkprot = $info{'linkprot'};
     $env{'form.interface'}=~s/\W//g;                  my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
                   delete($env{'form.ltoken'});
     (undef,undef,undef,undef,undef,undef,my $clientmobile) =              }
         &Apache::loncommon::decode_user_agent();              if ($linkprot) {
                   my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);
     my $iconpath=                   if ($env{'user.linkprotector'}) {
  &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                      my @protectors = split(/,/,$env{'user.linkprotector'});
                       unless (grep(/^\Q$linkprotector\E$/,@protectors)) {
     my $domain = &Apache::lonnet::default_login_domain();                          push(@protectors,$linkprotector);
     my $defdom = $domain;                          @protectors = sort { $a <=> $b } @protectors;
     if ($lonhost ne '') {                          &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});
         unless ($sessiondata{'sessionserver'}) {                      }
             my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);                  } else {
             if ($redirect) {                      &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });
                 $r->print($redirect);                  }
                 return OK;                  if ($env{'user.linkproturi'}) {
             }                      my @proturis = split(/,/,$env{'user.linkproturi'});
         }                      unless (grep(/^\Q$deeplink\E$/,@proturis)) {
     }                          push(@proturis,$deeplink);
                           @proturis = sort @proturis;
     if (($sessiondata{'domain'}) &&                          &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});
         (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {                      }
         $domain=$sessiondata{'domain'};                  } else {
     } elsif (($env{'form.domain'}) &&                       &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});
  (&Apache::lonnet::domain($env{'form.domain'},'description'))) {                  }
  $domain=$env{'form.domain'};              }
     }          } elsif (($env{'form.linkkey'}) || ($linkkey)) {
               if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     my $role    = $r->dir_config('lonRole');                  if ($linkkey eq '') {
     my $loadlim = $r->dir_config('lonLoadLim');                      $linkkey = $env{'form.linkkey'};
     my $uloadlim= $r->dir_config('lonUserLoadLim');                  }
     my $servadm = $r->dir_config('lonAdmEMail');                  if ($env{'user.deeplinkkey'}) {
     my $tabdir  = $r->dir_config('lonTabDir');                      my @linkkeys = split(/,/,$env{'user.deeplinkkey'});
     my $include = $r->dir_config('lonIncludes');                      unless (grep(/^\Q$linkkey\E$/,@linkkeys)) {
     my $expire  = $r->dir_config('lonExpire');                          push(@linkkeys,$linkkey);
     my $version = $r->dir_config('lonVersion');                          &Apache::lonnet::appenv({'user.deeplinkkey' => join(',',sort(@linkkeys))});  
     my $host_name = &Apache::lonnet::hostname($lonhost);                      }
                   } else {
 # --------------------------------------------- Default values for login fields                      &Apache::lonnet::appenv({'user.deeplinkkey' => $linkkey});
                       }
     my ($authusername,$authdomain);                  my $deeplink = $env{'form.firsturl'};
     if ($sessiondata{'username'}) {                  if ($env{'user.keyedlinkuri'}) {
         $authusername=$sessiondata{'username'};                      my @keyeduris = split(/,/,$env{'user.keyedlinkuri'});
     } else {                      unless (grep(/^\Q$deeplink\E$/,@keyeduris)) {
         $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});                          push(@keyeduris,$deeplink);
         $authusername=($env{'form.username'}?$env{'form.username'}:'');                          &Apache::lonnet::appenv({'user.keyedlinkuri' => join(',',sort(@keyeduris))});
     }                      }
     if ($sessiondata{'domain'}) {                  } else {
         $authdomain=$sessiondata{'domain'};                      &Apache::lonnet::appenv({'user.keyedlinkuri' => $deeplink});
     } else {                  }
         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});              }
         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);          }
     }   $r->print(
                     $start_page
 # ---------------------------------------------------------- Determine own load                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
     my $loadavg;                   .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',
     {                    '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'
  my $loadfile=Apache::File->new('/proc/loadavg');                   .$end_page
  $loadavg=<$loadfile>;                   );
     }          return OK;
     $loadavg =~ s/\s.*//g;      }
   
     my ($loadpercent,$userloadpercent);  # ---------------------------------------------------- No valid token, continue
     if ($loadlim) {  
         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);  # ---------------------------- Not possible to really login to domain "public"
     }      if ($env{'form.domain'} eq 'public') {
     if ($uloadlim) {   $env{'form.domain'}='';
         $userloadpercent=&Apache::lonnet::userload();   $env{'form.username'}='';
     }      }
   
     my $firsturl=  # ------ Is this page requested because /adm/migrateuser detected an IP change?
     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});      my %sessiondata;
       if ($env{'form.iptoken'}) {
 # ----------------------------------------------------------- Get announcements          %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});
     my $announcements=&Apache::lonnet::getannounce();          unless ($sessiondata{'sessionserver'}) {
 # -------------------------------------------------------- Set login parameters              my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});
               delete($env{'form.iptoken'});
     my @hexstr=('0','1','2','3','4','5','6','7',          }
                 '8','9','a','b','c','d','e','f');      }
     my $lkey='';  # ----------------------------------------------------------- Process Interface
     for (0..7) {      $env{'form.interface'}=~s/\W//g;
         $lkey.=$hexstr[rand(15)];  
     }      (undef,undef,undef,undef,undef,undef,my $clientmobile) =
           &Apache::loncommon::decode_user_agent();
     my $ukey='';  
     for (0..7) {      my $iconpath=
         $ukey.=$hexstr[rand(15)];   &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     }  
       my $domain = &Apache::lonnet::default_login_domain();
     my $lextkey=hex($lkey);      my $defdom = $domain;
     if ($lextkey>2147483647) { $lextkey-=4294967296; }      if ($lonhost ne '') {
           unless ($sessiondata{'sessionserver'}) {
     my $uextkey=hex($ukey);              my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie,$linkprot);
     if ($uextkey>2147483647) { $uextkey-=4294967296; }              if ($redirect) {
                   $r->print($redirect);
 # -------------------------------------------------------- Store away log token                  return OK;
     my $tokenextras;              }
     if ($env{'form.role'}) {          }
         $tokenextras = '&role='.&escape($env{'form.role'});      }
     }  
     if ($env{'form.symb'}) {      if (($sessiondata{'domain'}) &&
         if (!$tokenextras) {          (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {
             $tokenextras = '&';          $domain=$sessiondata{'domain'};
         }      } elsif (($env{'form.domain'}) &&
         $tokenextras .= '&symb='.&escape($env{'form.symb'});   (&Apache::lonnet::domain($env{'form.domain'},'description'))) {
     }   $domain=$env{'form.domain'};
     if ($env{'form.iptoken'}) {      }
         if (!$tokenextras) {  
             $tokenextras = '&&';      my $role    = $r->dir_config('lonRole');
         }      my $loadlim = $r->dir_config('lonLoadLim');
         $tokenextras .= '&iptoken='.&escape($env{'form.iptoken'});      my $uloadlim= $r->dir_config('lonUserLoadLim');
     }      my $servadm = $r->dir_config('lonAdmEMail');
     my $logtoken=Apache::lonnet::reply(      my $tabdir  = $r->dir_config('lonTabDir');
        'tmpput:'.$ukey.$lkey.'&'.$firsturl.$tokenextras,      my $include = $r->dir_config('lonIncludes');
        $lonhost);      my $expire  = $r->dir_config('lonExpire');
       my $version = $r->dir_config('lonVersion');
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname      my $host_name = &Apache::lonnet::hostname($lonhost);
 #    we are in serious trouble  
   # --------------------------------------------- Default values for login fields
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {     
         if ($logtoken eq 'no_such_host') {      my ($authusername,$authdomain);
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');      if ($sessiondata{'username'}) {
         }          $authusername=$sessiondata{'username'};
         my $spares='';      } else {
  my $last;          $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});
         foreach my $hostid (sort          $authusername=($env{'form.username'}?$env{'form.username'}:'');
     {      }
  &Apache::lonnet::hostname($a) cmp      if ($sessiondata{'domain'}) {
     &Apache::lonnet::hostname($b);          $authdomain=$sessiondata{'domain'};
     }      } else {
     keys(%Apache::lonnet::spareid)) {          $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});
             next if ($hostid eq $lonhost);          $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);
     my $hostname = &Apache::lonnet::hostname($hostid);      }
     next if (($last eq $hostname) || ($hostname eq ''));  
             $spares.='<br /><font size="+1"><a href="http://'.  # ---------------------------------------------------------- Determine own load
                 $hostname.      my $loadavg;
                 '/adm/login?domain='.$authdomain.'">'.      {
                 $hostname.'</a>'.   my $loadfile=Apache::File->new('/proc/loadavg');
                 ' '.&mt('(preferred)').'</font>'.$/;   $loadavg=<$loadfile>;
     $last=$hostname;      }
         }      $loadavg =~ s/\s.*//g;
         if ($spares) {  
             $spares.= '<br />';      my ($loadpercent,$userloadpercent);
         }      if ($loadlim) {
         my %all_hostnames = &Apache::lonnet::all_hostnames();          $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
         foreach my $hostid (sort      }
     {      if ($uloadlim) {
  &Apache::lonnet::hostname($a) cmp          $userloadpercent=&Apache::lonnet::userload();
     &Apache::lonnet::hostname($b);      }
     }  
     keys(%all_hostnames)) {      my $firsturl=
             next if ($hostid eq $lonhost || $Apache::lonnet::spareid{$hostid});      ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});
             my $hostname = &Apache::lonnet::hostname($hostid);  
             next if (($last eq $hostname) || ($hostname eq ''));  # ----------------------------------------------------------- Get announcements
             $spares.='<br /><a href="http://'.      my $announcements=&Apache::lonnet::getannounce();
              $hostname.  # -------------------------------------------------------- Set login parameters
              '/adm/login?domain='.$authdomain.'">'.  
              $hostname.'</a>';      my @hexstr=('0','1','2','3','4','5','6','7',
             $last=$hostname;                  '8','9','a','b','c','d','e','f');
          }      my $lkey='';
          $r->print(      for (0..7) {
    '<html>'          $lkey.=$hexstr[rand(15)];
   .'<head><title>'      }
   .&mt('The LearningOnline Network with CAPA')  
   .'</title></head>'      my $ukey='';
   .'<body bgcolor="#FFFFFF">'      for (0..7) {
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'          $ukey.=$hexstr[rand(15)];
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" align="right" />'      }
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');  
         if ($spares) {      my $lextkey=hex($lkey);
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      if ($lextkey>2147483647) { $lextkey-=4294967296; }
                      .'</p>'  
                      .$spares);      my $uextkey=hex($ukey);
         }      if ($uextkey>2147483647) { $uextkey-=4294967296; }
         $r->print('</body>'  
                  .'</html>'  # -------------------------------------------------------- Store away log token
         );      my $tokenextras;
         return OK;      if ($env{'form.role'}) {
     }          $tokenextras = '&role='.&escape($env{'form.role'});
       }
 # ----------------------------------------------- Apparently we are in business      if ($env{'form.symb'}) {
     $servadm=~s/\,/\<br \/\>/g;          if (!$tokenextras) {
               $tokenextras = '&';
 # ----------------------------------------------------------- Front page design          }
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);          $tokenextras .= '&symb='.&escape($env{'form.symb'});
     my $font=&Apache::loncommon::designparm('login.font',$domain);      }
     my $link=&Apache::loncommon::designparm('login.link',$domain);      if ($env{'form.iptoken'}) {
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);          if (!$tokenextras) {
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);              $tokenextras = '&&';
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);          }
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);          $tokenextras .= '&iptoken='.&escape($env{'form.iptoken'});
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);      }
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);      if ($env{'form.ltoken'}) {
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);          my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});
     my $img=&Apache::loncommon::designparm('login.img',$domain);          &Apache::lonnet::tmpdel($env{'form.ltoken'});
     my $domainlogo=&Apache::loncommon::domainlogo($domain);          delete($env{'form.ltoken'});
     my $showbanner = 1;          if ($info{'linkprot'}) {
     my $showmainlogo = 1;              if (!$tokenextras) {
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {                  $tokenextras = '&&&';
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);              }
     }              $tokenextras .= '&linkprot='.&escape($info{'linkprot'});
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {          }
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);      } elsif ($env{'form.linkkey'}) {
     }          if (!$tokenextras) {
     my $showadminmail;              $tokenextras = '&&&';
     my @possdoms = &Apache::lonnet::current_machine_domains();          }
     if (grep(/^\Q$domain\E$/,@possdoms)) {          $tokenextras .= '&linkkey='.&escape($env{'form.linkkey'});
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);      }
     }      my $logtoken=Apache::lonnet::reply(
     my $showcoursecat =         'tmpput:'.$ukey.$lkey.'&'.$firsturl.$tokenextras,
         &Apache::loncommon::designparm('login.coursecatalog',$domain);         $lonhost);
     my $shownewuserlink =   
         &Apache::loncommon::designparm('login.newuser',$domain);  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
     my $showhelpdesk =  #    we are in serious trouble
         &Apache::loncommon::designparm('login.helpdesk',$domain);  
     my $now=time;      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
     my $js = (<<ENDSCRIPT);          if ($logtoken eq 'no_such_host') {
               &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
 <script type="text/javascript" language="JavaScript">          }
 // <![CDATA[          my $spares='';
 function send()          my (@sparehosts,%spareservers);
 {          my $sparesref = &Apache::lonnet::this_host_spares($defdom);
 this.document.server.elements.uname.value          if (ref($sparesref) eq 'HASH') {
 =this.document.client.elements.uname.value;              foreach my $key (keys(%{$sparesref})) {
                   if (ref($sparesref->{$key}) eq 'ARRAY') {
 this.document.server.elements.udom.value                      my @sorted = sort { &Apache::lonnet::hostname($a) cmp
 =this.document.client.elements.udom.value;                                          &Apache::lonnet::hostname($b);
                                         } @{$sparesref->{$key}};
 uextkey=this.document.client.elements.uextkey.value;                      if (@sorted) {
 lextkey=this.document.client.elements.lextkey.value;                          if ($key eq 'primary') {
 initkeys();                              unshift(@sparehosts,@sorted);
                           } elsif ($key eq 'default') {
 this.document.server.elements.upass0.value                              push(@sparehosts,@sorted);
     =getCrypted(this.document.client.elements.upass$now.value);                          }
                       }
 this.document.client.elements.uname.value='';                  }
 this.document.client.elements.upass$now.value='';              }
           }
 this.document.server.submit();          foreach my $hostid (@sparehosts) {
 return false;              next if ($hostid eq $lonhost);
 }      my $hostname = &Apache::lonnet::hostname($hostid);
       next if (($hostname eq '') || ($spareservers{$hostname}));
 function enableInput() {              $spareservers{$hostname} = 1;
     this.document.client.elements.upass$now.removeAttribute("readOnly");              my $protocol = $Apache::lonnet::protocol{$hostid};
     this.document.client.elements.uname.removeAttribute("readOnly");              $protocol = 'http' if ($protocol ne 'https');
     this.document.client.elements.udom.removeAttribute("readOnly");              $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
     return;                  $hostname.
 }                  '/adm/login?domain='.$authdomain.'">'.
                   $hostname.'</a>'.
 // ]]>                  ' '.&mt('(preferred)').'</span>'.$/;
 </script>          }
           if ($spares) {
 ENDSCRIPT              $spares.= '<br />';
           }
 # --------------------------------------------------- Print login screen header          my %all_hostnames = &Apache::lonnet::all_hostnames();
           foreach my $hostid (sort
     my %add_entries = (      {
        bgcolor      => "$mainbg",   &Apache::lonnet::hostname($a) cmp
        text         => "$font",      &Apache::lonnet::hostname($b);
        link         => "$link",      }
        vlink        => "$vlink",      keys(%all_hostnames)) {
        alink        => "$alink",              next if ($hostid eq $lonhost);
                onload       => 'javascript:enableInput();',);              my $hostname = &Apache::lonnet::hostname($hostid);
               next if (($hostname eq '') || ($spareservers{$hostname}));
     my ($lonhost_in_use,$headextra,$headextra_exempt,@hosts,%defaultdomconf);              $spareservers{$hostname} = 1;
     @hosts = &Apache::lonnet::current_machine_ids();              my $protocol = $Apache::lonnet::protocol{$hostid};
     $lonhost_in_use = $lonhost;              $protocol = 'http' if ($protocol ne 'https');
     if (@hosts > 1) {              $spares.='<br /><a href="'.$protocol.'://'.
         foreach my $hostid (@hosts) {               $hostname.
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {               '/adm/login?domain='.$authdomain.'">'.
                 $lonhost_in_use = $hostid;               $hostname.'</a>';
                 last;           }
             }           $r->print(
         }     '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
     }    .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);    .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};    .&mt('The LearningOnline Network with CAPA')
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};    .'</title></head>'
     if ($headextra) {    .'<body bgcolor="#FFFFFF">'
         my $omitextra;    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
         if ($headextra_exempt ne '') {    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
             my @exempt = split(',',$headextra_exempt);    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
             my $ip = $ENV{'REMOTE_ADDR'};          if ($spares) {
             if (grep(/^\Q$ip\E$/,@exempt)) {              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
                 $omitextra = 1;                       .'</p>'
             }                       .$spares);
         }          }
         unless ($omitextra) {          $r->print('</body>'
             my $confname = $defdom.'-domainconfig';                   .'</html>'
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {          );
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));          return OK;
                 unless ($extra eq '-1') {      }
                     $js .= "\n".$extra."\n";  
                 }  # ----------------------------------------------- Apparently we are in business
             }      $servadm=~s/\,/\<br \/\>/g;
         }  
     }  # ----------------------------------------------------------- Front page design
       my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,      my $font=&Apache::loncommon::designparm('login.font',$domain);
        { 'redirect'       => [$expire,'/adm/roles'],       my $link=&Apache::loncommon::designparm('login.link',$domain);
  'add_entries' => \%add_entries,      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
  'only_body'   => 1,}));      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
       my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
 # ----------------------------------------------------------------------- Texts      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
       my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
     my %lt=&Apache::lonlocal::texthash(      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
           'un'       => 'Username',      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
           'pw'       => 'Password',      my $img=&Apache::loncommon::designparm('login.img',$domain);
           'dom'      => 'Domain',      my $domainlogo=&Apache::loncommon::domainlogo($domain);
           'perc'     => 'percent',      my $showbanner = 1;
           'load'     => 'Server Load',      my $showmainlogo = 1;
           'userload' => 'User Load',      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
           'catalog'  => 'Course/Community Catalog',          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
           'log'      => 'Log in',      }
           'help'     => 'Log-in Help',      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
           'serv'     => 'Server',          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
           'servadm'  => 'Server Administration',      }
           'helpdesk' => 'Contact Helpdesk',      my $showadminmail;
           'forgotpw' => 'Forgot password?',      my @possdoms = &Apache::lonnet::current_machine_domains();
           'newuser'  => 'New User?',      if (grep(/^\Q$domain\E$/,@possdoms)) {
        );          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 # -------------------------------------------------- Change password field name      }
       my $showcoursecat =
     my $forgotpw = &forgotpwdisplay(%lt);          &Apache::loncommon::designparm('login.coursecatalog',$domain);
     $forgotpw .= '<br />' if $forgotpw;      my $shownewuserlink =
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);          &Apache::loncommon::designparm('login.newuser',$domain);
     if ($loginhelp) {      my $showhelpdesk =
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';          &Apache::loncommon::designparm('login.helpdesk',$domain);
     }      my $now=time;
       my $js = (<<ENDSCRIPT);
 # ---------------------------------------------------- Serve out DES JavaScript  
     {  <script type="text/javascript" language="JavaScript">
     my $jsh=Apache::File->new($include."/londes.js");  // <![CDATA[
     $r->print(<$jsh>);  function send()
     }  {
 # ---------------------------------------------------------- Serve rest of page  this.document.server.elements.uname.value
   =this.document.client.elements.uname.value;
     $r->print(  
     '<div class="LC_Box"'  this.document.server.elements.udom.value
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'  =this.document.client.elements.udom.value;
 );  
   uextkey=this.document.client.elements.uextkey.value;
     $r->print(<<ENDSERVERFORM);  lextkey=this.document.client.elements.lextkey.value;
 <form name="server" action="/adm/authenticate" method="post" target="_top">  initkeys();
    <input type="hidden" name="logtoken" value="$logtoken" />  
    <input type="hidden" name="serverid" value="$lonhost" />  if(this.document.server.action.substr(0,5) === 'http:'){
    <input type="hidden" name="uname" value="" />      this.document.server.elements.upass0.value
    <input type="hidden" name="upass0" value="" />          =getCrypted(this.document.client.elements.upass$now.value);
    <input type="hidden" name="udom" value="" />  } else {
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />      this.document.server.elements.upass0.value
    <input type="hidden" name="localres" value="$env{'form.localres'}" />          =this.document.client.elements.upass$now.value;
   </form>  }
 ENDSERVERFORM  
     my $coursecatalog;  this.document.client.elements.uname.value='';
     if (($showcoursecat eq '') || ($showcoursecat)) {  this.document.client.elements.upass$now.value='';
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';  
     }  this.document.server.submit();
     my $newuserlink;  return false;
     if ($shownewuserlink) {  }
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';  
     }  function enableInput() {
     my $logintitle =      this.document.client.elements.upass$now.removeAttribute("readOnly");
         '<h2 class="LC_hcell"'      this.document.client.elements.uname.removeAttribute("readOnly");
        .' style="background:'.$loginbox_header_bgcol.';'      this.document.client.elements.udom.removeAttribute("readOnly");
        .' color:'.$loginbox_header_textcol.'">'      return;
        .$lt{'log'}  }
        .'</h2>';  
   // ]]>
     my $noscript_warning='<noscript><span class="LC_warning"><b>'  </script>
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')  
                         .'</b></span></noscript>';  ENDSCRIPT
     my $helpdeskscript;  
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,  # --------------------------------------------------- Print login screen header
                                        $authdomain,\$helpdeskscript,  
                                        $showhelpdesk,\@possdoms);      my %add_entries = (
          bgcolor      => "$mainbg",
     my $mobileargs;         text         => "$font",
     if ($clientmobile) {         link         => "$link",
         $mobileargs = 'autocapitalize="off" autocorrect="off"';          vlink        => "$vlink",
     }         alink        => "$alink",
     my $loginform=(<<LFORM);                 onload       => 'javascript:enableInput();',);
 <form name="client" action="" onsubmit="return(send())">  
   <input type="hidden" name="lextkey" value="$lextkey" />      my ($lonhost_in_use,$headextra,$headextra_exempt,@hosts,%defaultdomconf);
   <input type="hidden" name="uextkey" value="$uextkey" />      @hosts = &Apache::lonnet::current_machine_ids();
   <b><label for="uname">$lt{'un'}</label>:</b><br />      $lonhost_in_use = $lonhost;
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />      if (@hosts > 1) {
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />          foreach my $hostid (@hosts) {
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
   <b><label for="udom">$lt{'dom'}</label>:</b><br />                  $lonhost_in_use = $hostid;
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />                  last;
   <input type="submit" value="$lt{'log'}" />              }
 </form>          }
 LFORM      }
       %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
     if ($showbanner) {      $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
         $r->print(<<HEADER);      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
 <!-- The LON-CAPA Header -->      if ($headextra) {
 <div style="background:$pgbg;margin:0;width:100%;">          my $omitextra;
   <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />          if ($headextra_exempt ne '') {
 </div>              my @exempt = split(',',$headextra_exempt);
 HEADER              my $ip = &Apache::lonnet::get_requestor_ip();
     }              if (grep(/^\Q$ip\E$/,@exempt)) {
     $r->print(<<ENDTOP);                  $omitextra = 1;
 <div style="float:left;margin-top:0;">              }
 <div class="LC_Box" style="background:$loginbox_bg;">          }
   $logintitle          unless ($omitextra) {
   $loginform              my $confname = $defdom.'-domainconfig';
   $noscript_warning              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
 </div>                  my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
                     unless ($extra eq '-1') {
 <div class="LC_Box" style="padding-top: 10px;">                      $js .= "\n".$extra."\n";
   $loginhelp                  }
   $forgotpw              }
   $contactblock          }
   $newuserlink      }
   $coursecatalog  
 </div>      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
 </div>         { 'redirect'       => [$expire,'/adm/roles'],
    'add_entries' => \%add_entries,
 <div>   'only_body'   => 1,}));
 ENDTOP  
     if ($showmainlogo) {  # ----------------------------------------------------------------------- Texts
         $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");  
     }      my %lt=&Apache::lonlocal::texthash(
 $r->print(<<ENDTOP);            'un'       => 'Username',
 $announcements            'pw'       => 'Password',
 </div>            'dom'      => 'Domain',
 <hr style="clear:both;" />            'perc'     => 'percent',
 ENDTOP            'load'     => 'Server Load',
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);            'userload' => 'User Load',
     $domainrow = <<"END";            'catalog'  => 'Course/Community Catalog',
       <tr>            'log'      => 'Log in',
        <td  align="left" valign="top">            'help'     => 'Log-in Help',
         <small><b>$lt{'dom'}:&nbsp;</b></small>            'serv'     => 'Server',
        </td>            'servadm'  => 'Server Administration',
        <td  align="left" valign="top">            'helpdesk' => 'Contact Helpdesk',
         <small><tt>&nbsp;$domain</tt></small>            'forgotpw' => 'Forgot password?',
        </td>            'newuser'  => 'New User?',
       </tr>         );
 END  # -------------------------------------------------- Change password field name
     $serverrow = <<"END";  
       <tr>      my $forgotpw = &forgotpwdisplay(%lt);
        <td  align="left" valign="top">      $forgotpw .= '<br />' if $forgotpw;
         <small><b>$lt{'serv'}:&nbsp;</b></small>      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
        </td>      if ($loginhelp) {
        <td align="left" valign="top">          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
         <small><tt>&nbsp;$lonhost ($role)</tt></small>      }
        </td>  
       </tr>  # ---------------------------------------------------- Serve out DES JavaScript
 END      {
     if ($loadlim) {      my $jsh=Apache::File->new($include."/londes.js");
         $loadrow = <<"END";      $r->print(<$jsh>);
       <tr>      }
        <td align="left" valign="top">  # ---------------------------------------------------------- Serve rest of page
         <small><b>$lt{'load'}:&nbsp;</b></small>  
        </td>      $r->print(
        <td align="left" valign="top">      '<div class="LC_Box"'
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
        </td>  );
       </tr>  
 END      $r->print(<<ENDSERVERFORM);
     }  <form name="server" action="/adm/authenticate" method="post" target="_top">
     if ($uloadlim) {     <input type="hidden" name="logtoken" value="$logtoken" />
         $userloadrow = <<"END";     <input type="hidden" name="serverid" value="$lonhost" />
       <tr>     <input type="hidden" name="uname" value="" />
        <td align="left" valign="top">     <input type="hidden" name="upass0" value="" />
         <small><b>$lt{'userload'}:&nbsp;</b></small>     <input type="hidden" name="udom" value="" />
        </td>     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
        <td align="left" valign="top">     <input type="hidden" name="localres" value="$env{'form.localres'}" />
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>    </form>
        </td>  ENDSERVERFORM
       </tr>      my $coursecatalog;
 END      if (($showcoursecat eq '') || ($showcoursecat)) {
     }          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {      }
         $versionrow = <<"END";      my $newuserlink;
       <tr>      if ($shownewuserlink) {
        <td colspan="2" align="left">          $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
         <small>$version</small>      }
        </td>      my $logintitle =
       </tr>          '<h2 class="LC_hcell"'
 END         .' style="background:'.$loginbox_header_bgcol.';'
     }         .' color:'.$loginbox_header_textcol.'">'
          .$lt{'log'}
     $r->print(<<ENDDOCUMENT);         .'</h2>';
     <div style="float: left;">  
      <table border="0" cellspacing="0" cellpadding="0">      my $noscript_warning='<noscript><span class="LC_warning"><b>'
 $domainrow                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
 $serverrow                          .'</b></span></noscript>';
 $loadrow          my $helpdeskscript;
 $userloadrow      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
 $versionrow                                         $authdomain,\$helpdeskscript,
      </table>                                         $showhelpdesk,\@possdoms);
     </div>  
     <div style="float: right;">      my $mobileargs;
     $domainlogo      if ($clientmobile) {
     </div>          $mobileargs = 'autocapitalize="off" autocorrect="off"';
     <br style="clear:both;" />      }
  </div>      my $loginform=(<<LFORM);
   <form name="client" action="" onsubmit="return(send())">
 <script type="text/javascript">    <input type="hidden" name="lextkey" value="$lextkey" />
 // <![CDATA[    <input type="hidden" name="uextkey" value="$uextkey" />
 // the if prevents the script error if the browser can not handle this    <b><label for="uname">$lt{'un'}</label>:</b><br />
 if ( document.client.uname ) { document.client.uname.focus(); }    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
 // ]]>    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
 </script>    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
 $helpdeskscript    <b><label for="udom">$lt{'dom'}</label>:</b><br />
     <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
 ENDDOCUMENT    <input type="submit" value="$lt{'log'}" />
     my %endargs = ( 'noredirectlink' => 1, );  </form>
     $r->print(&Apache::loncommon::end_page(\%endargs));  LFORM
     return OK;  
 }      if ($showbanner) {
           $r->print(<<HEADER);
 sub check_loginvia {  <!-- The LON-CAPA Header -->
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;  <div style="background:$pgbg;margin:0;width:100%;">
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {    <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />
         return;  </div>
     }  HEADER
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);      }
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};      $r->print(<<ENDTOP);
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};  <div style="float:left;margin-top:0;">
     my $output;  <div class="LC_Box" style="background:$loginbox_bg;">
     if ($loginvia ne '') {    $logintitle
         my $noredirect;    $loginform
         my $ip = $ENV{'REMOTE_ADDR'};    $noscript_warning
         if ($ip eq '127.0.0.1') {  </div>
             $noredirect = 1;   
         } else {  <div class="LC_Box" style="padding-top: 10px;">
             if ($loginvia_exempt ne '') {    $loginhelp
                 my @exempt = split(',',$loginvia_exempt);    $forgotpw
                 if (grep(/^\Q$ip\E$/,@exempt)) {    $contactblock
                     $noredirect = 1;    $newuserlink
                 }    $coursecatalog
             }  </div>
         }  </div>
         unless ($noredirect) {  
             my ($newhost,$path);  <div>
             if ($loginvia =~ /:/) {  ENDTOP
                 ($newhost,$path) = split(':',$loginvia);      if ($showmainlogo) {
             } else {          $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");
                 $newhost = $loginvia;      }
             }  $r->print(<<ENDTOP);
             if ($newhost ne $lonhost) {  $announcements
                 if (&Apache::lonnet::hostname($newhost) ne '') {  </div>
                     if ($balcookie) {  <hr style="clear:both;" />
                         my ($balancer,$cookie) = split(/:/,$balcookie);  ENDTOP
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);      $domainrow = <<"END";
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {        <tr>
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {         <td  align="left" valign="top">
                                     while (my $filename=readdir($dh)) {          <small><b>$lt{'dom'}:&nbsp;</b></small>
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {         </td>
                                             my $handle = $1;         <td  align="left" valign="top">
                                             my %hash =          <small><tt>&nbsp;$domain</tt></small>
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,         </td>
                                                                                      ['request.balancercookie',        </tr>
                                                                                       'user.linkedenv']);  END
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {      $serverrow = <<"END";
                                                 if (unlink("$lonidsdir/$filename")) {        <tr>
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&         <td  align="left" valign="top">
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&          <small><b>$lt{'serv'}:&nbsp;</b></small>
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {         </td>
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");         <td align="left" valign="top">
                                                     }          <small><tt>&nbsp;$lonhost ($role)</tt></small>
                                                 }         </td>
                                             }        </tr>
                                             last;  END
                                         }      if ($loadlim) {
                                     }          $loadrow = <<"END";
                                     closedir($dh);        <tr>
                                 }         <td align="left" valign="top">
                             }          <small><b>$lt{'load'}:&nbsp;</b></small>
                         }         </td>
                     }         <td align="left" valign="top">
                     $output = &redirect_page($newhost,$path);          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
                 }         </td>
             }        </tr>
         }  END
     }      }
     return $output;      if ($uloadlim) {
 }          $userloadrow = <<"END";
         <tr>
 sub redirect_page {         <td align="left" valign="top">
     my ($desthost,$path) = @_;          <small><b>$lt{'userload'}:&nbsp;</b></small>
     my $hostname = &Apache::lonnet::hostname($desthost);         </td>
     my $protocol = $Apache::lonnet::protocol{$desthost};         <td align="left" valign="top">
     $protocol = 'http' if ($protocol ne 'https');          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
     unless ($path =~ m{^/}) {         </td>
         $path = '/'.$path;        </tr>
     }  END
     my $url = $protocol.'://'.$hostname.$path;      }
     if ($env{'form.firsturl'} ne '') {      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
         $url .='?firsturl='.$env{'form.firsturl'};          $versionrow = <<"END";
     }        <tr>
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,         <td colspan="2" align="left">
                                                     {'redirect' => [0,$url],});          <small>$version</small>
     my $end_page   = &Apache::loncommon::end_page();         </td>
     return $start_page.$end_page;        </tr>
 }  END
       }
 sub contactdisplay {  
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,      $r->print(<<ENDDOCUMENT);
         $possdoms) = @_;      <div style="float: left;">
     my $contactblock;       <table border="0" cellspacing="0" cellpadding="0">
     my $origmail;  $domainrow
     if (ref($possdoms) eq 'ARRAY') {  $serverrow
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {   $loadrow    
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};  $userloadrow
         }  $versionrow
     }       </table>
     my $requestmail =       </div>
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',      <div style="float: right;">
                                                  $authdomain,$origmail);      $domainlogo
     unless ($showhelpdesk eq '0') {      </div>
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {      <br style="clear:both;" />
             $showhelpdesk = 1;   </div>
         } else {  
             $showhelpdesk = 0;  <script type="text/javascript">
         }  // <![CDATA[
     }  // the if prevents the script error if the browser can not handle this
     if ($servadm && $showadminmail) {  if ( document.client.uname ) { document.client.uname.focus(); }
         $contactblock .= $$lt{'servadm'}.':<br />'.  // ]]>
                          '<tt>'.$servadm.'</tt><br />';  </script>
     }  $helpdeskscript
     if ($showhelpdesk) {  
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';  ENDDOCUMENT
         my $thisurl = &escape('/adm/login');      my %endargs = ( 'noredirectlink' => 1, );
         $$helpdeskscript = <<"ENDSCRIPT";      $r->print(&Apache::loncommon::end_page(\%endargs));
 <script type="text/javascript">      return OK;
 // <![CDATA[  }
 function helpdesk() {  
     var possdom = document.client.udom.value;  sub check_loginvia {
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');      my ($domain,$lonhost,$lonidsdir,$balcookie,$linkprot) = @_;
     if (codedom == '') {      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
         codedom = "$authdomain";          return;
     }      }
     var querystr = "origurl=$thisurl&codedom="+codedom;      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
     document.location.href = "/adm/helpdesk?"+querystr;      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
     return;      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
 }      my $output;
 // ]]>      if ($loginvia ne '') {
 </script>          my $noredirect;
 ENDSCRIPT          my $ip = &Apache::lonnet::get_requestor_ip();  
     }          if ($ip eq '127.0.0.1') {
     return $contactblock;              $noredirect = 1;
 }          } else {
               if ($loginvia_exempt ne '') {
 sub forgotpwdisplay {                  my @exempt = split(',',$loginvia_exempt);
     my (%lt) = @_;                  if (grep(/^\Q$ip\E$/,@exempt)) {
     my $prompt_for_resetpw = 1;                       $noredirect = 1;
     if ($prompt_for_resetpw) {                  }
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';              }
     }          }
     return;          unless ($noredirect) {
 }              my ($newhost,$path);
               if ($loginvia =~ /:/) {
 sub coursecatalog_link {                  ($newhost,$path) = split(':',$loginvia);
     my ($linkname) = @_;              } else {
     return <<"END";                  $newhost = $loginvia;
       <a href="/adm/coursecatalog">$linkname</a>              }
 END              if ($newhost ne $lonhost) {
 }                  if (&Apache::lonnet::hostname($newhost) ne '') {
                       if ($balcookie) {
 sub newuser_link {                          my ($balancer,$cookie) = split(/:/,$balcookie);
     my ($linkname) = @_;                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
     return '<a href="/adm/createaccount">'.$linkname.'</a>';                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
 }                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
                                   if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
 1;                                      while (my $filename=readdir($dh)) {
 __END__                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
                                               my $handle = $1;
                                               my %hash =
                                                   &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
                                                                                        ['request.balancercookie',
                                                                                         'user.linkedenv']);
                                               if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
                                                   if (unlink("$lonidsdir/$filename")) {
                                                       if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
                                                           (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
                                                           (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
                                                           unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
                                                       }
                                                   }
                                               }
                                               last;
                                           }
                                       }
                                       closedir($dh);
                                   }
                               }
                           }
                       }
                       $output = &redirect_page($newhost,$path,$linkprot);
                   }
               }
           }
       }
       return $output;
   }
   
   sub redirect_page {
       my ($desthost,$path,$linkprot) = @_;
       my $hostname = &Apache::lonnet::hostname($desthost);
       my $protocol = $Apache::lonnet::protocol{$desthost};
       $protocol = 'http' if ($protocol ne 'https');
       unless ($path =~ m{^/}) {
           $path = '/'.$path;
       }
       my $url = $protocol.'://'.$hostname.$path;
       if ($env{'form.firsturl'} ne '') {
           $url .='?firsturl='.$env{'form.firsturl'};
       }
       if ($linkprot) {
           my $ltoken = &Apache::lonnet::tmpput({linkprot => $linkprot},$desthost);
           if ($ltoken) {
               $url .= (($url =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
           }
       }
       my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
                                                       {'redirect' => [0,$url],});
       my $end_page   = &Apache::loncommon::end_page();
       return $start_page.$end_page;
   }
   
   sub contactdisplay {
       my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
           $possdoms) = @_;
       my $contactblock;
       my $origmail;
       if (ref($possdoms) eq 'ARRAY') {
           if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
               $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
           }
       }
       my $requestmail =
           &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                                    $authdomain,$origmail);
       unless ($showhelpdesk eq '0') {
           if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
               $showhelpdesk = 1;
           } else {
               $showhelpdesk = 0;
           }
       }
       if ($servadm && $showadminmail) {
           $contactblock .= $$lt{'servadm'}.':<br />'.
                            '<tt>'.$servadm.'</tt><br />';
       }
       if ($showhelpdesk) {
           $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
           my $thisurl = &escape('/adm/login');
           $$helpdeskscript = <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function helpdesk() {
       var possdom = document.client.udom.value;
       var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
       if (codedom == '') {
           codedom = "$authdomain";
       }
       var querystr = "origurl=$thisurl&codedom="+codedom;
       document.location.href = "/adm/helpdesk?"+querystr;
       return;
   }
   // ]]>
   </script>
   ENDSCRIPT
       }
       return $contactblock;
   }
   
   sub forgotpwdisplay {
       my (%lt) = @_;
       my $prompt_for_resetpw = 1;
       if ($prompt_for_resetpw) {
           return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
       }
       return;
   }
   
   sub coursecatalog_link {
       my ($linkname) = @_;
       return <<"END";
         <a href="/adm/coursecatalog">$linkname</a>
   END
   }
   
   sub newuser_link {
       my ($linkname) = @_;
       return '<a href="/adm/createaccount">'.$linkname.'</a>';
   }
   
   1;
   __END__

Removed from v.1.158.2.9.2.1  
changed lines
  Added in v.1.183


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