Diff for /loncom/auth/lonlogin.pm between versions 1.154 and 1.188

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


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