Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.8 and 1.182

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


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