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

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


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