Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.9.2.2 and 1.205

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


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