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

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

Removed from v.1.158.2.13.2.11  
changed lines
  Added in v.1.195


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