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

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


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