Diff for /loncom/auth/lonlogin.pm between versions 1.157 and 1.186

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

Removed from v.1.157  
changed lines
  Added in v.1.186


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