Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.6.2.1 and 1.185

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

Removed from v.1.158.2.6.2.1  
changed lines
  Added in v.1.185


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