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

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


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