Diff for /loncom/auth/lonlogin.pm between versions 1.151 and 1.179

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


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