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

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


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