Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.15 and 1.160

version 1.158.2.15, 2022/02/24 16:00:23 version 1.160, 2014/12/05 12:03:20
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Login Screen  # Login Screen
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonlogin;  package Apache::lonlogin;
   
 use strict;  use strict;
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use Apache::File ();  use Apache::File ();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonauth();  use Apache::lonauth();
 use Apache::lonlocal;  use Apache::lonlocal;
 use Apache::migrateuser();  use Apache::migrateuser();
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA;
 use URI::Escape;   
 use HTML::Entities();  sub handler {
 use CGI::Cookie();      my $r = shift;
    
 sub handler {      &Apache::loncommon::get_unprocessed_cgi
     my $r = shift;   (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},
         $ENV{'REDIRECT_QUERY_STRING'}),
     &Apache::loncommon::get_unprocessed_cgi   ['interface','username','domain','firsturl','localpath','localres',
  (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},    'token','role','symb','iptoken']);
       $ENV{'REDIRECT_QUERY_STRING'}),      if (!defined($env{'form.firsturl'})) {
  ['interface','username','domain','firsturl','localpath','localres',          &Apache::lonacc::get_posted_cgi($r,['firsturl']);
   'token','role','symb','iptoken','btoken','saml','sso','retry']);      }
   
 # -- check if they are a migrating user  # -- check if they are a migrating user
     if (defined($env{'form.token'})) {      if (defined($env{'form.token'})) {
  return &Apache::migrateuser::handler($r);   return &Apache::migrateuser::handler($r);
     }      }
   
     my $lonhost = $r->dir_config('lonHostID');      &Apache::loncommon::no_cache($r);
     if (($env{'form.sso'}) || ($env{'form.retry'})) {      &Apache::lonlocal::get_language_handle($r);
         my $infotoken;      &Apache::loncommon::content_type($r,'text/html');
         if ($env{'form.sso'}) {      $r->send_http_header;
             $infotoken = $env{'form.sso'};      return OK if $r->header_only;
         } else {  
             $infotoken = $env{'form.retry'};  
         }  # Are we re-routing?
         my $data = &Apache::lonnet::reply('tmpget:'.$infotoken,$lonhost);      my $londocroot = $r->dir_config('lonDocRoot');
         unless (($data=~/^error/) || ($data eq 'con_lost') ||      if (-e "$londocroot/lon-status/reroute.txt") {
                 ($data eq 'no_such_host')) {   &Apache::lonauth::reroute($r);
             my %info = &decode_token($data);   return OK;
             foreach my $item (keys(%info)) {      }
                 $env{'form.'.$item} = $info{$item};  
             }      $env{'form.firsturl'} =~ s/(`)/'/g;
             &Apache::lonnet::tmpdel($infotoken);  
         }  # -------------------------------- Prevent users from attempting to login twice
     } else {      my $handle = &Apache::lonnet::check_for_valid_session($r);
         if (!defined($env{'form.firsturl'})) {      if ($handle ne '') {
             &Apache::lonacc::get_posted_cgi($r,['firsturl']);          my $lonidsdir=$r->dir_config('lonIDsDir');
         }          if ($handle=~/^publicuser\_/) {
         if ($env{'form.firsturl'} eq '/adm/logout') {  # For "public user" - remove it, we apparently really want to login
             delete($env{'form.firsturl'});      unlink($r->dir_config('lonIDsDir')."/$handle.id");
         }          } else {
     }  # Indeed, a valid token is found
               &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
 # For "public user" - remove any exising "public" cookie, as user really wants to log-in      my $start_page =
     my ($handle,$lonidsdir,$expirepub,$userdom);          &Apache::loncommon::start_page('Already logged in');
     $lonidsdir=$r->dir_config('lonIDsDir');      my $end_page =
     unless ($r->header_only) {          &Apache::loncommon::end_page();
         $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);              my $dest = '/adm/roles';
         if ($handle ne '') {              if ($env{'form.firsturl'} ne '') {
             if ($handle=~/^publicuser\_/) {                  $dest = $env{'form.firsturl'};
                 unlink($r->dir_config('lonIDsDir')."/$handle.id");              }
                 undef($handle);      $r->print(
                 undef($userdom);                    $start_page
                 $expirepub = 1;                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
             }                   .'<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>'
     }                   .$end_page
                    );
     &Apache::loncommon::no_cache($r);              return OK;
     &Apache::lonlocal::get_language_handle($r);          }
     &Apache::loncommon::content_type($r,'text/html');      }
     if ($expirepub) {  
         my $c = new CGI::Cookie(-name    => 'lonPubID',  # ---------------------------------------------------- No valid token, continue
                                 -value   => '',  
                                 -expires => '-10y',);  # ---------------------------- Not possible to really login to domain "public"
         $r->header_out('Set-cookie' => $c);      if ($env{'form.domain'} eq 'public') {
     } elsif (($handle eq '') && ($userdom ne '')) {   $env{'form.domain'}='';
         my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));   $env{'form.username'}='';
         foreach my $name (keys(%cookies)) {      }
             next unless ($name =~ /^lon(|S|Link|Pub)ID$/);  
             my $c = new CGI::Cookie(-name    => $name,  # ------ Is this page requested because /adm/migrateuser detected an IP change?
                                     -value   => '',      my %sessiondata;
                                     -expires => '-10y',);      if ($env{'form.iptoken'}) {
             $r->headers_out->add('Set-cookie' => $c);          %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});
         }          my $delete = &Apache::lonnet::tmpdel($env{'form.token'});
     }      }
     $r->send_http_header;  # ----------------------------------------------------------- Process Interface
     return OK if $r->header_only;      $env{'form.interface'}=~s/\W//g;
   
       (undef,undef,undef,undef,undef,undef,my $clientmobile) =
 # Are we re-routing?          &Apache::loncommon::decode_user_agent();
     my $londocroot = $r->dir_config('lonDocRoot');   
     if (-e "$londocroot/lon-status/reroute.txt") {      my $iconpath=
  &Apache::lonauth::reroute($r);   &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
  return OK;  
     }      my $lonhost = $r->dir_config('lonHostID');
       my $domain = &Apache::lonnet::default_login_domain();
 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)      if ($lonhost ne '') {
           unless ($sessiondata{'sessionserver'}) {
     my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);              my $redirect = &check_loginvia($domain,$lonhost);
     if ($found_server) {              if ($redirect) {
         my $hostname = &Apache::lonnet::hostname($found_server);                  $r->print($redirect);
         if ($hostname ne '') {                  return OK;
             my $protocol = $Apache::lonnet::protocol{$found_server};              }
             $protocol = 'http' if ($protocol ne 'https');          }
             my $dest = '/adm/roles';      }
             if ($env{'form.firsturl'} ne '') {  
                 $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');      if (($sessiondata{'domain'}) &&
             }          (&Apache::lonnet::domain($env{'form.domain'},'description'))) {
             my %info = (          $domain=$sessiondata{'domain'};
                          balcookie => $lonhost.':'.$balancer_cookie,      } elsif (($env{'form.domain'}) &&
                        );   (&Apache::lonnet::domain($env{'form.domain'},'description'))) {
             if ($env{'form.role'}) {   $domain=$env{'form.domain'};
                 $info{'role'} = $env{'form.role'};      }
             }  
             if ($env{'form.symb'}) {      my $role    = $r->dir_config('lonRole');
                 $info{'symb'} = $env{'form.symb'};      my $loadlim = $r->dir_config('lonLoadLim');
             }      my $uloadlim= $r->dir_config('lonUserLoadLim');
             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);      my $servadm = $r->dir_config('lonAdmEMail');
             unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||      my $tabdir  = $r->dir_config('lonTabDir');
                     ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {      my $include = $r->dir_config('lonIncludes');
                 $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;      my $expire  = $r->dir_config('lonExpire');
             }      my $version = $r->dir_config('lonVersion');
             unless ($found_server eq $lonhost) {      my $host_name = &Apache::lonnet::hostname($lonhost);
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);  
                 $hostname = $alias if ($alias ne '');  # --------------------------------------------- Default values for login fields
             }     
             my $url = $protocol.'://'.$hostname.$dest;      my ($authusername,$authdomain);
             my $start_page =      if ($sessiondata{'username'}) {
                 &Apache::loncommon::start_page('Switching Server ...',undef,          $authusername=$sessiondata{'username'};
                                                {'redirect'       => [0,$url],});      } else {
             my $end_page   = &Apache::loncommon::end_page();          $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});
             $r->print($start_page.$end_page);          $authusername=($env{'form.username'}?$env{'form.username'}:'');
             return OK;      }
         }      if ($sessiondata{'domain'}) {
     }          $authdomain=$sessiondata{'domain'};
       } else {
 #          $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});
 # Check if a LON-CAPA load balancer sent user here because user's browser sent          $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);
 # it a balancer cookie for an active session on this server.      }
 #  
   # ---------------------------------------------------------- Determine own load
     my $balcookie;      my $loadavg;
     if ($env{'form.btoken'}) {      {
         my %info = &Apache::lonnet::tmpget($env{'form.btoken'});   my $loadfile=Apache::File->new('/proc/loadavg');
         $balcookie = $info{'balcookie'};   $loadavg=<$loadfile>;
         &Apache::lonnet::tmpdel($env{'form.btoken'});      }
         delete($env{'form.btoken'});      $loadavg =~ s/\s.*//g;
     }  
       my ($loadpercent,$userloadpercent);
 #      if ($loadlim) {
 # If browser sent an old cookie for which the session file had been removed          $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
 # check if configuration for user's domain has a portal URL set.  If so      }
 # switch user's log-in to the portal.      if ($uloadlim) {
 #          $userloadpercent=&Apache::lonnet::userload();
       }
     if (($handle eq '') && ($userdom ne '')) {  
         my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);      my $firsturl=
         if ($domdefaults{'portal_def'} =~ /^https?\:/) {      ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});
             my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,  
                                           {'redirect' => [0,$domdefaults{'portal_def'}],});  # ----------------------------------------------------------- Get announcements
             my $end_page   = &Apache::loncommon::end_page();      my $announcements=&Apache::lonnet::getannounce();
             $r->print($start_page.$end_page);  # -------------------------------------------------------- Set login parameters
             return OK;  
         }      my @hexstr=('0','1','2','3','4','5','6','7',
     }                  '8','9','a','b','c','d','e','f');
       my $lkey='';
 # -------------------------------- Prevent users from attempting to login twice      for (0..7) {
     if ($handle ne '') {          $lkey.=$hexstr[rand(15)];
         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);      }
  my $start_page =   
     &Apache::loncommon::start_page('Already logged in');      my $ukey='';
  my $end_page =       for (0..7) {
     &Apache::loncommon::end_page();          $ukey.=$hexstr[rand(15)];
         my $dest = '/adm/roles';      }
         if ($env{'form.firsturl'} ne '') {  
             $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');      my $lextkey=hex($lkey);
         }      if ($lextkey>2147483647) { $lextkey-=4294967296; }
  $r->print(  
               $start_page      my $uextkey=hex($ukey);
              .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'      if ($uextkey>2147483647) { $uextkey-=4294967296; }
              .'<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>'  # -------------------------------------------------------- Store away log token
              .$end_page      my $tokenextras;
              );      if ($env{'form.role'}) {
         return OK;          $tokenextras = '&role='.&escape($env{'form.role'});
     }      }
       if ($env{'form.symb'}) {
 # ---------------------------------------------------- No valid token, continue          if (!$tokenextras) {
               $tokenextras = '&';
 # ---------------------------- Not possible to really login to domain "public"          }
     if ($env{'form.domain'} eq 'public') {          $tokenextras .= '&symb='.&escape($env{'form.symb'});
  $env{'form.domain'}='';      }
  $env{'form.username'}='';      my $logtoken=Apache::lonnet::reply(
     }         'tmpput:'.$ukey.$lkey.'&'.$firsturl.$tokenextras,
          $lonhost);
 # ------ Is this page requested because /adm/migrateuser detected an IP change?  
     my %sessiondata;  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
     if ($env{'form.iptoken'}) {  #    we are in serious trouble
         %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});  
         unless ($sessiondata{'sessionserver'}) {      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
             my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});          if ($logtoken eq 'no_such_host') {
             delete($env{'form.iptoken'});              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
         }          }
     }          my $spares='';
 # ----------------------------------------------------------- Process Interface   my $last;
     $env{'form.interface'}=~s/\W//g;          foreach my $hostid (sort
       {
     (undef,undef,undef,undef,undef,undef,my $clientmobile) =   &Apache::lonnet::hostname($a) cmp
         &Apache::loncommon::decode_user_agent($r);      &Apache::lonnet::hostname($b);
       }
     my $iconpath=       keys(%Apache::lonnet::spareid)) {
  &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));              next if ($hostid eq $lonhost);
       my $hostname = &Apache::lonnet::hostname($hostid);
     my $domain = &Apache::lonnet::default_login_domain();      next if (($last eq $hostname) || ($hostname eq ''));
     my $defdom = $domain;              $spares.='<br /><font size="+1"><a href="http://'.
     if ($lonhost ne '') {                  $hostname.
         unless ($sessiondata{'sessionserver'}) {                  '/adm/login?domain='.$authdomain.'">'.
             my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);                  $hostname.'</a>'.
             if ($redirect) {                  ' '.&mt('(preferred)').'</font>'.$/;
                 $r->print($redirect);      $last=$hostname;
                 return OK;          }
             }          if ($spares) {
         }              $spares.= '<br />';
     }          }
           my %all_hostnames = &Apache::lonnet::all_hostnames();
     if (($sessiondata{'domain'}) &&          foreach my $hostid (sort
         (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {      {
         $domain=$sessiondata{'domain'};   &Apache::lonnet::hostname($a) cmp
     } elsif (($env{'form.domain'}) &&       &Apache::lonnet::hostname($b);
  (&Apache::lonnet::domain($env{'form.domain'},'description'))) {      }
  $domain=$env{'form.domain'};      keys(%all_hostnames)) {
     }              next if ($hostid eq $lonhost || $Apache::lonnet::spareid{$hostid});
               my $hostname = &Apache::lonnet::hostname($hostid);
     my $role    = $r->dir_config('lonRole');              next if (($last eq $hostname) || ($hostname eq ''));
     my $loadlim = $r->dir_config('lonLoadLim');              $spares.='<br /><a href="http://'.
     my $uloadlim= $r->dir_config('lonUserLoadLim');               $hostname.
     my $servadm = $r->dir_config('lonAdmEMail');               '/adm/login?domain='.$authdomain.'">'.
     my $tabdir  = $r->dir_config('lonTabDir');               $hostname.'</a>';
     my $include = $r->dir_config('lonIncludes');              $last=$hostname;
     my $expire  = $r->dir_config('lonExpire');           }
     my $version = $r->dir_config('lonVersion');           $r->print(
     my $host_name = &Apache::lonnet::hostname($lonhost);     '<html>'
     .'<head><title>'
 # --------------------------------------------- Default values for login fields    .&mt('The LearningOnline Network with CAPA')
         .'</title></head>'
     my ($authusername,$authdomain);    .'<body bgcolor="#FFFFFF">'
     if ($sessiondata{'username'}) {    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
         $authusername=$sessiondata{'username'};    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" align="right" />'
     } else {    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
         $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});          if ($spares) {
         $authusername=($env{'form.username'}?$env{'form.username'}:'');              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
     }                       .'</p>'
     if ($sessiondata{'domain'}) {                       .$spares);
         $authdomain=$sessiondata{'domain'};          }
     } else {          $r->print('</body>'
         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});                   .'</html>'
         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);          );
     }          return OK;
       }
 # ---------------------------------------------------------- Determine own load  
     my $loadavg;  # ----------------------------------------------- Apparently we are in business
     {      $servadm=~s/\,/\<br \/\>/g;
  my $loadfile=Apache::File->new('/proc/loadavg');  
  $loadavg=<$loadfile>;  # ----------------------------------------------------------- Front page design
     }      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
     $loadavg =~ s/\s.*//g;      my $font=&Apache::loncommon::designparm('login.font',$domain);
       my $link=&Apache::loncommon::designparm('login.link',$domain);
     my ($loadpercent,$userloadpercent);      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
     if ($loadlim) {      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
     }      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
     if ($uloadlim) {      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
         $userloadpercent=&Apache::lonnet::userload();      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 $firsturl=      my $domainlogo=&Apache::loncommon::domainlogo($domain);
     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});      my $showbanner = 1;
       my $showmainlogo = 1;
 # ----------------------------------------------------------- Get announcements      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
     my $announcements=&Apache::lonnet::getannounce();          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
 # -------------------------------------------------------- Set login parameters      }
       if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
     my @hexstr=('0','1','2','3','4','5','6','7',          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
                 '8','9','a','b','c','d','e','f');      }
     my $lkey='';      my $showadminmail;
     for (0..7) {      my @possdoms = &Apache::lonnet::current_machine_domains();
         $lkey.=$hexstr[rand(15)];      if (grep(/^\Q$domain\E$/,@possdoms)) {
     }          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
       }
     my $ukey='';      my $showcoursecat =
     for (0..7) {          &Apache::loncommon::designparm('login.coursecatalog',$domain);
         $ukey.=$hexstr[rand(15)];      my $shownewuserlink =
     }          &Apache::loncommon::designparm('login.newuser',$domain);
       my $showhelpdesk =
     my $lextkey=hex($lkey);          &Apache::loncommon::designparm('login.helpdesk',$domain);
     if ($lextkey>2147483647) { $lextkey-=4294967296; }      my $now=time;
       my $js = (<<ENDSCRIPT);
     my $uextkey=hex($ukey);  
     if ($uextkey>2147483647) { $uextkey-=4294967296; }  <script type="text/javascript" language="JavaScript">
   // <![CDATA[
 # -------------------------------------------------------- Store away log token  function send()
     my $tokenextras;  {
     my @names = ('role','symb','iptoken');  this.document.server.elements.uname.value
     foreach my $name (@names) {  =this.document.client.elements.uname.value;
         if ($env{'form.'.$name} ne '') {  
             $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});  this.document.server.elements.udom.value
         }  =this.document.client.elements.udom.value;
     }  
     my $logtoken=Apache::lonnet::reply(  uextkey=this.document.client.elements.uextkey.value;
        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,  lextkey=this.document.client.elements.lextkey.value;
        $lonhost);  initkeys();
   
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname  this.document.server.elements.upass0.value
 #    we are in serious trouble      =this.document.client.elements.upass$now.value.substr(0,15);
   this.document.server.elements.upass1.value
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {      =this.document.client.elements.upass$now.value.substr(15,15);
         if ($logtoken eq 'no_such_host') {  this.document.server.elements.upass2.value
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');      =this.document.client.elements.upass$now.value.substr(30,15);
         }  
         my $spares='';  if(this.document.server.action.substr(0,5) === 'http:'){
         my (@sparehosts,%spareservers);      for (var idx in [1,2,3]){
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);          this.document.server.elements['upass' + idx].value =
         if (ref($sparesref) eq 'HASH') {              crypted(this.document.server.elements['upass' + idx].value);
             foreach my $key (keys(%{$sparesref})) {      }
                 if (ref($sparesref->{$key}) eq 'ARRAY') {  }
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp  
                                         &Apache::lonnet::hostname($b);  this.document.client.elements.uname.value='';
                                       } @{$sparesref->{$key}};  this.document.client.elements.upass$now.value='';
                     if (@sorted) {  
                         if ($key eq 'primary') {  this.document.server.submit();
                             unshift(@sparehosts,@sorted);  return false;
                         } elsif ($key eq 'default') {  }
                             push(@sparehosts,@sorted);  
                         }  function enableInput() {
                     }      this.document.client.elements.upass$now.removeAttribute("readOnly");
                 }      this.document.client.elements.uname.removeAttribute("readOnly");
             }      this.document.client.elements.udom.removeAttribute("readOnly");
         }      return;
         foreach my $hostid (@sparehosts) {  }
             next if ($hostid eq $lonhost);  
     my $hostname = &Apache::lonnet::hostname($hostid);  // ]]>
     next if (($hostname eq '') || ($spareservers{$hostname}));  </script>
             $spareservers{$hostname} = 1;  
             my $protocol = $Apache::lonnet::protocol{$hostid};  ENDSCRIPT
             $protocol = 'http' if ($protocol ne 'https');  
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.  # --------------------------------------------------- Print login screen header
                 $hostname.  
                 '/adm/login?domain='.$authdomain.'">'.      my %add_entries = (
                 $hostname.'</a>'.         bgcolor      => "$mainbg",
                 ' '.&mt('(preferred)').'</span>'.$/;         text         => "$font",
         }         link         => "$link",
         if ($spares) {         vlink        => "$vlink",
             $spares.= '<br />';         alink        => "$alink",
         }                 onload       => 'javascript:enableInput();',);
         my %all_hostnames = &Apache::lonnet::all_hostnames();  
         foreach my $hostid (sort      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
     {         { 'redirect'       => [$expire,'/adm/roles'],
  &Apache::lonnet::hostname($a) cmp   'add_entries' => \%add_entries,
     &Apache::lonnet::hostname($b);   'only_body'   => 1,}));
     }  
     keys(%all_hostnames)) {  # ----------------------------------------------------------------------- Texts
             next if ($hostid eq $lonhost);  
             my $hostname = &Apache::lonnet::hostname($hostid);      my %lt=&Apache::lonlocal::texthash(
             next if (($hostname eq '') || ($spareservers{$hostname}));            'un'       => 'Username',
             $spareservers{$hostname} = 1;            'pw'       => 'Password',
             my $protocol = $Apache::lonnet::protocol{$hostid};            'dom'      => 'Domain',
             $protocol = 'http' if ($protocol ne 'https');            'perc'     => 'percent',
             $spares.='<br /><a href="'.$protocol.'://'.            'load'     => 'Server Load',
              $hostname.            'userload' => 'User Load',
              '/adm/login?domain='.$authdomain.'">'.            'catalog'  => 'Course/Community Catalog',
              $hostname.'</a>';            'log'      => 'Log in',
          }            'help'     => 'Log-in Help',
          $r->print(            'serv'     => 'Server',
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'            'servadm'  => 'Server Administration',
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'            'helpdesk' => 'Contact Helpdesk',
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'            'forgotpw' => 'Forgot password?',
   .&mt('The LearningOnline Network with CAPA')            'newuser'  => 'New User?',
   .'</title></head>'         );
   .'<body bgcolor="#FFFFFF">'  # -------------------------------------------------- Change password field name
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'  
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'      my $forgotpw = &forgotpwdisplay(%lt);
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');      $forgotpw .= '<br />' if $forgotpw;
         if ($spares) {      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      if ($loginhelp) {
                      .'</p>'          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
                      .$spares);      }
         }  
         $r->print('</body>'  # ---------------------------------------------------- Serve out DES JavaScript
                  .'</html>'      {
         );      my $jsh=Apache::File->new($include."/londes.js");
         return OK;      $r->print(<$jsh>);
     }      }
   # ---------------------------------------------------------- Serve rest of page
 # ----------------------------------------------- Apparently we are in business  
     $servadm=~s/\,/\<br \/\>/g;      $r->print(
       '<div class="LC_Box"'
 # ----------------------------------------------------------- Front page design     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);  );
     my $font=&Apache::loncommon::designparm('login.font',$domain);  
     my $link=&Apache::loncommon::designparm('login.link',$domain);      $r->print(<<ENDSERVERFORM);
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);  <form name="server" action="/adm/authenticate" method="post" target="_top">
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);     <input type="hidden" name="logtoken" value="$logtoken" />
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);     <input type="hidden" name="serverid" value="$lonhost" />
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);     <input type="hidden" name="uname" value="" />
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);     <input type="hidden" name="upass0" value="" />
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);     <input type="hidden" name="upass1" value="" />
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);     <input type="hidden" name="upass2" value="" />
     my $img=&Apache::loncommon::designparm('login.img',$domain);     <input type="hidden" name="udom" value="" />
     my $domainlogo=&Apache::loncommon::domainlogo($domain);     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
     my $showbanner = 1;     <input type="hidden" name="localres" value="$env{'form.localres'}" />
     my $showmainlogo = 1;    </form>
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {  ENDSERVERFORM
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);      my $coursecatalog;
     }      if (($showcoursecat eq '') || ($showcoursecat)) {
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);      }
     }      my $newuserlink;
     my $showadminmail;      if ($shownewuserlink) {
     my @possdoms = &Apache::lonnet::current_machine_domains();          $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
     if (grep(/^\Q$domain\E$/,@possdoms)) {      }
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);      my $logintitle =
     }          '<h2 class="LC_hcell"'
     my $showcoursecat =         .' style="background:'.$loginbox_header_bgcol.';'
         &Apache::loncommon::designparm('login.coursecatalog',$domain);         .' color:'.$loginbox_header_textcol.'">'
     my $shownewuserlink =          .$lt{'log'}
         &Apache::loncommon::designparm('login.newuser',$domain);         .'</h2>';
     my $showhelpdesk =  
         &Apache::loncommon::designparm('login.helpdesk',$domain);      my $noscript_warning='<noscript><span class="LC_warning"><b>'
     my $now=time;                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
     my $js = (<<ENDSCRIPT);                          .'</b></span></noscript>';
       my $helpdeskscript;
 <script type="text/javascript" language="JavaScript">      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
 // <![CDATA[                                         $authdomain,\$helpdeskscript,
 function send()                                         $showhelpdesk,\@possdoms);
 {  
 this.document.server.elements.uname.value      my $mobileargs;
 =this.document.client.elements.uname.value;      if ($clientmobile) {
           $mobileargs = 'autocapitalize="off" autocorrect="off"';
 this.document.server.elements.udom.value      }
 =this.document.client.elements.udom.value;      my $loginform=(<<LFORM);
   <form name="client" action="" onsubmit="return(send())">
 uextkey=this.document.client.elements.uextkey.value;    <input type="hidden" name="lextkey" value="$lextkey" />
 lextkey=this.document.client.elements.lextkey.value;    <input type="hidden" name="uextkey" value="$uextkey" />
 initkeys();    <b><label for="uname">$lt{'un'}</label>:</b><br />
     <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
 this.document.server.elements.upass0.value    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
     =getCrypted(this.document.client.elements.upass$now.value);    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
     <b><label for="udom">$lt{'dom'}</label>:</b><br />
 this.document.client.elements.uname.value='';    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
 this.document.client.elements.upass$now.value='';    <input type="submit" value="$lt{'log'}" />
   </form>
 this.document.server.submit();  LFORM
 return false;  
 }      if ($showbanner) {
           $r->print(<<HEADER);
 function enableInput() {  <!-- The LON-CAPA Header -->
     this.document.client.elements.upass$now.removeAttribute("readOnly");  <div style="background:$pgbg;margin:0;width:100%;">
     this.document.client.elements.uname.removeAttribute("readOnly");    <img src="$img" border="0" alt="The Learning Online Network with CAPA" />
     this.document.client.elements.udom.removeAttribute("readOnly");  </div>
     return;  HEADER
 }      }
       $r->print(<<ENDTOP);
 // ]]>  <div style="float:left;margin-top:0;">
 </script>  <div class="LC_Box" style="background:$loginbox_bg;">
     $logintitle
 ENDSCRIPT    $loginform
     $noscript_warning
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,  </div>
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);   
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);  <div class="LC_Box" style="padding-top: 10px;">
     @hosts = &Apache::lonnet::current_machine_ids();    $loginhelp
     $lonhost_in_use = $lonhost;    $forgotpw
     if (@hosts > 1) {    $contactblock
         foreach my $hostid (@hosts) {    $newuserlink
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {    $coursecatalog
                 $lonhost_in_use = $hostid;  </div>
                 last;  </div>
             }  
         }  <div>
     }  ENDTOP
     $saml_prefix = $defdom.'.login.saml_';      if ($showmainlogo) {
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {          $r->print(' <img src="'.$logo.'" alt="" />'."\n");
         $saml_landing = 1;      }
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};  $r->print(<<ENDTOP);
         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};  $announcements
         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};  </div>
         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};  <hr style="clear:both;" />
         $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};  ENDTOP
         $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
     }      $domainrow = <<"END";
     if ($saml_landing) {        <tr>
        if ($samlssotext eq '') {         <td  align="left" valign="top">
            $samlssotext = 'SSO Login';          <small><b>$lt{'dom'}:&nbsp;</b></small>
        }         </td>
        if ($samlnonsso eq '') {         <td  align="left" valign="top">
            $samlnonsso = 'Non-SSO Login';          <small><tt>&nbsp;$domain</tt></small>
        }         </td>
        $js .= <<"ENDSAMLJS";        </tr>
   END
 <script type="text/javascript">      $serverrow = <<"END";
 // <![CDATA[        <tr>
 function toggleLClogin() {         <td  align="left" valign="top">
     if (document.getElementById('LC_standard_login')) {          <small><b>$lt{'serv'}:&nbsp;</b></small>
         if (document.getElementById('LC_standard_login').style.display == 'none') {         </td>
             document.getElementById('LC_standard_login').style.display = 'inline-block';         <td align="left" valign="top">
             if (document.getElementById('LC_login_text')) {          <small><tt>&nbsp;$lonhost ($role)</tt></small>
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';         </td>
             }        </tr>
             if ( document.client.uname ) { document.client.uname.focus(); }  END
             if (document.getElementById('LC_SSO_login')) {      if ($loadlim) {
                 document.getElementById('LC_SSO_login').style.display = 'none';          $loadrow = <<"END";
             }        <tr>
         } else {         <td align="left" valign="top">
             document.getElementById('LC_standard_login').style.display = 'none';          <small><b>$lt{'load'}:&nbsp;</b></small>
             if (document.getElementById('LC_login_text')) {         </td>
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';         <td align="left" valign="top">
             }          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
             if (document.getElementById('LC_SSO_login')) {         </td>
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';        </tr>
             }  END
         }      }
     }      if ($uloadlim) {
     return;          $userloadrow = <<"END";
 }        <tr>
          <td align="left" valign="top">
 // ]]>          <small><b>$lt{'userload'}:&nbsp;</b></small>
 </script>         </td>
          <td align="left" valign="top">
 ENDSAMLJS          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
     }         </td>
         </tr>
 # --------------------------------------------------- Print login screen header  END
       }
     my %add_entries = (      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
        bgcolor      => "$mainbg",          $versionrow = <<"END";
        text         => "$font",        <tr>
        link         => "$link",         <td colspan="2" align="left">
        vlink        => "$vlink",          <small>$version</small>
        alink        => "$alink",         </td>
                onload       => 'javascript:enableInput();',);        </tr>
   END
     my ($headextra,$headextra_exempt);      }
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};  
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};      $r->print(<<ENDDOCUMENT);
     if ($headextra) {      <div style="float: left;">
         my $omitextra;       <table border="0" cellspacing="0" cellpadding="0">
         if ($headextra_exempt ne '') {  $domainrow
             my @exempt = split(',',$headextra_exempt);  $serverrow
             my $ip = &Apache::lonnet::get_requestor_ip();  $loadrow    
             if (grep(/^\Q$ip\E$/,@exempt)) {  $userloadrow
                 $omitextra = 1;  $versionrow
             }       </table>
         }      </div>
         unless ($omitextra) {      <div style="float: right;">
             my $confname = $defdom.'-domainconfig';      $domainlogo
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {      </div>
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));      <br style="clear:both;" />
                 unless ($extra eq '-1') {   </div>
                     $js .= "\n".$extra."\n";  
                 }  <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(); }
   // ]]>
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,  </script>
        { 'redirect'       => [$expire,'/adm/roles'],   $helpdeskscript
  'add_entries' => \%add_entries,  
  'only_body'   => 1,}));  ENDDOCUMENT
       my %endargs = ( 'noredirectlink' => 1, );
 # ----------------------------------------------------------------------- Texts      $r->print(&Apache::loncommon::end_page(\%endargs));
       return OK;
     my %lt=&Apache::lonlocal::texthash(  }
           'un'       => 'Username',  
           'pw'       => 'Password',  sub check_loginvia {
           'dom'      => 'Domain',      my ($domain,$lonhost) = @_;
           'perc'     => 'percent',      if ($domain eq '' || $lonhost eq '') {
           'load'     => 'Server Load',          return;
           'userload' => 'User Load',      }
           'catalog'  => 'Course/Community Catalog',      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
           'log'      => 'Log in',      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
           'help'     => 'Log-in Help',      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
           'serv'     => 'Server',      my $output;
           'servadm'  => 'Server Administration',      if ($loginvia ne '') {
           'helpdesk' => 'Contact Helpdesk',          my $noredirect;
           'forgotpw' => 'Forgot password?',          my $ip = $ENV{'REMOTE_ADDR'};
           'newuser'  => 'New User?',          if ($ip eq '127.0.0.1') {
           'change'   => 'Change?',              $noredirect = 1;
        );          } else {
 # -------------------------------------------------- Change password field name              if ($loginvia_exempt ne '') {
                   my @exempt = split(',',$loginvia_exempt);
     my $forgotpw = &forgotpwdisplay(%lt);                  if (grep(/^\Q$ip\E$/,@exempt)) {
     $forgotpw .= '<br />' if $forgotpw;                      $noredirect = 1;
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);                  }
     if ($loginhelp) {              }
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';          }
     }          unless ($noredirect) {
               my ($newhost,$path);
 # ---------------------------------------------------- Serve out DES JavaScript              if ($loginvia =~ /:/) {
     {                  ($newhost,$path) = split(':',$loginvia);
     my $jsh=Apache::File->new($include."/londes.js");              } else {
     $r->print(<$jsh>);                  $newhost = $loginvia;
     }              }
 # ---------------------------------------------------------- Serve rest of page              if ($newhost ne $lonhost) {
                   if (&Apache::lonnet::hostname($newhost) ne '') {
     $r->print(                      $output = &redirect_page($newhost,$path);
     '<div class="LC_Box"'                  }
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'              }
 );          }
       }
     $r->print(<<ENDSERVERFORM);      return $output;
 <form name="server" action="/adm/authenticate" method="post" target="_top">  }
    <input type="hidden" name="logtoken" value="$logtoken" />  
    <input type="hidden" name="serverid" value="$lonhost" />  sub redirect_page {
    <input type="hidden" name="uname" value="" />      my ($desthost,$path) = @_;
    <input type="hidden" name="upass0" value="" />      my $protocol = $Apache::lonnet::protocol{$desthost};
    <input type="hidden" name="udom" value="" />      $protocol = 'http' if ($protocol ne 'https');
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />      unless ($path =~ m{^/}) {
    <input type="hidden" name="localres" value="$env{'form.localres'}" />          $path = '/'.$path;
   </form>      }
 ENDSERVERFORM      my $url = $protocol.'://'.&Apache::lonnet::hostname($desthost).$path;
     my $coursecatalog;      if ($env{'form.firsturl'} ne '') {
     if (($showcoursecat eq '') || ($showcoursecat)) {          $url .='?firsturl='.$env{'form.firsturl'};
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';      }
     }      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
     my $newuserlink;                                                      {'redirect' => [0,$url],});
     if ($shownewuserlink) {      my $end_page   = &Apache::loncommon::end_page();
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';      return $start_page.$end_page;
     }  }
     my $logintitle =  
         '<h2 class="LC_hcell"'  sub contactdisplay {
        .' style="background:'.$loginbox_header_bgcol.';'      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
        .' color:'.$loginbox_header_textcol.'">'          $possdoms) = @_;
        .$lt{'log'}      my $contactblock;
        .'</h2>';      my $origmail;
       if (ref($possdoms) eq 'ARRAY') {
     my $noscript_warning='<noscript><span class="LC_warning"><b>'          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                         .'</b></span></noscript>';          }
     my $helpdeskscript;      }
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,      my $requestmail =
                                        $authdomain,\$helpdeskscript,          &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                        $showhelpdesk,\@possdoms);                                                   $authdomain,$origmail);
       unless ($showhelpdesk eq '0') {
     my $mobileargs;          if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
     if ($clientmobile) {              $showhelpdesk = 1;
         $mobileargs = 'autocapitalize="off" autocorrect="off"';           } else {
     }              $showhelpdesk = 0;
     my $loginform=(<<LFORM);          }
 <form name="client" action="" onsubmit="return(send())" id="lclogin">      }
   <input type="hidden" name="lextkey" value="$lextkey" />      if ($servadm && $showadminmail) {
   <input type="hidden" name="uextkey" value="$uextkey" />          $contactblock .= $$lt{'servadm'}.':<br />'.
   <b><label for="uname">$lt{'un'}</label>:</b><br />                           '<tt>'.$servadm.'</tt><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 />      if ($showhelpdesk) {
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />          $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
   <b><label for="udom">$lt{'dom'}</label>:</b><br />          my $thisurl = &escape('/adm/login');
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />          $$helpdeskscript = <<"ENDSCRIPT";
   <input type="submit" value="$lt{'log'}" />  <script type="text/javascript">
 </form>  // <![CDATA[
 LFORM  function helpdesk() {
       var possdom = document.client.udom.value;
     if ($showbanner) {      var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);      if (codedom == '') {
         if ($alttext eq '') {          codedom = "$authdomain";
             $alttext = 'The Learning Online Network with CAPA';      }
         }      var querystr = "origurl=$thisurl&codedom="+codedom;
         $r->print(<<HEADER);      document.location.href = "/adm/helpdesk?"+querystr;
 <!-- The LON-CAPA Header -->      return;
 <div style="background:$pgbg;margin:0;width:100%;">  }
   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />  // ]]>
 </div>  </script>
 HEADER  ENDSCRIPT
     }      }
       return $contactblock;
     my $stdauthformstyle = 'inline-block';  }
     my $ssoauthstyle = 'none';  
     my $logintype;  sub forgotpwdisplay {
     $r->print('<div style="float:left;margin-top:0;">');      my (%lt) = @_;
     if ($saml_landing) {      my $prompt_for_resetpw = 1;
         $ssoauthstyle = 'inline-block';      if ($prompt_for_resetpw) {
         $stdauthformstyle = 'none';          return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
         $logintype = $samlssotext;      }
         my $ssologin = '/adm/sso';      return;
         if ($samlssourl  ne '') {  }
             $ssologin = $samlssourl;  
         }  sub coursecatalog_link {
         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {      my ($linkname) = @_;
             my $querystring;      return <<"END";
             if ($env{'form.firsturl'} ne '') {        <a href="/adm/coursecatalog">$linkname</a>
                 $querystring = 'origurl=';  END
                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {  }
                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});  
                 } else {  sub newuser_link {
                     $querystring .= &uri_escape($env{'form.firsturl'});      my ($linkname) = @_;
                 }      return '<a href="/adm/createaccount">'.$linkname.'</a>';
                 $querystring = &HTML::Entities::encode($querystring,"'");  }
             }  
             if ($querystring ne '') {  1;
                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;  __END__
             }  
         } elsif ($logtoken ne '') {  
             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;  
         }  
         my $ssohref;  
         if ($samlssoimg ne '') {  
             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'">'.  
                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';  
         } else {  
             $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';  
         }  
         if (($env{'form.saml'} eq 'no') ||  
             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {  
             $ssoauthstyle = 'none';  
             $stdauthformstyle = 'inline-block';  
             $logintype = $samlnonsso;  
         }  
         $r->print(<<ENDSAML);  
 <p>  
 Log-in type:  
 <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />  
 <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>  
 </p>  
 <div style="display:$ssoauthstyle" id="LC_SSO_login">  
 <div class="LC_Box" style="padding-top: 10px;">  
 $ssohref  
 $noscript_warning  
 </div>  
 <div class="LC_Box" style="padding-top: 10px;">  
 $loginhelp  
 $contactblock  
 $coursecatalog  
 </div>  
 </div>  
 ENDSAML  
     }  
   
     $r->print(<<ENDLOGIN);  
 <div style="display:$stdauthformstyle;" id="LC_standard_login">  
 <div class="LC_Box" style="background:$loginbox_bg;">  
   $logintitle  
   $loginform  
   $noscript_warning  
 </div>  
     
 <div class="LC_Box" style="padding-top: 10px;">  
   $loginhelp  
   $forgotpw  
   $contactblock  
   $newuserlink  
   $coursecatalog  
 </div>  
 </div>  
   
 ENDLOGIN  
     $r->print('</div><div>'."\n");  
     if ($showmainlogo) {  
         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);  
         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");  
     }  
 $r->print(<<ENDTOP);  
 $announcements  
 </div>  
 <hr style="clear:both;" />  
 ENDTOP  
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$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) = @_;  
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {  
         return;  
     }  
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);  
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};  
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};  
     my $output;  
     if ($loginvia ne '') {  
         my $noredirect;  
         my $ip = &Apache::lonnet::get_requestor_ip();  
         if ($ip eq '127.0.0.1') {  
             $noredirect = 1;  
         } else {  
             if ($loginvia_exempt ne '') {  
                 my @exempt = split(',',$loginvia_exempt);  
                 if (grep(/^\Q$ip\E$/,@exempt)) {  
                     $noredirect = 1;  
                 }  
             }  
         }  
         unless ($noredirect) {  
             my ($newhost,$path);  
             if ($loginvia =~ /:/) {  
                 ($newhost,$path) = split(':',$loginvia);  
             } else {  
                 $newhost = $loginvia;  
             }  
             if ($newhost ne $lonhost) {  
                 if (&Apache::lonnet::hostname($newhost) ne '') {  
                     if ($balcookie) {  
                         my ($balancer,$cookie) = split(/:/,$balcookie);  
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {  
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);  
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {  
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {  
                                     while (my $filename=readdir($dh)) {  
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {  
                                             my $handle = $1;  
                                             my %hash =  
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,  
                                                                                      ['request.balancercookie',  
                                                                                       'user.linkedenv']);  
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {  
                                                 if (unlink("$lonidsdir/$filename")) {  
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&  
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&  
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {  
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");  
                                                     }  
                                                 }  
                                             }  
                                             last;  
                                         }  
                                     }  
                                     closedir($dh);  
                                 }  
                             }  
                         }  
                     }  
                     $output = &redirect_page($newhost,$path);  
                 }  
             }  
         }  
     }  
     return $output;  
 }  
   
 sub redirect_page {  
     my ($desthost,$path) = @_;  
     my $hostname = &Apache::lonnet::hostname($desthost);  
     my $protocol = $Apache::lonnet::protocol{$desthost};  
     $protocol = 'http' if ($protocol ne 'https');  
     unless ($path =~ m{^/}) {  
         $path = '/'.$path;  
     }  
     my $url = $protocol.'://'.$hostname.$path;  
     if ($env{'form.firsturl'} ne '') {  
         my $querystring;  
         if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {  
             $querystring = &uri_escape_utf8($env{'form.firsturl'});  
         } else {  
             $querystring = &uri_escape($env{'form.firsturl'});  
         }  
         $querystring = &HTML::Entities::encode($querystring,"'");  
         $url .='?firsturl='.$querystring;  
     }  
     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>';  
 }  
   
 sub decode_token {  
     my ($info) = @_;  
     my ($firsturl,@rest)=split(/\&/,$info);  
     my %form;  
     if ($firsturl ne '') {  
         $form{'firsturl'} = &unescape($firsturl);  
     }  
     foreach my $item (@rest) {  
         my ($key,$value) = split(/=/,$item);  
         $form{$key} = &unescape($value);  
     }  
     return %form;  
 }  
   
 1;  
 __END__  

Removed from v.1.158.2.15  
changed lines
  Added in v.1.160


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