Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.9.2.2 and 1.200

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


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