Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.9 and 1.196

version 1.158.2.13.2.9, 2023/02/03 23:11:31 version 1.196, 2022/05/25 18:05:56
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{'mailrecip'} = &escape($env{'form.username'}.':'.$env{'form.domain'});                  if (keys(%link_info)) {
                     }                      $link_info{'origurl'} = $env{'form.firsturl'};
                 }                      my $token = &Apache::lonnet::tmpput(\%link_info,$found_server,'link');
             }                      unless (($token eq 'con_lost') || ($token eq 'refused') ||
             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);                              ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
             unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||                          $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'ttoken='.$token;
                     ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {                      }
                 $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;                  }
             }              }
             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {              unless ($found_server eq $lonhost) {
                 my %link_info;                  my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);
                 if ($env{'form.ltoken'}) {                  $hostname = $alias if ($alias ne '');
                     $link_info{'ltoken'} = $env{'form.ltoken'};              }
                 } elsif ($env{'form.linkprot'}) {              my $url = $protocol.'://'.$hostname.$dest;
                     $link_info{'linkprot'} = $env{'form.linkprot'};              my $start_page =
                     foreach my $item ('linkprotuser','linkprotexit') {                  &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.ltoken'}) && ($name eq 'linkprot')) {
         $authdomain=$sessiondata{'domain'};                          $linkprot_for_login = $env{'form.linkprot'};
     } else {                      }
         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});                      $tokentype = 'link';
         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);                  }
     }              }
           }
 # ---------------------------------------------------------- Determine own load      }
     my $loadavg;      if ($tokentype) {
     {          $tokenextras .= ":$tokentype";
  my $loadfile=Apache::File->new('/proc/loadavg');      }
  $loadavg=<$loadfile>;      my $logtoken=Apache::lonnet::reply(
     }         'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,
     $loadavg =~ s/\s.*//g;         $lonhost);
   
     my ($loadpercent,$userloadpercent);  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
     if ($loadlim) {  #    we are in serious trouble
         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);  
     }      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
     if ($uloadlim) {          if ($logtoken eq 'no_such_host') {
         $userloadpercent=&Apache::lonnet::userload();              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
     }          }
           if ($env{'form.ltoken'}) {
     my $firsturl=              &Apache::lonnet::tmpdel($env{'form.ltoken'});
     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});              delete($env{'form.ltoken'});
           }
 # ----------------------------------------------------------- Get announcements          my $spares='';
     my $announcements=&Apache::lonnet::getannounce();          my (@sparehosts,%spareservers);
 # -------------------------------------------------------- Set login parameters          my $sparesref = &Apache::lonnet::this_host_spares($defdom);
           if (ref($sparesref) eq 'HASH') {
     my @hexstr=('0','1','2','3','4','5','6','7',              foreach my $key (keys(%{$sparesref})) {
                 '8','9','a','b','c','d','e','f');                  if (ref($sparesref->{$key}) eq 'ARRAY') {
     my $lkey='';                      my @sorted = sort { &Apache::lonnet::hostname($a) cmp
     for (0..7) {                                          &Apache::lonnet::hostname($b);
         $lkey.=$hexstr[rand(15)];                                        } @{$sparesref->{$key}};
     }                      if (@sorted) {
                           if ($key eq 'primary') {
     my $ukey='';                              unshift(@sparehosts,@sorted);
     for (0..7) {                          } elsif ($key eq 'default') {
         $ukey.=$hexstr[rand(15)];                              push(@sparehosts,@sorted);
     }                          }
                       }
     my $lextkey=hex($lkey);                  }
     if ($lextkey>2147483647) { $lextkey-=4294967296; }              }
           }
     my $uextkey=hex($ukey);          foreach my $hostid (@sparehosts) {
     if ($uextkey>2147483647) { $uextkey-=4294967296; }              next if ($hostid eq $lonhost);
       my $hostname = &Apache::lonnet::hostname($hostid);
 # -------------------------------------------------------- Store away log token      next if (($hostname eq '') || ($spareservers{$hostname}));
     my ($tokenextras,$tokentype,$linkprot_for_login);              $spareservers{$hostname} = 1;
     my @names = ('role','symb','iptoken','ltoken','linkprotuser','linkprotexit','linkprot','linkkey','display');              my $protocol = $Apache::lonnet::protocol{$hostid};
     foreach my $name (@names) {              $protocol = 'http' if ($protocol ne 'https');
         if ($env{'form.'.$name} ne '') {              $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
             if ($name eq 'ltoken') {                  $hostname.
                 my %info = &Apache::lonnet::tmpget($env{'form.'.$name});                  '/adm/login?domain='.$authdomain.'">'.
                 if ($info{'linkprot'}) {                  $hostname.'</a>'.
                     $linkprot_for_login = $info{'linkprot'};                  ' '.&mt('(preferred)').'</span>'.$/;
                     $tokenextras .= '&linkprot='.&escape($info{'linkprot'});          }
                     foreach my $item ('linkprotuser','linkprotexit') {          if ($spares) {
                         if ($info{$item}) {              $spares.= '<br />';
                             $tokenextras .= '&'.$item.'='.&escape($info{$item});          }
                         }          my %all_hostnames = &Apache::lonnet::all_hostnames();
                     }          foreach my $hostid (sort
                     $tokentype = 'link';      {
                     last;   &Apache::lonnet::hostname($a) cmp
                 }      &Apache::lonnet::hostname($b);
             } elsif ($env{'form.display'} && ($env{'form.firsturl'} eq '/adm/email')) {      }
                 if (($env{'form.mailrecip'}) ||      keys(%all_hostnames)) {
                     ($env{'form.username'} =~ /^$match_username$/) && ($env{'form.domain'} =~ /^$match_domain$/)) {              next if ($hostid eq $lonhost);
                     $tokenextras .= '&'.$name.'='.&escape($env{'form.display'});              my $hostname = &Apache::lonnet::hostname($hostid);
                     if ($env{'form.mailrecip'}) {              next if (($hostname eq '') || ($spareservers{$hostname}));
                         $tokenextras .= '&mailrecip='.&escape($env{'form.mailrecip'});              $spareservers{$hostname} = 1;
                     } else {              my $protocol = $Apache::lonnet::protocol{$hostid};
                         $tokenextras .= '&mailrecip='.&escape($env{'form.username'}.':'.$env{'form.domain'});              $protocol = 'http' if ($protocol ne 'https');
                     }              $spares.='<br /><a href="'.$protocol.'://'.
                 }               $hostname.
             } else {               '/adm/login?domain='.$authdomain.'">'.
                 $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});               $hostname.'</a>';
                 if (($name eq 'linkkey') || ($name eq 'linkprot')) {           }
                     if ((($env{'form.retry'}) || ($env{'form.sso'})) &&           $r->print(
                         (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {     '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                         $linkprot_for_login = $env{'form.linkprot'};    .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
                     }    .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
                     $tokentype = 'link';    .&mt('The LearningOnline Network with CAPA')
                 }    .'</title></head>'
             }    .'<body bgcolor="#FFFFFF">'
         }    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     }    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
     if ($tokentype) {    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
         $tokenextras .= ":$tokentype";          if ($spares) {
     }              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
     my $logtoken=Apache::lonnet::reply(                       .'</p>'
        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,                       .$spares);
        $lonhost);          }
           $r->print('</body>'
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname                   .'</html>'
 #    we are in serious trouble          );
           return OK;
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {      }
         if ($logtoken eq 'no_such_host') {  
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');  # ----------------------------------------------- Apparently we are in business
         }      $servadm=~s/\,/\<br \/\>/g;
         if ($env{'form.ltoken'}) {  
             &Apache::lonnet::tmpdel($env{'form.ltoken'});  # ----------------------------------------------------------- Front page design
             delete($env{'form.ltoken'});      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
         }      my $font=&Apache::loncommon::designparm('login.font',$domain);
         my $spares='';      my $link=&Apache::loncommon::designparm('login.link',$domain);
         my (@sparehosts,%spareservers);      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
         if (ref($sparesref) eq 'HASH') {      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
             foreach my $key (keys(%{$sparesref})) {      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
                 if (ref($sparesref->{$key}) eq 'ARRAY') {      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
                                         &Apache::lonnet::hostname($b);      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
                                       } @{$sparesref->{$key}};      my $img=&Apache::loncommon::designparm('login.img',$domain);
                     if (@sorted) {      my $domainlogo=&Apache::loncommon::domainlogo($domain);
                         if ($key eq 'primary') {      my $showbanner = 1;
                             unshift(@sparehosts,@sorted);      my $showmainlogo = 1;
                         } elsif ($key eq 'default') {      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
                             push(@sparehosts,@sorted);          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
                         }      }
                     }      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
                 }          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
             }      }
         }      my $showadminmail;
         foreach my $hostid (@sparehosts) {      my @possdoms = &Apache::lonnet::current_machine_domains();
             next if ($hostid eq $lonhost);      if (grep(/^\Q$domain\E$/,@possdoms)) {
     my $hostname = &Apache::lonnet::hostname($hostid);          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
     next if (($hostname eq '') || ($spareservers{$hostname}));      }
             $spareservers{$hostname} = 1;      my $showcoursecat =
             my $protocol = $Apache::lonnet::protocol{$hostid};          &Apache::loncommon::designparm('login.coursecatalog',$domain);
             $protocol = 'http' if ($protocol ne 'https');      my $shownewuserlink =
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.          &Apache::loncommon::designparm('login.newuser',$domain);
                 $hostname.      my $showhelpdesk =
                 '/adm/login?domain='.$authdomain.'">'.          &Apache::loncommon::designparm('login.helpdesk',$domain);
                 $hostname.'</a>'.      my $now=time;
                 ' '.&mt('(preferred)').'</span>'.$/;      my $js = (<<ENDSCRIPT);
         }  
         if ($spares) {  <script type="text/javascript" language="JavaScript">
             $spares.= '<br />';  // <![CDATA[
         }  function send()
         my %all_hostnames = &Apache::lonnet::all_hostnames();  {
         foreach my $hostid (sort  this.document.server.elements.uname.value
     {  =this.document.client.elements.uname.value;
  &Apache::lonnet::hostname($a) cmp  
     &Apache::lonnet::hostname($b);  this.document.server.elements.udom.value
     }  =this.document.client.elements.udom.value;
     keys(%all_hostnames)) {  
             next if ($hostid eq $lonhost);  uextkey=this.document.client.elements.uextkey.value;
             my $hostname = &Apache::lonnet::hostname($hostid);  lextkey=this.document.client.elements.lextkey.value;
             next if (($hostname eq '') || ($spareservers{$hostname}));  initkeys();
             $spareservers{$hostname} = 1;  
             my $protocol = $Apache::lonnet::protocol{$hostid};  if(this.document.server.action.substr(0,5) === 'http:'){
             $protocol = 'http' if ($protocol ne 'https');      this.document.server.elements.upass0.value
             $spares.='<br /><a href="'.$protocol.'://'.          =getCrypted(this.document.client.elements.upass$now.value);
              $hostname.  } else {
              '/adm/login?domain='.$authdomain.'">'.      this.document.server.elements.upass0.value
              $hostname.'</a>';          =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">'  this.document.client.elements.uname.value='';
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'  this.document.client.elements.upass$now.value='';
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'  
   .&mt('The LearningOnline Network with CAPA')  this.document.server.submit();
   .'</title></head>'  return false;
   .'<body bgcolor="#FFFFFF">'  }
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'  
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'  function enableInput() {
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');      this.document.client.elements.upass$now.removeAttribute("readOnly");
         if ($spares) {      this.document.client.elements.uname.removeAttribute("readOnly");
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      this.document.client.elements.udom.removeAttribute("readOnly");
                      .'</p>'      return;
                      .$spares);  }
         }  
         $r->print('</body>'  // ]]>
                  .'</html>'  </script>
         );  
         return OK;  ENDSCRIPT
     }  
       my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,
 # ----------------------------------------------- Apparently we are in business          $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);
     $servadm=~s/\,/\<br \/\>/g;      %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
       @hosts = &Apache::lonnet::current_machine_ids();
 # ----------------------------------------------------------- Front page design      $lonhost_in_use = $lonhost;
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);      if (@hosts > 1) {
     my $font=&Apache::loncommon::designparm('login.font',$domain);          foreach my $hostid (@hosts) {
     my $link=&Apache::loncommon::designparm('login.link',$domain);              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);                  $lonhost_in_use = $hostid;
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);                  last;
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);              }
     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);      $saml_prefix = $defdom.'.login.saml_';
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);      if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {
     my $img=&Apache::loncommon::designparm('login.img',$domain);          $saml_landing = 1;
     my $domainlogo=&Apache::loncommon::domainlogo($domain);          $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};
     my $showbanner = 1;          $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};
     my $showmainlogo = 1;          $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {          $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);          $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};
     }          $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {      }
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);      if ($saml_landing) {
     }         if ($samlssotext eq '') {
     my $showadminmail;             $samlssotext = 'SSO Login';
     my @possdoms = &Apache::lonnet::current_machine_domains();         }
     if (grep(/^\Q$domain\E$/,@possdoms)) {         if ($samlnonsso eq '') {
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);             $samlnonsso = 'Non-SSO Login';
     }         }
     my $showcoursecat =         $js .= <<"ENDSAMLJS";
         &Apache::loncommon::designparm('login.coursecatalog',$domain);  
     my $shownewuserlink =   <script type="text/javascript">
         &Apache::loncommon::designparm('login.newuser',$domain);  // <![CDATA[
     my $showhelpdesk =  function toggleLClogin() {
         &Apache::loncommon::designparm('login.helpdesk',$domain);      if (document.getElementById('LC_standard_login')) {
     my $now=time;          if (document.getElementById('LC_standard_login').style.display == 'none') {
     my $js = (<<ENDSCRIPT);              document.getElementById('LC_standard_login').style.display = 'inline-block';
               if (document.getElementById('LC_login_text')) {
 <script type="text/javascript" language="JavaScript">                  document.getElementById('LC_login_text').innerHTML = '$samlnonsso';
 // <![CDATA[              }
 function send()              if ( document.client.uname ) { document.client.uname.focus(); }
 {              if (document.getElementById('LC_SSO_login')) {
 this.document.server.elements.uname.value                  document.getElementById('LC_SSO_login').style.display = 'none';
 =this.document.client.elements.uname.value;              }
           } else {
 this.document.server.elements.udom.value              document.getElementById('LC_standard_login').style.display = 'none';
 =this.document.client.elements.udom.value;              if (document.getElementById('LC_login_text')) {
                   document.getElementById('LC_login_text').innerHTML = '$samlssotext';
 uextkey=this.document.client.elements.uextkey.value;              }
 lextkey=this.document.client.elements.lextkey.value;              if (document.getElementById('LC_SSO_login')) {
 initkeys();                  document.getElementById('LC_SSO_login').style.display = 'inline-block';
               }
 this.document.server.elements.upass0.value          }
     =getCrypted(this.document.client.elements.upass$now.value);      }
       return;
 this.document.client.elements.uname.value='';  }
 this.document.client.elements.upass$now.value='';  
   // ]]>
 this.document.server.submit();  </script>
 return false;  
 }  ENDSAMLJS
       }
 function enableInput() {  
     this.document.client.elements.upass$now.removeAttribute("readOnly");  # --------------------------------------------------- Print login screen header
     this.document.client.elements.uname.removeAttribute("readOnly");  
     this.document.client.elements.udom.removeAttribute("readOnly");      my %add_entries = (
     return;         bgcolor      => "$mainbg",
 }         text         => "$font",
          link         => "$link",
 // ]]>         vlink        => "$vlink",
 </script>         alink        => "$alink",
                  onload       => 'javascript:enableInput();',);
 ENDSCRIPT  
       my ($headextra,$headextra_exempt);
     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,      $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip,      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
         $samlwindow);      if ($headextra) {
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);          my $omitextra;
     @hosts = &Apache::lonnet::current_machine_ids();          if ($headextra_exempt ne '') {
     $lonhost_in_use = $lonhost;              my @exempt = split(',',$headextra_exempt);
     if (@hosts > 1) {              my $ip = &Apache::lonnet::get_requestor_ip();
         foreach my $hostid (@hosts) {              if (grep(/^\Q$ip\E$/,@exempt)) {
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {                  $omitextra = 1;
                 $lonhost_in_use = $hostid;              }
                 last;          }
             }          unless ($omitextra) {
         }              my $confname = $defdom.'-domainconfig';
     }              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
     $saml_prefix = $defdom.'.login.saml_';                  my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {                  unless ($extra eq '-1') {
         $saml_landing = 1;                      $js .= "\n".$extra."\n";
         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};                  }
         $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};      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
         $samlwindow = $defaultdomconf{$saml_prefix.'window_'.$lonhost_in_use};         { 'redirect'       => [$expire,'/adm/roles'],
     }   'add_entries' => \%add_entries,
     if ($saml_landing) {   'only_body'   => 1,}));
        if ($samlssotext eq '') {  
            $samlssotext = 'SSO Login';  # ----------------------------------------------------------------------- Texts
        }  
        if ($samlnonsso eq '') {      my %lt=&Apache::lonlocal::texthash(
            $samlnonsso = 'Non-SSO Login';            'un'       => 'Username',
        }            'pw'       => 'Password',
        $js .= <<"ENDSAMLJS";            'dom'      => 'Domain',
             'perc'     => 'percent',
 <script type="text/javascript">            'load'     => 'Server Load',
 // <![CDATA[            'userload' => 'User Load',
 function toggleLClogin() {            'catalog'  => 'Course/Community Catalog',
     if (document.getElementById('LC_standard_login')) {            'log'      => 'Log in',
         if (document.getElementById('LC_standard_login').style.display == 'none') {            'help'     => 'Log-in Help',
             document.getElementById('LC_standard_login').style.display = 'inline-block';            'serv'     => 'Server',
             if (document.getElementById('LC_login_text')) {            'servadm'  => 'Server Administration',
                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';            'helpdesk' => 'Contact Helpdesk',
             }            'forgotpw' => 'Forgot password?',
             if ( document.client.uname ) { document.client.uname.focus(); }            'newuser'  => 'New User?',
             if (document.getElementById('LC_SSO_login')) {            'change'   => 'Change?',
                 document.getElementById('LC_SSO_login').style.display = 'none';         );
             }  # -------------------------------------------------- Change password field name
         } else {  
             document.getElementById('LC_standard_login').style.display = 'none';      my $forgotpw = &forgotpwdisplay(%lt);
             if (document.getElementById('LC_login_text')) {      $forgotpw .= '<br />' if $forgotpw;
                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
             }      if ($loginhelp) {
             if (document.getElementById('LC_SSO_login')) {          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
                 document.getElementById('LC_SSO_login').style.display = 'inline-block';      }
             }  
         }  # ---------------------------------------------------- Serve out DES JavaScript
     }      {
     return;      my $jsh=Apache::File->new($include."/londes.js");
 }      $r->print(<$jsh>);
       }
 // ]]>  # ---------------------------------------------------------- Serve rest of page
 </script>  
       $r->print(
 ENDSAMLJS      '<div class="LC_Box"'
     }     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
   );
 # --------------------------------------------------- Print login screen header  
       $r->print(<<ENDSERVERFORM);
     my %add_entries = (  <form name="server" action="/adm/authenticate" method="post" target="_top">
        bgcolor      => "$mainbg",     <input type="hidden" name="logtoken" value="$logtoken" />
        text         => "$font",     <input type="hidden" name="serverid" value="$lonhost" />
        link         => "$link",     <input type="hidden" name="uname" value="" />
        vlink        => "$vlink",     <input type="hidden" name="upass0" value="" />
        alink        => "$alink",     <input type="hidden" name="udom" value="" />
                onload       => 'javascript:enableInput();',);     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
      <input type="hidden" name="localres" value="$env{'form.localres'}" />
     my ($headextra,$headextra_exempt);    </form>
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};  ENDSERVERFORM
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};      my $coursecatalog;
     if ($headextra) {      if (($showcoursecat eq '') || ($showcoursecat)) {
         my $omitextra;          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
         if ($headextra_exempt ne '') {      }
             my @exempt = split(',',$headextra_exempt);      my $newuserlink;
             my $ip = &Apache::lonnet::get_requestor_ip();      if ($shownewuserlink) {
             if (grep(/^\Q$ip\E$/,@exempt)) {          $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
                 $omitextra = 1;      }
             }      my $logintitle =
         }          '<h2 class="LC_hcell"'
         unless ($omitextra) {         .' style="background:'.$loginbox_header_bgcol.';'
             my $confname = $defdom.'-domainconfig';         .' color:'.$loginbox_header_textcol.'">'
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {         .$lt{'log'}
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));         .'</h2>';
                 unless ($extra eq '-1') {  
                     $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,
                                          $authdomain,\$helpdeskscript,
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,                                         $showhelpdesk,\@possdoms);
        { 'redirect'       => [$expire,'/adm/roles'],   
  'add_entries' => \%add_entries,      my $mobileargs;
  'only_body'   => 1,}));      if ($clientmobile) {
           $mobileargs = 'autocapitalize="off" autocorrect="off"';
 # ----------------------------------------------------------------------- Texts      }
       my $loginform=(<<LFORM);
     my %lt=&Apache::lonlocal::texthash(  <form name="client" action="" onsubmit="return(send())" id="lclogin">
           'un'       => 'Username',    <input type="hidden" name="lextkey" value="$lextkey" />
           'pw'       => 'Password',    <input type="hidden" name="uextkey" value="$uextkey" />
           'dom'      => 'Domain',    <b><label for="uname">$lt{'un'}</label>:</b><br />
           'perc'     => 'percent',    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
           'load'     => 'Server Load',    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
           'userload' => 'User Load',    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
           'catalog'  => 'Course/Community Catalog',    <b><label for="udom">$lt{'dom'}</label>:</b><br />
           'log'      => 'Log in',    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
           'help'     => 'Log-in Help',    <input type="submit" value="$lt{'log'}" />
           'serv'     => 'Server',  </form>
           'servadm'  => 'Server Administration',  LFORM
           'helpdesk' => 'Contact Helpdesk',  
           'forgotpw' => 'Forgot password?',      if ($showbanner) {
           'newuser'  => 'New User?',          my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);
           'change'   => 'Change?',          if ($alttext eq '') {
        );              $alttext = 'The Learning Online Network with CAPA';
 # -------------------------------------------------- Change password field name          }
           $r->print(<<HEADER);
     my $forgotpw = &forgotpwdisplay(%lt);  <!-- The LON-CAPA Header -->
     $forgotpw .= '<br />' if $forgotpw;  <div style="background:$pgbg;margin:0;width:100%;">
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);    <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />
     if ($loginhelp) {  </div>
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';  HEADER
     }      }
   
 # ---------------------------------------------------- Serve out DES JavaScript      my $stdauthformstyle = 'inline-block';
     {      my $ssoauthstyle = 'none';
     my $jsh=Apache::File->new($include."/londes.js");      my $logintype;
     $r->print(<$jsh>);      $r->print('<div style="float:left;margin-top:0;">');
     }      if ($saml_landing) {
 # ---------------------------------------------------------- Serve rest of page          $ssoauthstyle = 'inline-block';
           $stdauthformstyle = 'none';
     $r->print(          $logintype = $samlssotext;
     '<div class="LC_Box"'          my $ssologin = '/adm/sso';
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'          if ($samlssourl  ne '') {
 );              $ssologin = $samlssourl;
           }
     $r->print(<<ENDSERVERFORM);          if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
 <form name="server" action="/adm/authenticate" method="post" target="_top">              my $querystring;
    <input type="hidden" name="logtoken" value="$logtoken" />              if ($env{'form.firsturl'} ne '') {
    <input type="hidden" name="serverid" value="$lonhost" />                  $querystring = 'origurl=';
    <input type="hidden" name="uname" value="" />                  if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
    <input type="hidden" name="upass0" value="" />                      $querystring .= &uri_escape_utf8($env{'form.firsturl'});
    <input type="hidden" name="udom" value="" />                  } else {
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />                      $querystring .= &uri_escape($env{'form.firsturl'});
    <input type="hidden" name="localres" value="$env{'form.localres'}" />                  }
   </form>                  $querystring = &HTML::Entities::encode($querystring,"'");
 ENDSERVERFORM              }
     my $coursecatalog;              if ($env{'form.ltoken'} ne '') {
     if (($showcoursecat eq '') || ($showcoursecat)) {                  $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';                                    &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));
     }              } elsif ($env{'form.linkkey'}) {
     my $newuserlink;                  $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.
     if ($shownewuserlink) {                                    &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';              }
     }              if ($querystring ne '') {
     my $logintitle =                  $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;
         '<h2 class="LC_hcell"'              }
        .' style="background:'.$loginbox_header_bgcol.';'          } elsif ($logtoken ne '') {
        .' color:'.$loginbox_header_textcol.'">'              $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;
        .$lt{'log'}          }
        .'</h2>';          my $ssohref;
           if ($samlssoimg ne '') {
     my $noscript_warning='<noscript><span class="LC_warning"><b>'              $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'">'.
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')                         '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';
                         .'</b></span></noscript>';          } else {
     my $helpdeskscript;              $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,          }
                                        $authdomain,\$helpdeskscript,          if (($env{'form.saml'} eq 'no') ||
                                        $showhelpdesk,\@possdoms);              (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {
               $ssoauthstyle = 'none';
     my $mobileargs;              $stdauthformstyle = 'inline-block';
     if ($clientmobile) {              $logintype = $samlnonsso;
         $mobileargs = 'autocapitalize="off" autocorrect="off"';           }
     }          $r->print(<<ENDSAML);
     my $loginform=(<<LFORM);  <p>
 <form name="client" action="" onsubmit="return(send())" id="lclogin">  Log-in type:
   <input type="hidden" name="lextkey" value="$lextkey" />  <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />
   <input type="hidden" name="uextkey" value="$uextkey" />  <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>
   <b><label for="uname">$lt{'un'}</label>:</b><br />  </p>
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />  <div style="display:$ssoauthstyle" id="LC_SSO_login">
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />  <div class="LC_Box" style="padding-top: 10px;">
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />  $ssohref
   <b><label for="udom">$lt{'dom'}</label>:</b><br />  $noscript_warning
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />  </div>
   <input type="submit" value="$lt{'log'}" />  <div class="LC_Box" style="padding-top: 10px;">
 </form>  $loginhelp
 LFORM  $contactblock
   $coursecatalog
     if ($showbanner) {  </div>
         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);  </div>
         if ($alttext eq '') {  ENDSAML
             $alttext = 'The Learning Online Network with CAPA';      } else {
         }          if ($env{'form.ltoken'}) {
         $r->print(<<HEADER);              &Apache::lonnet::tmpdel($env{'form.ltoken'});
 <!-- The LON-CAPA Header -->              delete($env{'form.ltoken'});
 <div style="background:$pgbg;margin:0;width:100%;">          }
   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />      }
 </div>      my $in_frame_js;
 HEADER      if ($linkprot_for_login) {
     }          my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);
           if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {
     my $stdauthformstyle = 'inline-block';              my $set_target;
     my $ssoauthstyle = 'none';              if ($env{'form.retry'}) {
     my $sso_onclick;                  if ($linkproturi eq $env{'form.firsturl'}) {
     my $logintype;                      $set_target = "    document.server.target = '_self';";
     $r->print('<div style="float:left;margin-top:0;">');                  }
     if ($saml_landing) {              } else {
         $ssoauthstyle = 'inline-block';                  $set_target = <<ENDTARG;
         $stdauthformstyle = 'none';      var linkproturi = '$linkproturi';
         $logintype = $samlssotext;      var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');
         my $ssologin = '/adm/sso';      if (linkproturi == path) {
         if ($samlssourl  ne '') {          document.server.target = '_self';
             $ssologin = $samlssourl;      }
         }  ENDTARG
         my $ssologin_for_js = &js_escape($ssologin);              }
         my $querystr_for_js;              $in_frame_js = <<ENDJS;
         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {  <script type="text/javascript">
             my $querystring;  // <![CDATA[
             if ($env{'form.firsturl'} ne '') {  if ((window.self !== window.top) && (document.server.target != '_self')) {
                 $querystring = 'origurl=';      $set_target
                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {  }
                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});  // ]]>
                 } else {  </script>
                     $querystring .= &uri_escape($env{'form.firsturl'});  ENDJS
                 }          }
                 $querystring = &HTML::Entities::encode($querystring,"'");      }
             }  
             if ($env{'form.ltoken'} ne '') {      $r->print(<<ENDLOGIN);
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.  <div style="display:$stdauthformstyle;" id="LC_standard_login">
                                   &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));  <div class="LC_Box" style="background:$loginbox_bg;">
             } elsif ($env{'form.linkkey'}) {    $logintitle
                 $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.    $loginform
                                   &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));    $noscript_warning
             }  </div>
             if ($querystring ne '') {   
                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;  <div class="LC_Box" style="padding-top: 10px;">
                 $querystr_for_js = &js_escape($querystring);    $loginhelp
             }    $forgotpw
         } elsif ($logtoken ne '') {    $contactblock
             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;    $newuserlink
             $querystr_for_js = &js_escape('logtoken='.$logtoken);    $coursecatalog
         }  </div>
         my $ssohref;  </div>
         if ($samlwindow) {  
             $sso_onclick = <<"ENDJS";  ENDLOGIN
 if (document.getElementById('LC_sso_login_link')) {      $r->print('</div><div>'."\n");
     var ssoelem = document.getElementById('LC_sso_login_link')      if ($showmainlogo) {
     ssoelem.addEventListener('click',samlWinFunction,false);          my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);
     var windows = {};          $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");
     function samlWinFunction(evt) {      }
         evt.preventDefault();  $r->print(<<ENDTOP);
         var url = '$ssologin_for_js';  $announcements
         var name = 'lcssowin';  </div>
         var querystr = '$querystr_for_js';  <hr style="clear:both;" />
         if (querystr) {  ENDTOP
             url += '?'+querystr+'&lcssowin=1';      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
         } else {      $domainrow = <<"END";
             url += '?lcssowin=1';        <tr>
         }         <td  align="left" valign="top">
         if ((typeof windows[name] !== 'undefined') && (!windows[name].closed)) {          <small><b>$lt{'dom'}:&nbsp;</b></small>
             windows[name].close();         </td>
         }         <td  align="left" valign="top">
         windows[name]=window.open(url,name,'width=350,height=600');          <small><tt>&nbsp;$domain</tt></small>
         windows[name].focus();         </td>
         return false;        </tr>
     }  END
 }      $serverrow = <<"END";
 ENDJS        <tr>
         }         <td  align="left" valign="top">
         if ($samlssoimg ne '') {          <small><b>$lt{'serv'}:&nbsp;</b></small>
             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'" id="LC_sso_login_link">'.         </td>
                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';         <td align="left" valign="top">
         } else {          <small><tt>&nbsp;$lonhost ($role)</tt></small>
             $ssohref = '<a href="'.$ssologin.'" id="LC_sso_login_link">'.$samlssotext.'</a>';         </td>
         }        </tr>
         if (($env{'form.saml'} eq 'no') ||  END
             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {      if ($loadlim) {
             $ssoauthstyle = 'none';          $loadrow = <<"END";
             $stdauthformstyle = 'inline-block';        <tr>
             $logintype = $samlnonsso;         <td align="left" valign="top">
         }          <small><b>$lt{'load'}:&nbsp;</b></small>
         $r->print(<<ENDSAML);         </td>
 <p>         <td align="left" valign="top">
 Log-in type:          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
 <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />         </td>
 <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>        </tr>
 </p>  END
 <div style="display:$ssoauthstyle" id="LC_SSO_login">      }
 <div class="LC_Box" style="padding-top: 10px;">      if ($uloadlim) {
 $ssohref          $userloadrow = <<"END";
 $noscript_warning        <tr>
 </div>         <td align="left" valign="top">
 <div class="LC_Box" style="padding-top: 10px;">          <small><b>$lt{'userload'}:&nbsp;</b></small>
 $loginhelp         </td>
 $contactblock         <td align="left" valign="top">
 $coursecatalog          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
 </div>         </td>
 </div>        </tr>
 ENDSAML  END
     } else {      }
         if ($env{'form.ltoken'}) {      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
             &Apache::lonnet::tmpdel($env{'form.ltoken'});          $versionrow = <<"END";
             delete($env{'form.ltoken'});        <tr>
         }         <td colspan="2" align="left">
     }          <small>$version</small>
     my $in_frame_js;         </td>
     if ($linkprot_for_login) {        </tr>
         my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);  END
         if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {      }
             my $set_target;  
             if (($env{'form.retry'}) || ($env{'form.sso'})) {      $r->print(<<ENDDOCUMENT);
                 if ($linkproturi eq $env{'form.firsturl'}) {      <div style="float: left;">
                     $set_target = "    document.server.target = '_self';";       <table border="0" cellspacing="0" cellpadding="0">
                 }  $domainrow
             } else {  $serverrow
                 $set_target = <<ENDTARG;  $loadrow    
     var linkproturi = '$linkproturi';  $userloadrow
     var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');  $versionrow
     if (linkproturi == path) {       </table>
         document.server.target = '_self';      </div>
     }      <div style="float: right;">
 ENDTARG      $domainlogo
             }      </div>
             $in_frame_js = <<ENDJS;      <br style="clear:both;" />
 <script type="text/javascript">   </div>
 // <![CDATA[  
 if ((window.self !== window.top) && (document.server.target != '_self')) {  <script type="text/javascript">
     $set_target  // <![CDATA[
     $sso_onclick  // the if prevents the script error if the browser can not handle this
 }  if ( document.client.uname ) { document.client.uname.focus(); }
 // ]]>  // ]]>
 </script>  </script>
 ENDJS  $helpdeskscript
         }  
     } elsif ($samlwindow) {  ENDDOCUMENT
         $in_frame_js = <<ENDJS;      my %endargs = ( 'noredirectlink' => 1, );
 <script type="text/javascript">      $r->print(&Apache::loncommon::end_page(\%endargs));
 // <![CDATA[      return OK;
 if ((window.self !== window.top) && (document.server.target != '_self')) {  }
     $sso_onclick  
 }  sub check_loginvia {
 // ]]>      my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;
 </script>      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
 ENDJS          return;
     }      }
       my %domconfhash = &Apache::loncommon::get_domainconf($domain);
     $r->print(<<ENDLOGIN);      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
 <div style="display:$stdauthformstyle;" id="LC_standard_login">      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
 <div class="LC_Box" style="background:$loginbox_bg;">      my $output;
   $logintitle      if ($loginvia ne '') {
   $loginform          my $noredirect;
   $noscript_warning          my $ip = &Apache::lonnet::get_requestor_ip();  
 </div>          if ($ip eq '127.0.0.1') {
                 $noredirect = 1;
 <div class="LC_Box" style="padding-top: 10px;">          } else {
   $loginhelp              if ($loginvia_exempt ne '') {
   $forgotpw                  my @exempt = split(',',$loginvia_exempt);
   $contactblock                  if (grep(/^\Q$ip\E$/,@exempt)) {
   $newuserlink                      $noredirect = 1;
   $coursecatalog                  }
 </div>              }
 </div>          }
           unless ($noredirect) {
 ENDLOGIN              my ($newhost,$path);
     $r->print('</div><div>'."\n");              if ($loginvia =~ /:/) {
     if ($showmainlogo) {                  ($newhost,$path) = split(':',$loginvia);
         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain);              } else {
         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");                  $newhost = $loginvia;
     }              }
 $r->print(<<ENDTOP);              if ($newhost ne $lonhost) {
 $announcements                  if (&Apache::lonnet::hostname($newhost) ne '') {
 </div>                      if ($balcookie) {
 <hr style="clear:both;" />                          my ($balancer,$cookie) = split(/:/,$balcookie);
 ENDTOP                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
     $domainrow = <<"END";                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
       <tr>                                  if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
        <td  align="left" valign="top">                                      while (my $filename=readdir($dh)) {
         <small><b>$lt{'dom'}:&nbsp;</b></small>                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
        </td>                                              my $handle = $1;
        <td  align="left" valign="top">                                              my %hash =
         <small><tt>&nbsp;$domain</tt></small>                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
        </td>                                                                                       ['request.balancercookie',
       </tr>                                                                                        'user.linkedenv']);
 END                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
     $serverrow = <<"END";                                                  if (unlink("$lonidsdir/$filename")) {
       <tr>                                                      if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
        <td  align="left" valign="top">                                                          (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
         <small><b>$lt{'serv'}:&nbsp;</b></small>                                                          (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
        </td>                                                          unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
        <td align="left" valign="top">                                                      }
         <small><tt>&nbsp;$lonhost ($role)</tt></small>                                                  }
        </td>                                              }
       </tr>                                              last;
 END                                          }
     if ($loadlim) {                                      }
         $loadrow = <<"END";                                      closedir($dh);
       <tr>                                  }
        <td align="left" valign="top">                              }
         <small><b>$lt{'load'}:&nbsp;</b></small>                          }
        </td>                      }
        <td align="left" valign="top">                      $output = &redirect_page($newhost,$path);
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>                  }
        </td>              }
       </tr>          }
 END      }
     }      return $output;
     if ($uloadlim) {  }
         $userloadrow = <<"END";  
       <tr>  sub redirect_page {
        <td align="left" valign="top">      my ($desthost,$path) = @_;
         <small><b>$lt{'userload'}:&nbsp;</b></small>      my $hostname = &Apache::lonnet::hostname($desthost);
        </td>      my $protocol = $Apache::lonnet::protocol{$desthost};
        <td align="left" valign="top">      $protocol = 'http' if ($protocol ne 'https');
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>      unless ($path =~ m{^/}) {
        </td>          $path = '/'.$path;
       </tr>      }
 END      my $url = $protocol.'://'.$hostname.$path;
     }      if ($env{'form.firsturl'} ne '') {
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {          my $querystring;
         $versionrow = <<"END";          if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
       <tr>              $querystring = &uri_escape_utf8($env{'form.firsturl'});
        <td colspan="2" align="left">          } else {
         <small>$version</small>              $querystring = &uri_escape($env{'form.firsturl'});
        </td>          }
       </tr>          $querystring = &HTML::Entities::encode($querystring,"'");
 END          $url .='?firsturl='.$querystring;
     }      }
       if (($env{'form.ltoken'}) || ($env{'form.linkkey'} ne '')) {
     $r->print(<<ENDDOCUMENT);          my %link_info;
     <div style="float: left;">          if ($env{'form.ltoken'}) {
      <table border="0" cellspacing="0" cellpadding="0">              $link_info{'ltoken'} = $env{'form.ltoken'};
 $domainrow          } elsif ($env{'form.linkkey'} ne '') {
 $serverrow              $link_info{'linkkey'} = $env{'form.linkkey'};
 $loadrow              }
 $userloadrow          my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
 $versionrow          unless (($token eq 'con_lost') || ($token eq 'refused') ||
      </table>                  ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
     </div>              $url .= (($url=~/\?/)?'&amp;':'?') . 'ttoken='.$token;
     <div style="float: right;">          }
     $domainlogo      }
     </div>      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
     <br style="clear:both;" />                                                      {'redirect' => [0,$url],});
  </div>      my $end_page   = &Apache::loncommon::end_page();
       return $start_page.$end_page;
 $in_frame_js  }
 <script type="text/javascript">  
 // <![CDATA[  sub contactdisplay {
 // the if prevents the script error if the browser can not handle this      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
 if ( document.client.uname ) { document.client.uname.focus(); }          $possdoms) = @_;
 // ]]>      my $contactblock;
 </script>      my $origmail;
 $helpdeskscript      if (ref($possdoms) eq 'ARRAY') {
           if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
 ENDDOCUMENT              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
     my %endargs = ( 'noredirectlink' => 1, );          }
     $r->print(&Apache::loncommon::end_page(\%endargs));      }
     return OK;      my $requestmail =
 }          &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                                    $authdomain,$origmail);
 sub check_loginvia {      unless ($showhelpdesk eq '0') {
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;          if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {              $showhelpdesk = 1;
         return;          } else {
     }              $showhelpdesk = 0;
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);          }
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};      }
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};      if ($servadm && $showadminmail) {
     my $output;          $contactblock .= $$lt{'servadm'}.':<br />'.
     if ($loginvia ne '') {                           '<tt>'.$servadm.'</tt><br />';
         my $noredirect;      }
         my $ip = &Apache::lonnet::get_requestor_ip();      if ($showhelpdesk) {
         if ($ip eq '127.0.0.1') {          $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
             $noredirect = 1;          my $thisurl = &escape('/adm/login');
         } else {          $$helpdeskscript = <<"ENDSCRIPT";
             if ($loginvia_exempt ne '') {  <script type="text/javascript">
                 my @exempt = split(',',$loginvia_exempt);  // <![CDATA[
                 if (grep(/^\Q$ip\E$/,@exempt)) {  function helpdesk() {
                     $noredirect = 1;      var possdom = document.client.udom.value;
                 }      var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
             }      if (codedom == '') {
         }          codedom = "$authdomain";
         unless ($noredirect) {      }
             my ($newhost,$path);      var querystr = "origurl=$thisurl&codedom="+codedom;
             if ($loginvia =~ /:/) {      document.location.href = "/adm/helpdesk?"+querystr;
                 ($newhost,$path) = split(':',$loginvia);      return;
             } else {  }
                 $newhost = $loginvia;  // ]]>
             }  </script>
             if ($newhost ne $lonhost) {  ENDSCRIPT
                 if (&Apache::lonnet::hostname($newhost) ne '') {      }
                     if ($balcookie) {      return $contactblock;
                         my ($balancer,$cookie) = split(/:/,$balcookie);  }
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {  
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);  sub forgotpwdisplay {
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {      my (%lt) = @_;
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {      my $prompt_for_resetpw = 1;
                                     while (my $filename=readdir($dh)) {      if ($prompt_for_resetpw) {
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {          return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
                                             my $handle = $1;      }
                                             my %hash =      return;
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,  }
                                                                                      ['request.balancercookie',  
                                                                                       'user.linkedenv']);  sub coursecatalog_link {
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {      my ($linkname) = @_;
                                                 if (unlink("$lonidsdir/$filename")) {      return <<"END";
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&        <a href="/adm/coursecatalog">$linkname</a>
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&  END
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {  }
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");  
                                                     }  sub newuser_link {
                                                 }      my ($linkname) = @_;
                                             }      return '<a href="/adm/createaccount">'.$linkname.'</a>';
                                             last;  }
                                         }  
                                     }  sub decode_token {
                                     closedir($dh);      my ($info) = @_;
                                 }      my ($firsturl,@rest)=split(/\&/,$info);
                             }      my %form;
                         }      if ($firsturl ne '') {
                     }          $form{'firsturl'} = &unescape($firsturl);
                     $output = &redirect_page($newhost,$path);      }
                 }      foreach my $item (@rest) {
             }          my ($key,$value) = split(/=/,$item);
         }          $form{$key} = &unescape($value);
     }      }
     return $output;      return %form;
 }  }
   
 sub redirect_page {  1;
     my ($desthost,$path) = @_;  __END__
     my $hostname = &Apache::lonnet::hostname($desthost);  
     my $protocol = $Apache::lonnet::protocol{$desthost};  
     $protocol = 'http' if ($protocol ne 'https');  
     unless ($path =~ m{^/}) {  
         $path = '/'.$path;  
     }  
     my $url = $protocol.'://'.$hostname.$path;  
     my $args = {};  
     if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {  
         $url = $protocol.'://'.$hostname.$env{'form.firsturl'};  
         if (($env{'form.ltoken'}) || ($env{'form.linkprot'} ne '') ||  
             ($env{'form.linkkey'} ne '')) {  
             my %link_info;  
             if ($env{'form.ltoken'}) {  
                 %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});  
                 &Apache::lonnet::tmpdel($env{'form.ltoken'});  
                 $args->{'only_body'} = 1;  
             } elsif ($env{'form.linkprot'}) {  
                 $link_info{'linkprot'} = $env{'form.linkprot'};  
                 foreach my $item ('linkprotuser','linkprotexit') {  
                     if ($env{'form.'.$item}) {  
                         $link_info{$item} = $env{'form.'.$item};  
                     }  
                 }  
                 $args->{'only_body'} = 1;  
             } elsif ($env{'form.linkkey'} ne '') {  
                 $link_info{'linkkey'} = $env{'form.linkkey'};  
             }  
             my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');  
             unless (($token eq 'con_lost') || ($token eq 'refused') ||  
                     ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {  
                 $url .= '?ltoken='.$token;  
             }  
         }  
     } else {  
         my $querystring;  
         if ($env{'form.firsturl'} ne '') {  
             if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {  
                 $querystring = &uri_escape_utf8($env{'form.firsturl'});  
             } else {  
                 $querystring = &uri_escape($env{'form.firsturl'});  
             }  
             $querystring = &HTML::Entities::encode($querystring,"'");  
             $querystring = '?firsturl='.$querystring;  
         }  
         if ($env{'form.ltoken'}) {  
             my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});  
             &Apache::lonnet::tmpdel($env{'form.ltoken'});  
             my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');  
             unless (($token eq 'con_lost') || ($token eq 'refused') || ($token =~ /^error:/) ||  
                     ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {  
                 unless (($path eq '/adm/roles') || ($path eq '/adm/login')) {  
                     $url = $protocol.'://'.$hostname.'/adm/roles';  
                 }  
                 $querystring .= (($querystring =~/^\?/)?'&amp;':'?') . 'ttoken='.$token;  
             }  
         }  
         $url .= $querystring;  
     }  
     $args->{'redirect'} = [0,$url];  
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,$args);  
     my $end_page   = &Apache::loncommon::end_page();  
     return $start_page.$end_page;  
 }  
   
 sub contactdisplay {  
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,  
         $possdoms) = @_;  
     my $contactblock;  
     my $origmail;  
     if (ref($possdoms) eq 'ARRAY') {  
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {   
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};  
         }  
     }  
     my $requestmail =   
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',  
                                                  $authdomain,$origmail);  
     unless ($showhelpdesk eq '0') {  
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {  
             $showhelpdesk = 1;  
         } else {  
             $showhelpdesk = 0;  
         }  
     }  
     if ($servadm && $showadminmail) {  
         $contactblock .= $$lt{'servadm'}.':<br />'.  
                          '<tt>'.$servadm.'</tt><br />';  
     }  
     if ($showhelpdesk) {  
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';  
         my $thisurl = &escape('/adm/login');  
         $$helpdeskscript = <<"ENDSCRIPT";  
 <script type="text/javascript">  
 // <![CDATA[  
 function helpdesk() {  
     var possdom = document.client.udom.value;  
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');  
     if (codedom == '') {  
         codedom = "$authdomain";  
     }  
     var querystr = "origurl=$thisurl&codedom="+codedom;  
     document.location.href = "/adm/helpdesk?"+querystr;  
     return;  
 }  
 // ]]>  
 </script>  
 ENDSCRIPT  
     }  
     return $contactblock;  
 }  
   
 sub forgotpwdisplay {  
     my (%lt) = @_;  
     my $prompt_for_resetpw = 1;   
     if ($prompt_for_resetpw) {  
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';  
     }  
     return;  
 }  
   
 sub coursecatalog_link {  
     my ($linkname) = @_;  
     return <<"END";  
       <a href="/adm/coursecatalog">$linkname</a>  
 END  
 }  
   
 sub newuser_link {  
     my ($linkname) = @_;  
     return '<a href="/adm/createaccount">'.$linkname.'</a>';  
 }  
   
 sub decode_token {  
     my ($info) = @_;  
     my ($firsturl,@rest)=split(/\&/,$info);  
     my %form;  
     if ($firsturl ne '') {  
         $form{'firsturl'} = &unescape($firsturl);  
     }  
     foreach my $item (@rest) {  
         my ($key,$value) = split(/=/,$item);  
         $form{$key} = &unescape($value);  
     }  
     return %form;  
 }  
   
 1;  
 __END__  

Removed from v.1.158.2.13.2.9  
changed lines
  Added in v.1.196


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