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

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


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