Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.2 and 1.199

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

Removed from v.1.158.2.13.2.2  
changed lines
  Added in v.1.199


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