Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.6 and 1.192

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

Removed from v.1.158.2.13.2.6  
changed lines
  Added in v.1.192


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