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

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

Removed from v.1.158.2.13.2.7  
changed lines
  Added in v.1.211


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