Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13 and 1.161

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


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