Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.9.2.3 and 1.202

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


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