Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.2 and 1.176

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


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