Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.3 and 1.198

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


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