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

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

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


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