Diff for /loncom/auth/lonlogin.pm between versions 1.152 and 1.195

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


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