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

version 1.158.2.13.2.8, 2023/01/23 00:52:44 version 1.213, 2025/02/25 16:33:37
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{'mailrecipient'} = &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 class="LC_landmark" 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);  .LC_landmark {
     my $showbanner = 1;    margin: 0;
     my $showmainlogo = 1;    padding: 0;
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {    border: none;
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);  }
     }  </style></head>'
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {    .'<body bgcolor="#FFFFFF">'
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);    .'<div class="LC_landmark" role="banner">'
     }    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     my $showadminmail;    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
     my @possdoms = &Apache::lonnet::current_machine_domains();    .'</div>'
     if (grep(/^\Q$domain\E$/,@possdoms)) {    .'<div class="LC_landmark" role="main">'
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);    .'<h2>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h2>');
     }          if ($spares) {
     my $showcoursecat =              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
         &Apache::loncommon::designparm('login.coursecatalog',$domain);                       .'</p>'
     my $shownewuserlink =                        .$spares);
         &Apache::loncommon::designparm('login.newuser',$domain);          }
     my $showhelpdesk =          $r->print('</div></body>'
         &Apache::loncommon::designparm('login.helpdesk',$domain);                   .'</html>'
     my $now=time;          );
     my $js = (<<ENDSCRIPT);          return OK;
       }
 <script type="text/javascript" language="JavaScript">  
 // <![CDATA[  # ----------------------------------------------- Apparently we are in business
 function send()      $servadm=~s/\,/\<br \/\>/g;
 {  
 this.document.server.elements.uname.value  # ----------------------------------------------------------- Front page design
 =this.document.client.elements.uname.value;      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
       my $font=&Apache::loncommon::designparm('login.font',$domain);
 this.document.server.elements.udom.value      my $link=&Apache::loncommon::designparm('login.link',$domain);
 =this.document.client.elements.udom.value;      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
       my $alink=&Apache::loncommon::designparm('login.alink',$domain);
 uextkey=this.document.client.elements.uextkey.value;      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
 lextkey=this.document.client.elements.lextkey.value;      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
 initkeys();      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
       my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
 this.document.server.elements.upass0.value      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
     =getCrypted(this.document.client.elements.upass$now.value);      my $img=&Apache::loncommon::designparm('login.img',$domain);
       my $domainlogo=&Apache::loncommon::domainlogo($domain);
 this.document.client.elements.uname.value='';      my $showbanner = 1;
 this.document.client.elements.upass$now.value='';      my $showmainlogo = 1;
       if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
 this.document.server.submit();          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
 return false;      }
 }      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
           $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
 function enableInput() {      }
     this.document.client.elements.upass$now.removeAttribute("readOnly");      my $showadminmail;
     this.document.client.elements.uname.removeAttribute("readOnly");      my @possdoms = &Apache::lonnet::current_machine_domains();
     this.document.client.elements.udom.removeAttribute("readOnly");      if (grep(/^\Q$domain\E$/,@possdoms)) {
     return;          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 }      }
       my $showcoursecat =
 // ]]>          &Apache::loncommon::designparm('login.coursecatalog',$domain);
 </script>      my $shownewuserlink =
           &Apache::loncommon::designparm('login.newuser',$domain);
 ENDSCRIPT      my $showhelpdesk =
           &Apache::loncommon::designparm('login.helpdesk',$domain);
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,      my $now=time;
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip,      my $js = (<<ENDSCRIPT);
         $samlwindow);  
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);  <script type="text/javascript" language="JavaScript">
     @hosts = &Apache::lonnet::current_machine_ids();  // <![CDATA[
     $lonhost_in_use = $lonhost;  function send()
     if (@hosts > 1) {  {
         foreach my $hostid (@hosts) {  this.document.server.elements.uname.value
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {  =this.document.client.elements.uname.value;
                 $lonhost_in_use = $hostid;  
                 last;  this.document.server.elements.udom.value
             }  =this.document.client.elements.udom.value;
         }  
     }  uextkey=this.document.client.elements.uextkey.value;
     $saml_prefix = $defdom.'.login.saml_';  lextkey=this.document.client.elements.lextkey.value;
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {  initkeys();
         $saml_landing = 1;  
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};  if(this.document.server.action.substr(0,5) === 'http:'){
         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};      this.document.server.elements.upass0.value
         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};          =getCrypted(this.document.client.elements.upass$now.value);
         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};  } else {
         $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};      this.document.server.elements.upass0.value
         $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};          =this.document.client.elements.upass$now.value;
         $samlwindow = $defaultdomconf{$saml_prefix.'window_'.$lonhost_in_use};  }
     }  
     if ($saml_landing) {  this.document.client.elements.uname.value='';
        if ($samlssotext eq '') {  this.document.client.elements.upass$now.value='';
            $samlssotext = 'SSO Login';  
        }  this.document.server.submit();
        if ($samlnonsso eq '') {  return false;
            $samlnonsso = 'Non-SSO Login';  }
        }  
        $js .= <<"ENDSAMLJS";  function enableInput() {
       this.document.client.elements.upass$now.removeAttribute("readOnly");
 <script type="text/javascript">      this.document.client.elements.uname.removeAttribute("readOnly");
 // <![CDATA[      this.document.client.elements.udom.removeAttribute("readOnly");
 function toggleLClogin() {      return;
     if (document.getElementById('LC_standard_login')) {  }
         if (document.getElementById('LC_standard_login').style.display == 'none') {  
             document.getElementById('LC_standard_login').style.display = 'inline-block';  // ]]>
             if (document.getElementById('LC_login_text')) {  </script>
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';  
             }  ENDSCRIPT
             if ( document.client.uname ) { document.client.uname.focus(); }  
             if (document.getElementById('LC_SSO_login')) {      my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,
                 document.getElementById('LC_SSO_login').style.display = 'none';          $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip,
             }          $samlwindow);
         } else {      %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
             document.getElementById('LC_standard_login').style.display = 'none';      @hosts = &Apache::lonnet::current_machine_ids();
             if (document.getElementById('LC_login_text')) {      $lonhost_in_use = $lonhost;
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';      if (@hosts > 1) {
             }          foreach my $hostid (@hosts) {
             if (document.getElementById('LC_SSO_login')) {              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';                  $lonhost_in_use = $hostid;
             }                  last;
         }              }
     }          }
     return;      }
 }      $saml_prefix = $defdom.'.login.saml_';
       if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {
 // ]]>          $saml_landing = 1;
 </script>          $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};
           $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};
 ENDSAMLJS          $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};
     }          $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};
           $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};
 # --------------------------------------------------- Print login screen header          $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};
           $samlwindow = $defaultdomconf{$saml_prefix.'window_'.$lonhost_in_use};
     my %add_entries = (      }
        bgcolor      => "$mainbg",      if ($saml_landing) {
        text         => "$font",         if ($samlssotext eq '') {
        link         => "$link",             $samlssotext = 'SSO Login';
        vlink        => "$vlink",         }
        alink        => "$alink",         if ($samlnonsso eq '') {
                onload       => 'javascript:enableInput();',);             $samlnonsso = 'Non-SSO Login';
          }
     my ($headextra,$headextra_exempt);         $js .= <<"ENDSAMLJS";
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};  
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};  <script type="text/javascript">
     if ($headextra) {  // <![CDATA[
         my $omitextra;  function toggleLClogin() {
         if ($headextra_exempt ne '') {      if (document.getElementById('LC_standard_login')) {
             my @exempt = split(',',$headextra_exempt);          if (document.getElementById('LC_standard_login').style.display == 'none') {
             my $ip = &Apache::lonnet::get_requestor_ip();              document.getElementById('LC_standard_login').style.display = 'inline-block';
             if (grep(/^\Q$ip\E$/,@exempt)) {              if (document.getElementById('LC_login_text')) {
                 $omitextra = 1;                  document.getElementById('LC_login_text').innerHTML = '$samlnonsso';
             }              }
         }              if ( document.client.uname ) { document.client.uname.focus(); }
         unless ($omitextra) {              if (document.getElementById('LC_SSO_login')) {
             my $confname = $defdom.'-domainconfig';                  document.getElementById('LC_SSO_login').style.display = 'none';
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {              }
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));          } else {
                 unless ($extra eq '-1') {              document.getElementById('LC_standard_login').style.display = 'none';
                     $js .= "\n".$extra."\n";              if (document.getElementById('LC_login_text')) {
                 }                  document.getElementById('LC_login_text').innerHTML = '$samlssotext';
             }              }
         }              if (document.getElementById('LC_SSO_login')) {
     }                  document.getElementById('LC_SSO_login').style.display = 'inline-block';
               }
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,          }
        { 'redirect'       => [$expire,'/adm/roles'],       }
  'add_entries' => \%add_entries,      return;
  'only_body'   => 1,}));  }
   
 # ----------------------------------------------------------------------- Texts  // ]]>
   </script>
     my %lt=&Apache::lonlocal::texthash(  
           'un'       => 'Username',  ENDSAMLJS
           'pw'       => 'Password',      }
           'dom'      => 'Domain',  
           'perc'     => 'percent',  # --------------------------------------------------- Print login screen header
           'load'     => 'Server Load',  
           'userload' => 'User Load',      my %add_entries = (
           'catalog'  => 'Course/Community Catalog',         bgcolor      => "$mainbg",
           'log'      => 'Log in',         text         => "$font",
           'help'     => 'Log-in Help',         link         => "$link",
           'serv'     => 'Server',         vlink        => "$vlink",
           'servadm'  => 'Server Administration',         alink        => "$alink",
           'helpdesk' => 'Contact Helpdesk',                 onload       => 'javascript:enableInput();',);
           'forgotpw' => 'Forgot password?',  
           'newuser'  => 'New User?',      my ($headextra,$headextra_exempt);
           'change'   => 'Change?',      $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
        );      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
 # -------------------------------------------------- Change password field name      if ($headextra) {
           my $omitextra;
     my $forgotpw = &forgotpwdisplay(%lt);          if ($headextra_exempt ne '') {
     $forgotpw .= '<br />' if $forgotpw;              my @exempt = split(',',$headextra_exempt);
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);              my $ip = &Apache::lonnet::get_requestor_ip();
     if ($loginhelp) {              if (grep(/^\Q$ip\E$/,@exempt)) {
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';                  $omitextra = 1;
     }              }
           }
 # ---------------------------------------------------- Serve out DES JavaScript          unless ($omitextra) {
     {              my $confname = $defdom.'-domainconfig';
     my $jsh=Apache::File->new($include."/londes.js");              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
     $r->print(<$jsh>);                  my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
     }                  unless ($extra eq '-1') {
 # ---------------------------------------------------------- Serve rest of page                      $js .= "\n".$extra."\n";
                   }
     $r->print(              }
     '<div class="LC_Box"'          }
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'      }
 );  
       my $args = {
     $r->print(<<ENDSERVERFORM);                   'redirect'    => [$expire,'/adm/roles'],
 <form name="server" action="/adm/authenticate" method="post" target="_top">                   'add_entries' => \%add_entries,
    <input type="hidden" name="logtoken" value="$logtoken" />                   'only_body'   => 1,
    <input type="hidden" name="serverid" value="$lonhost" />                 };
    <input type="hidden" name="uname" value="" />      if ($clientunicode && !$clientmathml) {
    <input type="hidden" name="upass0" value="" />          $args->{'browser.unicode'} = 1;
    <input type="hidden" name="udom" value="" />      }
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',
    <input type="hidden" name="localres" value="$env{'form.localres'}" />                                               $js,$args));
   </form>  
 ENDSERVERFORM  # ----------------------------------------------------------------------- Texts
     my $coursecatalog;  
     if (($showcoursecat eq '') || ($showcoursecat)) {      my %lt=&Apache::lonlocal::texthash(
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';            'un'       => 'Username',
     }            'pw'       => 'Password',
     my $newuserlink;            'dom'      => 'Domain',
     if ($shownewuserlink) {            'perc'     => 'percent',
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';            'load'     => 'Server Load',
     }            'userload' => 'User Load',
     my $logintitle =            'catalog'  => 'Course/Community Catalog',
         '<h2 class="LC_hcell"'            'log'      => 'Log in',
        .' style="background:'.$loginbox_header_bgcol.';'            'help'     => 'Log-in Help',
        .' color:'.$loginbox_header_textcol.'">'            'serv'     => 'Server',
        .$lt{'log'}            'servadm'  => 'Server Administration',
        .'</h2>';            'helpdesk' => 'Contact Helpdesk',
             'forgotpw' => 'Forgot password?',
     my $noscript_warning='<noscript><span class="LC_warning"><b>'            'newuser'  => 'New User?',
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')            'change'   => 'Change?',
                         .'</b></span></noscript>';            'nojs'     => 'Use of LON-CAPA requires Javascript to be enabled in your web browser.',
     my $helpdeskscript;         );
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,  # -------------------------------------------------- Change password field name
                                        $authdomain,\$helpdeskscript,  
                                        $showhelpdesk,\@possdoms);      my $forgotpw = &forgotpwdisplay(%lt);
       if ($forgotpw) {
     my $mobileargs;          $forgotpw = '<div class="LC_login_links">'.
     if ($clientmobile) {                      $forgotpw.'</div>';
         $mobileargs = 'autocapitalize="off" autocorrect="off"';       }
     }      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
     my $loginform=(<<LFORM);      if ($loginhelp) {
 <form name="client" action="" onsubmit="return(send())" id="lclogin">          $loginhelp = '<div class="LC_login_links">'.
   <input type="hidden" name="lextkey" value="$lextkey" />                       '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a></div>';
   <input type="hidden" name="uextkey" value="$uextkey" />      }
   <b><label for="uname">$lt{'un'}</label>:</b><br />  
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />  # ---------------------------------------------------- Serve out DES JavaScript
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />      {
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />      my $jsh=Apache::File->new($include."/londes.js");
   <b><label for="udom">$lt{'dom'}</label>:</b><br />      $r->print(<$jsh>);
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />      }
   <input type="submit" value="$lt{'log'}" />  # ---------------------------------------------------------- Serve rest of page
 </form>  
 LFORM      $r->print(
       '<div class="LC_Box"'
     if ($showbanner) {     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);  );
         if ($alttext eq '') {  
             $alttext = 'The Learning Online Network with CAPA';      my $target = '_top';
         }      if ($sessiondata{'linkprot'}) {
         $r->print(<<HEADER);          my ($linkprotector,$deeplink) = split(/:/,$sessiondata{'linkprot'},2);
 <!-- The LON-CAPA Header -->          if (($deeplink eq $sessiondata{'origurl'}) &&
 <div style="background:$pgbg;margin:0;width:100%;">              (($sessiondata{'linkprotuser'} eq $sessiondata{'username'}.':'.$sessiondata{'domain'}) ||
   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />               ($sessiondata{'linkprotuser'} eq $sessiondata{'username'}))) {
 </div>              $target = '_self';
 HEADER          }
     }      }
       $r->print(<<ENDSERVERFORM);
     my $stdauthformstyle = 'inline-block';  <form name="server" action="/adm/authenticate" method="post" target="$target">
     my $ssoauthstyle = 'none';     <input type="hidden" name="logtoken" value="$logtoken" />
     my $sso_onclick;     <input type="hidden" name="serverid" value="$lonhost" />
     my $logintype;     <input type="hidden" name="uname" value="" />
     $r->print('<div style="float:left;margin-top:0;">');     <input type="hidden" name="upass0" value="" />
     if ($saml_landing) {     <input type="hidden" name="udom" value="" />
         $ssoauthstyle = 'inline-block';     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
         $stdauthformstyle = 'none';     <input type="hidden" name="localres" value="$env{'form.localres'}" />
         $logintype = $samlssotext;    </form>
         my $ssologin = '/adm/sso';  ENDSERVERFORM
         if ($samlssourl  ne '') {      my $coursecatalog;
             $ssologin = $samlssourl;      if (($showcoursecat eq '') || ($showcoursecat)) {
         }          $coursecatalog = '<div class="LC_login_links">'.
         my $ssologin_for_js = &js_escape($ssologin);                           &coursecatalog_link($lt{'catalog'}).'</div>';
         my $querystr_for_js;      }
         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {      my $newuserlink;
             my $querystring;      if ($shownewuserlink) {
             if ($env{'form.firsturl'} ne '') {          $newuserlink = '<div class="LC_login_links">'.
                 $querystring = 'origurl=';                         &newuser_link($lt{'newuser'}).'</div>';
                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {      }
                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});      my $logintitle =
                 } else {          '<h2 class="LC_hcell"'
                     $querystring .= &uri_escape($env{'form.firsturl'});         .' style="background:'.$loginbox_header_bgcol.';'
                 }         .' color:'.$loginbox_header_textcol.'">'
                 $querystring = &HTML::Entities::encode($querystring,"'");         .$lt{'log'}
             }         .'</h2>';
             if ($env{'form.ltoken'} ne '') {  
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.      my $noscript_warning = <<"ENDNOJS";
                                   &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));  <div aria-hidden="true" style="padding:0;margin:0;border:0">
             } elsif ($env{'form.linkkey'}) {  <noscript>
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.  <span style="color: darkred; font-weight: bold;">$lt{'nojs'}</span>
                                   &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));  </noscript>
             }  </div>
             if ($querystring ne '') {  <div class="LC_visually_hidden">
                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;  <noscript>
                 $querystr_for_js = &js_escape($querystring);  $lt{'nojs'}
             }  </noscript>
         } elsif ($logtoken ne '') {  </div>
             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;  ENDNOJS
             $querystr_for_js = &js_escape('logtoken='.$logtoken);      my $helpdeskscript;
         }      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
         my $ssohref;                                         $authdomain,\$helpdeskscript,
         if ($samlwindow) {                                         $showhelpdesk,\@possdoms);
             $sso_onclick = <<"ENDJS";  
 if (document.getElementById('LC_sso_login_link')) {      my $mobileargs;
     var ssoelem = document.getElementById('LC_sso_login_link')      if ($clientmobile) {
     ssoelem.addEventListener('click',samlWinFunction,false);          $mobileargs = 'autocapitalize="off" autocorrect="off"';
     var windows = {};      }
     function samlWinFunction(evt) {      my $loginform=(<<LFORM);
         evt.preventDefault();  <form name="client" action="" onsubmit="return(send())" id="lclogin">
         var url = '$ssologin_for_js';    <input type="hidden" name="lextkey" value="$lextkey" />
         var name = 'lcssowin';    <input type="hidden" name="uextkey" value="$uextkey" />
         var querystr = '$querystr_for_js';    <b><label for="uname">$lt{'un'}</label>:</b><br />
         if (querystr) {    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
             url += '?'+querystr+'&lcssowin=1';    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
         } else {    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
             url += '?lcssowin=1';    <b><label for="udom">$lt{'dom'}</label>:</b><br />
         }    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
         if ((typeof windows[name] !== 'undefined') && (!windows[name].closed)) {    <input type="submit" value="$lt{'log'}" />
             windows[name].close();  </form>
         }  LFORM
         windows[name]=window.open(url,name,'width=350,height=600');  
         windows[name].focus();      if ($showbanner) {
         return false;          my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);
     }          if ($alttext eq '') {
 }              $alttext = 'The Learning Online Network with CAPA';
 ENDJS          }
         }          $r->print(<<HEADER);
         if ($samlssoimg ne '') {  <!-- The LON-CAPA Header -->
             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'" id="LC_sso_login_link">'.  <div style="background:$pgbg;margin:0;width:100%;" role="banner">
                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';    <h1 style="padding:0;margin:0">
         } else {    <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />
             $ssohref = '<a href="'.$ssologin.'" id="LC_sso_login_link">'.$samlssotext.'</a>';    </h1>
         }  </div>
         if (($env{'form.saml'} eq 'no') ||  HEADER
             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {      } else {
             $ssoauthstyle = 'none';          $r->print('<div role="banner" class="LC_visually_hidden" tabindex="-1">'.
             $stdauthformstyle = 'inline-block';                    '<h1>'.&mt('LON-CAPA Login Page').'</h1></div>');
             $logintype = $samlnonsso;      }
         }  
         $r->print(<<ENDSAML);      my $stdauthformstyle = 'inline-block';
 <p>      my $ssoauthstyle = 'none';
 Log-in type:      my $sso_onclick;
 <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />      my $logintype;
 <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>      $r->print('<div style="float:left;margin-top:0;" role="main">');
 </p>      if ($saml_landing) {
 <div style="display:$ssoauthstyle" id="LC_SSO_login">          $ssoauthstyle = 'inline-block';
 <div class="LC_Box" style="padding-top: 10px;">          $stdauthformstyle = 'none';
 $ssohref          $logintype = $samlssotext;
 $noscript_warning          my $ssologin = '/adm/sso';
 </div>          if ($samlssourl  ne '') {
 <div class="LC_Box" style="padding-top: 10px;">              $ssologin = $samlssourl;
 $loginhelp          }
 $contactblock          my $ssologin_for_js = &js_escape($ssologin);
 $coursecatalog          my $querystr_for_js;
 </div>          if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
 </div>              my $querystring;
 ENDSAML              if ($env{'form.firsturl'} ne '') {
     } else {                  $querystring = 'origurl=';
         if ($env{'form.ltoken'}) {                  if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
             &Apache::lonnet::tmpdel($env{'form.ltoken'});                      $querystring .= &uri_escape_utf8($env{'form.firsturl'});
             delete($env{'form.ltoken'});                  } else {
         }                      $querystring .= &uri_escape($env{'form.firsturl'});
     }                  }
     my $in_frame_js;                  $querystring = &HTML::Entities::encode($querystring,"'");
     if ($linkprot_for_login) {              }
         my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);              if ($env{'form.ltoken'} ne '') {
         if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {                  $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.
             my $set_target;                                    &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));
             if (($env{'form.retry'}) || ($env{'form.sso'})) {              } elsif ($env{'form.linkkey'}) {
                 if ($linkproturi eq $env{'form.firsturl'}) {                  $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.
                     $set_target = "    document.server.target = '_self';";                                    &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));
                 }              }
             } else {              if ($querystring ne '') {
                 $set_target = <<ENDTARG;                  $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;
     var linkproturi = '$linkproturi';                  $querystr_for_js = &js_escape($querystring);
     var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');              }
     if (linkproturi == path) {          } elsif ($logtoken ne '') {
         document.server.target = '_self';              $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;
     }              $querystr_for_js = &js_escape('logtoken='.$logtoken);
 ENDTARG          }
             }          my $ssohref;
             $in_frame_js = <<ENDJS;          if ($samlwindow) {
 <script type="text/javascript">              $sso_onclick = <<"ENDJS";
 // <![CDATA[  if (document.getElementById('LC_sso_login_link')) {
 if ((window.self !== window.top) && (document.server.target != '_self')) {      var ssoelem = document.getElementById('LC_sso_login_link')
     $set_target      ssoelem.addEventListener('click',samlWinFunction,false);
     $sso_onclick      var windows = {};
 }      function samlWinFunction(evt) {
 // ]]>          evt.preventDefault();
 </script>          var url = '$ssologin_for_js';
 ENDJS          var name = 'lcssowin';
         }          var querystr = '$querystr_for_js';
     } elsif ($samlwindow) {          if (querystr) {
         $in_frame_js = <<ENDJS;              url += '?'+querystr+'&lcssowin=1';
 <script type="text/javascript">          } else {
 // <![CDATA[              url += '?lcssowin=1';
 if ((window.self !== window.top) && (document.server.target != '_self')) {          }
     $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;
       }
     $r->print(<<ENDLOGIN);  }
 <div style="display:$stdauthformstyle;" id="LC_standard_login">  ENDJS
 <div class="LC_Box" style="background:$loginbox_bg;">          }
   $logintitle          if ($samlssoimg ne '') {
   $loginform              $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'" id="LC_sso_login_link">'.
   $noscript_warning                         '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';
 </div>          } else {
                 $ssohref = '<a href="'.$ssologin.'" id="LC_sso_login_link">'.$samlssotext.'</a>';
 <div class="LC_Box" style="padding-top: 10px;">          }
   $loginhelp          if (($env{'form.saml'} eq 'no') ||
   $forgotpw              (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {
   $contactblock              $ssoauthstyle = 'none';
   $newuserlink              $stdauthformstyle = 'inline-block';
   $coursecatalog              $logintype = $samlnonsso;
 </div>          }
 </div>          $r->print(<<ENDSAML);
   <p>
 ENDLOGIN  Log-in type:
     $r->print('</div><div>'."\n");  <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />
     if ($showmainlogo) {  <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>
         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);  </p>
         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");  <div style="display:$ssoauthstyle" id="LC_SSO_login">
     }  <div class="LC_Box" style="padding-top: 10px;">
 $r->print(<<ENDTOP);  $ssohref
 $announcements  $noscript_warning
 </div>  </div>
 <hr style="clear:both;" />  <div class="LC_Box" style="padding-top: 10px;">
 ENDTOP  $loginhelp
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);  $contactblock
     $domainrow = <<"END";  $coursecatalog
       <tr>  </div>
        <td  align="left" valign="top">  </div>
         <small><b>$lt{'dom'}:&nbsp;</b></small>  ENDSAML
        </td>      } else {
        <td  align="left" valign="top">          if ($env{'form.ltoken'}) {
         <small><tt>&nbsp;$domain</tt></small>              &Apache::lonnet::tmpdel($env{'form.ltoken'});
        </td>              delete($env{'form.ltoken'});
       </tr>          }
 END      }
     $serverrow = <<"END";      my $in_frame_js;
       <tr>      if ($linkprot_for_login) {
        <td  align="left" valign="top">          my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);
         <small><b>$lt{'serv'}:&nbsp;</b></small>          if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {
        </td>              my $set_target;
        <td align="left" valign="top">              if (($env{'form.retry'}) || ($env{'form.sso'})) {
         <small><tt>&nbsp;$lonhost ($role)</tt></small>                  if ($linkproturi eq $env{'form.firsturl'}) {
        </td>                      $set_target = "    document.server.target = '_self';";
       </tr>                  }
 END              } else {
     if ($loadlim) {                  $set_target = <<ENDTARG;
         $loadrow = <<"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{'load'}:&nbsp;</b></small>          document.server.target = '_self';
        </td>      }
        <td align="left" valign="top">  ENDTARG
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>              }
        </td>              $in_frame_js = <<ENDJS;
       </tr>  <script type="text/javascript">
 END  // <![CDATA[
     }  if ((window.self !== window.top) && (document.server.target != '_self')) {
     if ($uloadlim) {      $set_target
         $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>      } elsif ($samlwindow) {
        </td>          $in_frame_js = <<ENDJS;
       </tr>  <script type="text/javascript">
 END  // <![CDATA[
     }  if ((window.self !== window.top) && (document.server.target != '_self')) {
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {      $sso_onclick
         $versionrow = <<"END";  }
       <tr>  // ]]>
        <td colspan="2" align="left">  </script>
         <small>$version</small>  ENDJS
        </td>      }
       </tr>  
 END      $r->print(<<ENDLOGIN);
     }  <div style="display:$stdauthformstyle;" id="LC_standard_login">
   <div class="LC_Box" style="background:$loginbox_bg;">
     $r->print(<<ENDDOCUMENT);    $logintitle
     <div style="float: left;">    $loginform
      <table border="0" cellspacing="0" cellpadding="0">    $noscript_warning
 $domainrow  </div>
 $serverrow   
 $loadrow      <div class="LC_Box" style="padding-top: 10px;">
 $userloadrow    $loginhelp
 $versionrow    $forgotpw
      </table>    $contactblock
     </div>    $newuserlink
     <div style="float: right;">    $coursecatalog
     $domainlogo  </div>
     </div>  </div>
     <br style="clear:both;" />  
  </div>  ENDLOGIN
       $r->print('</div><div>'."\n");
 $in_frame_js      if ($showmainlogo) {
 <script type="text/javascript">          my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);
 // <![CDATA[          $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");
 // the if prevents the script error if the browser can not handle this      }
 if ( document.client.uname ) { document.client.uname.focus(); }  $r->print(<<ENDTOP);
 // ]]>  $announcements
 </script>  </div>
 $helpdeskscript  <hr style="clear:both;" />
   ENDTOP
 ENDDOCUMENT      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versioninfo);
     my %endargs = ( 'noredirectlink' => 1, );      $domainrow = <<"END";
     $r->print(&Apache::loncommon::end_page(\%endargs));        <tr>
     return OK;         <th align="left" valign="top">
 }          <small><b>$lt{'dom'}:&nbsp;</b></small>
          </th>
 sub check_loginvia {         <td align="left" valign="top">
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;          <small><tt>&nbsp;$domain</tt></small>
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {         </td>
         return;        </tr>
     }  END
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);      $serverrow = <<"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{'serv'}:&nbsp;</b></small>
     if ($loginvia ne '') {         </th>
         my $noredirect;         <td align="left" valign="top">
         my $ip = &Apache::lonnet::get_requestor_ip();          <small><tt>&nbsp;$lonhost ($role)</tt></small>
         if ($ip eq '127.0.0.1') {         </td>
             $noredirect = 1;        </tr>
         } else {  END
             if ($loginvia_exempt ne '') {      if ($loadlim) {
                 my @exempt = split(',',$loginvia_exempt);          $loadrow = <<"END";
                 if (grep(/^\Q$ip\E$/,@exempt)) {        <tr>
                     $noredirect = 1;         <th align="left" valign="top">
                 }          <small><b>$lt{'load'}:&nbsp;</b></small>
             }         </th>
         }         <td align="left" valign="top">
         unless ($noredirect) {          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
             my ($newhost,$path);         </td>
             if ($loginvia =~ /:/) {        </tr>
                 ($newhost,$path) = split(':',$loginvia);  END
             } else {      }
                 $newhost = $loginvia;      if ($uloadlim) {
             }          $userloadrow = <<"END";
             if ($newhost ne $lonhost) {        <tr>
                 if (&Apache::lonnet::hostname($newhost) ne '') {         <th align="left" valign="top">
                     if ($balcookie) {          <small><b>$lt{'userload'}:&nbsp;</b></small>
                         my ($balancer,$cookie) = split(/:/,$balcookie);         </th>
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {         <td align="left" valign="top">
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {         </td>
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {        </tr>
                                     while (my $filename=readdir($dh)) {  END
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {      }
                                             my $handle = $1;      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
                                             my %hash =          $versioninfo = "<small>$version</small>";
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,      }
                                                                                      ['request.balancercookie',  
                                                                                       'user.linkedenv']);      $r->print(<<ENDDOCUMENT);
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {      <div class="LC_landmark" role="contentinfo">
                                                 if (unlink("$lonidsdir/$filename")) {      <div style="float: left;">
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&       <table border="0" cellspacing="0" cellpadding="0">
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&  $domainrow
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {  $serverrow
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");  $loadrow    
                                                     }  $userloadrow
                                                 }       </table>
                                             }      $versioninfo
                                             last;      </div>
                                         }      <div style="float: right;">
                                     }      $domainlogo
                                     closedir($dh);      </div>
                                 }      </div>
                             }      <br style="clear:both;" />
                         }   </div>
                     }  
                     $output = &redirect_page($newhost,$path);  $in_frame_js
                 }  <script type="text/javascript">
             }  // <![CDATA[
         }  // the if prevents the script error if the browser can not handle this
     }  if ( document.client.uname ) { document.client.uname.focus(); }
     return $output;  // ]]>
 }  </script>
   $helpdeskscript
 sub redirect_page {  
     my ($desthost,$path) = @_;  ENDDOCUMENT
     my $hostname = &Apache::lonnet::hostname($desthost);      my %endargs = ( 'noredirectlink' => 1, );
     my $protocol = $Apache::lonnet::protocol{$desthost};      $r->print(&Apache::loncommon::end_page(\%endargs));
     $protocol = 'http' if ($protocol ne 'https');      return OK;
     unless ($path =~ m{^/}) {  }
         $path = '/'.$path;  
     }  sub check_loginvia {
     my $url = $protocol.'://'.$hostname.$path;      my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;
     my $args = {};      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
     if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {          return;
         $url = $protocol.'://'.$hostname.$env{'form.firsturl'};      }
         if (($env{'form.ltoken'}) || ($env{'form.linkprot'} ne '') ||      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
             ($env{'form.linkkey'} ne '')) {      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
             my %link_info;      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
             if ($env{'form.ltoken'}) {      my $output;
                 %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});      if ($loginvia ne '') {
                 &Apache::lonnet::tmpdel($env{'form.ltoken'});          my $noredirect;
                 $args->{'only_body'} = 1;          my $ip = &Apache::lonnet::get_requestor_ip();  
             } elsif ($env{'form.linkprot'}) {          if ($ip eq '127.0.0.1') {
                 $link_info{'linkprot'} = $env{'form.linkprot'};              $noredirect = 1;
                 foreach my $item ('linkprotuser','linkprotexit') {          } else {
                     if ($env{'form.'.$item}) {              if ($loginvia_exempt ne '') {
                         $link_info{$item} = $env{'form.'.$item};                  my @exempt = split(',',$loginvia_exempt);
                     }                  if (grep(/^\Q$ip\E$/,@exempt)) {
                 }                      $noredirect = 1;
                 $args->{'only_body'} = 1;                  }
             } elsif ($env{'form.linkkey'} ne '') {              }
                 $link_info{'linkkey'} = $env{'form.linkkey'};          }
             }          unless ($noredirect) {
             my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');              my ($newhost,$path);
             unless (($token eq 'con_lost') || ($token eq 'refused') ||              if ($loginvia =~ /:/) {
                     ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {                  ($newhost,$path) = split(':',$loginvia);
                 $url .= '?ltoken='.$token;              } else {
             }                  $newhost = $loginvia;
         }              }
     } else {              if ($newhost ne $lonhost) {
         my $querystring;                  if (&Apache::lonnet::hostname($newhost) ne '') {
         if ($env{'form.firsturl'} ne '') {                      if ($balcookie) {
             if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {                          my ($balancer,$cookie) = split(/:/,$balcookie);
                 $querystring = &uri_escape_utf8($env{'form.firsturl'});                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
             } else {                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
                 $querystring = &uri_escape($env{'form.firsturl'});                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
             }                                  if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
             $querystring = &HTML::Entities::encode($querystring,"'");                                      while (my $filename=readdir($dh)) {
             $querystring = '?firsturl='.$querystring;                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
         }                                              my $handle = $1;
         if ($env{'form.ltoken'}) {                                              my %hash =
             my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
             &Apache::lonnet::tmpdel($env{'form.ltoken'});                                                                                       ['request.balancercookie',
             my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');                                                                                        'user.linkedenv']);
             unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
                     ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {                                                  if (unlink("$lonidsdir/$filename")) {
                 unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {                                                      if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
                     $url = $protocol.'://'.$hostname.'/adm/roles';                                                          (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
                 }                                                          (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
                 $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;                                                          unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
             }                                                      }
         }                                                  }
         $url .= $querystring;                                              }
     }                                              last;
     $args->{'redirect'} = [0,$url];                                          }
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,$args);                                      }
     my $end_page   = &Apache::loncommon::end_page();                                      closedir($dh);
     return $start_page.$end_page;                                  }
 }                              }
                           }
 sub contactdisplay {                      }
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,                      $output = &redirect_page($newhost,$path);
         $possdoms) = @_;                  }
     my $contactblock;              }
     my $origmail;          }
     if (ref($possdoms) eq 'ARRAY') {      }
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {       return $output;
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};  }
         }  
     }  sub redirect_page {
     my $requestmail =       my ($desthost,$path) = @_;
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',      my $hostname = &Apache::lonnet::hostname($desthost);
                                                  $authdomain,$origmail);      my $protocol = $Apache::lonnet::protocol{$desthost};
     unless ($showhelpdesk eq '0') {      $protocol = 'http' if ($protocol ne 'https');
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {      unless ($path =~ m{^/}) {
             $showhelpdesk = 1;          $path = '/'.$path;
         } else {      }
             $showhelpdesk = 0;      my $url = $protocol.'://'.$hostname.$path;
         }      my $args = {};
     }      if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     if ($servadm && $showadminmail) {          $url = $protocol.'://'.$hostname.$env{'form.firsturl'};
         $contactblock .= $$lt{'servadm'}.':<br />'.          if (($env{'form.ltoken'}) || ($env{'form.linkprot'} ne '') ||
                          '<tt>'.$servadm.'</tt><br />';              ($env{'form.linkkey'} ne '')) {
     }              my %link_info;
     if ($showhelpdesk) {              if ($env{'form.ltoken'}) {
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';                  %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
         my $thisurl = &escape('/adm/login');                  &Apache::lonnet::tmpdel($env{'form.ltoken'});
         $$helpdeskscript = <<"ENDSCRIPT";                  $args->{'only_body'} = 1;
 <script type="text/javascript">              } elsif ($env{'form.linkprot'}) {
 // <![CDATA[                  $link_info{'linkprot'} = $env{'form.linkprot'};
 function helpdesk() {                  foreach my $item ('linkprotuser','linkprotexit','linkprotpbid','linkprotpburl') {
     var possdom = document.client.udom.value;                      if ($env{'form.'.$item}) {
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');                          $link_info{$item} = $env{'form.'.$item};
     if (codedom == '') {                      }
         codedom = "$authdomain";                  }
     }                  $args->{'only_body'} = 1;
     var querystr = "origurl=$thisurl&codedom="+codedom;              } elsif ($env{'form.linkkey'} ne '') {
     document.location.href = "/adm/helpdesk?"+querystr;                  $link_info{'linkkey'} = $env{'form.linkkey'};
     return;              }
 }              my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
 // ]]>              unless (($token eq 'con_lost') || ($token eq 'refused') ||
 </script>                      ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
 ENDSCRIPT                  $url .= '?ltoken='.$token;
     }              }
     return $contactblock;          }
 }      } else {
           my $querystring;
 sub forgotpwdisplay {          if ($env{'form.firsturl'} ne '') {
     my (%lt) = @_;              if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
     my $prompt_for_resetpw = 1;                   $querystring = &uri_escape_utf8($env{'form.firsturl'});
     if ($prompt_for_resetpw) {              } else {
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';                  $querystring = &uri_escape($env{'form.firsturl'});
     }              }
     return;              $querystring = &HTML::Entities::encode($querystring,"'");
 }              $querystring = '?firsturl='.$querystring;
           }
 sub coursecatalog_link {          if ($env{'form.ltoken'}) {
     my ($linkname) = @_;              my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
     return <<"END";              &Apache::lonnet::tmpdel($env{'form.ltoken'});
       <a href="/adm/coursecatalog">$linkname</a>              my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
 END              unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||
 }                      ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                   unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {
 sub newuser_link {                      $url = $protocol.'://'.$hostname.'/adm/roles';
     my ($linkname) = @_;                  }
     return '<a href="/adm/createaccount">'.$linkname.'</a>';                  $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;
 }              }
           }
 sub decode_token {          $url .= $querystring;
     my ($info) = @_;      }
     my ($firsturl,@rest)=split(/\&/,$info);      $args->{'redirect'} = [0,$url,'','',1];
     my %form;      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,$args);
     if ($firsturl ne '') {      my $end_page   = &Apache::loncommon::end_page();
         $form{'firsturl'} = &unescape($firsturl);      return $start_page.$end_page;
     }  }
     foreach my $item (@rest) {  
         my ($key,$value) = split(/=/,$item);  sub contactdisplay {
         $form{$key} = &unescape($value);      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
     }          $possdoms) = @_;
     return %form;      my $contactblock;
 }      my $origmail;
       if (ref($possdoms) eq 'ARRAY') {
 1;          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
 __END__              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
           }
       }
       my $requestmail =
           &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                                    $authdomain,$origmail);
       unless ($showhelpdesk eq '0') {
           if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
               $showhelpdesk = 1;
           } else {
               $showhelpdesk = 0;
           }
       }
       if ($servadm && $showadminmail) {
           $contactblock = '<div class="LC_login_links">'.$lt->{'servadm'}.':<br />'.
                           '<tt>'.$servadm.'</tt></div>';
       }
       if ($showhelpdesk) {
           $contactblock .= '<div class="LC_login_links">'.
                            '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a></div>';
           my $thisurl = &escape('/adm/login');
           $$helpdeskscript = <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function helpdesk() {
       var possdom = document.client.udom.value;
       var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
       if (codedom == '') {
           codedom = "$authdomain";
       }
       var querystr = "origurl=$thisurl&codedom="+codedom;
       document.location.href = "/adm/helpdesk?"+querystr;
       return;
   }
   // ]]>
   </script>
   ENDSCRIPT
       }
       return $contactblock;
   }
   
   sub forgotpwdisplay {
       my (%lt) = @_;
       my $prompt_for_resetpw = 1;
       if ($prompt_for_resetpw) {
           return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
       }
       return;
   }
   
   sub coursecatalog_link {
       my ($linkname) = @_;
       return <<"END";
         <a href="/adm/coursecatalog">$linkname</a>
   END
   }
   
   sub newuser_link {
       my ($linkname) = @_;
       return '<a href="/adm/createaccount">'.$linkname.'</a>';
   }
   
   sub decode_token {
       my ($info) = @_;
       my ($firsturl,@rest)=split(/\&/,$info);
       my %form;
       if ($firsturl ne '') {
           $form{'firsturl'} = &unescape($firsturl);
       }
       foreach my $item (@rest) {
           my ($key,$value) = split(/=/,$item);
           $form{$key} = &unescape($value);
       }
       return %form;
   }
   
   1;
   __END__

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


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