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

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


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