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

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

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


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