Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.5 and 1.204

version 1.158.2.13.2.5, 2022/06/01 12:21:06 version 1.204, 2022/09/17 23:38:50
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Login Screen  # Login Screen
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # LON-CAPA is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonlogin;  package Apache::lonlogin;
   
 use strict;  use strict;
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use Apache::File ();  use Apache::File ();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonauth();  use Apache::lonauth();
 use Apache::lonlocal;  use Apache::lonlocal;
 use Apache::migrateuser();  use Apache::migrateuser();
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
 use URI::Escape;  use URI::Escape;
 use HTML::Entities();  use HTML::Entities();
 use CGI::Cookie();  use CGI::Cookie();
     
 sub handler {  sub handler {
     my $r = shift;      my $r = shift;
   
     &Apache::loncommon::get_unprocessed_cgi      &Apache::loncommon::get_unprocessed_cgi
  (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},   (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},
       $ENV{'REDIRECT_QUERY_STRING'}),        $ENV{'REDIRECT_QUERY_STRING'}),
  ['interface','username','domain','firsturl','localpath','localres',   ['interface','username','domain','firsturl','localpath','localres',
   'token','role','symb','iptoken','btoken','ltoken','ttoken','linkkey',    'token','role','symb','iptoken','btoken','ltoken','ttoken','linkkey',
           'saml','sso','retry']);            'saml','sso','retry','display']);
   
 # -- check if they are a migrating user  # -- check if they are a migrating user
     if (defined($env{'form.token'})) {      if (defined($env{'form.token'})) {
  return &Apache::migrateuser::handler($r);          return &Apache::migrateuser::handler($r);
     }      }
   
     my $lonhost = $r->dir_config('lonHostID');      my $lonhost = $r->dir_config('lonHostID');
     if ($env{'form.ttoken'}) {      if ($env{'form.ttoken'}) {
         my %info = &Apache::lonnet::tmpget($env{'form.ttoken'});          my %info = &Apache::lonnet::tmpget($env{'form.ttoken'});
         &Apache::lonnet::tmpdel($env{'form.ttoken'});          &Apache::lonnet::tmpdel($env{'form.ttoken'});
         if ($info{'origurl'}) {          if ($info{'origurl'}) {
             $env{'form.firsturl'} = $info{'origurl'};              $env{'form.firsturl'} = $info{'origurl'};
         }          }
         if ($info{'ltoken'}) {          if ($info{'ltoken'}) {
             $env{'form.ltoken'} = $info{'ltoken'};              $env{'form.ltoken'} = $info{'ltoken'};
         } elsif ($info{'linkprot'}) {          } elsif ($info{'linkprot'}) {
             $env{'form.linkprot'} = $info{'linkprot'};              $env{'form.linkprot'} = $info{'linkprot'};
         } elsif ($info{'linkkey'} ne '') {              foreach my $item ('linkprotuser','linkprotexit') {
             $env{'form.linkkey'} = $info{'linkkey'};                  if ($info{$item} ne '') {
         }                      $env{'form.'.$item} = $info{$item};
     } elsif (($env{'form.sso'}) || ($env{'form.retry'})) {                  }
         my $infotoken;              }
         if ($env{'form.sso'}) {          } elsif ($info{'linkkey'} ne '') {
             $infotoken = $env{'form.sso'};              $env{'form.linkkey'} = $info{'linkkey'};
         } else {          }
             $infotoken = $env{'form.retry'};      } elsif (($env{'form.sso'}) || ($env{'form.retry'})) {
         }          my $infotoken;
         my $data = &Apache::lonnet::reply('tmpget:'.$infotoken,$lonhost);          if ($env{'form.sso'}) {
         unless (($data=~/^error/) || ($data eq 'con_lost') ||              $infotoken = $env{'form.sso'};
                 ($data eq 'no_such_host')) {          } else {
             my %info = &decode_token($data);              $infotoken = $env{'form.retry'};
             foreach my $item (keys(%info)) {          }
                 $env{'form.'.$item} = $info{$item};          my $data = &Apache::lonnet::reply('tmpget:'.$infotoken,$lonhost);
             }          unless (($data=~/^error/) || ($data eq 'con_lost') ||
             &Apache::lonnet::tmpdel($infotoken);                  ($data eq 'no_such_host')) {
         }              my %info = &decode_token($data);
     } else {              foreach my $item (keys(%info)) {
         if (!defined($env{'form.firsturl'})) {                  $env{'form.'.$item} = $info{$item};
             &Apache::lonacc::get_posted_cgi($r,['firsturl']);              }
         }              &Apache::lonnet::tmpdel($infotoken);
         if (!defined($env{'form.firsturl'})) {          }
             if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {      } else {
                 $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};          if (!defined($env{'form.firsturl'})) {
             }              &Apache::lonacc::get_posted_cgi($r,['firsturl']);
         }          }
         if (($env{'form.firsturl'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) &&          if (!defined($env{'form.firsturl'})) {
             (!$env{'form.ltoken'}) && (!$env{'form.linkprot'}) && (!$env{'form.linkkey'})) {              if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {
             &Apache::lonacc::get_posted_cgi($r,['linkkey']);                  $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};
         }              }
         if ($env{'form.firsturl'} eq '/adm/logout') {          }
             delete($env{'form.firsturl'});          if (($env{'form.firsturl'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) &&
         }              (!$env{'form.ltoken'}) && (!$env{'form.linkprot'}) && (!$env{'form.linkkey'})) {
     }              &Apache::lonacc::get_posted_cgi($r,['linkkey']);
           }
 # For "public user" - remove any exising "public" cookie, as user really wants to log-in          if ($env{'form.firsturl'} eq '/adm/logout') {
     my ($handle,$lonidsdir,$expirepub,$userdom);              delete($env{'form.firsturl'});
     $lonidsdir=$r->dir_config('lonIDsDir');          }
     unless ($r->header_only) {      }
         $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);  
         if ($handle ne '') {  # For "public user" - remove any exising "public" cookie, as user really wants to log-in
             if ($handle=~/^publicuser\_/) {      my ($handle,$lonidsdir,$expirepub,$userdom);
                 unlink($r->dir_config('lonIDsDir')."/$handle.id");      $lonidsdir=$r->dir_config('lonIDsDir');
                 undef($handle);      unless ($r->header_only) {
                 undef($userdom);          $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);
                 $expirepub = 1;          if ($handle ne '') {
             }              if ($handle=~/^publicuser\_/) {
         }                  unlink($r->dir_config('lonIDsDir')."/$handle.id");
     }                  undef($handle);
                   undef($userdom);
     &Apache::loncommon::no_cache($r);                  $expirepub = 1;
     &Apache::lonlocal::get_language_handle($r);              }
     &Apache::loncommon::content_type($r,'text/html');          }
     if ($expirepub) {      }
         my $c = new CGI::Cookie(-name    => 'lonPubID',  
                                 -value   => '',      &Apache::loncommon::no_cache($r);
                                 -expires => '-10y',);      &Apache::lonlocal::get_language_handle($r);
         $r->header_out('Set-cookie' => $c);      &Apache::loncommon::content_type($r,'text/html');
     } elsif (($handle eq '') && ($userdom ne '')) {      if ($expirepub) {
         my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));          my $c = new CGI::Cookie(-name    => 'lonPubID',
         foreach my $name (keys(%cookies)) {                                  -value   => '',
             next unless ($name =~ /^lon(|S|Link|Pub)ID$/);                                  -expires => '-10y',);
             my $c = new CGI::Cookie(-name    => $name,          $r->header_out('Set-cookie' => $c);
                                     -value   => '',      } elsif (($handle eq '') && ($userdom ne '')) {
                                     -expires => '-10y',);          my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
             $r->headers_out->add('Set-cookie' => $c);          foreach my $name (keys(%cookies)) {
         }              next unless ($name =~ /^lon(|S|Link|Pub)ID$/);
     }              my $c = new CGI::Cookie(-name    => $name,
     $r->send_http_header;                                      -value   => '',
     return OK if $r->header_only;                                      -expires => '-10y',);
               $r->headers_out->add('Set-cookie' => $c);
           }
 # Are we re-routing?      }
     my $londocroot = $r->dir_config('lonDocRoot');       $r->send_http_header;
     if (-e "$londocroot/lon-status/reroute.txt") {      return OK if $r->header_only;
  &Apache::lonauth::reroute($r);  
  return OK;  
     }  # Are we re-routing?
       my $londocroot = $r->dir_config('lonDocRoot');
 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)      if (-e "$londocroot/lon-status/reroute.txt") {
    &Apache::lonauth::reroute($r);
     my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);   return OK;
     if ($found_server) {      }
         my $hostname = &Apache::lonnet::hostname($found_server);  
         if ($hostname ne '') {  # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
             my $protocol = $Apache::lonnet::protocol{$found_server};  
             $protocol = 'http' if ($protocol ne 'https');      my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);
             my $dest = '/adm/roles';      if ($found_server) {
             if ($env{'form.firsturl'} ne '') {          my $hostname = &Apache::lonnet::hostname($found_server);
                 $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');          if ($hostname ne '') {
             }              my $protocol = $Apache::lonnet::protocol{$found_server};
             my %info = (              $protocol = 'http' if ($protocol ne 'https');
                          balcookie => $lonhost.':'.$balancer_cookie,              my $dest = '/adm/roles';
                        );              if ($env{'form.firsturl'} ne '') {
             if ($env{'form.role'}) {                  $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');
                 $info{'role'} = $env{'form.role'};              }
             }              my %info = (
             if ($env{'form.symb'}) {                           balcookie => $lonhost.':'.$balancer_cookie,
                 $info{'symb'} = $env{'form.symb'};                         );
             }              if ($env{'form.role'}) {
             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);                  $info{'role'} = $env{'form.role'};
             unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||              }
                     ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {              if ($env{'form.symb'}) {
                 $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;                  $info{'symb'} = $env{'form.symb'};
             }              }
             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {              if (($env{'form.firsturl'} eq '/adm/email') && ($env{'form.display'} ne '')) {
                 my %link_info;                  if ($env{'form.sso'}) {
                 if ($env{'form.ltoken'}) {                      if ($env{'form.mailrecip'}) {
                     $link_info{'ltoken'} = $env{'form.ltoken'};                          $info{'display'} = &escape($env{'form.display'});
                 } elsif ($env{'form.linkprot'}) {                          $info{'mailrecip'} = &escape($env{'form.mailrecip'});
                     $link_info{'linkprot'} = $env{'form.linkprot'};                      }
                 } elsif ($env{'form.linkkey'} ne '') {                  } else {
                     $link_info{'linkkey'} = $env{'form.linkkey'};                      if (($env{'form.username'}) && ($env{'form.domain'})) {
                 }                          $info{'display'} = &escape($env{'form.display'});
                 if (keys(%link_info)) {                          $info{'mailrecipient'} = &escape($env{'form.username'}.':'.$env{'form.domain'});
                     $link_info{'origurl'} = $env{'form.firsturl'};                      }
                     my $token = &Apache::lonnet::tmpput(\%link_info,$found_server,'link');                  }
                     unless (($token eq 'con_lost') || ($token eq 'refused') ||              }
                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {              my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);
                         $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'ttoken='.$token;              unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||
                     }                      ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {
                 }                  $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;
             }              }
             unless ($found_server eq $lonhost) {              if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
                 my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);                  my %link_info;
                 $hostname = $alias if ($alias ne '');                  if ($env{'form.ltoken'}) {
             }                      $link_info{'ltoken'} = $env{'form.ltoken'};
             my $url = $protocol.'://'.$hostname.$dest;                  } elsif ($env{'form.linkprot'}) {
             my $start_page =                      $link_info{'linkprot'} = $env{'form.linkprot'};
                 &Apache::loncommon::start_page('Switching Server ...',undef,                      foreach my $item ('linkprotuser','linkprotexit') {
                                                {'redirect'       => [0,$url],});                          if ($env{'form.'.$item} ne '') {
             my $end_page   = &Apache::loncommon::end_page();                              $link_info{$item} = $env{'form.'.$item};
             $r->print($start_page.$end_page);                          }
             return OK;                      }
         }                  } elsif ($env{'form.linkkey'} ne '') {
     }                      $link_info{'linkkey'} = $env{'form.linkkey'};
                   }
 #                  if (keys(%link_info)) {
 # Check if a LON-CAPA load balancer sent user here because user's browser sent                      $link_info{'origurl'} = $env{'form.firsturl'};
 # it a balancer cookie for an active session on this server.                      my $token = &Apache::lonnet::tmpput(\%link_info,$found_server,'link');
 #                      unless (($token eq 'con_lost') || ($token eq 'refused') ||
                               ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
     my $balcookie;                          $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'ttoken='.$token;
     if ($env{'form.btoken'}) {                      }
         my %info = &Apache::lonnet::tmpget($env{'form.btoken'});                  }
         $balcookie = $info{'balcookie'};              }
         &Apache::lonnet::tmpdel($env{'form.btoken'});              unless ($found_server eq $lonhost) {
         delete($env{'form.btoken'});                  my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);
     }                  $hostname = $alias if ($alias ne '');
               }
 #              my $url = $protocol.'://'.$hostname.$dest;
 # If browser sent an old cookie for which the session file had been removed              my $start_page =
 # check if configuration for user's domain has a portal URL set.  If so                  &Apache::loncommon::start_page('Switching Server ...',undef,
 # switch user's log-in to the portal.                                                 {'redirect'       => [0,$url],});
 #              my $end_page   = &Apache::loncommon::end_page();
               $r->print($start_page.$end_page);
     if (($handle eq '') && ($userdom ne '')) {              return OK;
         my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);          }
         if ($domdefaults{'portal_def'} =~ /^https?\:/) {      }
             my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,  
                                           {'redirect' => [0,$domdefaults{'portal_def'}],});  #
             my $end_page   = &Apache::loncommon::end_page();  # Check if a LON-CAPA load balancer sent user here because user's browser sent
             $r->print($start_page.$end_page);  # it a balancer cookie for an active session on this server.
             return OK;  #
         }  
     }      my $balcookie;
       if ($env{'form.btoken'}) {
 # -------------------------------- Prevent users from attempting to login twice          my %info = &Apache::lonnet::tmpget($env{'form.btoken'});
     if ($handle ne '') {          $balcookie = $info{'balcookie'};
         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);          &Apache::lonnet::tmpdel($env{'form.btoken'});
  my $start_page =           delete($env{'form.btoken'});
     &Apache::loncommon::start_page('Already logged in');          if (($env{'form.firsturl'} eq '/adm/email') &&
  my $end_page =               (exists($info{'display'})) && (exists($info{'mailrecip'}))) {
     &Apache::loncommon::end_page();              $env{'form.display'} = &unescape($info{'display'});
         my $dest = '/adm/roles';              $env{'form.mailrecip'} = &unescape($info{'mailrecip'});
         if ($env{'form.firsturl'} ne '') {          }
             $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');      }
         }  
         if (($env{'form.ltoken'}) || ($env{'form.linkprot'})) {  #
             my $linkprot;  # If browser sent an old cookie for which the session file had been removed
             if ($env{'form.ltoken'}) {  # check if configuration for user's domain has a portal URL set.  If so
                 my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});  # switch user's log-in to the portal.
                 $linkprot = $info{'linkprot'};  #
                 my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});  
             } else {      if (($handle eq '') && ($userdom ne '')) {
                 $linkprot = $env{'form.linkprot'};          my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);
             }          if ($domdefaults{'portal_def'} =~ /^https?\:/) {
             if ($linkprot) {              my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
                 my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);                                            {'redirect' => [0,$domdefaults{'portal_def'}],});
                 if ($env{'user.linkprotector'}) {              my $end_page   = &Apache::loncommon::end_page();
                     my @protectors = split(/,/,$env{'user.linkprotector'});              $r->print($start_page.$end_page);
                     unless (grep(/^\Q$linkprotector\E$/,@protectors)) {              return OK;
                         push(@protectors,$linkprotector);          }
                         @protectors = sort { $a <=> $b } @protectors;      }
                         &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});  
                     }  # -------------------------------- Prevent users from attempting to login twice
                 } else {      if ($handle ne '') {
                     &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });          &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                 }   my $start_page =
                 if ($env{'user.linkproturi'}) {      &Apache::loncommon::start_page('Already logged in');
                     my @proturis = split(/,/,$env{'user.linkproturi'});   my $end_page =
                     unless (grep(/^\Q$deeplink\E$/,@proturis)) {      &Apache::loncommon::end_page();
                         push(@proturis,$deeplink);          my $dest = '/adm/roles';
                         @proturis = sort @proturis;          if ($env{'form.firsturl'} ne '') {
                         &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});              $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');
                     }          }
                 } else {          if (($env{'form.ltoken'}) || ($env{'form.linkprot'})) {
                     &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});              my ($linkprot,$linkprotuser,$linkprotexit);
                 }              if ($env{'form.ltoken'}) {
             }                  my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});
         } elsif ($env{'form.linkkey'} ne '') {                  $linkprot = $info{'linkprot'};
             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {                  if ($info{'linkprotuser'} ne '') {
                 my $linkkey = $env{'form.linkkey'};                      $linkprotuser = $info{'linkprotuser'};
                 if ($env{'user.deeplinkkey'}) {                  }
                     my @linkkeys = split(/,/,$env{'user.deeplinkkey'});                  if ($info{'linkprotexit'} ne '') {
                     unless (grep(/^\Q$linkkey\E$/,@linkkeys)) {                      $linkprotexit = $info{'linkprotexit'};
                         push(@linkkeys,$linkkey);                  }
                         &Apache::lonnet::appenv({'user.deeplinkkey' => join(',',sort(@linkkeys))});              } else {
                     }                  $linkprot = $env{'form.linkprot'};
                 } else {                  $linkprotuser = $env{'form.linkprotuser'};
                     &Apache::lonnet::appenv({'user.deeplinkkey' => $linkkey});                  $linkprotexit = $env{'form.linkprotexit'};
                 }              }
                 my $deeplink = $env{'form.firsturl'};              if ($linkprot) {
                 if ($env{'user.keyedlinkuri'}) {                  my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);
                     my @keyeduris = split(/,/,$env{'user.keyedlinkuri'});                  if (($deeplink =~ m{^/tiny/$match_domain/\w+$}) &&
                     unless (grep(/^\Q$deeplink\E$/,@keyeduris)) {                      ($linkprotuser ne '') && ($linkprotuser ne $env{'user.name'}.':'.$env{'user.domain'})) {
                         push(@keyeduris,$deeplink);                      my $ip = &Apache::lonnet::get_requestor_ip();
                         &Apache::lonnet::appenv({'user.keyedlinkuri' => join(',',sort(@keyeduris))});                      my %linkprotinfo = (
                     }                                            origurl => $deeplink,
                 } else {                                            linkprot => $linkprot,
                     &Apache::lonnet::appenv({'user.keyedlinkuri' => $deeplink});                                            linkprotuser => $linkprotuser,
                 }                                            linkprotexit => $linkprotexit,
             }                                         );    
         }                      if ($env{'form.ltoken'}) {
  $r->print(                          my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
               $start_page                      }
              .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'                      &Apache::migrateuser::logout($r,$ip,$handle,undef,undef,\%linkprotinfo);
              .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',                      return OK;
               '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'                  }
              .$end_page                  if ($env{'user.linkprotector'}) {
              );                      my @protectors = split(/,/,$env{'user.linkprotector'});
         return OK;                      unless (grep(/^\Q$linkprotector\E$/,@protectors)) {
     }                          push(@protectors,$linkprotector);
                           @protectors = sort { $a <=> $b } @protectors;
 # ---------------------------------------------------- No valid token, continue                          &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});
                       }
 # ---------------------------- Not possible to really login to domain "public"                  } else {
     if ($env{'form.domain'} eq 'public') {                      &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });
  $env{'form.domain'}='';                  }
  $env{'form.username'}='';                  if ($env{'user.linkproturi'}) {
     }                      my @proturis = split(/,/,$env{'user.linkproturi'});
                       unless (grep(/^\Q$deeplink\E$/,@proturis)) {
 # ------ Is this page requested because /adm/migrateuser detected an IP change?                          push(@proturis,$deeplink);
     my %sessiondata;                          @proturis = sort @proturis;
     if ($env{'form.iptoken'}) {                          &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});
         %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});                      }
         unless ($sessiondata{'sessionserver'}) {                  } else {
             my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});                      &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});
             delete($env{'form.iptoken'});                  }
         }              }
     }          } elsif ($env{'form.linkkey'} ne '') {
 # ----------------------------------------------------------- Process Interface              if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
     $env{'form.interface'}=~s/\W//g;                  my $linkkey = $env{'form.linkkey'};
                   if ($env{'user.deeplinkkey'}) {
     (undef,undef,undef,undef,undef,undef,my $clientmobile) =                      my @linkkeys = split(/,/,$env{'user.deeplinkkey'});
         &Apache::loncommon::decode_user_agent($r);                      unless (grep(/^\Q$linkkey\E$/,@linkkeys)) {
                           push(@linkkeys,$linkkey);
     my $iconpath=                           &Apache::lonnet::appenv({'user.deeplinkkey' => join(',',sort(@linkkeys))});
  &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                      }
                   } else {
     my $domain = &Apache::lonnet::default_login_domain();                      &Apache::lonnet::appenv({'user.deeplinkkey' => $linkkey});
     my $defdom = $domain;                  }
     if ($lonhost ne '') {                  my $deeplink = $env{'form.firsturl'};
         unless ($sessiondata{'sessionserver'}) {                  if ($env{'user.keyedlinkuri'}) {
             my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);                      my @keyeduris = split(/,/,$env{'user.keyedlinkuri'});
             if ($redirect) {                      unless (grep(/^\Q$deeplink\E$/,@keyeduris)) {
                 $r->print($redirect);                          push(@keyeduris,$deeplink);
                 return OK;                          &Apache::lonnet::appenv({'user.keyedlinkuri' => join(',',sort(@keyeduris))});
             }                      }
         }                  } else {
     }                      &Apache::lonnet::appenv({'user.keyedlinkuri' => $deeplink});
                   }
     if (($sessiondata{'domain'}) &&              }
         (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {          }
         $domain=$sessiondata{'domain'};          if ($env{'form.ltoken'}) {
     } elsif (($env{'form.domain'}) &&               my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
  (&Apache::lonnet::domain($env{'form.domain'},'description'))) {          }
  $domain=$env{'form.domain'};          if (($env{'form.firsturl'} eq '/adm/email') && ($env{'form.display'})) {
     }              if ($env{'form.mailrecip'}) {
                   if ($env{'form.mailrecip'} eq "$env{'user.name'}:$env{'user.domain'}") {
     my $role    = $r->dir_config('lonRole');                      $dest .= (($dest=~/\?/)?'&amp;':'?') . 'display='.&escape($env{'form.display'}).
     my $loadlim = $r->dir_config('lonLoadLim');                                                             '&amp;mailrecip='.&escape($env{'form.mailrecip'});
     my $uloadlim= $r->dir_config('lonUserLoadLim');                  }
     my $servadm = $r->dir_config('lonAdmEMail');              } elsif (($env{'form.username'} eq $env{'user.name'}) && ($env{'form.domain'} eq $env{'user.domain'})) {
     my $tabdir  = $r->dir_config('lonTabDir');                  $dest .= (($dest=~/\?/)?'&amp;':'?') . 'display='.&escape($env{'form.display'}).
     my $include = $r->dir_config('lonIncludes');                                                         '&amp;mailrecip='.&escape("$env{'user.name'}:$env{'form.domain'}");
     my $expire  = $r->dir_config('lonExpire');              }
     my $version = $r->dir_config('lonVersion');          }
     my $host_name = &Apache::lonnet::hostname($lonhost);   $r->print(
                     $start_page
 # --------------------------------------------- Default values for login fields                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
                        .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',
     my ($authusername,$authdomain);                    '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'
     if ($sessiondata{'username'}) {                   .$end_page
         $authusername=$sessiondata{'username'};                   );
     } else {          return OK;
         $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});      }
         $authusername=($env{'form.username'}?$env{'form.username'}:'');  
     }  # ---------------------------------------------------- No valid token, continue
     if ($sessiondata{'domain'}) {  
         $authdomain=$sessiondata{'domain'};  # ---------------------------- Not possible to really login to domain "public"
     } else {      if ($env{'form.domain'} eq 'public') {
         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});   $env{'form.domain'}='';
         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);   $env{'form.username'}='';
     }      }
   
 # ---------------------------------------------------------- Determine own load  # ------ Is this page requested because /adm/migrateuser detected an IP change?
     my $loadavg;      my %sessiondata;
     {      if ($env{'form.iptoken'}) {
  my $loadfile=Apache::File->new('/proc/loadavg');          %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});
  $loadavg=<$loadfile>;          unless ($sessiondata{'sessionserver'}) {
     }              my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});
     $loadavg =~ s/\s.*//g;              delete($env{'form.iptoken'});
           }
     my ($loadpercent,$userloadpercent);      }
     if ($loadlim) {  # ----------------------------------------------------------- Process Interface
         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);      $env{'form.interface'}=~s/\W//g;
     }  
     if ($uloadlim) {      (undef,undef,undef,undef,undef,undef,my $clientmobile) =
         $userloadpercent=&Apache::lonnet::userload();          &Apache::loncommon::decode_user_agent($r);
     }  
       my $iconpath=
     my $firsturl=   &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});  
       my $domain = &Apache::lonnet::default_login_domain();
 # ----------------------------------------------------------- Get announcements      my $defdom = $domain;
     my $announcements=&Apache::lonnet::getannounce();      if ($lonhost ne '') {
 # -------------------------------------------------------- Set login parameters          unless ($sessiondata{'sessionserver'}) {
               my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);
     my @hexstr=('0','1','2','3','4','5','6','7',              if ($redirect) {
                 '8','9','a','b','c','d','e','f');                  $r->print($redirect);
     my $lkey='';                  return OK;
     for (0..7) {              }
         $lkey.=$hexstr[rand(15)];          }
     }      }
   
     my $ukey='';      if (($sessiondata{'domain'}) &&
     for (0..7) {          (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {
         $ukey.=$hexstr[rand(15)];          $domain=$sessiondata{'domain'};
     }      } elsif (($env{'form.domain'}) &&
    (&Apache::lonnet::domain($env{'form.domain'},'description'))) {
     my $lextkey=hex($lkey);   $domain=$env{'form.domain'};
     if ($lextkey>2147483647) { $lextkey-=4294967296; }      }
   
     my $uextkey=hex($ukey);      my $role    = $r->dir_config('lonRole');
     if ($uextkey>2147483647) { $uextkey-=4294967296; }      my $loadlim = $r->dir_config('lonLoadLim');
       my $uloadlim= $r->dir_config('lonUserLoadLim');
 # -------------------------------------------------------- Store away log token      my $servadm = $r->dir_config('lonAdmEMail');
     my ($tokenextras,$tokentype,$linkprot_for_login);      my $tabdir  = $r->dir_config('lonTabDir');
     my @names = ('role','symb','iptoken','ltoken','linkprot','linkkey');      my $include = $r->dir_config('lonIncludes');
     foreach my $name (@names) {      my $expire  = $r->dir_config('lonExpire');
         if ($env{'form.'.$name} ne '') {      my $version = $r->dir_config('lonVersion');
             if ($name eq 'ltoken') {      my $host_name = &Apache::lonnet::hostname($lonhost);
                 my %info = &Apache::lonnet::tmpget($env{'form.'.$name});  
                 if ($info{'linkprot'}) {  # --------------------------------------------- Default values for login fields
                     $linkprot_for_login = $info{'linkprot'};     
                     $tokenextras .= '&linkprot='.&escape($info{'linkprot'});      my ($authusername,$authdomain);
                     $tokentype = 'link';      if ($sessiondata{'username'}) {
                     last;          $authusername=$sessiondata{'username'};
                 }      } else {
             } else {          $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});
                 $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});          $authusername=($env{'form.username'}?$env{'form.username'}:'');
                 if (($name eq 'linkkey') || ($name eq 'linkprot')) {      }
                     if ((($env{'form.retry'}) || ($env{'form.sso'})) &&      if ($sessiondata{'domain'}) {
                         (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {          $authdomain=$sessiondata{'domain'};
                         $linkprot_for_login = $env{'form.linkprot'};      } else {
                     }          $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});
                     $tokentype = 'link';          $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);
                 }      }
             }  
         }  # ---------------------------------------------------------- Determine own load
     }      my $loadavg;
     if ($tokentype) {      {
         $tokenextras .= ":$tokentype";   my $loadfile=Apache::File->new('/proc/loadavg');
     }   $loadavg=<$loadfile>;
     my $logtoken=Apache::lonnet::reply(      }
        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,      $loadavg =~ s/\s.*//g;
        $lonhost);  
       my ($loadpercent,$userloadpercent);
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname      if ($loadlim) {
 #    we are in serious trouble          $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
       }
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {      if ($uloadlim) {
         if ($logtoken eq 'no_such_host') {          $userloadpercent=&Apache::lonnet::userload();
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');      }
         }  
         if ($env{'form.ltoken'}) {      my $firsturl=
             &Apache::lonnet::tmpdel($env{'form.ltoken'});      ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});
             delete($env{'form.ltoken'});  
         }  # ----------------------------------------------------------- Get announcements
         my $spares='';      my $announcements=&Apache::lonnet::getannounce();
         my (@sparehosts,%spareservers);  # -------------------------------------------------------- Set login parameters
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);  
         if (ref($sparesref) eq 'HASH') {      my @hexstr=('0','1','2','3','4','5','6','7',
             foreach my $key (keys(%{$sparesref})) {                  '8','9','a','b','c','d','e','f');
                 if (ref($sparesref->{$key}) eq 'ARRAY') {      my $lkey='';
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp      for (0..7) {
                                         &Apache::lonnet::hostname($b);          $lkey.=$hexstr[rand(15)];
                                       } @{$sparesref->{$key}};      }
                     if (@sorted) {  
                         if ($key eq 'primary') {      my $ukey='';
                             unshift(@sparehosts,@sorted);      for (0..7) {
                         } elsif ($key eq 'default') {          $ukey.=$hexstr[rand(15)];
                             push(@sparehosts,@sorted);      }
                         }  
                     }      my $lextkey=hex($lkey);
                 }      if ($lextkey>2147483647) { $lextkey-=4294967296; }
             }  
         }      my $uextkey=hex($ukey);
         foreach my $hostid (@sparehosts) {      if ($uextkey>2147483647) { $uextkey-=4294967296; }
             next if ($hostid eq $lonhost);  
     my $hostname = &Apache::lonnet::hostname($hostid);  # -------------------------------------------------------- Store away log token
     next if (($hostname eq '') || ($spareservers{$hostname}));      my ($tokenextras,$tokentype,$linkprot_for_login);
             $spareservers{$hostname} = 1;      my @names = ('role','symb','iptoken','ltoken','linkprotuser','linkprotexit','linkprot','linkkey','display');
             my $protocol = $Apache::lonnet::protocol{$hostid};      foreach my $name (@names) {
             $protocol = 'http' if ($protocol ne 'https');          if ($env{'form.'.$name} ne '') {
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.              if ($name eq 'ltoken') {
                 $hostname.                  my %info = &Apache::lonnet::tmpget($env{'form.'.$name});
                 '/adm/login?domain='.$authdomain.'">'.                  if ($info{'linkprot'}) {
                 $hostname.'</a>'.                      $linkprot_for_login = $info{'linkprot'};
                 ' '.&mt('(preferred)').'</span>'.$/;                      $tokenextras .= '&linkprot='.&escape($info{'linkprot'});
         }                      foreach my $item ('linkprotuser','linkprotexit') {
         if ($spares) {                          if ($info{$item}) {
             $spares.= '<br />';                              $tokenextras .= '&'.$item.'='.&escape($info{$item});
         }                          }
         my %all_hostnames = &Apache::lonnet::all_hostnames();                      }
         foreach my $hostid (sort                      $tokentype = 'link';
     {                      last;
  &Apache::lonnet::hostname($a) cmp                  }
     &Apache::lonnet::hostname($b);              } elsif ($env{'form.display'} && ($env{'form.firsturl'} eq '/adm/email')) {
     }                  if (($env{'form.mailrecip'}) ||
     keys(%all_hostnames)) {                      ($env{'form.username'} =~ /^$match_username$/) && ($env{'form.domain'} =~ /^$match_domain$/)) {
             next if ($hostid eq $lonhost);                      $tokenextras .= '&'.$name.'='.&escape($env{'form.display'});
             my $hostname = &Apache::lonnet::hostname($hostid);                      if ($env{'form.mailrecip'}) {
             next if (($hostname eq '') || ($spareservers{$hostname}));                          $tokenextras .= '&mailrecip='.&escape($env{'form.mailrecip'});
             $spareservers{$hostname} = 1;                      } else {
             my $protocol = $Apache::lonnet::protocol{$hostid};                          $tokenextras .= '&mailrecip='.&escape($env{'form.username'}.':'.$env{'form.domain'});
             $protocol = 'http' if ($protocol ne 'https');                      }
             $spares.='<br /><a href="'.$protocol.'://'.                  }
              $hostname.              } else {
              '/adm/login?domain='.$authdomain.'">'.                  $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});
              $hostname.'</a>';                  if (($name eq 'linkkey') || ($name eq 'linkprot')) {
          }                      if ((($env{'form.retry'}) || ($env{'form.sso'})) &&
          $r->print(                          (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'                          $linkprot_for_login = $env{'form.linkprot'};
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'                      }
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'                      $tokentype = 'link';
   .&mt('The LearningOnline Network with CAPA')                  }
   .'</title></head>'              }
   .'<body bgcolor="#FFFFFF">'          }
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'      }
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'      if ($tokentype) {
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');          $tokenextras .= ":$tokentype";
         if ($spares) {      }
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      my $logtoken=Apache::lonnet::reply(
                      .'</p>'         'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,
                      .$spares);         $lonhost);
         }  
         $r->print('</body>'  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
                  .'</html>'  #    we are in serious trouble
         );  
         return OK;      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
     }          if ($logtoken eq 'no_such_host') {
               &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
 # ----------------------------------------------- Apparently we are in business          }
     $servadm=~s/\,/\<br \/\>/g;          if ($env{'form.ltoken'}) {
               &Apache::lonnet::tmpdel($env{'form.ltoken'});
 # ----------------------------------------------------------- Front page design              delete($env{'form.ltoken'});
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);          }
     my $font=&Apache::loncommon::designparm('login.font',$domain);          my $spares='';
     my $link=&Apache::loncommon::designparm('login.link',$domain);          my (@sparehosts,%spareservers);
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);          my $sparesref = &Apache::lonnet::this_host_spares($defdom);
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);          if (ref($sparesref) eq 'HASH') {
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);              foreach my $key (keys(%{$sparesref})) {
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);                  if (ref($sparesref->{$key}) eq 'ARRAY') {
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);                      my @sorted = sort { &Apache::lonnet::hostname($a) cmp
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);                                          &Apache::lonnet::hostname($b);
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);                                        } @{$sparesref->{$key}};
     my $img=&Apache::loncommon::designparm('login.img',$domain);                      if (@sorted) {
     my $domainlogo=&Apache::loncommon::domainlogo($domain);                          if ($key eq 'primary') {
     my $showbanner = 1;                              unshift(@sparehosts,@sorted);
     my $showmainlogo = 1;                          } elsif ($key eq 'default') {
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {                              push(@sparehosts,@sorted);
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);                          }
     }                      }
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {                  }
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);              }
     }          }
     my $showadminmail;          foreach my $hostid (@sparehosts) {
     my @possdoms = &Apache::lonnet::current_machine_domains();              next if ($hostid eq $lonhost);
     if (grep(/^\Q$domain\E$/,@possdoms)) {      my $hostname = &Apache::lonnet::hostname($hostid);
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);      next if (($hostname eq '') || ($spareservers{$hostname}));
     }              $spareservers{$hostname} = 1;
     my $showcoursecat =              my $protocol = $Apache::lonnet::protocol{$hostid};
         &Apache::loncommon::designparm('login.coursecatalog',$domain);              $protocol = 'http' if ($protocol ne 'https');
     my $shownewuserlink =               $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
         &Apache::loncommon::designparm('login.newuser',$domain);                  $hostname.
     my $showhelpdesk =                  '/adm/login?domain='.$authdomain.'">'.
         &Apache::loncommon::designparm('login.helpdesk',$domain);                  $hostname.'</a>'.
     my $now=time;                  ' '.&mt('(preferred)').'</span>'.$/;
     my $js = (<<ENDSCRIPT);          }
           if ($spares) {
 <script type="text/javascript" language="JavaScript">              $spares.= '<br />';
 // <![CDATA[          }
 function send()          my %all_hostnames = &Apache::lonnet::all_hostnames();
 {          foreach my $hostid (sort
 this.document.server.elements.uname.value      {
 =this.document.client.elements.uname.value;   &Apache::lonnet::hostname($a) cmp
       &Apache::lonnet::hostname($b);
 this.document.server.elements.udom.value      }
 =this.document.client.elements.udom.value;      keys(%all_hostnames)) {
               next if ($hostid eq $lonhost);
 uextkey=this.document.client.elements.uextkey.value;              my $hostname = &Apache::lonnet::hostname($hostid);
 lextkey=this.document.client.elements.lextkey.value;              next if (($hostname eq '') || ($spareservers{$hostname}));
 initkeys();              $spareservers{$hostname} = 1;
               my $protocol = $Apache::lonnet::protocol{$hostid};
 this.document.server.elements.upass0.value              $protocol = 'http' if ($protocol ne 'https');
     =getCrypted(this.document.client.elements.upass$now.value);              $spares.='<br /><a href="'.$protocol.'://'.
                $hostname.
 this.document.client.elements.uname.value='';               '/adm/login?domain='.$authdomain.'">'.
 this.document.client.elements.upass$now.value='';               $hostname.'</a>';
            }
 this.document.server.submit();           $r->print(
 return false;     '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
 }    .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
     .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
 function enableInput() {    .&mt('The LearningOnline Network with CAPA')
     this.document.client.elements.upass$now.removeAttribute("readOnly");    .'</title></head>'
     this.document.client.elements.uname.removeAttribute("readOnly");    .'<body bgcolor="#FFFFFF">'
     this.document.client.elements.udom.removeAttribute("readOnly");    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     return;    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
 }    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
           if ($spares) {
 // ]]>              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
 </script>                       .'</p>'
                        .$spares);
 ENDSCRIPT          }
           $r->print('</body>'
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,                   .'</html>'
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);          );
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);          return OK;
     @hosts = &Apache::lonnet::current_machine_ids();      }
     $lonhost_in_use = $lonhost;  
     if (@hosts > 1) {  # ----------------------------------------------- Apparently we are in business
         foreach my $hostid (@hosts) {      $servadm=~s/\,/\<br \/\>/g;
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {  
                 $lonhost_in_use = $hostid;  # ----------------------------------------------------------- Front page design
                 last;      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
             }      my $font=&Apache::loncommon::designparm('login.font',$domain);
         }      my $link=&Apache::loncommon::designparm('login.link',$domain);
     }      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
     $saml_prefix = $defdom.'.login.saml_';      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
         $saml_landing = 1;      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};      my $img=&Apache::loncommon::designparm('login.img',$domain);
         $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};      my $domainlogo=&Apache::loncommon::domainlogo($domain);
         $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};      my $showbanner = 1;
     }      my $showmainlogo = 1;
     if ($saml_landing) {      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
        if ($samlssotext eq '') {          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
            $samlssotext = 'SSO Login';      }
        }      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
        if ($samlnonsso eq '') {          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
            $samlnonsso = 'Non-SSO Login';      }
        }      my $showadminmail;
        $js .= <<"ENDSAMLJS";      my @possdoms = &Apache::lonnet::current_machine_domains();
       if (grep(/^\Q$domain\E$/,@possdoms)) {
 <script type="text/javascript">          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 // <![CDATA[      }
 function toggleLClogin() {      my $showcoursecat =
     if (document.getElementById('LC_standard_login')) {          &Apache::loncommon::designparm('login.coursecatalog',$domain);
         if (document.getElementById('LC_standard_login').style.display == 'none') {      my $shownewuserlink =
             document.getElementById('LC_standard_login').style.display = 'inline-block';          &Apache::loncommon::designparm('login.newuser',$domain);
             if (document.getElementById('LC_login_text')) {      my $showhelpdesk =
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';          &Apache::loncommon::designparm('login.helpdesk',$domain);
             }      my $now=time;
             if ( document.client.uname ) { document.client.uname.focus(); }      my $js = (<<ENDSCRIPT);
             if (document.getElementById('LC_SSO_login')) {  
                 document.getElementById('LC_SSO_login').style.display = 'none';  <script type="text/javascript" language="JavaScript">
             }  // <![CDATA[
         } else {  function send()
             document.getElementById('LC_standard_login').style.display = 'none';  {
             if (document.getElementById('LC_login_text')) {  this.document.server.elements.uname.value
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';  =this.document.client.elements.uname.value;
             }  
             if (document.getElementById('LC_SSO_login')) {  this.document.server.elements.udom.value
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';  =this.document.client.elements.udom.value;
             }  
         }  uextkey=this.document.client.elements.uextkey.value;
     }  lextkey=this.document.client.elements.lextkey.value;
     return;  initkeys();
 }  
   if(this.document.server.action.substr(0,5) === 'http:'){
 // ]]>      this.document.server.elements.upass0.value
 </script>          =getCrypted(this.document.client.elements.upass$now.value);
   } else {
 ENDSAMLJS      this.document.server.elements.upass0.value
     }          =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') {
                       if ($env{'form.'.$item}) {
                           $link_info{$item} = $env{'form.'.$item};
                       }
                   }
                   $args->{'only_body'} = 1;
               } elsif ($env{'form.linkkey'} ne '') {
                   $link_info{'linkkey'} = $env{'form.linkkey'};
               }
               my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
               unless (($token eq 'con_lost') || ($token eq 'refused') ||
                       ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                   $url .= '?ltoken='.$token;
               }
           }
       } else {
           my $querystring;
           if ($env{'form.firsturl'} ne '') {
               if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
                   $querystring = &uri_escape_utf8($env{'form.firsturl'});
               } else {
                   $querystring = &uri_escape($env{'form.firsturl'});
               }
               $querystring = &HTML::Entities::encode($querystring,"'");
               $querystring = '?firsturl='.$querystring;
           }
           if ($env{'form.ltoken'}) {
               my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
               &Apache::lonnet::tmpdel($env{'form.ltoken'});
               my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
               unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||
                       ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
                   unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {
                       $url = $protocol.'://'.$hostname.'/adm/roles';
                   }
                   $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;
               }
           }
           $url .= $querystring;
       }
       $args->{'redirect'} = [0,$url];
       my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,$args);
       my $end_page   = &Apache::loncommon::end_page();
       return $start_page.$end_page;
   }
   
   sub contactdisplay {
       my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
           $possdoms) = @_;
       my $contactblock;
       my $origmail;
       if (ref($possdoms) eq 'ARRAY') {
           if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
               $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
           }
       }
       my $requestmail =
           &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                                    $authdomain,$origmail);
       unless ($showhelpdesk eq '0') {
           if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
               $showhelpdesk = 1;
           } else {
               $showhelpdesk = 0;
           }
       }
       if ($servadm && $showadminmail) {
           $contactblock .= $$lt{'servadm'}.':<br />'.
                            '<tt>'.$servadm.'</tt><br />';
       }
       if ($showhelpdesk) {
           $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
           my $thisurl = &escape('/adm/login');
           $$helpdeskscript = <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function helpdesk() {
       var possdom = document.client.udom.value;
       var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
       if (codedom == '') {
           codedom = "$authdomain";
       }
       var querystr = "origurl=$thisurl&codedom="+codedom;
       document.location.href = "/adm/helpdesk?"+querystr;
       return;
   }
   // ]]>
   </script>
   ENDSCRIPT
       }
       return $contactblock;
   }
   
   sub forgotpwdisplay {
       my (%lt) = @_;
       my $prompt_for_resetpw = 1;
       if ($prompt_for_resetpw) {
           return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
       }
       return;
   }
   
   sub coursecatalog_link {
       my ($linkname) = @_;
       return <<"END";
         <a href="/adm/coursecatalog">$linkname</a>
   END
   }
   
   sub newuser_link {
       my ($linkname) = @_;
       return '<a href="/adm/createaccount">'.$linkname.'</a>';
   }
   
   sub decode_token {
       my ($info) = @_;
       my ($firsturl,@rest)=split(/\&/,$info);
       my %form;
       if ($firsturl ne '') {
           $form{'firsturl'} = &unescape($firsturl);
       }
       foreach my $item (@rest) {
           my ($key,$value) = split(/=/,$item);
           $form{$key} = &unescape($value);
       }
       return %form;
   }
   
   1;
   __END__

Removed from v.1.158.2.13.2.5  
changed lines
  Added in v.1.204


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