Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.6.2.3 and 1.181

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

Removed from v.1.158.2.6.2.3  
changed lines
  Added in v.1.181


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