Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.4 and 1.200

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


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