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

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


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