Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.4 and 1.183

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


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