File:  [LON-CAPA] / loncom / auth / lonlogin.pm
Revision 1.207: download - view: text, annotated - select for diffs
Tue Nov 21 19:52:18 2023 UTC (5 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Avoid endless redirects to current host when login page redirects are in
  effect and original URL request was for /enc/ for an expired session.

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

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