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

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


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