Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.7 and 1.204

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


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