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

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


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