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

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


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