Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.13.2.6 and 1.174

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


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