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

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

Removed from v.1.158.2.13.2.1  
changed lines
  Added in v.1.192


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