Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.11 and 1.198

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


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