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

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


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