Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.15 and 1.175

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

Removed from v.1.158.2.15  
changed lines
  Added in v.1.175


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