Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.10 and 1.207

version 1.158.2.13.2.10, 2023/07/05 17:03:27 version 1.207, 2023/11/21 19:52:18
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Login Screen  # Login Screen
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonlogin;  package Apache::lonlogin;
   
 use strict;  use strict;
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use Apache::File ();  use Apache::File ();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonauth();  use Apache::lonauth();
 use Apache::lonlocal;  use Apache::lonlocal;
 use Apache::migrateuser();  use Apache::migrateuser();
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
 use URI::Escape;  use URI::Escape;
 use HTML::Entities();  use HTML::Entities();
 use CGI::Cookie();  use CGI::Cookie();
     
 sub handler {  sub handler {
     my $r = shift;      my $r = shift;
   
     &Apache::loncommon::get_unprocessed_cgi      &Apache::loncommon::get_unprocessed_cgi
  (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},   (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},
       $ENV{'REDIRECT_QUERY_STRING'}),        $ENV{'REDIRECT_QUERY_STRING'}),
  ['interface','username','domain','firsturl','localpath','localres',   ['interface','username','domain','firsturl','localpath','localres',
   'token','role','symb','iptoken','btoken','ltoken','ttoken','linkkey',    'token','role','symb','iptoken','btoken','ltoken','ttoken','linkkey',
           'saml','sso','retry','display']);            'saml','sso','retry','display']);
   
 # -- check if they are a migrating user  # -- check if they are a migrating user
     if (defined($env{'form.token'})) {      if (defined($env{'form.token'})) {
  return &Apache::migrateuser::handler($r);          return &Apache::migrateuser::handler($r);
     }      }
   
     my $lonhost = $r->dir_config('lonHostID');      my $lonhost = $r->dir_config('lonHostID');
     if ($env{'form.ttoken'}) {      if ($env{'form.ttoken'}) {
         my %info = &Apache::lonnet::tmpget($env{'form.ttoken'});          my %info = &Apache::lonnet::tmpget($env{'form.ttoken'});
         &Apache::lonnet::tmpdel($env{'form.ttoken'});          &Apache::lonnet::tmpdel($env{'form.ttoken'});
         if ($info{'origurl'}) {          if ($info{'origurl'}) {
             $env{'form.firsturl'} = $info{'origurl'};              $env{'form.firsturl'} = $info{'origurl'};
         }          }
         if ($info{'ltoken'}) {          if ($info{'ltoken'}) {
             $env{'form.ltoken'} = $info{'ltoken'};              $env{'form.ltoken'} = $info{'ltoken'};
         } elsif ($info{'linkprot'}) {          } elsif ($info{'linkprot'}) {
             $env{'form.linkprot'} = $info{'linkprot'};              $env{'form.linkprot'} = $info{'linkprot'};
             foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {              foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {
                 if ($info{$item} ne '') {                  if ($info{$item} ne '') {
                     $env{'form.'.$item} = $info{$item};                      $env{'form.'.$item} = $info{$item};
                 }                  }
             }              }
         } elsif ($info{'linkkey'} ne '') {          } elsif ($info{'linkkey'} ne '') {
             $env{'form.linkkey'} = $info{'linkkey'};              $env{'form.linkkey'} = $info{'linkkey'};
         }          }
     } elsif (($env{'form.sso'}) || ($env{'form.retry'})) {      } elsif (($env{'form.sso'}) || ($env{'form.retry'})) {
         my $infotoken;          my $infotoken;
         if ($env{'form.sso'}) {          if ($env{'form.sso'}) {
             $infotoken = $env{'form.sso'};              $infotoken = $env{'form.sso'};
         } else {          } else {
             $infotoken = $env{'form.retry'};              $infotoken = $env{'form.retry'};
         }          }
         my $data = &Apache::lonnet::reply('tmpget:'.$infotoken,$lonhost);          my $data = &Apache::lonnet::reply('tmpget:'.$infotoken,$lonhost);
         unless (($data=~/^error/) || ($data eq 'con_lost') ||          unless (($data=~/^error/) || ($data eq 'con_lost') ||
                 ($data eq 'no_such_host')) {                  ($data eq 'no_such_host')) {
             my %info = &decode_token($data);              my %info = &decode_token($data);
             foreach my $item (keys(%info)) {              foreach my $item (keys(%info)) {
                 $env{'form.'.$item} = $info{$item};                  $env{'form.'.$item} = $info{$item};
             }              }
             &Apache::lonnet::tmpdel($infotoken);              &Apache::lonnet::tmpdel($infotoken);
         }          }
     } else {      } else {
         if (!defined($env{'form.firsturl'})) {          if (!defined($env{'form.firsturl'})) {
             &Apache::lonacc::get_posted_cgi($r,['firsturl']);              &Apache::lonacc::get_posted_cgi($r,['firsturl']);
         }          }
         if (!defined($env{'form.firsturl'})) {          if (!defined($env{'form.firsturl'})) {
             if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {              if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {
                 $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};                  $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};
             }              }
         }          }
         if (($env{'form.firsturl'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) &&          if (($env{'form.firsturl'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) &&
             (!$env{'form.ltoken'}) && (!$env{'form.linkprot'}) && (!$env{'form.linkkey'})) {              (!$env{'form.ltoken'}) && (!$env{'form.linkprot'}) && (!$env{'form.linkkey'})) {
             &Apache::lonacc::get_posted_cgi($r,['linkkey']);              &Apache::lonacc::get_posted_cgi($r,['linkkey']);
         }          }
         if ($env{'form.firsturl'} eq '/adm/logout') {          if ($env{'form.firsturl'} eq '/adm/logout') {
             delete($env{'form.firsturl'});              delete($env{'form.firsturl'});
         }          }
     }      }
   
 # For "public user" - remove any exising "public" cookie, as user really wants to log-in  # For "public user" - remove any exising "public" cookie, as user really wants to log-in
     my ($handle,$lonidsdir,$expirepub,$userdom);      my ($handle,$lonidsdir,$expirepub,$userdom);
     $lonidsdir=$r->dir_config('lonIDsDir');      $lonidsdir=$r->dir_config('lonIDsDir');
     unless ($r->header_only) {      unless ($r->header_only) {
         $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);          $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);
         if ($handle ne '') {          if ($handle ne '') {
             if ($handle=~/^publicuser\_/) {              if ($handle=~/^publicuser\_/) {
                 unlink($r->dir_config('lonIDsDir')."/$handle.id");                  unlink($r->dir_config('lonIDsDir')."/$handle.id");
                 undef($handle);                  undef($handle);
                 undef($userdom);                  undef($userdom);
                 $expirepub = 1;                  $expirepub = 1;
             }              }
         }          }
     }      }
   
     &Apache::loncommon::no_cache($r);      &Apache::loncommon::no_cache($r);
     &Apache::lonlocal::get_language_handle($r);      &Apache::lonlocal::get_language_handle($r);
     &Apache::loncommon::content_type($r,'text/html');      &Apache::loncommon::content_type($r,'text/html');
     if ($expirepub) {      if ($expirepub) {
         my $c = new CGI::Cookie(-name    => 'lonPubID',          my $c = new CGI::Cookie(-name    => 'lonPubID',
                                 -value   => '',                                  -value   => '',
                                 -expires => '-10y',);                                  -expires => '-10y',);
         $r->header_out('Set-cookie' => $c);          $r->header_out('Set-cookie' => $c);
     } elsif (($handle eq '') && ($userdom ne '')) {      } elsif (($handle eq '') && ($userdom ne '')) {
         my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));          my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
         foreach my $name (keys(%cookies)) {          foreach my $name (keys(%cookies)) {
             next unless ($name =~ /^lon(|S|Link|Pub)ID$/);              next unless ($name =~ /^lon(|S|Link|Pub)ID$/);
             my $c = new CGI::Cookie(-name    => $name,              my $c = new CGI::Cookie(-name    => $name,
                                     -value   => '',                                      -value   => '',
                                     -expires => '-10y',);                                      -expires => '-10y',);
             $r->headers_out->add('Set-cookie' => $c);              $r->headers_out->add('Set-cookie' => $c);
         }          }
     }      }
     $r->send_http_header;      $r->send_http_header;
     return OK if $r->header_only;      return OK if $r->header_only;
   
   
 # Are we re-routing?  # Are we re-routing?
     my $londocroot = $r->dir_config('lonDocRoot');       my $londocroot = $r->dir_config('lonDocRoot');
     if (-e "$londocroot/lon-status/reroute.txt") {      if (-e "$londocroot/lon-status/reroute.txt") {
  &Apache::lonauth::reroute($r);   &Apache::lonauth::reroute($r);
  return OK;   return OK;
     }      }
   
 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)  # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
   
     my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);      my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);
     if ($found_server) {      if ($found_server) {
         my $hostname = &Apache::lonnet::hostname($found_server);          my $hostname = &Apache::lonnet::hostname($found_server);
         if ($hostname ne '') {          if ($hostname ne '') {
             my $protocol = $Apache::lonnet::protocol{$found_server};              my $protocol = $Apache::lonnet::protocol{$found_server};
             $protocol = 'http' if ($protocol ne 'https');              $protocol = 'http' if ($protocol ne 'https');
             my $dest = '/adm/roles';              my $dest = '/adm/roles';
             if ($env{'form.firsturl'} ne '') {              if ($env{'form.firsturl'} ne '') {
                 $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');                  $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');
             }              }
             my %info = (              my %info = (
                          balcookie => $lonhost.':'.$balancer_cookie,                           balcookie => $lonhost.':'.$balancer_cookie,
                        );                         );
             if ($env{'form.role'}) {              if ($env{'form.role'}) {
                 $info{'role'} = $env{'form.role'};                  $info{'role'} = $env{'form.role'};
             }              }
             if ($env{'form.symb'}) {              if ($env{'form.symb'}) {
                 $info{'symb'} = $env{'form.symb'};                  $info{'symb'} = $env{'form.symb'};
             }              }
             if (($env{'form.firsturl'} eq '/adm/email') && ($env{'form.display'} ne '')) {              if (($env{'form.firsturl'} eq '/adm/email') && ($env{'form.display'} ne '')) {
                 if ($env{'form.sso'}) {                  if ($env{'form.sso'}) {
                     if ($env{'form.mailrecip'}) {                      if ($env{'form.mailrecip'}) {
                         $info{'display'} = &escape($env{'form.display'});                          $info{'display'} = &escape($env{'form.display'});
                         $info{'mailrecip'} = &escape($env{'form.mailrecip'});                          $info{'mailrecip'} = &escape($env{'form.mailrecip'});
                     }                      }
                 } else {                  } else {
                     if (($env{'form.username'}) && ($env{'form.domain'})) {                      if (($env{'form.username'}) && ($env{'form.domain'})) {
                         $info{'display'} = &escape($env{'form.display'});                          $info{'display'} = &escape($env{'form.display'});
                         $info{'mailrecip'} = &escape($env{'form.username'}.':'.$env{'form.domain'});                          $info{'mailrecip'} = &escape($env{'form.username'}.':'.$env{'form.domain'});
                     }                      }
                 }                  }
             }              }
             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);              my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);
             unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||              unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||
                     ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {                      ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {
                 $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;                  $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;
             }              }
             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {              if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                 my %link_info;                  my %link_info;
                 if ($env{'form.ltoken'}) {                  if ($env{'form.ltoken'}) {
                     $link_info{'ltoken'} = $env{'form.ltoken'};                      $link_info{'ltoken'} = $env{'form.ltoken'};
                 } elsif ($env{'form.linkprot'}) {                  } elsif ($env{'form.linkprot'}) {
                     $link_info{'linkprot'} = $env{'form.linkprot'};                      $link_info{'linkprot'} = $env{'form.linkprot'};
                     foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {                      foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {
                         if ($env{'form.'.$item} ne '') {                          if ($env{'form.'.$item} ne '') {
                             $link_info{$item} = $env{'form.'.$item};                              $link_info{$item} = $env{'form.'.$item};
                         }                          }
                     }                      }
                 } elsif ($env{'form.linkkey'} ne '') {                  } elsif ($env{'form.linkkey'} ne '') {
                     $link_info{'linkkey'} = $env{'form.linkkey'};                      $link_info{'linkkey'} = $env{'form.linkkey'};
                 }                  }
                 if (keys(%link_info)) {                  if (keys(%link_info)) {
                     $link_info{'origurl'} = $env{'form.firsturl'};                      $link_info{'origurl'} = $env{'form.firsturl'};
                     my $token = &Apache::lonnet::tmpput(\%link_info,$found_server,'link');                      my $token = &Apache::lonnet::tmpput(\%link_info,$found_server,'link');
                     unless (($token eq 'con_lost') || ($token eq 'refused') ||                      unless (($token eq 'con_lost') || ($token eq 'refused') ||
                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {                              ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                         $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'ttoken='.$token;                          $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'ttoken='.$token;
                     }                      }
                 }                  }
             }              }
             unless ($found_server eq $lonhost) {              unless ($found_server eq $lonhost) {
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);                  my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);
                 $hostname = $alias if ($alias ne '');                  $hostname = $alias if ($alias ne '');
             }              }
             my $url = $protocol.'://'.$hostname.$dest;              my $url = $protocol.'://'.$hostname.$dest;
             my $start_page =              my $start_page =
                 &Apache::loncommon::start_page('Switching Server ...',undef,                  &Apache::loncommon::start_page('Switching Server ...',undef,
                                                {'redirect'       => [0,$url],});                                                 {'redirect'       => [0,$url],});
             my $end_page   = &Apache::loncommon::end_page();              my $end_page   = &Apache::loncommon::end_page();
             $r->print($start_page.$end_page);              $r->print($start_page.$end_page);
             return OK;              return OK;
         }          }
     }      }
   
 #  #
 # Check if a LON-CAPA load balancer sent user here because user's browser sent  # Check if a LON-CAPA load balancer sent user here because user's browser sent
 # it a balancer cookie for an active session on this server.  # it a balancer cookie for an active session on this server.
 #  #
   
     my $balcookie;      my $balcookie;
     if ($env{'form.btoken'}) {      if ($env{'form.btoken'}) {
         my %info = &Apache::lonnet::tmpget($env{'form.btoken'});          my %info = &Apache::lonnet::tmpget($env{'form.btoken'});
         $balcookie = $info{'balcookie'};          $balcookie = $info{'balcookie'};
         &Apache::lonnet::tmpdel($env{'form.btoken'});          &Apache::lonnet::tmpdel($env{'form.btoken'});
         delete($env{'form.btoken'});          delete($env{'form.btoken'});
         if (($env{'form.firsturl'} eq '/adm/email') &&          if (($env{'form.firsturl'} eq '/adm/email') &&
             (exists($info{'display'})) && (exists($info{'mailrecip'}))) {              (exists($info{'display'})) && (exists($info{'mailrecip'}))) {
             $env{'form.display'} = &unescape($info{'display'});              $env{'form.display'} = &unescape($info{'display'});
             $env{'form.mailrecip'} = &unescape($info{'mailrecip'});              $env{'form.mailrecip'} = &unescape($info{'mailrecip'});
         }          }
     }      }
   
 #  #
 # 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,$linkprotpbid,$linkprotpburl);
             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 '') {                  if ($info{'linkprotpbid'} ne '') {
                     $linkprotpbid = $info{'linkprotpbid'};                      $linkprotpbid = $info{'linkprotpbid'};
                 }                  }
                 if ($info{'linkprotpburl'} ne '') {                  if ($info{'linkprotpburl'} ne '') {
                     $linkprotpburl = $info{'linkprotpburl'};                      $linkprotpburl = $info{'linkprotpburl'};
                 }                  }
             } else {              } else {
                 $linkprot = $env{'form.linkprot'};                  $linkprot = $env{'form.linkprot'};
                 $linkprotuser = $env{'form.linkprotuser'};                  $linkprotuser = $env{'form.linkprotuser'};
                 $linkprotexit = $env{'form.linkprotexit'};                  $linkprotexit = $env{'form.linkprotexit'};
                 $linkprotpbid = $env{'form.linkprotpbid'};                  $linkprotpbid = $env{'form.linkprotpbid'};
                 $linkprotpburl = $env{'form.linkprotpburl'};                  $linkprotpburl = $env{'form.linkprotpburl'};
             }              }
             if ($linkprot) {              if ($linkprot) {
                 my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);                  my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);
                 if (($deeplink =~ m{^/tiny/$match_domain/\w+$}) &&                  if (($deeplink =~ m{^/tiny/$match_domain/\w+$}) &&
                     ($linkprotuser ne '') && ($linkprotuser ne $env{'user.name'}.':'.$env{'user.domain'})) {                      ($linkprotuser ne '') && ($linkprotuser ne $env{'user.name'}.':'.$env{'user.domain'})) {
                     my $ip = &Apache::lonnet::get_requestor_ip();                      my $ip = &Apache::lonnet::get_requestor_ip();
                     my %linkprotinfo = (                      my %linkprotinfo = (
                                           origurl => $deeplink,                                            origurl => $deeplink,
                                           linkprot => $linkprot,                                            linkprot => $linkprot,
                                           linkprotuser => $linkprotuser,                                            linkprotuser => $linkprotuser,
                                           linkprotexit => $linkprotexit,                                            linkprotexit => $linkprotexit,
                                           linkprotpbid => $linkprotpbid,                                            linkprotpbid => $linkprotpbid,
                                           linkprotpburl => $linkprotpburl,                                            linkprotpburl => $linkprotpburl,
                                        );                                         );
                     if ($env{'form.ltoken'}) {                      if ($env{'form.ltoken'}) {
                         my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});                          my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
                     }                      }
                     &Apache::migrateuser::logout($r,$ip,$handle,undef,undef,\%linkprotinfo);                      &Apache::migrateuser::logout($r,$ip,$handle,undef,undef,\%linkprotinfo);
                     return OK;                      return OK;
                 }                  }
                 if ($env{'user.linkprotector'}) {                  if ($env{'user.linkprotector'}) {
                     my @protectors = split(/,/,$env{'user.linkprotector'});                      my @protectors = split(/,/,$env{'user.linkprotector'});
                     unless (grep(/^\Q$linkprotector\E$/,@protectors)) {                      unless (grep(/^\Q$linkprotector\E$/,@protectors)) {
                         push(@protectors,$linkprotector);                          push(@protectors,$linkprotector);
                         @protectors = sort { $a <=> $b } @protectors;                          @protectors = sort { $a <=> $b } @protectors;
                         &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});                          &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});
                     }                      }
                 } else {                  } else {
                     &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });                      &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });
                 }                  }
                 if ($env{'user.linkproturi'}) {                  if ($env{'user.linkproturi'}) {
                     my @proturis = split(/,/,$env{'user.linkproturi'});                      my @proturis = split(/,/,$env{'user.linkproturi'});
                     unless (grep(/^\Q$deeplink\E$/,@proturis)) {                      unless (grep(/^\Q$deeplink\E$/,@proturis)) {
                         push(@proturis,$deeplink);                          push(@proturis,$deeplink);
                         @proturis = sort @proturis;                          @proturis = sort @proturis;
                         &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});                          &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});
                     }                      }
                 } else {                  } else {
                     &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});                      &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});
                 }                  }
             }              }
         } elsif ($env{'form.linkkey'} ne '') {          } elsif ($env{'form.linkkey'} ne '') {
             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {              if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                 my $linkkey = $env{'form.linkkey'};                  my $linkkey = $env{'form.linkkey'};
                 if ($env{'user.deeplinkkey'}) {                  if ($env{'user.deeplinkkey'}) {
                     my @linkkeys = split(/,/,$env{'user.deeplinkkey'});                      my @linkkeys = split(/,/,$env{'user.deeplinkkey'});
                     unless (grep(/^\Q$linkkey\E$/,@linkkeys)) {                      unless (grep(/^\Q$linkkey\E$/,@linkkeys)) {
                         push(@linkkeys,$linkkey);                          push(@linkkeys,$linkkey);
                         &Apache::lonnet::appenv({'user.deeplinkkey' => join(',',sort(@linkkeys))});                          &Apache::lonnet::appenv({'user.deeplinkkey' => join(',',sort(@linkkeys))});
                     }                      }
                 } else {                  } else {
                     &Apache::lonnet::appenv({'user.deeplinkkey' => $linkkey});                      &Apache::lonnet::appenv({'user.deeplinkkey' => $linkkey});
                 }                  }
                 my $deeplink = $env{'form.firsturl'};                  my $deeplink = $env{'form.firsturl'};
                 if ($env{'user.keyedlinkuri'}) {                  if ($env{'user.keyedlinkuri'}) {
                     my @keyeduris = split(/,/,$env{'user.keyedlinkuri'});                      my @keyeduris = split(/,/,$env{'user.keyedlinkuri'});
                     unless (grep(/^\Q$deeplink\E$/,@keyeduris)) {                      unless (grep(/^\Q$deeplink\E$/,@keyeduris)) {
                         push(@keyeduris,$deeplink);                          push(@keyeduris,$deeplink);
                         &Apache::lonnet::appenv({'user.keyedlinkuri' => join(',',sort(@keyeduris))});                          &Apache::lonnet::appenv({'user.keyedlinkuri' => join(',',sort(@keyeduris))});
                     }                      }
                 } else {                  } else {
                     &Apache::lonnet::appenv({'user.keyedlinkuri' => $deeplink});                      &Apache::lonnet::appenv({'user.keyedlinkuri' => $deeplink});
                 }                  }
             }              }
         }          }
         if ($env{'form.ltoken'}) {          if ($env{'form.ltoken'}) {
             my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});              my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
         }          }
         if (($env{'form.firsturl'} eq '/adm/email') && ($env{'form.display'})) {          if (($env{'form.firsturl'} eq '/adm/email') && ($env{'form.display'})) {
             if ($env{'form.mailrecip'}) {              if ($env{'form.mailrecip'}) {
                 if ($env{'form.mailrecip'} eq "$env{'user.name'}:$env{'user.domain'}") {                  if ($env{'form.mailrecip'} eq "$env{'user.name'}:$env{'user.domain'}") {
                     $dest .= (($dest=~/\?/)?'&amp;':'?') . 'display='.&escape($env{'form.display'}).                      $dest .= (($dest=~/\?/)?'&amp;':'?') . 'display='.&escape($env{'form.display'}).
                                                            '&amp;mailrecip='.&escape($env{'form.mailrecip'});                                                             '&amp;mailrecip='.&escape($env{'form.mailrecip'});
                 }                  }
             } elsif (($env{'form.username'} eq $env{'user.name'}) && ($env{'form.domain'} eq $env{'user.domain'})) {              } elsif (($env{'form.username'} eq $env{'user.name'}) && ($env{'form.domain'} eq $env{'user.domain'})) {
                 $dest .= (($dest=~/\?/)?'&amp;':'?') . 'display='.&escape($env{'form.display'}).                  $dest .= (($dest=~/\?/)?'&amp;':'?') . 'display='.&escape($env{'form.display'}).
                                                        '&amp;mailrecip='.&escape("$env{'user.name'}:$env{'form.domain'}");                                                         '&amp;mailrecip='.&escape("$env{'user.name'}:$env{'form.domain'}");
             }              }
         }          }
  $r->print(   $r->print(
               $start_page                    $start_page
              .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
              .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',                   .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',
               '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'                    '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'
              .$end_page                   .$end_page
              );                   );
         return OK;          return OK;
     }      }
   
 # ---------------------------------------------------- No valid token, continue  # ---------------------------------------------------- No valid token, continue
   
 # ---------------------------- Not possible to really login to domain "public"  # ---------------------------- Not possible to really login to domain "public"
     if ($env{'form.domain'} eq 'public') {      if ($env{'form.domain'} eq 'public') {
  $env{'form.domain'}='';   $env{'form.domain'}='';
  $env{'form.username'}='';   $env{'form.username'}='';
     }      }
   
 # ------ Is this page requested because /adm/migrateuser detected an IP change?  # ------ Is this page requested because /adm/migrateuser detected an IP change?
     my %sessiondata;      my %sessiondata;
     if ($env{'form.iptoken'}) {      if ($env{'form.iptoken'}) {
         %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});          %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});
         unless ($sessiondata{'sessionserver'}) {          unless ($sessiondata{'sessionserver'}) {
             my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});              my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});
             delete($env{'form.iptoken'});              delete($env{'form.iptoken'});
         }          }
     }      }
 # ----------------------------------------------------------- Process Interface  # ----------------------------------------------------------- Process Interface
     $env{'form.interface'}=~s/\W//g;      $env{'form.interface'}=~s/\W//g;
   
     (undef,undef,undef,undef,undef,undef,my $clientmobile) =      (undef,undef,undef,undef,undef,undef,my $clientmobile) =
         &Apache::loncommon::decode_user_agent($r);          &Apache::loncommon::decode_user_agent($r);
   
     my $iconpath=       my $iconpath=
  &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));   &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
   
     my $domain = &Apache::lonnet::default_login_domain();      my $domain = &Apache::lonnet::default_login_domain();
     my $defdom = $domain;      my $defdom = $domain;
     if ($lonhost ne '') {      if ($lonhost ne '') {
         unless ($sessiondata{'sessionserver'}) {          unless ($sessiondata{'sessionserver'}) {
             my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);              my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);
             if ($redirect) {              if ($redirect) {
                 $r->print($redirect);                  $r->print($redirect);
                 return OK;                  return OK;
             }              }
         }          }
     }      }
   
     if (($sessiondata{'domain'}) &&      if (($sessiondata{'domain'}) &&
         (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {          (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {
         $domain=$sessiondata{'domain'};          $domain=$sessiondata{'domain'};
     } elsif (($env{'form.domain'}) &&       } elsif (($env{'form.domain'}) &&
  (&Apache::lonnet::domain($env{'form.domain'},'description'))) {   (&Apache::lonnet::domain($env{'form.domain'},'description'))) {
  $domain=$env{'form.domain'};   $domain=$env{'form.domain'};
     }      }
   
     my $role    = $r->dir_config('lonRole');      my $role    = $r->dir_config('lonRole');
     my $loadlim = $r->dir_config('lonLoadLim');      my $loadlim = $r->dir_config('lonLoadLim');
     my $uloadlim= $r->dir_config('lonUserLoadLim');      my $uloadlim= $r->dir_config('lonUserLoadLim');
     my $servadm = $r->dir_config('lonAdmEMail');      my $servadm = $r->dir_config('lonAdmEMail');
     my $tabdir  = $r->dir_config('lonTabDir');      my $tabdir  = $r->dir_config('lonTabDir');
     my $include = $r->dir_config('lonIncludes');      my $include = $r->dir_config('lonIncludes');
     my $expire  = $r->dir_config('lonExpire');      my $expire  = $r->dir_config('lonExpire');
     my $version = $r->dir_config('lonVersion');      my $version = $r->dir_config('lonVersion');
     my $host_name = &Apache::lonnet::hostname($lonhost);      my $host_name = &Apache::lonnet::hostname($lonhost);
   
 # --------------------------------------------- Default values for login fields  # --------------------------------------------- Default values for login fields
          
     my ($authusername,$authdomain);      my ($authusername,$authdomain);
     if ($sessiondata{'username'}) {      if ($sessiondata{'username'}) {
         $authusername=$sessiondata{'username'};          $authusername=$sessiondata{'username'};
     } else {      } else {
         $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});          $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});
         $authusername=($env{'form.username'}?$env{'form.username'}:'');          $authusername=($env{'form.username'}?$env{'form.username'}:'');
     }      }
     if ($sessiondata{'domain'}) {      if ($sessiondata{'domain'}) {
         $authdomain=$sessiondata{'domain'};          $authdomain=$sessiondata{'domain'};
     } else {      } else {
         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});          $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});
         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);          $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);
     }      }
   
 # ---------------------------------------------------------- Determine own load  # ---------------------------------------------------------- Determine own load
     my $loadavg;      my $loadavg;
     {      {
  my $loadfile=Apache::File->new('/proc/loadavg');   my $loadfile=Apache::File->new('/proc/loadavg');
  $loadavg=<$loadfile>;   $loadavg=<$loadfile>;
     }      }
     $loadavg =~ s/\s.*//g;      $loadavg =~ s/\s.*//g;
   
     my ($loadpercent,$userloadpercent);      my ($loadpercent,$userloadpercent);
     if ($loadlim) {      if ($loadlim) {
         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);          $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
     }      }
     if ($uloadlim) {      if ($uloadlim) {
         $userloadpercent=&Apache::lonnet::userload();          $userloadpercent=&Apache::lonnet::userload();
     }      }
   
     my $firsturl=      my $firsturl=
     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});      ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});
   
 # ----------------------------------------------------------- Get announcements  # ----------------------------------------------------------- Get announcements
     my $announcements=&Apache::lonnet::getannounce();      my $announcements=&Apache::lonnet::getannounce();
 # -------------------------------------------------------- Set login parameters  # -------------------------------------------------------- Set login parameters
   
     my @hexstr=('0','1','2','3','4','5','6','7',      my @hexstr=('0','1','2','3','4','5','6','7',
                 '8','9','a','b','c','d','e','f');                  '8','9','a','b','c','d','e','f');
     my $lkey='';      my $lkey='';
     for (0..7) {      for (0..7) {
         $lkey.=$hexstr[rand(15)];          $lkey.=$hexstr[rand(15)];
     }      }
   
     my $ukey='';      my $ukey='';
     for (0..7) {      for (0..7) {
         $ukey.=$hexstr[rand(15)];          $ukey.=$hexstr[rand(15)];
     }      }
   
     my $lextkey=hex($lkey);      my $lextkey=hex($lkey);
     if ($lextkey>2147483647) { $lextkey-=4294967296; }      if ($lextkey>2147483647) { $lextkey-=4294967296; }
   
     my $uextkey=hex($ukey);      my $uextkey=hex($ukey);
     if ($uextkey>2147483647) { $uextkey-=4294967296; }      if ($uextkey>2147483647) { $uextkey-=4294967296; }
   
 # -------------------------------------------------------- Store away log token  # -------------------------------------------------------- Store away log token
     my ($tokenextras,$tokentype,$linkprot_for_login);      my ($tokenextras,$tokentype,$linkprot_for_login);
     my @names = ('role','symb','iptoken','ltoken','linkprotuser','linkprotexit',      my @names = ('role','symb','iptoken','ltoken','linkprotuser','linkprotexit',
                  'linkprot','linkkey','display','linkprotpbid','linkprotpburl');                   'linkprot','linkkey','display','linkprotpbid','linkprotpburl');
     foreach my $name (@names) {      foreach my $name (@names) {
         if ($env{'form.'.$name} ne '') {          if ($env{'form.'.$name} ne '') {
             if ($name eq 'ltoken') {              if ($name eq 'ltoken') {
                 my %info = &Apache::lonnet::tmpget($env{'form.'.$name});                  my %info = &Apache::lonnet::tmpget($env{'form.'.$name});
                 if ($info{'linkprot'}) {                  if ($info{'linkprot'}) {
                     $linkprot_for_login = $info{'linkprot'};                      $linkprot_for_login = $info{'linkprot'};
                     $tokenextras .= '&linkprot='.&escape($info{'linkprot'});                      $tokenextras .= '&linkprot='.&escape($info{'linkprot'});
                     foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {                      foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {
                         if ($info{$item}) {                          if ($info{$item}) {
                             $tokenextras .= '&'.$item.'='.&escape($info{$item});                              $tokenextras .= '&'.$item.'='.&escape($info{$item});
                         }                          }
                     }                      }
                     $tokentype = 'link';                      $tokentype = 'link';
                     last;                      last;
                 }                  }
             } elsif ($env{'form.display'} && ($env{'form.firsturl'} eq '/adm/email')) {              } elsif ($env{'form.display'} && ($env{'form.firsturl'} eq '/adm/email')) {
                 if (($env{'form.mailrecip'}) ||                  if (($env{'form.mailrecip'}) ||
                     ($env{'form.username'} =~ /^$match_username$/) && ($env{'form.domain'} =~ /^$match_domain$/)) {                      ($env{'form.username'} =~ /^$match_username$/) && ($env{'form.domain'} =~ /^$match_domain$/)) {
                     $tokenextras .= '&'.$name.'='.&escape($env{'form.display'});                      $tokenextras .= '&'.$name.'='.&escape($env{'form.display'});
                     if ($env{'form.mailrecip'}) {                      if ($env{'form.mailrecip'}) {
                         $tokenextras .= '&mailrecip='.&escape($env{'form.mailrecip'});                          $tokenextras .= '&mailrecip='.&escape($env{'form.mailrecip'});
                     } else {                      } else {
                         $tokenextras .= '&mailrecip='.&escape($env{'form.username'}.':'.$env{'form.domain'});                          $tokenextras .= '&mailrecip='.&escape($env{'form.username'}.':'.$env{'form.domain'});
                     }                      }
                 }                  }
             } else {              } else {
                 $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});                  $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});
                 if (($name eq 'linkkey') || ($name eq 'linkprot')) {                  if (($name eq 'linkkey') || ($name eq 'linkprot')) {
                     if ((($env{'form.retry'}) || ($env{'form.sso'})) &&                      if ((($env{'form.retry'}) || ($env{'form.sso'})) &&
                         (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {                          (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {
                         $linkprot_for_login = $env{'form.linkprot'};                          $linkprot_for_login = $env{'form.linkprot'};
                     }                      }
                     $tokentype = 'link';                      $tokentype = 'link';
                 }                  }
             }              }
         }          }
     }      }
     if ($tokentype) {      if ($tokentype) {
         $tokenextras .= ":$tokentype";          $tokenextras .= ":$tokentype";
     }      }
     my $logtoken=Apache::lonnet::reply(      my $logtoken=Apache::lonnet::reply(
        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,         'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,
        $lonhost);         $lonhost);
   
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
 #    we are in serious trouble  #    we are in serious trouble
   
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
         if ($logtoken eq 'no_such_host') {          if ($logtoken eq 'no_such_host') {
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
         }          }
         if ($env{'form.ltoken'}) {          if ($env{'form.ltoken'}) {
             &Apache::lonnet::tmpdel($env{'form.ltoken'});              &Apache::lonnet::tmpdel($env{'form.ltoken'});
             delete($env{'form.ltoken'});              delete($env{'form.ltoken'});
         }          }
         my $spares='';          my $spares='';
         my (@sparehosts,%spareservers);          my (@sparehosts,%spareservers);
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);          my $sparesref = &Apache::lonnet::this_host_spares($defdom);
         if (ref($sparesref) eq 'HASH') {          if (ref($sparesref) eq 'HASH') {
             foreach my $key (keys(%{$sparesref})) {              foreach my $key (keys(%{$sparesref})) {
                 if (ref($sparesref->{$key}) eq 'ARRAY') {                  if (ref($sparesref->{$key}) eq 'ARRAY') {
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp                      my @sorted = sort { &Apache::lonnet::hostname($a) cmp
                                         &Apache::lonnet::hostname($b);                                          &Apache::lonnet::hostname($b);
                                       } @{$sparesref->{$key}};                                        } @{$sparesref->{$key}};
                     if (@sorted) {                      if (@sorted) {
                         if ($key eq 'primary') {                          if ($key eq 'primary') {
                             unshift(@sparehosts,@sorted);                              unshift(@sparehosts,@sorted);
                         } elsif ($key eq 'default') {                          } elsif ($key eq 'default') {
                             push(@sparehosts,@sorted);                              push(@sparehosts,@sorted);
                         }                          }
                     }                      }
                 }                  }
             }              }
         }          }
         foreach my $hostid (@sparehosts) {          foreach my $hostid (@sparehosts) {
             next if ($hostid eq $lonhost);              next if ($hostid eq $lonhost);
     my $hostname = &Apache::lonnet::hostname($hostid);      my $hostname = &Apache::lonnet::hostname($hostid);
     next if (($hostname eq '') || ($spareservers{$hostname}));      next if (($hostname eq '') || ($spareservers{$hostname}));
             $spareservers{$hostname} = 1;              $spareservers{$hostname} = 1;
             my $protocol = $Apache::lonnet::protocol{$hostid};              my $protocol = $Apache::lonnet::protocol{$hostid};
             $protocol = 'http' if ($protocol ne 'https');              $protocol = 'http' if ($protocol ne 'https');
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.              $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
                 $hostname.                  $hostname.
                 '/adm/login?domain='.$authdomain.'">'.                  '/adm/login?domain='.$authdomain.'">'.
                 $hostname.'</a>'.                  $hostname.'</a>'.
                 ' '.&mt('(preferred)').'</span>'.$/;                  ' '.&mt('(preferred)').'</span>'.$/;
         }          }
         if ($spares) {          if ($spares) {
             $spares.= '<br />';              $spares.= '<br />';
         }          }
         my %all_hostnames = &Apache::lonnet::all_hostnames();          my %all_hostnames = &Apache::lonnet::all_hostnames();
         foreach my $hostid (sort          foreach my $hostid (sort
     {      {
  &Apache::lonnet::hostname($a) cmp   &Apache::lonnet::hostname($a) cmp
     &Apache::lonnet::hostname($b);      &Apache::lonnet::hostname($b);
     }      }
     keys(%all_hostnames)) {      keys(%all_hostnames)) {
             next if ($hostid eq $lonhost);              next if ($hostid eq $lonhost);
             my $hostname = &Apache::lonnet::hostname($hostid);              my $hostname = &Apache::lonnet::hostname($hostid);
             next if (($hostname eq '') || ($spareservers{$hostname}));              next if (($hostname eq '') || ($spareservers{$hostname}));
             $spareservers{$hostname} = 1;              $spareservers{$hostname} = 1;
             my $protocol = $Apache::lonnet::protocol{$hostid};              my $protocol = $Apache::lonnet::protocol{$hostid};
             $protocol = 'http' if ($protocol ne 'https');              $protocol = 'http' if ($protocol ne 'https');
             $spares.='<br /><a href="'.$protocol.'://'.              $spares.='<br /><a href="'.$protocol.'://'.
              $hostname.               $hostname.
              '/adm/login?domain='.$authdomain.'">'.               '/adm/login?domain='.$authdomain.'">'.
              $hostname.'</a>';               $hostname.'</a>';
          }           }
          $r->print(           $r->print(
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'     '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'    .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'    .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
   .&mt('The LearningOnline Network with CAPA')    .&mt('The LearningOnline Network with CAPA')
   .'</title></head>'    .'</title></head>'
   .'<body bgcolor="#FFFFFF">'    .'<body bgcolor="#FFFFFF">'
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'    .'<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>');    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
         if ($spares) {          if ($spares) {
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
                      .'</p>'                       .'</p>'
                      .$spares);                       .$spares);
         }          }
         $r->print('</body>'          $r->print('</body>'
                  .'</html>'                   .'</html>'
         );          );
         return OK;          return OK;
     }      }
   
 # ----------------------------------------------- Apparently we are in business  # ----------------------------------------------- Apparently we are in business
     $servadm=~s/\,/\<br \/\>/g;      $servadm=~s/\,/\<br \/\>/g;
   
 # ----------------------------------------------------------- Front page design  # ----------------------------------------------------------- Front page design
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
     my $font=&Apache::loncommon::designparm('login.font',$domain);      my $font=&Apache::loncommon::designparm('login.font',$domain);
     my $link=&Apache::loncommon::designparm('login.link',$domain);      my $link=&Apache::loncommon::designparm('login.link',$domain);
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
     my $img=&Apache::loncommon::designparm('login.img',$domain);      my $img=&Apache::loncommon::designparm('login.img',$domain);
     my $domainlogo=&Apache::loncommon::domainlogo($domain);      my $domainlogo=&Apache::loncommon::domainlogo($domain);
     my $showbanner = 1;      my $showbanner = 1;
     my $showmainlogo = 1;      my $showmainlogo = 1;
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
     }      }
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
     }      }
     my $showadminmail;      my $showadminmail;
     my @possdoms = &Apache::lonnet::current_machine_domains();      my @possdoms = &Apache::lonnet::current_machine_domains();
     if (grep(/^\Q$domain\E$/,@possdoms)) {      if (grep(/^\Q$domain\E$/,@possdoms)) {
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
     }      }
     my $showcoursecat =      my $showcoursecat =
         &Apache::loncommon::designparm('login.coursecatalog',$domain);          &Apache::loncommon::designparm('login.coursecatalog',$domain);
     my $shownewuserlink =       my $shownewuserlink =
         &Apache::loncommon::designparm('login.newuser',$domain);          &Apache::loncommon::designparm('login.newuser',$domain);
     my $showhelpdesk =      my $showhelpdesk =
         &Apache::loncommon::designparm('login.helpdesk',$domain);          &Apache::loncommon::designparm('login.helpdesk',$domain);
     my $now=time;      my $now=time;
     my $js = (<<ENDSCRIPT);      my $js = (<<ENDSCRIPT);
   
 <script type="text/javascript" language="JavaScript">  <script type="text/javascript" language="JavaScript">
 // <![CDATA[  // <![CDATA[
 function send()  function send()
 {  {
 this.document.server.elements.uname.value  this.document.server.elements.uname.value
 =this.document.client.elements.uname.value;  =this.document.client.elements.uname.value;
   
 this.document.server.elements.udom.value  this.document.server.elements.udom.value
 =this.document.client.elements.udom.value;  =this.document.client.elements.udom.value;
   
 uextkey=this.document.client.elements.uextkey.value;  uextkey=this.document.client.elements.uextkey.value;
 lextkey=this.document.client.elements.lextkey.value;  lextkey=this.document.client.elements.lextkey.value;
 initkeys();  initkeys();
   
 this.document.server.elements.upass0.value  if(this.document.server.action.substr(0,5) === 'http:'){
     =getCrypted(this.document.client.elements.upass$now.value);      this.document.server.elements.upass0.value
           =getCrypted(this.document.client.elements.upass$now.value);
 this.document.client.elements.uname.value='';  } else {
 this.document.client.elements.upass$now.value='';      this.document.server.elements.upass0.value
           =this.document.client.elements.upass$now.value;
 this.document.server.submit();  }
 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','linkprotpbid','linkprotpburl') {                  %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.10  
changed lines
  Added in v.1.207


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