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

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


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