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

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

Removed from v.1.158.2.13.2.6  
changed lines
  Added in v.1.188


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