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

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

Removed from v.1.158.2.13.2.5  
changed lines
  Added in v.1.186


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