Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.3 and 1.184

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

Removed from v.1.158.2.3  
changed lines
  Added in v.1.184


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