Diff for /loncom/auth/lonlogin.pm between versions 1.159 and 1.193

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

Removed from v.1.159  
changed lines
  Added in v.1.193


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