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

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

Removed from v.1.158.2.13.2.2  
changed lines
  Added in v.1.178


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