Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.11 and 1.209

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

Removed from v.1.158.2.13.2.11  
changed lines
  Added in v.1.209


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