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

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


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