Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.9.2.1 and 1.193

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


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