Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.15 and 1.207

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

Removed from v.1.158.2.15  
changed lines
  Added in v.1.207


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