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

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


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