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

version 1.158.2.13.2.2, 2022/01/16 23:31:27 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);          }
     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'}) {  
                     $tokenextras .= '&linkprot='.&escape($info{'linkprot'});  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
                     $tokentype = 'link';  #    we are in serious trouble
                     last;  
                 }      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
             } else {          if ($logtoken eq 'no_such_host') {
                 $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
                 if (($name eq 'linkkey') || ($name eq 'linkprot')) {          }
                     $tokentype = 'link';          my $spares='';
                 }          my (@sparehosts,%spareservers);
             }          my $sparesref = &Apache::lonnet::this_host_spares($defdom);
         }          if (ref($sparesref) eq 'HASH') {
     }              foreach my $key (keys(%{$sparesref})) {
     if ($tokentype) {                  if (ref($sparesref->{$key}) eq 'ARRAY') {
         $tokenextras .= ":$tokentype";                      my @sorted = sort { &Apache::lonnet::hostname($a) cmp
     }                                          &Apache::lonnet::hostname($b);
     my $logtoken=Apache::lonnet::reply(                                        } @{$sparesref->{$key}};
        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,                      if (@sorted) {
        $lonhost);                          if ($key eq 'primary') {
                               unshift(@sparehosts,@sorted);
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname                          } elsif ($key eq 'default') {
 #    we are in serious trouble                              push(@sparehosts,@sorted);
                           }
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {                      }
         if ($logtoken eq 'no_such_host') {                  }
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');              }
         }          }
         if ($env{'form.ltoken'}) {          foreach my $hostid (@sparehosts) {
             &Apache::lonnet::tmpdel($env{'form.ltoken'});              next if ($hostid eq $lonhost);
             delete($env{'form.ltoken'});      my $hostname = &Apache::lonnet::hostname($hostid);
         }      next if (($hostname eq '') || ($spareservers{$hostname}));
         my $spares='';              $spareservers{$hostname} = 1;
         my (@sparehosts,%spareservers);              my $protocol = $Apache::lonnet::protocol{$hostid};
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);              $protocol = 'http' if ($protocol ne 'https');
         if (ref($sparesref) eq 'HASH') {              $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
             foreach my $key (keys(%{$sparesref})) {                  $hostname.
                 if (ref($sparesref->{$key}) eq 'ARRAY') {                  '/adm/login?domain='.$authdomain.'">'.
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp                  $hostname.'</a>'.
                                         &Apache::lonnet::hostname($b);                  ' '.&mt('(preferred)').'</span>'.$/;
                                       } @{$sparesref->{$key}};          }
                     if (@sorted) {          if ($spares) {
                         if ($key eq 'primary') {              $spares.= '<br />';
                             unshift(@sparehosts,@sorted);          }
                         } elsif ($key eq 'default') {          my %all_hostnames = &Apache::lonnet::all_hostnames();
                             push(@sparehosts,@sorted);          foreach my $hostid (sort
                         }      {
                     }   &Apache::lonnet::hostname($a) cmp
                 }      &Apache::lonnet::hostname($b);
             }      }
         }      keys(%all_hostnames)) {
         foreach my $hostid (@sparehosts) {              next if ($hostid eq $lonhost);
             next if ($hostid eq $lonhost);              my $hostname = &Apache::lonnet::hostname($hostid);
     my $hostname = &Apache::lonnet::hostname($hostid);              next if (($hostname eq '') || ($spareservers{$hostname}));
     next if (($hostname eq '') || ($spareservers{$hostname}));              $spareservers{$hostname} = 1;
             $spareservers{$hostname} = 1;              my $protocol = $Apache::lonnet::protocol{$hostid};
             my $protocol = $Apache::lonnet::protocol{$hostid};              $protocol = 'http' if ($protocol ne 'https');
             $protocol = 'http' if ($protocol ne 'https');              $spares.='<br /><a href="'.$protocol.'://'.
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.               $hostname.
                 $hostname.               '/adm/login?domain='.$authdomain.'">'.
                 '/adm/login?domain='.$authdomain.'">'.               $hostname.'</a>';
                 $hostname.'</a>'.           }
                 ' '.&mt('(preferred)').'</span>'.$/;           $r->print(
         }     '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
         if ($spares) {    .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
             $spares.= '<br />';    .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
         }    .&mt('The LearningOnline Network with CAPA')
         my %all_hostnames = &Apache::lonnet::all_hostnames();    .'</title></head>'
         foreach my $hostid (sort    .'<body bgcolor="#FFFFFF">'
     {    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
  &Apache::lonnet::hostname($a) cmp    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
     &Apache::lonnet::hostname($b);    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
     }          if ($spares) {
     keys(%all_hostnames)) {              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
             next if ($hostid eq $lonhost);                       .'</p>'
             my $hostname = &Apache::lonnet::hostname($hostid);                       .$spares);
             next if (($hostname eq '') || ($spareservers{$hostname}));          }
             $spareservers{$hostname} = 1;          $r->print('</body>'
             my $protocol = $Apache::lonnet::protocol{$hostid};                   .'</html>'
             $protocol = 'http' if ($protocol ne 'https');          );
             $spares.='<br /><a href="'.$protocol.'://'.          return OK;
              $hostname.      }
              '/adm/login?domain='.$authdomain.'">'.  
              $hostname.'</a>';  # ----------------------------------------------- Apparently we are in business
          }      $servadm=~s/\,/\<br \/\>/g;
          $r->print(  
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'  # ----------------------------------------------------------- Front page design
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'      my $font=&Apache::loncommon::designparm('login.font',$domain);
   .&mt('The LearningOnline Network with CAPA')      my $link=&Apache::loncommon::designparm('login.link',$domain);
   .'</title></head>'      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
   .'<body bgcolor="#FFFFFF">'      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
         if ($spares) {      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
                      .'</p>'      my $img=&Apache::loncommon::designparm('login.img',$domain);
                      .$spares);      my $domainlogo=&Apache::loncommon::domainlogo($domain);
         }      my $showbanner = 1;
         $r->print('</body>'      my $showmainlogo = 1;
                  .'</html>'      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
         );          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
         return OK;      }
     }      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
           $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
 # ----------------------------------------------- Apparently we are in business      }
     $servadm=~s/\,/\<br \/\>/g;      my $showadminmail;
       my @possdoms = &Apache::lonnet::current_machine_domains();
 # ----------------------------------------------------------- Front page design      if (grep(/^\Q$domain\E$/,@possdoms)) {
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
     my $font=&Apache::loncommon::designparm('login.font',$domain);      }
     my $link=&Apache::loncommon::designparm('login.link',$domain);      my $showcoursecat =
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);          &Apache::loncommon::designparm('login.coursecatalog',$domain);
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);      my $shownewuserlink =
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);          &Apache::loncommon::designparm('login.newuser',$domain);
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);      my $showhelpdesk =
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);          &Apache::loncommon::designparm('login.helpdesk',$domain);
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);      my $now=time;
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);      my $js = (<<ENDSCRIPT);
     my $img=&Apache::loncommon::designparm('login.img',$domain);  
     my $domainlogo=&Apache::loncommon::domainlogo($domain);  <script type="text/javascript" language="JavaScript">
     my $showbanner = 1;  // <![CDATA[
     my $showmainlogo = 1;  function send()
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {  {
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);  this.document.server.elements.uname.value
     }  =this.document.client.elements.uname.value;
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {  
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);  this.document.server.elements.udom.value
     }  =this.document.client.elements.udom.value;
     my $showadminmail;  
     my @possdoms = &Apache::lonnet::current_machine_domains();  uextkey=this.document.client.elements.uextkey.value;
     if (grep(/^\Q$domain\E$/,@possdoms)) {  lextkey=this.document.client.elements.lextkey.value;
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);  initkeys();
     }  
     my $showcoursecat =  if(this.document.server.action.substr(0,5) === 'http:'){
         &Apache::loncommon::designparm('login.coursecatalog',$domain);      this.document.server.elements.upass0.value
     my $shownewuserlink =           =getCrypted(this.document.client.elements.upass$now.value);
         &Apache::loncommon::designparm('login.newuser',$domain);  } else {
     my $showhelpdesk =      this.document.server.elements.upass0.value
         &Apache::loncommon::designparm('login.helpdesk',$domain);          =this.document.client.elements.upass$now.value;
     my $now=time;  }
     my $js = (<<ENDSCRIPT);  
   this.document.client.elements.uname.value='';
 <script type="text/javascript" language="JavaScript">  this.document.client.elements.upass$now.value='';
 // <![CDATA[  
 function send()  this.document.server.submit();
 {  return false;
 this.document.server.elements.uname.value  }
 =this.document.client.elements.uname.value;  
   function enableInput() {
 this.document.server.elements.udom.value      this.document.client.elements.upass$now.removeAttribute("readOnly");
 =this.document.client.elements.udom.value;      this.document.client.elements.uname.removeAttribute("readOnly");
       this.document.client.elements.udom.removeAttribute("readOnly");
 uextkey=this.document.client.elements.uextkey.value;      return;
 lextkey=this.document.client.elements.lextkey.value;  }
 initkeys();  
   // ]]>
 this.document.server.elements.upass0.value  </script>
     =getCrypted(this.document.client.elements.upass$now.value);  
   ENDSCRIPT
 this.document.client.elements.uname.value='';  
 this.document.client.elements.upass$now.value='';      my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,
           $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);
 this.document.server.submit();      %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
 return false;      @hosts = &Apache::lonnet::current_machine_ids();
 }      $lonhost_in_use = $lonhost;
       if (@hosts > 1) {
 function enableInput() {          foreach my $hostid (@hosts) {
     this.document.client.elements.upass$now.removeAttribute("readOnly");              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
     this.document.client.elements.uname.removeAttribute("readOnly");                  $lonhost_in_use = $hostid;
     this.document.client.elements.udom.removeAttribute("readOnly");                  last;
     return;              }
 }          }
       }
 // ]]>      $saml_prefix = $defdom.'.login.saml_';
 </script>      if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {
           $saml_landing = 1;
 ENDSCRIPT          $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};
           $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,          $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);          $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);          $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};
     @hosts = &Apache::lonnet::current_machine_ids();          $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};
     $lonhost_in_use = $lonhost;      }
     if (@hosts > 1) {      if ($saml_landing) {
         foreach my $hostid (@hosts) {         if ($samlssotext eq '') {
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {             $samlssotext = 'SSO Login';
                 $lonhost_in_use = $hostid;         }
                 last;         if ($samlnonsso eq '') {
             }             $samlnonsso = 'Non-SSO Login';
         }         }
     }         $js .= <<"ENDSAMLJS";
     $saml_prefix = $defdom.'.login.saml_';  
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {  <script type="text/javascript">
         $saml_landing = 1;  // <![CDATA[
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};  function toggleLClogin() {
         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};      if (document.getElementById('LC_standard_login')) {
         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};          if (document.getElementById('LC_standard_login').style.display == 'none') {
         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};              document.getElementById('LC_standard_login').style.display = 'inline-block';
         $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 = '$samlnonsso';
     }              }
     if ($saml_landing) {              if (document.getElementById('LC_SSO_login')) {
        if ($samlssotext eq '') {                  document.getElementById('LC_SSO_login').style.display = 'none';
            $samlssotext = 'SSO Login';              }
        }          } else {
        if ($samlnonsso eq '') {              document.getElementById('LC_standard_login').style.display = 'none';
            $samlnonsso = 'Non-SSO Login';              if (document.getElementById('LC_login_text')) {
        }                  document.getElementById('LC_login_text').innerHTML = '$samlssotext';
        $js .= <<"ENDSAMLJS";              }
               if (document.getElementById('LC_SSO_login')) {
 <script type="text/javascript">                  document.getElementById('LC_SSO_login').style.display = 'inline-block';
 // <![CDATA[              }
 function toggleLClogin() {          }
     if (document.getElementById('LC_standard_login')) {      }
         if (document.getElementById('LC_standard_login').style.display == 'none') {      return;
             document.getElementById('LC_standard_login').style.display = 'inline-block';  }
             if (document.getElementById('LC_login_text')) {  
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';  // ]]>
             }  </script>
             if (document.getElementById('LC_SSO_login')) {  
                 document.getElementById('LC_SSO_login').style.display = 'none';  ENDSAMLJS
             }      }
         } else {  
             document.getElementById('LC_standard_login').style.display = 'none';  # --------------------------------------------------- Print login screen header
             if (document.getElementById('LC_login_text')) {  
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';      my %add_entries = (
             }         bgcolor      => "$mainbg",
             if (document.getElementById('LC_SSO_login')) {         text         => "$font",
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';         link         => "$link",
             }         vlink        => "$vlink",
         }         alink        => "$alink",
     }                 onload       => 'javascript:enableInput();',);
     return;  
 }      my ($headextra,$headextra_exempt);
       $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
 // ]]>      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
 </script>      if ($headextra) {
           my $omitextra;
 ENDSAMLJS          if ($headextra_exempt ne '') {
     }              my @exempt = split(',',$headextra_exempt);
               my $ip = &Apache::lonnet::get_requestor_ip();
 # --------------------------------------------------- Print login screen header              if (grep(/^\Q$ip\E$/,@exempt)) {
                   $omitextra = 1;
     my %add_entries = (              }
        bgcolor      => "$mainbg",          }
        text         => "$font",          unless ($omitextra) {
        link         => "$link",              my $confname = $defdom.'-domainconfig';
        vlink        => "$vlink",              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
        alink        => "$alink",                  my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
                onload       => 'javascript:enableInput();',);                  unless ($extra eq '-1') {
                       $js .= "\n".$extra."\n";
     my ($headextra,$headextra_exempt);                  }
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};              }
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};          }
     if ($headextra) {      }
         my $omitextra;  
         if ($headextra_exempt ne '') {      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
             my @exempt = split(',',$headextra_exempt);         { 'redirect'       => [$expire,'/adm/roles'],
             my $ip = &Apache::lonnet::get_requestor_ip();   'add_entries' => \%add_entries,
             if (grep(/^\Q$ip\E$/,@exempt)) {   'only_body'   => 1,}));
                 $omitextra = 1;  
             }  # ----------------------------------------------------------------------- Texts
         }  
         unless ($omitextra) {      my %lt=&Apache::lonlocal::texthash(
             my $confname = $defdom.'-domainconfig';            'un'       => 'Username',
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {            'pw'       => 'Password',
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));            'dom'      => 'Domain',
                 unless ($extra eq '-1') {            'perc'     => 'percent',
                     $js .= "\n".$extra."\n";            'load'     => 'Server Load',
                 }            'userload' => 'User Load',
             }            'catalog'  => 'Course/Community Catalog',
         }            'log'      => 'Log in',
     }            'help'     => 'Log-in Help',
             'serv'     => 'Server',
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,            'servadm'  => 'Server Administration',
        { 'redirect'       => [$expire,'/adm/roles'],             'helpdesk' => 'Contact Helpdesk',
  'add_entries' => \%add_entries,            'forgotpw' => 'Forgot password?',
  'only_body'   => 1,}));            'newuser'  => 'New User?',
             'change'   => 'Change?',
 # ----------------------------------------------------------------------- Texts         );
   # -------------------------------------------------- Change password field name
     my %lt=&Apache::lonlocal::texthash(  
           'un'       => 'Username',      my $forgotpw = &forgotpwdisplay(%lt);
           'pw'       => 'Password',      $forgotpw .= '<br />' if $forgotpw;
           'dom'      => 'Domain',      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
           'perc'     => 'percent',      if ($loginhelp) {
           'load'     => 'Server Load',          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
           'userload' => 'User Load',      }
           'catalog'  => 'Course/Community Catalog',  
           'log'      => 'Log in',  # ---------------------------------------------------- Serve out DES JavaScript
           'help'     => 'Log-in Help',      {
           'serv'     => 'Server',      my $jsh=Apache::File->new($include."/londes.js");
           'servadm'  => 'Server Administration',      $r->print(<$jsh>);
           'helpdesk' => 'Contact Helpdesk',      }
           'forgotpw' => 'Forgot password?',  # ---------------------------------------------------------- Serve rest of page
           'newuser'  => 'New User?',  
           'change'   => 'Change?',      $r->print(
        );      '<div class="LC_Box"'
 # -------------------------------------------------- Change password field name     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
   );
     my $forgotpw = &forgotpwdisplay(%lt);  
     $forgotpw .= '<br />' if $forgotpw;      $r->print(<<ENDSERVERFORM);
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);  <form name="server" action="/adm/authenticate" method="post" target="_top">
     if ($loginhelp) {     <input type="hidden" name="logtoken" value="$logtoken" />
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';     <input type="hidden" name="serverid" value="$lonhost" />
     }     <input type="hidden" name="uname" value="" />
      <input type="hidden" name="upass0" value="" />
 # ---------------------------------------------------- Serve out DES JavaScript     <input type="hidden" name="udom" value="" />
     {     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
     my $jsh=Apache::File->new($include."/londes.js");     <input type="hidden" name="localres" value="$env{'form.localres'}" />
     $r->print(<$jsh>);    </form>
     }  ENDSERVERFORM
 # ---------------------------------------------------------- Serve rest of page      my $coursecatalog;
       if (($showcoursecat eq '') || ($showcoursecat)) {
     $r->print(          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
     '<div class="LC_Box"'      }
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'      my $newuserlink;
 );      if ($shownewuserlink) {
           $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
     $r->print(<<ENDSERVERFORM);      }
 <form name="server" action="/adm/authenticate" method="post" target="_top">      my $logintitle =
    <input type="hidden" name="logtoken" value="$logtoken" />          '<h2 class="LC_hcell"'
    <input type="hidden" name="serverid" value="$lonhost" />         .' style="background:'.$loginbox_header_bgcol.';'
    <input type="hidden" name="uname" value="" />         .' color:'.$loginbox_header_textcol.'">'
    <input type="hidden" name="upass0" value="" />         .$lt{'log'}
    <input type="hidden" name="udom" value="" />         .'</h2>';
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />  
    <input type="hidden" name="localres" value="$env{'form.localres'}" />      my $noscript_warning='<noscript><span class="LC_warning"><b>'
   </form>                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
 ENDSERVERFORM                          .'</b></span></noscript>';
     my $coursecatalog;      my $helpdeskscript;
     if (($showcoursecat eq '') || ($showcoursecat)) {      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';                                         $authdomain,\$helpdeskscript,
     }                                         $showhelpdesk,\@possdoms);
     my $newuserlink;  
     if ($shownewuserlink) {      my $mobileargs;
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';      if ($clientmobile) {
     }          $mobileargs = 'autocapitalize="off" autocorrect="off"';
     my $logintitle =      }
         '<h2 class="LC_hcell"'      my $loginform=(<<LFORM);
        .' style="background:'.$loginbox_header_bgcol.';'  <form name="client" action="" onsubmit="return(send())" id="lclogin">
        .' color:'.$loginbox_header_textcol.'">'    <input type="hidden" name="lextkey" value="$lextkey" />
        .$lt{'log'}    <input type="hidden" name="uextkey" value="$uextkey" />
        .'</h2>';    <b><label for="uname">$lt{'un'}</label>:</b><br />
     <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
     my $noscript_warning='<noscript><span class="LC_warning"><b>'    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
                         .'</b></span></noscript>';    <b><label for="udom">$lt{'dom'}</label>:</b><br />
     my $helpdeskscript;    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,    <input type="submit" value="$lt{'log'}" />
                                        $authdomain,\$helpdeskscript,  </form>
                                        $showhelpdesk,\@possdoms);  LFORM
   
     my $mobileargs;      if ($showbanner) {
     if ($clientmobile) {          $r->print(<<HEADER);
         $mobileargs = 'autocapitalize="off" autocorrect="off"';   <!-- The LON-CAPA Header -->
     }  <div style="background:$pgbg;margin:0;width:100%;">
     my $loginform=(<<LFORM);    <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />
 <form name="client" action="" onsubmit="return(send())" id="lclogin">  </div>
   <input type="hidden" name="lextkey" value="$lextkey" />  HEADER
   <input type="hidden" name="uextkey" value="$uextkey" />      }
   <b><label for="uname">$lt{'un'}</label>:</b><br />  
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />      my $stdauthformstyle = 'inline-block';
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />      my $ssoauthstyle = 'none';
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />      my $logintype;
   <b><label for="udom">$lt{'dom'}</label>:</b><br />      $r->print('<div style="float:left;margin-top:0;">');
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />      if ($saml_landing) {
   <input type="submit" value="$lt{'log'}" />          $ssoauthstyle = 'inline-block';
 </form>          $stdauthformstyle = 'none';
 LFORM          $logintype = $samlssotext;
           my $ssologin = '/adm/sso';
     if ($showbanner) {          if ($samlssourl  ne '') {
         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);              $ssologin = $samlssourl;
         if ($alttext eq '') {          }
             $alttext = 'The Learning Online Network with CAPA';          if ($env{'form.firsturl'} ne '') {
         }              my $querystring;
         $r->print(<<HEADER);              if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
 <!-- The LON-CAPA Header -->                  $querystring = &uri_escape_utf8($env{'form.firsturl'});
 <div style="background:$pgbg;margin:0;width:100%;">              } else {
   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />                  $querystring = &uri_escape($env{'form.firsturl'});
 </div>              }
 HEADER              $querystring = &HTML::Entities::encode($querystring,"'");
     }              $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;
           }
     my $stdauthformstyle = 'inline-block';          my $ssohref;
     my $ssoauthstyle = 'none';          if ($samlssoimg ne '') {
     my $logintype;              $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'"><img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" /></a>';
     $r->print('<div style="float:left;margin-top:0;">');          } else {
     if ($saml_landing) {              $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';
         $ssoauthstyle = 'inline-block';          }
         $stdauthformstyle = 'none';          if (($env{'form.saml'} eq 'no') ||
         $logintype = $samlssotext;              (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {
         my $ssologin = '/adm/sso';              $ssoauthstyle = 'none';
         if ($samlssourl  ne '') {              $stdauthformstyle = 'inline-block';
             $ssologin = $samlssourl;              $logintype = $samlnonsso;
         }          }
         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {          $r->print(<<ENDSAML);
             my $querystring;  <p>
             if ($env{'form.firsturl'} ne '') {  Log-in type:
                 $querystring = 'origurl=';  <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />
                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {  <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>
                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});  </p>
                 } else {  <div style="display:$ssoauthstyle" id="LC_SSO_login">
                     $querystring .= &uri_escape($env{'form.firsturl'});  <div class="LC_Box" style="padding-top: 10px;">
                 }  $ssohref
                 $querystring = &HTML::Entities::encode($querystring,"'");  $noscript_warning
             }  </div>
             if ($env{'form.ltoken'} ne '') {  <div class="LC_Box" style="padding-top: 10px;">
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.  $loginhelp
                                   &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));  $contactblock
             } elsif ($env{'form.linkkey'}) {  $coursecatalog
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.  </div>
                                   &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));  </div>
             }  ENDSAML
             if ($querystring ne '') {      }
                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;  
             }      $r->print(<<ENDLOGIN);
         } elsif ($logtoken ne '') {  <div style="display:$stdauthformstyle;" id="LC_standard_login">
             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;  <div class="LC_Box" style="background:$loginbox_bg;">
         }    $logintitle
         my $ssohref;    $loginform
         if ($samlssoimg ne '') {    $noscript_warning
             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'">'.  </div>
                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';   
         } else {  <div class="LC_Box" style="padding-top: 10px;">
             $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';    $loginhelp
         }    $forgotpw
         if (($env{'form.saml'} eq 'no') ||    $contactblock
             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {    $newuserlink
             $ssoauthstyle = 'none';    $coursecatalog
             $stdauthformstyle = 'inline-block';  </div>
             $logintype = $samlnonsso;  </div>
         }  
         $r->print(<<ENDSAML);  ENDLOGIN
 <p>      $r->print('</div><div>'."\n");
 Log-in type:      if ($showmainlogo) {
 <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />          $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");
 <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>      }
 </p>  $r->print(<<ENDTOP);
 <div style="display:$ssoauthstyle" id="LC_SSO_login">  $announcements
 <div class="LC_Box" style="padding-top: 10px;">  </div>
 $ssohref  <hr style="clear:both;" />
 $noscript_warning  ENDTOP
 </div>      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
 <div class="LC_Box" style="padding-top: 10px;">      $domainrow = <<"END";
 $loginhelp        <tr>
 $contactblock         <td  align="left" valign="top">
 $coursecatalog          <small><b>$lt{'dom'}:&nbsp;</b></small>
 </div>         </td>
 </div>         <td  align="left" valign="top">
 ENDSAML          <small><tt>&nbsp;$domain</tt></small>
     } else {         </td>
         if ($env{'form.ltoken'}) {        </tr>
             &Apache::lonnet::tmpdel($env{'form.ltoken'});  END
             delete($env{'form.ltoken'});      $serverrow = <<"END";
         }        <tr>
     }         <td  align="left" valign="top">
           <small><b>$lt{'serv'}:&nbsp;</b></small>
     $r->print(<<ENDLOGIN);         </td>
 <div style="display:$stdauthformstyle;" id="LC_standard_login">         <td align="left" valign="top">
 <div class="LC_Box" style="background:$loginbox_bg;">          <small><tt>&nbsp;$lonhost ($role)</tt></small>
   $logintitle         </td>
   $loginform        </tr>
   $noscript_warning  END
 </div>      if ($loadlim) {
             $loadrow = <<"END";
 <div class="LC_Box" style="padding-top: 10px;">        <tr>
   $loginhelp         <td align="left" valign="top">
   $forgotpw          <small><b>$lt{'load'}:&nbsp;</b></small>
   $contactblock         </td>
   $newuserlink         <td align="left" valign="top">
   $coursecatalog          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
 </div>         </td>
 </div>        </tr>
   END
 ENDLOGIN      }
     $r->print('</div><div>'."\n");      if ($uloadlim) {
     if ($showmainlogo) {          $userloadrow = <<"END";
         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);        <tr>
         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");         <td align="left" valign="top">
     }          <small><b>$lt{'userload'}:&nbsp;</b></small>
 $r->print(<<ENDTOP);         </td>
 $announcements         <td align="left" valign="top">
 </div>          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
 <hr style="clear:both;" />         </td>
 ENDTOP        </tr>
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);  END
     $domainrow = <<"END";      }
       <tr>      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
        <td  align="left" valign="top">          $versionrow = <<"END";
         <small><b>$lt{'dom'}:&nbsp;</b></small>        <tr>
        </td>         <td colspan="2" align="left">
        <td  align="left" valign="top">          <small>$version</small>
         <small><tt>&nbsp;$domain</tt></small>         </td>
        </td>        </tr>
       </tr>  END
 END      }
     $serverrow = <<"END";  
       <tr>      $r->print(<<ENDDOCUMENT);
        <td  align="left" valign="top">      <div style="float: left;">
         <small><b>$lt{'serv'}:&nbsp;</b></small>       <table border="0" cellspacing="0" cellpadding="0">
        </td>  $domainrow
        <td align="left" valign="top">  $serverrow
         <small><tt>&nbsp;$lonhost ($role)</tt></small>  $loadrow    
        </td>  $userloadrow
       </tr>  $versionrow
 END       </table>
     if ($loadlim) {      </div>
         $loadrow = <<"END";      <div style="float: right;">
       <tr>      $domainlogo
        <td align="left" valign="top">      </div>
         <small><b>$lt{'load'}:&nbsp;</b></small>      <br style="clear:both;" />
        </td>   </div>
        <td align="left" valign="top">  
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>  <script type="text/javascript">
        </td>  // <![CDATA[
       </tr>  // the if prevents the script error if the browser can not handle this
 END  if ( document.client.uname ) { document.client.uname.focus(); }
     }  // ]]>
     if ($uloadlim) {  </script>
         $userloadrow = <<"END";  $helpdeskscript
       <tr>  
        <td align="left" valign="top">  ENDDOCUMENT
         <small><b>$lt{'userload'}:&nbsp;</b></small>      my %endargs = ( 'noredirectlink' => 1, );
        </td>      $r->print(&Apache::loncommon::end_page(\%endargs));
        <td align="left" valign="top">      return OK;
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>  }
        </td>  
       </tr>  sub check_loginvia {
 END      my ($domain,$lonhost,$lonidsdir,$balcookie,$linkprot) = @_;
     }      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {          return;
         $versionrow = <<"END";      }
       <tr>      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
        <td colspan="2" align="left">      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
         <small>$version</small>      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
        </td>      my $output;
       </tr>      if ($loginvia ne '') {
 END          my $noredirect;
     }          my $ip = &Apache::lonnet::get_requestor_ip();  
           if ($ip eq '127.0.0.1') {
     $r->print(<<ENDDOCUMENT);              $noredirect = 1;
     <div style="float: left;">          } else {
      <table border="0" cellspacing="0" cellpadding="0">              if ($loginvia_exempt ne '') {
 $domainrow                  my @exempt = split(',',$loginvia_exempt);
 $serverrow                  if (grep(/^\Q$ip\E$/,@exempt)) {
 $loadrow                          $noredirect = 1;
 $userloadrow                  }
 $versionrow              }
      </table>          }
     </div>          unless ($noredirect) {
     <div style="float: right;">              my ($newhost,$path);
     $domainlogo              if ($loginvia =~ /:/) {
     </div>                  ($newhost,$path) = split(':',$loginvia);
     <br style="clear:both;" />              } else {
  </div>                  $newhost = $loginvia;
               }
 <script type="text/javascript">              if ($newhost ne $lonhost) {
 // <![CDATA[                  if (&Apache::lonnet::hostname($newhost) ne '') {
 // the if prevents the script error if the browser can not handle this                      if ($balcookie) {
 if ( document.client.uname ) { document.client.uname.focus(); }                          my ($balancer,$cookie) = split(/:/,$balcookie);
 // ]]>                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
 </script>                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
 $helpdeskscript                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
                                   if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
 ENDDOCUMENT                                      while (my $filename=readdir($dh)) {
     my %endargs = ( 'noredirectlink' => 1, );                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
     $r->print(&Apache::loncommon::end_page(\%endargs));                                              my $handle = $1;
     return OK;                                              my %hash =
 }                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
                                                                                        ['request.balancercookie',
 sub check_loginvia {                                                                                        'user.linkedenv']);
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {                                                  if (unlink("$lonidsdir/$filename")) {
         return;                                                      if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
     }                                                          (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);                                                          (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};                                                          unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};                                                      }
     my $output;                                                  }
     if ($loginvia ne '') {                                              }
         my $noredirect;                                              last;
         my $ip = &Apache::lonnet::get_requestor_ip();                                          }
         if ($ip eq '127.0.0.1') {                                      }
             $noredirect = 1;                                      closedir($dh);
         } else {                                  }
             if ($loginvia_exempt ne '') {                              }
                 my @exempt = split(',',$loginvia_exempt);                          }
                 if (grep(/^\Q$ip\E$/,@exempt)) {                      }
                     $noredirect = 1;                      $output = &redirect_page($newhost,$path,$linkprot);
                 }                  }
             }              }
         }          }
         unless ($noredirect) {      }
             my ($newhost,$path);      return $output;
             if ($loginvia =~ /:/) {  }
                 ($newhost,$path) = split(':',$loginvia);  
             } else {  sub redirect_page {
                 $newhost = $loginvia;      my ($desthost,$path,$linkprot) = @_;
             }      my $hostname = &Apache::lonnet::hostname($desthost);
             if ($newhost ne $lonhost) {      my $protocol = $Apache::lonnet::protocol{$desthost};
                 if (&Apache::lonnet::hostname($newhost) ne '') {      $protocol = 'http' if ($protocol ne 'https');
                     if ($balcookie) {      unless ($path =~ m{^/}) {
                         my ($balancer,$cookie) = split(/:/,$balcookie);          $path = '/'.$path;
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {      }
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);      my $url = $protocol.'://'.$hostname.$path;
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {      if ($env{'form.firsturl'} ne '') {
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {          my $querystring;
                                     while (my $filename=readdir($dh)) {          if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {              $querystring = &uri_escape_utf8($env{'form.firsturl'});
                                             my $handle = $1;          } else {
                                             my %hash =              $querystring = &uri_escape($env{'form.firsturl'});
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,          }
                                                                                      ['request.balancercookie',          $querystring = &HTML::Entities::encode($querystring,"'");
                                                                                       'user.linkedenv']);          $url .='?firsturl='.$querystring
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {      }
                                                 if (unlink("$lonidsdir/$filename")) {      if ($linkprot) {
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&          my $ltoken = &Apache::lonnet::tmpput({linkprot => $linkprot},$desthost);
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&          if ($ltoken) {
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {              $url .= (($url =~ /\?/) ? '&amp;' : '?').'ltoken='.$ltoken;
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");          }
                                                     }      }
                                                 }      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
                                             }                                                      {'redirect' => [0,$url],});
                                             last;      my $end_page   = &Apache::loncommon::end_page();
                                         }      return $start_page.$end_page;
                                     }  }
                                     closedir($dh);  
                                 }  sub contactdisplay {
                             }      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
                         }          $possdoms) = @_;
                     }      my $contactblock;
                     $output = &redirect_page($newhost,$path);      my $origmail;
                 }      if (ref($possdoms) eq 'ARRAY') {
             }          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
         }              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
     }          }
     return $output;      }
 }      my $requestmail =
           &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
 sub redirect_page {                                                   $authdomain,$origmail);
     my ($desthost,$path) = @_;      unless ($showhelpdesk eq '0') {
     my $hostname = &Apache::lonnet::hostname($desthost);          if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
     my $protocol = $Apache::lonnet::protocol{$desthost};              $showhelpdesk = 1;
     $protocol = 'http' if ($protocol ne 'https');          } else {
     unless ($path =~ m{^/}) {              $showhelpdesk = 0;
         $path = '/'.$path;          }
     }      }
     my $url = $protocol.'://'.$hostname.$path;      if ($servadm && $showadminmail) {
     if ($env{'form.firsturl'} ne '') {          $contactblock .= $$lt{'servadm'}.':<br />'.
         my $querystring;                           '<tt>'.$servadm.'</tt><br />';
         if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {      }
             $querystring = &uri_escape_utf8($env{'form.firsturl'});      if ($showhelpdesk) {
         } else {          $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
             $querystring = &uri_escape($env{'form.firsturl'});          my $thisurl = &escape('/adm/login');
         }          $$helpdeskscript = <<"ENDSCRIPT";
         $querystring = &HTML::Entities::encode($querystring,"'");  <script type="text/javascript">
         $url .='?firsturl='.$querystring;  // <![CDATA[
     }  function helpdesk() {
     if (($env{'form.ltoken'}) || ($env{'form.linkkey'} ne '')) {      var possdom = document.client.udom.value;
         my %link_info;      var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
         if ($env{'form.ltoken'}) {      if (codedom == '') {
             $link_info{'ltoken'} = $env{'form.ltoken'};          codedom = "$authdomain";
         } elsif ($env{'form.linkkey'} ne '') {      }
             $link_info{'linkkey'} = $env{'form.linkkey'};      var querystr = "origurl=$thisurl&codedom="+codedom;
         }      document.location.href = "/adm/helpdesk?"+querystr;
         my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');      return;
         unless (($token eq 'con_lost') || ($token eq 'refused') ||  }
                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {  // ]]>
             $url .= (($url=~/\?/)?'&amp;':'?') . 'ttoken='.$token;  </script>
         }  ENDSCRIPT
     }      }
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,      return $contactblock;
                                                     {'redirect' => [0,$url],});  }
     my $end_page   = &Apache::loncommon::end_page();  
     return $start_page.$end_page;  sub forgotpwdisplay {
 }      my (%lt) = @_;
       my $prompt_for_resetpw = 1;
 sub contactdisplay {      if ($prompt_for_resetpw) {
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,          return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
         $possdoms) = @_;      }
     my $contactblock;      return;
     my $origmail;  }
     if (ref($possdoms) eq 'ARRAY') {  
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {   sub coursecatalog_link {
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};      my ($linkname) = @_;
         }      return <<"END";
     }        <a href="/adm/coursecatalog">$linkname</a>
     my $requestmail =   END
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',  }
                                                  $authdomain,$origmail);  
     unless ($showhelpdesk eq '0') {  sub newuser_link {
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {      my ($linkname) = @_;
             $showhelpdesk = 1;      return '<a href="/adm/createaccount">'.$linkname.'</a>';
         } else {  }
             $showhelpdesk = 0;  
         }  1;
     }  __END__
     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.2  
changed lines
  Added in v.1.189


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