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

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


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