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

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


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