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

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

Removed from v.1.158.2.13.2.6  
changed lines
  Added in v.1.206


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