Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13 and 1.204

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


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