File:  [LON-CAPA] / loncom / auth / lonlogin.pm
Revision 1.196: download - view: text, annotated - select for diffs
Wed May 25 18:05:56 2022 UTC (2 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6907
  Stop deep-linked items escaping iframe context, if LTI link protection in
  effect, but user needs to authenticate.

    1: # The LearningOnline Network
    2: # Login Screen
    3: #
    4: # $Id: lonlogin.pm,v 1.196 2022/05/25 18:05:56 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonlogin;
   30: 
   31: use strict;
   32: use Apache::Constants qw(:common);
   33: use Apache::File ();
   34: use Apache::lonnet;
   35: use Apache::loncommon();
   36: use Apache::lonauth();
   37: use Apache::lonlocal;
   38: use Apache::migrateuser();
   39: use lib '/home/httpd/lib/perl/';
   40: use LONCAPA qw(:DEFAULT :match);
   41: use URI::Escape;
   42: use HTML::Entities();
   43: use CGI::Cookie();
   44:  
   45: sub handler {
   46:     my $r = shift;
   47: 
   48:     &Apache::loncommon::get_unprocessed_cgi
   49: 	(join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},
   50: 	      $ENV{'REDIRECT_QUERY_STRING'}),
   51: 	 ['interface','username','domain','firsturl','localpath','localres',
   52: 	  'token','role','symb','iptoken','btoken','ltoken','ttoken','linkkey',
   53:           'saml','sso','retry']); 
   54: 
   55: # -- check if they are a migrating user
   56:     if (defined($env{'form.token'})) {
   57:         return &Apache::migrateuser::handler($r);
   58:     }
   59: 
   60:     my $lonhost = $r->dir_config('lonHostID');
   61:     if ($env{'form.ttoken'}) {
   62:         my %info = &Apache::lonnet::tmpget($env{'form.ttoken'});
   63:         &Apache::lonnet::tmpdel($env{'form.ttoken'});
   64:         if ($info{'origurl'}) {
   65:             $env{'form.firsturl'} = $info{'origurl'};
   66:         }
   67:         if ($info{'ltoken'}) {
   68:             $env{'form.ltoken'} = $info{'ltoken'};
   69:         } elsif ($info{'linkprot'}) {
   70:             $env{'form.linkprot'} = $info{'linkprot'};
   71:         } elsif ($info{'linkkey'} ne '') {
   72:             $env{'form.linkkey'} = $info{'linkkey'};
   73:         }
   74:     } elsif (($env{'form.sso'}) || ($env{'form.retry'})) {
   75:         my $infotoken;
   76:         if ($env{'form.sso'}) {
   77:             $infotoken = $env{'form.sso'};
   78:         } else {
   79:             $infotoken = $env{'form.retry'};
   80:         }
   81:         my $data = &Apache::lonnet::reply('tmpget:'.$infotoken,$lonhost);
   82:         unless (($data=~/^error/) || ($data eq 'con_lost') ||
   83:                 ($data eq 'no_such_host')) {
   84:             my %info = &decode_token($data);
   85:             foreach my $item (keys(%info)) {
   86:                 $env{'form.'.$item} = $info{$item};
   87:             }
   88:             &Apache::lonnet::tmpdel($infotoken);
   89:         }
   90:     } else {
   91:         if (!defined($env{'form.firsturl'})) {
   92:             &Apache::lonacc::get_posted_cgi($r,['firsturl']);
   93:         }
   94:         if (!defined($env{'form.firsturl'})) {
   95:             if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {
   96:                 $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};
   97:             }
   98:         }
   99:         if (($env{'form.firsturl'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) &&
  100:             (!$env{'form.ltoken'}) && (!$env{'form.linkprot'}) && (!$env{'form.linkkey'})) {
  101:             &Apache::lonacc::get_posted_cgi($r,['linkkey']);
  102:         }
  103:         if ($env{'form.firsturl'} eq '/adm/logout') {
  104:             delete($env{'form.firsturl'});
  105:         }
  106:     }
  107: 
  108: # For "public user" - remove any exising "public" cookie, as user really wants to log-in
  109:     my ($handle,$lonidsdir,$expirepub,$userdom);
  110:     $lonidsdir=$r->dir_config('lonIDsDir');
  111:     unless ($r->header_only) {
  112:         $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);
  113:         if ($handle ne '') {
  114:             if ($handle=~/^publicuser\_/) {
  115:                 unlink($r->dir_config('lonIDsDir')."/$handle.id");
  116:                 undef($handle);
  117:                 undef($userdom);
  118:                 $expirepub = 1;
  119:             }
  120:         }
  121:     }
  122: 
  123:     &Apache::loncommon::no_cache($r);
  124:     &Apache::lonlocal::get_language_handle($r);
  125:     &Apache::loncommon::content_type($r,'text/html');
  126:     if ($expirepub) {
  127:         my $c = new CGI::Cookie(-name    => 'lonPubID',
  128:                                 -value   => '',
  129:                                 -expires => '-10y',);
  130:         $r->header_out('Set-cookie' => $c);
  131:     } elsif (($handle eq '') && ($userdom ne '')) {
  132:         my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  133:         foreach my $name (keys(%cookies)) {
  134:             next unless ($name =~ /^lon(|S|Link|Pub)ID$/);
  135:             my $c = new CGI::Cookie(-name    => $name,
  136:                                     -value   => '',
  137:                                     -expires => '-10y',);
  138:             $r->headers_out->add('Set-cookie' => $c);
  139:         }
  140:     }
  141:     $r->send_http_header;
  142:     return OK if $r->header_only;
  143: 
  144: 
  145: # Are we re-routing?
  146:     my $londocroot = $r->dir_config('lonDocRoot'); 
  147:     if (-e "$londocroot/lon-status/reroute.txt") {
  148: 	&Apache::lonauth::reroute($r);
  149: 	return OK;
  150:     }
  151: 
  152: # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
  153: 
  154:     my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);
  155:     if ($found_server) {
  156:         my $hostname = &Apache::lonnet::hostname($found_server);
  157:         if ($hostname ne '') {
  158:             my $protocol = $Apache::lonnet::protocol{$found_server};
  159:             $protocol = 'http' if ($protocol ne 'https');
  160:             my $dest = '/adm/roles';
  161:             if ($env{'form.firsturl'} ne '') {
  162:                 $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');
  163:             }
  164:             my %info = (
  165:                          balcookie => $lonhost.':'.$balancer_cookie,
  166:                        );
  167:             if ($env{'form.role'}) {
  168:                 $info{'role'} = $env{'form.role'};
  169:             }
  170:             if ($env{'form.symb'}) {
  171:                 $info{'symb'} = $env{'form.symb'};
  172:             }
  173:             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);
  174:             unless (($balancer_token eq 'con_lost') || ($balancer_token eq 'refused') ||
  175:                     ($balancer_token eq 'unknown_cmd') || ($balancer_token eq 'no_such_host')) {
  176:                 $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'btoken='.$balancer_token;
  177:             }
  178:             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  179:                 my %link_info;
  180:                 if ($env{'form.ltoken'}) {
  181:                     $link_info{'ltoken'} = $env{'form.ltoken'};
  182:                 } elsif ($env{'form.linkprot'}) {
  183:                     $link_info{'linkprot'} = $env{'form.linkprot'};
  184:                 } elsif ($env{'form.linkkey'} ne '') {
  185:                     $link_info{'linkkey'} = $env{'form.linkkey'};
  186:                 }
  187:                 if (keys(%link_info)) {
  188:                     $link_info{'origurl'} = $env{'form.firsturl'};
  189:                     my $token = &Apache::lonnet::tmpput(\%link_info,$found_server,'link');
  190:                     unless (($token eq 'con_lost') || ($token eq 'refused') ||
  191:                             ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
  192:                         $dest .=  (($dest=~/\?/)?'&amp;':'?') . 'ttoken='.$token;
  193:                     }
  194:                 }
  195:             }
  196:             unless ($found_server eq $lonhost) {
  197:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$found_server);
  198:                 $hostname = $alias if ($alias ne '');
  199:             }
  200:             my $url = $protocol.'://'.$hostname.$dest;
  201:             my $start_page =
  202:                 &Apache::loncommon::start_page('Switching Server ...',undef,
  203:                                                {'redirect'       => [0,$url],});
  204:             my $end_page   = &Apache::loncommon::end_page();
  205:             $r->print($start_page.$end_page);
  206:             return OK;
  207:         }
  208:     }
  209: 
  210: #
  211: # Check if a LON-CAPA load balancer sent user here because user's browser sent
  212: # it a balancer cookie for an active session on this server.
  213: #
  214: 
  215:     my $balcookie;
  216:     if ($env{'form.btoken'}) {
  217:         my %info = &Apache::lonnet::tmpget($env{'form.btoken'});
  218:         $balcookie = $info{'balcookie'};
  219:         &Apache::lonnet::tmpdel($env{'form.btoken'});
  220:         delete($env{'form.btoken'});
  221:     }
  222: 
  223: #
  224: # If browser sent an old cookie for which the session file had been removed
  225: # check if configuration for user's domain has a portal URL set.  If so
  226: # switch user's log-in to the portal.
  227: #
  228: 
  229:     if (($handle eq '') && ($userdom ne '')) {
  230:         my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);
  231:         if ($domdefaults{'portal_def'} =~ /^https?\:/) {
  232:             my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
  233:                                           {'redirect' => [0,$domdefaults{'portal_def'}],});
  234:             my $end_page   = &Apache::loncommon::end_page();
  235:             $r->print($start_page.$end_page);
  236:             return OK;
  237:         }
  238:     }
  239: 
  240: # -------------------------------- Prevent users from attempting to login twice
  241:     if ($handle ne '') {
  242:         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
  243: 	my $start_page = 
  244: 	    &Apache::loncommon::start_page('Already logged in');
  245: 	my $end_page = 
  246: 	    &Apache::loncommon::end_page();
  247:         my $dest = '/adm/roles';
  248:         if ($env{'form.firsturl'} ne '') {
  249:             $dest = &HTML::Entities::encode($env{'form.firsturl'},'\'"<>&');
  250:         }
  251:         if (($env{'form.ltoken'}) || ($env{'form.linkprot'})) {
  252:             my $linkprot;
  253:             if ($env{'form.ltoken'}) {
  254:                 my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});
  255:                 $linkprot = $info{'linkprot'};
  256:                 my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
  257:             } else {
  258:                 $linkprot = $env{'form.linkprot'};
  259:             }
  260:             if ($linkprot) {
  261:                 my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);
  262:                 if ($env{'user.linkprotector'}) {
  263:                     my @protectors = split(/,/,$env{'user.linkprotector'});
  264:                     unless (grep(/^\Q$linkprotector\E$/,@protectors)) {
  265:                         push(@protectors,$linkprotector);
  266:                         @protectors = sort { $a <=> $b } @protectors;
  267:                         &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});
  268:                     }
  269:                 } else {
  270:                     &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });
  271:                 }
  272:                 if ($env{'user.linkproturi'}) {
  273:                     my @proturis = split(/,/,$env{'user.linkproturi'});
  274:                     unless (grep(/^\Q$deeplink\E$/,@proturis)) {
  275:                         push(@proturis,$deeplink);
  276:                         @proturis = sort @proturis;
  277:                         &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});
  278:                     }
  279:                 } else {
  280:                     &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});
  281:                 }
  282:             }
  283:         } elsif ($env{'form.linkkey'} ne '') {
  284:             if ($env{'form.firsturl'} =~ m{^/tiny/$match_domain/\w+$}) {
  285:                 my $linkkey = $env{'form.linkkey'};
  286:                 if ($env{'user.deeplinkkey'}) {
  287:                     my @linkkeys = split(/,/,$env{'user.deeplinkkey'});
  288:                     unless (grep(/^\Q$linkkey\E$/,@linkkeys)) {
  289:                         push(@linkkeys,$linkkey);
  290:                         &Apache::lonnet::appenv({'user.deeplinkkey' => join(',',sort(@linkkeys))});
  291:                     }
  292:                 } else {
  293:                     &Apache::lonnet::appenv({'user.deeplinkkey' => $linkkey});
  294:                 }
  295:                 my $deeplink = $env{'form.firsturl'}; 
  296:                 if ($env{'user.keyedlinkuri'}) {
  297:                     my @keyeduris = split(/,/,$env{'user.keyedlinkuri'});
  298:                     unless (grep(/^\Q$deeplink\E$/,@keyeduris)) {
  299:                         push(@keyeduris,$deeplink);
  300:                         &Apache::lonnet::appenv({'user.keyedlinkuri' => join(',',sort(@keyeduris))});
  301:                     }
  302:                 } else {
  303:                     &Apache::lonnet::appenv({'user.keyedlinkuri' => $deeplink});
  304:                 }
  305:             }
  306:         }
  307: 	$r->print(
  308:                   $start_page
  309:                  .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
  310:                  .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',
  311:                   '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'
  312:                  .$end_page
  313:                  );
  314:         return OK;
  315:     }
  316: 
  317: # ---------------------------------------------------- No valid token, continue
  318: 
  319: # ---------------------------- Not possible to really login to domain "public"
  320:     if ($env{'form.domain'} eq 'public') {
  321: 	$env{'form.domain'}='';
  322: 	$env{'form.username'}='';
  323:     }
  324: 
  325: # ------ Is this page requested because /adm/migrateuser detected an IP change?
  326:     my %sessiondata;
  327:     if ($env{'form.iptoken'}) {
  328:         %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});
  329:         unless ($sessiondata{'sessionserver'}) {
  330:             my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});
  331:             delete($env{'form.iptoken'});
  332:         }
  333:     }
  334: # ----------------------------------------------------------- Process Interface
  335:     $env{'form.interface'}=~s/\W//g;
  336: 
  337:     (undef,undef,undef,undef,undef,undef,my $clientmobile) =
  338:         &Apache::loncommon::decode_user_agent($r);
  339: 
  340:     my $iconpath= 
  341: 	&Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
  342: 
  343:     my $domain = &Apache::lonnet::default_login_domain();
  344:     my $defdom = $domain;
  345:     if ($lonhost ne '') {
  346:         unless ($sessiondata{'sessionserver'}) {
  347:             my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);
  348:             if ($redirect) {
  349:                 $r->print($redirect);
  350:                 return OK;
  351:             }
  352:         }
  353:     }
  354: 
  355:     if (($sessiondata{'domain'}) &&
  356:         (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {
  357:         $domain=$sessiondata{'domain'};
  358:     } elsif (($env{'form.domain'}) && 
  359: 	(&Apache::lonnet::domain($env{'form.domain'},'description'))) {
  360: 	$domain=$env{'form.domain'};
  361:     }
  362: 
  363:     my $role    = $r->dir_config('lonRole');
  364:     my $loadlim = $r->dir_config('lonLoadLim');
  365:     my $uloadlim= $r->dir_config('lonUserLoadLim');
  366:     my $servadm = $r->dir_config('lonAdmEMail');
  367:     my $tabdir  = $r->dir_config('lonTabDir');
  368:     my $include = $r->dir_config('lonIncludes');
  369:     my $expire  = $r->dir_config('lonExpire');
  370:     my $version = $r->dir_config('lonVersion');
  371:     my $host_name = &Apache::lonnet::hostname($lonhost);
  372: 
  373: # --------------------------------------------- Default values for login fields
  374:     
  375:     my ($authusername,$authdomain);
  376:     if ($sessiondata{'username'}) {
  377:         $authusername=$sessiondata{'username'};
  378:     } else {
  379:         $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});
  380:         $authusername=($env{'form.username'}?$env{'form.username'}:'');
  381:     }
  382:     if ($sessiondata{'domain'}) {
  383:         $authdomain=$sessiondata{'domain'};
  384:     } else {
  385:         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});
  386:         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);
  387:     }
  388: 
  389: # ---------------------------------------------------------- Determine own load
  390:     my $loadavg;
  391:     {
  392: 	my $loadfile=Apache::File->new('/proc/loadavg');
  393: 	$loadavg=<$loadfile>;
  394:     }
  395:     $loadavg =~ s/\s.*//g;
  396: 
  397:     my ($loadpercent,$userloadpercent);
  398:     if ($loadlim) {
  399:         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
  400:     }
  401:     if ($uloadlim) {
  402:         $userloadpercent=&Apache::lonnet::userload();
  403:     }
  404: 
  405:     my $firsturl=
  406:     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});
  407: 
  408: # ----------------------------------------------------------- Get announcements
  409:     my $announcements=&Apache::lonnet::getannounce();
  410: # -------------------------------------------------------- Set login parameters
  411: 
  412:     my @hexstr=('0','1','2','3','4','5','6','7',
  413:                 '8','9','a','b','c','d','e','f');
  414:     my $lkey='';
  415:     for (0..7) {
  416:         $lkey.=$hexstr[rand(15)];
  417:     }
  418: 
  419:     my $ukey='';
  420:     for (0..7) {
  421:         $ukey.=$hexstr[rand(15)];
  422:     }
  423: 
  424:     my $lextkey=hex($lkey);
  425:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
  426: 
  427:     my $uextkey=hex($ukey);
  428:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
  429: 
  430: # -------------------------------------------------------- Store away log token
  431:     my ($tokenextras,$tokentype,$linkprot_for_login);
  432:     my @names = ('role','symb','iptoken','ltoken','linkprot','linkkey');
  433:     foreach my $name (@names) {
  434:         if ($env{'form.'.$name} ne '') {
  435:             if ($name eq 'ltoken') {
  436:                 my %info = &Apache::lonnet::tmpget($env{'form.'.$name});
  437:                 if ($info{'linkprot'}) {
  438:                     $linkprot_for_login = $info{'linkprot'};
  439:                     $tokenextras .= '&linkprot='.&escape($info{'linkprot'});
  440:                     $tokentype = 'link';
  441:                     last;
  442:                 }
  443:             } else {
  444:                 $tokenextras .= '&'.$name.'='.&escape($env{'form.'.$name});
  445:                 if (($name eq 'linkkey') || ($name eq 'linkprot')) {
  446:                     if (($env{'form.retry'}) && (!$env{'form.ltoken'}) && ($name eq 'linkprot')) {
  447:                         $linkprot_for_login = $env{'form.linkprot'};
  448:                     }
  449:                     $tokentype = 'link';
  450:                 }
  451:             }
  452:         }
  453:     }
  454:     if ($tokentype) {
  455:         $tokenextras .= ":$tokentype";
  456:     }
  457:     my $logtoken=Apache::lonnet::reply(
  458:        'tmpput:'.$ukey.$lkey.'&'.&escape($firsturl).$tokenextras,
  459:        $lonhost);
  460: 
  461: # -- If we cannot talk to ourselves, or hostID does not map to a hostname
  462: #    we are in serious trouble
  463: 
  464:     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
  465:         if ($logtoken eq 'no_such_host') {
  466:             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
  467:         }
  468:         if ($env{'form.ltoken'}) {
  469:             &Apache::lonnet::tmpdel($env{'form.ltoken'});
  470:             delete($env{'form.ltoken'});
  471:         }
  472:         my $spares='';
  473:         my (@sparehosts,%spareservers);
  474:         my $sparesref = &Apache::lonnet::this_host_spares($defdom);
  475:         if (ref($sparesref) eq 'HASH') {
  476:             foreach my $key (keys(%{$sparesref})) {
  477:                 if (ref($sparesref->{$key}) eq 'ARRAY') {
  478:                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp
  479:                                         &Apache::lonnet::hostname($b);
  480:                                       } @{$sparesref->{$key}};
  481:                     if (@sorted) {
  482:                         if ($key eq 'primary') {
  483:                             unshift(@sparehosts,@sorted);
  484:                         } elsif ($key eq 'default') {
  485:                             push(@sparehosts,@sorted);
  486:                         }
  487:                     }
  488:                 }
  489:             }
  490:         }
  491:         foreach my $hostid (@sparehosts) {
  492:             next if ($hostid eq $lonhost);
  493: 	    my $hostname = &Apache::lonnet::hostname($hostid);
  494: 	    next if (($hostname eq '') || ($spareservers{$hostname}));
  495:             $spareservers{$hostname} = 1;
  496:             my $protocol = $Apache::lonnet::protocol{$hostid};
  497:             $protocol = 'http' if ($protocol ne 'https');
  498:             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.
  499:                 $hostname.
  500:                 '/adm/login?domain='.$authdomain.'">'.
  501:                 $hostname.'</a>'.
  502:                 ' '.&mt('(preferred)').'</span>'.$/;
  503:         }
  504:         if ($spares) {
  505:             $spares.= '<br />';
  506:         }
  507:         my %all_hostnames = &Apache::lonnet::all_hostnames();
  508:         foreach my $hostid (sort
  509: 		    {
  510: 			&Apache::lonnet::hostname($a) cmp
  511: 			    &Apache::lonnet::hostname($b);
  512: 		    }
  513: 		    keys(%all_hostnames)) {
  514:             next if ($hostid eq $lonhost);
  515:             my $hostname = &Apache::lonnet::hostname($hostid);
  516:             next if (($hostname eq '') || ($spareservers{$hostname}));
  517:             $spareservers{$hostname} = 1;
  518:             my $protocol = $Apache::lonnet::protocol{$hostid};
  519:             $protocol = 'http' if ($protocol ne 'https');
  520:             $spares.='<br /><a href="'.$protocol.'://'.
  521: 	             $hostname.
  522: 	             '/adm/login?domain='.$authdomain.'">'.
  523: 	             $hostname.'</a>';
  524:          }
  525:          $r->print(
  526:    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
  527:   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'
  528:   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'
  529:   .&mt('The LearningOnline Network with CAPA')
  530:   .'</title></head>'
  531:   .'<body bgcolor="#FFFFFF">'
  532:   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
  533:   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'
  534:   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
  535:         if ($spares) {
  536:             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
  537:                      .'</p>'
  538:                      .$spares);
  539:         }
  540:         $r->print('</body>'
  541:                  .'</html>'
  542:         );
  543:         return OK;
  544:     }
  545: 
  546: # ----------------------------------------------- Apparently we are in business
  547:     $servadm=~s/\,/\<br \/\>/g;
  548: 
  549: # ----------------------------------------------------------- Front page design
  550:     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
  551:     my $font=&Apache::loncommon::designparm('login.font',$domain);
  552:     my $link=&Apache::loncommon::designparm('login.link',$domain);
  553:     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
  554:     my $alink=&Apache::loncommon::designparm('login.alink',$domain);
  555:     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
  556:     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
  557:     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
  558:     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
  559:     my $logo=&Apache::loncommon::designparm('login.logo',$domain);
  560:     my $img=&Apache::loncommon::designparm('login.img',$domain);
  561:     my $domainlogo=&Apache::loncommon::domainlogo($domain);
  562:     my $showbanner = 1;
  563:     my $showmainlogo = 1;
  564:     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
  565:         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
  566:     }
  567:     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
  568:         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
  569:     }
  570:     my $showadminmail;
  571:     my @possdoms = &Apache::lonnet::current_machine_domains();
  572:     if (grep(/^\Q$domain\E$/,@possdoms)) {
  573:         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
  574:     }
  575:     my $showcoursecat =
  576:         &Apache::loncommon::designparm('login.coursecatalog',$domain);
  577:     my $shownewuserlink = 
  578:         &Apache::loncommon::designparm('login.newuser',$domain);
  579:     my $showhelpdesk =
  580:         &Apache::loncommon::designparm('login.helpdesk',$domain);
  581:     my $now=time;
  582:     my $js = (<<ENDSCRIPT);
  583: 
  584: <script type="text/javascript" language="JavaScript">
  585: // <![CDATA[
  586: function send()
  587: {
  588: this.document.server.elements.uname.value
  589: =this.document.client.elements.uname.value;
  590: 
  591: this.document.server.elements.udom.value
  592: =this.document.client.elements.udom.value;
  593: 
  594: uextkey=this.document.client.elements.uextkey.value;
  595: lextkey=this.document.client.elements.lextkey.value;
  596: initkeys();
  597: 
  598: if(this.document.server.action.substr(0,5) === 'http:'){
  599:     this.document.server.elements.upass0.value
  600:         =getCrypted(this.document.client.elements.upass$now.value);
  601: } else {
  602:     this.document.server.elements.upass0.value
  603:         =this.document.client.elements.upass$now.value;
  604: }
  605: 
  606: this.document.client.elements.uname.value='';
  607: this.document.client.elements.upass$now.value='';
  608: 
  609: this.document.server.submit();
  610: return false;
  611: }
  612: 
  613: function enableInput() {
  614:     this.document.client.elements.upass$now.removeAttribute("readOnly");
  615:     this.document.client.elements.uname.removeAttribute("readOnly");
  616:     this.document.client.elements.udom.removeAttribute("readOnly");
  617:     return;
  618: }
  619: 
  620: // ]]>
  621: </script>
  622: 
  623: ENDSCRIPT
  624: 
  625:     my ($lonhost_in_use,@hosts,%defaultdomconf,$saml_prefix,$saml_landing,
  626:         $samlssotext,$samlnonsso,$samlssoimg,$samlssoalt,$samlssourl,$samltooltip);
  627:     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
  628:     @hosts = &Apache::lonnet::current_machine_ids();
  629:     $lonhost_in_use = $lonhost;
  630:     if (@hosts > 1) {
  631:         foreach my $hostid (@hosts) {
  632:             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
  633:                 $lonhost_in_use = $hostid;
  634:                 last;
  635:             }
  636:         }
  637:     }
  638:     $saml_prefix = $defdom.'.login.saml_';
  639:     if ($defaultdomconf{$saml_prefix.$lonhost_in_use}) {
  640:         $saml_landing = 1;
  641:         $samlssotext = $defaultdomconf{$saml_prefix.'text_'.$lonhost_in_use};
  642:         $samlnonsso = $defaultdomconf{$saml_prefix.'notsso_'.$lonhost_in_use};
  643:         $samlssoimg = $defaultdomconf{$saml_prefix.'img_'.$lonhost_in_use};
  644:         $samlssoalt = $defaultdomconf{$saml_prefix.'alt_'.$lonhost_in_use};
  645:         $samlssourl = $defaultdomconf{$saml_prefix.'url_'.$lonhost_in_use};
  646:         $samltooltip = $defaultdomconf{$saml_prefix.'title_'.$lonhost_in_use};
  647:     }
  648:     if ($saml_landing) {
  649:        if ($samlssotext eq '') {
  650:            $samlssotext = 'SSO Login';
  651:        }
  652:        if ($samlnonsso eq '') {
  653:            $samlnonsso = 'Non-SSO Login';
  654:        }
  655:        $js .= <<"ENDSAMLJS";
  656: 
  657: <script type="text/javascript">
  658: // <![CDATA[
  659: function toggleLClogin() {
  660:     if (document.getElementById('LC_standard_login')) {
  661:         if (document.getElementById('LC_standard_login').style.display == 'none') {
  662:             document.getElementById('LC_standard_login').style.display = 'inline-block';
  663:             if (document.getElementById('LC_login_text')) {
  664:                 document.getElementById('LC_login_text').innerHTML = '$samlnonsso';
  665:             }
  666:             if ( document.client.uname ) { document.client.uname.focus(); }
  667:             if (document.getElementById('LC_SSO_login')) {
  668:                 document.getElementById('LC_SSO_login').style.display = 'none';
  669:             }
  670:         } else {
  671:             document.getElementById('LC_standard_login').style.display = 'none';
  672:             if (document.getElementById('LC_login_text')) {
  673:                 document.getElementById('LC_login_text').innerHTML = '$samlssotext';
  674:             }
  675:             if (document.getElementById('LC_SSO_login')) {
  676:                 document.getElementById('LC_SSO_login').style.display = 'inline-block';
  677:             }
  678:         }
  679:     }
  680:     return;
  681: }
  682: 
  683: // ]]>
  684: </script>
  685: 
  686: ENDSAMLJS
  687:     }
  688: 
  689: # --------------------------------------------------- Print login screen header
  690: 
  691:     my %add_entries = (
  692: 	       bgcolor      => "$mainbg",
  693: 	       text         => "$font",
  694: 	       link         => "$link",
  695: 	       vlink        => "$vlink",
  696: 	       alink        => "$alink",
  697:                onload       => 'javascript:enableInput();',);
  698: 
  699:     my ($headextra,$headextra_exempt);
  700:     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
  701:     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
  702:     if ($headextra) {
  703:         my $omitextra;
  704:         if ($headextra_exempt ne '') {
  705:             my @exempt = split(',',$headextra_exempt);
  706:             my $ip = &Apache::lonnet::get_requestor_ip();
  707:             if (grep(/^\Q$ip\E$/,@exempt)) {
  708:                 $omitextra = 1;
  709:             }
  710:         }
  711:         unless ($omitextra) {
  712:             my $confname = $defdom.'-domainconfig';
  713:             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
  714:                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
  715:                 unless ($extra eq '-1') {
  716:                     $js .= "\n".$extra."\n";
  717:                 }
  718:             }
  719:         }
  720:     }
  721: 
  722:     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
  723: 			       { 'redirect'       => [$expire,'/adm/roles'], 
  724: 				 'add_entries' => \%add_entries,
  725: 				 'only_body'   => 1,}));
  726: 
  727: # ----------------------------------------------------------------------- Texts
  728: 
  729:     my %lt=&Apache::lonlocal::texthash(
  730:           'un'       => 'Username',
  731:           'pw'       => 'Password',
  732:           'dom'      => 'Domain',
  733:           'perc'     => 'percent',
  734:           'load'     => 'Server Load',
  735:           'userload' => 'User Load',
  736:           'catalog'  => 'Course/Community Catalog',
  737:           'log'      => 'Log in',
  738:           'help'     => 'Log-in Help',
  739:           'serv'     => 'Server',
  740:           'servadm'  => 'Server Administration',
  741:           'helpdesk' => 'Contact Helpdesk',
  742:           'forgotpw' => 'Forgot password?',
  743:           'newuser'  => 'New User?',
  744:           'change'   => 'Change?',
  745:        );
  746: # -------------------------------------------------- Change password field name
  747: 
  748:     my $forgotpw = &forgotpwdisplay(%lt);
  749:     $forgotpw .= '<br />' if $forgotpw;
  750:     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
  751:     if ($loginhelp) {
  752:         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
  753:     }
  754: 
  755: # ---------------------------------------------------- Serve out DES JavaScript
  756:     {
  757:     my $jsh=Apache::File->new($include."/londes.js");
  758:     $r->print(<$jsh>);
  759:     }
  760: # ---------------------------------------------------------- Serve rest of page
  761: 
  762:     $r->print(
  763:     '<div class="LC_Box"'
  764:    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
  765: );
  766: 
  767:     $r->print(<<ENDSERVERFORM);
  768: <form name="server" action="/adm/authenticate" method="post" target="_top">
  769:    <input type="hidden" name="logtoken" value="$logtoken" />
  770:    <input type="hidden" name="serverid" value="$lonhost" />
  771:    <input type="hidden" name="uname" value="" />
  772:    <input type="hidden" name="upass0" value="" />
  773:    <input type="hidden" name="udom" value="" />
  774:    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
  775:    <input type="hidden" name="localres" value="$env{'form.localres'}" />
  776:   </form>
  777: ENDSERVERFORM
  778:     my $coursecatalog;
  779:     if (($showcoursecat eq '') || ($showcoursecat)) {
  780:         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
  781:     }
  782:     my $newuserlink;
  783:     if ($shownewuserlink) {
  784:         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
  785:     }
  786:     my $logintitle =
  787:         '<h2 class="LC_hcell"'
  788:        .' style="background:'.$loginbox_header_bgcol.';'
  789:        .' color:'.$loginbox_header_textcol.'">'
  790:        .$lt{'log'}
  791:        .'</h2>';
  792: 
  793:     my $noscript_warning='<noscript><span class="LC_warning"><b>'
  794:                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
  795:                         .'</b></span></noscript>';
  796:     my $helpdeskscript;
  797:     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
  798:                                        $authdomain,\$helpdeskscript,
  799:                                        $showhelpdesk,\@possdoms);
  800: 
  801:     my $mobileargs;
  802:     if ($clientmobile) {
  803:         $mobileargs = 'autocapitalize="off" autocorrect="off"'; 
  804:     }
  805:     my $loginform=(<<LFORM);
  806: <form name="client" action="" onsubmit="return(send())" id="lclogin">
  807:   <input type="hidden" name="lextkey" value="$lextkey" />
  808:   <input type="hidden" name="uextkey" value="$uextkey" />
  809:   <b><label for="uname">$lt{'un'}</label>:</b><br />
  810:   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
  811:   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
  812:   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
  813:   <b><label for="udom">$lt{'dom'}</label>:</b><br />
  814:   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
  815:   <input type="submit" value="$lt{'log'}" />
  816: </form>
  817: LFORM
  818: 
  819:     if ($showbanner) {
  820:         my $alttext = &Apache::loncommon::designparm('login.alttext_img',$domain);
  821:         if ($alttext eq '') {
  822:             $alttext = 'The Learning Online Network with CAPA';
  823:         }
  824:         $r->print(<<HEADER);
  825: <!-- The LON-CAPA Header -->
  826: <div style="background:$pgbg;margin:0;width:100%;">
  827:   <img src="$img" border="0" alt="$alttext" class="LC_maxwidth" id="lcloginbanner" />
  828: </div>
  829: HEADER
  830:     }
  831: 
  832:     my $stdauthformstyle = 'inline-block';
  833:     my $ssoauthstyle = 'none';
  834:     my $logintype;
  835:     $r->print('<div style="float:left;margin-top:0;">');
  836:     if ($saml_landing) {
  837:         $ssoauthstyle = 'inline-block';
  838:         $stdauthformstyle = 'none';
  839:         $logintype = $samlssotext;
  840:         my $ssologin = '/adm/sso';
  841:         if ($samlssourl  ne '') {
  842:             $ssologin = $samlssourl;
  843:         }
  844:         if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
  845:             my $querystring;
  846:             if ($env{'form.firsturl'} ne '') {
  847:                 $querystring = 'origurl=';
  848:                 if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
  849:                     $querystring .= &uri_escape_utf8($env{'form.firsturl'});
  850:                 } else {
  851:                     $querystring .= &uri_escape($env{'form.firsturl'});
  852:                 }
  853:                 $querystring = &HTML::Entities::encode($querystring,"'");
  854:             }
  855:             if ($env{'form.ltoken'} ne '') {
  856:                 $querystring .= (($querystring eq '')?'':'&amp;') . 'ltoken='.
  857:                                   &HTML::Entities::encode(&uri_escape($env{'form.ltoken'}));
  858:             } elsif ($env{'form.linkkey'}) {
  859:                 $querystring .= (($querystring eq '')?'':'&amp;') . 'linkkey='.
  860:                                   &HTML::Entities::encode(&uri_escape($env{'form.linkkey'}));
  861:             }
  862:             if ($querystring ne '') {
  863:                 $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . $querystring;
  864:             }
  865:         } elsif ($logtoken ne '') {
  866:             $ssologin .= (($ssologin=~/\?/)?'&amp;':'?') . 'logtoken='.$logtoken;
  867:         }
  868:         my $ssohref;
  869:         if ($samlssoimg ne '') {
  870:             $ssohref = '<a href="'.$ssologin.'" title="'.$samltooltip.'">'.
  871:                        '<img src="'.$samlssoimg.'" alt="'.$samlssoalt.'" id="lcssobutton" /></a>';
  872:         } else {
  873:             $ssohref = '<a href="'.$ssologin.'">'.$samlssotext.'</a>';
  874:         }
  875:         if (($env{'form.saml'} eq 'no') ||
  876:             (($env{'form.username'} ne '') && ($env{'form.domain'} ne ''))) {
  877:             $ssoauthstyle = 'none';
  878:             $stdauthformstyle = 'inline-block';
  879:             $logintype = $samlnonsso;
  880:         }
  881:         $r->print(<<ENDSAML);
  882: <p>
  883: Log-in type:
  884: <span style="font-weight:bold" id="LC_login_text">$logintype</span><br />
  885: <span><a href="javascript:toggleLClogin();" style="color:#000000">$lt{'change'}</a></span>
  886: </p>
  887: <div style="display:$ssoauthstyle" id="LC_SSO_login">
  888: <div class="LC_Box" style="padding-top: 10px;">
  889: $ssohref
  890: $noscript_warning
  891: </div>
  892: <div class="LC_Box" style="padding-top: 10px;">
  893: $loginhelp
  894: $contactblock
  895: $coursecatalog
  896: </div>
  897: </div>
  898: ENDSAML
  899:     } else {
  900:         if ($env{'form.ltoken'}) {
  901:             &Apache::lonnet::tmpdel($env{'form.ltoken'});
  902:             delete($env{'form.ltoken'});
  903:         }
  904:     }
  905:     my $in_frame_js;
  906:     if ($linkprot_for_login) {
  907:         my ($linkprotector,$linkproturi) = split(/:/,$linkprot_for_login,2);
  908:         if (($linkprotector =~ /^\d+(c|d)$/) && ($linkproturi =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$})) {
  909:             my $set_target;
  910:             if ($env{'form.retry'}) {
  911:                 if ($linkproturi eq $env{'form.firsturl'}) {
  912:                     $set_target = "    document.server.target = '_self';";
  913:                 }
  914:             } else {
  915:                 $set_target = <<ENDTARG;
  916:     var linkproturi = '$linkproturi';
  917:     var path = document.location.pathname.replace( new RegExp('^/adm/launch'),'');
  918:     if (linkproturi == path) {
  919:         document.server.target = '_self';
  920:     }
  921: ENDTARG
  922:             }
  923:             $in_frame_js = <<ENDJS;
  924: <script type="text/javascript">
  925: // <![CDATA[
  926: if ((window.self !== window.top) && (document.server.target != '_self')) {
  927:     $set_target
  928: }
  929: // ]]>
  930: </script>
  931: ENDJS
  932:         }
  933:     }
  934: 
  935:     $r->print(<<ENDLOGIN);
  936: <div style="display:$stdauthformstyle;" id="LC_standard_login">
  937: <div class="LC_Box" style="background:$loginbox_bg;">
  938:   $logintitle
  939:   $loginform
  940:   $noscript_warning
  941: </div>
  942:   
  943: <div class="LC_Box" style="padding-top: 10px;">
  944:   $loginhelp
  945:   $forgotpw
  946:   $contactblock
  947:   $newuserlink
  948:   $coursecatalog
  949: </div>
  950: </div>
  951: 
  952: ENDLOGIN
  953:     $r->print('</div><div>'."\n");
  954:     if ($showmainlogo) {
  955:         my $alttext = &Apache::loncommon::designparm('login.alttext_logo',$domain); 
  956:         $r->print(' <img src="'.$logo.'" alt="'.$alttext.'" class="LC_maxwidth" id="lcloginmainlogo" />'."\n");
  957:     }
  958: $r->print(<<ENDTOP);
  959: $announcements
  960: </div>
  961: <hr style="clear:both;" />
  962: ENDTOP
  963:     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
  964:     $domainrow = <<"END";
  965:       <tr>
  966:        <td  align="left" valign="top">
  967:         <small><b>$lt{'dom'}:&nbsp;</b></small>
  968:        </td>
  969:        <td  align="left" valign="top">
  970:         <small><tt>&nbsp;$domain</tt></small>
  971:        </td>
  972:       </tr>
  973: END
  974:     $serverrow = <<"END";
  975:       <tr>
  976:        <td  align="left" valign="top">
  977:         <small><b>$lt{'serv'}:&nbsp;</b></small>
  978:        </td>
  979:        <td align="left" valign="top">
  980:         <small><tt>&nbsp;$lonhost ($role)</tt></small>
  981:        </td>
  982:       </tr>
  983: END
  984:     if ($loadlim) {
  985:         $loadrow = <<"END";
  986:       <tr>
  987:        <td align="left" valign="top">
  988:         <small><b>$lt{'load'}:&nbsp;</b></small>
  989:        </td>
  990:        <td align="left" valign="top">
  991:         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
  992:        </td>
  993:       </tr>
  994: END
  995:     }
  996:     if ($uloadlim) {
  997:         $userloadrow = <<"END";
  998:       <tr>
  999:        <td align="left" valign="top">
 1000:         <small><b>$lt{'userload'}:&nbsp;</b></small>
 1001:        </td>
 1002:        <td align="left" valign="top">
 1003:         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
 1004:        </td>
 1005:       </tr>
 1006: END
 1007:     }
 1008:     if (($version ne '') && ($version ne '<!-- VERSION -->')) {
 1009:         $versionrow = <<"END";
 1010:       <tr>
 1011:        <td colspan="2" align="left">
 1012:         <small>$version</small>
 1013:        </td>
 1014:       </tr>
 1015: END
 1016:     }
 1017: 
 1018:     $r->print(<<ENDDOCUMENT);
 1019:     <div style="float: left;">
 1020:      <table border="0" cellspacing="0" cellpadding="0">
 1021: $domainrow
 1022: $serverrow
 1023: $loadrow    
 1024: $userloadrow
 1025: $versionrow
 1026:      </table>
 1027:     </div>
 1028:     <div style="float: right;">
 1029:     $domainlogo
 1030:     </div>
 1031:     <br style="clear:both;" />
 1032:  </div>
 1033: 
 1034: <script type="text/javascript">
 1035: // <![CDATA[
 1036: // the if prevents the script error if the browser can not handle this
 1037: if ( document.client.uname ) { document.client.uname.focus(); }
 1038: // ]]>
 1039: </script>
 1040: $helpdeskscript
 1041: 
 1042: ENDDOCUMENT
 1043:     my %endargs = ( 'noredirectlink' => 1, );
 1044:     $r->print(&Apache::loncommon::end_page(\%endargs));
 1045:     return OK;
 1046: }
 1047: 
 1048: sub check_loginvia {
 1049:     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;
 1050:     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
 1051:         return;
 1052:     }
 1053:     my %domconfhash = &Apache::loncommon::get_domainconf($domain);
 1054:     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
 1055:     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
 1056:     my $output;
 1057:     if ($loginvia ne '') {
 1058:         my $noredirect;
 1059:         my $ip = &Apache::lonnet::get_requestor_ip();   
 1060:         if ($ip eq '127.0.0.1') {
 1061:             $noredirect = 1;
 1062:         } else {
 1063:             if ($loginvia_exempt ne '') {
 1064:                 my @exempt = split(',',$loginvia_exempt);
 1065:                 if (grep(/^\Q$ip\E$/,@exempt)) {
 1066:                     $noredirect = 1;
 1067:                 }
 1068:             }
 1069:         }
 1070:         unless ($noredirect) {
 1071:             my ($newhost,$path);
 1072:             if ($loginvia =~ /:/) {
 1073:                 ($newhost,$path) = split(':',$loginvia);
 1074:             } else {
 1075:                 $newhost = $loginvia;
 1076:             }
 1077:             if ($newhost ne $lonhost) {
 1078:                 if (&Apache::lonnet::hostname($newhost) ne '') {
 1079:                     if ($balcookie) {
 1080:                         my ($balancer,$cookie) = split(/:/,$balcookie);
 1081:                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
 1082:                             my ($udom,$uname,$cookieid) = ($1,$2,$3);
 1083:                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
 1084:                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
 1085:                                     while (my $filename=readdir($dh)) {
 1086:                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
 1087:                                             my $handle = $1;
 1088:                                             my %hash =
 1089:                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
 1090:                                                                                      ['request.balancercookie',
 1091:                                                                                       'user.linkedenv']);
 1092:                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
 1093:                                                 if (unlink("$lonidsdir/$filename")) {
 1094:                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
 1095:                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
 1096:                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
 1097:                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
 1098:                                                     }
 1099:                                                 }
 1100:                                             }
 1101:                                             last;
 1102:                                         }
 1103:                                     }
 1104:                                     closedir($dh);
 1105:                                 }
 1106:                             }
 1107:                         }
 1108:                     }
 1109:                     $output = &redirect_page($newhost,$path);
 1110:                 }
 1111:             }
 1112:         }
 1113:     }
 1114:     return $output;
 1115: }
 1116: 
 1117: sub redirect_page {
 1118:     my ($desthost,$path) = @_;
 1119:     my $hostname = &Apache::lonnet::hostname($desthost);
 1120:     my $protocol = $Apache::lonnet::protocol{$desthost};
 1121:     $protocol = 'http' if ($protocol ne 'https');
 1122:     unless ($path =~ m{^/}) {
 1123:         $path = '/'.$path;
 1124:     }
 1125:     my $url = $protocol.'://'.$hostname.$path;
 1126:     if ($env{'form.firsturl'} ne '') {
 1127:         my $querystring;
 1128:         if ($env{'form.firsturl'} =~ /[^\x00-\xFF]/) {
 1129:             $querystring = &uri_escape_utf8($env{'form.firsturl'});
 1130:         } else {
 1131:             $querystring = &uri_escape($env{'form.firsturl'});
 1132:         }
 1133:         $querystring = &HTML::Entities::encode($querystring,"'");
 1134:         $url .='?firsturl='.$querystring;
 1135:     }
 1136:     if (($env{'form.ltoken'}) || ($env{'form.linkkey'} ne '')) {
 1137:         my %link_info;
 1138:         if ($env{'form.ltoken'}) {
 1139:             $link_info{'ltoken'} = $env{'form.ltoken'};
 1140:         } elsif ($env{'form.linkkey'} ne '') {
 1141:             $link_info{'linkkey'} = $env{'form.linkkey'};
 1142:         }
 1143:         my $token = &Apache::lonnet::tmpput(\%link_info,$desthost,'link');
 1144:         unless (($token eq 'con_lost') || ($token eq 'refused') ||
 1145:                 ($token eq 'unknown_cmd') || ($token eq 'no_such_host')) {
 1146:             $url .= (($url=~/\?/)?'&amp;':'?') . 'ttoken='.$token;
 1147:         }
 1148:     }
 1149:     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
 1150:                                                     {'redirect' => [0,$url],});
 1151:     my $end_page   = &Apache::loncommon::end_page();
 1152:     return $start_page.$end_page;
 1153: }
 1154: 
 1155: sub contactdisplay {
 1156:     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
 1157:         $possdoms) = @_;
 1158:     my $contactblock;
 1159:     my $origmail;
 1160:     if (ref($possdoms) eq 'ARRAY') {
 1161:         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) { 
 1162:             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
 1163:         }
 1164:     }
 1165:     my $requestmail = 
 1166:         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
 1167:                                                  $authdomain,$origmail);
 1168:     unless ($showhelpdesk eq '0') {
 1169:         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
 1170:             $showhelpdesk = 1;
 1171:         } else {
 1172:             $showhelpdesk = 0;
 1173:         }
 1174:     }
 1175:     if ($servadm && $showadminmail) {
 1176:         $contactblock .= $$lt{'servadm'}.':<br />'.
 1177:                          '<tt>'.$servadm.'</tt><br />';
 1178:     }
 1179:     if ($showhelpdesk) {
 1180:         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
 1181:         my $thisurl = &escape('/adm/login');
 1182:         $$helpdeskscript = <<"ENDSCRIPT";
 1183: <script type="text/javascript">
 1184: // <![CDATA[
 1185: function helpdesk() {
 1186:     var possdom = document.client.udom.value;
 1187:     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
 1188:     if (codedom == '') {
 1189:         codedom = "$authdomain";
 1190:     }
 1191:     var querystr = "origurl=$thisurl&codedom="+codedom;
 1192:     document.location.href = "/adm/helpdesk?"+querystr;
 1193:     return;
 1194: }
 1195: // ]]>
 1196: </script>
 1197: ENDSCRIPT
 1198:     }
 1199:     return $contactblock;
 1200: }
 1201: 
 1202: sub forgotpwdisplay {
 1203:     my (%lt) = @_;
 1204:     my $prompt_for_resetpw = 1; 
 1205:     if ($prompt_for_resetpw) {
 1206:         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
 1207:     }
 1208:     return;
 1209: }
 1210: 
 1211: sub coursecatalog_link {
 1212:     my ($linkname) = @_;
 1213:     return <<"END";
 1214:       <a href="/adm/coursecatalog">$linkname</a>
 1215: END
 1216: }
 1217: 
 1218: sub newuser_link {
 1219:     my ($linkname) = @_;
 1220:     return '<a href="/adm/createaccount">'.$linkname.'</a>';
 1221: }
 1222: 
 1223: sub decode_token {
 1224:     my ($info) = @_;
 1225:     my ($firsturl,@rest)=split(/\&/,$info);
 1226:     my %form;
 1227:     if ($firsturl ne '') {
 1228:         $form{'firsturl'} = &unescape($firsturl);
 1229:     }
 1230:     foreach my $item (@rest) {
 1231:         my ($key,$value) = split(/=/,$item);
 1232:         $form{$key} = &unescape($value);
 1233:     }
 1234:     return %form;
 1235: }
 1236: 
 1237: 1;
 1238: __END__

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