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

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

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


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