Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.3 and 1.201

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

Removed from v.1.158.2.13.2.3  
changed lines
  Added in v.1.201


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