Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.6 and 1.205

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

Removed from v.1.158.2.13.2.6  
changed lines
  Added in v.1.205


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