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

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


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