Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.14 and 1.173

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


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