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

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

Removed from v.1.158.2.6  
changed lines
  Added in v.1.188


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