Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.3 and 1.213

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


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