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

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

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


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