Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.6 and 1.197

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

Removed from v.1.158.2.13.2.6  
changed lines
  Added in v.1.197


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