Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.6.2.3 and 1.192

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


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