Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.11 and 1.200

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


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