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

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


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