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

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


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