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

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


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