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

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

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


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