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

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


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