Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.14 and 1.203

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

Removed from v.1.158.2.14  
changed lines
  Added in v.1.203


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