Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.8 and 1.200

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

Removed from v.1.158.2.13.2.8  
changed lines
  Added in v.1.200


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