Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.5 and 1.195

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


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