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

version 1.158.2.13.2.5, 2022/06/01 12:21:06 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,$linkprot_for_login);  # -------------------------------------------------------- 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)];
                     $linkprot_for_login = $info{'linkprot'};      }
                     $tokenextras .= '&linkprot='.&escape($info{'linkprot'});  
                     $tokentype = 'link';      my $ukey='';
                     last;      for (0..7) {
                 }          $ukey.=$hexstr[rand(15)];
             } else {      }
                 $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});  
                 if (($name eq 'linkkey') || ($name eq 'linkprot')) {      my $lextkey=hex($lkey);
                     if ((($env{'form.retry'}) || ($env{'form.sso'})) &&      if ($lextkey>2147483647) { $lextkey-=4294967296; }
                         (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {  
                         $linkprot_for_login = $env{'form.linkprot'};      my $uextkey=hex($ukey);
                     }      if ($uextkey>2147483647) { $uextkey-=4294967296; }
                     $tokentype = 'link';  
                 }  # -------------------------------------------------------- Store away log token
             }      my ($tokenextras,$tokentype,$linkprot_for_login);
         }      my @names = ('role','symb','iptoken','ltoken','linkprotuser','linkprot','linkkey');
     }      foreach my $name (@names) {
     if ($tokentype) {          if ($env{'form.'.$name} ne '') {
         $tokenextras .= ":$tokentype";              if ($name eq 'ltoken') {
     }                  my %info = &Apache::lonnet::tmpget($env{'form.'.$name});
     my $logtoken=Apache::lonnet::reply(                  if ($info{'linkprot'}) {
        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,                      $linkprot_for_login = $info{'linkprot'};
        $lonhost);                      $tokenextras .= '&linkprot='.&escape($info{'linkprot'});
                       if ($info{'linkprotuser'}) {
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname                          $tokenextras .= '&linkprotuser='.&escape($info{'linkprotuser'});
 #    we are in serious trouble                      }
                       $tokentype = 'link';
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {                      last;
         if ($logtoken eq 'no_such_host') {                  }
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');              } else {
         }                  $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});
         if ($env{'form.ltoken'}) {                  if (($name eq 'linkkey') || ($name eq 'linkprot')) {
             &Apache::lonnet::tmpdel($env{'form.ltoken'});                      if ((($env{'form.retry'}) || ($env{'form.sso'})) &&
             delete($env{'form.ltoken'});                          (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {
         }                          $linkprot_for_login = $env{'form.linkprot'};
         my $spares='';                      }
         my (@sparehosts,%spareservers);                      $tokentype = 'link';
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);                  }
         if (ref($sparesref) eq 'HASH') {              }
             foreach my $key (keys(%{$sparesref})) {          }
                 if (ref($sparesref->{$key}) eq 'ARRAY') {      }
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp      if ($tokentype) {
                                         &Apache::lonnet::hostname($b);          $tokenextras .= ":$tokentype";
                                       } @{$sparesref->{$key}};      }
                     if (@sorted) {      my $logtoken=Apache::lonnet::reply(
                         if ($key eq 'primary') {         'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,
                             unshift(@sparehosts,@sorted);         $lonhost);
                         } elsif ($key eq 'default') {  
                             push(@sparehosts,@sorted);  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
                         }  #    we are in serious trouble
                     }  
                 }      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
             }          if ($logtoken eq 'no_such_host') {
         }              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
         foreach my $hostid (@sparehosts) {          }
             next if ($hostid eq $lonhost);          if ($env{'form.ltoken'}) {
     my $hostname = &Apache::lonnet::hostname($hostid);              &Apache::lonnet::tmpdel($env{'form.ltoken'});
     next if (($hostname eq '') || ($spareservers{$hostname}));              delete($env{'form.ltoken'});
             $spareservers{$hostname} = 1;          }
             my $protocol = $Apache::lonnet::protocol{$hostid};          my $spares='';
             $protocol = 'http' if ($protocol ne 'https');          my (@sparehosts,%spareservers);
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.          my $sparesref = &Apache::lonnet::this_host_spares($defdom);
                 $hostname.          if (ref($sparesref) eq 'HASH') {
                 '/adm/login?domain='.$authdomain.'">'.              foreach my $key (keys(%{$sparesref})) {
                 $hostname.'</a>'.                  if (ref($sparesref->{$key}) eq 'ARRAY') {
                 ' '.&mt('(preferred)').'</span>'.$/;                      my @sorted = sort { &Apache::lonnet::hostname($a) cmp
         }                                          &Apache::lonnet::hostname($b);
         if ($spares) {                                        } @{$sparesref->{$key}};
             $spares.= '<br />';                      if (@sorted) {
         }                          if ($key eq 'primary') {
         my %all_hostnames = &Apache::lonnet::all_hostnames();                              unshift(@sparehosts,@sorted);
         foreach my $hostid (sort                          } elsif ($key eq 'default') {
     {                              push(@sparehosts,@sorted);
  &Apache::lonnet::hostname($a) cmp                          }
     &Apache::lonnet::hostname($b);                      }
     }                  }
     keys(%all_hostnames)) {              }
             next if ($hostid eq $lonhost);          }
             my $hostname = &Apache::lonnet::hostname($hostid);          foreach my $hostid (@sparehosts) {
             next if (($hostname eq '') || ($spareservers{$hostname}));              next if ($hostid eq $lonhost);
             $spareservers{$hostname} = 1;      my $hostname = &Apache::lonnet::hostname($hostid);
             my $protocol = $Apache::lonnet::protocol{$hostid};      next if (($hostname eq '') || ($spareservers{$hostname}));
             $protocol = 'http' if ($protocol ne 'https');              $spareservers{$hostname} = 1;
             $spares.='<br /><a href="'.$protocol.'://'.              my $protocol = $Apache::lonnet::protocol{$hostid};
              $hostname.              $protocol = 'http' if ($protocol ne 'https');
              '/adm/login?domain='.$authdomain.'">'.              $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
              $hostname.'</a>';                  $hostname.
          }                  '/adm/login?domain='.$authdomain.'">'.
          $r->print(                  $hostname.'</a>'.
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'                  ' '.&mt('(preferred)').'</span>'.$/;
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'          }
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'          if ($spares) {
   .&mt('The LearningOnline Network with CAPA')              $spares.= '<br />';
   .'</title></head>'          }
   .'<body bgcolor="#FFFFFF">'          my %all_hostnames = &Apache::lonnet::all_hostnames();
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'          foreach my $hostid (sort
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'      {
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');   &Apache::lonnet::hostname($a) cmp
         if ($spares) {      &Apache::lonnet::hostname($b);
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      }
                      .'</p>'      keys(%all_hostnames)) {
                      .$spares);              next if ($hostid eq $lonhost);
         }              my $hostname = &Apache::lonnet::hostname($hostid);
         $r->print('</body>'              next if (($hostname eq '') || ($spareservers{$hostname}));
                  .'</html>'              $spareservers{$hostname} = 1;
         );              my $protocol = $Apache::lonnet::protocol{$hostid};
         return OK;              $protocol = 'http' if ($protocol ne 'https');
     }              $spares.='<br /><a href="'.$protocol.'://'.
                $hostname.
 # ----------------------------------------------- Apparently we are in business               '/adm/login?domain='.$authdomain.'">'.
     $servadm=~s/\,/\<br \/\>/g;               $hostname.'</a>';
            }
 # ----------------------------------------------------------- Front page design           $r->print(
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);     '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
     my $font=&Apache::loncommon::designparm('login.font',$domain);    .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
     my $link=&Apache::loncommon::designparm('login.link',$domain);    .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);    .&mt('The LearningOnline Network with CAPA')
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);    .'</title></head>'
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);    .'<body bgcolor="#FFFFFF">'
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);          if ($spares) {
     my $img=&Apache::loncommon::designparm('login.img',$domain);              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
     my $domainlogo=&Apache::loncommon::domainlogo($domain);                       .'</p>'
     my $showbanner = 1;                       .$spares);
     my $showmainlogo = 1;          }
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {          $r->print('</body>'
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);                   .'</html>'
     }          );
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {          return OK;
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);      }
     }  
     my $showadminmail;  # ----------------------------------------------- Apparently we are in business
     my @possdoms = &Apache::lonnet::current_machine_domains();      $servadm=~s/\,/\<br \/\>/g;
     if (grep(/^\Q$domain\E$/,@possdoms)) {  
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);  # ----------------------------------------------------------- Front page design
     }      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
     my $showcoursecat =      my $font=&Apache::loncommon::designparm('login.font',$domain);
         &Apache::loncommon::designparm('login.coursecatalog',$domain);      my $link=&Apache::loncommon::designparm('login.link',$domain);
     my $shownewuserlink =       my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
         &Apache::loncommon::designparm('login.newuser',$domain);      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
     my $showhelpdesk =      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
         &Apache::loncommon::designparm('login.helpdesk',$domain);      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
     my $now=time;      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
     my $js = (<<ENDSCRIPT);      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
       my $logo=&Apache::loncommon::designparm('login.logo',$domain);
 <script type="text/javascript" language="JavaScript">      my $img=&Apache::loncommon::designparm('login.img',$domain);
 // <![CDATA[      my $domainlogo=&Apache::loncommon::domainlogo($domain);
 function send()      my $showbanner = 1;
 {      my $showmainlogo = 1;
 this.document.server.elements.uname.value      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
 =this.document.client.elements.uname.value;          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
       }
 this.document.server.elements.udom.value      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
 =this.document.client.elements.udom.value;          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
       }
 uextkey=this.document.client.elements.uextkey.value;      my $showadminmail;
 lextkey=this.document.client.elements.lextkey.value;      my @possdoms = &Apache::lonnet::current_machine_domains();
 initkeys();      if (grep(/^\Q$domain\E$/,@possdoms)) {
           $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 this.document.server.elements.upass0.value      }
     =getCrypted(this.document.client.elements.upass$now.value);      my $showcoursecat =
           &Apache::loncommon::designparm('login.coursecatalog',$domain);
 this.document.client.elements.uname.value='';      my $shownewuserlink =
 this.document.client.elements.upass$now.value='';          &Apache::loncommon::designparm('login.newuser',$domain);
       my $showhelpdesk =
 this.document.server.submit();          &Apache::loncommon::designparm('login.helpdesk',$domain);
 return false;      my $now=time;
 }      my $js = (<<ENDSCRIPT);
   
 function enableInput() {  <script type="text/javascript" language="JavaScript">
     this.document.client.elements.upass$now.removeAttribute("readOnly");  // <![CDATA[
     this.document.client.elements.uname.removeAttribute("readOnly");  function send()
     this.document.client.elements.udom.removeAttribute("readOnly");  {
     return;  this.document.server.elements.uname.value
 }  =this.document.client.elements.uname.value;
   
 // ]]>  this.document.server.elements.udom.value
 </script>  =this.document.client.elements.udom.value;
   
 ENDSCRIPT  uextkey=this.document.client.elements.uextkey.value;
   lextkey=this.document.client.elements.lextkey.value;
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,  initkeys();
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);  
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);  if(this.document.server.action.substr(0,5) === 'http:'){
     @hosts = &Apache::lonnet::current_machine_ids();      this.document.server.elements.upass0.value
     $lonhost_in_use = $lonhost;          =getCrypted(this.document.client.elements.upass$now.value);
     if (@hosts > 1) {  } else {
         foreach my $hostid (@hosts) {      this.document.server.elements.upass0.value
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {          =this.document.client.elements.upass$now.value;
                 $lonhost_in_use = $hostid;  }
                 last;  
             }  this.document.client.elements.uname.value='';
         }  this.document.client.elements.upass$now.value='';
     }  
     $saml_prefix = $defdom.'.login.saml_';  this.document.server.submit();
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {  return false;
         $saml_landing = 1;  }
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};  
         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};  function enableInput() {
         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};      this.document.client.elements.upass$now.removeAttribute("readOnly");
         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};      this.document.client.elements.uname.removeAttribute("readOnly");
         $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};      this.document.client.elements.udom.removeAttribute("readOnly");
         $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};      return;
     }  }
     if ($saml_landing) {  
        if ($samlssotext eq '') {  // ]]>
            $samlssotext = 'SSO Login';  </script>
        }  
        if ($samlnonsso eq '') {  ENDSCRIPT
            $samlnonsso = 'Non-SSO Login';  
        }      my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,
        $js .= <<"ENDSAMLJS";          $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);
       %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
 <script type="text/javascript">      @hosts = &Apache::lonnet::current_machine_ids();
 // <![CDATA[      $lonhost_in_use = $lonhost;
 function toggleLClogin() {      if (@hosts > 1) {
     if (document.getElementById('LC_standard_login')) {          foreach my $hostid (@hosts) {
         if (document.getElementById('LC_standard_login').style.display == 'none') {              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
             document.getElementById('LC_standard_login').style.display = 'inline-block';                  $lonhost_in_use = $hostid;
             if (document.getElementById('LC_login_text')) {                  last;
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';              }
             }          }
             if ( document.client.uname ) { document.client.uname.focus(); }      }
             if (document.getElementById('LC_SSO_login')) {      $saml_prefix = $defdom.'.login.saml_';
                 document.getElementById('LC_SSO_login').style.display = 'none';      if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {
             }          $saml_landing = 1;
         } else {          $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};
             document.getElementById('LC_standard_login').style.display = 'none';          $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};
             if (document.getElementById('LC_login_text')) {          $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';          $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};
             }          $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};
             if (document.getElementById('LC_SSO_login')) {          $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';      }
             }      if ($saml_landing) {
         }         if ($samlssotext eq '') {
     }             $samlssotext = 'SSO Login';
     return;         }
 }         if ($samlnonsso eq '') {
              $samlnonsso = 'Non-SSO Login';
 // ]]>         }
 </script>         $js .= <<"ENDSAMLJS";
   
 ENDSAMLJS  <script type="text/javascript">
     }  // <![CDATA[
   function toggleLClogin() {
 # --------------------------------------------------- Print login screen header      if (document.getElementById('LC_standard_login')) {
           if (document.getElementById('LC_standard_login').style.display == 'none') {
     my %add_entries = (              document.getElementById('LC_standard_login').style.display = 'inline-block';
        bgcolor      => "$mainbg",              if (document.getElementById('LC_login_text')) {
        text         => "$font",                  document.getElementById('LC_login_text').innerHTML = '$samlnonsso';
        link         => "$link",              }
        vlink        => "$vlink",              if ( document.client.uname ) { document.client.uname.focus(); }
        alink        => "$alink",              if (document.getElementById('LC_SSO_login')) {
                onload       => 'javascript:enableInput();',);                  document.getElementById('LC_SSO_login').style.display = 'none';
               }
     my ($headextra,$headextra_exempt);          } else {
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};              document.getElementById('LC_standard_login').style.display = 'none';
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};              if (document.getElementById('LC_login_text')) {
     if ($headextra) {                  document.getElementById('LC_login_text').innerHTML = '$samlssotext';
         my $omitextra;              }
         if ($headextra_exempt ne '') {              if (document.getElementById('LC_SSO_login')) {
             my @exempt = split(',',$headextra_exempt);                  document.getElementById('LC_SSO_login').style.display = 'inline-block';
             my $ip = &Apache::lonnet::get_requestor_ip();              }
             if (grep(/^\Q$ip\E$/,@exempt)) {          }
                 $omitextra = 1;      }
             }      return;
         }  }
         unless ($omitextra) {  
             my $confname = $defdom.'-domainconfig';  // ]]>
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {  </script>
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));  
                 unless ($extra eq '-1') {  ENDSAMLJS
                     $js .= "\n".$extra."\n";      }
                 }  
             }  # --------------------------------------------------- Print login screen header
         }  
     }      my %add_entries = (
          bgcolor      => "$mainbg",
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,         text         => "$font",
        { 'redirect'       => [$expire,'/adm/roles'],          link         => "$link",
  'add_entries' => \%add_entries,         vlink        => "$vlink",
  'only_body'   => 1,}));         alink        => "$alink",
                  onload       => 'javascript:enableInput();',);
 # ----------------------------------------------------------------------- Texts  
       my ($headextra,$headextra_exempt);
     my %lt=&Apache::lonlocal::texthash(      $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
           'un'       => 'Username',      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
           'pw'       => 'Password',      if ($headextra) {
           'dom'      => 'Domain',          my $omitextra;
           'perc'     => 'percent',          if ($headextra_exempt ne '') {
           'load'     => 'Server Load',              my @exempt = split(',',$headextra_exempt);
           'userload' => 'User Load',              my $ip = &Apache::lonnet::get_requestor_ip();
           'catalog'  => 'Course/Community Catalog',              if (grep(/^\Q$ip\E$/,@exempt)) {
           'log'      => 'Log in',                  $omitextra = 1;
           'help'     => 'Log-in Help',              }
           'serv'     => 'Server',          }
           'servadm'  => 'Server Administration',          unless ($omitextra) {
           'helpdesk' => 'Contact Helpdesk',              my $confname = $defdom.'-domainconfig';
           'forgotpw' => 'Forgot password?',              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
           'newuser'  => 'New User?',                  my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
           'change'   => 'Change?',                  unless ($extra eq '-1') {
        );                      $js .= "\n".$extra."\n";
 # -------------------------------------------------- Change password field name                  }
               }
     my $forgotpw = &forgotpwdisplay(%lt);          }
     $forgotpw .= '<br />' if $forgotpw;      }
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);  
     if ($loginhelp) {      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';         { 'redirect'       => [$expire,'/adm/roles'],
     }   'add_entries' => \%add_entries,
    'only_body'   => 1,}));
 # ---------------------------------------------------- Serve out DES JavaScript  
     {  # ----------------------------------------------------------------------- Texts
     my $jsh=Apache::File->new($include."/londes.js");  
     $r->print(<$jsh>);      my %lt=&Apache::lonlocal::texthash(
     }            'un'       => 'Username',
 # ---------------------------------------------------------- Serve rest of page            'pw'       => 'Password',
             'dom'      => 'Domain',
     $r->print(            'perc'     => 'percent',
     '<div class="LC_Box"'            'load'     => 'Server Load',
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'            'userload' => 'User Load',
 );            'catalog'  => 'Course/Community Catalog',
             'log'      => 'Log in',
     $r->print(<<ENDSERVERFORM);            'help'     => 'Log-in Help',
 <form name="server" action="/adm/authenticate" method="post" target="_top">            'serv'     => 'Server',
    <input type="hidden" name="logtoken" value="$logtoken" />            'servadm'  => 'Server Administration',
    <input type="hidden" name="serverid" value="$lonhost" />            'helpdesk' => 'Contact Helpdesk',
    <input type="hidden" name="uname" value="" />            'forgotpw' => 'Forgot password?',
    <input type="hidden" name="upass0" value="" />            'newuser'  => 'New User?',
    <input type="hidden" name="udom" value="" />            'change'   => 'Change?',
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />         );
    <input type="hidden" name="localres" value="$env{'form.localres'}" />  # -------------------------------------------------- Change password field name
   </form>  
 ENDSERVERFORM      my $forgotpw = &forgotpwdisplay(%lt);
     my $coursecatalog;      $forgotpw .= '<br />' if $forgotpw;
     if (($showcoursecat eq '') || ($showcoursecat)) {      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';      if ($loginhelp) {
     }          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
     my $newuserlink;      }
     if ($shownewuserlink) {  
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';  # ---------------------------------------------------- Serve out DES JavaScript
     }      {
     my $logintitle =      my $jsh=Apache::File->new($include."/londes.js");
         '<h2 class="LC_hcell"'      $r->print(<$jsh>);
        .' style="background:'.$loginbox_header_bgcol.';'      }
        .' color:'.$loginbox_header_textcol.'">'  # ---------------------------------------------------------- Serve rest of page
        .$lt{'log'}  
        .'</h2>';      $r->print(
       '<div class="LC_Box"'
     my $noscript_warning='<noscript><span class="LC_warning"><b>'     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')  );
                         .'</b></span></noscript>';  
     my $helpdeskscript;      $r->print(<<ENDSERVERFORM);
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,  <form name="server" action="/adm/authenticate" method="post" target="_top">
                                        $authdomain,\$helpdeskscript,     <input type="hidden" name="logtoken" value="$logtoken" />
                                        $showhelpdesk,\@possdoms);     <input type="hidden" name="serverid" value="$lonhost" />
      <input type="hidden" name="uname" value="" />
     my $mobileargs;     <input type="hidden" name="upass0" value="" />
     if ($clientmobile) {     <input type="hidden" name="udom" value="" />
         $mobileargs = 'autocapitalize="off" autocorrect="off"';      <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
     }     <input type="hidden" name="localres" value="$env{'form.localres'}" />
     my $loginform=(<<LFORM);    </form>
 <form name="client" action="" onsubmit="return(send())" id="lclogin">  ENDSERVERFORM
   <input type="hidden" name="lextkey" value="$lextkey" />      my $coursecatalog;
   <input type="hidden" name="uextkey" value="$uextkey" />      if (($showcoursecat eq '') || ($showcoursecat)) {
   <b><label for="uname">$lt{'un'}</label>:</b><br />          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />      }
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />      my $newuserlink;
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />      if ($shownewuserlink) {
   <b><label for="udom">$lt{'dom'}</label>:</b><br />          $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />      }
   <input type="submit" value="$lt{'log'}" />      my $logintitle =
 </form>          '<h2 class="LC_hcell"'
 LFORM         .' style="background:'.$loginbox_header_bgcol.';'
          .' color:'.$loginbox_header_textcol.'">'
     if ($showbanner) {         .$lt{'log'}
         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);         .'</h2>';
         if ($alttext eq '') {  
             $alttext = 'The Learning Online Network with CAPA';      my $noscript_warning='<noscript><span class="LC_warning"><b>'
         }                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
         $r->print(<<HEADER);                          .'</b></span></noscript>';
 <!-- The LON-CAPA Header -->      my $helpdeskscript;
 <div style="background:$pgbg;margin:0;width:100%;">      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />                                         $authdomain,\$helpdeskscript,
 </div>                                         $showhelpdesk,\@possdoms);
 HEADER  
     }      my $mobileargs;
       if ($clientmobile) {
     my $stdauthformstyle = 'inline-block';          $mobileargs = 'autocapitalize="off" autocorrect="off"';
     my $ssoauthstyle = 'none';      }
     my $logintype;      my $loginform=(<<LFORM);
     $r->print('<div style="float:left;margin-top:0;">');  <form name="client" action="" onsubmit="return(send())" id="lclogin">
     if ($saml_landing) {    <input type="hidden" name="lextkey" value="$lextkey" />
         $ssoauthstyle = 'inline-block';    <input type="hidden" name="uextkey" value="$uextkey" />
         $stdauthformstyle = 'none';    <b><label for="uname">$lt{'un'}</label>:</b><br />
         $logintype = $samlssotext;    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
         my $ssologin = '/adm/sso';    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
         if ($samlssourl  ne '') {    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
             $ssologin = $samlssourl;    <b><label for="udom">$lt{'dom'}</label>:</b><br />
         }    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {    <input type="submit" value="$lt{'log'}" />
             my $querystring;  </form>
             if ($env{'form.firsturl'} ne '') {  LFORM
                 $querystring = 'origurl=';  
                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {      if ($showbanner) {
                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});          my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);
                 } else {          if ($alttext eq '') {
                     $querystring .= &uri_escape($env{'form.firsturl'});              $alttext = 'The Learning Online Network with CAPA';
                 }          }
                 $querystring = &HTML::Entities::encode($querystring,"'");          $r->print(<<HEADER);
             }  <!-- The LON-CAPA Header -->
             if ($env{'form.ltoken'} ne '') {  <div style="background:$pgbg;margin:0;width:100%;">
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.    <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />
                                   &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));  </div>
             } elsif ($env{'form.linkkey'}) {  HEADER
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.      }
                                   &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));  
             }      my $stdauthformstyle = 'inline-block';
             if ($querystring ne '') {      my $ssoauthstyle = 'none';
                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;      my $logintype;
             }      $r->print('<div style="float:left;margin-top:0;">');
         } elsif ($logtoken ne '') {      if ($saml_landing) {
             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;          $ssoauthstyle = 'inline-block';
         }          $stdauthformstyle = 'none';
         my $ssohref;          $logintype = $samlssotext;
         if ($samlssoimg ne '') {          my $ssologin = '/adm/sso';
             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'">'.          if ($samlssourl  ne '') {
                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';              $ssologin = $samlssourl;
         } else {          }
             $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';          if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
         }              my $querystring;
         if (($env{'form.saml'} eq 'no') ||              if ($env{'form.firsturl'} ne '') {
             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {                  $querystring = 'origurl=';
             $ssoauthstyle = 'none';                  if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
             $stdauthformstyle = 'inline-block';                      $querystring .= &uri_escape_utf8($env{'form.firsturl'});
             $logintype = $samlnonsso;                  } else {
         }                      $querystring .= &uri_escape($env{'form.firsturl'});
         $r->print(<<ENDSAML);                  }
 <p>                  $querystring = &HTML::Entities::encode($querystring,"'");
 Log-in type:              }
 <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />              if ($env{'form.ltoken'} ne '') {
 <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>                  $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.
 </p>                                    &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));
 <div style="display:$ssoauthstyle" id="LC_SSO_login">              } elsif ($env{'form.linkkey'}) {
 <div class="LC_Box" style="padding-top: 10px;">                  $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.
 $ssohref                                    &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));
 $noscript_warning              }
 </div>              if ($querystring ne '') {
 <div class="LC_Box" style="padding-top: 10px;">                  $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;
 $loginhelp              }
 $contactblock          } elsif ($logtoken ne '') {
 $coursecatalog              $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;
 </div>          }
 </div>          my $ssohref;
 ENDSAML          if ($samlssoimg ne '') {
     } else {              $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'">'.
         if ($env{'form.ltoken'}) {                         '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';
             &Apache::lonnet::tmpdel($env{'form.ltoken'});          } else {
             delete($env{'form.ltoken'});              $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';
         }          }
     }          if (($env{'form.saml'} eq 'no') ||
     my $in_frame_js;              (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {
     if ($linkprot_for_login) {              $ssoauthstyle = 'none';
         my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);              $stdauthformstyle = 'inline-block';
         if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {              $logintype = $samlnonsso;
             my $set_target;          }
             if (($env{'form.retry'}) || ($env{'form.sso'})) {          $r->print(<<ENDSAML);
                 if ($linkproturi eq $env{'form.firsturl'}) {  <p>
                     $set_target = "    document.server.target = '_self';";  Log-in type:
                 }  <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />
             } else {  <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>
                 $set_target = <<ENDTARG;  </p>
     var linkproturi = '$linkproturi';  <div style="display:$ssoauthstyle" id="LC_SSO_login">
     var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');  <div class="LC_Box" style="padding-top: 10px;">
     if (linkproturi == path) {  $ssohref
         document.server.target = '_self';  $noscript_warning
     }  </div>
 ENDTARG  <div class="LC_Box" style="padding-top: 10px;">
             }  $loginhelp
             $in_frame_js = <<ENDJS;  $contactblock
 <script type="text/javascript">  $coursecatalog
 // <![CDATA[  </div>
 if ((window.self !== window.top) && (document.server.target != '_self')) {  </div>
     $set_target  ENDSAML
 }      } else {
 // ]]>          if ($env{'form.ltoken'}) {
 </script>              &Apache::lonnet::tmpdel($env{'form.ltoken'});
 ENDJS              delete($env{'form.ltoken'});
         }          }
     }      }
       my $in_frame_js;
     $r->print(<<ENDLOGIN);      if ($linkprot_for_login) {
 <div style="display:$stdauthformstyle;" id="LC_standard_login">          my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);
 <div class="LC_Box" style="background:$loginbox_bg;">          if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {
   $logintitle              my $set_target;
   $loginform              if (($env{'form.retry'}) || ($env{'form.sso'})) {
   $noscript_warning                  if ($linkproturi eq $env{'form.firsturl'}) {
 </div>                      $set_target = "    document.server.target = '_self';";
                     }
 <div class="LC_Box" style="padding-top: 10px;">              } else {
   $loginhelp                  $set_target = <<ENDTARG;
   $forgotpw      var linkproturi = '$linkproturi';
   $contactblock      var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');
   $newuserlink      if (linkproturi == path) {
   $coursecatalog          document.server.target = '_self';
 </div>      }
 </div>  ENDTARG
               }
 ENDLOGIN              $in_frame_js = <<ENDJS;
     $r->print('</div><div>'."\n");  <script type="text/javascript">
     if ($showmainlogo) {  // <![CDATA[
         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);  if ((window.self !== window.top) && (document.server.target != '_self')) {
         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");      $set_target
     }  }
 $r->print(<<ENDTOP);  // ]]>
 $announcements  </script>
 </div>  ENDJS
 <hr style="clear:both;" />          }
 ENDTOP      }
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);  
     $domainrow = <<"END";      $r->print(<<ENDLOGIN);
       <tr>  <div style="display:$stdauthformstyle;" id="LC_standard_login">
        <td  align="left" valign="top">  <div class="LC_Box" style="background:$loginbox_bg;">
         <small><b>$lt{'dom'}:&nbsp;</b></small>    $logintitle
        </td>    $loginform
        <td  align="left" valign="top">    $noscript_warning
         <small><tt>&nbsp;$domain</tt></small>  </div>
        </td>   
       </tr>  <div class="LC_Box" style="padding-top: 10px;">
 END    $loginhelp
     $serverrow = <<"END";    $forgotpw
       <tr>    $contactblock
        <td  align="left" valign="top">    $newuserlink
         <small><b>$lt{'serv'}:&nbsp;</b></small>    $coursecatalog
        </td>  </div>
        <td align="left" valign="top">  </div>
         <small><tt>&nbsp;$lonhost ($role)</tt></small>  
        </td>  ENDLOGIN
       </tr>      $r->print('</div><div>'."\n");
 END      if ($showmainlogo) {
     if ($loadlim) {          my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);
         $loadrow = <<"END";          $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");
       <tr>      }
        <td align="left" valign="top">  $r->print(<<ENDTOP);
         <small><b>$lt{'load'}:&nbsp;</b></small>  $announcements
        </td>  </div>
        <td align="left" valign="top">  <hr style="clear:both;" />
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>  ENDTOP
        </td>      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
       </tr>      $domainrow = <<"END";
 END        <tr>
     }         <td  align="left" valign="top">
     if ($uloadlim) {          <small><b>$lt{'dom'}:&nbsp;</b></small>
         $userloadrow = <<"END";         </td>
       <tr>         <td  align="left" valign="top">
        <td align="left" valign="top">          <small><tt>&nbsp;$domain</tt></small>
         <small><b>$lt{'userload'}:&nbsp;</b></small>         </td>
        </td>        </tr>
        <td align="left" valign="top">  END
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>      $serverrow = <<"END";
        </td>        <tr>
       </tr>         <td  align="left" valign="top">
 END          <small><b>$lt{'serv'}:&nbsp;</b></small>
     }         </td>
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {         <td align="left" valign="top">
         $versionrow = <<"END";          <small><tt>&nbsp;$lonhost ($role)</tt></small>
       <tr>         </td>
        <td colspan="2" align="left">        </tr>
         <small>$version</small>  END
        </td>      if ($loadlim) {
       </tr>          $loadrow = <<"END";
 END        <tr>
     }         <td align="left" valign="top">
           <small><b>$lt{'load'}:&nbsp;</b></small>
     $r->print(<<ENDDOCUMENT);         </td>
     <div style="float: left;">         <td align="left" valign="top">
      <table border="0" cellspacing="0" cellpadding="0">          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
 $domainrow         </td>
 $serverrow        </tr>
 $loadrow      END
 $userloadrow      }
 $versionrow      if ($uloadlim) {
      </table>          $userloadrow = <<"END";
     </div>        <tr>
     <div style="float: right;">         <td align="left" valign="top">
     $domainlogo          <small><b>$lt{'userload'}:&nbsp;</b></small>
     </div>         </td>
     <br style="clear:both;" />         <td align="left" valign="top">
  </div>          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
          </td>
 $in_frame_js        </tr>
 <script type="text/javascript">  END
 // <![CDATA[      }
 // the if prevents the script error if the browser can not handle this      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
 if ( document.client.uname ) { document.client.uname.focus(); }          $versionrow = <<"END";
 // ]]>        <tr>
 </script>         <td colspan="2" align="left">
 $helpdeskscript          <small>$version</small>
          </td>
 ENDDOCUMENT        </tr>
     my %endargs = ( 'noredirectlink' => 1, );  END
     $r->print(&Apache::loncommon::end_page(\%endargs));      }
     return OK;  
 }      $r->print(<<ENDDOCUMENT);
       <div style="float: left;">
 sub check_loginvia {       <table border="0" cellspacing="0" cellpadding="0">
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;  $domainrow
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {  $serverrow
         return;  $loadrow    
     }  $userloadrow
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);  $versionrow
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};       </table>
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};      </div>
     my $output;      <div style="float: right;">
     if ($loginvia ne '') {      $domainlogo
         my $noredirect;      </div>
         my $ip = &Apache::lonnet::get_requestor_ip();      <br style="clear:both;" />
         if ($ip eq '127.0.0.1') {   </div>
             $noredirect = 1;  
         } else {  $in_frame_js
             if ($loginvia_exempt ne '') {  <script type="text/javascript">
                 my @exempt = split(',',$loginvia_exempt);  // <![CDATA[
                 if (grep(/^\Q$ip\E$/,@exempt)) {  // the if prevents the script error if the browser can not handle this
                     $noredirect = 1;  if ( document.client.uname ) { document.client.uname.focus(); }
                 }  // ]]>
             }  </script>
         }  $helpdeskscript
         unless ($noredirect) {  
             my ($newhost,$path);  ENDDOCUMENT
             if ($loginvia =~ /:/) {      my %endargs = ( 'noredirectlink' => 1, );
                 ($newhost,$path) = split(':',$loginvia);      $r->print(&Apache::loncommon::end_page(\%endargs));
             } else {      return OK;
                 $newhost = $loginvia;  }
             }  
             if ($newhost ne $lonhost) {  sub check_loginvia {
                 if (&Apache::lonnet::hostname($newhost) ne '') {      my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;
                     if ($balcookie) {      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
                         my ($balancer,$cookie) = split(/:/,$balcookie);          return;
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {      }
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
                                     while (my $filename=readdir($dh)) {      my $output;
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {      if ($loginvia ne '') {
                                             my $handle = $1;          my $noredirect;
                                             my %hash =          my $ip = &Apache::lonnet::get_requestor_ip();  
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,          if ($ip eq '127.0.0.1') {
                                                                                      ['request.balancercookie',              $noredirect = 1;
                                                                                       'user.linkedenv']);          } else {
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {              if ($loginvia_exempt ne '') {
                                                 if (unlink("$lonidsdir/$filename")) {                  my @exempt = split(',',$loginvia_exempt);
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&                  if (grep(/^\Q$ip\E$/,@exempt)) {
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&                      $noredirect = 1;
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {                  }
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");              }
                                                     }          }
                                                 }          unless ($noredirect) {
                                             }              my ($newhost,$path);
                                             last;              if ($loginvia =~ /:/) {
                                         }                  ($newhost,$path) = split(':',$loginvia);
                                     }              } else {
                                     closedir($dh);                  $newhost = $loginvia;
                                 }              }
                             }              if ($newhost ne $lonhost) {
                         }                  if (&Apache::lonnet::hostname($newhost) ne '') {
                     }                      if ($balcookie) {
                     $output = &redirect_page($newhost,$path);                          my ($balancer,$cookie) = split(/:/,$balcookie);
                 }                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
             }                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
         }                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
     }                                  if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
     return $output;                                      while (my $filename=readdir($dh)) {
 }                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
                                               my $handle = $1;
 sub redirect_page {                                              my %hash =
     my ($desthost,$path) = @_;                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
     my $hostname = &Apache::lonnet::hostname($desthost);                                                                                       ['request.balancercookie',
     my $protocol = $Apache::lonnet::protocol{$desthost};                                                                                        'user.linkedenv']);
     $protocol = 'http' if ($protocol ne 'https');                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
     unless ($path =~ m{^/}) {                                                  if (unlink("$lonidsdir/$filename")) {
         $path = '/'.$path;                                                      if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
     }                                                          (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
     my $url = $protocol.'://'.$hostname.$path;                                                          (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
     if ($env{'form.firsturl'} ne '') {                                                          unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
         my $querystring;                                                      }
         if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {                                                  }
             $querystring = &uri_escape_utf8($env{'form.firsturl'});                                              }
         } else {                                              last;
             $querystring = &uri_escape($env{'form.firsturl'});                                          }
         }                                      }
         $querystring = &HTML::Entities::encode($querystring,"'");                                      closedir($dh);
         $url .='?firsturl='.$querystring;                                  }
     }                              }
     if (($env{'form.ltoken'}) || ($env{'form.linkkey'} ne '')) {                          }
         my %link_info;                      }
         if ($env{'form.ltoken'}) {                      $output = &redirect_page($newhost,$path);
             $link_info{'ltoken'} = $env{'form.ltoken'};                  }
         } elsif ($env{'form.linkkey'} ne '') {              }
             $link_info{'linkkey'} = $env{'form.linkkey'};          }
         }      }
         my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');      return $output;
         unless (($token eq 'con_lost') || ($token eq 'refused') ||  }
                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {  
             $url .= (($url=~/\?/)?'&amp;':'?') . 'ttoken='.$token;  sub redirect_page {
         }      my ($desthost,$path) = @_;
     }      my $hostname = &Apache::lonnet::hostname($desthost);
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,      my $protocol = $Apache::lonnet::protocol{$desthost};
                                                     {'redirect' => [0,$url],});      $protocol = 'http' if ($protocol ne 'https');
     my $end_page   = &Apache::loncommon::end_page();      unless ($path =~ m{^/}) {
     return $start_page.$end_page;          $path = '/'.$path;
 }      }
       my $url = $protocol.'://'.$hostname.$path;
 sub contactdisplay {      if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,          $url = $protocol.'://'.$hostname.$env{'form.firsturl'};
         $possdoms) = @_;          if (($env{'form.ltoken'}) || ($env{'form.linkprot'} ne '') ||
     my $contactblock;              ($env{'form.linkkey'} ne '')) {
     my $origmail;              my %link_info;
     if (ref($possdoms) eq 'ARRAY') {              if ($env{'form.ltoken'}) {
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {                   %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};                  &Apache::lonnet::tmpdel($env{'form.ltoken'});
         }              } elsif ($env{'form.linkprot'}) {
     }                  $link_info{'linkprot'} = $env{'form.linkprot'};
     my $requestmail =                   if ($env{'form.linkprotuser'}) {
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',                      $link_info{'linkprotuser'} = $env{'form.linkprotuser'};
                                                  $authdomain,$origmail);                  }
     unless ($showhelpdesk eq '0') {              } elsif ($env{'form.linkkey'} ne '') {
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {                  $link_info{'linkkey'} = $env{'form.linkkey'};
             $showhelpdesk = 1;              }
         } else {              my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
             $showhelpdesk = 0;              unless (($token eq 'con_lost') || ($token eq 'refused') ||
         }                      ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
     }                  $url .= '?ltoken='.$token;
     if ($servadm && $showadminmail) {              }
         $contactblock .= $$lt{'servadm'}.':<br />'.          }
                          '<tt>'.$servadm.'</tt><br />';      } else {
     }          my $querystring;
     if ($showhelpdesk) {          if ($env{'form.firsturl'} ne '') {
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';              if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
         my $thisurl = &escape('/adm/login');                  $querystring = &uri_escape_utf8($env{'form.firsturl'});
         $$helpdeskscript = <<"ENDSCRIPT";              } else {
 <script type="text/javascript">                  $querystring = &uri_escape($env{'form.firsturl'});
 // <![CDATA[              }
 function helpdesk() {              $querystring = &HTML::Entities::encode($querystring,"'");
     var possdom = document.client.udom.value;              $querystring = '?firsturl='.$querystring;
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');          }
     if (codedom == '') {          if ($env{'form.ltoken'}) {
         codedom = "$authdomain";              my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
     }              &Apache::lonnet::tmpdel($env{'form.ltoken'});
     var querystr = "origurl=$thisurl&codedom="+codedom;              my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
     document.location.href = "/adm/helpdesk?"+querystr;              unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||
     return;                      ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
 }                  unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {
 // ]]>                      $url = $protocol.'://'.$hostname.'/adm/roles';
 </script>                  }
 ENDSCRIPT                  $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;
     }              }
     return $contactblock;          }
 }          $url .= $querystring;
       }
 sub forgotpwdisplay {      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
     my (%lt) = @_;                                                      {'redirect' => [0,$url],});
     my $prompt_for_resetpw = 1;       my $end_page   = &Apache::loncommon::end_page();
     if ($prompt_for_resetpw) {      return $start_page.$end_page;
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';  }
     }  
     return;  sub contactdisplay {
 }      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
           $possdoms) = @_;
 sub coursecatalog_link {      my $contactblock;
     my ($linkname) = @_;      my $origmail;
     return <<"END";      if (ref($possdoms) eq 'ARRAY') {
       <a href="/adm/coursecatalog">$linkname</a>          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
 END              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
 }          }
       }
 sub newuser_link {      my $requestmail =
     my ($linkname) = @_;          &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
     return '<a href="/adm/createaccount">'.$linkname.'</a>';                                                   $authdomain,$origmail);
 }      unless ($showhelpdesk eq '0') {
           if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
 sub decode_token {              $showhelpdesk = 1;
     my ($info) = @_;          } else {
     my ($firsturl,@rest)=split(/\&/,$info);              $showhelpdesk = 0;
     my %form;          }
     if ($firsturl ne '') {      }
         $form{'firsturl'} = &unescape($firsturl);      if ($servadm && $showadminmail) {
     }          $contactblock .= $$lt{'servadm'}.':<br />'.
     foreach my $item (@rest) {                           '<tt>'.$servadm.'</tt><br />';
         my ($key,$value) = split(/=/,$item);      }
         $form{$key} = &unescape($value);      if ($showhelpdesk) {
     }          $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
     return %form;          my $thisurl = &escape('/adm/login');
 }          $$helpdeskscript = <<"ENDSCRIPT";
   <script type="text/javascript">
 1;  // <![CDATA[
 __END__  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.5  
changed lines
  Added in v.1.199


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