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

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


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