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

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

Removed from v.1.154  
changed lines
  Added in v.1.192


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