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

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

Removed from v.1.158.2.13.2.9  
changed lines
  Added in v.1.207


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