Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.1 and 1.182

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


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