Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.2 and 1.181

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


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