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

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

Removed from v.1.158.2.8  
changed lines
  Added in v.1.192


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