Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.6 and 1.176

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


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