Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.2 and 1.191

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


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