Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.11 and 1.180

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


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