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

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

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


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