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

version 1.158.2.13.2.11, 2023/12/29 23:49:12 version 1.213, 2025/02/25 16:33:37
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 class="LC_landmark" 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);  .LC_landmark {
     my $font=&Apache::loncommon::designparm('login.font',$domain);    margin: 0;
     my $link=&Apache::loncommon::designparm('login.link',$domain);    padding: 0;
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);    border: none;
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);  }
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);  </style></head>'
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);    .'<body bgcolor="#FFFFFF">'
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);    .'<div class="LC_landmark" role="banner">'
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
     my $img=&Apache::loncommon::designparm('login.img',$domain);    .'</div>'
     my $domainlogo=&Apache::loncommon::domainlogo($domain);    .'<div class="LC_landmark" role="main">'
     my $showbanner = 1;    .'<h2>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h2>');
     my $showmainlogo = 1;          if ($spares) {
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);                       .'</p>'
     }                       .$spares);
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {          }
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);          $r->print('</div></body>'
     }                   .'</html>'
     my $showadminmail;          );
     my @possdoms = &Apache::lonnet::current_machine_domains();          return OK;
     if (grep(/^\Q$domain\E$/,@possdoms)) {      }
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);  
     }  # ----------------------------------------------- Apparently we are in business
     my $showcoursecat =      $servadm=~s/\,/\<br \/\>/g;
         &Apache::loncommon::designparm('login.coursecatalog',$domain);  
     my $shownewuserlink =   # ----------------------------------------------------------- Front page design
         &Apache::loncommon::designparm('login.newuser',$domain);      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
     my $showhelpdesk =      my $font=&Apache::loncommon::designparm('login.font',$domain);
         &Apache::loncommon::designparm('login.helpdesk',$domain);      my $link=&Apache::loncommon::designparm('login.link',$domain);
     my $now=time;      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
     my $js = (<<ENDSCRIPT);      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
       my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
 <script type="text/javascript" language="JavaScript">      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
 // <![CDATA[      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
 function send()      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
 {      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
 this.document.server.elements.uname.value      my $img=&Apache::loncommon::designparm('login.img',$domain);
 =this.document.client.elements.uname.value;      my $domainlogo=&Apache::loncommon::domainlogo($domain);
       my $showbanner = 1;
 this.document.server.elements.udom.value      my $showmainlogo = 1;
 =this.document.client.elements.udom.value;      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
           $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
 uextkey=this.document.client.elements.uextkey.value;      }
 lextkey=this.document.client.elements.lextkey.value;      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
 initkeys();          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
       }
 this.document.server.elements.upass0.value      my $showadminmail;
     =getCrypted(this.document.client.elements.upass$now.value);      my @possdoms = &Apache::lonnet::current_machine_domains();
       if (grep(/^\Q$domain\E$/,@possdoms)) {
 this.document.client.elements.uname.value='';          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 this.document.client.elements.upass$now.value='';      }
       my $showcoursecat =
 this.document.server.submit();          &Apache::loncommon::designparm('login.coursecatalog',$domain);
 return false;      my $shownewuserlink =
 }          &Apache::loncommon::designparm('login.newuser',$domain);
       my $showhelpdesk =
 function enableInput() {          &Apache::loncommon::designparm('login.helpdesk',$domain);
     this.document.client.elements.upass$now.removeAttribute("readOnly");      my $now=time;
     this.document.client.elements.uname.removeAttribute("readOnly");      my $js = (<<ENDSCRIPT);
     this.document.client.elements.udom.removeAttribute("readOnly");  
     return;  <script type="text/javascript" language="JavaScript">
 }  // <![CDATA[
   function send()
 // ]]>  {
 </script>  this.document.server.elements.uname.value
   =this.document.client.elements.uname.value;
 ENDSCRIPT  
   this.document.server.elements.udom.value
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,  =this.document.client.elements.udom.value;
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip,  
         $samlwindow);  uextkey=this.document.client.elements.uextkey.value;
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);  lextkey=this.document.client.elements.lextkey.value;
     @hosts = &Apache::lonnet::current_machine_ids();  initkeys();
     $lonhost_in_use = $lonhost;  
     if (@hosts > 1) {  if(this.document.server.action.substr(0,5) === 'http:'){
         foreach my $hostid (@hosts) {      this.document.server.elements.upass0.value
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {          =getCrypted(this.document.client.elements.upass$now.value);
                 $lonhost_in_use = $hostid;  } else {
                 last;      this.document.server.elements.upass0.value
             }          =this.document.client.elements.upass$now.value;
         }  }
     }  
     $saml_prefix = $defdom.'.login.saml_';  this.document.client.elements.uname.value='';
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {  this.document.client.elements.upass$now.value='';
         $saml_landing = 1;  
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};  this.document.server.submit();
         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};  return false;
         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};  }
         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};  
         $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};  function enableInput() {
         $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};      this.document.client.elements.upass$now.removeAttribute("readOnly");
         $samlwindow = $defaultdomconf{$saml_prefix.'window_'.$lonhost_in_use};      this.document.client.elements.uname.removeAttribute("readOnly");
     }      this.document.client.elements.udom.removeAttribute("readOnly");
     if ($saml_landing) {      return;
        if ($samlssotext eq '') {  }
            $samlssotext = 'SSO Login';  
        }  // ]]>
        if ($samlnonsso eq '') {  </script>
            $samlnonsso = 'Non-SSO Login';  
        }  ENDSCRIPT
        $js .= <<"ENDSAMLJS";  
       my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,
 <script type="text/javascript">          $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip,
 // <![CDATA[          $samlwindow);
 function toggleLClogin() {      %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
     if (document.getElementById('LC_standard_login')) {      @hosts = &Apache::lonnet::current_machine_ids();
         if (document.getElementById('LC_standard_login').style.display == 'none') {      $lonhost_in_use = $lonhost;
             document.getElementById('LC_standard_login').style.display = 'inline-block';      if (@hosts > 1) {
             if (document.getElementById('LC_login_text')) {          foreach my $hostid (@hosts) {
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
             }                  $lonhost_in_use = $hostid;
             if ( document.client.uname ) { document.client.uname.focus(); }                  last;
             if (document.getElementById('LC_SSO_login')) {              }
                 document.getElementById('LC_SSO_login').style.display = 'none';          }
             }      }
         } else {      $saml_prefix = $defdom.'.login.saml_';
             document.getElementById('LC_standard_login').style.display = 'none';      if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {
             if (document.getElementById('LC_login_text')) {          $saml_landing = 1;
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';          $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};
             }          $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};
             if (document.getElementById('LC_SSO_login')) {          $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';          $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};
             }          $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};
         }          $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};
     }          $samlwindow = $defaultdomconf{$saml_prefix.'window_'.$lonhost_in_use};
     return;      }
 }      if ($saml_landing) {
          if ($samlssotext eq '') {
 // ]]>             $samlssotext = 'SSO Login';
 </script>         }
          if ($samlnonsso eq '') {
 ENDSAMLJS             $samlnonsso = 'Non-SSO Login';
     }         }
          $js .= <<"ENDSAMLJS";
 # --------------------------------------------------- Print login screen header  
   <script type="text/javascript">
     my %add_entries = (  // <![CDATA[
        bgcolor      => "$mainbg",  function toggleLClogin() {
        text         => "$font",      if (document.getElementById('LC_standard_login')) {
        link         => "$link",          if (document.getElementById('LC_standard_login').style.display == 'none') {
        vlink        => "$vlink",              document.getElementById('LC_standard_login').style.display = 'inline-block';
        alink        => "$alink",              if (document.getElementById('LC_login_text')) {
                onload       => 'javascript:enableInput();',);                  document.getElementById('LC_login_text').innerHTML = '$samlnonsso';
               }
     my ($headextra,$headextra_exempt);              if ( document.client.uname ) { document.client.uname.focus(); }
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};              if (document.getElementById('LC_SSO_login')) {
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};                  document.getElementById('LC_SSO_login').style.display = 'none';
     if ($headextra) {              }
         my $omitextra;          } else {
         if ($headextra_exempt ne '') {              document.getElementById('LC_standard_login').style.display = 'none';
             my @exempt = split(',',$headextra_exempt);              if (document.getElementById('LC_login_text')) {
             my $ip = &Apache::lonnet::get_requestor_ip();                  document.getElementById('LC_login_text').innerHTML = '$samlssotext';
             if (grep(/^\Q$ip\E$/,@exempt)) {              }
                 $omitextra = 1;              if (document.getElementById('LC_SSO_login')) {
             }                  document.getElementById('LC_SSO_login').style.display = 'inline-block';
         }              }
         unless ($omitextra) {          }
             my $confname = $defdom.'-domainconfig';      }
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {      return;
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));  }
                 unless ($extra eq '-1') {  
                     $js .= "\n".$extra."\n";  // ]]>
                 }  </script>
             }  
         }  ENDSAMLJS
     }      }
   
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,  # --------------------------------------------------- Print login screen header
        { 'redirect'       => [$expire,'/adm/roles'],   
  'add_entries' => \%add_entries,      my %add_entries = (
  'only_body'   => 1,}));         bgcolor      => "$mainbg",
          text         => "$font",
 # ----------------------------------------------------------------------- Texts         link         => "$link",
          vlink        => "$vlink",
     my %lt=&Apache::lonlocal::texthash(         alink        => "$alink",
           'un'       => 'Username',                 onload       => 'javascript:enableInput();',);
           'pw'       => 'Password',  
           'dom'      => 'Domain',      my ($headextra,$headextra_exempt);
           'perc'     => 'percent',      $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
           'load'     => 'Server Load',      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
           'userload' => 'User Load',      if ($headextra) {
           'catalog'  => 'Course/Community Catalog',          my $omitextra;
           'log'      => 'Log in',          if ($headextra_exempt ne '') {
           'help'     => 'Log-in Help',              my @exempt = split(',',$headextra_exempt);
           'serv'     => 'Server',              my $ip = &Apache::lonnet::get_requestor_ip();
           'servadm'  => 'Server Administration',              if (grep(/^\Q$ip\E$/,@exempt)) {
           'helpdesk' => 'Contact Helpdesk',                  $omitextra = 1;
           'forgotpw' => 'Forgot password?',              }
           'newuser'  => 'New User?',          }
           'change'   => 'Change?',          unless ($omitextra) {
        );              my $confname = $defdom.'-domainconfig';
 # -------------------------------------------------- Change password field name              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
                   my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
     my $forgotpw = &forgotpwdisplay(%lt);                  unless ($extra eq '-1') {
     $forgotpw .= '<br />' if $forgotpw;                      $js .= "\n".$extra."\n";
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);                  }
     if ($loginhelp) {              }
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';          }
     }      }
   
 # ---------------------------------------------------- Serve out DES JavaScript      my $args = {
     {                   'redirect'    => [$expire,'/adm/roles'],
     my $jsh=Apache::File->new($include."/londes.js");                   'add_entries' => \%add_entries,
     $r->print(<$jsh>);                   'only_body'   => 1,
     }                 };
 # ---------------------------------------------------------- Serve rest of page      if ($clientunicode && !$clientmathml) {
           $args->{'browser.unicode'} = 1;
     $r->print(      }
     '<div class="LC_Box"'      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'                                               $js,$args));
 );  
   # ----------------------------------------------------------------------- Texts
     $r->print(<<ENDSERVERFORM);  
 <form name="server" action="/adm/authenticate" method="post" target="_top">      my %lt=&Apache::lonlocal::texthash(
    <input type="hidden" name="logtoken" value="$logtoken" />            'un'       => 'Username',
    <input type="hidden" name="serverid" value="$lonhost" />            'pw'       => 'Password',
    <input type="hidden" name="uname" value="" />            'dom'      => 'Domain',
    <input type="hidden" name="upass0" value="" />            'perc'     => 'percent',
    <input type="hidden" name="udom" value="" />            'load'     => 'Server Load',
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />            'userload' => 'User Load',
    <input type="hidden" name="localres" value="$env{'form.localres'}" />            'catalog'  => 'Course/Community Catalog',
   </form>            'log'      => 'Log in',
 ENDSERVERFORM            'help'     => 'Log-in Help',
     my $coursecatalog;            'serv'     => 'Server',
     if (($showcoursecat eq '') || ($showcoursecat)) {            'servadm'  => 'Server Administration',
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';            'helpdesk' => 'Contact Helpdesk',
     }            'forgotpw' => 'Forgot password?',
     my $newuserlink;            'newuser'  => 'New User?',
     if ($shownewuserlink) {            'change'   => 'Change?',
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';            'nojs'     => 'Use of LON-CAPA requires Javascript to be enabled in your web browser.',
     }         );
     my $logintitle =  # -------------------------------------------------- Change password field name
         '<h2 class="LC_hcell"'  
        .' style="background:'.$loginbox_header_bgcol.';'      my $forgotpw = &forgotpwdisplay(%lt);
        .' color:'.$loginbox_header_textcol.'">'      if ($forgotpw) {
        .$lt{'log'}          $forgotpw = '<div class="LC_login_links">'.
        .'</h2>';                      $forgotpw.'</div>';
       }
     my $noscript_warning='<noscript><span class="LC_warning"><b>'      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')      if ($loginhelp) {
                         .'</b></span></noscript>';          $loginhelp = '<div class="LC_login_links">'.
     my $helpdeskscript;                       '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a></div>';
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,      }
                                        $authdomain,\$helpdeskscript,  
                                        $showhelpdesk,\@possdoms);  # ---------------------------------------------------- Serve out DES JavaScript
       {
     my $mobileargs;      my $jsh=Apache::File->new($include."/londes.js");
     if ($clientmobile) {      $r->print(<$jsh>);
         $mobileargs = 'autocapitalize="off" autocorrect="off"';       }
     }  # ---------------------------------------------------------- Serve rest of page
     my $loginform=(<<LFORM);  
 <form name="client" action="" onsubmit="return(send())" id="lclogin">      $r->print(
   <input type="hidden" name="lextkey" value="$lextkey" />      '<div class="LC_Box"'
   <input type="hidden" name="uextkey" value="$uextkey" />     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
   <b><label for="uname">$lt{'un'}</label>:</b><br />  );
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />  
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />      my $target = '_top';
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />      if ($sessiondata{'linkprot'}) {
   <b><label for="udom">$lt{'dom'}</label>:</b><br />          my ($linkprotector,$deeplink) = split(/:/,$sessiondata{'linkprot'},2);
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />          if (($deeplink eq $sessiondata{'origurl'}) &&
   <input type="submit" value="$lt{'log'}" />              (($sessiondata{'linkprotuser'} eq $sessiondata{'username'}.':'.$sessiondata{'domain'}) ||
 </form>               ($sessiondata{'linkprotuser'} eq $sessiondata{'username'}))) {
 LFORM              $target = '_self';
           }
     if ($showbanner) {      }
         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);      $r->print(<<ENDSERVERFORM);
         if ($alttext eq '') {  <form name="server" action="/adm/authenticate" method="post" target="$target">
             $alttext = 'The Learning Online Network with CAPA';     <input type="hidden" name="logtoken" value="$logtoken" />
         }     <input type="hidden" name="serverid" value="$lonhost" />
         $r->print(<<HEADER);     <input type="hidden" name="uname" value="" />
 <!-- The LON-CAPA Header -->     <input type="hidden" name="upass0" value="" />
 <div style="background:$pgbg;margin:0;width:100%;">     <input type="hidden" name="udom" value="" />
   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
 </div>     <input type="hidden" name="localres" value="$env{'form.localres'}" />
 HEADER    </form>
     }  ENDSERVERFORM
       my $coursecatalog;
     my $stdauthformstyle = 'inline-block';      if (($showcoursecat eq '') || ($showcoursecat)) {
     my $ssoauthstyle = 'none';          $coursecatalog = '<div class="LC_login_links">'.
     my $sso_onclick;                           &coursecatalog_link($lt{'catalog'}).'</div>';
     my $logintype;      }
     $r->print('<div style="float:left;margin-top:0;">');      my $newuserlink;
     if ($saml_landing) {      if ($shownewuserlink) {
         $ssoauthstyle = 'inline-block';          $newuserlink = '<div class="LC_login_links">'.
         $stdauthformstyle = 'none';                         &newuser_link($lt{'newuser'}).'</div>';
         $logintype = $samlssotext;      }
         my $ssologin = '/adm/sso';      my $logintitle =
         if ($samlssourl  ne '') {          '<h2 class="LC_hcell"'
             $ssologin = $samlssourl;         .' style="background:'.$loginbox_header_bgcol.';'
         }         .' color:'.$loginbox_header_textcol.'">'
         my $ssologin_for_js = &js_escape($ssologin);         .$lt{'log'}
         my $querystr_for_js;         .'</h2>';
         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {  
             my $querystring;      my $noscript_warning = <<"ENDNOJS";
             if ($env{'form.firsturl'} ne '') {  <div aria-hidden="true" style="padding:0;margin:0;border:0">
                 $querystring = 'origurl=';  <noscript>
                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {  <span style="color: darkred; font-weight: bold;">$lt{'nojs'}</span>
                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});  </noscript>
                 } else {  </div>
                     $querystring .= &uri_escape($env{'form.firsturl'});  <div class="LC_visually_hidden">
                 }  <noscript>
                 $querystring = &HTML::Entities::encode($querystring,"'");  $lt{'nojs'}
             }  </noscript>
             if ($env{'form.ltoken'} ne '') {  </div>
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.  ENDNOJS
                                   &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));      my $helpdeskscript;
             } elsif ($env{'form.linkkey'}) {      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.                                         $authdomain,\$helpdeskscript,
                                   &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));                                         $showhelpdesk,\@possdoms);
             }  
             if ($querystring ne '') {      my $mobileargs;
                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;      if ($clientmobile) {
                 $querystr_for_js = &js_escape($querystring);          $mobileargs = 'autocapitalize="off" autocorrect="off"';
             }      }
         } elsif ($logtoken ne '') {      my $loginform=(<<LFORM);
             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;  <form name="client" action="" onsubmit="return(send())" id="lclogin">
             $querystr_for_js = &js_escape('logtoken='.$logtoken);    <input type="hidden" name="lextkey" value="$lextkey" />
         }    <input type="hidden" name="uextkey" value="$uextkey" />
         my $ssohref;    <b><label for="uname">$lt{'un'}</label>:</b><br />
         if ($samlwindow) {    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
             $sso_onclick = <<"ENDJS";    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
 if (document.getElementById('LC_sso_login_link')) {    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
     var ssoelem = document.getElementById('LC_sso_login_link')    <b><label for="udom">$lt{'dom'}</label>:</b><br />
     ssoelem.addEventListener('click',samlWinFunction,false);    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
     var windows = {};    <input type="submit" value="$lt{'log'}" />
     function samlWinFunction(evt) {  </form>
         evt.preventDefault();  LFORM
         var url = '$ssologin_for_js';  
         var name = 'lcssowin';      if ($showbanner) {
         var querystr = '$querystr_for_js';          my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);
         if (querystr) {          if ($alttext eq '') {
             url += '?'+querystr+'&lcssowin=1';              $alttext = 'The Learning Online Network with CAPA';
         } else {          }
             url += '?lcssowin=1';          $r->print(<<HEADER);
         }  <!-- The LON-CAPA Header -->
         if ((typeof windows[name] !== 'undefined') && (!windows[name].closed)) {  <div style="background:$pgbg;margin:0;width:100%;" role="banner">
             windows[name].close();    <h1 style="padding:0;margin:0">
         }    <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />
         windows[name]=window.open(url,name,'width=350,height=600');    </h1>
         windows[name].focus();  </div>
         return false;  HEADER
     }      } else {
 }          $r->print('<div role="banner" class="LC_visually_hidden" tabindex="-1">'.
 ENDJS                    '<h1>'.&mt('LON-CAPA Login Page').'</h1></div>');
         }      }
         if ($samlssoimg ne '') {  
             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'" id="LC_sso_login_link">'.      my $stdauthformstyle = 'inline-block';
                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';      my $ssoauthstyle = 'none';
         } else {      my $sso_onclick;
             $ssohref = '<a href="'.$ssologin.'" id="LC_sso_login_link">'.$samlssotext.'</a>';      my $logintype;
         }      $r->print('<div style="float:left;margin-top:0;" role="main">');
         if (($env{'form.saml'} eq 'no') ||      if ($saml_landing) {
             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {          $ssoauthstyle = 'inline-block';
             $ssoauthstyle = 'none';          $stdauthformstyle = 'none';
             $stdauthformstyle = 'inline-block';          $logintype = $samlssotext;
             $logintype = $samlnonsso;          my $ssologin = '/adm/sso';
         }          if ($samlssourl  ne '') {
         $r->print(<<ENDSAML);              $ssologin = $samlssourl;
 <p>          }
 Log-in type:          my $ssologin_for_js = &js_escape($ssologin);
 <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />          my $querystr_for_js;
 <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>          if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
 </p>              my $querystring;
 <div style="display:$ssoauthstyle" id="LC_SSO_login">              if ($env{'form.firsturl'} ne '') {
 <div class="LC_Box" style="padding-top: 10px;">                  $querystring = 'origurl=';
 $ssohref                  if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
 $noscript_warning                      $querystring .= &uri_escape_utf8($env{'form.firsturl'});
 </div>                  } else {
 <div class="LC_Box" style="padding-top: 10px;">                      $querystring .= &uri_escape($env{'form.firsturl'});
 $loginhelp                  }
 $contactblock                  $querystring = &HTML::Entities::encode($querystring,"'");
 $coursecatalog              }
 </div>              if ($env{'form.ltoken'} ne '') {
 </div>                  $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.
 ENDSAML                                    &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));
     } else {              } elsif ($env{'form.linkkey'}) {
         if ($env{'form.ltoken'}) {                  $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.
             &Apache::lonnet::tmpdel($env{'form.ltoken'});                                    &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));
             delete($env{'form.ltoken'});              }
         }              if ($querystring ne '') {
     }                  $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;
     my $in_frame_js;                  $querystr_for_js = &js_escape($querystring);
     if ($linkprot_for_login) {              }
         my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);          } elsif ($logtoken ne '') {
         if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {              $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;
             my $set_target;              $querystr_for_js = &js_escape('logtoken='.$logtoken);
             if (($env{'form.retry'}) || ($env{'form.sso'})) {          }
                 if ($linkproturi eq $env{'form.firsturl'}) {          my $ssohref;
                     $set_target = "    document.server.target = '_self';";          if ($samlwindow) {
                 }              $sso_onclick = <<"ENDJS";
             } else {  if (document.getElementById('LC_sso_login_link')) {
                 $set_target = <<ENDTARG;      var ssoelem = document.getElementById('LC_sso_login_link')
     var linkproturi = '$linkproturi';      ssoelem.addEventListener('click',samlWinFunction,false);
     var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');      var windows = {};
     if (linkproturi == path) {      function samlWinFunction(evt) {
         document.server.target = '_self';          evt.preventDefault();
     }          var url = '$ssologin_for_js';
 ENDTARG          var name = 'lcssowin';
             }          var querystr = '$querystr_for_js';
             $in_frame_js = <<ENDJS;          if (querystr) {
 <script type="text/javascript">              url += '?'+querystr+'&lcssowin=1';
 // <![CDATA[          } else {
 if ((window.self !== window.top) && (document.server.target != '_self')) {              url += '?lcssowin=1';
     $set_target          }
     $sso_onclick          if ((typeof windows[name] !== 'undefined') && (!windows[name].closed)) {
 }              windows[name].close();
 // ]]>          }
 </script>          windows[name]=window.open(url,name,'width=350,height=600');
 ENDJS          windows[name].focus();
         }          return false;
     } elsif ($samlwindow) {      }
         $in_frame_js = <<ENDJS;  }
 <script type="text/javascript">  ENDJS
 // <![CDATA[          }
 if ((window.self !== window.top) && (document.server.target != '_self')) {          if ($samlssoimg ne '') {
     $sso_onclick              $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'" id="LC_sso_login_link">'.
 }                         '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';
 // ]]>          } else {
 </script>              $ssohref = '<a href="'.$ssologin.'" id="LC_sso_login_link">'.$samlssotext.'</a>';
 ENDJS          }
     }          if (($env{'form.saml'} eq 'no') ||
               (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {
     $r->print(<<ENDLOGIN);              $ssoauthstyle = 'none';
 <div style="display:$stdauthformstyle;" id="LC_standard_login">              $stdauthformstyle = 'inline-block';
 <div class="LC_Box" style="background:$loginbox_bg;">              $logintype = $samlnonsso;
   $logintitle          }
   $loginform          $r->print(<<ENDSAML);
   $noscript_warning  <p>
 </div>  Log-in type:
     <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />
 <div class="LC_Box" style="padding-top: 10px;">  <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>
   $loginhelp  </p>
   $forgotpw  <div style="display:$ssoauthstyle" id="LC_SSO_login">
   $contactblock  <div class="LC_Box" style="padding-top: 10px;">
   $newuserlink  $ssohref
   $coursecatalog  $noscript_warning
 </div>  </div>
 </div>  <div class="LC_Box" style="padding-top: 10px;">
   $loginhelp
 ENDLOGIN  $contactblock
     $r->print('</div><div>'."\n");  $coursecatalog
     if ($showmainlogo) {  </div>
         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);  </div>
         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");  ENDSAML
     }      } else {
 $r->print(<<ENDTOP);          if ($env{'form.ltoken'}) {
 $announcements              &Apache::lonnet::tmpdel($env{'form.ltoken'});
 </div>              delete($env{'form.ltoken'});
 <hr style="clear:both;" />          }
 ENDTOP      }
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);      my $in_frame_js;
     $domainrow = <<"END";      if ($linkprot_for_login) {
       <tr>          my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);
        <td  align="left" valign="top">          if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {
         <small><b>$lt{'dom'}:&nbsp;</b></small>              my $set_target;
        </td>              if (($env{'form.retry'}) || ($env{'form.sso'})) {
        <td  align="left" valign="top">                  if ($linkproturi eq $env{'form.firsturl'}) {
         <small><tt>&nbsp;$domain</tt></small>                      $set_target = "    document.server.target = '_self';";
        </td>                  }
       </tr>              } else {
 END                  $set_target = <<ENDTARG;
     $serverrow = <<"END";      var linkproturi = '$linkproturi';
       <tr>      var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');
        <td  align="left" valign="top">      if (linkproturi == path) {
         <small><b>$lt{'serv'}:&nbsp;</b></small>          document.server.target = '_self';
        </td>      }
        <td align="left" valign="top">  ENDTARG
         <small><tt>&nbsp;$lonhost ($role)</tt></small>              }
        </td>              $in_frame_js = <<ENDJS;
       </tr>  <script type="text/javascript">
 END  // <![CDATA[
     if ($loadlim) {  if ((window.self !== window.top) && (document.server.target != '_self')) {
         $loadrow = <<"END";      $set_target
       <tr>      $sso_onclick
        <td align="left" valign="top">  }
         <small><b>$lt{'load'}:&nbsp;</b></small>  // ]]>
        </td>  </script>
        <td align="left" valign="top">  ENDJS
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>          }
        </td>      } elsif ($samlwindow) {
       </tr>          $in_frame_js = <<ENDJS;
 END  <script type="text/javascript">
     }  // <![CDATA[
     if ($uloadlim) {  if ((window.self !== window.top) && (document.server.target != '_self')) {
         $userloadrow = <<"END";      $sso_onclick
       <tr>  }
        <td align="left" valign="top">  // ]]>
         <small><b>$lt{'userload'}:&nbsp;</b></small>  </script>
        </td>  ENDJS
        <td align="left" valign="top">      }
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>  
        </td>      $r->print(<<ENDLOGIN);
       </tr>  <div style="display:$stdauthformstyle;" id="LC_standard_login">
 END  <div class="LC_Box" style="background:$loginbox_bg;">
     }    $logintitle
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {    $loginform
         $versionrow = <<"END";    $noscript_warning
       <tr>  </div>
        <td colspan="2" align="left">   
         <small>$version</small>  <div class="LC_Box" style="padding-top: 10px;">
        </td>    $loginhelp
       </tr>    $forgotpw
 END    $contactblock
     }    $newuserlink
     $coursecatalog
     $r->print(<<ENDDOCUMENT);  </div>
     <div style="float: left;">  </div>
      <table border="0" cellspacing="0" cellpadding="0">  
 $domainrow  ENDLOGIN
 $serverrow      $r->print('</div><div>'."\n");
 $loadrow          if ($showmainlogo) {
 $userloadrow          my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);
 $versionrow          $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");
      </table>      }
     </div>  $r->print(<<ENDTOP);
     <div style="float: right;">  $announcements
     $domainlogo  </div>
     </div>  <hr style="clear:both;" />
     <br style="clear:both;" />  ENDTOP
  </div>      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versioninfo);
       $domainrow = <<"END";
 $in_frame_js        <tr>
 <script type="text/javascript">         <th align="left" valign="top">
 // <![CDATA[          <small><b>$lt{'dom'}:&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;$domain</tt></small>
 </script>         </td>
 $helpdeskscript        </tr>
   END
 ENDDOCUMENT      $serverrow = <<"END";
     my %endargs = ( 'noredirectlink' => 1, );        <tr>
     $r->print(&Apache::loncommon::end_page(\%endargs));         <th align="left" valign="top">
     return OK;          <small><b>$lt{'serv'}:&nbsp;</b></small>
 }         </th>
          <td align="left" valign="top">
 sub check_loginvia {          <small><tt>&nbsp;$lonhost ($role)</tt></small>
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;         </td>
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {        </tr>
         return;  END
     }      if ($loadlim) {
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);          $loadrow = <<"END";
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};        <tr>
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};         <th align="left" valign="top">
     my $output;          <small><b>$lt{'load'}:&nbsp;</b></small>
     if ($loginvia ne '') {         </th>
         my $noredirect;         <td align="left" valign="top">
         my $ip = &Apache::lonnet::get_requestor_ip();          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
         if ($ip eq '127.0.0.1') {         </td>
             $noredirect = 1;        </tr>
         } else {  END
             if ($loginvia_exempt ne '') {      }
                 my @exempt = split(',',$loginvia_exempt);      if ($uloadlim) {
                 if (grep(/^\Q$ip\E$/,@exempt)) {          $userloadrow = <<"END";
                     $noredirect = 1;        <tr>
                 }         <th align="left" valign="top">
             }          <small><b>$lt{'userload'}:&nbsp;</b></small>
         }         </th>
         unless ($noredirect) {         <td align="left" valign="top">
             my ($newhost,$path);          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
             if ($loginvia =~ /:/) {         </td>
                 ($newhost,$path) = split(':',$loginvia);        </tr>
             } else {  END
                 $newhost = $loginvia;      }
             }      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
             if ($newhost ne $lonhost) {          $versioninfo = "<small>$version</small>";
                 if (&Apache::lonnet::hostname($newhost) ne '') {      }
                     if ($balcookie) {  
                         my ($balancer,$cookie) = split(/:/,$balcookie);      $r->print(<<ENDDOCUMENT);
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {      <div class="LC_landmark" role="contentinfo">
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);      <div style="float: left;">
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {       <table border="0" cellspacing="0" cellpadding="0">
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {  $domainrow
                                     while (my $filename=readdir($dh)) {  $serverrow
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {  $loadrow    
                                             my $handle = $1;  $userloadrow
                                             my %hash =       </table>
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,      $versioninfo
                                                                                      ['request.balancercookie',      </div>
                                                                                       'user.linkedenv']);      <div style="float: right;">
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {      $domainlogo
                                                 if (unlink("$lonidsdir/$filename")) {      </div>
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&      </div>
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&      <br style="clear:both;" />
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {   </div>
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");  
                                                     }  $in_frame_js
                                                 }  <script type="text/javascript">
                                             }  // <![CDATA[
                                             last;  // the if prevents the script error if the browser can not handle this
                                         }  if ( document.client.uname ) { document.client.uname.focus(); }
                                     }  // ]]>
                                     closedir($dh);  </script>
                                 }  $helpdeskscript
                             }  
                         }  ENDDOCUMENT
                     }      my %endargs = ( 'noredirectlink' => 1, );
                     $output = &redirect_page($newhost,$path);      $r->print(&Apache::loncommon::end_page(\%endargs));
                 }      return OK;
             }  }
         }  
     }  sub check_loginvia {
     return $output;      my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;
 }      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
           return;
 sub redirect_page {      }
     my ($desthost,$path) = @_;      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
     my $hostname = &Apache::lonnet::hostname($desthost);      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
     my $protocol = $Apache::lonnet::protocol{$desthost};      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
     $protocol = 'http' if ($protocol ne 'https');      my $output;
     unless ($path =~ m{^/}) {      if ($loginvia ne '') {
         $path = '/'.$path;          my $noredirect;
     }          my $ip = &Apache::lonnet::get_requestor_ip();  
     my $url = $protocol.'://'.$hostname.$path;          if ($ip eq '127.0.0.1') {
     my $args = {};              $noredirect = 1;
     if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {          } else {
         $url = $protocol.'://'.$hostname.$env{'form.firsturl'};              if ($loginvia_exempt ne '') {
         if (($env{'form.ltoken'}) || ($env{'form.linkprot'} ne '') ||                  my @exempt = split(',',$loginvia_exempt);
             ($env{'form.linkkey'} ne '')) {                  if (grep(/^\Q$ip\E$/,@exempt)) {
             my %link_info;                      $noredirect = 1;
             if ($env{'form.ltoken'}) {                  }
                 %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});              }
                 &Apache::lonnet::tmpdel($env{'form.ltoken'});          }
                 $args->{'only_body'} = 1;          unless ($noredirect) {
             } elsif ($env{'form.linkprot'}) {              my ($newhost,$path);
                 $link_info{'linkprot'} = $env{'form.linkprot'};              if ($loginvia =~ /:/) {
                 foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {                  ($newhost,$path) = split(':',$loginvia);
                     if ($env{'form.'.$item}) {              } else {
                         $link_info{$item} = $env{'form.'.$item};                  $newhost = $loginvia;
                     }              }
                 }              if ($newhost ne $lonhost) {
                 $args->{'only_body'} = 1;                  if (&Apache::lonnet::hostname($newhost) ne '') {
             } elsif ($env{'form.linkkey'} ne '') {                      if ($balcookie) {
                 $link_info{'linkkey'} = $env{'form.linkkey'};                          my ($balancer,$cookie) = split(/:/,$balcookie);
             }                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
             my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
             unless (($token eq 'con_lost') || ($token eq 'refused') ||                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
                     ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {                                  if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
                 $url .= '?ltoken='.$token;                                      while (my $filename=readdir($dh)) {
             }                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
         }                                              my $handle = $1;
     } else {                                              my %hash =
         my $querystring;                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
         if ($env{'form.firsturl'} ne '') {                                                                                       ['request.balancercookie',
             if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {                                                                                        'user.linkedenv']);
                 $querystring = &uri_escape_utf8($env{'form.firsturl'});                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
             } else {                                                  if (unlink("$lonidsdir/$filename")) {
                 $querystring = &uri_escape($env{'form.firsturl'});                                                      if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
             }                                                          (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
             $querystring = &HTML::Entities::encode($querystring,"'");                                                          (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
             $querystring = '?firsturl='.$querystring;                                                          unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
         }                                                      }
         if ($env{'form.ltoken'}) {                                                  }
             my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});                                              }
             &Apache::lonnet::tmpdel($env{'form.ltoken'});                                              last;
             my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');                                          }
             unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||                                      }
                     ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {                                      closedir($dh);
                 unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {                                  }
                     $url = $protocol.'://'.$hostname.'/adm/roles';                              }
                 }                          }
                 $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;                      }
             }                      $output = &redirect_page($newhost,$path);
         }                  }
         $url .= $querystring;              }
     }          }
     $args->{'redirect'} = [0,$url,'','',1];      }
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,$args);      return $output;
     my $end_page   = &Apache::loncommon::end_page();  }
     return $start_page.$end_page;  
 }  sub redirect_page {
       my ($desthost,$path) = @_;
 sub contactdisplay {      my $hostname = &Apache::lonnet::hostname($desthost);
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,      my $protocol = $Apache::lonnet::protocol{$desthost};
         $possdoms) = @_;      $protocol = 'http' if ($protocol ne 'https');
     my $contactblock;      unless ($path =~ m{^/}) {
     my $origmail;          $path = '/'.$path;
     if (ref($possdoms) eq 'ARRAY') {      }
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {       my $url = $protocol.'://'.$hostname.$path;
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      my $args = {};
         }      if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     }          $url = $protocol.'://'.$hostname.$env{'form.firsturl'};
     my $requestmail =           if (($env{'form.ltoken'}) || ($env{'form.linkprot'} ne '') ||
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',              ($env{'form.linkkey'} ne '')) {
                                                  $authdomain,$origmail);              my %link_info;
     unless ($showhelpdesk eq '0') {              if ($env{'form.ltoken'}) {
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {                  %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
             $showhelpdesk = 1;                  &Apache::lonnet::tmpdel($env{'form.ltoken'});
         } else {                  $args->{'only_body'} = 1;
             $showhelpdesk = 0;              } elsif ($env{'form.linkprot'}) {
         }                  $link_info{'linkprot'} = $env{'form.linkprot'};
     }                  foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {
     if ($servadm && $showadminmail) {                      if ($env{'form.'.$item}) {
         $contactblock .= $$lt{'servadm'}.':<br />'.                          $link_info{$item} = $env{'form.'.$item};
                          '<tt>'.$servadm.'</tt><br />';                      }
     }                  }
     if ($showhelpdesk) {                  $args->{'only_body'} = 1;
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';              } elsif ($env{'form.linkkey'} ne '') {
         my $thisurl = &escape('/adm/login');                  $link_info{'linkkey'} = $env{'form.linkkey'};
         $$helpdeskscript = <<"ENDSCRIPT";              }
 <script type="text/javascript">              my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
 // <![CDATA[              unless (($token eq 'con_lost') || ($token eq 'refused') ||
 function helpdesk() {                      ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
     var possdom = document.client.udom.value;                  $url .= '?ltoken='.$token;
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');              }
     if (codedom == '') {          }
         codedom = "$authdomain";      } else {
     }          my $querystring;
     var querystr = "origurl=$thisurl&codedom="+codedom;          if ($env{'form.firsturl'} ne '') {
     document.location.href = "/adm/helpdesk?"+querystr;              if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
     return;                  $querystring = &uri_escape_utf8($env{'form.firsturl'});
 }              } else {
 // ]]>                  $querystring = &uri_escape($env{'form.firsturl'});
 </script>              }
 ENDSCRIPT              $querystring = &HTML::Entities::encode($querystring,"'");
     }              $querystring = '?firsturl='.$querystring;
     return $contactblock;          }
 }          if ($env{'form.ltoken'}) {
               my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
 sub forgotpwdisplay {              &Apache::lonnet::tmpdel($env{'form.ltoken'});
     my (%lt) = @_;              my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
     my $prompt_for_resetpw = 1;               unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||
     if ($prompt_for_resetpw) {                      ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';                  unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {
     }                      $url = $protocol.'://'.$hostname.'/adm/roles';
     return;                  }
 }                  $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;
               }
 sub coursecatalog_link {          }
     my ($linkname) = @_;          $url .= $querystring;
     return <<"END";      }
       <a href="/adm/coursecatalog">$linkname</a>      $args->{'redirect'} = [0,$url,'','',1];
 END      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,$args);
 }      my $end_page   = &Apache::loncommon::end_page();
       return $start_page.$end_page;
 sub newuser_link {  }
     my ($linkname) = @_;  
     return '<a href="/adm/createaccount">'.$linkname.'</a>';  sub contactdisplay {
 }      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
           $possdoms) = @_;
 sub decode_token {      my $contactblock;
     my ($info) = @_;      my $origmail;
     my ($firsturl,@rest)=split(/\&/,$info);      if (ref($possdoms) eq 'ARRAY') {
     my %form;          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
     if ($firsturl ne '') {              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
         $form{'firsturl'} = &unescape($firsturl);          }
     }      }
     foreach my $item (@rest) {      my $requestmail =
         my ($key,$value) = split(/=/,$item);          &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
         $form{$key} = &unescape($value);                                                   $authdomain,$origmail);
     }      unless ($showhelpdesk eq '0') {
     return %form;          if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
 }              $showhelpdesk = 1;
           } else {
 1;              $showhelpdesk = 0;
 __END__          }
       }
       if ($servadm && $showadminmail) {
           $contactblock = '<div class="LC_login_links">'.$lt->{'servadm'}.':<br />'.
                           '<tt>'.$servadm.'</tt></div>';
       }
       if ($showhelpdesk) {
           $contactblock .= '<div class="LC_login_links">'.
                            '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a></div>';
           my $thisurl = &escape('/adm/login');
           $$helpdeskscript = <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function helpdesk() {
       var possdom = document.client.udom.value;
       var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
       if (codedom == '') {
           codedom = "$authdomain";
       }
       var querystr = "origurl=$thisurl&codedom="+codedom;
       document.location.href = "/adm/helpdesk?"+querystr;
       return;
   }
   // ]]>
   </script>
   ENDSCRIPT
       }
       return $contactblock;
   }
   
   sub forgotpwdisplay {
       my (%lt) = @_;
       my $prompt_for_resetpw = 1;
       if ($prompt_for_resetpw) {
           return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
       }
       return;
   }
   
   sub coursecatalog_link {
       my ($linkname) = @_;
       return <<"END";
         <a href="/adm/coursecatalog">$linkname</a>
   END
   }
   
   sub newuser_link {
       my ($linkname) = @_;
       return '<a href="/adm/createaccount">'.$linkname.'</a>';
   }
   
   sub decode_token {
       my ($info) = @_;
       my ($firsturl,@rest)=split(/\&/,$info);
       my %form;
       if ($firsturl ne '') {
           $form{'firsturl'} = &unescape($firsturl);
       }
       foreach my $item (@rest) {
           my ($key,$value) = split(/=/,$item);
           $form{$key} = &unescape($value);
       }
       return %form;
   }
   
   1;
   __END__

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


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