Diff for /loncom/auth/lonlogin.pm between versions 1.158 and 1.185

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

Removed from v.1.158  
changed lines
  Added in v.1.185


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