Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.14 and 1.191

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

Removed from v.1.158.2.14  
changed lines
  Added in v.1.191


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