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

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


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