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

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


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