Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.5 and 1.188

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


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