Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.12 and 1.179

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


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