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

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

Removed from v.1.158.2.13.2.4  
changed lines
  Added in v.1.206


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