Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.15 and 1.201

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


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