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

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


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