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

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

Removed from v.1.158.2.13.2.7  
changed lines
  Added in v.1.183


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