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

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

Removed from v.1.158.2.13.2.8  
changed lines
  Added in v.1.198


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