File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1513: download - view: text, annotated - select for diffs
Thu Jul 20 12:47:09 2023 UTC (12 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &get_ltitools_id() moved from courseprefs.pm to lonnet.pm to facilitate
  reuse.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1513 2023/07/20 12:47:09 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: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use HTTP::Date;
   75: use Image::Magick;
   76: use CGI::Cookie;
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab $passwdmin);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use Net::CIDR;
  100: use Sys::Hostname::FQDN();
  101: use LONCAPA qw(:DEFAULT :match);
  102: use LONCAPA::Configuration;
  103: use LONCAPA::lonmetadata;
  104: use LONCAPA::Lond;
  105: use LONCAPA::LWPReq;
  106: use LONCAPA::transliterate;
  107: 
  108: use File::Copy;
  109: 
  110: my $readit;
  111: my $max_connection_retries = 20;     # Or some such value.
  112: 
  113: require Exporter;
  114: 
  115: our @ISA = qw (Exporter);
  116: our @EXPORT = qw(%env);
  117: 
  118: 
  119: # ------------------------------------ Logging (parameters, docs, slots, roles)
  120: {
  121:     my $logid;
  122:     sub write_log {
  123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  124:         if ($context eq 'course') {
  125:             if (($cnum eq '') || ($cdom eq '')) {
  126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  128:             }
  129:         }
  130: 	$logid ++;
  131:         my $now = time();
  132: 	my $id=$now.'00000'.$$.'00000'.$logid;
  133:         my $ip = &get_requestor_ip();
  134:         my $logentry = { 
  135:                           $id => {
  136:                                    'exe_uname' => $env{'user.name'},
  137:                                    'exe_udom'  => $env{'user.domain'},
  138:                                    'exe_time'  => $now,
  139:                                    'exe_ip'    => $ip,
  140:                                    'delflag'   => $delflag,
  141:                                    'logentry'  => $storehash,
  142:                                    'uname'     => $uname,
  143:                                    'udom'      => $udom,
  144:                                   }
  145:                        };
  146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  147:     }
  148: }
  149: 
  150: sub logtouch {
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     unless (-e "$execdir/logs/lonnet.log") {	
  153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  154: 	close $fh;
  155:     }
  156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  158: }
  159: 
  160: sub logthis {
  161:     my $message=shift;
  162:     my $execdir=$perlvar{'lonDaemons'};
  163:     my $now=time;
  164:     my $local=localtime($now);
  165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  167: 	print $fh $logstring;
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub logperm {
  174:     my $message=shift;
  175:     my $execdir=$perlvar{'lonDaemons'};
  176:     my $now=time;
  177:     my $local=localtime($now);
  178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  179: 	print $fh "$now:$message:$local\n";
  180: 	close($fh);
  181:     }
  182:     return 1;
  183: }
  184: 
  185: sub create_connection {
  186:     my ($hostname,$lonid) = @_;
  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  188: 				     Type    => SOCK_STREAM,
  189: 				     Timeout => 10);
  190:     return 0 if (!$client);
  191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
  192:     my $result = <$client>;
  193:     chomp($result);
  194:     return 1 if ($result eq 'done');
  195:     return 0;
  196: }
  197: 
  198: sub get_server_timezone {
  199:     my ($cnum,$cdom) = @_;
  200:     my $home=&homeserver($cnum,$cdom);
  201:     if ($home ne 'no_host') {
  202:         my $cachetime = 24*3600;
  203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  204:         if (defined($cached)) {
  205:             return $timezone;
  206:         } else {
  207:             my $timezone = &reply('servertimezone',$home);
  208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  209:         }
  210:     }
  211: }
  212: 
  213: sub get_server_distarch {
  214:     my ($lonhost,$ignore_cache) = @_;
  215:     if (defined($lonhost)) {
  216:         if (!defined(&hostname($lonhost))) {
  217:             return;
  218:         }
  219:         my $cachetime = 12*3600;
  220:         if (!$ignore_cache) {
  221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  222:             if (defined($cached)) {
  223:                 return $distarch;
  224:             }
  225:         }
  226:         my $rep = &reply('serverdistarch',$lonhost);
  227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  229:                 $rep eq '') {
  230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  231:         }
  232:     }
  233:     return;
  234: }
  235: 
  236: sub get_servercerts_info {
  237:     my ($lonhost,$hostname,$context) = @_;
  238:     return if ($lonhost eq '');
  239:     if ($hostname eq '') {
  240:         $hostname = &hostname($lonhost);
  241:     }
  242:     return if ($hostname eq '');
  243:     my ($rep,$uselocal);
  244:     if ($context eq 'install') {
  245:         $uselocal = 1;
  246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
  247:         $uselocal = 1;
  248:     }
  249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
  250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  251:         if ($distro eq '') {
  252:             $uselocal = 0;
  253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  254:             if ($1 < 6) {
  255:                 $uselocal = 0;
  256:             }
  257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  258:             if ($1 < 12) {
  259:                 $uselocal = 0;
  260:             }
  261:         }
  262:     }
  263:     if ($uselocal) {
  264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
  265:     } else {
  266:         $rep=&reply('servercerts',$lonhost);
  267:     }
  268:     my ($result,%returnhash);
  269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  270:         ($rep eq 'unknown_cmd')) {
  271:         $result = $rep;
  272:     } else {
  273:         $result = 'ok';
  274:         my @pairs=split(/\&/,$rep);
  275:         foreach my $item (@pairs) {
  276:             my ($key,$value)=split(/=/,$item,2);
  277:             my $what = &unescape($key);
  278:             $returnhash{$what}=&thaw_unescape($value);
  279:         }
  280:     }
  281:     return ($result,\%returnhash);
  282: }
  283: 
  284: sub get_server_loncaparev {
  285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  286:     if (defined($lonhost)) {
  287:         if (!defined(&hostname($lonhost))) {
  288:             undef($lonhost);
  289:         }
  290:     }
  291:     if (!defined($lonhost)) {
  292:         if (defined(&domain($dom,'primary'))) {
  293:             $lonhost=&domain($dom,'primary');
  294:             if ($lonhost eq 'no_host') {
  295:                 undef($lonhost);
  296:             }
  297:         }
  298:     }
  299:     if (defined($lonhost)) {
  300:         my $cachetime = 12*3600;
  301:         if (!$ignore_cache) {
  302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  303:             if (defined($cached)) {
  304:                 return $loncaparev;
  305:             }
  306:         }
  307:         my ($answer,$loncaparev);
  308:         my @ids=&current_machine_ids();
  309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  310:             $answer = $perlvar{'lonVersion'};
  311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  312:                 $loncaparev = $1;
  313:             }
  314:         } else {
  315:             $answer = &reply('serverloncaparev',$lonhost);
  316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  317:                 if ($caller eq 'loncron') {
  318:                     my $hostname = &hostname($lonhost);
  319:                     my $protocol = $protocol{$lonhost};
  320:                     $protocol = 'http' if ($protocol ne 'https');
  321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  322:                     my $request=new HTTP::Request('GET',$url);
  323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  324:                     unless ($response->is_error()) {
  325:                         my $content = $response->content;
  326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  327:                             $loncaparev = $1;
  328:                         }
  329:                     }
  330:                 } else {
  331:                     $loncaparev = $loncaparevs{$lonhost};
  332:                 }
  333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  334:                 $loncaparev = $1;
  335:             }
  336:         }
  337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  338:     }
  339: }
  340: 
  341: sub get_server_homeID {
  342:     my ($hostname,$ignore_cache,$caller) = @_;
  343:     unless ($ignore_cache) {
  344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  345:         if (defined($cached)) {
  346:             return $serverhomeID;
  347:         }
  348:     }
  349:     my $cachetime = 12*3600;
  350:     my $serverhomeID;
  351:     if ($caller eq 'loncron') { 
  352:         my @machine_ids = &machine_ids($hostname);
  353:         foreach my $id (@machine_ids) {
  354:             my $response = &reply('serverhomeID',$id);
  355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  356:                 $serverhomeID = $response;
  357:                 last;
  358:             }
  359:         }
  360:         if ($serverhomeID eq '') {
  361:             $serverhomeID = $machine_ids[-1];
  362:         }
  363:     } else {
  364:         $serverhomeID = $serverhomeIDs{$hostname};
  365:     }
  366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  367: }
  368: 
  369: sub get_remote_globals {
  370:     my ($lonhost,$whathash,$ignore_cache) = @_;
  371:     my ($result,%returnhash,%whatneeded);
  372:     if (ref($whathash) eq 'HASH') {
  373:         foreach my $what (sort(keys(%{$whathash}))) {
  374:             my $hashid = $lonhost.'-'.$what;
  375:             my ($response,$cached);
  376:             unless ($ignore_cache) {
  377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  378:             }
  379:             if (defined($cached)) {
  380:                 $returnhash{$what} = $response;
  381:             } else {
  382:                 $whatneeded{$what} = 1;
  383:             }
  384:         }
  385:         if (keys(%whatneeded) == 0) {
  386:             $result = 'ok';
  387:         } else {
  388:             my $requested = &freeze_escape(\%whatneeded);
  389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  391:                 ($rep eq 'unknown_cmd')) {
  392:                 $result = $rep;
  393:             } else {
  394:                 $result = 'ok';
  395:                 my @pairs=split(/\&/,$rep);
  396:                 foreach my $item (@pairs) {
  397:                     my ($key,$value)=split(/=/,$item,2);
  398:                     my $what = &unescape($key);
  399:                     my $hashid = $lonhost.'-'.$what;
  400:                     $returnhash{$what}=&thaw_unescape($value);
  401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  402:                 }
  403:             }
  404:         }
  405:     }
  406:     return ($result,\%returnhash);
  407: }
  408: 
  409: sub remote_devalidate_cache {
  410:     my ($lonhost,$cachekeys) = @_;
  411:     my $items;
  412:     return unless (ref($cachekeys) eq 'ARRAY');
  413:     my $cachestr = join('&',@{$cachekeys});
  414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  415:     return $response;
  416: }
  417: 
  418: sub sign_lti {
  419:     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
  420:     my $chome;
  421:     if (&domain($cdom) ne '') {
  422:         if ($crsdef) {
  423:             $chome = &homeserver($cnum,$cdom);
  424:         } else {
  425:             $chome = &domain($cdom,'primary');
  426:         }
  427:     }
  428:     if ($cdom && $chome && ($chome ne 'no_host')) {
  429:         if ((ref($paramsref) eq 'HASH') &&
  430:             (ref($inforef) eq 'HASH')) {
  431:             my $rep;
  432:             if (grep { $_ eq $chome } &current_machine_ids()) {
  433:                 # domain information is hosted on this machine
  434:                 $rep =
  435:                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
  436:                                                      $context,$url,$ltinum,$keynum,
  437:                                                      $perlvar{'lonVersion'},
  438:                                                      $paramsref,$inforef);
  439:                 if (ref($rep) eq 'HASH') {
  440:                     return ('ok',$rep);
  441:                 }
  442:             } else {
  443:                 my ($escurl,$params,$info);
  444:                 $escurl = &escape($url);
  445:                 if (ref($paramsref) eq 'HASH') {
  446:                     $params = &freeze_escape($paramsref);
  447:                 }
  448:                 if (ref($inforef) eq 'HASH') {
  449:                     $info = &freeze_escape($inforef);
  450:                 }
  451:                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
  452:             }
  453:             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
  454:                 return ();
  455:             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
  456:                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
  457:                 return ('ok',$rep);
  458:             } else {
  459:                 my %returnhash;
  460:                 foreach my $item (split(/\&/,$rep)) {
  461:                     my ($name,$value)=split(/\=/,$item);
  462:                     $returnhash{&unescape($name)}=&thaw_unescape($value);
  463:                 }
  464:                 return('ok',\%returnhash);
  465:             }
  466:         } else {
  467:             return ();
  468:         }
  469:     } else {
  470:         return ();
  471:         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
  472:     }
  473: }
  474: 
  475: # -------------------------------------------------- Non-critical communication
  476: sub subreply {
  477:     my ($cmd,$server)=@_;
  478:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  479:     #
  480:     #  With loncnew process trimming, there's a timing hole between lonc server
  481:     #  process exit and the master server picking up the listen on the AF_UNIX
  482:     #  socket.  In that time interval, a lock file will exist:
  483: 
  484:     my $lockfile=$peerfile.".lock";
  485:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  486: 	sleep(0.1);
  487:     }
  488:     # At this point, either a loncnew parent is listening or an old lonc
  489:     # or loncnew child is listening so we can connect or everything's dead.
  490:     #
  491:     #   We'll give the connection a few tries before abandoning it.  If
  492:     #   connection is not possible, we'll con_lost back to the client.
  493:     #   
  494:     my $client;
  495:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  496: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  497: 				      Type    => SOCK_STREAM,
  498: 				      Timeout => 10);
  499: 	if ($client) {
  500: 	    last;		# Connected!
  501: 	} else {
  502: 	    &create_connection(&hostname($server),$server);
  503: 	}
  504:         sleep(0.1);	# Try again later if failed connection.
  505:     }
  506:     my $answer;
  507:     if ($client) {
  508: 	print $client "sethost:$server:$cmd\n";
  509: 	$answer=<$client>;
  510: 	if (!$answer) { $answer="con_lost"; }
  511: 	chomp($answer);
  512:     } else {
  513: 	$answer = 'con_lost';	# Failed connection.
  514:     }
  515:     return $answer;
  516: }
  517: 
  518: sub reply {
  519:     my ($cmd,$server)=@_;
  520:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  521:     my $answer=subreply($cmd,$server);
  522:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  523:         my $logged = $cmd;
  524:         if ($cmd =~ /^encrypt:([^:]+):/) {
  525:             my $subcmd = $1;
  526:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  527:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  528:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
  529:                 ($subcmd eq 'put')) {
  530:                 (undef,undef,my @rest) = split(/:/,$cmd);
  531:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  532:                     splice(@rest,2,1,'Hidden');
  533:                 } elsif ($subcmd eq 'passwd') {
  534:                     splice(@rest,2,2,('Hidden','Hidden'));
  535:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  536:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
  537:                     splice(@rest,3,1,'Hidden');
  538:                 }
  539:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  540:             }
  541:         }
  542:         &logthis("<font color=\"blue\">WARNING:".
  543:                  " $logged to $server returned $answer</font>");
  544:     }
  545:     return $answer;
  546: }
  547: 
  548: # ----------------------------------------------------------- Send USR1 to lonc
  549: 
  550: sub reconlonc {
  551:     my ($lonid) = @_;
  552:     if ($lonid) {
  553:         my $hostname = &hostname($lonid);
  554: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  555: 	if ($hostname && -e $peerfile) {
  556: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  557: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  558: 					     Type    => SOCK_STREAM,
  559: 					     Timeout => 10);
  560: 	    if ($client) {
  561: 		print $client ("reset_retries\n");
  562: 		my $answer=<$client>;
  563: 		#reset just this one.
  564: 	    }
  565: 	}
  566: 	return;
  567:     }
  568: 
  569:     &logthis("Trying to reconnect lonc");
  570:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  571:     if (open(my $fh,"<",$loncfile)) {
  572: 	my $loncpid=<$fh>;
  573:         chomp($loncpid);
  574:         if (kill 0 => $loncpid) {
  575: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  576:             kill USR1 => $loncpid;
  577:             sleep 1;
  578:         } else {
  579: 	    &logthis(
  580:                "<font color=\"blue\">WARNING:".
  581:                " lonc at pid $loncpid not responding, giving up</font>");
  582:         }
  583:     } else {
  584: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  585:     }
  586: }
  587: 
  588: # ------------------------------------------------------ Critical communication
  589: 
  590: sub critical {
  591:     my ($cmd,$server)=@_;
  592:     unless (&hostname($server)) {
  593:         &logthis("<font color=\"blue\">WARNING:".
  594:                " Critical message to unknown server ($server)</font>");
  595:         return 'no_such_host';
  596:     }
  597:     my $answer=reply($cmd,$server);
  598:     if ($answer eq 'con_lost') {
  599: 	&reconlonc($server);
  600: 	my $answer=reply($cmd,$server);
  601:         if ($answer eq 'con_lost') {
  602:             my $now=time;
  603:             my $middlename=$cmd;
  604:             $middlename=substr($middlename,0,16);
  605:             $middlename=~s/\W//g;
  606:             my $dfilename=
  607:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  608:             $dumpcount++;
  609:             {
  610: 		my $dfh;
  611: 		if (open($dfh,">",$dfilename)) {
  612: 		    print $dfh "$cmd\n"; 
  613: 		    close($dfh);
  614: 		}
  615:             }
  616:             sleep 1;
  617:             my $wcmd='';
  618:             {
  619: 		my $dfh;
  620: 		if (open($dfh,"<",$dfilename)) {
  621: 		    $wcmd=<$dfh>; 
  622: 		    close($dfh);
  623: 		}
  624:             }
  625:             chomp($wcmd);
  626:             if ($wcmd eq $cmd) {
  627: 		&logthis("<font color=\"blue\">WARNING: ".
  628:                          "Connection buffer $dfilename: $cmd</font>");
  629:                 &logperm("D:$server:$cmd");
  630: 	        return 'con_delayed';
  631:             } else {
  632:                 &logthis("<font color=\"red\">CRITICAL:"
  633:                         ." Critical connection failed: $server $cmd</font>");
  634:                 &logperm("F:$server:$cmd");
  635:                 return 'con_failed';
  636:             }
  637:         }
  638:     }
  639:     return $answer;
  640: }
  641: 
  642: # ------------------------------------------- check if return value is an error
  643: 
  644: sub error {
  645:     my ($result) = @_;
  646:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  647: 	if ($2 == 2) { return undef; }
  648: 	return $1;
  649:     }
  650:     return undef;
  651: }
  652: 
  653: sub convert_and_load_session_env {
  654:     my ($lonidsdir,$handle)=@_;
  655:     my @profile;
  656:     {
  657: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  658: 	if (!$opened) {
  659: 	    return 0;
  660: 	}
  661: 	flock($idf,LOCK_SH);
  662: 	@profile=<$idf>;
  663: 	close($idf);
  664:     }
  665:     my %temp_env;
  666:     foreach my $line (@profile) {
  667: 	if ($line !~ m/=/) {
  668: 	    return 0;
  669: 	}
  670: 	chomp($line);
  671: 	my ($envname,$envvalue)=split(/=/,$line,2);
  672: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  673:     }
  674:     unlink("$lonidsdir/$handle.id");
  675:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  676: 	    0640)) {
  677: 	%disk_env = %temp_env;
  678: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  679: 	untie(%disk_env);
  680:     }
  681:     return 1;
  682: }
  683: 
  684: # ------------------------------------------- Transfer profile into environment
  685: my $env_loaded;
  686: sub transfer_profile_to_env {
  687:     my ($lonidsdir,$handle,$force_transfer) = @_;
  688:     if (!$force_transfer && $env_loaded) { return; } 
  689: 
  690:     if (!defined($lonidsdir)) {
  691: 	$lonidsdir = $perlvar{'lonIDsDir'};
  692:     }
  693:     if (!defined($handle)) {
  694:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  695:     }
  696: 
  697:     my $convert;
  698:     {
  699:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  700: 	if (!$opened) {
  701: 	    return;
  702: 	}
  703: 	flock($idf,LOCK_SH);
  704: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  705: 		&GDBM_READER(),0640)) {
  706: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  707: 	    untie(%disk_env);
  708: 	} else {
  709: 	    $convert = 1;
  710: 	}
  711:     }
  712:     if ($convert) {
  713: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  714: 	    &logthis("Failed to load session, or convert session.");
  715: 	}
  716:     }
  717: 
  718:     my %remove;
  719:     while ( my $envname = each(%env) ) {
  720:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  721:             if ($time < time-300) {
  722:                 $remove{$key}++;
  723:             }
  724:         }
  725:     }
  726: 
  727:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  728:     $env_loaded=1;
  729:     foreach my $expired_key (keys(%remove)) {
  730:         &delenv($expired_key);
  731:     }
  732: }
  733: 
  734: # ---------------------------------------------------- Check for valid session 
  735: sub check_for_valid_session {
  736:     my ($r,$name,$userhashref,$domref) = @_;
  737:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  738:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  739:     if ($name eq 'lonDAV') {
  740:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  741:     } else {
  742:         $lonidsdir=$r->dir_config('lonIDsDir');
  743:         if ($name eq '') {
  744:             $name = 'lonID';
  745:         }
  746:     }
  747:     if ($name eq 'lonID') {
  748:         $secure = 'lonSID';
  749:         $linkname = 'lonLinkID';
  750:         $pubname = 'lonPubID';
  751:         if (exists($cookies{$secure})) {
  752:             $lonid=$cookies{$secure};
  753:         } elsif (exists($cookies{$name})) {
  754:             $lonid=$cookies{$name};
  755:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  756:             $lonid=$cookies{$linkname};
  757:         } elsif (exists($cookies{$pubname})) {
  758:             $lonid=$cookies{$pubname};
  759:         }
  760:     } else {
  761:         $lonid=$cookies{$name};
  762:     }
  763:     return undef if (!$lonid);
  764: 
  765:     my $handle=&LONCAPA::clean_handle($lonid->value);
  766:     if (-l "$lonidsdir/$handle.id") {
  767:         my $link = readlink("$lonidsdir/$handle.id");
  768:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  769:             $handle = $1;
  770:         }
  771:     }
  772:     if (!-e "$lonidsdir/$handle.id") {
  773:         if ((ref($domref)) && ($name eq 'lonID') && 
  774:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  775:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  776:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  777:                 $$domref = $possudom;
  778:             }
  779:         }
  780:         return undef;
  781:     }
  782: 
  783:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  784:     return undef if (!$opened);
  785: 
  786:     flock($idf,LOCK_SH);
  787:     my %disk_env;
  788:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  789: 	    &GDBM_READER(),0640)) {
  790: 	return undef;	
  791:     }
  792: 
  793:     if (!defined($disk_env{'user.name'})
  794: 	|| !defined($disk_env{'user.domain'})) {
  795:         untie(%disk_env);
  796: 	return undef;
  797:     }
  798: 
  799:     if (ref($userhashref) eq 'HASH') {
  800:         $userhashref->{'name'} = $disk_env{'user.name'};
  801:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  802:         if ($disk_env{'request.role'}) {
  803:             $userhashref->{'role'} = $disk_env{'request.role'};
  804:         }
  805:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  806:         if ($userhashref->{'lti'}) {
  807:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
  808:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
  809:         }
  810:     }
  811:     untie(%disk_env);
  812: 
  813:     return $handle;
  814: }
  815: 
  816: sub timed_flock {
  817:     my ($file,$lock_type) = @_;
  818:     my $failed=0;
  819:     eval {
  820: 	local $SIG{__DIE__}='DEFAULT';
  821: 	local $SIG{ALRM}=sub {
  822: 	    $failed=1;
  823: 	    die("failed lock");
  824: 	};
  825: 	alarm(13);
  826: 	flock($file,$lock_type);
  827: 	alarm(0);
  828:     };
  829:     if ($failed) {
  830: 	return undef;
  831:     } else {
  832: 	return 1;
  833:     }
  834: }
  835: 
  836: sub get_sessionfile_vars {
  837:     my ($handle,$lonidsdir,$storearr) = @_;
  838:     my %returnhash;
  839:     unless (ref($storearr) eq 'ARRAY') {
  840:         return %returnhash;
  841:     }
  842:     if (-l "$lonidsdir/$handle.id") {
  843:         my $link = readlink("$lonidsdir/$handle.id");
  844:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  845:             $handle = $1;
  846:         }
  847:     }
  848:     if ((-e "$lonidsdir/$handle.id") &&
  849:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  850:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  851:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  852:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  853:                 flock($idf,LOCK_SH);
  854:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  855:                         &GDBM_READER(),0640)) {
  856:                     foreach my $item (@{$storearr}) {
  857:                         $returnhash{$item} = $disk_env{$item};
  858:                     }
  859:                     untie(%disk_env);
  860:                 }
  861:             }
  862:         }
  863:     }
  864:     return %returnhash;
  865: }
  866: 
  867: # ---------------------------------------------------------- Append Environment
  868: 
  869: sub appenv {
  870:     my ($newenv,$roles) = @_;
  871:     if (ref($newenv) eq 'HASH') {
  872:         foreach my $key (keys(%{$newenv})) {
  873:             my $refused = 0;
  874: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  875:                 $refused = 1;
  876:                 if (ref($roles) eq 'ARRAY') {
  877:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  878:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  879:                         $refused = 0;
  880:                     }
  881:                 }
  882:             }
  883:             if ($refused) {
  884:                 &logthis("<font color=\"blue\">WARNING: ".
  885:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  886:                          .'</font>');
  887: 	        delete($newenv->{$key});
  888:             } else {
  889:                 $env{$key}=$newenv->{$key};
  890:             }
  891:         }
  892:         my $lonids = $perlvar{'lonIDsDir'};
  893:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  894:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  895:             if ($opened
  896: 	        && &timed_flock($env_file,LOCK_EX)
  897: 	        &&
  898: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  899: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  900: 	        while (my ($key,$value) = each(%{$newenv})) {
  901: 	            $disk_env{$key} = $value;
  902: 	        }
  903: 	        untie(%disk_env);
  904:             }
  905:         }
  906:     }
  907:     return 'ok';
  908: }
  909: # ----------------------------------------------------- Delete from Environment
  910: 
  911: sub delenv {
  912:     my ($delthis,$regexp,$roles) = @_;
  913:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  914:         my $refused = 1;
  915:         if (ref($roles) eq 'ARRAY') {
  916:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  917:             if (grep(/^\Q$role\E$/,@{$roles})) {
  918:                 $refused = 0;
  919:             }
  920:         }
  921:         if ($refused) {
  922:             &logthis("<font color=\"blue\">WARNING: ".
  923:                      "Attempt to delete from environment ".$delthis);
  924:             return 'error';
  925:         }
  926:     }
  927:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  928:     if ($opened
  929: 	&& &timed_flock($env_file,LOCK_EX)
  930: 	&&
  931: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  932: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  933: 	foreach my $key (keys(%disk_env)) {
  934: 	    if ($regexp) {
  935:                 if ($key=~/^$delthis/) {
  936:                     delete($env{$key});
  937:                     delete($disk_env{$key});
  938:                 } 
  939:             } else {
  940:                 if ($key=~/^\Q$delthis\E/) {
  941: 		    delete($env{$key});
  942: 		    delete($disk_env{$key});
  943: 	        }
  944:             }
  945: 	}
  946: 	untie(%disk_env);
  947:     }
  948:     return 'ok';
  949: }
  950: 
  951: sub get_env_multiple {
  952:     my ($name) = @_;
  953:     my @values;
  954:     if (defined($env{$name})) {
  955:         # exists is it an array
  956:         if (ref($env{$name})) {
  957:             @values=@{ $env{$name} };
  958:         } else {
  959:             $values[0]=$env{$name};
  960:         }
  961:     }
  962:     return(@values);
  963: }
  964: 
  965: # ------------------------------------------------------------------- Locking
  966: 
  967: sub set_lock {
  968:     my ($text)=@_;
  969:     $locknum++;
  970:     my $id=$$.'-'.$locknum;
  971:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  972:              'session.lock.'.$id => $text});
  973:     return $id;
  974: }
  975: 
  976: sub get_locks {
  977:     my $num=0;
  978:     my %texts=();
  979:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  980:        if ($lock=~/\w/) {
  981:           $num++;
  982:           $texts{$lock}=$env{'session.lock.'.$lock};
  983:        }
  984:    }
  985:    return ($num,%texts);
  986: }
  987: 
  988: sub remove_lock {
  989:     my ($id)=@_;
  990:     my $newlocks='';
  991:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  992:        if (($lock=~/\w/) && ($lock ne $id)) {
  993:           $newlocks.=','.$lock;
  994:        }
  995:     }
  996:     &appenv({'session.locks' => $newlocks});
  997:     &delenv('session.lock.'.$id);
  998: }
  999: 
 1000: sub remove_all_locks {
 1001:     my $activelocks=$env{'session.locks'};
 1002:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
 1003:        if ($lock=~/\w/) {
 1004:           &remove_lock($lock);
 1005:        }
 1006:     }
 1007: }
 1008: 
 1009: 
 1010: # ------------------------------------------ Find out current server userload
 1011: sub userload {
 1012:     my $numusers=0;
 1013:     {
 1014: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
 1015: 	my $filename;
 1016: 	my $curtime=time;
 1017: 	while ($filename=readdir(LONIDS)) {
 1018: 	    next if ($filename eq '.' || $filename eq '..');
 1019: 	    next if ($filename =~ /publicuser_\d+\.id/);
 1020:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
 1021: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
 1022: 	    if ($curtime-$mtime < 1800) { $numusers++; }
 1023: 	}
 1024: 	closedir(LONIDS);
 1025:     }
 1026:     my $userloadpercent=0;
 1027:     my $maxuserload=$perlvar{'lonUserLoadLim'};
 1028:     if ($maxuserload) {
 1029: 	$userloadpercent=100*$numusers/$maxuserload;
 1030:     }
 1031:     $userloadpercent=sprintf("%.2f",$userloadpercent);
 1032:     return $userloadpercent;
 1033: }
 1034: 
 1035: # ------------------------------ Find server with least workload from spare.tab
 1036: 
 1037: sub spareserver {
 1038:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
 1039:     my $spare_server;
 1040:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
 1041:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
 1042:                                                      :  $userloadpercent;
 1043:     my ($uint_dom,$remotesessions);
 1044:     if (($udom ne '') && (&domain($udom) ne '')) {
 1045:         my $uprimary_id = &domain($udom,'primary');
 1046:         $uint_dom = &internet_dom($uprimary_id);
 1047:         my %udomdefaults = &get_domain_defaults($udom);
 1048:         $remotesessions = $udomdefaults{'remotesessions'};
 1049:     }
 1050:     my $spareshash = &this_host_spares($udom);
 1051:     if (ref($spareshash) eq 'HASH') {
 1052:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1053:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1054:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
 1055:                                              $try_server));
 1056: 	        ($spare_server, $lowest_load) =
 1057: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
 1058:             }
 1059:         }
 1060: 
 1061:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
 1062: 
 1063:         if (!$found_server) {
 1064:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
 1065: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
 1066:                     next unless (&spare_can_host($udom,$uint_dom,
 1067:                                                  $remotesessions,$try_server));
 1068: 	            ($spare_server, $lowest_load) =
 1069: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
 1070:                 }
 1071: 	    }
 1072:         }
 1073:     }
 1074: 
 1075:     if (!$want_server_name) {
 1076:         if (defined($spare_server)) {
 1077:             my $hostname = &hostname($spare_server);
 1078:             if (defined($hostname)) {
 1079:                 my $protocol = 'http';
 1080:                 if ($protocol{$spare_server} eq 'https') {
 1081:                     $protocol = $protocol{$spare_server};
 1082:                 }
 1083:                 my $alias = &use_proxy_alias($r,$spare_server);
 1084:                 $hostname = $alias if ($alias ne '');
 1085: 	        $spare_server = $protocol.'://'.$hostname;
 1086:             }
 1087:         }
 1088:     }
 1089:     return $spare_server;
 1090: }
 1091: 
 1092: sub compare_server_load {
 1093:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
 1094: 
 1095:     if ($required) {
 1096:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
 1097:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1098:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 1099:         if (($major eq '' && $minor eq '') ||
 1100:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
 1101:             return ($spare_server,$lowest_load);
 1102:         }
 1103:     }
 1104: 
 1105:     my $loadans     = &reply('load',    $try_server);
 1106:     my $userloadans = &reply('userload',$try_server);
 1107: 
 1108:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
 1109: 	return ($spare_server, $lowest_load); #didn't get a number from the server
 1110:     }
 1111: 
 1112:     my $load;
 1113:     if ($loadans =~ /\d/) {
 1114: 	if ($userloadans =~ /\d/) {
 1115: 	    #both are numbers, pick the bigger one
 1116: 	    $load = ($loadans > $userloadans) ? $loadans 
 1117: 		                              : $userloadans;
 1118: 	} else {
 1119: 	    $load = $loadans;
 1120: 	}
 1121:     } else {
 1122: 	$load = $userloadans;
 1123:     }
 1124: 
 1125:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1126: 	$spare_server = $try_server;
 1127: 	$lowest_load  = $load;
 1128:     }
 1129:     return ($spare_server,$lowest_load);
 1130: }
 1131: 
 1132: # --------------------------- ask offload servers if user already has a session
 1133: sub find_existing_session {
 1134:     my ($udom,$uname) = @_;
 1135:     my $spareshash = &this_host_spares($udom);
 1136:     if (ref($spareshash) eq 'HASH') {
 1137:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1138:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1139:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1140:             }
 1141:         }
 1142:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1143:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1144:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1145:             }
 1146:         }
 1147:     }
 1148:     return;
 1149: }
 1150: 
 1151: sub delusersession {
 1152:     my ($lonid,$udom,$uname) = @_;
 1153:     my $uprimary_id = &domain($udom,'primary');
 1154:     my $uintdom = &internet_dom($uprimary_id);
 1155:     my $intdom = &internet_dom($lonid);
 1156:     my $serverhomedom = &host_domain($lonid);
 1157:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1158:         return &reply(join(':','delusersession',
 1159:                             map {&escape($_)} ($udom,$uname)),$lonid);
 1160:     }
 1161:     return;
 1162: }
 1163: 
 1164: # check if user's browser sent load balancer cookie and server still has session
 1165: # and is not overloaded.
 1166: sub check_for_balancer_cookie {
 1167:     my ($r,$update_mtime) = @_;
 1168:     my ($otherserver,$cookie);
 1169:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1170:     if (exists($cookies{'balanceID'})) {
 1171:         my $balid = $cookies{'balanceID'};
 1172:         $cookie=&LONCAPA::clean_handle($balid->value);
 1173:         my $balancedir=$r->dir_config('lonBalanceDir');
 1174:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1175:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1176:                 my ($possudom,$possuname) = ($1,$2);
 1177:                 my $has_session = 0;
 1178:                 if ((&domain($possudom) ne '') &&
 1179:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1180:                     my $try_server;
 1181:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1182:                     if ($opened) {
 1183:                         flock($idf,LOCK_SH);
 1184:                         while (my $line = <$idf>) {
 1185:                             chomp($line);
 1186:                             if (&hostname($line) ne '') {
 1187:                                 $try_server = $line;
 1188:                                 last;
 1189:                             }
 1190:                         }
 1191:                         close($idf);
 1192:                         if (($try_server) &&
 1193:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1194:                             my $lowest_load = 30000;
 1195:                             ($otherserver,$lowest_load) =
 1196:                                 &compare_server_load($try_server,undef,$lowest_load);
 1197:                             if ($otherserver ne '' && $lowest_load < 100) {
 1198:                                 $has_session = 1;
 1199:                             } else {
 1200:                                 undef($otherserver);
 1201:                             }
 1202:                         }
 1203:                     }
 1204:                 }
 1205:                 if ($has_session) {
 1206:                     if ($update_mtime) {
 1207:                         my $atime = my $mtime = time;
 1208:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1209:                     }
 1210:                 } else {
 1211:                     unlink("$balancedir/$cookie.id");
 1212:                 }
 1213:             }
 1214:         }
 1215:     }
 1216:     return ($otherserver,$cookie);
 1217: }
 1218: 
 1219: sub updatebalcookie {
 1220:     my ($cookie,$balancer,$lastentry)=@_;
 1221:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1222:         my ($udom,$uname) = ($1,$2);
 1223:         my $uprimary_id = &domain($udom,'primary');
 1224:         my $uintdom = &internet_dom($uprimary_id);
 1225:         my $intdom = &internet_dom($balancer);
 1226:         my $serverhomedom = &host_domain($balancer);
 1227:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1228:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
 1229:         }
 1230:     }
 1231:     return;
 1232: }
 1233: 
 1234: sub delbalcookie {
 1235:     my ($cookie,$balancer) =@_;
 1236:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1237:         my ($udom,$uname) = ($1,$2);
 1238:         my $uprimary_id = &domain($udom,'primary');
 1239:         my $uintdom = &internet_dom($uprimary_id);
 1240:         my $intdom = &internet_dom($balancer);
 1241:         my $serverhomedom = &host_domain($balancer);
 1242:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1243:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
 1244:         }
 1245:     }
 1246: }
 1247: 
 1248: # -------------------------------- ask if server already has a session for user
 1249: sub has_user_session {
 1250:     my ($lonid,$udom,$uname) = @_;
 1251:     my $result = &reply(join(':','userhassession',
 1252: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1253:     return 1 if ($result eq 'ok');
 1254: 
 1255:     return 0;
 1256: }
 1257: 
 1258: # --------- determine least loaded server in a user's domain which allows login
 1259: 
 1260: sub choose_server {
 1261:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1262:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1263:     my %servers = &get_servers($udom);
 1264:     my $lowest_load = 30000;
 1265:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1266:     if ($skiploadbal) {
 1267:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1268:         unless (defined($cached)) {
 1269:             my $cachetime = 60*60*24;
 1270:             my %domconfig =
 1271:                 &get_dom('configuration',['loadbalancing'],$udom);
 1272:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1273:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1274:                                            $cachetime);
 1275:             }
 1276:         }
 1277:     }
 1278:     foreach my $lonhost (keys(%servers)) {
 1279:         if ($skiploadbal) {
 1280:             if (ref($balancers) eq 'HASH') {
 1281:                 next if (exists($balancers->{$lonhost}));
 1282:             }
 1283:         }
 1284:         my $loginvia;
 1285:         if ($checkloginvia) {
 1286:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1287:             if ($loginvia) {
 1288:                 my ($server,$path) = split(/:/,$loginvia);
 1289:                 ($login_host, $lowest_load) =
 1290:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1291:                 if ($login_host eq $server) {
 1292:                     $portal_path = $path;
 1293:                     $isredirect = 1;
 1294:                 }
 1295:             } else {
 1296:                 ($login_host, $lowest_load) =
 1297:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1298:                 if ($login_host eq $lonhost) {
 1299:                     $portal_path = '';
 1300:                     $isredirect = ''; 
 1301:                 }
 1302:             }
 1303:         } else {
 1304:             ($login_host, $lowest_load) =
 1305:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1306:         }
 1307:     }
 1308:     if ($login_host ne '') {
 1309:         $hostname = &hostname($login_host);
 1310:     }
 1311:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1312: }
 1313: 
 1314: sub get_course_sessions {
 1315:     my ($cnum,$cdom,$lastactivity) = @_;
 1316:     my %servers = &internet_dom_servers($cdom);
 1317:     my %returnhash;
 1318:     foreach my $server (sort(keys(%servers))) {
 1319:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1320:         my @pairs=split(/\&/,$rep);
 1321:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1322:             foreach my $item (@pairs) {
 1323:                 my ($key,$value)=split(/=/,$item,2);
 1324:                 $key = &unescape($key);
 1325:                 next if ($key =~ /^error: 2 /);
 1326:                 if (exists($returnhash{$key})) {
 1327:                     next if ($value < $returnhash{$key});
 1328:                 }
 1329:                 $returnhash{$key}=$value;
 1330:             }
 1331:         }
 1332:     }
 1333:     return %returnhash;
 1334: }
 1335: 
 1336: # --------------------------------------------- Try to change a user's password
 1337: 
 1338: sub changepass {
 1339:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1340:     $currentpass = &escape($currentpass);
 1341:     $newpass     = &escape($newpass);
 1342:     my $lonhost = $perlvar{'lonHostID'};
 1343:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1344: 		       $server);
 1345:     if (! $answer) {
 1346: 	&logthis("No reply on password change request to $server ".
 1347: 		 "by $uname in domain $udom.");
 1348:     } elsif ($answer =~ "^ok") {
 1349:         &logthis("$uname in $udom successfully changed their password ".
 1350: 		 "on $server.");
 1351:     } elsif ($answer =~ "^pwchange_failure") {
 1352: 	&logthis("$uname in $udom was unable to change their password ".
 1353: 		 "on $server.  The action was blocked by either lcpasswd ".
 1354: 		 "or pwchange");
 1355:     } elsif ($answer =~ "^non_authorized") {
 1356:         &logthis("$uname in $udom did not get their password correct when ".
 1357: 		 "attempting to change it on $server.");
 1358:     } elsif ($answer =~ "^auth_mode_error") {
 1359:         &logthis("$uname in $udom attempted to change their password despite ".
 1360: 		 "not being locally or internally authenticated on $server.");
 1361:     } elsif ($answer =~ "^unknown_user") {
 1362:         &logthis("$uname in $udom attempted to change their password ".
 1363: 		 "on $server but were unable to because $server is not ".
 1364: 		 "their home server.");
 1365:     } elsif ($answer =~ "^refused") {
 1366: 	&logthis("$server refused to change $uname in $udom password because ".
 1367: 		 "it was sent an unencrypted request to change the password.");
 1368:     } elsif ($answer =~ "invalid_client") {
 1369:         &logthis("$server refused to change $uname in $udom password because ".
 1370:                  "it was a reset by e-mail originating from an invalid server.");
 1371:     } elsif ($answer =~ "^prioruse") {
 1372:        &logthis("$server refused to change $uname in $udom password because ".
 1373:                 "the password had been used before");
 1374:     }
 1375:     return $answer;
 1376: }
 1377: 
 1378: # ----------------------- Try to determine user's current authentication scheme
 1379: 
 1380: sub queryauthenticate {
 1381:     my ($uname,$udom)=@_;
 1382:     my $uhome=&homeserver($uname,$udom);
 1383:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1384: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1385: 	return 'no_host';
 1386:     }
 1387:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1388:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1389: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1390:     }
 1391:     return $answer;
 1392: }
 1393: 
 1394: # --------- Try to authenticate user from domain's lib servers (first this one)
 1395: 
 1396: sub authenticate {
 1397:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1398:     $upass=&escape($upass);
 1399:     $uname= &LONCAPA::clean_username($uname);
 1400:     my $uhome=&homeserver($uname,$udom,1);
 1401:     my $newhome;
 1402:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1403: # Maybe the machine was offline and only re-appeared again recently?
 1404:         &reconlonc();
 1405: # One more
 1406: 	$uhome=&homeserver($uname,$udom,1);
 1407:         if (($uhome eq 'no_host') && $checkdefauth) {
 1408:             if (defined(&domain($udom,'primary'))) {
 1409:                 $newhome=&domain($udom,'primary');
 1410:             }
 1411:             if ($newhome ne '') {
 1412:                 $uhome = $newhome;
 1413:             }
 1414:         }
 1415: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1416: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1417: 	    return 'no_host';
 1418:         }
 1419:     }
 1420:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1421:     if ($answer eq 'authorized') {
 1422:         if ($newhome) {
 1423:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1424:             return 'no_account_on_host'; 
 1425:         } else {
 1426:             &logthis("User $uname at $udom authorized by $uhome");
 1427:             return $uhome;
 1428:         }
 1429:     }
 1430:     if ($answer eq 'non_authorized') {
 1431: 	&logthis("User $uname at $udom rejected by $uhome");
 1432: 	return 'no_host';
 1433:     }
 1434:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1435:     return 'no_host';
 1436: }
 1437: 
 1438: sub can_switchserver {
 1439:     my ($udom,$home) = @_;
 1440:     my ($canswitch,@intdoms);
 1441:     my $internet_names = &get_internet_names($home);
 1442:     if (ref($internet_names) eq 'ARRAY') {
 1443:         @intdoms = @{$internet_names};
 1444:     }
 1445:     my $uint_dom = &internet_dom(&domain($udom,'primary'));
 1446:     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1447:         $canswitch = 1;
 1448:     } else {
 1449:          my $serverhomeID = &get_server_homeID(&hostname($home));
 1450:          my $serverhomedom = &host_domain($serverhomeID);
 1451:          my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1452:          my %udomdefaults = &get_domain_defaults($udom);
 1453:          my $remoterev = &get_server_loncaparev('',$home);
 1454:          $canswitch = &can_host_session($udom,$home,$remoterev,
 1455:                                         $udomdefaults{'remotesessions'},
 1456:                                         $defdomdefaults{'hostedsessions'});
 1457:     }
 1458:     return $canswitch;
 1459: }
 1460: 
 1461: sub can_host_session {
 1462:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1463:     my $canhost = 1;
 1464:     my $host_idn = &internet_dom($lonhost);
 1465:     if (ref($remotesessions) eq 'HASH') {
 1466:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1467:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1468:                 $canhost = 0;
 1469:             } else {
 1470:                 $canhost = 1;
 1471:             }
 1472:         }
 1473:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1474:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1475:                 $canhost = 1;
 1476:             } else {
 1477:                 $canhost = 0;
 1478:             }
 1479:         }
 1480:         if ($canhost) {
 1481:             if ($remotesessions->{'version'} ne '') {
 1482:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1483:                 if ($reqmajor ne '' && $reqminor ne '') {
 1484:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1485:                         my $major = $1;
 1486:                         my $minor = $2;
 1487:                         if (($major < $reqmajor ) ||
 1488:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1489:                             $canhost = 0;
 1490:                         }
 1491:                     } else {
 1492:                         $canhost = 0;
 1493:                     }
 1494:                 }
 1495:             }
 1496:         }
 1497:     }
 1498:     if ($canhost) {
 1499:         if (ref($hostedsessions) eq 'HASH') {
 1500:             my $uprimary_id = &domain($udom,'primary');
 1501:             my $uint_dom = &internet_dom($uprimary_id);
 1502:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1503:                 if (($uint_dom ne '') && 
 1504:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1505:                     $canhost = 0;
 1506:                 } else {
 1507:                     $canhost = 1;
 1508:                 }
 1509:             }
 1510:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1511:                 if (($uint_dom ne '') && 
 1512:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1513:                     $canhost = 1;
 1514:                 } else {
 1515:                     $canhost = 0;
 1516:                 }
 1517:             }
 1518:         }
 1519:     }
 1520:     return $canhost;
 1521: }
 1522: 
 1523: sub spare_can_host {
 1524:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1525:     my $canhost=1;
 1526:     my $try_server_hostname = &hostname($try_server);
 1527:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1528:     my $serverhomedom = &host_domain($serverhomeID);
 1529:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1530:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1531:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1532:             $canhost = 0;
 1533:         }
 1534:     }
 1535:     if ($canhost) {
 1536:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
 1537:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
 1538:                 unless (&shared_institution($udom,$try_server)) {
 1539:                     $canhost = 0;
 1540:                 }
 1541:             }
 1542:         }
 1543:     }
 1544:     if (($canhost) && ($uint_dom)) {
 1545:         my @intdoms;
 1546:         my $internet_names = &get_internet_names($try_server);
 1547:         if (ref($internet_names) eq 'ARRAY') {
 1548:             @intdoms = @{$internet_names};
 1549:         }
 1550:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1551:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1552:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1553:                                          $remotesessions,
 1554:                                          $defdomdefaults{'hostedsessions'});
 1555:         }
 1556:     }
 1557:     return $canhost;
 1558: }
 1559: 
 1560: sub this_host_spares {
 1561:     my ($dom) = @_;
 1562:     my ($dom_in_use,$lonhost_in_use,$result);
 1563:     my @hosts = &current_machine_ids();
 1564:     foreach my $lonhost (@hosts) {
 1565:         if (&host_domain($lonhost) eq $dom) {
 1566:             $dom_in_use = $dom;
 1567:             $lonhost_in_use = $lonhost;
 1568:             last;
 1569:         }
 1570:     }
 1571:     if ($dom_in_use ne '') {
 1572:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1573:     }
 1574:     if (ref($result) ne 'HASH') {
 1575:         $lonhost_in_use = $perlvar{'lonHostID'};
 1576:         $dom_in_use = &host_domain($lonhost_in_use);
 1577:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1578:         if (ref($result) ne 'HASH') {
 1579:             $result = \%spareid;
 1580:         }
 1581:     }
 1582:     return $result;
 1583: }
 1584: 
 1585: sub spares_for_offload  {
 1586:     my ($dom_in_use,$lonhost_in_use) = @_;
 1587:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1588:     if (defined($cached)) {
 1589:         return $result;
 1590:     } else {
 1591:         my $cachetime = 60*60*24;
 1592:         my %domconfig =
 1593:             &get_dom('configuration',['usersessions'],$dom_in_use);
 1594:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1595:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1596:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1597:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1598:                 }
 1599:             }
 1600:         }
 1601:     }
 1602:     return;
 1603: }
 1604: 
 1605: sub get_lonbalancer_config {
 1606:     my ($servers) = @_;
 1607:     my ($currbalancer,$currtargets);
 1608:     if (ref($servers) eq 'HASH') {
 1609:         foreach my $server (keys(%{$servers})) {
 1610:             my %what = (
 1611:                          spareid => 1,
 1612:                          perlvar => 1,
 1613:                        );
 1614:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1615:             if ($result eq 'ok') {
 1616:                 if (ref($returnhash) eq 'HASH') {
 1617:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1618:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1619:                             $currbalancer = $server;
 1620:                             $currtargets = {};
 1621:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1622:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1623:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1624:                                 }
 1625:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1626:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1627:                                 }
 1628:                             }
 1629:                             last;
 1630:                         }
 1631:                     }
 1632:                 }
 1633:             }
 1634:         }
 1635:     }
 1636:     return ($currbalancer,$currtargets);
 1637: }
 1638: 
 1639: sub check_loadbalancing {
 1640:     my ($uname,$udom,$caller) = @_;
 1641:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1642:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
 1643:     my $lonhost = $perlvar{'lonHostID'};
 1644:     my @hosts = &current_machine_ids();
 1645:     my $uprimary_id = &domain($udom,'primary');
 1646:     my $uintdom = &internet_dom($uprimary_id);
 1647:     my $intdom = &internet_dom($lonhost);
 1648:     my $serverhomedom = &host_domain($lonhost);
 1649:     my $domneedscache;
 1650:     my $cachetime = 60*60*24;
 1651: 
 1652:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1653:         $dom_in_use = $udom;
 1654:         $homeintdom = 1;
 1655:     } else {
 1656:         $dom_in_use = $serverhomedom;
 1657:     }
 1658:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1659:     unless (defined($cached)) {
 1660:         my %domconfig =
 1661:             &get_dom('configuration',['loadbalancing'],$dom_in_use);
 1662:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1663:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1664:         } else {
 1665:             $domneedscache = $dom_in_use;
 1666:         }
 1667:     }
 1668:     if (ref($result) eq 'HASH') {
 1669:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1670:             &check_balancer_result($result,@hosts);
 1671:         if ($is_balancer) {
 1672:             if (ref($currrules) eq 'HASH') {
 1673:                 if ($homeintdom) {
 1674:                     if ($uname ne '') {
 1675:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1676:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1677:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1678:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1679:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1680:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1681:                             }
 1682:                         }
 1683:                         if ($rule_in_effect eq '') {
 1684:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1685:                             if ($userenv{'inststatus'} ne '') {
 1686:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1687:                                 my ($othertitle,$usertypes,$types) =
 1688:                                     &Apache::loncommon::sorted_inst_types($udom);
 1689:                                 if (ref($types) eq 'ARRAY') {
 1690:                                     foreach my $type (@{$types}) {
 1691:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1692:                                             if (exists($currrules->{$type})) {
 1693:                                                 $rule_in_effect = $currrules->{$type};
 1694:                                             }
 1695:                                         }
 1696:                                     }
 1697:                                 }
 1698:                             } else {
 1699:                                 if (exists($currrules->{'default'})) {
 1700:                                     $rule_in_effect = $currrules->{'default'};
 1701:                                 }
 1702:                             }
 1703:                         }
 1704:                     } else {
 1705:                         if (exists($currrules->{'default'})) {
 1706:                             $rule_in_effect = $currrules->{'default'};
 1707:                         }
 1708:                     }
 1709:                 } else {
 1710:                     if ($currrules->{'_LC_external'} ne '') {
 1711:                         $rule_in_effect = $currrules->{'_LC_external'};
 1712:                     }
 1713:                 }
 1714:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1715:                                                        $uname,$udom);
 1716:             }
 1717:         }
 1718:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1719:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1720:         unless (defined($cached)) {
 1721:             my %domconfig =
 1722:                 &get_dom('configuration',['loadbalancing'],$serverhomedom);
 1723:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1724:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1725:             } else {
 1726:                 $domneedscache = $serverhomedom;
 1727:             }
 1728:         }
 1729:         if (ref($result) eq 'HASH') {
 1730:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
 1731:                 &check_balancer_result($result,@hosts);
 1732:             if ($is_balancer) {
 1733:                 if (ref($currrules) eq 'HASH') {
 1734:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1735:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1736:                     }
 1737:                 }
 1738:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1739:                                                        $uname,$udom);
 1740:             }
 1741:         } else {
 1742:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1743:                 $is_balancer = 1;
 1744:                 $offloadto = &this_host_spares($dom_in_use);
 1745:             }
 1746:             unless (defined($cached)) {
 1747:                 $domneedscache = $serverhomedom;
 1748:             }
 1749:         }
 1750:     } else {
 1751:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1752:             $is_balancer = 1;
 1753:             $offloadto = &this_host_spares($dom_in_use);
 1754:         }
 1755:         unless (defined($cached)) {
 1756:             $domneedscache = $serverhomedom;
 1757:         }
 1758:     }
 1759:     if ($domneedscache) {
 1760:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1761:     }
 1762:     if (($is_balancer) && ($caller ne 'switchserver')) {
 1763:         my $lowest_load = 30000;
 1764:         if (ref($offloadto) eq 'HASH') {
 1765:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1766:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1767:                     ($otherserver,$lowest_load) =
 1768:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1769:                 }
 1770:             }
 1771:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1772: 
 1773:             if (!$found_server) {
 1774:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1775:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1776:                         ($otherserver,$lowest_load) =
 1777:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1778:                     }
 1779:                 }
 1780:             }
 1781:         } elsif (ref($offloadto) eq 'ARRAY') {
 1782:             if (@{$offloadto} == 1) {
 1783:                 $otherserver = $offloadto->[0];
 1784:             } elsif (@{$offloadto} > 1) {
 1785:                 foreach my $try_server (@{$offloadto}) {
 1786:                     ($otherserver,$lowest_load) =
 1787:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1788:                 }
 1789:             }
 1790:         }
 1791:         unless ($caller eq 'login') {
 1792:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1793:                 $is_balancer = 0;
 1794:                 if ($uname ne '' && $udom ne '') {
 1795:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1796:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1797:                                  'user.loadbalcheck.time' => time});
 1798:                     }
 1799:                 }
 1800:             }
 1801:         }
 1802:     }
 1803:     if (($is_balancer) && (!$homeintdom)) {
 1804:         undef($setcookie);
 1805:     }
 1806:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
 1807: }
 1808: 
 1809: sub check_balancer_result {
 1810:     my ($result,@hosts) = @_;
 1811:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1812:     if (ref($result) eq 'HASH') {
 1813:         if ($result->{'lonhost'} ne '') {
 1814:             my $currbalancer = $result->{'lonhost'};
 1815:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1816:                 $is_balancer = 1;
 1817:                 $currtargets = $result->{'targets'};
 1818:                 $currrules = $result->{'rules'};
 1819:             }
 1820:             $dom_balancers = $currbalancer;
 1821:         } else {
 1822:             if (keys(%{$result})) {
 1823:                 foreach my $key (keys(%{$result})) {
 1824:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1825:                         (ref($result->{$key}) eq 'HASH')) {
 1826:                         $is_balancer = 1;
 1827:                         $currrules = $result->{$key}{'rules'};
 1828:                         $currtargets = $result->{$key}{'targets'};
 1829:                         $setcookie = $result->{$key}{'cookie'};
 1830:                         last;
 1831:                     }
 1832:                 }
 1833:                 $dom_balancers = join(',',sort(keys(%{$result})));
 1834:             }
 1835:         }
 1836:     }
 1837:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
 1838: }
 1839: 
 1840: sub get_loadbalancer_targets {
 1841:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1842:     my $offloadto;
 1843:     if ($rule_in_effect eq 'none') {
 1844:         return [$perlvar{'lonHostID'}];
 1845:     } elsif ($rule_in_effect eq '') {
 1846:         $offloadto = $currtargets;
 1847:     } else {
 1848:         if ($rule_in_effect eq 'homeserver') {
 1849:             my $homeserver = &homeserver($uname,$udom);
 1850:             if ($homeserver ne 'no_host') {
 1851:                 $offloadto = [$homeserver];
 1852:             }
 1853:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1854:             my %domconfig =
 1855:                 &get_dom('configuration',['loadbalancing'],$udom);
 1856:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1857:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1858:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1859:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1860:                     }
 1861:                 }
 1862:             } else {
 1863:                 my %servers = &internet_dom_servers($udom);
 1864:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1865:                 if (&hostname($remotebalancer) ne '') {
 1866:                     $offloadto = [$remotebalancer];
 1867:                 }
 1868:             }
 1869:         } elsif (&hostname($rule_in_effect) ne '') {
 1870:             $offloadto = [$rule_in_effect];
 1871:         }
 1872:     }
 1873:     return $offloadto;
 1874: }
 1875: 
 1876: sub internet_dom_servers {
 1877:     my ($dom) = @_;
 1878:     my (%uniqservers,%servers);
 1879:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1880:     my @machinedoms = &machine_domains($primaryserver);
 1881:     foreach my $mdom (@machinedoms) {
 1882:         my %currservers = %servers;
 1883:         my %server = &get_servers($mdom);
 1884:         %servers = (%currservers,%server);
 1885:     }
 1886:     my %by_hostname;
 1887:     foreach my $id (keys(%servers)) {
 1888:         push(@{$by_hostname{$servers{$id}}},$id);
 1889:     }
 1890:     foreach my $hostname (sort(keys(%by_hostname))) {
 1891:         if (@{$by_hostname{$hostname}} > 1) {
 1892:             my $match = 0;
 1893:             foreach my $id (@{$by_hostname{$hostname}}) {
 1894:                 if (&host_domain($id) eq $dom) {
 1895:                     $uniqservers{$id} = $hostname;
 1896:                     $match = 1;
 1897:                 }
 1898:             }
 1899:             unless ($match) {
 1900:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1901:             }
 1902:         } else {
 1903:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1904:         }
 1905:     }
 1906:     return %uniqservers;
 1907: }
 1908: 
 1909: sub trusted_domains {
 1910:     my ($cmdtype,$calldom) = @_;
 1911:     my ($trusted,$untrusted);
 1912:     if (&domain($calldom) eq '') {
 1913:         return ($trusted,$untrusted);
 1914:     }
 1915:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
 1916:         return ($trusted,$untrusted);
 1917:     }
 1918:     my $callprimary = &domain($calldom,'primary');
 1919:     my $intcalldom = &internet_dom($callprimary);
 1920:     if ($intcalldom eq '') {
 1921:         return ($trusted,$untrusted);
 1922:     }
 1923: 
 1924:     my ($trustconfig,$cached)=&is_cached_new('trust',$calldom);
 1925:     unless (defined($cached)) {
 1926:         my %domconfig = &get_dom('configuration',['trust'],$calldom);
 1927:         &do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1928:         $trustconfig = $domconfig{'trust'};
 1929:     }
 1930:     if (ref($trustconfig)) {
 1931:         my (%possexc,%possinc,@allexc,@allinc); 
 1932:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1933:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1934:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1935:             }
 1936:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1937:                 $possinc{$intcalldom} = 1;
 1938:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1939:             }
 1940:         }
 1941:         if (keys(%possexc)) {
 1942:             if (keys(%possinc)) {
 1943:                 foreach my $key (sort(keys(%possexc))) {
 1944:                     next if ($key eq $intcalldom);
 1945:                     unless ($possinc{$key}) {
 1946:                         push(@allexc,$key);
 1947:                     }
 1948:                 }
 1949:             } else {
 1950:                 @allexc = sort(keys(%possexc));
 1951:             }
 1952:         }
 1953:         if (keys(%possinc)) {
 1954:             $possinc{$intcalldom} = 1;
 1955:             @allinc = sort(keys(%possinc));
 1956:         }
 1957:         if ((@allexc > 0) || (@allinc > 0)) {
 1958:             my %doms_by_intdom;
 1959:             my %allintdoms = &all_host_intdom();
 1960:             my %alldoms = &all_host_domain();
 1961:             foreach my $key (%allintdoms) {
 1962:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1963:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1964:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1965:                     }
 1966:                 } else {
 1967:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1968:                 }
 1969:             }
 1970:             foreach my $exc (@allexc) {
 1971:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1972:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
 1973:                 }
 1974:             }
 1975:             foreach my $inc (@allinc) {
 1976:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1977:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
 1978:                 }
 1979:             }
 1980:         }
 1981:     }
 1982:     return ($trusted,$untrusted);
 1983: }
 1984: 
 1985: sub will_trust {
 1986:     my ($cmdtype,$domain,$possdom) = @_;
 1987:     return 1 if ($domain eq $possdom);
 1988:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1989:     my $willtrust; 
 1990:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1991:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1992:             $willtrust = 1;
 1993:         }
 1994:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1995:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1996:             $willtrust = 1;
 1997:         }
 1998:     } else {
 1999:         $willtrust = 1;
 2000:     }
 2001:     return $willtrust;
 2002: }
 2003: 
 2004: # ---------------------- Find the homebase for a user from domain's lib servers
 2005: 
 2006: my %homecache;
 2007: sub homeserver {
 2008:     my ($uname,$udom,$ignoreBadCache)=@_;
 2009:     my $index="$uname:$udom";
 2010: 
 2011:     if (exists($homecache{$index})) { return $homecache{$index}; }
 2012: 
 2013:     my %servers = &get_servers($udom,'library');
 2014:     foreach my $tryserver (keys(%servers)) {
 2015:         next if ($ignoreBadCache ne 'true' && 
 2016: 		 exists($badServerCache{$tryserver}));
 2017: 
 2018: 	my $answer=reply("home:$udom:$uname",$tryserver);
 2019: 	if ($answer eq 'found') {
 2020: 	    delete($badServerCache{$tryserver}); 
 2021: 	    return $homecache{$index}=$tryserver;
 2022: 	} elsif ($answer eq 'no_host') {
 2023: 	    $badServerCache{$tryserver}=1;
 2024: 	}
 2025:     }    
 2026:     return 'no_host';
 2027: }
 2028: 
 2029: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 2030: 
 2031: sub idget {
 2032:     my ($udom,$idsref,$namespace)=@_;
 2033:     my %returnhash=();
 2034:     my @ids=(); 
 2035:     if (ref($idsref) eq 'ARRAY') {
 2036:         @ids = @{$idsref};
 2037:     } else {
 2038:         return %returnhash; 
 2039:     }
 2040:     if ($namespace eq '') {
 2041:         $namespace = 'ids';
 2042:     }
 2043:     
 2044:     my %servers = &get_servers($udom,'library');
 2045:     foreach my $tryserver (keys(%servers)) {
 2046: 	my $idlist=join('&', map { &escape($_); } @ids);
 2047: 	if ($namespace eq 'ids') {
 2048: 	    $idlist=~tr/A-Z/a-z/;
 2049: 	}
 2050: 	my $reply;
 2051: 	if ($namespace eq 'ids') {
 2052: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 2053: 	} else {
 2054: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 2055: 	}
 2056: 	my @answer=();
 2057: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 2058: 	    @answer=split(/\&/,$reply);
 2059: 	}                    ;
 2060: 	my $i;
 2061: 	for ($i=0;$i<=$#ids;$i++) {
 2062: 	    if ($answer[$i]) {
 2063: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 2064: 	    }
 2065: 	}
 2066:     }
 2067:     return %returnhash;
 2068: }
 2069: 
 2070: # ------------------------------------- Find the IDs behind a list of usernames
 2071: 
 2072: sub idrget {
 2073:     my ($udom,@unames)=@_;
 2074:     my %returnhash=();
 2075:     foreach my $uname (@unames) {
 2076:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 2077:     }
 2078:     return %returnhash;
 2079: }
 2080: 
 2081: # Store away a list of names and associated student/employee IDs or clicker IDs
 2082: 
 2083: sub idput {
 2084:     my ($udom,$idsref,$uhom,$namespace)=@_;
 2085:     my %servers=();
 2086:     my %ids=();
 2087:     my %byid = ();
 2088:     if (ref($idsref) eq 'HASH') {
 2089:         %ids=%{$idsref};
 2090:     }
 2091:     if ($namespace eq '') {
 2092:         $namespace = 'ids'; 
 2093:     }
 2094:     foreach my $uname (keys(%ids)) {
 2095: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 2096:         if ($uhom eq '') {
 2097:             $uhom=&homeserver($uname,$udom);
 2098:         }
 2099:         if ($uhom ne 'no_host') {
 2100:             my $esc_unam=&escape($uname);
 2101:             if ($namespace eq 'ids') {
 2102:                 my $id=&escape($ids{$uname});
 2103:                 $id=~tr/A-Z/a-z/;
 2104:                 my $esc_unam=&escape($uname);
 2105:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 2106:             } else {
 2107:                 my @currids = split(/,/,$ids{$uname});
 2108:                 foreach my $id (@currids) {
 2109:                     $byid{$uhom}{$id} .= $uname.',';
 2110:                 }
 2111:             }
 2112:         }
 2113:     }
 2114:     if ($namespace eq 'clickers') {
 2115:         foreach my $server (keys(%byid)) {
 2116:             if (ref($byid{$server}) eq 'HASH') {
 2117:                 foreach my $id (keys(%{$byid{$server}})) {
 2118:                     $byid{$server} =~ s/,$//;
 2119:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 2120:                 }
 2121:             }
 2122:         }
 2123:     }
 2124:     foreach my $server (keys(%servers)) {
 2125:         $servers{$server} =~ s/\&$//;
 2126:         if ($namespace eq 'ids') {     
 2127:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 2128:         } else {
 2129:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 2130:         }
 2131:     }
 2132: }
 2133: 
 2134: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 2135: 
 2136: sub iddel {
 2137:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 2138:     my %result=();
 2139:     my %ids=();
 2140:     my %byid = ();
 2141:     if (ref($idshashref) eq 'HASH') {
 2142:         %ids=%{$idshashref};
 2143:     } else {
 2144:         return %result;
 2145:     }
 2146:     if ($namespace eq '') {
 2147:         $namespace = 'ids';
 2148:     }
 2149:     my %servers=();
 2150:     while (my ($id,$unamestr) = each(%ids)) {
 2151:         if ($namespace eq 'ids') {
 2152:             my $uhom = $uhome;
 2153:             if ($uhom eq '') { 
 2154:                 $uhom=&homeserver($unamestr,$udom);
 2155:             }
 2156:             if ($uhom ne 'no_host') {
 2157:                 $servers{$uhom}.='&'.&escape($id);
 2158:             }
 2159:          } else {
 2160:             my @curritems = split(/,/,$ids{$id});
 2161:             foreach my $uname (@curritems) {
 2162:                 my $uhom = $uhome;
 2163:                 if ($uhom eq '') {
 2164:                     $uhom=&homeserver($uname,$udom);
 2165:                 }
 2166:                 if ($uhom ne 'no_host') { 
 2167:                     $byid{$uhom}{$id} .= $uname.',';
 2168:                 }
 2169:             }
 2170:         }
 2171:     }
 2172:     if ($namespace eq 'clickers') {
 2173:         foreach my $server (keys(%byid)) {
 2174:             if (ref($byid{$server}) eq 'HASH') {
 2175:                 foreach my $id (keys(%{$byid{$server}})) {
 2176:                     $byid{$server}{$id} =~ s/,$//;
 2177:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 2178:                 }
 2179:             }
 2180:         }
 2181:     }
 2182:     foreach my $server (keys(%servers)) {
 2183:         $servers{$server} =~ s/\&$//;
 2184:         if ($namespace eq 'ids') {
 2185:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 2186:         } elsif ($namespace eq 'clickers') {
 2187:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 2188:         }
 2189:     }
 2190:     return %result;
 2191: }
 2192: 
 2193: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 2194: 
 2195: sub updateclickers {
 2196:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 2197:     my %clickers;
 2198:     if (ref($idshashref) eq 'HASH') {
 2199:         %clickers=%{$idshashref};
 2200:     } else {
 2201:         return;
 2202:     }
 2203:     my $items='';
 2204:     foreach my $item (keys(%clickers)) {
 2205:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 2206:     }
 2207:     $items=~s/\&$//;
 2208:     my $request = "updateclickers:$udom:$action:$items";
 2209:     if ($critical) {
 2210:         return &critical($request,$uhome);
 2211:     } else {
 2212:         return &reply($request,$uhome);
 2213:     }
 2214: }
 2215: 
 2216: # ------------------------------dump from db file owned by domainconfig user
 2217: sub dump_dom {
 2218:     my ($namespace, $udom, $regexp) = @_;
 2219: 
 2220:     $udom ||= $env{'user.domain'};
 2221: 
 2222:     return () unless $udom;
 2223: 
 2224:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 2225: }
 2226: 
 2227: # ------------------------------------------ get items from domain db files   
 2228: 
 2229: sub get_dom {
 2230:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
 2231:     return if ($udom eq 'public');
 2232:     my $items='';
 2233:     foreach my $item (@$storearr) {
 2234:         $items.=&escape($item).'&';
 2235:     }
 2236:     $items=~s/\&$//;
 2237:     if (!$udom) {
 2238:         $udom=$env{'user.domain'};
 2239:         return if ($udom eq 'public');
 2240:         if (defined(&domain($udom,'primary'))) {
 2241:             $uhome=&domain($udom,'primary');
 2242:         } else {
 2243:             undef($uhome);
 2244:         }
 2245:     } else {
 2246:         if (!$uhome) {
 2247:             if (defined(&domain($udom,'primary'))) {
 2248:                 $uhome=&domain($udom,'primary');
 2249:             }
 2250:         }
 2251:     }
 2252:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2253:         my $rep;
 2254:         if (grep { $_ eq $uhome } &current_machine_ids()) {
 2255:             # domain information is hosted on this machine
 2256:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
 2257:         } else {
 2258:             if ($encrypt) {
 2259:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 2260:             } else {
 2261:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 2262:             }
 2263:         }
 2264:         my %returnhash;
 2265:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 2266:             return %returnhash;
 2267:         }
 2268:         my @pairs=split(/\&/,$rep);
 2269:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2270:             return @pairs;
 2271:         }
 2272:         my $i=0;
 2273:         foreach my $item (@$storearr) {
 2274:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2275:             $i++;
 2276:         }
 2277:         return %returnhash;
 2278:     } else {
 2279:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 2280:     }
 2281: }
 2282: 
 2283: # -------------------------------------------- put items in domain db files 
 2284: 
 2285: sub put_dom {
 2286:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
 2287:     if (!$udom) {
 2288:         $udom=$env{'user.domain'};
 2289:         if (defined(&domain($udom,'primary'))) {
 2290:             $uhome=&domain($udom,'primary');
 2291:         } else {
 2292:             undef($uhome);
 2293:         }
 2294:     } else {
 2295:         if (!$uhome) {
 2296:             if (defined(&domain($udom,'primary'))) {
 2297:                 $uhome=&domain($udom,'primary');
 2298:             }
 2299:         }
 2300:     } 
 2301:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 2302:         my $items='';
 2303:         foreach my $item (keys(%$storehash)) {
 2304:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2305:         }
 2306:         $items=~s/\&$//;
 2307:         if ($encrypt) {
 2308:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2309:         } else {
 2310:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2311:         }
 2312:     } else {
 2313:         &logthis("put_dom failed - no homeserver and/or domain");
 2314:     }
 2315: }
 2316: 
 2317: # --------------------- newput for items in db file owned by domainconfig user
 2318: sub newput_dom {
 2319:     my ($namespace,$storehash,$udom) = @_;
 2320:     my $result;
 2321:     if (!$udom) {
 2322:         $udom=$env{'user.domain'};
 2323:     }
 2324:     if ($udom) {
 2325:         my $uname = &get_domainconfiguser($udom);
 2326:         $result = &newput($namespace,$storehash,$udom,$uname);
 2327:     }
 2328:     return $result;
 2329: }
 2330: 
 2331: # --------------------- delete for items in db file owned by domainconfig user
 2332: sub del_dom {
 2333:     my ($namespace,$storearr,$udom)=@_;
 2334:     if (ref($storearr) eq 'ARRAY') {
 2335:         if (!$udom) {
 2336:             $udom=$env{'user.domain'};
 2337:         }
 2338:         if ($udom) {
 2339:             my $uname = &get_domainconfiguser($udom); 
 2340:             return &del($namespace,$storearr,$udom,$uname);
 2341:         }
 2342:     }
 2343: }
 2344: 
 2345: sub store_dom {
 2346:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
 2347:     $$storehash{'ip'}=&get_requestor_ip();
 2348:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2349:     my $namevalue='';
 2350:     foreach my $key (keys(%{$storehash})) {
 2351:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2352:     }
 2353:     $namevalue=~s/\&$//;
 2354:     if (grep { $_ eq $home } current_machine_ids()) {
 2355:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
 2356:     } else {
 2357:         if ($namespace eq 'private') {
 2358:             return 'refused';
 2359:         } elsif ($encrypt) {
 2360:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
 2361:         } else {
 2362:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
 2363:         }
 2364:     }
 2365: }
 2366: 
 2367: sub restore_dom {
 2368:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
 2369:     my $answer;
 2370:     if (grep { $_ eq $home } current_machine_ids()) {
 2371:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
 2372:     } elsif ($namespace ne 'private') {
 2373:         if ($encrypt) {
 2374:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
 2375:         } else {
 2376:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
 2377:         }
 2378:     }
 2379:     my %returnhash=();
 2380:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
 2381:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
 2382:         foreach my $line (split(/\&/,$answer)) {
 2383:             my ($name,$value)=split(/\=/,$line);
 2384:             $returnhash{&unescape($name)}=&thaw_unescape($value);
 2385:         }
 2386:         my $version;
 2387:         for ($version=1;$version<=$returnhash{'version'};$version++) {
 2388:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2389:                 $returnhash{$item}=$returnhash{$version.':'.$item};
 2390:             }
 2391:         }
 2392:     }
 2393:     return %returnhash;
 2394: }
 2395: 
 2396: # ----------------------------------construct domainconfig user for a domain 
 2397: sub get_domainconfiguser {
 2398:     my ($udom) = @_;
 2399:     return $udom.'-domainconfig';
 2400: }
 2401: 
 2402: sub retrieve_inst_usertypes {
 2403:     my ($udom) = @_;
 2404:     my (%returnhash,@order);
 2405:     my %domdefs = &get_domain_defaults($udom);
 2406:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2407:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2408:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2409:     } else {
 2410:         if (defined(&domain($udom,'primary'))) {
 2411:             my $uhome=&domain($udom,'primary');
 2412:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2413:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2414:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2415:                 return (\%returnhash,\@order);
 2416:             }
 2417:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2418:             my @pairs=split(/\&/,$hashitems);
 2419:             foreach my $item (@pairs) {
 2420:                 my ($key,$value)=split(/=/,$item,2);
 2421:                 $key = &unescape($key);
 2422:                 next if ($key =~ /^error: 2 /);
 2423:                 $returnhash{$key}=&thaw_unescape($value);
 2424:             }
 2425:             my @esc_order = split(/\&/,$orderitems);
 2426:             foreach my $item (@esc_order) {
 2427:                 push(@order,&unescape($item));
 2428:             }
 2429:         } else {
 2430:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2431:         }
 2432:         return (\%returnhash,\@order);
 2433:     }
 2434: }
 2435: 
 2436: sub is_domainimage {
 2437:     my ($url) = @_;
 2438:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
 2439:         if (&domain($1) ne '') {
 2440:             return '1';
 2441:         }
 2442:     }
 2443:     return;
 2444: }
 2445: 
 2446: sub inst_directory_query {
 2447:     my ($srch) = @_;
 2448:     my $udom = $srch->{'srchdomain'};
 2449:     my %results;
 2450:     my $homeserver = &domain($udom,'primary');
 2451:     my $outcome;
 2452:     if ($homeserver ne '') {
 2453:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2454:             if ($srch->{'srchby'} eq 'email') {
 2455:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2456:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2457:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2458:                     (($major == 2) && ($minor < 12))) {
 2459:                     return;
 2460:                 }
 2461:             }
 2462:         }
 2463: 	my $queryid=&reply("querysend:instdirsearch:".
 2464: 			   &escape($srch->{'srchby'}).':'.
 2465: 			   &escape($srch->{'srchterm'}).':'.
 2466: 			   &escape($srch->{'srchtype'}),$homeserver);
 2467: 	my $host=&hostname($homeserver);
 2468: 	if ($queryid !~/^\Q$host\E\_/) {
 2469: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2470: 	    return;
 2471: 	}
 2472: 	my $response = &get_query_reply($queryid);
 2473: 	my $maxtries = 5;
 2474: 	my $tries = 1;
 2475: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2476: 	    $response = &get_query_reply($queryid);
 2477: 	    $tries ++;
 2478: 	}
 2479: 
 2480:         if (!&error($response) && $response ne 'refused') {
 2481:             if ($response eq 'unavailable') {
 2482:                 $outcome = $response;
 2483:             } else {
 2484:                 $outcome = 'ok';
 2485:                 my @matches = split(/\n/,$response);
 2486:                 foreach my $match (@matches) {
 2487:                     my ($key,$value) = split(/=/,$match);
 2488:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2489:                 }
 2490:             }
 2491:         }
 2492:     }
 2493:     return ($outcome,%results);
 2494: }
 2495: 
 2496: sub usersearch {
 2497:     my ($srch) = @_;
 2498:     my $dom = $srch->{'srchdomain'};
 2499:     my %results;
 2500:     my %libserv = &all_library();
 2501:     my $query = 'usersearch';
 2502:     foreach my $tryserver (keys(%libserv)) {
 2503:         if (&host_domain($tryserver) eq $dom) {
 2504:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2505:                 if ($srch->{'srchby'} eq 'email') {
 2506:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2507:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2508:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2509:                              (($major == 2) && ($minor < 12)));
 2510:                 }
 2511:             }
 2512:             my $host=&hostname($tryserver);
 2513:             my $queryid=
 2514:                 &reply("querysend:".&escape($query).':'.
 2515:                        &escape($srch->{'srchby'}).':'.
 2516:                        &escape($srch->{'srchtype'}).':'.
 2517:                        &escape($srch->{'srchterm'}),$tryserver);
 2518:             if ($queryid !~/^\Q$host\E\_/) {
 2519:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2520:                 next;
 2521:             }
 2522:             my $reply = &get_query_reply($queryid);
 2523:             my $maxtries = 1;
 2524:             my $tries = 1;
 2525:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2526:                 $reply = &get_query_reply($queryid);
 2527:                 $tries ++;
 2528:             }
 2529:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2530:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2531:             } else {
 2532:                 my @matches;
 2533:                 if ($reply =~ /\n/) {
 2534:                     @matches = split(/\n/,$reply);
 2535:                 } else {
 2536:                     @matches = split(/\&/,$reply);
 2537:                 }
 2538:                 foreach my $match (@matches) {
 2539:                     my ($uname,$udom,%userhash);
 2540:                     foreach my $entry (split(/:/,$match)) {
 2541:                         my ($key,$value) =
 2542:                             map {&unescape($_);} split(/=/,$entry);
 2543:                         $userhash{$key} = $value;
 2544:                         if ($key eq 'username') {
 2545:                             $uname = $value;
 2546:                         } elsif ($key eq 'domain') {
 2547:                             $udom = $value;
 2548:                         }
 2549:                     }
 2550:                     $results{$uname.':'.$udom} = \%userhash;
 2551:                 }
 2552:             }
 2553:         }
 2554:     }
 2555:     return %results;
 2556: }
 2557: 
 2558: sub get_instuser {
 2559:     my ($udom,$uname,$id) = @_;
 2560:     my $homeserver = &domain($udom,'primary');
 2561:     my ($outcome,%results);
 2562:     if ($homeserver ne '') {
 2563:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2564:                            &escape($id).':'.&escape($udom),$homeserver);
 2565:         my $host=&hostname($homeserver);
 2566:         if ($queryid !~/^\Q$host\E\_/) {
 2567:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2568:             return;
 2569:         }
 2570:         my $response = &get_query_reply($queryid);
 2571:         my $maxtries = 5;
 2572:         my $tries = 1;
 2573:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2574:             $response = &get_query_reply($queryid);
 2575:             $tries ++;
 2576:         }
 2577:         if (!&error($response) && $response ne 'refused') {
 2578:             if ($response eq 'unavailable') {
 2579:                 $outcome = $response;
 2580:             } else {
 2581:                 $outcome = 'ok';
 2582:                 my @matches = split(/\n/,$response);
 2583:                 foreach my $match (@matches) {
 2584:                     my ($key,$value) = split(/=/,$match);
 2585:                     $results{&unescape($key)} = &thaw_unescape($value);
 2586:                 }
 2587:             }
 2588:         }
 2589:     }
 2590:     my %userinfo;
 2591:     if (ref($results{$uname}) eq 'HASH') {
 2592:         %userinfo = %{$results{$uname}};
 2593:     } 
 2594:     return ($outcome,%userinfo);
 2595: }
 2596: 
 2597: sub get_multiple_instusers {
 2598:     my ($udom,$users,$caller) = @_;
 2599:     my ($outcome,$results);
 2600:     if (ref($users) eq 'HASH') {
 2601:         my $count = keys(%{$users}); 
 2602:         my $requested = &freeze_escape($users);
 2603:         my $homeserver = &domain($udom,'primary');
 2604:         if ($homeserver ne '') {
 2605:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2606:             my $host=&hostname($homeserver);
 2607:             if ($queryid !~/^\Q$host\E\_/) {
 2608:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2609:                          ' for host: '.$homeserver.'in domain '.$udom);
 2610:                 return ($outcome,$results);
 2611:             }
 2612:             my $response = &get_query_reply($queryid);
 2613:             my $maxtries = 5;
 2614:             if ($count > 100) {
 2615:                 $maxtries = 1+int($count/20);
 2616:             }
 2617:             my $tries = 1;
 2618:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2619:                 $response = &get_query_reply($queryid);
 2620:                 $tries ++;
 2621:             }
 2622:             if ($response eq '') {
 2623:                 $results = {};
 2624:                 foreach my $key (keys(%{$users})) {
 2625:                     my ($uname,$id);
 2626:                     if ($caller eq 'id') {
 2627:                         $id = $key;
 2628:                     } else {
 2629:                         $uname = $key;
 2630:                     }
 2631:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2632:                     $outcome = $resp;
 2633:                     if ($resp eq 'ok') {
 2634:                         %{$results} = (%{$results}, %info);
 2635:                     } else {
 2636:                         last;
 2637:                     }
 2638:                 }
 2639:             } elsif(!&error($response) && ($response ne 'refused')) {
 2640:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2641:                     $outcome = $response;
 2642:                 } else {
 2643:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2644:                     if ($outcome eq 'ok') {
 2645:                         $results = &thaw_unescape($userdata); 
 2646:                     }
 2647:                 }
 2648:             }
 2649:         }
 2650:     }
 2651:     return ($outcome,$results);
 2652: }
 2653: 
 2654: sub inst_rulecheck {
 2655:     my ($udom,$uname,$id,$item,$rules) = @_;
 2656:     my %returnhash;
 2657:     if ($udom ne '') {
 2658:         if (ref($rules) eq 'ARRAY') {
 2659:             @{$rules} = map {&escape($_);} (@{$rules});
 2660:             my $rulestr = join(':',@{$rules});
 2661:             my $homeserver=&domain($udom,'primary');
 2662:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2663:                 my $response;
 2664:                 if ($item eq 'username') {                
 2665:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2666:                                               ':'.&escape($uname).':'.$rulestr,
 2667:                                               $homeserver));
 2668:                 } elsif ($item eq 'id') {
 2669:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2670:                                               ':'.&escape($id).':'.$rulestr,
 2671:                                               $homeserver));
 2672:                 } elsif ($item eq 'selfcreate') {
 2673:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2674:                                                &escape($udom).':'.&escape($uname).
 2675:                                               ':'.$rulestr,$homeserver));
 2676:                 } elsif ($item eq 'unamemap') {
 2677:                     $response=&unescape(&reply('instunamemapcheck:'.
 2678:                                                &escape($udom).':'.&escape($uname).
 2679:                                               ':'.$rulestr,$homeserver));
 2680:                 }
 2681:                 if ($response ne 'refused') {
 2682:                     my @pairs=split(/\&/,$response);
 2683:                     foreach my $item (@pairs) {
 2684:                         my ($key,$value)=split(/=/,$item,2);
 2685:                         $key = &unescape($key);
 2686:                         next if ($key =~ /^error: 2 /);
 2687:                         $returnhash{$key}=&thaw_unescape($value);
 2688:                     }
 2689:                 }
 2690:             }
 2691:         }
 2692:     }
 2693:     return %returnhash;
 2694: }
 2695: 
 2696: sub inst_userrules {
 2697:     my ($udom,$check) = @_;
 2698:     my (%ruleshash,@ruleorder);
 2699:     if ($udom ne '') {
 2700:         my $homeserver=&domain($udom,'primary');
 2701:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2702:             my $response;
 2703:             if ($check eq 'id') {
 2704:                 $response=&reply('instidrules:'.&escape($udom),
 2705:                                  $homeserver);
 2706:             } elsif ($check eq 'email') {
 2707:                 $response=&reply('instemailrules:'.&escape($udom),
 2708:                                  $homeserver);
 2709:             } elsif ($check eq 'unamemap') {
 2710:                 $response=&reply('unamemaprules:'.&escape($udom),
 2711:                                  $homeserver); 
 2712:             } else {
 2713:                 $response=&reply('instuserrules:'.&escape($udom),
 2714:                                  $homeserver);
 2715:             }
 2716:             if (($response ne 'refused') && ($response ne 'error') && 
 2717:                 ($response ne 'unknown_cmd') && 
 2718:                 ($response ne 'no_such_host')) {
 2719:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2720:                 my @pairs=split(/\&/,$hashitems);
 2721:                 foreach my $item (@pairs) {
 2722:                     my ($key,$value)=split(/=/,$item,2);
 2723:                     $key = &unescape($key);
 2724:                     next if ($key =~ /^error: 2 /);
 2725:                     $ruleshash{$key}=&thaw_unescape($value);
 2726:                 }
 2727:                 my @esc_order = split(/\&/,$orderitems);
 2728:                 foreach my $item (@esc_order) {
 2729:                     push(@ruleorder,&unescape($item));
 2730:                 }
 2731:             }
 2732:         }
 2733:     }
 2734:     return (\%ruleshash,\@ruleorder);
 2735: }
 2736: 
 2737: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2738: 
 2739: sub get_domain_defaults {
 2740:     my ($domain,$ignore_cache) = @_;
 2741:     return if (($domain eq '') || ($domain eq 'public'));
 2742:     my $cachetime = 60*60*24;
 2743:     unless ($ignore_cache) {
 2744:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2745:         if (defined($cached)) {
 2746:             if (ref($result) eq 'HASH') {
 2747:                 return %{$result};
 2748:             }
 2749:         }
 2750:     }
 2751:     my %domdefaults;
 2752:     my %domconfig =
 2753:          &get_dom('configuration',['defaults','quotas',
 2754:                                   'requestcourses','inststatus',
 2755:                                   'coursedefaults','usersessions',
 2756:                                   'requestauthor','selfenrollment',
 2757:                                   'coursecategories','ssl','autoenroll',
 2758:                                   'trust','helpsettings','wafproxy',
 2759:                                   'ltisec','toolsec','domexttool',
 2760:                                   'exttool','privacy'],$domain);
 2761:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2762:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2763:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2764:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2765:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2766:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2767:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2768:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2769:         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
 2770:         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
 2771:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2772:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2773:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2774:         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
 2775:     } else {
 2776:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2777:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2778:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2779:     }
 2780:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2781:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2782:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2783:         } else {
 2784:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2785:         }
 2786:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2787:         foreach my $item (@usertools) {
 2788:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2789:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2790:             }
 2791:         }
 2792:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2793:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2794:         }
 2795:     }
 2796:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2797:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2798:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2799:         }
 2800:     }
 2801:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2802:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2803:     }
 2804:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2805:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2806:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2807:         }
 2808:     }
 2809:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2810:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2811:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2812:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
 2813:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2814:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2815:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2816:         }
 2817:         foreach my $type (@coursetypes) {
 2818:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2819:                 unless ($type eq 'community') {
 2820:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2821:                 }
 2822:             }
 2823:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2824:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2825:             }
 2826:             if ($domdefaults{'postsubmit'} eq 'on') {
 2827:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2828:                     $domdefaults{$type.'postsubtimeout'} = 
 2829:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2830:                 }
 2831:             }
 2832:             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
 2833:                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
 2834:             } else {
 2835:                 $domdefaults{$type.'domexttool'} = 1;
 2836:             }
 2837:             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
 2838:                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
 2839:             } else {
 2840:                 $domdefaults{$type.'exttool'} = 0;
 2841:             }
 2842:         }
 2843:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2844:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2845:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2846:                 if (@clonecodes) {
 2847:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2848:                 }
 2849:             }
 2850:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2851:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2852:         }
 2853:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2854:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2855:         }
 2856:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
 2857:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
 2858:         }
 2859:     }
 2860:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2861:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2862:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2863:         }
 2864:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2865:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2866:         }
 2867:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2868:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2869:         }
 2870:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
 2871:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
 2872:         }
 2873:     }
 2874:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2875:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2876:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2877:                             'approval','limit');
 2878:             foreach my $type (@coursetypes) {
 2879:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2880:                     my @mgrdc = ();
 2881:                     foreach my $item (@settings) {
 2882:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2883:                             push(@mgrdc,$item);
 2884:                         }
 2885:                     }
 2886:                     if (@mgrdc) {
 2887:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2888:                     }
 2889:                 }
 2890:             }
 2891:         }
 2892:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2893:             foreach my $type (@coursetypes) {
 2894:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2895:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2896:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2897:                     }
 2898:                 }
 2899:             }
 2900:         }
 2901:     }
 2902:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2903:         $domdefaults{'catauth'} = 'std';
 2904:         $domdefaults{'catunauth'} = 'std';
 2905:         if ($domconfig{'coursecategories'}{'auth'}) {
 2906:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2907:         }
 2908:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2909:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2910:         }
 2911:     }
 2912:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2913:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2914:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2915:         }
 2916:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2917:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2918:         }
 2919:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2920:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2921:         }
 2922:     }
 2923:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2924:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2925:         foreach my $prefix (@prefixes) {
 2926:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2927:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2928:             }
 2929:         }
 2930:     }
 2931:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2932:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2933:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
 2934:     }
 2935:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2936:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2937:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2938:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2939:         }
 2940:     }
 2941:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
 2942:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
 2943:             if ($domconfig{'wafproxy'}{$item}) {
 2944:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
 2945:             }
 2946:         }
 2947:     }
 2948:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
 2949:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
 2950:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
 2951:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
 2952:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
 2953:         }
 2954:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
 2955:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
 2956:                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
 2957:             }
 2958:         }
 2959:     }
 2960:     if (ref($domconfig{'toolsec'}) eq 'HASH') {
 2961:         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
 2962:             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
 2963:             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
 2964:         }
 2965:         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
 2966:             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
 2967:                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
 2968:             }
 2969:         }
 2970:     }
 2971:     if (ref($domconfig{'privacy'}) eq 'HASH') {
 2972:         if (ref($domconfig{'privacy'}{'approval'}) eq 'HASH') {
 2973:             foreach my $domtype ('instdom','extdom') {
 2974:                 if (ref($domconfig{'privacy'}{'approval'}{$domtype}) eq 'HASH') {
 2975:                     foreach my $roletype ('domain','author','course','community') {
 2976:                         if ($domconfig{'privacy'}{'approval'}{$domtype}{$roletype} eq 'user') {
 2977:                             $domdefaults{'userapprovals'} = 1;
 2978:                             last;
 2979:                         }
 2980:                     }
 2981:                 }
 2982:                 last if ($domdefaults{'userapprovals'});
 2983:             }
 2984:         }
 2985:     }
 2986:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2987:     return %domdefaults;
 2988: }
 2989: 
 2990: sub get_dom_cats {
 2991:     my ($dom) = @_;
 2992:     return unless (&domain($dom));
 2993:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2994:     unless (defined($cached)) {
 2995:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2996:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2997:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2998:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2999:             } else {
 3000:                 $cats = {};
 3001:             }
 3002:         } else {
 3003:             $cats = {};
 3004:         }
 3005:         &do_cache_new('cats',$dom,$cats,3600);
 3006:     }
 3007:     return $cats;
 3008: }
 3009: 
 3010: sub get_dom_instcats {
 3011:     my ($dom) = @_;
 3012:     return unless (&domain($dom));
 3013:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 3014:     unless (defined($cached)) {
 3015:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 3016:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 3017:         if ($totcodes > 0) {
 3018:             my $caller = 'global';
 3019:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 3020:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 3021:                 $instcats = {
 3022:                                 totcodes => $totcodes,
 3023:                                 codes => \%codes,
 3024:                                 codetitles => \@codetitles,
 3025:                                 cat_titles => \%cat_titles,
 3026:                                 cat_order => \%cat_order,
 3027:                             };
 3028:                 &do_cache_new('instcats',$dom,$instcats,3600);
 3029:             }
 3030:         }
 3031:     }
 3032:     return $instcats;
 3033: }
 3034: 
 3035: sub retrieve_instcodes {
 3036:     my ($coursecodes,$dom) = @_;
 3037:     my $totcodes;
 3038:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 3039:     foreach my $course (keys(%courses)) {
 3040:         if (ref($courses{$course}) eq 'HASH') {
 3041:             if ($courses{$course}{'inst_code'} ne '') {
 3042:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 3043:                 $totcodes ++;
 3044:             }
 3045:         }
 3046:     }
 3047:     return $totcodes;
 3048: }
 3049: 
 3050: sub course_portal_url {
 3051:     my ($cnum,$cdom,$r) = @_;
 3052:     my $chome = &homeserver($cnum,$cdom);
 3053:     my $hostname = &hostname($chome);
 3054:     my $protocol = $protocol{$chome};
 3055:     $protocol = 'http' if ($protocol ne 'https');
 3056:     my %domdefaults = &get_domain_defaults($cdom);
 3057:     my $firsturl;
 3058:     if ($domdefaults{'portal_def'}) {
 3059:         $firsturl = $domdefaults{'portal_def'};
 3060:     } else {
 3061:         my $alias = &use_proxy_alias($r,$chome);
 3062:         $hostname = $alias if ($alias ne '');
 3063:         $firsturl = $protocol.'://'.$hostname;
 3064:     }
 3065:     return $firsturl;
 3066: }
 3067: 
 3068: sub url_prefix {
 3069:     my ($r,$dom,$home,$context) = @_;
 3070:     my $prefix;
 3071:     my %domdefs = &get_domain_defaults($dom);
 3072:     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
 3073:         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
 3074:             $prefix = $1;
 3075:         }
 3076:     }
 3077:     if ($prefix eq '') {
 3078:         my $hostname = &hostname($home);
 3079:         my $protocol = $protocol{$home};
 3080:         $protocol = 'http' if ($protocol{$home} ne 'https');
 3081:         my $alias = &use_proxy_alias($r,$home);
 3082:         $hostname = $alias if ($alias ne '');
 3083:         $prefix = $protocol.'://'.$hostname;
 3084:     }
 3085:     return $prefix;
 3086: }
 3087: 
 3088: # --------------------------------------------- Get domain config for passwords
 3089: 
 3090: sub get_passwdconf {
 3091:     my ($dom) = @_;
 3092:     my (%passwdconf,$gotconf,$lookup);
 3093:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 3094:     if (defined($cached)) {
 3095:         if (ref($result) eq 'HASH') {
 3096:             %passwdconf = %{$result};
 3097:             $gotconf = 1;
 3098:         }
 3099:     }
 3100:     unless ($gotconf) {
 3101:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 3102:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 3103:             %passwdconf = %{$domconfig{'passwords'}};
 3104:         }
 3105:         my $cachetime = 24*60*60;
 3106:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 3107:     }
 3108:     return %passwdconf;
 3109: }
 3110: 
 3111: # --------------------------------------------------- Assign a key to a student
 3112: 
 3113: sub assign_access_key {
 3114: #
 3115: # a valid key looks like uname:udom#comments
 3116: # comments are being appended
 3117: #
 3118:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 3119:     $kdom=
 3120:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 3121:     $knum=
 3122:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 3123:     $cdom=
 3124:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3125:     $cnum=
 3126:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3127:     $udom=$env{'user.name'} unless (defined($udom));
 3128:     $uname=$env{'user.domain'} unless (defined($uname));
 3129:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 3130:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 3131:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 3132:                                                   # assigned to this person
 3133:                                                   # - this should not happen,
 3134:                                                   # unless something went wrong
 3135:                                                   # the first time around
 3136: # ready to assign
 3137:         $logentry=$1.'; '.$logentry;
 3138:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 3139:                                                  $kdom,$knum) eq 'ok') {
 3140: # key now belongs to user
 3141: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 3142:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 3143:                 &appenv({'environment.'.$envkey => $ckey});
 3144:                 return 'ok';
 3145:             } else {
 3146:                 return 
 3147:   'error: Count not permanently assign key, will need to be re-entered later.';
 3148: 	    }
 3149:         } else {
 3150:             return 'error: Could not assign key, try again later.';
 3151:         }
 3152:     } elsif (!$existing{$ckey}) {
 3153: # the key does not exist
 3154: 	return 'error: The key does not exist';
 3155:     } else {
 3156: # the key is somebody else's
 3157: 	return 'error: The key is already in use';
 3158:     }
 3159: }
 3160: 
 3161: # ------------------------------------------ put an additional comment on a key
 3162: 
 3163: sub comment_access_key {
 3164: #
 3165: # a valid key looks like uname:udom#comments
 3166: # comments are being appended
 3167: #
 3168:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 3169:     $cdom=
 3170:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3171:     $cnum=
 3172:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3173:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3174:     if ($existing{$ckey}) {
 3175:         $existing{$ckey}.='; '.$logentry;
 3176: # ready to assign
 3177:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 3178:                                                  $cdom,$cnum) eq 'ok') {
 3179: 	    return 'ok';
 3180:         } else {
 3181: 	    return 'error: Count not store comment.';
 3182:         }
 3183:     } else {
 3184: # the key does not exist
 3185: 	return 'error: The key does not exist';
 3186:     }
 3187: }
 3188: 
 3189: # ------------------------------------------------------ Generate a set of keys
 3190: 
 3191: sub generate_access_keys {
 3192:     my ($number,$cdom,$cnum,$logentry)=@_;
 3193:     $cdom=
 3194:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3195:     $cnum=
 3196:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3197:     unless (&allowed('mky',$cdom)) { return 0; }
 3198:     unless (($cdom) && ($cnum)) { return 0; }
 3199:     if ($number>10000) { return 0; }
 3200:     sleep(2); # make sure don't get same seed twice
 3201:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 3202:     my $total=0;
 3203:     for (my $i=1;$i<=$number;$i++) {
 3204:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 3205:                   sprintf("%lx",int(100000*rand)).'-'.
 3206:                   sprintf("%lx",int(100000*rand));
 3207:        $newkey=~s/1/g/g; # folks mix up 1 and l
 3208:        $newkey=~s/0/h/g; # and also 0 and O
 3209:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 3210:        if ($existing{$newkey}) {
 3211:            $i--;
 3212:        } else {
 3213: 	  if (&put('accesskeys',
 3214:               { $newkey => '# generated '.localtime().
 3215:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 3216:                            '; '.$logentry },
 3217: 		   $cdom,$cnum) eq 'ok') {
 3218:               $total++;
 3219: 	  }
 3220:        }
 3221:     }
 3222:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3223:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 3224:     return $total;
 3225: }
 3226: 
 3227: # ------------------------------------------------------- Validate an accesskey
 3228: 
 3229: sub validate_access_key {
 3230:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 3231:     $cdom=
 3232:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 3233:     $cnum=
 3234:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 3235:     $udom=$env{'user.domain'} unless (defined($udom));
 3236:     $uname=$env{'user.name'} unless (defined($uname));
 3237:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 3238:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 3239: }
 3240: 
 3241: # ------------------------------------- Find the section of student in a course
 3242: sub devalidate_getsection_cache {
 3243:     my ($udom,$unam,$courseid)=@_;
 3244:     my $hashid="$udom:$unam:$courseid";
 3245:     &devalidate_cache_new('getsection',$hashid);
 3246: }
 3247: 
 3248: sub courseid_to_courseurl {
 3249:     my ($courseid) = @_;
 3250:     #already url style courseid
 3251:     return $courseid if ($courseid =~ m{^/});
 3252: 
 3253:     if (exists($env{'course.'.$courseid.'.num'})) {
 3254: 	my $cnum = $env{'course.'.$courseid.'.num'};
 3255: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 3256: 	return "/$cdom/$cnum";
 3257:     }
 3258: 
 3259:     my %courseinfo=&coursedescription($courseid);
 3260:     if (exists($courseinfo{'num'})) {
 3261: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 3262:     }
 3263: 
 3264:     return undef;
 3265: }
 3266: 
 3267: sub getsection {
 3268:     my ($udom,$unam,$courseid)=@_;
 3269:     my $cachetime=1800;
 3270: 
 3271:     my $hashid="$udom:$unam:$courseid";
 3272:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 3273:     if (defined($cached)) { return $result; }
 3274: 
 3275:     my %Pending; 
 3276:     my %Expired;
 3277:     #
 3278:     # Each role can either have not started yet (pending), be active, 
 3279:     #    or have expired.
 3280:     #
 3281:     # If there is an active role, we are done.
 3282:     #
 3283:     # If there is more than one role which has not started yet, 
 3284:     #     choose the one which will start sooner
 3285:     # If there is one role which has not started yet, return it.
 3286:     #
 3287:     # If there is more than one expired role, choose the one which ended last.
 3288:     # If there is a role which has expired, return it.
 3289:     #
 3290:     $courseid = &courseid_to_courseurl($courseid);
 3291:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 3292:     foreach my $key (keys(%roleshash)) {
 3293:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 3294:         my $section=$1;
 3295:         if ($key eq $courseid.'_st') { $section=''; }
 3296:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 3297:         my $now=time;
 3298:         if (defined($end) && $end && ($now > $end)) {
 3299:             $Expired{$end}=$section;
 3300:             next;
 3301:         }
 3302:         if (defined($start) && $start && ($now < $start)) {
 3303:             $Pending{$start}=$section;
 3304:             next;
 3305:         }
 3306:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 3307:     }
 3308:     #
 3309:     # Presumedly there will be few matching roles from the above
 3310:     # loop and the sorting time will be negligible.
 3311:     if (scalar(keys(%Pending))) {
 3312:         my ($time) = sort {$a <=> $b} keys(%Pending);
 3313:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 3314:     } 
 3315:     if (scalar(keys(%Expired))) {
 3316:         my @sorted = sort {$a <=> $b} keys(%Expired);
 3317:         my $time = pop(@sorted);
 3318:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 3319:     }
 3320:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 3321: }
 3322: 
 3323: sub save_cache {
 3324:     &purge_remembered();
 3325:     #&Apache::loncommon::validate_page();
 3326:     undef(%env);
 3327:     undef($env_loaded);
 3328: }
 3329: 
 3330: my $to_remember=-1;
 3331: my %remembered;
 3332: my %accessed;
 3333: my $kicks=0;
 3334: my $hits=0;
 3335: sub make_key {
 3336:     my ($name,$id) = @_;
 3337:     if (length($id) > 65 
 3338: 	&& length(&escape($id)) > 200) {
 3339: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 3340:     }
 3341:     return &escape($name.':'.$id);
 3342: }
 3343: 
 3344: sub devalidate_cache_new {
 3345:     my ($name,$id,$debug) = @_;
 3346:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 3347:     my $remembered_id=$name.':'.$id;
 3348:     $id=&make_key($name,$id);
 3349:     $memcache->delete($id);
 3350:     delete($remembered{$remembered_id});
 3351:     delete($accessed{$remembered_id});
 3352: }
 3353: 
 3354: sub is_cached_new {
 3355:     my ($name,$id,$debug) = @_;
 3356:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 3357:     if (exists($remembered{$remembered_id})) {
 3358: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 3359: 	$accessed{$remembered_id}=[&gettimeofday()];
 3360: 	$hits++;
 3361: 	return ($remembered{$remembered_id},1);
 3362:     }
 3363:     $id=&make_key($name,$id);
 3364:     my $value = $memcache->get($id);
 3365:     if (!(defined($value))) {
 3366: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 3367: 	return (undef,undef);
 3368:     }
 3369:     if ($value eq '__undef__') {
 3370: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 3371: 	$value=undef;
 3372:     }
 3373:     &make_room($remembered_id,$value,$debug);
 3374:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 3375:     return ($value,1);
 3376: }
 3377: 
 3378: sub do_cache_new {
 3379:     my ($name,$id,$value,$time,$debug) = @_;
 3380:     my $remembered_id=$name.':'.$id;
 3381:     $id=&make_key($name,$id);
 3382:     my $setvalue=$value;
 3383:     if (!defined($setvalue)) {
 3384: 	$setvalue='__undef__';
 3385:     }
 3386:     if (!defined($time) ) {
 3387: 	$time=600;
 3388:     }
 3389:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 3390:     my $result = $memcache->set($id,$setvalue,$time);
 3391:     if (! $result) {
 3392: 	&logthis("caching of id -> $id  failed");
 3393: 	$memcache->disconnect_all();
 3394:     }
 3395:     # need to make a copy of $value
 3396:     &make_room($remembered_id,$value,$debug);
 3397:     return $value;
 3398: }
 3399: 
 3400: sub make_room {
 3401:     my ($remembered_id,$value,$debug)=@_;
 3402: 
 3403:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 3404:                                     : $value;
 3405:     if ($to_remember<0) { return; }
 3406:     $accessed{$remembered_id}=[&gettimeofday()];
 3407:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 3408:     my $to_kick;
 3409:     my $max_time=0;
 3410:     foreach my $other (keys(%accessed)) {
 3411: 	if (&tv_interval($accessed{$other}) > $max_time) {
 3412: 	    $to_kick=$other;
 3413: 	    $max_time=&tv_interval($accessed{$other});
 3414: 	}
 3415:     }
 3416:     delete($remembered{$to_kick});
 3417:     delete($accessed{$to_kick});
 3418:     $kicks++;
 3419:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 3420:     return;
 3421: }
 3422: 
 3423: sub purge_remembered {
 3424:     #&logthis("Tossing ".scalar(keys(%remembered)));
 3425:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 3426:     undef(%remembered);
 3427:     undef(%accessed);
 3428: }
 3429: # ------------------------------------- Read an entry from a user's environment
 3430: 
 3431: sub userenvironment {
 3432:     my ($udom,$unam,@what)=@_;
 3433:     my $items;
 3434:     foreach my $item (@what) {
 3435:         $items.=&escape($item).'&';
 3436:     }
 3437:     $items=~s/\&$//;
 3438:     my %returnhash=();
 3439:     my $uhome = &homeserver($unam,$udom);
 3440:     unless ($uhome eq 'no_host') {
 3441:         my @answer=split(/\&/, 
 3442:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 3443:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 3444:             return %returnhash;
 3445:         }
 3446:         my $i;
 3447:         for ($i=0;$i<=$#what;$i++) {
 3448: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 3449:         }
 3450:     }
 3451:     return %returnhash;
 3452: }
 3453: 
 3454: # ---------------------------------------------------------- Get a studentphoto
 3455: sub studentphoto {
 3456:     my ($udom,$unam,$ext) = @_;
 3457:     my $home=&homeserver($unam,$udom);
 3458:     if (defined($env{'request.course.id'})) {
 3459:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 3460:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 3461:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 3462:             } else {
 3463:                 my ($result,$perm_reqd)=
 3464: 		    &auto_photo_permission($unam,$udom);
 3465:                 if ($result eq 'ok') {
 3466:                     if (!($perm_reqd eq 'yes')) {
 3467:                         return(&retrievestudentphoto($udom,$unam,$ext));
 3468:                     }
 3469:                 }
 3470:             }
 3471:         }
 3472:     } else {
 3473:         my ($result,$perm_reqd) = 
 3474: 	    &auto_photo_permission($unam,$udom);
 3475:         if ($result eq 'ok') {
 3476:             if (!($perm_reqd eq 'yes')) {
 3477:                 return(&retrievestudentphoto($udom,$unam,$ext));
 3478:             }
 3479:         }
 3480:     }
 3481:     return '/adm/lonKaputt/lonlogo_broken.gif';
 3482: }
 3483: 
 3484: sub retrievestudentphoto {
 3485:     my ($udom,$unam,$ext,$type) = @_;
 3486:     my $home=&homeserver($unam,$udom);
 3487:     my $ret=&reply("studentphoto:$udom:$unam:$ext:$type",$home);
 3488:     if ($ret eq 'ok') {
 3489:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 3490:         if ($type eq 'thumbnail') {
 3491:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 3492:         }
 3493:         my $tokenurl=&tokenwrapper($url);
 3494:         return $tokenurl;
 3495:     } else {
 3496:         if ($type eq 'thumbnail') {
 3497:             return '/adm/lonKaputt/genericstudent_tn.gif';
 3498:         } else { 
 3499:             return '/adm/lonKaputt/lonlogo_broken.gif';
 3500:         }
 3501:     }
 3502: }
 3503: 
 3504: # -------------------------------------------------------------------- New chat
 3505: 
 3506: sub chatsend {
 3507:     my ($newentry,$anon,$group)=@_;
 3508:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 3509:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3510:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3511:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 3512: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 3513: 		   &escape($newentry)).':'.$group,$chome);
 3514: }
 3515: 
 3516: # ------------------------------------------ Find current version of a resource
 3517: 
 3518: sub getversion {
 3519:     my $fname=&clutter(shift);
 3520:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 3521:     return &currentversion(&filelocation('',$fname));
 3522: }
 3523: 
 3524: sub currentversion {
 3525:     my $fname=shift;
 3526:     my $author=$fname;
 3527:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3528:     my ($udom,$uname)=split(/\//,$author);
 3529:     my $home=&homeserver($uname,$udom);
 3530:     if ($home eq 'no_host') { 
 3531:         return -1; 
 3532:     }
 3533:     my $answer=&reply("currentversion:$fname",$home);
 3534:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3535: 	return -1;
 3536:     }
 3537:     return $answer;
 3538: }
 3539: 
 3540: #
 3541: # Return special version number of resource if set by override, empty otherwise
 3542: #
 3543: sub usedversion {
 3544:     my $fname=shift;
 3545:     unless ($fname) { $fname=$env{'request.uri'}; }
 3546:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3547:     if ($urlversion) { return $urlversion; }
 3548:     return '';
 3549: }
 3550: 
 3551: # ----------------------------- Subscribe to a resource, return URL if possible
 3552: 
 3553: sub subscribe {
 3554:     my $fname=shift;
 3555:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3556:     $fname=~s/[\n\r]//g;
 3557:     my $author=$fname;
 3558:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3559:     my ($udom,$uname)=split(/\//,$author);
 3560:     my $home=homeserver($uname,$udom);
 3561:     if ($home eq 'no_host') {
 3562:         return 'not_found';
 3563:     }
 3564:     my $answer=reply("sub:$fname",$home);
 3565:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3566: 	$answer.=' by '.$home;
 3567:     }
 3568:     return $answer;
 3569: }
 3570:     
 3571: # -------------------------------------------------------------- Replicate file
 3572: 
 3573: sub repcopy {
 3574:     my $filename=shift;
 3575:     $filename=~s/\/+/\//g;
 3576:     my $londocroot = $perlvar{'lonDocRoot'};
 3577:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3578:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3579:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3580: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3581: 	return &repcopy_userfile($filename);
 3582:     }
 3583:     $filename=~s/[\n\r]//g;
 3584:     my $transname="$filename.in.transfer";
 3585: # FIXME: this should flock
 3586:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3587:     my $remoteurl=subscribe($filename);
 3588:     if ($remoteurl =~ /^con_lost by/) {
 3589: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3590:            return 'unavailable';
 3591:     } elsif ($remoteurl eq 'not_found') {
 3592: 	   #&logthis("Subscribe returned not_found: $filename");
 3593: 	   return 'not_found';
 3594:     } elsif ($remoteurl =~ /^rejected by/) {
 3595: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3596:            return 'forbidden';
 3597:     } elsif ($remoteurl eq 'directory') {
 3598:            return 'ok';
 3599:     } else {
 3600:         my $author=$filename;
 3601:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3602:         my ($udom,$uname)=split(/\//,$author);
 3603:         my $home=homeserver($uname,$udom);
 3604:         unless ($home eq $perlvar{'lonHostID'}) {
 3605:            my @parts=split(/\//,$filename);
 3606:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3607:            if ($path ne "$londocroot/res") {
 3608:                &logthis("Malconfiguration for replication: $filename");
 3609: 	       return 'bad_request';
 3610:            }
 3611:            my $count;
 3612:            for ($count=5;$count<$#parts;$count++) {
 3613:                $path.="/$parts[$count]";
 3614:                if ((-e $path)!=1) {
 3615: 		   mkdir($path,0777);
 3616:                }
 3617:            }
 3618:            my $request=new HTTP::Request('GET',"$remoteurl");
 3619:            my $response;
 3620:            if ($remoteurl =~ m{/raw/}) {
 3621:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3622:            } else {
 3623:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3624:            }
 3625:            if ($response->is_error()) {
 3626: 	       unlink($transname);
 3627:                my $message=$response->status_line;
 3628:                &logthis("<font color=\"blue\">WARNING:"
 3629:                        ." LWP get: $message: $filename</font>");
 3630:                return 'unavailable';
 3631:            } else {
 3632: 	       if ($remoteurl!~/\.meta$/) {
 3633:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3634:                   my $mresponse;
 3635:                   if ($remoteurl =~ m{/raw/}) {
 3636:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3637:                   } else {
 3638:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3639:                   }
 3640:                   if ($mresponse->is_error()) {
 3641: 		      unlink($filename.'.meta');
 3642:                       &logthis(
 3643:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3644:                   }
 3645: 	       }
 3646:                rename($transname,$filename);
 3647:                return 'ok';
 3648:            }
 3649:        }
 3650:     }
 3651: }
 3652: 
 3653: # ------------------------------------------------- Unsubscribe from a resource
 3654: 
 3655: sub unsubscribe {
 3656:     my ($fname) = @_;
 3657:     my $answer;
 3658:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3659:     $fname=~s/[\n\r]//g;
 3660:     my $author=$fname;
 3661:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3662:     my ($udom,$uname)=split(/\//,$author);
 3663:     my $home=homeserver($uname,$udom);
 3664:     if ($home eq 'no_host') {
 3665:         $answer = 'no_host';
 3666:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3667:         $answer = 'home';
 3668:     } else {
 3669:         my $defdom = $perlvar{'lonDefDomain'};
 3670:         if (&will_trust('content',$defdom,$udom)) {
 3671:             $answer = reply("unsub:$fname",$home);
 3672:         } else {
 3673:             $answer = 'untrusted';
 3674:         }
 3675:     }
 3676:     return $answer;
 3677: }
 3678: 
 3679: # ------------------------------------------------ Get server side include body
 3680: sub ssi_body {
 3681:     my ($filelink,%form)=@_;
 3682:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3683:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3684:     }
 3685:     my $output='';
 3686:     my $response;
 3687:     if ($filelink=~/^https?\:/) {
 3688:        ($output,$response)=&externalssi($filelink);
 3689:     } else {
 3690:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3691:        $filelink .= 'inhibitmenu=yes';
 3692:        ($output,$response)=&ssi($filelink,%form);
 3693:     }
 3694:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3695:     $output=~s/^.*?\<body[^\>]*\>//si;
 3696:     $output=~s/\<\/body\s*\>.*?$//si;
 3697:     if (wantarray) {
 3698:         return ($output, $response);
 3699:     } else {
 3700:         return $output;
 3701:     }
 3702: }
 3703: 
 3704: # --------------------------------------------------------- Server Side Include
 3705: 
 3706: sub absolute_url {
 3707:     my ($host_name,$unalias,$keep_proto) = @_;
 3708:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3709:     if ($host_name eq '') {
 3710: 	$host_name = $ENV{'SERVER_NAME'};
 3711:     }
 3712:     if ($unalias) {
 3713:         my $alias = &get_proxy_alias();
 3714:         if ($alias eq $host_name) {
 3715:             my $lonhost = $perlvar{'lonHostID'};
 3716:             my $hostname = &hostname($lonhost);
 3717:             my $lcproto; 
 3718:             if (($keep_proto) || ($hostname eq '')) {
 3719:                 $lcproto = $protocol;
 3720:             } else {
 3721:                 $lcproto = $protocol{$lonhost};
 3722:                 $lcproto = 'http' if ($lcproto ne 'https');
 3723:                 $lcproto .= '://';
 3724:             }
 3725:             unless ($hostname eq '') {
 3726:                 return $lcproto.$hostname;
 3727:             }
 3728:         }
 3729:     }
 3730:     return $protocol.$host_name;
 3731: }
 3732: 
 3733: #
 3734: #   Server side include.
 3735: # Parameters:
 3736: #  fn     Possibly encrypted resource name/id.
 3737: #  form   Hash that describes how the rendering should be done
 3738: #         and other things.
 3739: # Returns:
 3740: #   Scalar context: The content of the response.
 3741: #   Array context:  2 element list of the content and the full response object.
 3742: #     
 3743: sub ssi {
 3744: 
 3745:     my ($fn,%form)=@_;
 3746:     my ($host,$request,$response);
 3747:     $host = &absolute_url('',1);
 3748: 
 3749:     $form{'no_update_last_known'}=1;
 3750:     &Apache::lonenc::check_encrypt(\$fn);
 3751:     if (%form) {
 3752:       $request=new HTTP::Request('POST',$host.$fn);
 3753:       $request->content(join('&',map { 
 3754:             my $name = escape($_);
 3755:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3756:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3757:             : &escape($form{$_}) );    
 3758:         } keys(%form)));
 3759:     } else {
 3760:       $request=new HTTP::Request('GET',$host.$fn);
 3761:     }
 3762: 
 3763:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3764:     my $lonhost = $perlvar{'lonHostID'};
 3765:     my $islocal;
 3766:     if (($env{'request.course.id'}) &&
 3767:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3768:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3769:         ($form{'grade_symb'} ne '') &&
 3770:         (&allowed('mgr',$env{'request.course.id'}.
 3771:                         ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3772:         $islocal = 1;
 3773:     }
 3774:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
 3775:                                              '','','',$islocal);
 3776: 
 3777:     if (wantarray) {
 3778: 	return ($response->content, $response);
 3779:     } else {
 3780: 	return $response->content;
 3781:     }
 3782: }
 3783: 
 3784: sub externalssi {
 3785:     my ($url)=@_;
 3786:     my $request=new HTTP::Request('GET',$url);
 3787:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3788:     if (wantarray) {
 3789:         return ($response->content, $response);
 3790:     } else {
 3791:         return $response->content;
 3792:     }
 3793: }
 3794: 
 3795: 
 3796: # If the local copy of a replicated resource is outdated, trigger a  
 3797: # connection from the homeserver to flush the delayed queue. If no update 
 3798: # happens, remove local copies of outdated resource (and corresponding
 3799: # metadata file).
 3800: 
 3801: sub remove_stale_resfile {
 3802:     my ($url) = @_;
 3803:     my $removed;
 3804:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3805:         my $audom = $1;
 3806:         my $auname = $2;
 3807:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3808:             my $homeserver = &homeserver($auname,$audom);
 3809:             unless (($homeserver eq 'no_host') ||
 3810:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3811:                 my $fname = &filelocation('',$url);
 3812:                 if (-e $fname) {
 3813:                     my $hostname = &hostname($homeserver);
 3814:                     if ($hostname) {
 3815:                         my $protocol = $protocol{$homeserver};
 3816:                         $protocol = 'http' if ($protocol ne 'https');
 3817:                         my $uri = &declutter($url);
 3818:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3819:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3820:                         if ($response->is_success()) {
 3821:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3822:                             my $locmodtime = (stat($fname))[9];
 3823:                             if ($locmodtime < $remmodtime) {
 3824:                                 my $stale;
 3825:                                 my $answer = &reply('pong',$homeserver);
 3826:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3827:                                     sleep(0.2);
 3828:                                     $locmodtime = (stat($fname))[9];
 3829:                                     if ($locmodtime < $remmodtime) {
 3830:                                         my $posstransfer = $fname.'.in.transfer';
 3831:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3832:                                             $removed = 1;
 3833:                                         } else {
 3834:                                             $stale = 1;
 3835:                                         }
 3836:                                     } else {
 3837:                                         $removed = 1;
 3838:                                     }
 3839:                                 } else {
 3840:                                     $stale = 1;
 3841:                                 }
 3842:                                 if ($stale) {
 3843:                                     if (unlink($fname)) {
 3844:                                         if ($uri!~/\.meta$/) {
 3845:                                             if (-e $fname.'.meta') {
 3846:                                                 unlink($fname.'.meta');
 3847:                                             }
 3848:                                         }
 3849:                                         my $unsubresult = &unsubscribe($fname);
 3850:                                         unless ($unsubresult eq 'ok') {
 3851:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3852:                                         }
 3853:                                         $removed = 1;
 3854:                                     }
 3855:                                 }
 3856:                             }
 3857:                         }
 3858:                     }
 3859:                 }
 3860:             }
 3861:         }
 3862:     }
 3863:     return $removed;
 3864: }
 3865: 
 3866: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3867: 
 3868: sub allowuploaded {
 3869:     my ($srcurl,$url)=@_;
 3870:     $url=&clutter(&declutter($url));
 3871:     my $dir=$url;
 3872:     $dir=~s/\/[^\/]+$//;
 3873:     my %httpref=();
 3874:     my $httpurl=&hreflocation('',$url);
 3875:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3876:     &Apache::lonnet::appenv(\%httpref);
 3877: }
 3878: 
 3879: #
 3880: # Determine if the current user should be able to edit a particular resource,
 3881: # when viewing in course context.
 3882: # (a) When viewing resource used to determine if "Edit" item is included in 
 3883: #     Functions.
 3884: # (b) When displaying folder contents in course editor, used to determine if
 3885: #     "Edit" link will be displayed alongside resource.
 3886: #
 3887: #  input: six args -- filename (decluttered), course number, course domain,
 3888: #                   url, symb (if registered) and group (if this is a group
 3889: #                   item -- e.g., bulletin board, group page etc.).
 3890: #  output: array of five scalars -- 
 3891: #          $cfile -- url for file editing if editable on current server
 3892: #          $home -- homeserver of resource (i.e., for author if published,
 3893: #                                           or course if uploaded.).
 3894: #          $switchserver --  1 if server switch will be needed.
 3895: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3896: #          $forceview -- 1 if icon/link should be to go to view mode
 3897: #
 3898: 
 3899: sub can_edit_resource {
 3900:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3901:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3902: #
 3903: # For aboutme pages user can only edit his/her own.
 3904: #
 3905:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3906:         my ($sdom,$sname) = ($1,$2);
 3907:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3908:             $home = $env{'user.home'};
 3909:             $cfile = $resurl;
 3910:             if ($env{'form.forceedit'}) {
 3911:                 $forceview = 1;
 3912:             } else {
 3913:                 $forceedit = 1;
 3914:             }
 3915:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3916:         } else {
 3917:             return;
 3918:         }
 3919:     }
 3920: 
 3921:     if ($env{'request.course.id'}) {
 3922:         my $crsedit = &allowed('mdc',$env{'request.course.id'});
 3923:         if ($group ne '') {
 3924: # if this is a group homepage or group bulletin board, check group privs
 3925:             my $allowed = 0;
 3926:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3927:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3928:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3929:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3930:                     $allowed = 1;
 3931:                 }
 3932:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3933:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3934:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3935:                     $allowed = 1;
 3936:                 }
 3937:             }
 3938:             if ($allowed) {
 3939:                 $home=&homeserver($cnum,$cdom);
 3940:                 if ($env{'form.forceedit'}) {
 3941:                     $forceview = 1;
 3942:                 } else {
 3943:                     $forceedit = 1;
 3944:                 }
 3945:                 $cfile = $resurl;
 3946:             } else {
 3947:                 return;
 3948:             }
 3949:         } else {
 3950:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3951:                 unless (&allowed('opa',$env{'request.course.id'})) {
 3952:                     return;
 3953:                 }
 3954:             } elsif (!$crsedit) {
 3955:                 if ($env{'request.role'} =~ m{^st\./$cdom/$cnum}) {
 3956: #
 3957: # No edit allowed where CC has switched to student role.
 3958: #
 3959:                     return;
 3960:                 } elsif (($resurl !~ m{^/res/$match_domain/$match_username/}) ||
 3961:                          ($resurl =~ m{^/res/lib/templates/})) {
 3962:                     return;
 3963:                 }
 3964:             }
 3965:         }
 3966:     }
 3967: 
 3968:     if ($file ne '') {
 3969:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3970:             if (&is_course_upload($file,$cnum,$cdom)) {
 3971:                 $uploaded = 1;
 3972:                 $incourse = 1;
 3973:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3974:                     $cfile = &hreflocation('',$file);
 3975:                     if ($env{'form.forceedit'}) {
 3976:                         $forceview = 1;
 3977:                     } else {
 3978:                         $forceedit = 1;
 3979:                     }
 3980:                 }
 3981:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3982:                 $incourse = 1;
 3983:                 if ($env{'form.forceedit'}) {
 3984:                     $forceview = 1;
 3985:                 } else {
 3986:                     $forceedit = 1;
 3987:                 }
 3988:                 $cfile = $resurl;
 3989:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3990:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3991:                     $incourse = 1;
 3992:                     if ($env{'form.forceedit'}) {
 3993:                         $forceview = 1;
 3994:                     } else {
 3995:                         $forceedit = 1;
 3996:                     }
 3997:                     $cfile = $resurl;
 3998:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3999:                     $incourse = 1;
 4000:                     $cfile = $resurl.'/smpedit';
 4001:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 4002:                     $incourse = 1;
 4003:                     if ($env{'form.forceedit'}) {
 4004:                         $forceview = 1;
 4005:                     } else {
 4006:                         $forceedit = 1;
 4007:                     }
 4008:                     $cfile = $resurl;
 4009:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 4010:                     my ($map,$id,$res) = &decode_symb($symb);
 4011:                     if ($map =~ /\.page$/) {
 4012:                         $incourse = 1;
 4013:                         if ($env{'form.forceedit'}) {
 4014:                             $forceview = 1;
 4015:                             $cfile = $map;
 4016:                         } else {
 4017:                             $forceedit = 1;
 4018:                             $cfile =  '/adm/wrapper'.$resurl;
 4019:                         }
 4020:                     }
 4021:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4022:                     $incourse = 1;
 4023:                     if ($env{'form.forceedit'}) {
 4024:                         $forceview = 1;
 4025:                     } else {
 4026:                         $forceedit = 1;
 4027:                     }
 4028:                     $cfile = $resurl;
 4029:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4030:                     $incourse = 1;
 4031:                     if ($env{'form.forceedit'}) {
 4032:                         $forceview = 1;
 4033:                     } else {
 4034:                         $forceedit = 1;
 4035:                     }
 4036:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4037:                 }
 4038:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 4039:                 my $template = '/res/lib/templates/simpleproblem.problem';
 4040:                 if (&is_on_map($template)) { 
 4041:                     $incourse = 1;
 4042:                     $forceview = 1;
 4043:                     $cfile = $template;
 4044:                 }
 4045:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4046:                 $incourse = 1;
 4047:                 if ($env{'form.forceedit'}) {
 4048:                     $forceview = 1;
 4049:                 } else {
 4050:                     $forceedit = 1;
 4051:                 }
 4052:                 $cfile = $resurl;
 4053:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 4054:                 $incourse = 1;
 4055:                 if ($env{'form.forceedit'}) {
 4056:                     $forceview = 1;
 4057:                 } else {
 4058:                     $forceedit = 1;
 4059:                 }
 4060:                 $cfile = $resurl;
 4061:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 4062:                 $incourse = 1;
 4063:                 $forceview = 1;
 4064:                 if ($symb) {
 4065:                     my ($map,$id,$res)=&decode_symb($symb);
 4066:                     $env{'request.symb'} = $symb;
 4067:                     $cfile = &clutter($res);
 4068:                 } else {
 4069:                     $cfile = $env{'form.suppurl'};
 4070:                     my $escfile = &unescape($cfile);
 4071:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 4072:                         $cfile = '/adm/wrapper'.$escfile;
 4073:                     } else {
 4074:                         $escfile =~ s{^http://}{};
 4075:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 4076:                     }
 4077:                 }
 4078:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 4079:                 if ($env{'form.forceedit'}) {
 4080:                     $forceview = 1;
 4081:                 } else {
 4082:                     $forceedit = 1;
 4083:                 }
 4084:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 4085:             }
 4086:         }
 4087:         if ($uploaded || $incourse) {
 4088:             $home=&homeserver($cnum,$cdom);
 4089:         } elsif ($file !~ m{/$}) {
 4090:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 4091:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 4092:             # Check that the user has permission to edit this resource
 4093:             my $setpriv = 1;
 4094:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 4095:             if (defined($cfudom)) {
 4096:                 $home=&homeserver($cfuname,$cfudom);
 4097:                 $cfile=$file;
 4098:             }
 4099:         }
 4100:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 4101:             (($home ne '') && ($home ne 'no_host'))) {
 4102:             my @ids=&current_machine_ids();
 4103:             unless (grep(/^\Q$home\E$/,@ids)) {
 4104:                 $switchserver=1;
 4105:             }
 4106:         }
 4107:     }
 4108:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 4109: }
 4110: 
 4111: sub is_course_upload {
 4112:     my ($file,$cnum,$cdom) = @_;
 4113:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 4114:     $uploadpath =~ s{^\/}{};
 4115:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 4116:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 4117:         return 1;
 4118:     }
 4119:     return;
 4120: }
 4121: 
 4122: sub in_course {
 4123:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 4124:     if ($hideprivileged) {
 4125:         my $skipuser;
 4126:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 4127:         my @possdoms = ($cdom);  
 4128:         if ($coursehash{'checkforpriv'}) { 
 4129:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 4130:         }
 4131:         if (&privileged($uname,$udom,\@possdoms)) {
 4132:             $skipuser = 1;
 4133:             if ($coursehash{'nothideprivileged'}) {
 4134:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4135:                     my $user;
 4136:                     if ($item =~ /:/) {
 4137:                         $user = $item;
 4138:                     } else {
 4139:                         $user = join(':',split(/[\@]/,$item));
 4140:                     }
 4141:                     if ($user eq $uname.':'.$udom) {
 4142:                         undef($skipuser);
 4143:                         last;
 4144:                     }
 4145:                 }
 4146:             }
 4147:             if ($skipuser) {
 4148:                 return 0;
 4149:             }
 4150:         }
 4151:     }
 4152:     $type ||= 'any';
 4153:     if (!defined($cdom) || !defined($cnum)) {
 4154:         my $cid  = $env{'request.course.id'};
 4155:         $cdom = $env{'course.'.$cid.'.domain'};
 4156:         $cnum = $env{'course.'.$cid.'.num'};
 4157:     }
 4158:     my $typesref;
 4159:     if (($type eq 'any') || ($type eq 'all')) {
 4160:         $typesref = ['active','previous','future'];
 4161:     } elsif ($type eq 'previous' || $type eq 'future') {
 4162:         $typesref = [$type];
 4163:     }
 4164:     my %roles = &get_my_roles($uname,$udom,'userroles',
 4165:                               $typesref,undef,[$cdom]);
 4166:     my ($tmp) = keys(%roles);
 4167:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 4168:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 4169:     if (@course_roles > 0) {
 4170:         return 1;
 4171:     }
 4172:     return 0;
 4173: }
 4174: 
 4175: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 4176: # input: action, courseID, current domain, intended
 4177: #        path to file, source of file, instruction to parse file for objects,
 4178: #        ref to hash for embedded objects,
 4179: #        ref to hash for codebase of java objects.
 4180: #        reference to scalar to accommodate mime type determined
 4181: #          from File::MMagic if $parser = parse.
 4182: #
 4183: # output: url to file (if action was uploaddoc), 
 4184: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 4185: #
 4186: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 4187: # course.
 4188: #
 4189: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4190: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 4191: #          course's home server.
 4192: #
 4193: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 4194: #          be copied from $source (current location) to 
 4195: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4196: #         and will then be copied to
 4197: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 4198: #         course's home server.
 4199: #
 4200: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4201: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 4202: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 4203: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 4204: #         in course's home server.
 4205: #
 4206: 
 4207: sub process_coursefile {
 4208:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 4209:         $mimetype)=@_;
 4210:     my $fetchresult;
 4211:     my $home=&homeserver($docuname,$docudom);
 4212:     if ($action eq 'propagate') {
 4213:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4214: 			     $home);
 4215:     } else {
 4216:         my $fpath = '';
 4217:         my $fname = $file;
 4218:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4219:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4220:         my $filepath = &build_filepath($fpath);
 4221:         if ($action eq 'copy') {
 4222:             if ($source eq '') {
 4223:                 $fetchresult = 'no source file';
 4224:                 return $fetchresult;
 4225:             } else {
 4226:                 my $destination = $filepath.'/'.$fname;
 4227:                 rename($source,$destination);
 4228:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4229:                                  $home);
 4230:             }
 4231:         } elsif ($action eq 'uploaddoc') {
 4232:             open(my $fh,'>',$filepath.'/'.$fname);
 4233:             print $fh $env{'form.'.$source};
 4234:             close($fh);
 4235:             if ($parser eq 'parse') {
 4236:                 my $mm = new File::MMagic;
 4237:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 4238:                 if ($type eq 'text/html') {
 4239:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 4240:                     unless ($parse_result eq 'ok') {
 4241:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 4242:                     }
 4243:                 }
 4244:                 if (ref($mimetype)) {
 4245:                     $$mimetype = $type;
 4246:                 } 
 4247:             }
 4248:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4249:                                  $home);
 4250:             if ($fetchresult eq 'ok') {
 4251:                 return '/uploaded/'.$fpath.'/'.$fname;
 4252:             } else {
 4253:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4254:                         ' to host '.$home.': '.$fetchresult);
 4255:                 return '/adm/notfound.html';
 4256:             }
 4257:         }
 4258:     }
 4259:     unless ( $fetchresult eq 'ok') {
 4260:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4261:              ' to host '.$home.': '.$fetchresult);
 4262:     }
 4263:     return $fetchresult;
 4264: }
 4265: 
 4266: sub build_filepath {
 4267:     my ($fpath) = @_;
 4268:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 4269:     unless ($fpath eq '') {
 4270:         my @parts=split('/',$fpath);
 4271:         foreach my $part (@parts) {
 4272:             $filepath.= '/'.$part;
 4273:             if ((-e $filepath)!=1) {
 4274:                 mkdir($filepath,0777);
 4275:             }
 4276:         }
 4277:     }
 4278:     return $filepath;
 4279: }
 4280: 
 4281: sub store_edited_file {
 4282:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 4283:     my $file = $primary_url;
 4284:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 4285:     my $fpath = '';
 4286:     my $fname = $file;
 4287:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 4288:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 4289:     my $filepath = &build_filepath($fpath);
 4290:     open(my $fh,'>',$filepath.'/'.$fname);
 4291:     print $fh $content;
 4292:     close($fh);
 4293:     my $home=&homeserver($docuname,$docudom);
 4294:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 4295: 			  $home);
 4296:     if ($$fetchresult eq 'ok') {
 4297:         return '/uploaded/'.$fpath.'/'.$fname;
 4298:     } else {
 4299:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 4300: 		 ' to host '.$home.': '.$$fetchresult);
 4301:         return '/adm/notfound.html';
 4302:     }
 4303: }
 4304: 
 4305: sub clean_filename {
 4306:     my ($fname,$args)=@_;
 4307: # Replace Windows backslashes by forward slashes
 4308:     $fname=~s/\\/\//g;
 4309:     if (!$args->{'keep_path'}) {
 4310:         # Get rid of everything but the actual filename
 4311: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 4312:     }
 4313: # Replace spaces by underscores
 4314:     $fname=~s/\s+/\_/g;
 4315: # Transliterate non-ascii text to ascii
 4316:     my $lang = &Apache::lonlocal::current_language();
 4317:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 4318: # Replace all other weird characters by nothing
 4319:     $fname=~s{[^/\w\.\-]}{}g;
 4320: # Replace all .\d. sequences with _\d. so they no longer look like version
 4321: # numbers
 4322:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 4323: # Replace three or more adjacent underscores with one for consistency 
 4324: # with loncfile::filename_check() so complete url can be extracted by
 4325: # lonnet::decode_symb()
 4326:     $fname=~s/_{3,}/_/g;
 4327:     return $fname;
 4328: }
 4329: 
 4330: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 4331: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 4332: # image with the same aspect ratio as the original, but with dimensions which do 
 4333: # not exceed $resizewidth and $resizeheight.
 4334:  
 4335: sub resizeImage {
 4336:     my ($img_path,$resizewidth,$resizeheight) = @_;
 4337:     my $ima = Image::Magick->new;
 4338:     my $resized;
 4339:     if (-e $img_path) {
 4340:         $ima->Read($img_path);
 4341:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 4342:             my $width = $ima->Get('width');
 4343:             my $height = $ima->Get('height');
 4344:             if ($width > $resizewidth) {
 4345: 	        my $factor = $width/$resizewidth;
 4346:                 my $newheight = $height/$factor;
 4347:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 4348:                 $resized = 1;
 4349:             }
 4350:         }
 4351:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 4352:             my $width = $ima->Get('width');
 4353:             my $height = $ima->Get('height');
 4354:             if ($height > $resizeheight) {
 4355:                 my $factor = $height/$resizeheight;
 4356:                 my $newwidth = $width/$factor;
 4357:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 4358:                 $resized = 1;
 4359:             }
 4360:         }
 4361:         if ($resized) {
 4362:             $ima->Write($img_path);
 4363:         }
 4364:     }
 4365:     return;
 4366: }
 4367: 
 4368: # --------------- Take an uploaded file and put it into the userfiles directory
 4369: # input: $formname - the contents of the file are in $env{"form.$formname"}
 4370: #                    the desired filename is in $env{"form.$formname.filename"}
 4371: #        $context - possible values: coursedoc, existingfile, overwrite, 
 4372: #                                    canceloverwrite, scantron, toollogo  or ''.
 4373: #                   if 'coursedoc': upload to the current course
 4374: #                   if 'existingfile': write file to tmp/overwrites directory 
 4375: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 4376: #                   $context is passed as argument to &finishuserfileupload
 4377: #        $subdir - directory in userfile to store the file into
 4378: #        $parser - instruction to parse file for objects ($parser = parse) or
 4379: #                  if context is 'scantron', $parser is hashref of csv column mapping
 4380: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
 4381: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 4382: #        $allfiles - reference to hash for embedded objects
 4383: #        $codebase - reference to hash for codebase of java objects
 4384: #        $destuname - username for permanent storage of uploaded file
 4385: #        $destudom - domain for permanaent storage of uploaded file
 4386: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 4387: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 4388: #        $resizewidth - width (pixels) to which to resize uploaded image
 4389: #        $resizeheight - height (pixels) to which to resize uploaded image
 4390: #        $mimetype - reference to scalar to accommodate mime type determined
 4391: #                    from File::MMagic.
 4392: # 
 4393: # output: url of file in userspace, or error: <message> 
 4394: #             or /adm/notfound.html if failure to upload occurse
 4395: 
 4396: sub userfileupload {
 4397:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 4398:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 4399:     if (!defined($subdir)) { $subdir='unknown'; }
 4400:     my $fname=$env{'form.'.$formname.'.filename'};
 4401:     $fname=&clean_filename($fname);
 4402:     # See if there is anything left
 4403:     unless ($fname) { return 'error: no uploaded file'; }
 4404:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 4405:     if ($fname =~ /^\./) {
 4406:         my ($s,$usec) = &gettimeofday();
 4407:         while (length($usec) < 6) {
 4408:             $usec = '0'.$usec;
 4409:         }
 4410:         $fname = $s.'_'.substr($usec,0,3).$fname;
 4411:     }
 4412:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 4413:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 4414:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 4415:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4416:         my $now = time;
 4417:         my $filepath;
 4418:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 4419:              $filepath = 'tmp/helprequests/'.$now;
 4420:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 4421:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 4422:                          '_'.$env{'user.domain'}.'/pending';
 4423:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 4424:             my ($docuname,$docudom);
 4425:             if ($destudom =~ /^$match_domain$/) {
 4426:                 $docudom = $destudom;
 4427:             } else {
 4428:                 $docudom = $env{'user.domain'};
 4429:             }
 4430:             if ($destuname =~ /^$match_username$/) {
 4431:                 $docuname = $destuname;
 4432:             } else {
 4433:                 $docuname = $env{'user.name'};
 4434:             }
 4435:             if (exists($env{'form.group'})) {
 4436:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4437:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4438:             }
 4439:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 4440:             if ($context eq 'canceloverwrite') {
 4441:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 4442:                 if (-e  $tempfile) {
 4443:                     my @info = stat($tempfile);
 4444:                     if ($info[9] eq $env{'form.timestamp'}) {
 4445:                         unlink($tempfile);
 4446:                     }
 4447:                 }
 4448:                 return;
 4449:             }
 4450:         }
 4451:         # Create the directory if not present
 4452:         my @parts=split(/\//,$filepath);
 4453:         my $fullpath = $perlvar{'lonDaemons'};
 4454:         for (my $i=0;$i<@parts;$i++) {
 4455:             $fullpath .= '/'.$parts[$i];
 4456:             if ((-e $fullpath)!=1) {
 4457:                 mkdir($fullpath,0777);
 4458:             }
 4459:         }
 4460:         open(my $fh,'>',$fullpath.'/'.$fname);
 4461:         print $fh $env{'form.'.$formname};
 4462:         close($fh);
 4463:         if ($context eq 'existingfile') {
 4464:             my @info = stat($fullpath.'/'.$fname);
 4465:             return ($fullpath.'/'.$fname,$info[9]);
 4466:         } else {
 4467:             return $fullpath.'/'.$fname;
 4468:         }
 4469:     }
 4470:     if ($subdir eq 'scantron') {
 4471:         $fname = 'scantron_orig_'.$fname;
 4472:     } else {
 4473:         $fname="$subdir/$fname";
 4474:     }
 4475:     if ($context eq 'coursedoc') {
 4476: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4477: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4478:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 4479:             return &finishuserfileupload($docuname,$docudom,
 4480: 					 $formname,$fname,$parser,$allfiles,
 4481: 					 $codebase,$thumbwidth,$thumbheight,
 4482:                                          $resizewidth,$resizeheight,$context,$mimetype);
 4483:         } else {
 4484:             if ($env{'form.folder'}) {
 4485:                 $fname=$env{'form.folder'}.'/'.$fname;
 4486:             }
 4487:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 4488: 				       $fname,$formname,$parser,
 4489: 				       $allfiles,$codebase,$mimetype);
 4490:         }
 4491:     } elsif (defined($destuname)) {
 4492:         my $docuname=$destuname;
 4493:         my $docudom=$destudom;
 4494: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4495: 				     $parser,$allfiles,$codebase,
 4496:                                      $thumbwidth,$thumbheight,
 4497:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4498:     } else {
 4499:         my $docuname=$env{'user.name'};
 4500:         my $docudom=$env{'user.domain'};
 4501:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 4502:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4503:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4504:         }
 4505: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 4506: 				     $parser,$allfiles,$codebase,
 4507:                                      $thumbwidth,$thumbheight,
 4508:                                      $resizewidth,$resizeheight,$context,$mimetype);
 4509:     }
 4510: }
 4511: 
 4512: sub finishuserfileupload {
 4513:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 4514:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 4515:     my $path=$docudom.'/'.$docuname.'/';
 4516:     my $filepath=$perlvar{'lonDocRoot'};
 4517:   
 4518:     my ($fnamepath,$file,$fetchthumb);
 4519:     $file=$fname;
 4520:     if ($fname=~m|/|) {
 4521:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 4522: 	$path.=$fnamepath.'/';
 4523:     }
 4524:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 4525:     my $count;
 4526:     for ($count=4;$count<=$#parts;$count++) {
 4527:         $filepath.="/$parts[$count]";
 4528:         if ((-e $filepath)!=1) {
 4529: 	    mkdir($filepath,0777);
 4530:         }
 4531:     }
 4532: 
 4533: # Save the file
 4534:     {
 4535: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 4536: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 4537: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 4538: 	    return '/adm/notfound.html';
 4539: 	}
 4540:         if ($context eq 'overwrite') {
 4541:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 4542:             my $target = $filepath.'/'.$file;
 4543:             if (-e $source) {
 4544:                 my @info = stat($source);
 4545:                 if ($info[9] eq $env{'form.timestamp'}) {   
 4546:                     unless (&File::Copy::move($source,$target)) {
 4547:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 4548:                         return "Moving from $source failed";
 4549:                     }
 4550:                 } else {
 4551:                     return "Temporary file: $source had unexpected date/time for last modification";
 4552:                 }
 4553:             } else {
 4554:                 return "Temporary file: $source missing";
 4555:             }
 4556:         } elsif (!print FH ($env{'form.'.$formname})) {
 4557: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 4558: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 4559: 	    return '/adm/notfound.html';
 4560: 	}
 4561: 	close(FH);
 4562:         if ($resizewidth && $resizeheight) {
 4563:             my $mm = new File::MMagic;
 4564:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 4565:             if ($mime_type =~ m{^image/}) {
 4566: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 4567:             }  
 4568: 	}
 4569:     }
 4570:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4571:         if (ref($mimetype)) {
 4572:             if ($$mimetype eq '') {
 4573:                 my $mm = new File::MMagic;
 4574:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4575:                 $$mimetype = $type;
 4576:             }
 4577:         }
 4578:     }
 4579:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4580:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4581:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4582:                                                        $allfiles,$codebase);
 4583:             unless ($parse_result eq 'ok') {
 4584:                 &logthis('Failed to parse '.$filepath.$file.
 4585: 	   	         ' for embedded media: '.$parse_result); 
 4586:             }
 4587:         }
 4588:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4589:         my $format = $env{'form.scantron_format'};
 4590:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4591:     }
 4592:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4593:         my $input = $filepath.'/'.$file;
 4594:         my $output = $filepath.'/'.'tn-'.$file;
 4595:         my $makethumb; 
 4596:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4597:         if ($context eq 'toollogo') {
 4598:             my ($fullwidth,$fullheight) = &check_dimensions($input);
 4599:             if ($fullwidth ne '' && $fullheight ne '') {
 4600:                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
 4601:                     $makethumb = 1;
 4602:                 }
 4603:             }
 4604:         } else {
 4605:             $makethumb = 1;
 4606:         }
 4607:         if ($makethumb) {
 4608:             my @args = ('convert','-sample',$thumbsize,$input,$output);
 4609:             system({$args[0]} @args);
 4610:             if (-e $filepath.'/'.'tn-'.$file) {
 4611:                 $fetchthumb  = 1; 
 4612:             }
 4613:         }
 4614:     }
 4615:  
 4616: # Notify homeserver to grep it
 4617: #
 4618:     my $docuhome=&homeserver($docuname,$docudom);	
 4619:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4620:     if ($fetchresult eq 'ok') {
 4621:         if ($fetchthumb) {
 4622:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4623:             if ($thumbresult ne 'ok') {
 4624:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4625:                          $docuhome.': '.$thumbresult);
 4626:             }
 4627:         }
 4628: #
 4629: # Return the URL to it
 4630:         return '/uploaded/'.$path.$file;
 4631:     } else {
 4632:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4633: 		 ': '.$fetchresult);
 4634:         return '/adm/notfound.html';
 4635:     }
 4636: }
 4637: 
 4638: sub extract_embedded_items {
 4639:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4640:     my @state = ();
 4641:     my (%lastids,%related,%shockwave,%flashvars);
 4642:     my %javafiles = (
 4643:                       codebase => '',
 4644:                       code => '',
 4645:                       archive => ''
 4646:                     );
 4647:     my %mediafiles = (
 4648:                       src => '',
 4649:                       movie => '',
 4650:                      );
 4651:     my $p;
 4652:     if ($content) {
 4653:         $p = HTML::LCParser->new($content);
 4654:     } else {
 4655:         $p = HTML::LCParser->new($fullpath);
 4656:     }
 4657:     while (my $t=$p->get_token()) {
 4658: 	if ($t->[0] eq 'S') {
 4659: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4660: 	    push(@state, $tagname);
 4661:             if (lc($tagname) eq 'allow') {
 4662:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4663:             }
 4664: 	    if (lc($tagname) eq 'img') {
 4665: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4666: 	    }
 4667: 	    if (lc($tagname) eq 'a') {
 4668:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4669:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4670:                 }
 4671: 	    }
 4672:             if (lc($tagname) eq 'script') {
 4673:                 my $src;
 4674:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4675:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4676:                 } else {
 4677:                     if ($attr->{'src'} ne '') {
 4678:                         $src = $attr->{'src'};
 4679:                         &add_filetype($allfiles,$src,'src');
 4680:                     }
 4681:                 }
 4682:                 my $text = $p->get_trimmed_text();
 4683:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4684:                     my @swfargs = split(/,/,$1);
 4685:                     foreach my $item (@swfargs) {
 4686:                         $item =~ s/["']//g;
 4687:                         $item =~ s/^\s+//;
 4688:                         $item =~ s/\s+$//;
 4689:                     }
 4690:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4691:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4692:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4693:                         } else {
 4694:                             $related{$swfargs[0]} = [$swfargs[2]];
 4695:                         }
 4696:                     }
 4697:                 }
 4698:             }
 4699:             if (lc($tagname) eq 'link') {
 4700:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4701:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4702:                 }
 4703:             }
 4704: 	    if (lc($tagname) eq 'object' ||
 4705: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4706: 		foreach my $item (keys(%javafiles)) {
 4707: 		    $javafiles{$item} = '';
 4708: 		}
 4709:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4710:                     $lastids{lc($tagname)} = $attr->{'id'};
 4711:                 }
 4712: 	    }
 4713: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4714: 		my $name = lc($attr->{'name'});
 4715: 		foreach my $item (keys(%javafiles)) {
 4716: 		    if ($name eq $item) {
 4717: 			$javafiles{$item} = $attr->{'value'};
 4718: 			last;
 4719: 		    }
 4720: 		}
 4721:                 my $pathfrom;
 4722: 		foreach my $item (keys(%mediafiles)) {
 4723: 		    if ($name eq $item) {
 4724:                         $pathfrom = $attr->{'value'};
 4725:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4726: 			&add_filetype($allfiles,$pathfrom,$name);
 4727: 			last;
 4728: 		    }
 4729: 		}
 4730:                 if ($name eq 'flashvars') {
 4731:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4732:                 }
 4733:                 if ($pathfrom ne '') {
 4734:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4735:                                          $pathfrom);
 4736:                 }
 4737: 	    }
 4738: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4739: 		foreach my $item (keys(%javafiles)) {
 4740: 		    if ($attr->{$item}) {
 4741: 			$javafiles{$item} = $attr->{$item};
 4742: 			last;
 4743: 		    }
 4744: 		}
 4745: 		foreach my $item (keys(%mediafiles)) {
 4746: 		    if ($attr->{$item}) {
 4747: 			&add_filetype($allfiles,$attr->{$item},$item);
 4748: 			last;
 4749: 		    }
 4750: 		}
 4751:                 if (lc($tagname) eq 'embed') {
 4752:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4753:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4754:                                              $attr->{'src'});
 4755:                     }
 4756:                 }
 4757: 	    }
 4758:             if (lc($tagname) eq 'iframe') {
 4759:                 my $src = $attr->{'src'} ;
 4760:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4761:                     &add_filetype($allfiles,$src,'src');
 4762:                 } elsif ($src =~ m{^/}) {
 4763:                     if ($env{'request.course.id'}) {
 4764:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4765:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4766:                         my $url = &hreflocation('',$fullpath);
 4767:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4768:                             my $relpath = $1;
 4769:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4770:                                 &add_filetype($allfiles,$1,'src');
 4771:                             }
 4772:                         }
 4773:                     }
 4774:                 }
 4775:             }
 4776:             if ($t->[4] =~ m{/>$}) {
 4777:                 pop(@state);
 4778:             }
 4779: 	} elsif ($t->[0] eq 'E') {
 4780: 	    my ($tagname) = ($t->[1]);
 4781: 	    if ($javafiles{'codebase'} ne '') {
 4782: 		$javafiles{'codebase'} .= '/';
 4783: 	    }  
 4784: 	    if (lc($tagname) eq 'applet' ||
 4785: 		lc($tagname) eq 'object' ||
 4786: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4787: 		) {
 4788: 		foreach my $item (keys(%javafiles)) {
 4789: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4790: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4791: 			&add_filetype($allfiles,$file,$item);
 4792: 		    }
 4793: 		}
 4794: 	    } 
 4795: 	    pop @state;
 4796: 	}
 4797:     }
 4798:     foreach my $id (sort(keys(%flashvars))) {
 4799:         if ($shockwave{$id} ne '') {
 4800:             my @pairs = split(/\&/,$flashvars{$id});
 4801:             foreach my $pair (@pairs) {
 4802:                 my ($key,$value) = split(/\=/,$pair);
 4803:                 if ($key eq 'thumb') {
 4804:                     &add_filetype($allfiles,$value,$key);
 4805:                 } elsif ($key eq 'content') {
 4806:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4807:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4808:                     if ($ext ne '') {
 4809:                         &add_filetype($allfiles,$path.$value,$ext);
 4810:                     }
 4811:                 }
 4812:             }
 4813:         }
 4814:     }
 4815:     return 'ok';
 4816: }
 4817: 
 4818: sub add_filetype {
 4819:     my ($allfiles,$file,$type)=@_;
 4820:     if (exists($allfiles->{$file})) {
 4821: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4822: 	    push(@{$allfiles->{$file}}, &escape($type));
 4823: 	}
 4824:     } else {
 4825: 	@{$allfiles->{$file}} = (&escape($type));
 4826:     }
 4827: }
 4828: 
 4829: sub embedded_dependency {
 4830:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4831:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4832:         if (($identifier ne '') &&
 4833:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4834:             ($pathfrom ne '')) {
 4835:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4836:             foreach my $dep (@{$related->{$identifier}}) {
 4837:                 &add_filetype($allfiles,$path.$dep,'object');
 4838:             }
 4839:         }
 4840:     }
 4841:     return;
 4842: }
 4843: 
 4844: sub check_dimensions {
 4845:     my ($inputfile) = @_;
 4846:     my ($fullwidth,$fullheight);
 4847:     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
 4848:         my $mm = new File::MMagic;
 4849:         my $mime_type = $mm->checktype_filename($inputfile);
 4850:         if ($mime_type =~ m{^image/}) {
 4851:             if (open(PIPE,"identify $inputfile 2>&1 |")) {
 4852:                 my $imageinfo = <PIPE>;
 4853:                 if (!close(PIPE)) {
 4854:                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
 4855:                 }
 4856:                 chomp($imageinfo);
 4857:                 my ($fullsize) =
 4858:                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
 4859:                 if ($fullsize) {
 4860:                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
 4861:                 }
 4862:             }
 4863:         }
 4864:     }
 4865:     return ($fullwidth,$fullheight);
 4866: }
 4867: 
 4868: sub bubblesheet_converter {
 4869:     my ($cdom,$fullpath,$config,$format) = @_;
 4870:     if ((&domain($cdom) ne '') &&
 4871:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4872:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4873:         my (%csvcols,%csvoptions);
 4874:         if (ref($config->{'fields'}) eq 'HASH') {  
 4875:             %csvcols = %{$config->{'fields'}};
 4876:         }
 4877:         if (ref($config->{'options'}) eq 'HASH') {
 4878:             %csvoptions = %{$config->{'options'}};
 4879:         }
 4880:         my %csvbynum = reverse(%csvcols);
 4881:         my %scantronconf = &get_scantron_config($format,$cdom);
 4882:         if (keys(%scantronconf)) {
 4883:             my %bynum = (
 4884:                           $scantronconf{CODEstart} => 'CODEstart',
 4885:                           $scantronconf{IDstart}   => 'IDstart',
 4886:                           $scantronconf{PaperID}   => 'PaperID',
 4887:                           $scantronconf{FirstName} => 'FirstName',
 4888:                           $scantronconf{LastName}  => 'LastName',
 4889:                           $scantronconf{Qstart}    => 'Qstart',
 4890:                         );
 4891:             my @ordered;
 4892:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4893:                 push(@ordered,$bynum{$item});
 4894:             }
 4895:             my %mapstart = (
 4896:                               CODEstart => 'CODE',
 4897:                               IDstart   => 'ID',
 4898:                               PaperID   => 'PaperID',
 4899:                               FirstName => 'FirstName',
 4900:                               LastName  => 'LastName',
 4901:                               Qstart    => 'FirstQuestion',
 4902:                            );
 4903:             my %maplength = (
 4904:                               CODEstart => 'CODElength',
 4905:                               IDstart   => 'IDlength',
 4906:                               PaperID   => 'PaperIDlength',
 4907:                               FirstName => 'FirstNamelength',
 4908:                               LastName  => 'LastNamelength',
 4909:             );
 4910:             if (open(my $fh,'<',$fullpath)) {
 4911:                 my $output;
 4912:                 my %lettdig = &letter_to_digits();
 4913:                 my %diglett = reverse(%lettdig);
 4914:                 my $numletts = scalar(keys(%lettdig));
 4915:                 my $num = 0;
 4916:                 while (my $line=<$fh>) {
 4917:                     $num ++;
 4918:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4919:                     $line =~ s{[\r\n]+$}{};
 4920:                     my %found;
 4921:                     my @values = split(/,/,$line,-1);
 4922:                     my ($qstart,$record);
 4923:                     for (my $i=0; $i<@values; $i++) {
 4924:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4925:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4926:                             if ($values[$i] eq '') {
 4927:                                 $values[$i] = $scantronconf{'Qoff'};
 4928:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4929:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4930:                                     $values[$i] = $lettdig{uc($values[$i])};
 4931:                                 }
 4932:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4933:                                 if ($values[$i] =~ /^[0-9]$/) {
 4934:                                     $values[$i] = $diglett{$values[$i]};
 4935:                                 }
 4936:                             } else {
 4937:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4938:                                     my $digit;
 4939:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4940:                                         $digit = $lettdig{uc($values[$i])}-1;
 4941:                                         if ($values[$i] eq 'J') {
 4942:                                             $digit += $numletts;
 4943:                                         }
 4944:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4945:                                         $digit = $values[$i]-1;
 4946:                                         if ($values[$i] eq '0') {
 4947:                                             $digit += $numletts;
 4948:                                         }
 4949:                                     }
 4950:                                     my $qval='';
 4951:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4952:                                         if ($j == $digit) {
 4953:                                             $qval .= $scantronconf{'Qon'};
 4954:                                         } else {
 4955:                                             $qval .= $scantronconf{'Qoff'};
 4956:                                         }
 4957:                                     }
 4958:                                     $values[$i] = $qval;
 4959:                                 }
 4960:                             }
 4961:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4962:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4963:                             }
 4964:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4965:                             if ($numblank > 0) {
 4966:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4967:                             }
 4968:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4969:                                 $qstart = $i;
 4970:                                 $found{$csvbynum{$i}} = $values[$i];
 4971:                             } else {
 4972:                                 $found{'FirstQuestion'} .= $values[$i];
 4973:                             }
 4974:                         } elsif (exists($csvbynum{$i})) {
 4975:                             if ($csvoptions{'rem'}) {
 4976:                                 $values[$i] =~ s/^\s+//;
 4977:                             }
 4978:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4979:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4980:                                     $values[$i] = '0'.$values[$i];
 4981:                                 }
 4982:                             }
 4983:                             $found{$csvbynum{$i}} = $values[$i];
 4984:                         }
 4985:                     }
 4986:                     foreach my $item (@ordered) {
 4987:                         my $currlength = 1+length($record);
 4988:                         my $numspaces = $scantronconf{$item} - $currlength;
 4989:                         if ($numspaces > 0) {
 4990:                             $record .= (' ' x $numspaces);
 4991:                         }
 4992:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4993:                             unless ($item eq 'Qstart') {
 4994:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4995:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4996:                                 }
 4997:                             }
 4998:                             $record .= $found{$mapstart{$item}};
 4999:                         }
 5000:                     }
 5001:                     $output .= "$record\n";
 5002:                 }
 5003:                 close($fh);
 5004:                 if ($output) {
 5005:                     if (open(my $fh,'>',$fullpath)) {
 5006:                         print $fh $output;
 5007:                         close($fh);
 5008:                     }
 5009:                 }
 5010:             }
 5011:         }
 5012:         return;
 5013:     }
 5014: }
 5015: 
 5016: sub letter_to_digits {
 5017:     my %lettdig = (
 5018:                     A => 1,
 5019:                     B => 2,
 5020:                     C => 3,
 5021:                     D => 4,
 5022:                     E => 5,
 5023:                     F => 6,
 5024:                     G => 7,
 5025:                     H => 8,
 5026:                     I => 9,
 5027:                     J => 0,
 5028:                   );
 5029:     return %lettdig;
 5030: }
 5031: 
 5032: sub get_scantron_config {
 5033:     my ($which,$cdom) = @_;
 5034:     my @lines = &get_scantronformat_file($cdom);
 5035:     my %config;
 5036:     #FIXME probably should move to XML it has already gotten a bit much now
 5037:     foreach my $line (@lines) {
 5038:         my ($name,$descrip)=split(/:/,$line);
 5039:         if ($name ne $which ) { next; }
 5040:         chomp($line);
 5041:         my @config=split(/:/,$line);
 5042:         $config{'name'}=$config[0];
 5043:         $config{'description'}=$config[1];
 5044:         $config{'CODElocation'}=$config[2];
 5045:         $config{'CODEstart'}=$config[3];
 5046:         $config{'CODElength'}=$config[4];
 5047:         $config{'IDstart'}=$config[5];
 5048:         $config{'IDlength'}=$config[6];
 5049:         $config{'Qstart'}=$config[7];
 5050:         $config{'Qlength'}=$config[8];
 5051:         $config{'Qoff'}=$config[9];
 5052:         $config{'Qon'}=$config[10];
 5053:         $config{'PaperID'}=$config[11];
 5054:         $config{'PaperIDlength'}=$config[12];
 5055:         $config{'FirstName'}=$config[13];
 5056:         $config{'FirstNamelength'}=$config[14];
 5057:         $config{'LastName'}=$config[15];
 5058:         $config{'LastNamelength'}=$config[16];
 5059:         $config{'BubblesPerRow'}=$config[17];
 5060:         last;
 5061:     }
 5062:     return %config;
 5063: }
 5064: 
 5065: sub get_scantronformat_file {
 5066:     my ($cdom) = @_;
 5067:     if ($cdom eq '') {
 5068:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 5069:     }
 5070:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 5071:     my $gottab = 0;
 5072:     my @lines;
 5073:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 5074:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 5075:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 5076:             if ($formatfile ne '-1') {
 5077:                 @lines = split("\n",$formatfile,-1);
 5078:                 $gottab = 1;
 5079:             }
 5080:         }
 5081:     }
 5082:     if (!$gottab) {
 5083:         my $confname = $cdom.'-domainconfig';
 5084:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 5085:         my $formatfile = &getfile($default);
 5086:         if ($formatfile ne '-1') {
 5087:             @lines = split("\n",$formatfile,-1);
 5088:             $gottab = 1;
 5089:         }
 5090:     }
 5091:     if (!$gottab) {
 5092:         my @domains = &current_machine_domains();
 5093:         if (grep(/^\Q$cdom\E$/,@domains)) {
 5094:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 5095:                 @lines = <$fh>;
 5096:                 close($fh);
 5097:             }
 5098:         } else {
 5099:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 5100:                 @lines = <$fh>;
 5101:                 close($fh);
 5102:             }
 5103:         }
 5104:         chomp(@lines);
 5105:     }
 5106:     return @lines;
 5107: }
 5108: 
 5109: sub removeuploadedurl {
 5110:     my ($url)=@_;	
 5111:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 5112:     return &removeuserfile($uname,$udom,$fname);
 5113: }
 5114: 
 5115: sub removeuserfile {
 5116:     my ($docuname,$docudom,$fname)=@_;
 5117:     my $home=&homeserver($docuname,$docudom);    
 5118:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 5119:     if ($result eq 'ok') {	
 5120:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 5121:             my $metafile = $fname.'.meta';
 5122:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 5123: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 5124:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 5125:             my $sqlresult = 
 5126:                 &update_portfolio_table($docuname,$docudom,$file,
 5127:                                         'portfolio_metadata',$group,
 5128:                                         'delete');
 5129:         }
 5130:     }
 5131:     return $result;
 5132: }
 5133: 
 5134: sub mkdiruserfile {
 5135:     my ($docuname,$docudom,$dir)=@_;
 5136:     my $home=&homeserver($docuname,$docudom);
 5137:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 5138: }
 5139: 
 5140: sub renameuserfile {
 5141:     my ($docuname,$docudom,$old,$new)=@_;
 5142:     my $home=&homeserver($docuname,$docudom);
 5143:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 5144:                         &escape("$old").':'.&escape("$new"),$home);
 5145:     if ($result eq 'ok') {
 5146:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 5147:             my $oldmeta = $old.'.meta';
 5148:             my $newmeta = $new.'.meta';
 5149:             my $metaresult = 
 5150:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 5151: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 5152:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 5153:             my $sqlresult = 
 5154:                 &update_portfolio_table($docuname,$docudom,$file,
 5155:                                         'portfolio_metadata',$group,
 5156:                                         'delete');
 5157:         }
 5158:     }
 5159:     return $result;
 5160: }
 5161: 
 5162: # ------------------------------------------------------------------------- Log
 5163: 
 5164: sub log {
 5165:     my ($dom,$nam,$hom,$what)=@_;
 5166:     return critical("log:$dom:$nam:$what",$hom);
 5167: }
 5168: 
 5169: # ------------------------------------------------------------------ Course Log
 5170: #
 5171: # This routine flushes several buffers of non-mission-critical nature
 5172: #
 5173: 
 5174: sub flushcourselogs {
 5175:     &logthis('Flushing log buffers');
 5176: #
 5177: # course logs
 5178: # This is a log of all transactions in a course, which can be used
 5179: # for data mining purposes
 5180: #
 5181: # It also collects the courseid database, which lists last transaction
 5182: # times and course titles for all courseids
 5183: #
 5184:     my %courseidbuffer=();
 5185:     foreach my $crsid (keys(%courselogs)) {
 5186:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 5187: 		          &escape($courselogs{$crsid}),
 5188: 		          $coursehombuf{$crsid}) eq 'ok') {
 5189: 	    delete $courselogs{$crsid};
 5190:         } else {
 5191:             &logthis('Failed to flush log buffer for '.$crsid);
 5192:             if (length($courselogs{$crsid})>40000) {
 5193:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 5194:                         " exceeded maximum size, deleting.</font>");
 5195:                delete $courselogs{$crsid};
 5196:             }
 5197:         }
 5198:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 5199:             'description' => $coursedescrbuf{$crsid},
 5200:             'inst_code'    => $courseinstcodebuf{$crsid},
 5201:             'type'        => $coursetypebuf{$crsid},
 5202:             'owner'       => $courseownerbuf{$crsid},
 5203:         };
 5204:     }
 5205: #
 5206: # Write course id database (reverse lookup) to homeserver of courses 
 5207: # Is used in pickcourse
 5208: #
 5209:     foreach my $crs_home (keys(%courseidbuffer)) {
 5210:         my $response = &courseidput(&host_domain($crs_home),
 5211:                                     $courseidbuffer{$crs_home},
 5212:                                     $crs_home,'timeonly');
 5213:     }
 5214: #
 5215: # File accesses
 5216: # Writes to the dynamic metadata of resources to get hit counts, etc.
 5217: #
 5218:     foreach my $entry (keys(%accesshash)) {
 5219:         if ($entry =~ /___count$/) {
 5220:             my ($dom,$name);
 5221:             ($dom,$name,undef)=
 5222: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 5223:             if (! defined($dom) || $dom eq '' || 
 5224:                 ! defined($name) || $name eq '') {
 5225:                 my $cid = $env{'request.course.id'};
 5226: #
 5227: # FIXME 11/29/2021
 5228: # Typo in rev. 1.458 (2003/12/09)??
 5229: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
 5230: #
 5231: # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
 5232: # $dom and $name will always be null, so the &inc() call will default to storing this data
 5233: # in a nohist_accesscount.db file for the user rather than the course.
 5234: #
 5235: # That said there is a lot of noise in the data being stored.
 5236: # So counts for prtspool/  and adm/ etc. are recorded.
 5237: #
 5238: # A review of which items ending '___count' are written to %accesshash should likely be 
 5239: # made before deciding whether to set these to 'course.' instead of 'request.'
 5240: #
 5241: # Under the current scheme each user receives a nohist_accesscount.db file listing 
 5242: # accesses for things which are not published resources, regardless of course, and
 5243: # there is not a nohist_accesscount.db file in a course, which might log accesses from
 5244: # anyone in the course for things which are not published resources.
 5245: #
 5246: # For an author, nohist_accesscount.db ends up having records for other items
 5247: # mixed up with the legitimate access counts for the author's published resources.
 5248: #
 5249:                 $dom  = $env{'request.'.$cid.'.domain'};
 5250:                 $name = $env{'request.'.$cid.'.num'};
 5251:             }
 5252:             my $value = $accesshash{$entry};
 5253:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 5254:             my %temphash=($url => $value);
 5255:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 5256:             if ($result eq 'ok') {
 5257:                 delete $accesshash{$entry};
 5258:             }
 5259:         } else {
 5260:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 5261:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 5262:             my %temphash=($entry => $accesshash{$entry});
 5263:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 5264:                 delete $accesshash{$entry};
 5265:             }
 5266:         }
 5267:     }
 5268: #
 5269: # Roles
 5270: # Reverse lookup of user roles for course faculty/staff and co-authorship
 5271: #
 5272:     foreach my $entry (keys(%userrolehash)) {
 5273:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 5274: 	    split(/\:/,$entry);
 5275:         if (&put('nohist_userroles',
 5276:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 5277:                 $rudom,$runame) eq 'ok') {
 5278: 	    delete $userrolehash{$entry};
 5279:         }
 5280:     }
 5281: #
 5282: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 5283: #
 5284:     my %domrolebuffer = ();
 5285:     foreach my $entry (keys(%domainrolehash)) {
 5286:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 5287:         if ($domrolebuffer{$rudom}) {
 5288:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 5289:                       '='.&escape($domainrolehash{$entry});
 5290:         } else {
 5291:             $domrolebuffer{$rudom}.=&escape($entry).
 5292:                       '='.&escape($domainrolehash{$entry});
 5293:         }
 5294:         delete $domainrolehash{$entry};
 5295:     }
 5296:     foreach my $dom (keys(%domrolebuffer)) {
 5297: 	my %servers;
 5298: 	if (defined(&domain($dom,'primary'))) {
 5299: 	    my $primary=&domain($dom,'primary');
 5300: 	    my $hostname=&hostname($primary);
 5301: 	    $servers{$primary} = $hostname;
 5302: 	} else { 
 5303: 	    %servers = &get_servers($dom,'library');
 5304: 	}
 5305: 	foreach my $tryserver (keys(%servers)) {
 5306: 	    if (&reply('domroleput:'.$dom.':'.
 5307: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 5308: 		last;
 5309: 	    } else {  
 5310: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 5311: 	    }
 5312:         }
 5313:     }
 5314:     $dumpcount++;
 5315: }
 5316: 
 5317: sub courselog {
 5318:     my $what=shift;
 5319:     $what=time.':'.$what;
 5320:     unless ($env{'request.course.id'}) { return ''; }
 5321:     $coursedombuf{$env{'request.course.id'}}=
 5322:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 5323:     $coursenumbuf{$env{'request.course.id'}}=
 5324:        $env{'course.'.$env{'request.course.id'}.'.num'};
 5325:     $coursehombuf{$env{'request.course.id'}}=
 5326:        $env{'course.'.$env{'request.course.id'}.'.home'};
 5327:     $coursedescrbuf{$env{'request.course.id'}}=
 5328:        $env{'course.'.$env{'request.course.id'}.'.description'};
 5329:     $courseinstcodebuf{$env{'request.course.id'}}=
 5330:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 5331:     $courseownerbuf{$env{'request.course.id'}}=
 5332:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 5333:     $coursetypebuf{$env{'request.course.id'}}=
 5334:        $env{'course.'.$env{'request.course.id'}.'.type'};
 5335:     if (defined $courselogs{$env{'request.course.id'}}) {
 5336: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 5337:     } else {
 5338: 	$courselogs{$env{'request.course.id'}}.=$what;
 5339:     }
 5340:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 5341: 	&flushcourselogs();
 5342:     }
 5343: }
 5344: 
 5345: sub courseacclog {
 5346:     my $fnsymb=shift;
 5347:     unless ($env{'request.course.id'}) { return ''; }
 5348:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 5349:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 5350:         $what.=':POST';
 5351:         # FIXME: Probably ought to escape things....
 5352: 	foreach my $key (keys(%env)) {
 5353:             if ($key=~/^form\.(.*)/) {
 5354:                 my $formitem = $1;
 5355:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 5356:                     $what.=':'.$formitem.'='.$env{$key};
 5357:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 5358:                     if ($formitem eq 'proctorpassword') {
 5359:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
 5360:                     } else {
 5361:                         $what.=':'.$formitem.'='.$env{$key};
 5362:                     }
 5363:                 }
 5364:             }
 5365:         }
 5366:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 5367:         # FIXME: We should not be depending on a form parameter that someone
 5368:         # editing lonsearchcat.pm might change in the future.
 5369:         if ($env{'form.phase'} eq 'course_search') {
 5370:             $what.= ':POST';
 5371:             # FIXME: Probably ought to escape things....
 5372:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 5373:                                  'crsdiscuss') {
 5374:                 $what.=':'.$element.'='.$env{'form.'.$element};
 5375:             }
 5376:         }
 5377:     }
 5378:     &courselog($what);
 5379: }
 5380: 
 5381: sub countacc {
 5382:     my $url=&declutter(shift);
 5383:     return if (! defined($url) || $url eq '');
 5384:     unless ($env{'request.course.id'}) { return ''; }
 5385: #
 5386: # Mark that this url was used in this course
 5387: #
 5388:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 5389: #
 5390: # Increase the access count for this resource in this child process
 5391: #
 5392:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 5393:     $accesshash{$key}++;
 5394: }
 5395: 
 5396: sub linklog {
 5397:     my ($from,$to)=@_;
 5398:     $from=&declutter($from);
 5399:     $to=&declutter($to);
 5400:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 5401:     $accesshash{$to.'___'.$from.'___goto'}=1;
 5402: }
 5403: 
 5404: sub statslog {
 5405:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 5406:     if ($users<2) { return; }
 5407:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 5408:             'course'       => $env{'request.course.id'},
 5409:             'sections'     => '"all"',
 5410:             'num_students' => $users,
 5411:             'part'         => $part,
 5412:             'symb'         => $symb,
 5413:             'mean_tries'   => $av_attempts,
 5414:             'deg_of_diff'  => $degdiff});
 5415:     foreach my $key (keys(%dynstore)) {
 5416:         $accesshash{$key}=$dynstore{$key};
 5417:     }
 5418: }
 5419:   
 5420: sub userrolelog {
 5421:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 5422:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 5423:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5424:        $userrolehash
 5425:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5426:                     =$tend.':'.$tstart;
 5427:     }
 5428:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 5429:        $userrolehash
 5430:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 5431:                     =$tend.':'.$tstart;
 5432:     }
 5433:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 5434:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 5435:        $domainrolehash
 5436:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 5437:                     = $tend.':'.$tstart;
 5438:     }
 5439: }
 5440: 
 5441: sub courserolelog {
 5442:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,
 5443:         $context,$othdomby,$requester)=@_;
 5444:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 5445:         my $cdom = $1;
 5446:         my $cnum = $2;
 5447:         my $sec = $3;
 5448:         my $namespace = 'rolelog';
 5449:         my %storehash = (
 5450:                            role    => $trole,
 5451:                            start   => $tstart,
 5452:                            end     => $tend,
 5453:                            selfenroll => $selfenroll,
 5454:                            context    => $context,
 5455:                         );
 5456:         if ($othdomby) {
 5457:             if ($othdomby eq 'othdombydc') {
 5458:                 $storehash{'approval'} = 'domain';
 5459:             } elsif ($othdomby eq 'othdombyuser') {
 5460:                 $storehash{'approval'} = 'user'; 
 5461:             }
 5462:             if ($requester ne '') {
 5463:                 $storehash{'requester'} = $requester;
 5464:             }
 5465:         }
 5466:         if ($trole eq 'gr') {
 5467:             $namespace = 'groupslog';
 5468:             $storehash{'group'} = $sec;
 5469:         } else {
 5470:             $storehash{'section'} = $sec;
 5471:         }
 5472:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 5473:                    $domain,$cnum,$cdom);
 5474:         if (($trole ne 'st') || ($sec ne '')) {
 5475:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 5476:         }
 5477:     }
 5478:     return;
 5479: }
 5480: 
 5481: sub domainrolelog {
 5482:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5483:         $context,$othdomby,$requester)=@_;
 5484:     if ($area =~ m{^/($match_domain)/$}) {
 5485:         my $cdom = $1;
 5486:         my $domconfiguser = &get_domainconfiguser($cdom);
 5487:         my $namespace = 'rolelog';
 5488:         my %storehash = (
 5489:                            role    => $trole,
 5490:                            start   => $tstart,
 5491:                            end     => $tend,
 5492:                            context => $context,
 5493:                         );
 5494:         if ($othdomby) {
 5495:             if ($othdomby eq 'othdombydc') {
 5496:                 $storehash{'approval'} = 'domain';
 5497:             } elsif ($othdomby eq 'othdombyuser') {
 5498:                 $storehash{'approval'} = 'user';
 5499:             }
 5500:             if ($requester ne '') {
 5501:                 $storehash{'requester'} = $requester;
 5502:             }
 5503:         }
 5504:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 5505:                    $domain,$domconfiguser,$cdom);
 5506:     }
 5507:     return;
 5508: 
 5509: }
 5510: 
 5511: sub coauthorrolelog {
 5512:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,
 5513:         $context,$othdomby,$requester)=@_;
 5514:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 5515:         my $audom = $1;
 5516:         my $auname = $2;
 5517:         my $namespace = 'rolelog';
 5518:         my %storehash = (
 5519:                            role    => $trole,
 5520:                            start   => $tstart,
 5521:                            end     => $tend,
 5522:                            context => $context,
 5523:                         );
 5524:         if ($othdomby) {
 5525:             if ($othdomby eq 'othdombydc') {
 5526:                 $storehash{'approval'} = 'domain';
 5527:             } elsif ($othdomby eq 'othdombyuser') {
 5528:                 $storehash{'approval'} = 'user';
 5529:             }
 5530:             if ($requester ne '') {
 5531:                 $storehash{'requester'} = $requester;
 5532:             }
 5533:         }
 5534:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 5535:                    $domain,$auname,$audom);
 5536:     }
 5537:     return;
 5538: }
 5539: 
 5540: sub get_course_adv_roles {
 5541:     my ($cid,$codes) = @_;
 5542:     $cid=$env{'request.course.id'} unless (defined($cid));
 5543:     my %coursehash=&coursedescription($cid);
 5544:     my $crstype = &Apache::loncommon::course_type($cid);
 5545:     my %nothide=();
 5546:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5547:         if ($user !~ /:/) {
 5548: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 5549:         } else {
 5550:             $nothide{$user}=1;
 5551:         }
 5552:     }
 5553:     my @possdoms = ($coursehash{'domain'});
 5554:     if ($coursehash{'checkforpriv'}) {
 5555:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 5556:     }
 5557:     my %returnhash=();
 5558:     my %dumphash=
 5559:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 5560:     my $now=time;
 5561:     my %privileged;
 5562:     foreach my $entry (keys(%dumphash)) {
 5563: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5564:         if (($tstart) && ($tstart<0)) { next; }
 5565:         if (($tend) && ($tend<$now)) { next; }
 5566:         if (($tstart) && ($now<$tstart)) { next; }
 5567:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 5568: 	if ($username eq '' || $domain eq '') { next; }
 5569:         if ((&privileged($username,$domain,\@possdoms)) &&
 5570:             (!$nothide{$username.':'.$domain})) { next; }
 5571: 	if ($role eq 'cr') { next; }
 5572:         if ($codes) {
 5573:             if ($section) { $role .= ':'.$section; }
 5574:             if ($returnhash{$role}) {
 5575:                 $returnhash{$role}.=','.$username.':'.$domain;
 5576:             } else {
 5577:                 $returnhash{$role}=$username.':'.$domain;
 5578:             }
 5579:         } else {
 5580:             my $key=&plaintext($role,$crstype);
 5581:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 5582:             if ($returnhash{$key}) {
 5583: 	        $returnhash{$key}.=','.$username.':'.$domain;
 5584:             } else {
 5585:                 $returnhash{$key}=$username.':'.$domain;
 5586:             }
 5587:         }
 5588:     }
 5589:     return %returnhash;
 5590: }
 5591: 
 5592: sub get_my_roles {
 5593:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 5594:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 5595:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 5596:     my (%dumphash,%nothide);
 5597:     if ($context eq 'userroles') {
 5598:         %dumphash = &dump('roles',$udom,$uname);
 5599:     } else {
 5600:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 5601:         if ($hidepriv) {
 5602:             my %coursehash=&coursedescription($udom.'_'.$uname);
 5603:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 5604:                 if ($user !~ /:/) {
 5605:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 5606:                 } else {
 5607:                     $nothide{$user} = 1;
 5608:                 }
 5609:             }
 5610:         }
 5611:     }
 5612:     my %returnhash=();
 5613:     my $now=time;
 5614:     my %privileged;
 5615:     foreach my $entry (keys(%dumphash)) {
 5616:         my ($role,$tend,$tstart);
 5617:         if ($context eq 'userroles') {
 5618:             next if ($entry =~ /^rolesdef/);
 5619: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 5620:         } else {
 5621:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 5622:         }
 5623:         if (($tstart) && ($tstart<0)) { next; }
 5624:         my $status = 'active';
 5625:         if (($tend) && ($tend<=$now)) {
 5626:             $status = 'previous';
 5627:         } 
 5628:         if (($tstart) && ($now<$tstart)) {
 5629:             $status = 'future';
 5630:         }
 5631:         if (ref($types) eq 'ARRAY') {
 5632:             if (!grep(/^\Q$status\E$/,@{$types})) {
 5633:                 next;
 5634:             } 
 5635:         } else {
 5636:             if ($status ne 'active') {
 5637:                 next;
 5638:             }
 5639:         }
 5640:         my ($rolecode,$username,$domain,$section,$area);
 5641:         if ($context eq 'userroles') {
 5642:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 5643:             (undef,$domain,$username,$section) = split(/\//,$area);
 5644:         } else {
 5645:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 5646:         }
 5647:         if (ref($roledoms) eq 'ARRAY') {
 5648:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 5649:                 next;
 5650:             }
 5651:         }
 5652:         if (ref($roles) eq 'ARRAY') {
 5653:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 5654:                 if ($role =~ /^cr\//) {
 5655:                     if (!grep(/^cr$/,@{$roles})) {
 5656:                         next;
 5657:                     }
 5658:                 } elsif ($role =~ /^gr\//) {
 5659:                     if (!grep(/^gr$/,@{$roles})) {
 5660:                         next;
 5661:                     }
 5662:                 } else {
 5663:                     next;
 5664:                 }
 5665:             }
 5666:         }
 5667:         if ($hidepriv) {
 5668:             my @privroles = ('dc','su');
 5669:             if ($context eq 'userroles') {
 5670:                 next if (grep(/^\Q$role\E$/,@privroles));
 5671:             } else {
 5672:                 my $possdoms = [$domain];
 5673:                 if (ref($roledoms) eq 'ARRAY') {
 5674:                    push(@{$possdoms},@{$roledoms}); 
 5675:                 }
 5676:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5677:                     if (!$nothide{$username.':'.$domain}) {
 5678:                         next;
 5679:                     }
 5680:                 }
 5681:             }
 5682:         }
 5683:         if ($withsec) {
 5684:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5685:                 $tstart.':'.$tend;
 5686:         } else {
 5687:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5688:         }
 5689:     }
 5690:     return %returnhash;
 5691: }
 5692: 
 5693: sub get_all_adhocroles {
 5694:     my ($dom) = @_;
 5695:     my @roles_by_num = ();
 5696:     my %domdefaults = &get_domain_defaults($dom);
 5697:     my (%description,%access_in_dom,%access_info);
 5698:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5699:         my $count = 0;
 5700:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5701:         my %ordered;
 5702:         foreach my $role (sort(keys(%domcurrent))) {
 5703:             my ($order,$desc,$access_in_dom);
 5704:             if (ref($domcurrent{$role}) eq 'HASH') {
 5705:                 $order = $domcurrent{$role}{'order'};
 5706:                 $desc = $domcurrent{$role}{'desc'};
 5707:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5708:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5709:             }
 5710:             if ($order eq '') {
 5711:                 $order = $count;
 5712:             }
 5713:             $ordered{$order} = $role;
 5714:             if ($desc ne '') {
 5715:                 $description{$role} = $desc;
 5716:             } else {
 5717:                 $description{$role}= $role;
 5718:             }
 5719:             $count++;
 5720:         }
 5721:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5722:             push(@roles_by_num,$ordered{$item});
 5723:         }
 5724:     }
 5725:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5726: }
 5727: 
 5728: sub get_my_adhocroles {
 5729:     my ($cid,$checkreg) = @_;
 5730:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5731:     if ($env{'request.course.id'} eq $cid) {
 5732:         $cdom = $env{'course.'.$cid.'.domain'};
 5733:         $cnum = $env{'course.'.$cid.'.num'};
 5734:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5735:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5736:         $cdom = $1;
 5737:         $cnum = $2;
 5738:         %info = &get('environment',['internal.coursecode'],
 5739:                      $cdom,$cnum);
 5740:     }
 5741:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5742:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5743:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5744:         if ($rosterhash{$user} ne '') {
 5745:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5746:             return ([],{}) if ($type eq 'auto');
 5747:         }
 5748:     }
 5749:     if (($cdom ne '') && ($cnum ne ''))  {
 5750:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5751:             my $then=$env{'user.login.time'};
 5752:             my $update=$env{'user.update.time'};
 5753:             if (!$update) {
 5754:                 $update = $then;
 5755:             }
 5756:             my @liveroles;
 5757:             foreach my $role ('dh','da') {
 5758:                 if ($env{"user.role.$role./$cdom/"}) {
 5759:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5760:                     my $limit = $update;
 5761:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5762:                         $limit = $then;
 5763:                     }
 5764:                     my $activerole = 1;
 5765:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5766:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5767:                     if ($activerole) {
 5768:                         push(@liveroles,$role);
 5769:                     }
 5770:                 }
 5771:             }
 5772:             if (@liveroles) {
 5773:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5774:                     my ($accessref,$accessinfo,%access_in_dom);
 5775:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5776:                     if (ref($roles_by_num) eq 'ARRAY') {
 5777:                         if (@{$roles_by_num}) {
 5778:                             my %settings;
 5779:                             if ($env{'request.course.id'} eq $cid) {
 5780:                                 foreach my $envkey (keys(%env)) {
 5781:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5782:                                         $settings{$1} = $env{$envkey};
 5783:                                     }
 5784:                                 }
 5785:                             } else {
 5786:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5787:                             }
 5788:                             my %setincrs;
 5789:                             if ($settings{'internal.adhocaccess'}) {
 5790:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5791:                             }
 5792:                             my @statuses;
 5793:                             if ($env{'environment.inststatus'}) {
 5794:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5795:                             }
 5796:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5797:                             if (ref($accessref) eq 'HASH') {
 5798:                                 %access_in_dom = %{$accessref};
 5799:                             }
 5800:                             foreach my $role (@{$roles_by_num}) {
 5801:                                 my ($curraccess,@okstatus,@personnel);
 5802:                                 if ($setincrs{$role}) {
 5803:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5804:                                     if ($curraccess eq 'status') {
 5805:                                         @okstatus = split(/\&/,$rest);
 5806:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5807:                                         @personnel = split(/\&/,$rest);
 5808:                                     }
 5809:                                 } else {
 5810:                                     $curraccess = $access_in_dom{$role};
 5811:                                     if (ref($accessinfo) eq 'HASH') {
 5812:                                         if ($curraccess eq 'status') {
 5813:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5814:                                                 @okstatus = @{$accessinfo->{$role}};
 5815:                                             }
 5816:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5817:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5818:                                                 @personnel = @{$accessinfo->{$role}};
 5819:                                             }
 5820:                                         }
 5821:                                     }
 5822:                                 }
 5823:                                 if ($curraccess eq 'none') {
 5824:                                     next;
 5825:                                 } elsif ($curraccess eq 'all') {
 5826:                                     push(@possroles,$role);
 5827:                                 } elsif ($curraccess eq 'dh') {
 5828:                                     if (grep(/^dh$/,@liveroles)) {
 5829:                                         push(@possroles,$role);
 5830:                                     } else {
 5831:                                         next;
 5832:                                     }
 5833:                                 } elsif ($curraccess eq 'da') {
 5834:                                     if (grep(/^da$/,@liveroles)) {
 5835:                                         push(@possroles,$role);
 5836:                                     } else {
 5837:                                         next;
 5838:                                     }
 5839:                                 } elsif ($curraccess eq 'status') {
 5840:                                     if (@okstatus) {
 5841:                                         if (!@statuses) {
 5842:                                             if (grep(/^default$/,@okstatus)) {
 5843:                                                 push(@possroles,$role);
 5844:                                             }
 5845:                                         } else {
 5846:                                             foreach my $status (@okstatus) {
 5847:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5848:                                                     push(@possroles,$role);
 5849:                                                     last;
 5850:                                                 }
 5851:                                             }
 5852:                                         }
 5853:                                     }
 5854:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5855:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5856:                                         if ($curraccess eq 'exc') {
 5857:                                             push(@possroles,$role);
 5858:                                         }
 5859:                                     } elsif ($curraccess eq 'inc') {
 5860:                                         push(@possroles,$role);
 5861:                                     }
 5862:                                 }
 5863:                             }
 5864:                         }
 5865:                     }
 5866:                 }
 5867:             }
 5868:         }
 5869:     }
 5870:     unless (ref($description) eq 'HASH') {
 5871:         if (ref($roles_by_num) eq 'ARRAY') {
 5872:             my %desc;
 5873:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5874:             $description = \%desc;
 5875:         } else {
 5876:             $description = {};
 5877:         }
 5878:     }
 5879:     return (\@possroles,$description);
 5880: }
 5881: 
 5882: # ----------------------------------------------------- Frontpage Announcements
 5883: #
 5884: #
 5885: 
 5886: sub postannounce {
 5887:     my ($server,$text)=@_;
 5888:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5889:     unless ($text=~/\w/) { $text=''; }
 5890:     return &reply('setannounce:'.&escape($text),$server);
 5891: }
 5892: 
 5893: sub getannounce {
 5894: 
 5895:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5896: 	my $announcement='';
 5897: 	while (my $line = <$fh>) { $announcement .= $line; }
 5898: 	close($fh);
 5899: 	if ($announcement=~/\w/) { 
 5900: 	    return 
 5901:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5902:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5903: 	} else {
 5904: 	    return '';
 5905: 	}
 5906:     } else {
 5907: 	return '';
 5908:     }
 5909: }
 5910: 
 5911: # ---------------------------------------------------------- Course ID routines
 5912: # Deal with domain's nohist_courseid.db files
 5913: #
 5914: 
 5915: sub courseidput {
 5916:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5917:     return unless (ref($storehash) eq 'HASH');
 5918:     my $outcome;
 5919:     if ($caller eq 'timeonly') {
 5920:         my $cids = '';
 5921:         foreach my $item (keys(%$storehash)) {
 5922:             $cids.=&escape($item).'&';
 5923:         }
 5924:         $cids=~s/\&$//;
 5925:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5926:                           $coursehome);       
 5927:     } else {
 5928:         my $items = '';
 5929:         foreach my $item (keys(%$storehash)) {
 5930:             $items.= &escape($item).'='.
 5931:                      &freeze_escape($$storehash{$item}).'&';
 5932:         }
 5933:         $items=~s/\&$//;
 5934:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5935:                           $coursehome);
 5936:     }
 5937:     if ($outcome eq 'unknown_cmd') {
 5938:         my $what;
 5939:         foreach my $cid (keys(%$storehash)) {
 5940:             $what .= &escape($cid).'=';
 5941:             foreach my $item ('description','inst_code','owner','type') {
 5942:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5943:             }
 5944:             $what =~ s/\:$/&/;
 5945:         }
 5946:         $what =~ s/\&$//;  
 5947:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5948:     } else {
 5949:         return $outcome;
 5950:     }
 5951: }
 5952: 
 5953: sub courseiddump {
 5954:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5955:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5956:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5957:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5958:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5959:     my $as_hash = 1;
 5960:     my %returnhash;
 5961:     if (!$domfilter) { $domfilter=''; }
 5962:     my %libserv = &all_library();
 5963:     foreach my $tryserver (keys(%libserv)) {
 5964:         if ( (  $hostidflag == 1 
 5965: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5966: 	     || (!defined($hostidflag)) ) {
 5967: 
 5968: 	    if (($domfilter eq '') ||
 5969: 		(&host_domain($tryserver) eq $domfilter)) {
 5970:                 my $rep;
 5971:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 5972:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5973:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5974:                                 &escape($descfilter), &escape($instcodefilter), 
 5975:                                 &escape($ownerfilter), &escape($coursefilter),
 5976:                                 &escape($typefilter), &escape($regexp_ok), 
 5977:                                 $as_hash, &escape($selfenrollonly), 
 5978:                                 &escape($catfilter), $showhidden, $caller, 
 5979:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5980:                                 &escape($createdbefore), &escape($createdafter), 
 5981:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5982:                                 $reqcrsdom,&escape($reqinstcode))));
 5983:                 } else {
 5984:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5985:                              $sincefilter.':'.&escape($descfilter).':'.
 5986:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5987:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5988:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5989:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5990:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5991:                              &escape($cc_clone).':'.$cloneonly.':'.
 5992:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5993:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5994:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5995:                 }
 5996:                      
 5997:                 my @pairs=split(/\&/,$rep);
 5998:                 foreach my $item (@pairs) {
 5999:                     my ($key,$value)=split(/\=/,$item,2);
 6000:                     $key = &unescape($key);
 6001:                     next if ($key =~ /^error: 2 /);
 6002:                     my $result = &thaw_unescape($value);
 6003:                     if (ref($result) eq 'HASH') {
 6004:                         $returnhash{$key}=$result;
 6005:                     } else {
 6006:                         my @responses = split(/:/,$value);
 6007:                         my @items = ('description','inst_code','owner','type');
 6008:                         for (my $i=0; $i<@responses; $i++) {
 6009:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 6010:                         }
 6011:                     }
 6012:                 }
 6013:             }
 6014:         }
 6015:     }
 6016:     return %returnhash;
 6017: }
 6018: 
 6019: sub courselastaccess {
 6020:     my ($cdom,$cnum,$hostidref) = @_;
 6021:     my %returnhash;
 6022:     if ($cdom && $cnum) {
 6023:         my $chome = &homeserver($cnum,$cdom);
 6024:         if ($chome ne 'no_host') {
 6025:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 6026:             &extract_lastaccess(\%returnhash,$rep);
 6027:         }
 6028:     } else {
 6029:         if (!$cdom) { $cdom=''; }
 6030:         my %libserv = &all_library();
 6031:         foreach my $tryserver (keys(%libserv)) {
 6032:             if (ref($hostidref) eq 'ARRAY') {
 6033:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 6034:             } 
 6035:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 6036:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 6037:                 &extract_lastaccess(\%returnhash,$rep);
 6038:             }
 6039:         }
 6040:     }
 6041:     return %returnhash;
 6042: }
 6043: 
 6044: sub extract_lastaccess {
 6045:     my ($returnhash,$rep) = @_;
 6046:     if (ref($returnhash) eq 'HASH') {
 6047:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 6048:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 6049:                  $rep eq '') {
 6050:             my @pairs=split(/\&/,$rep);
 6051:             foreach my $item (@pairs) {
 6052:                 my ($key,$value)=split(/\=/,$item,2);
 6053:                 $key = &unescape($key);
 6054:                 next if ($key =~ /^error: 2 /);
 6055:                 $returnhash->{$key} = &thaw_unescape($value);
 6056:             }
 6057:         }
 6058:     }
 6059:     return;
 6060: }
 6061: 
 6062: # ---------------------------------------------------------- DC e-mail
 6063: 
 6064: sub dcmailput {
 6065:     my ($domain,$msgid,$message,$server)=@_;
 6066:     my $status = &critical(
 6067:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 6068:        &escape($message),$server);
 6069:     return $status;
 6070: }
 6071: 
 6072: sub dcmaildump {
 6073:     my ($dom,$startdate,$enddate,$senders) = @_;
 6074:     my %returnhash=();
 6075: 
 6076:     if (defined(&domain($dom,'primary'))) {
 6077:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 6078:                                                          &escape($enddate).':';
 6079: 	my @esc_senders=map { &escape($_)} @$senders;
 6080: 	$cmd.=&escape(join('&',@esc_senders));
 6081: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 6082:             my ($key,$value) = split(/\=/,$line,2);
 6083:             if (($key) && ($value)) {
 6084:                 $returnhash{&unescape($key)} = &unescape($value);
 6085:             }
 6086:         }
 6087:     }
 6088:     return %returnhash;
 6089: }
 6090: # ---------------------------------------------------------- Domain roles
 6091: 
 6092: sub get_domain_roles {
 6093:     my ($dom,$roles,$startdate,$enddate)=@_;
 6094:     if ((!defined($startdate)) || ($startdate eq '')) {
 6095:         $startdate = '.';
 6096:     }
 6097:     if ((!defined($enddate)) || ($enddate eq '')) {
 6098:         $enddate = '.';
 6099:     }
 6100:     my $rolelist;
 6101:     if (ref($roles) eq 'ARRAY') {
 6102:         $rolelist = join('&',@{$roles});
 6103:     }
 6104:     my %personnel = ();
 6105: 
 6106:     my %servers = &get_servers($dom,'library');
 6107:     foreach my $tryserver (keys(%servers)) {
 6108: 	%{$personnel{$tryserver}}=();
 6109: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 6110: 					    &escape($startdate).':'.
 6111: 					    &escape($enddate).':'.
 6112: 					    &escape($rolelist), $tryserver))) {
 6113: 	    my ($key,$value) = split(/\=/,$line,2);
 6114: 	    if (($key) && ($value)) {
 6115: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 6116: 	    }
 6117: 	}
 6118:     }
 6119:     return %personnel;
 6120: }
 6121: 
 6122: sub get_active_domroles {
 6123:     my ($dom,$roles) = @_;
 6124:     return () unless (ref($roles) eq 'ARRAY');
 6125:     my $now = time;
 6126:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 6127:     my %domroles;
 6128:     foreach my $server (keys(%dompersonnel)) {
 6129:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 6130:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 6131:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 6132:         }
 6133:     }
 6134:     return %domroles;
 6135: }
 6136: 
 6137: # ----------------------------------------------------------- Interval timing 
 6138: 
 6139: {
 6140: # Caches needed for speedup of navmaps
 6141: # We don't want to cache this for very long at all (5 seconds at most)
 6142: # 
 6143: # The user for whom we cache
 6144: my $cachedkey='';
 6145: # The cached times for this user
 6146: my %cachedtimes=();
 6147: # When this was last done
 6148: my $cachedtime='';
 6149: 
 6150: sub load_all_first_access {
 6151:     my ($uname,$udom,$ignorecache)=@_;
 6152:     if (($cachedkey eq $uname.':'.$udom) &&
 6153:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 6154:         (!$ignorecache)) {
 6155:         return;
 6156:     }
 6157:     $cachedtime=time;
 6158:     $cachedkey=$uname.':'.$udom;
 6159:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 6160: }
 6161: 
 6162: sub get_first_access {
 6163:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 6164:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6165:     if ($argsymb) { $symb=$argsymb; }
 6166:     my ($map,$id,$res)=&decode_symb($symb);
 6167:     if ($argmap) { $map = $argmap; }
 6168:     if ($type eq 'course') {
 6169: 	$res='course';
 6170:     } elsif ($type eq 'map') {
 6171: 	$res=&symbread($map);
 6172:     } else {
 6173: 	$res=$symb;
 6174:     }
 6175:     &load_all_first_access($uname,$udom,$ignorecache);
 6176:     return $cachedtimes{"$courseid\0$res"};
 6177: }
 6178: 
 6179: sub set_first_access {
 6180:     my ($type,$interval)=@_;
 6181:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 6182:     my ($map,$id,$res)=&decode_symb($symb);
 6183:     if ($type eq 'course') {
 6184: 	$res='course';
 6185:     } elsif ($type eq 'map') {
 6186: 	$res=&symbread($map);
 6187:     } else {
 6188: 	$res=$symb;
 6189:     }
 6190:     $cachedkey='';
 6191:     my $firstaccess=&get_first_access($type,$symb,$map);
 6192:     if ($firstaccess) {
 6193:         &logthis("First access time already set ($firstaccess) when attempting ".
 6194:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 6195:                  "in $courseid");
 6196:         return 'already_set';
 6197:     } else {
 6198:         my $start = time;
 6199: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 6200:                           $udom,$uname);
 6201:         if ($putres eq 'ok') {
 6202:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 6203:                  $udom,$uname); 
 6204:             &appenv(
 6205:                      {
 6206:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 6207:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 6208:                      }
 6209:                   );
 6210:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 6211:                 $cachedtimes{"$courseid\0$res"} = $start;
 6212:             }
 6213:         } elsif ($putres ne 'refused') {
 6214:             &logthis("Result: $putres when attempting to set first access time ".
 6215:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 6216:         }
 6217:         return $putres;
 6218:     }
 6219:     return 'already_set';
 6220: }
 6221: }
 6222: 
 6223: # --------------------------------------------- Set Expire Date for Spreadsheet
 6224: 
 6225: sub expirespread {
 6226:     my ($uname,$udom,$stype,$usymb)=@_;
 6227:     my $cid=$env{'request.course.id'}; 
 6228:     if ($cid) {
 6229:        my $now=time;
 6230:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 6231:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 6232:                             $env{'course.'.$cid.'.num'}.
 6233: 	        	    ':nohist_expirationdates:'.
 6234:                             &escape($key).'='.$now,
 6235:                             $env{'course.'.$cid.'.home'})
 6236:     }
 6237:     return 'ok';
 6238: }
 6239: 
 6240: # ----------------------------------------------------- Devalidate Spreadsheets
 6241: 
 6242: sub devalidate {
 6243:     my ($symb,$uname,$udom)=@_;
 6244:     my $cid=$env{'request.course.id'}; 
 6245:     if ($cid) {
 6246:         # delete the stored spreadsheets for
 6247:         # - the student level sheet of this user in course's homespace
 6248:         # - the assessment level sheet for this resource 
 6249:         #   for this user in user's homespace
 6250: 	# - current conditional state info
 6251: 	my $key=$uname.':'.$udom.':';
 6252:         my $status=
 6253: 	    &del('nohist_calculatedsheets',
 6254: 		 [$key.'studentcalc:'],
 6255: 		 $env{'course.'.$cid.'.domain'},
 6256: 		 $env{'course.'.$cid.'.num'})
 6257: 		.' '.
 6258: 	    &del('nohist_calculatedsheets_'.$cid,
 6259: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 6260:         unless ($status eq 'ok ok') {
 6261:            &logthis('Could not devalidate spreadsheet '.
 6262:                     $uname.' at '.$udom.' for '.
 6263: 		    $symb.': '.$status);
 6264:         }
 6265: 	&delenv('user.state.'.$cid);
 6266:     }
 6267: }
 6268: 
 6269: sub get_scalar {
 6270:     my ($string,$end) = @_;
 6271:     my $value;
 6272:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 6273: 	$value = $1;
 6274:     } elsif ($$string =~ s/^([^&]*?)&//) {
 6275: 	$value = $1;
 6276:     }
 6277:     return &unescape($value);
 6278: }
 6279: 
 6280: sub array2str {
 6281:   my (@array) = @_;
 6282:   my $result=&arrayref2str(\@array);
 6283:   $result=~s/^__ARRAY_REF__//;
 6284:   $result=~s/__END_ARRAY_REF__$//;
 6285:   return $result;
 6286: }
 6287: 
 6288: sub arrayref2str {
 6289:   my ($arrayref) = @_;
 6290:   my $result='__ARRAY_REF__';
 6291:   foreach my $elem (@$arrayref) {
 6292:     if(ref($elem) eq 'ARRAY') {
 6293:       $result.=&arrayref2str($elem).'&';
 6294:     } elsif(ref($elem) eq 'HASH') {
 6295:       $result.=&hashref2str($elem).'&';
 6296:     } elsif(ref($elem)) {
 6297:       #print("Got a ref of ".(ref($elem))." skipping.");
 6298:     } else {
 6299:       $result.=&escape($elem).'&';
 6300:     }
 6301:   }
 6302:   $result=~s/\&$//;
 6303:   $result .= '__END_ARRAY_REF__';
 6304:   return $result;
 6305: }
 6306: 
 6307: sub hash2str {
 6308:   my (%hash) = @_;
 6309:   my $result=&hashref2str(\%hash);
 6310:   $result=~s/^__HASH_REF__//;
 6311:   $result=~s/__END_HASH_REF__$//;
 6312:   return $result;
 6313: }
 6314: 
 6315: sub hashref2str {
 6316:   my ($hashref)=@_;
 6317:   my $result='__HASH_REF__';
 6318:   foreach my $key (sort(keys(%$hashref))) {
 6319:     if (ref($key) eq 'ARRAY') {
 6320:       $result.=&arrayref2str($key).'=';
 6321:     } elsif (ref($key) eq 'HASH') {
 6322:       $result.=&hashref2str($key).'=';
 6323:     } elsif (ref($key)) {
 6324:       $result.='=';
 6325:       #print("Got a ref of ".(ref($key))." skipping.");
 6326:     } else {
 6327: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 6328:     }
 6329: 
 6330:     if(ref($hashref->{$key}) eq 'ARRAY') {
 6331:       $result.=&arrayref2str($hashref->{$key}).'&';
 6332:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 6333:       $result.=&hashref2str($hashref->{$key}).'&';
 6334:     } elsif(ref($hashref->{$key})) {
 6335:        $result.='&';
 6336:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 6337:     } else {
 6338:       $result.=&escape($hashref->{$key}).'&';
 6339:     }
 6340:   }
 6341:   $result=~s/\&$//;
 6342:   $result .= '__END_HASH_REF__';
 6343:   return $result;
 6344: }
 6345: 
 6346: sub str2hash {
 6347:     my ($string)=@_;
 6348:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 6349:     return %$hash;
 6350: }
 6351: 
 6352: sub str2hashref {
 6353:   my ($string) = @_;
 6354: 
 6355:   my %hash;
 6356: 
 6357:   if($string !~ /^__HASH_REF__/) {
 6358:       if (! ($string eq '' || !defined($string))) {
 6359: 	  $hash{'error'}='Not hash reference';
 6360:       }
 6361:       return (\%hash, $string);
 6362:   }
 6363: 
 6364:   $string =~ s/^__HASH_REF__//;
 6365: 
 6366:   while($string !~ /^__END_HASH_REF__/) {
 6367:       #key
 6368:       my $key='';
 6369:       if($string =~ /^__HASH_REF__/) {
 6370:           ($key, $string)=&str2hashref($string);
 6371:           if(defined($key->{'error'})) {
 6372:               $hash{'error'}='Bad data';
 6373:               return (\%hash, $string);
 6374:           }
 6375:       } elsif($string =~ /^__ARRAY_REF__/) {
 6376:           ($key, $string)=&str2arrayref($string);
 6377:           if($key->[0] eq 'Array reference error') {
 6378:               $hash{'error'}='Bad data';
 6379:               return (\%hash, $string);
 6380:           }
 6381:       } else {
 6382:           $string =~ s/^(.*?)=//;
 6383: 	  $key=&unescape($1);
 6384:       }
 6385:       $string =~ s/^=//;
 6386: 
 6387:       #value
 6388:       my $value='';
 6389:       if($string =~ /^__HASH_REF__/) {
 6390:           ($value, $string)=&str2hashref($string);
 6391:           if(defined($value->{'error'})) {
 6392:               $hash{'error'}='Bad data';
 6393:               return (\%hash, $string);
 6394:           }
 6395:       } elsif($string =~ /^__ARRAY_REF__/) {
 6396:           ($value, $string)=&str2arrayref($string);
 6397:           if($value->[0] eq 'Array reference error') {
 6398:               $hash{'error'}='Bad data';
 6399:               return (\%hash, $string);
 6400:           }
 6401:       } else {
 6402: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 6403:       }
 6404:       $string =~ s/^&//;
 6405: 
 6406:       $hash{$key}=$value;
 6407:   }
 6408: 
 6409:   $string =~ s/^__END_HASH_REF__//;
 6410: 
 6411:   return (\%hash, $string);
 6412: }
 6413: 
 6414: sub str2array {
 6415:     my ($string)=@_;
 6416:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 6417:     return @$array;
 6418: }
 6419: 
 6420: sub str2arrayref {
 6421:   my ($string) = @_;
 6422:   my @array;
 6423: 
 6424:   if($string !~ /^__ARRAY_REF__/) {
 6425:       if (! ($string eq '' || !defined($string))) {
 6426: 	  $array[0]='Array reference error';
 6427:       }
 6428:       return (\@array, $string);
 6429:   }
 6430: 
 6431:   $string =~ s/^__ARRAY_REF__//;
 6432: 
 6433:   while($string !~ /^__END_ARRAY_REF__/) {
 6434:       my $value='';
 6435:       if($string =~ /^__HASH_REF__/) {
 6436:           ($value, $string)=&str2hashref($string);
 6437:           if(defined($value->{'error'})) {
 6438:               $array[0] ='Array reference error';
 6439:               return (\@array, $string);
 6440:           }
 6441:       } elsif($string =~ /^__ARRAY_REF__/) {
 6442:           ($value, $string)=&str2arrayref($string);
 6443:           if($value->[0] eq 'Array reference error') {
 6444:               $array[0] ='Array reference error';
 6445:               return (\@array, $string);
 6446:           }
 6447:       } else {
 6448: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 6449:       }
 6450:       $string =~ s/^&//;
 6451: 
 6452:       push(@array, $value);
 6453:   }
 6454: 
 6455:   $string =~ s/^__END_ARRAY_REF__//;
 6456: 
 6457:   return (\@array, $string);
 6458: }
 6459: 
 6460: # -------------------------------------------------------------------Temp Store
 6461: 
 6462: sub tmpreset {
 6463:   my ($symb,$namespace,$domain,$stuname) = @_;
 6464:   if (!$symb) {
 6465:     $symb=&symbread();
 6466:     if (!$symb) { $symb= $env{'request.url'}; }
 6467:   }
 6468:   $symb=escape($symb);
 6469: 
 6470:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6471:   $namespace=~s/\//\_/g;
 6472:   $namespace=~s/\W//g;
 6473: 
 6474:   if (!$domain) { $domain=$env{'user.domain'}; }
 6475:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6476:   if ($domain eq 'public' && $stuname eq 'public') {
 6477:       $stuname=&get_requestor_ip();
 6478:   }
 6479:   my $path=LONCAPA::tempdir();
 6480:   my %hash;
 6481:   if (tie(%hash,'GDBM_File',
 6482: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6483: 	  &GDBM_WRCREAT(),0640)) {
 6484:     foreach my $key (keys(%hash)) {
 6485:       if ($key=~ /:$symb/) {
 6486: 	delete($hash{$key});
 6487:       }
 6488:     }
 6489:   }
 6490: }
 6491: 
 6492: sub tmpstore {
 6493:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 6494: 
 6495:   if (!$symb) {
 6496:     $symb=&symbread();
 6497:     if (!$symb) { $symb= $env{'request.url'}; }
 6498:   }
 6499:   $symb=escape($symb);
 6500: 
 6501:   if (!$namespace) {
 6502:     # I don't think we would ever want to store this for a course.
 6503:     # it seems this will only be used if we don't have a course.
 6504:     #$namespace=$env{'request.course.id'};
 6505:     #if (!$namespace) {
 6506:       $namespace=$env{'request.state'};
 6507:     #}
 6508:   }
 6509:   $namespace=~s/\//\_/g;
 6510:   $namespace=~s/\W//g;
 6511:   if (!$domain) { $domain=$env{'user.domain'}; }
 6512:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6513:   if ($domain eq 'public' && $stuname eq 'public') {
 6514:       $stuname=&get_requestor_ip();
 6515:   }
 6516:   my $now=time;
 6517:   my %hash;
 6518:   my $path=LONCAPA::tempdir();
 6519:   if (tie(%hash,'GDBM_File',
 6520: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6521: 	  &GDBM_WRCREAT(),0640)) {
 6522:     $hash{"version:$symb"}++;
 6523:     my $version=$hash{"version:$symb"};
 6524:     my $allkeys=''; 
 6525:     foreach my $key (keys(%$storehash)) {
 6526:       $allkeys.=$key.':';
 6527:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 6528:     }
 6529:     $hash{"$version:$symb:timestamp"}=$now;
 6530:     $allkeys.='timestamp';
 6531:     $hash{"$version:keys:$symb"}=$allkeys;
 6532:     if (untie(%hash)) {
 6533:       return 'ok';
 6534:     } else {
 6535:       return "error:$!";
 6536:     }
 6537:   } else {
 6538:     return "error:$!";
 6539:   }
 6540: }
 6541: 
 6542: # -----------------------------------------------------------------Temp Restore
 6543: 
 6544: sub tmprestore {
 6545:   my ($symb,$namespace,$domain,$stuname) = @_;
 6546: 
 6547:   if (!$symb) {
 6548:     $symb=&symbread();
 6549:     if (!$symb) { $symb= $env{'request.url'}; }
 6550:   }
 6551:   $symb=escape($symb);
 6552: 
 6553:   if (!$namespace) { $namespace=$env{'request.state'}; }
 6554: 
 6555:   if (!$domain) { $domain=$env{'user.domain'}; }
 6556:   if (!$stuname) { $stuname=$env{'user.name'}; }
 6557:   if ($domain eq 'public' && $stuname eq 'public') {
 6558:       $stuname=&get_requestor_ip();
 6559:   }
 6560:   my %returnhash;
 6561:   $namespace=~s/\//\_/g;
 6562:   $namespace=~s/\W//g;
 6563:   my %hash;
 6564:   my $path=LONCAPA::tempdir();
 6565:   if (tie(%hash,'GDBM_File',
 6566: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 6567: 	  &GDBM_READER(),0640)) {
 6568:     my $version=$hash{"version:$symb"};
 6569:     $returnhash{'version'}=$version;
 6570:     my $scope;
 6571:     for ($scope=1;$scope<=$version;$scope++) {
 6572:       my $vkeys=$hash{"$scope:keys:$symb"};
 6573:       my @keys=split(/:/,$vkeys);
 6574:       my $key;
 6575:       $returnhash{"$scope:keys"}=$vkeys;
 6576:       foreach $key (@keys) {
 6577: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6578: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 6579:       }
 6580:     }
 6581:     if (!(untie(%hash))) {
 6582:       return "error:$!";
 6583:     }
 6584:   } else {
 6585:     return "error:$!";
 6586:   }
 6587:   return %returnhash;
 6588: }
 6589: 
 6590: # ----------------------------------------------------------------------- Store
 6591: 
 6592: sub store {
 6593:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6594:     my $home='';
 6595: 
 6596:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6597: 
 6598:     $symb=&symbclean($symb);
 6599:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6600: 
 6601:     if (!$domain) { $domain=$env{'user.domain'}; }
 6602:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6603: 
 6604:     &devalidate($symb,$stuname,$domain);
 6605: 
 6606:     $symb=escape($symb);
 6607:     if (!$namespace) { 
 6608:        unless ($namespace=$env{'request.course.id'}) { 
 6609:           return ''; 
 6610:        } 
 6611:     }
 6612:     if (!$home) { $home=$env{'user.home'}; }
 6613: 
 6614:     $$storehash{'ip'}=&get_requestor_ip();
 6615:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6616: 
 6617:     my $namevalue='';
 6618:     foreach my $key (keys(%$storehash)) {
 6619:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6620:     }
 6621:     $namevalue=~s/\&$//;
 6622:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6623:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6624: }
 6625: 
 6626: # -------------------------------------------------------------- Critical Store
 6627: 
 6628: sub cstore {
 6629:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6630:     my $home='';
 6631: 
 6632:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6633: 
 6634:     $symb=&symbclean($symb);
 6635:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6636: 
 6637:     if (!$domain) { $domain=$env{'user.domain'}; }
 6638:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6639: 
 6640:     &devalidate($symb,$stuname,$domain);
 6641: 
 6642:     $symb=escape($symb);
 6643:     if (!$namespace) { 
 6644:        unless ($namespace=$env{'request.course.id'}) { 
 6645:           return ''; 
 6646:        } 
 6647:     }
 6648:     if (!$home) { $home=$env{'user.home'}; }
 6649: 
 6650:     $$storehash{'ip'}=&get_requestor_ip();
 6651:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6652: 
 6653:     my $namevalue='';
 6654:     foreach my $key (keys(%$storehash)) {
 6655:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6656:     }
 6657:     $namevalue=~s/\&$//;
 6658:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6659:     return critical
 6660:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6661: }
 6662: 
 6663: # --------------------------------------------------------------------- Restore
 6664: 
 6665: sub restore {
 6666:     my ($symb,$namespace,$domain,$stuname) = @_;
 6667:     my $home='';
 6668: 
 6669:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6670: 
 6671:     if (!$symb) {
 6672:         return if ($namespace eq 'courserequests');
 6673:         unless ($symb=escape(&symbread())) { return ''; }
 6674:     } else {
 6675:         unless ($namespace eq 'courserequests') {
 6676:             $symb=&escape(&symbclean($symb));
 6677:         }
 6678:     }
 6679:     if (!$namespace) { 
 6680:        unless ($namespace=$env{'request.course.id'}) { 
 6681:           return ''; 
 6682:        } 
 6683:     }
 6684:     if (!$domain) { $domain=$env{'user.domain'}; }
 6685:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6686:     if (!$home) { $home=$env{'user.home'}; }
 6687:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6688: 
 6689:     my %returnhash=();
 6690:     foreach my $line (split(/\&/,$answer)) {
 6691: 	my ($name,$value)=split(/\=/,$line);
 6692:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6693:     }
 6694:     my $version;
 6695:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6696:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6697:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6698:        }
 6699:     }
 6700:     return %returnhash;
 6701: }
 6702: 
 6703: # ---------------------------------------------------------- Course Description
 6704: #
 6705: #  
 6706: 
 6707: sub coursedescription {
 6708:     my ($courseid,$args)=@_;
 6709:     $courseid=~s/^\///;
 6710:     $courseid=~s/\_/\//g;
 6711:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6712:     my $chome=&homeserver($cnum,$cdomain);
 6713:     my $normalid=$cdomain.'_'.$cnum;
 6714:     # need to always cache even if we get errors otherwise we keep 
 6715:     # trying and trying and trying to get the course description.
 6716:     my %envhash=();
 6717:     my %returnhash=();
 6718:     
 6719:     my $expiretime=600;
 6720:     if ($env{'request.course.id'} eq $normalid) {
 6721: 	$expiretime=120;
 6722:     }
 6723: 
 6724:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6725:     if (!$args->{'freshen_cache'}
 6726: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6727: 	foreach my $key (keys(%env)) {
 6728: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6729: 	    my ($setting) = $1;
 6730: 	    $returnhash{$setting} = $env{$key};
 6731: 	}
 6732: 	return %returnhash;
 6733:     }
 6734: 
 6735:     # get the data again
 6736: 
 6737:     if (!$args->{'one_time'}) {
 6738: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6739:     }
 6740: 
 6741:     if ($chome ne 'no_host') {
 6742:        %returnhash=&dump('environment',$cdomain,$cnum);
 6743:        if (!exists($returnhash{'con_lost'})) {
 6744: 	   my $username = $env{'user.name'}; # Defult username
 6745: 	   if(defined $args->{'user'}) {
 6746: 	       $username = $args->{'user'};
 6747: 	   }
 6748:            $returnhash{'home'}= $chome;
 6749: 	   $returnhash{'domain'} = $cdomain;
 6750: 	   $returnhash{'num'} = $cnum;
 6751:            if (!defined($returnhash{'type'})) {
 6752:                $returnhash{'type'} = 'Course';
 6753:            }
 6754:            while (my ($name,$value) = each %returnhash) {
 6755:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6756:            }
 6757:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6758:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6759: 	       $username.'_'.$cdomain.'_'.$cnum;
 6760:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6761:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6762:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6763:        }
 6764:     }
 6765:     if (!$args->{'one_time'}) {
 6766: 	&appenv(\%envhash);
 6767:     }
 6768:     return %returnhash;
 6769: }
 6770: 
 6771: sub update_released_required {
 6772:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6773:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6774:         $cid = $env{'request.course.id'};
 6775:         $cdom = $env{'course.'.$cid.'.domain'};
 6776:         $cnum = $env{'course.'.$cid.'.num'};
 6777:         $chome = $env{'course.'.$cid.'.home'};
 6778:     }
 6779:     if ($needsrelease) {
 6780:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6781:         my $needsupdate;
 6782:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6783:             $needsupdate = 1;
 6784:         } else {
 6785:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6786:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6787:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6788:                 $needsupdate = 1;
 6789:             }
 6790:         }
 6791:         if ($needsupdate) {
 6792:             my %needshash = (
 6793:                              'internal.releaserequired' => $needsrelease,
 6794:                             );
 6795:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6796:             if ($putresult eq 'ok') {
 6797:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6798:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6799:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6800:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6801:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6802:                 }
 6803:             }
 6804:         }
 6805:     }
 6806:     return;
 6807: }
 6808: 
 6809: # -------------------------------------------------See if a user is privileged
 6810: 
 6811: sub privileged {
 6812:     my ($username,$domain,$possdomains,$possroles)=@_;
 6813:     my $now = time;
 6814:     my $roles;
 6815:     if (ref($possroles) eq 'ARRAY') {
 6816:         $roles = $possroles; 
 6817:     } else {
 6818:         $roles = ['dc','su'];
 6819:     }
 6820:     if (ref($possdomains) eq 'ARRAY') {
 6821:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6822:         foreach my $dom (@{$possdomains}) {
 6823:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6824:                 (ref($privileged{$dom}) eq 'HASH')) {
 6825:                 foreach my $role (@{$roles}) {
 6826:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6827:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6828:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6829:                             return 1 unless (($end && $end < $now) ||
 6830:                                              ($start && $start > $now));
 6831:                         }
 6832:                     }
 6833:                 }
 6834:             }
 6835:         }
 6836:     } else {
 6837:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6838:         my $now = time;
 6839: 
 6840:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6841:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6842:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6843:                 return 1 unless ($tend && $tend < $now) 
 6844:                         or ($tstart && $tstart > $now);
 6845:             }
 6846:         }
 6847:     }
 6848:     return 0;
 6849: }
 6850: 
 6851: sub privileged_by_domain {
 6852:     my ($domains,$roles) = @_;
 6853:     my %privileged = ();
 6854:     my $cachetime = 60*60*24;
 6855:     my $now = time;
 6856:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6857:         return %privileged;
 6858:     }
 6859:     foreach my $dom (@{$domains}) {
 6860:         next if (ref($privileged{$dom}) eq 'HASH');
 6861:         my $needroles;
 6862:         foreach my $role (@{$roles}) {
 6863:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6864:             if (defined($cached)) {
 6865:                 if (ref($result) eq 'HASH') {
 6866:                     $privileged{$dom}{$role} = $result;
 6867:                 }
 6868:             } else {
 6869:                 $needroles = 1;
 6870:             }
 6871:         }
 6872:         if ($needroles) {
 6873:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6874:             $privileged{$dom} = {};
 6875:             foreach my $server (keys(%dompersonnel)) {
 6876:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6877:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6878:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6879:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6880:                         next if ($end && $end < $now);
 6881:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 6882:                             $dompersonnel{$server}{$item};
 6883:                     }
 6884:                 }
 6885:             }
 6886:             if (ref($privileged{$dom}) eq 'HASH') {
 6887:                 foreach my $role (@{$roles}) {
 6888:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6889:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6890:                     } else {
 6891:                         my %hash = ();
 6892:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6893:                     }
 6894:                 }
 6895:             }
 6896:         }
 6897:     }
 6898:     return %privileged;
 6899: }
 6900: 
 6901: # -------------------------------------------------------- Get user privileges
 6902: 
 6903: sub rolesinit {
 6904:     my ($domain, $username) = @_;
 6905:     my %userroles = ('user.login.time' => time);
 6906:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6907: 
 6908:     # firstaccess and timerinterval are related to timed maps/resources. 
 6909:     # also, blocking can be triggered by an activating timer
 6910:     # it's saved in the user's %env.
 6911:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6912:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6913:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6914:         %timerintchk, %timerintenv);
 6915: 
 6916:     foreach my $key (keys(%firstaccess)) {
 6917:         my ($cid, $rest) = split(/\0/, $key);
 6918:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6919:     }
 6920: 
 6921:     foreach my $key (keys(%timerinterval)) {
 6922:         my ($cid,$rest) = split(/\0/,$key);
 6923:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6924:     }
 6925: 
 6926:     my %allroles=();
 6927:     my %allgroups=();
 6928: 
 6929:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6930:         my $role = $rolesdump{$area};
 6931:         $area =~ s/\_\w\w$//;
 6932: 
 6933:         my ($trole, $tend, $tstart, $group_privs);
 6934: 
 6935:         if ($role =~ /^cr/) {
 6936:         # Custom role, defined by a user 
 6937:         # e.g., user.role.cr/msu/smith/mynewrole
 6938:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6939:                 $trole = $1;
 6940:                 ($tend, $tstart) = split('_', $2);
 6941:             } else {
 6942:                 $trole = $role;
 6943:             }
 6944:         } elsif ($role =~ m|^gr/|) {
 6945:         # Role of member in a group, defined within a course/community
 6946:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6947:             ($trole, $tend, $tstart) = split(/_/, $role);
 6948:             next if $tstart eq '-1';
 6949:             ($trole, $group_privs) = split(/\//, $trole);
 6950:             $group_privs = &unescape($group_privs);
 6951:         } else {
 6952:         # Just a normal role, defined in roles.tab
 6953:             ($trole, $tend, $tstart) = split(/_/,$role);
 6954:         }
 6955: 
 6956:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6957:                  $username);
 6958:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6959: 
 6960:         # role expired or not available yet?
 6961:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6962:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6963: 
 6964:         next if $area eq '' or $trole eq '';
 6965: 
 6966:         my $spec = "$trole.$area";
 6967:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6968: 
 6969:         if ($trole =~ /^cr\//) {
 6970:         # Custom role, defined by a user
 6971:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6972:         } elsif ($trole eq 'gr') {
 6973:         # Role of a member in a group, defined within a course/community
 6974:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6975:             next;
 6976:         } else {
 6977:         # Normal role, defined in roles.tab
 6978:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6979:         }
 6980: 
 6981:         my $cid = $tdomain.'_'.$trest;
 6982:         unless ($firstaccchk{$cid}) {
 6983:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6984:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6985:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6986:                         $coursetimerstarts{$cid}{$item}; 
 6987:                 }
 6988:             }
 6989:             $firstaccchk{$cid} = 1;
 6990:         }
 6991:         unless ($timerintchk{$cid}) {
 6992:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6993:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6994:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6995:                        $coursetimerintervals{$cid}{$item};
 6996:                 }
 6997:             }
 6998:             $timerintchk{$cid} = 1;
 6999:         }
 7000:     }
 7001: 
 7002:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 7003:                                                           \%allroles, \%allgroups);
 7004:     $env{'user.adv'} = $userroles{'user.adv'};
 7005:     $env{'user.rar'} = $userroles{'user.rar'};
 7006: 
 7007:     return (\%userroles,\%firstaccenv,\%timerintenv);
 7008: }
 7009: 
 7010: sub set_arearole {
 7011:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 7012:     unless ($nolog) {
 7013: # log the associated role with the area
 7014:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 7015:     }
 7016:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 7017: }
 7018: 
 7019: sub custom_roleprivs {
 7020:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 7021:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 7022:     my $homsvr = &homeserver($rauthor,$rdomain);
 7023:     if (&hostname($homsvr) ne '') {
 7024:         my ($rdummy,$roledef)=
 7025:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 7026:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 7027:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 7028:             if (defined($syspriv)) {
 7029:                 if ($trest =~ /^$match_community$/) {
 7030:                     $syspriv =~ s/bre\&S//; 
 7031:                 }
 7032:                 $$allroles{'cm./'}.=':'.$syspriv;
 7033:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 7034:             }
 7035:             if ($tdomain ne '') {
 7036:                 if (defined($dompriv)) {
 7037:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 7038:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 7039:                 }
 7040:                 if (($trest ne '') && (defined($coursepriv))) {
 7041:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 7042:                         my $rolename = $1;
 7043:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 7044:                     }
 7045:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 7046:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 7047:                 }
 7048:             }
 7049:         }
 7050:     }
 7051: }
 7052: 
 7053: sub course_adhocrole_privs {
 7054:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 7055:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 7056:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 7057:         my (%currprivs,%storeprivs);
 7058:         foreach my $item (split(/:/,$coursepriv)) {
 7059:             my ($priv,$restrict) = split(/\&/,$item);
 7060:             $currprivs{$priv} = $restrict;
 7061:         }
 7062:         my (%possadd,%possremove,%full);
 7063:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 7064:             my ($priv,$restrict)=split(/\&/,$item);
 7065:             $full{$priv} = $restrict;
 7066:         }
 7067:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 7068:             next if ($item eq '');
 7069:             my ($rule,$rest) = split(/=/,$item);
 7070:             next unless (($rule eq 'off') || ($rule eq 'on'));
 7071:             foreach my $priv (split(/:/,$rest)) {
 7072:                 if ($priv ne '') {
 7073:                     if ($rule eq 'off') {
 7074:                         $possremove{$priv} = 1;
 7075:                     } else {
 7076:                         $possadd{$priv} = 1;
 7077:                     }
 7078:                 }
 7079:             }
 7080:         }
 7081:         foreach my $priv (sort(keys(%full))) {
 7082:             if (exists($currprivs{$priv})) {
 7083:                 unless (exists($possremove{$priv})) {
 7084:                     $storeprivs{$priv} = $currprivs{$priv};
 7085:                 }
 7086:             } elsif (exists($possadd{$priv})) {
 7087:                 $storeprivs{$priv} = $full{$priv};
 7088:             }
 7089:         }
 7090:         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 7091:     }
 7092:     return $coursepriv;
 7093: }
 7094: 
 7095: sub group_roleprivs {
 7096:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 7097:     my $access = 1;
 7098:     my $now = time;
 7099:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 7100:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 7101:     if ($access) {
 7102:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 7103:         $$allgroups{$course}{$group} .=':'.$group_privs;
 7104:     }
 7105: }
 7106: 
 7107: sub standard_roleprivs {
 7108:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 7109:     if (defined($pr{$trole.':s'})) {
 7110:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 7111:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 7112:     }
 7113:     if ($tdomain ne '') {
 7114:         if (defined($pr{$trole.':d'})) {
 7115:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7116:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 7117:         }
 7118:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 7119:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 7120:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 7121:         }
 7122:     }
 7123: }
 7124: 
 7125: sub set_userprivs {
 7126:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 7127:     my $author=0;
 7128:     my $adv=0;
 7129:     my $rar=0;
 7130:     my %grouproles = ();
 7131:     if (keys(%{$allgroups}) > 0) {
 7132:         my @groupkeys; 
 7133:         foreach my $role (keys(%{$allroles})) {
 7134:             push(@groupkeys,$role);
 7135:         }
 7136:         if (ref($groups_roles) eq 'HASH') {
 7137:             foreach my $key (keys(%{$groups_roles})) {
 7138:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 7139:                     push(@groupkeys,$key);
 7140:                 }
 7141:             }
 7142:         }
 7143:         if (@groupkeys > 0) {
 7144:             foreach my $role (@groupkeys) {
 7145:                 my ($trole,$area,$sec,$extendedarea);
 7146:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 7147:                     $trole = $1;
 7148:                     $area = $2;
 7149:                     $sec = $3;
 7150:                     $extendedarea = $area.$sec;
 7151:                     if (exists($$allgroups{$area})) {
 7152:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 7153:                             my $spec = $trole.'.'.$extendedarea;
 7154:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 7155:                                                 $$allgroups{$area}{$group};
 7156:                         }
 7157:                     }
 7158:                 }
 7159:             }
 7160:         }
 7161:     }
 7162:     foreach my $group (keys(%grouproles)) {
 7163:         $$allroles{$group} = $grouproles{$group};
 7164:     }
 7165:     foreach my $role (keys(%{$allroles})) {
 7166:         my %thesepriv;
 7167:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 7168:         foreach my $item (split(/:/,$$allroles{$role})) {
 7169:             if ($item ne '') {
 7170:                 my ($privilege,$restrictions)=split(/&/,$item);
 7171:                 if ($restrictions eq '') {
 7172:                     $thesepriv{$privilege}='F';
 7173:                 } elsif ($thesepriv{$privilege} ne 'F') {
 7174:                     $thesepriv{$privilege}.=$restrictions;
 7175:                 }
 7176:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 7177:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 7178:             }
 7179:         }
 7180:         my $thesestr='';
 7181:         foreach my $priv (sort(keys(%thesepriv))) {
 7182: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 7183: 	}
 7184:         $userroles->{'user.priv.'.$role} = $thesestr;
 7185:     }
 7186:     return ($author,$adv,$rar);
 7187: }
 7188: 
 7189: sub role_status {
 7190:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 7191:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 7192:         my ($one,$two) = split(m{\./},$rolekey,2);
 7193:         (undef,undef,$$role) = split(/\./,$one,3);
 7194:         unless (!defined($$role) || $$role eq '') {
 7195:             $$where = '/'.$two;
 7196:             $$trolecode=$$role.'.'.$$where;
 7197:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 7198:             $$tstatus='is';
 7199:             if ($$tstart && $$tstart>$update) {
 7200:                 $$tstatus='future';
 7201:                 if ($$tstart<$now) {
 7202:                     if ($$tstart && $$tstart>$refresh) {
 7203:                         if (($$where ne '') && ($$role ne '')) {
 7204:                             my (%allroles,%allgroups,$group_privs,
 7205:                                 %groups_roles,@rolecodes);
 7206:                             my %userroles = (
 7207:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 7208:                             );
 7209:                             @rolecodes = ('cm'); 
 7210:                             my $spec=$$role.'.'.$$where;
 7211:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 7212:                             if ($$role =~ /^cr\//) {
 7213:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 7214:                                 push(@rolecodes,'cr');
 7215:                             } elsif ($$role eq 'gr') {
 7216:                                 push(@rolecodes,$$role);
 7217:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 7218:                                                     $env{'user.name'});
 7219:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 7220:                                 (undef,my $group_privs) = split(/\//,$trole);
 7221:                                 $group_privs = &unescape($group_privs);
 7222:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 7223:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 7224:                                 &get_groups_roles($tdomain,$trest,
 7225:                                                   \%course_roles,\@rolecodes,
 7226:                                                   \%groups_roles);
 7227:                             } else {
 7228:                                 push(@rolecodes,$$role);
 7229:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 7230:                             }
 7231:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 7232:                                                                    \%groups_roles);
 7233:                             &appenv(\%userroles,\@rolecodes);
 7234:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7235:                         }
 7236:                     }
 7237:                     $$tstatus = 'is';
 7238:                 }
 7239:             }
 7240:             if ($$tend) {
 7241:                 if ($$tend<$update) {
 7242:                     $$tstatus='expired';
 7243:                 } elsif ($$tend<$now) {
 7244:                     $$tstatus='will_not';
 7245:                 }
 7246:             }
 7247:         }
 7248:     }
 7249: }
 7250: 
 7251: sub get_groups_roles {
 7252:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 7253:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 7254:                   (ref($rolecodes) eq 'ARRAY') && 
 7255:                   (ref($groups_roles) eq 'HASH')); 
 7256:     if (keys(%{$cdom_courseroles}) > 0) {
 7257:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 7258:         if ($cdom ne '' && $cnum ne '') {
 7259:             foreach my $key (keys(%{$cdom_courseroles})) {
 7260:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 7261:                     my $crsrole = $1;
 7262:                     my $crssec = $2;
 7263:                     if ($crsrole =~ /^cr/) {
 7264:                         unless (grep(/^cr$/,@{$rolecodes})) {
 7265:                             push(@{$rolecodes},'cr');
 7266:                         }
 7267:                     } else {
 7268:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 7269:                             push(@{$rolecodes},$crsrole);
 7270:                         }
 7271:                     }
 7272:                     my $rolekey = "$crsrole./$cdom/$cnum";
 7273:                     if ($crssec ne '') {
 7274:                         $rolekey .= "/$crssec";
 7275:                     }
 7276:                     $rolekey .= './';
 7277:                     $groups_roles->{$rolekey} = $rolecodes;
 7278:                 }
 7279:             }
 7280:         }
 7281:     }
 7282:     return;
 7283: }
 7284: 
 7285: sub delete_env_groupprivs {
 7286:     my ($where,$courseroles,$possroles) = @_;
 7287:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 7288:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 7289:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 7290:         %{$courseroles->{$udom}} =
 7291:             &get_my_roles('','','userroles',['active'],
 7292:                           $possroles,[$udom],1);
 7293:     }
 7294:     if (ref($courseroles->{$udom}) eq 'HASH') {
 7295:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 7296:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 7297:             my $area = '/'.$cdom.'/'.$cnum;
 7298:             my $privkey = "user.priv.$crsrole.$area";
 7299:             if ($crssec ne '') {
 7300:                 $privkey .= '/'.$crssec;
 7301:             }
 7302:             $privkey .= ".$area/$group";
 7303:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 7304:         }
 7305:     }
 7306:     return;
 7307: }
 7308: 
 7309: sub check_adhoc_privs {
 7310:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 7311:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 7312:     if ($sec) {
 7313:         $cckey .= '/'.$sec;
 7314:     } 
 7315:     my $setprivs;
 7316:     if ($env{$cckey}) {
 7317:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 7318:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 7319:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 7320:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7321:             $setprivs = 1;
 7322:         }
 7323:     } else {
 7324:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 7325:         $setprivs = 1;
 7326:     }
 7327:     return $setprivs;
 7328: }
 7329: 
 7330: sub set_adhoc_privileges {
 7331: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 7332:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 7333:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 7334:     if ($sec ne '') {
 7335:         $area .= '/'.$sec;
 7336:     }
 7337:     my $spec = $role.'.'.$area;
 7338:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 7339:                                   $env{'user.name'},1);
 7340:     my %rolehash = ();
 7341:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 7342:         my $rolename = $1;
 7343:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 7344:         my %domdef = &get_domain_defaults($dcdom);
 7345:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 7346:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 7347:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 7348:             }
 7349:         }
 7350:     } else {
 7351:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 7352:     }
 7353:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 7354:     &appenv(\%userroles,[$role,'cm']);
 7355:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 7356:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
 7357:             ($caller eq 'tiny')) {
 7358:         &appenv( {'request.role'        => $spec,
 7359:                   'request.role.domain' => $dcdom,
 7360:                   'request.course.sec'  => $sec,
 7361:                  }
 7362:                );
 7363:         my $tadv=0;
 7364:         if (&allowed('adv') eq 'F') { $tadv=1; }
 7365:         &appenv({'request.role.adv'    => $tadv});
 7366:     }
 7367: }
 7368: 
 7369: # --------------------------------------------------------------- get interface
 7370: 
 7371: sub get {
 7372:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7373:    my $items='';
 7374:    foreach my $item (@$storearr) {
 7375:        $items.=&escape($item).'&';
 7376:    }
 7377:    $items=~s/\&$//;
 7378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7379:    if (!$uname) { $uname=$env{'user.name'}; }
 7380:    my $uhome=&homeserver($uname,$udomain);
 7381: 
 7382:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 7383:    my @pairs=split(/\&/,$rep);
 7384:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 7385:      return @pairs;
 7386:    }
 7387:    my %returnhash=();
 7388:    my $i=0;
 7389:    foreach my $item (@$storearr) {
 7390:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7391:       $i++;
 7392:    }
 7393:    return %returnhash;
 7394: }
 7395: 
 7396: # --------------------------------------------------------------- del interface
 7397: 
 7398: sub del {
 7399:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7400:    my $items='';
 7401:    foreach my $item (@$storearr) {
 7402:        $items.=&escape($item).'&';
 7403:    }
 7404: 
 7405:    $items=~s/\&$//;
 7406:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7407:    if (!$uname) { $uname=$env{'user.name'}; }
 7408:    my $uhome=&homeserver($uname,$udomain);
 7409:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 7410: }
 7411: 
 7412: # -------------------------------------------------------------- dump interface
 7413: 
 7414: sub unserialize {
 7415:     my ($rep, $escapedkeys) = @_;
 7416: 
 7417:     return {} if $rep =~ /^error/;
 7418: 
 7419:     my %returnhash=();
 7420: 	foreach my $item (split(/\&/,$rep)) {
 7421: 	    my ($key, $value) = split(/=/, $item, 2);
 7422: 	    $key = unescape($key) unless $escapedkeys;
 7423: 	    next if $key =~ /^error: 2 /;
 7424: 	    $returnhash{$key} = &thaw_unescape($value);
 7425: 	}
 7426:     #return %returnhash;
 7427:     return \%returnhash;
 7428: }        
 7429: 
 7430: # see Lond::dump_with_regexp
 7431: # if $escapedkeys hash keys won't get unescaped.
 7432: sub dump {
 7433:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
 7434:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7435:     if (!$uname) { $uname=$env{'user.name'}; }
 7436:     my $uhome=&homeserver($uname,$udomain);
 7437: 
 7438:     if ($regexp) {
 7439:         $regexp=&escape($regexp);
 7440:     } else {
 7441:         $regexp='.';
 7442:     }
 7443:     if (grep { $_ eq $uhome } current_machine_ids()) {
 7444:         # user is hosted on this machine
 7445:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 7446:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 7447:         return %{unserialize($reply, $escapedkeys)};
 7448:     }
 7449:     my $rep;
 7450:     if ($encrypt) {
 7451:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7452:     } else {
 7453:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 7454:     }
 7455:     my @pairs=split(/\&/,$rep);
 7456:     my %returnhash=();
 7457:     if (!($rep =~ /^error/ )) {
 7458: 	foreach my $item (@pairs) {
 7459: 	    my ($key,$value)=split(/=/,$item,2);
 7460:         $key = unescape($key) unless $escapedkeys;
 7461:         #$key = &unescape($key);
 7462: 	    next if ($key =~ /^error: 2 /);
 7463: 	    $returnhash{$key}=&thaw_unescape($value);
 7464: 	}
 7465:     }
 7466:     return %returnhash;
 7467: }
 7468: 
 7469: 
 7470: # --------------------------------------------------------- dumpstore interface
 7471: 
 7472: sub dumpstore {
 7473:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 7474:    # same as dump but keys must be escaped. They may contain colon separated
 7475:    # lists of values that may themself contain colons (e.g. symbs).
 7476:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 7477: }
 7478: 
 7479: # -------------------------------------------------------------- keys interface
 7480: 
 7481: sub getkeys {
 7482:    my ($namespace,$udomain,$uname)=@_;
 7483:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7484:    if (!$uname) { $uname=$env{'user.name'}; }
 7485:    my $uhome=&homeserver($uname,$udomain);
 7486:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 7487:    my @keyarray=();
 7488:    foreach my $key (split(/\&/,$rep)) {
 7489:       next if ($key =~ /^error: 2 /);
 7490:       push(@keyarray,&unescape($key));
 7491:    }
 7492:    return @keyarray;
 7493: }
 7494: 
 7495: # --------------------------------------------------------------- currentdump
 7496: sub currentdump {
 7497:    my ($courseid,$sdom,$sname)=@_;
 7498:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 7499:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 7500:    $sname    = $env{'user.name'}         if (! defined($sname));
 7501:    my $uhome = &homeserver($sname,$sdom);
 7502:    my $rep;
 7503: 
 7504:    if (grep { $_ eq $uhome } current_machine_ids()) {
 7505:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 7506:                    $courseid)));
 7507:    } else {
 7508:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 7509:    }
 7510: 
 7511:    return if ($rep =~ /^(error:|no_such_host)/);
 7512:    #
 7513:    my %returnhash=();
 7514:    #
 7515:    if ($rep eq 'unknown_cmd') {
 7516:        # an old lond will not know currentdump
 7517:        # Do a dump and make it look like a currentdump
 7518:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 7519:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 7520:        my %hash = @tmp;
 7521:        @tmp=();
 7522:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 7523:    } else {
 7524:        my @pairs=split(/\&/,$rep);
 7525:        foreach my $pair (@pairs) {
 7526:            my ($key,$value)=split(/=/,$pair,2);
 7527:            my ($symb,$param) = split(/:/,$key);
 7528:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 7529:                                                         &thaw_unescape($value);
 7530:        }
 7531:    }
 7532:    return %returnhash;
 7533: }
 7534: 
 7535: sub convert_dump_to_currentdump{
 7536:     my %hash = %{shift()};
 7537:     my %returnhash;
 7538:     # Code ripped from lond, essentially.  The only difference
 7539:     # here is the unescaping done by lonnet::dump().  Conceivably
 7540:     # we might run in to problems with parameter names =~ /^v\./
 7541:     while (my ($key,$value) = each(%hash)) {
 7542:         my ($v,$symb,$param) = split(/:/,$key);
 7543: 	$symb  = &unescape($symb);
 7544: 	$param = &unescape($param);
 7545:         next if ($v eq 'version' || $symb eq 'keys');
 7546:         next if (exists($returnhash{$symb}) &&
 7547:                  exists($returnhash{$symb}->{$param}) &&
 7548:                  $returnhash{$symb}->{'v.'.$param} > $v);
 7549:         $returnhash{$symb}->{$param}=$value;
 7550:         $returnhash{$symb}->{'v.'.$param}=$v;
 7551:     }
 7552:     #
 7553:     # Remove all of the keys in the hashes which keep track of
 7554:     # the version of the parameter.
 7555:     while (my ($symb,$param_hash) = each(%returnhash)) {
 7556:         # use a foreach because we are going to delete from the hash.
 7557:         foreach my $key (keys(%$param_hash)) {
 7558:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 7559:         }
 7560:     }
 7561:     return \%returnhash;
 7562: }
 7563: 
 7564: # ------------------------------------------------------ critical inc interface
 7565: 
 7566: sub cinc {
 7567:     return &inc(@_,'critical');
 7568: }
 7569: 
 7570: # --------------------------------------------------------------- inc interface
 7571: 
 7572: sub inc {
 7573:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 7574:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7575:     if (!$uname) { $uname=$env{'user.name'}; }
 7576:     my $uhome=&homeserver($uname,$udomain);
 7577:     my $items='';
 7578:     if (! ref($store)) {
 7579:         # got a single value, so use that instead
 7580:         $items = &escape($store).'=&';
 7581:     } elsif (ref($store) eq 'SCALAR') {
 7582:         $items = &escape($$store).'=&';        
 7583:     } elsif (ref($store) eq 'ARRAY') {
 7584:         $items = join('=&',map {&escape($_);} @{$store});
 7585:     } elsif (ref($store) eq 'HASH') {
 7586:         while (my($key,$value) = each(%{$store})) {
 7587:             $items.= &escape($key).'='.&escape($value).'&';
 7588:         }
 7589:     }
 7590:     $items=~s/\&$//;
 7591:     if ($critical) {
 7592: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7593:     } else {
 7594: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7595:     }
 7596: }
 7597: 
 7598: # --------------------------------------------------------------- put interface
 7599: 
 7600: sub put {
 7601:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
 7602:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7603:    if (!$uname) { $uname=$env{'user.name'}; }
 7604:    my $uhome=&homeserver($uname,$udomain);
 7605:    my $items='';
 7606:    foreach my $item (keys(%$storehash)) {
 7607:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7608:    }
 7609:    $items=~s/\&$//;
 7610:    if ($encrypt) {
 7611:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
 7612:    } else {
 7613:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7614:    }
 7615: }
 7616: 
 7617: # ------------------------------------------------------------ newput interface
 7618: 
 7619: sub newput {
 7620:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7621:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7622:    if (!$uname) { $uname=$env{'user.name'}; }
 7623:    my $uhome=&homeserver($uname,$udomain);
 7624:    my $items='';
 7625:    foreach my $key (keys(%$storehash)) {
 7626:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7627:    }
 7628:    $items=~s/\&$//;
 7629:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7630: }
 7631: 
 7632: # ---------------------------------------------------------  putstore interface
 7633: 
 7634: sub putstore {
 7635:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7636:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7637:    if (!$uname) { $uname=$env{'user.name'}; }
 7638:    my $uhome=&homeserver($uname,$udomain);
 7639:    my $items='';
 7640:    foreach my $key (keys(%$storehash)) {
 7641:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7642:    }
 7643:    $items=~s/\&$//;
 7644:    my $esc_symb=&escape($symb);
 7645:    my $esc_v=&escape($version);
 7646:    my $reply =
 7647:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7648: 	      $uhome);
 7649:    if (($tolog) && ($reply eq 'ok')) {
 7650:        my $namevalue='';
 7651:        foreach my $key (keys(%{$storehash})) {
 7652:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7653:        }
 7654:        my $ip = &get_requestor_ip();
 7655:        $namevalue .= 'ip='.&escape($ip).
 7656:                      '&host='.&escape($perlvar{'lonHostID'}).
 7657:                      '&version='.$esc_v.
 7658:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7659:        &courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7660:    }
 7661:    if ($reply eq 'unknown_cmd') {
 7662:        # gfall back to way things use to be done
 7663:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7664: 			    $uname);
 7665:    }
 7666:    return $reply;
 7667: }
 7668: 
 7669: sub old_putstore {
 7670:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7671:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7672:     if (!$uname) { $uname=$env{'user.name'}; }
 7673:     my $uhome=&homeserver($uname,$udomain);
 7674:     my %newstorehash;
 7675:     foreach my $item (keys(%$storehash)) {
 7676: 	my $key = $version.':'.&escape($symb).':'.$item;
 7677: 	$newstorehash{$key} = $storehash->{$item};
 7678:     }
 7679:     my $items='';
 7680:     my %allitems = ();
 7681:     foreach my $item (keys(%newstorehash)) {
 7682: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7683: 	    my $key = $1.':keys:'.$2;
 7684: 	    $allitems{$key} .= $3.':';
 7685: 	}
 7686: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7687:     }
 7688:     foreach my $item (keys(%allitems)) {
 7689: 	$allitems{$item} =~ s/\:$//;
 7690: 	$items.= $item.'='.$allitems{$item}.'&';
 7691:     }
 7692:     $items=~s/\&$//;
 7693:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7694: }
 7695: 
 7696: # ------------------------------------------------------ critical put interface
 7697: 
 7698: sub cput {
 7699:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7700:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7701:    if (!$uname) { $uname=$env{'user.name'}; }
 7702:    my $uhome=&homeserver($uname,$udomain);
 7703:    my $items='';
 7704:    foreach my $item (keys(%$storehash)) {
 7705:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7706:    }
 7707:    $items=~s/\&$//;
 7708:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7709: }
 7710: 
 7711: # -------------------------------------------------------------- eget interface
 7712: 
 7713: sub eget {
 7714:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7715:    my $items='';
 7716:    foreach my $item (@$storearr) {
 7717:        $items.=&escape($item).'&';
 7718:    }
 7719:    $items=~s/\&$//;
 7720:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7721:    if (!$uname) { $uname=$env{'user.name'}; }
 7722:    my $uhome=&homeserver($uname,$udomain);
 7723:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7724:    my @pairs=split(/\&/,$rep);
 7725:    my %returnhash=();
 7726:    my $i=0;
 7727:    foreach my $item (@$storearr) {
 7728:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7729:       $i++;
 7730:    }
 7731:    return %returnhash;
 7732: }
 7733: 
 7734: # ------------------------------------------------------------ tmpput interface
 7735: sub tmpput {
 7736:     my ($storehash,$server,$context)=@_;
 7737:     my $items='';
 7738:     foreach my $item (keys(%$storehash)) {
 7739: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7740:     }
 7741:     $items=~s/\&$//;
 7742:     if (defined($context)) {
 7743:         $items .= ':'.&escape($context);
 7744:     }
 7745:     return &reply("tmpput:$items",$server);
 7746: }
 7747: 
 7748: # ------------------------------------------------------------ tmpget interface
 7749: sub tmpget {
 7750:     my ($token,$server)=@_;
 7751:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7752:     my $rep=&reply("tmpget:$token",$server);
 7753:     my %returnhash;
 7754:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7755:         return %returnhash;
 7756:     }
 7757:     foreach my $item (split(/\&/,$rep)) {
 7758: 	my ($key,$value)=split(/=/,$item);
 7759: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7760:     }
 7761:     return %returnhash;
 7762: }
 7763: 
 7764: # ------------------------------------------------------------ tmpdel interface
 7765: sub tmpdel {
 7766:     my ($token,$server)=@_;
 7767:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7768:     return &reply("tmpdel:$token",$server);
 7769: }
 7770: 
 7771: # ------------------------------------------------------------ get_timebased_id 
 7772: 
 7773: sub get_timebased_id {
 7774:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7775:         $maxtries) = @_;
 7776:     my ($newid,$error,$dellock);
 7777:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 7778:         return ('','ok','invalid call to get suffix');
 7779:     }
 7780: 
 7781: # set defaults for any optional args for which values were not supplied
 7782:     if ($who eq '') {
 7783:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7784:     }
 7785:     if (!$locktries) {
 7786:         $locktries = 3;
 7787:     }
 7788:     if (!$maxtries) {
 7789:         $maxtries = 10;
 7790:     }
 7791:     
 7792:     if (($cdom eq '') || ($cnum eq '')) {
 7793:         if ($env{'request.course.id'}) {
 7794:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7795:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7796:         }
 7797:         if (($cdom eq '') || ($cnum eq '')) {
 7798:             return ('','ok','call to get suffix not in course context');
 7799:         }
 7800:     }
 7801: 
 7802: # construct locking item
 7803:     my $lockhash = {
 7804:                       $prefix."\0".'locked_'.$keyid => $who,
 7805:                    };
 7806:     my $tries = 0;
 7807: 
 7808: # attempt to get lock on nohist_$namespace file
 7809:     my $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7810:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7811:         $tries ++;
 7812:         sleep 1;
 7813:         $gotlock = &newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7814:     }
 7815: 
 7816: # attempt to get unique identifier, based on current timestamp
 7817:     if ($gotlock eq 'ok') {
 7818:         my %inuse = &dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7819:         my $id = time;
 7820:         $newid = $id;
 7821:         if ($idtype eq 'addcode') {
 7822:             $newid .= &sixnum_code();
 7823:         }
 7824:         my $idtries = 0;
 7825:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7826:             if ($idtype eq 'concat') {
 7827:                 $newid = $id.$idtries;
 7828:             } elsif ($idtype eq 'addcode') {
 7829:                 $newid = $newid.&sixnum_code();
 7830:             } else {
 7831:                 $newid ++;
 7832:             }
 7833:             $idtries ++;
 7834:         }
 7835:         if (!exists($inuse{$prefix."\0".$newid})) {
 7836:             my %new_item =  (
 7837:                               $prefix."\0".$newid => $who,
 7838:                             );
 7839:             my $putresult = &put('nohist_'.$namespace,\%new_item,
 7840:                                                  $cdom,$cnum);
 7841:             if ($putresult ne 'ok') {
 7842:                 undef($newid);
 7843:                 $error = 'error saving new item: '.$putresult;
 7844:             }
 7845:         } else {
 7846:              undef($newid);
 7847:              $error = ('error: no unique suffix available for the new item ');
 7848:         }
 7849: #  remove lock
 7850:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7851:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7852:     } else {
 7853:         $error = "error: could not obtain lockfile\n";
 7854:         $dellock = 'ok';
 7855:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7856:             $dellock = 'nolock';
 7857:         }
 7858:     }
 7859:     return ($newid,$dellock,$error);
 7860: }
 7861: 
 7862: sub sixnum_code {
 7863:     my $code;
 7864:     for (0..6) {
 7865:         $code .= int( rand(9) );
 7866:     }
 7867:     return $code;
 7868: }
 7869: 
 7870: # -------------------------------------------------- portfolio access checking
 7871: 
 7872: sub portfolio_access {
 7873:     my ($requrl,$clientip) = @_;
 7874:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7875:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7876:     if ($result) {
 7877:         my %setters;
 7878:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7879:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7880:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
 7881:             if (($startblock && $endblock) || ($by_ip)) {
 7882:                 return 'B';
 7883:             }
 7884:         } else {
 7885:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
 7886:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 7887:             if (($startblock && $endblock) || ($by_ip)) {
 7888:                 return 'B';
 7889:             }
 7890:         }
 7891:     }
 7892:     if ($result eq 'ok') {
 7893:        return 'F';
 7894:     } elsif ($result =~ /^[^:]+:guest_/) {
 7895:        return 'A';
 7896:     }
 7897:     return '';
 7898: }
 7899: 
 7900: sub get_portfolio_access {
 7901:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7902: 
 7903:     if (!ref($access_hash)) {
 7904: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7905: 	my %access_controls = &get_access_controls($current_perms,$group,
 7906: 						   $file_name);
 7907: 	$access_hash = $access_controls{$file_name};
 7908:     }
 7909: 
 7910:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7911:     my $now = time;
 7912:     if (ref($access_hash) eq 'HASH') {
 7913:         foreach my $key (keys(%{$access_hash})) {
 7914:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7915:             if ($start > $now) {
 7916:                 next;
 7917:             }
 7918:             if ($end && $end<$now) {
 7919:                 next;
 7920:             }
 7921:             if ($scope eq 'public') {
 7922:                 $public = $key;
 7923:                 last;
 7924:             } elsif ($scope eq 'guest') {
 7925:                 $guest = $key;
 7926:             } elsif ($scope eq 'domains') {
 7927:                 push(@domains,$key);
 7928:             } elsif ($scope eq 'users') {
 7929:                 push(@users,$key);
 7930:             } elsif ($scope eq 'course') {
 7931:                 push(@courses,$key);
 7932:             } elsif ($scope eq 'group') {
 7933:                 push(@groups,$key);
 7934:             } elsif ($scope eq 'ip') {
 7935:                 push(@ips,$key);
 7936:             }
 7937:         }
 7938:         if ($public) {
 7939:             return 'ok';
 7940:         } elsif (@ips > 0) {
 7941:             my $allowed;
 7942:             foreach my $ipkey (@ips) {
 7943:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7944:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7945:                         $allowed = 1;
 7946:                         last; 
 7947:                     }
 7948:                 }
 7949:             }
 7950:             if ($allowed) {
 7951:                 return 'ok';
 7952:             }
 7953:         }
 7954:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7955:             if ($guest) {
 7956:                 return $guest;
 7957:             }
 7958:         } else {
 7959:             if (@domains > 0) {
 7960:                 foreach my $domkey (@domains) {
 7961:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7962:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7963:                             return 'ok';
 7964:                         }
 7965:                     }
 7966:                 }
 7967:             }
 7968:             if (@users > 0) {
 7969:                 foreach my $userkey (@users) {
 7970:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7971:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7972:                             if (ref($item) eq 'HASH') {
 7973:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7974:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7975:                                     return 'ok';
 7976:                                 }
 7977:                             }
 7978:                         }
 7979:                     } 
 7980:                 }
 7981:             }
 7982:             my %roleshash;
 7983:             my @courses_and_groups = @courses;
 7984:             push(@courses_and_groups,@groups); 
 7985:             if (@courses_and_groups > 0) {
 7986:                 my (%allgroups,%allroles); 
 7987:                 my ($start,$end,$role,$sec,$group);
 7988:                 foreach my $envkey (%env) {
 7989:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7990:                         my $cid = $2.'_'.$3; 
 7991:                         if ($1 eq 'gr') {
 7992:                             $group = $4;
 7993:                             $allgroups{$cid}{$group} = $env{$envkey};
 7994:                         } else {
 7995:                             if ($4 eq '') {
 7996:                                 $sec = 'none';
 7997:                             } else {
 7998:                                 $sec = $4;
 7999:                             }
 8000:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8001:                         }
 8002:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 8003:                         my $cid = $2.'_'.$3;
 8004:                         if ($4 eq '') {
 8005:                             $sec = 'none';
 8006:                         } else {
 8007:                             $sec = $4;
 8008:                         }
 8009:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 8010:                     }
 8011:                 }
 8012:                 if (keys(%allroles) == 0) {
 8013:                     return;
 8014:                 }
 8015:                 foreach my $key (@courses_and_groups) {
 8016:                     my %content = %{$$access_hash{$key}};
 8017:                     my $cnum = $content{'number'};
 8018:                     my $cdom = $content{'domain'};
 8019:                     my $cid = $cdom.'_'.$cnum;
 8020:                     if (!exists($allroles{$cid})) {
 8021:                         next;
 8022:                     }    
 8023:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 8024:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 8025:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 8026:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 8027:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 8028:                         foreach my $role (keys(%{$allroles{$cid}})) {
 8029:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 8030:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 8031:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 8032:                                         if (grep/^all$/,@sections) {
 8033:                                             return 'ok';
 8034:                                         } else {
 8035:                                             if (grep/^$sec$/,@sections) {
 8036:                                                 return 'ok';
 8037:                                             }
 8038:                                         }
 8039:                                     }
 8040:                                 }
 8041:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 8042:                                     if (grep/^none$/,@groups) {
 8043:                                         return 'ok';
 8044:                                     }
 8045:                                 } else {
 8046:                                     if (grep/^all$/,@groups) {
 8047:                                         return 'ok';
 8048:                                     } 
 8049:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 8050:                                         if (grep/^$group$/,@groups) {
 8051:                                             return 'ok';
 8052:                                         }
 8053:                                     }
 8054:                                 } 
 8055:                             }
 8056:                         }
 8057:                     }
 8058:                 }
 8059:             }
 8060:             if ($guest) {
 8061:                 return $guest;
 8062:             }
 8063:         }
 8064:     }
 8065:     return;
 8066: }
 8067: 
 8068: sub course_group_datechecker {
 8069:     my ($dates,$now,$status) = @_;
 8070:     my ($start,$end) = split(/\./,$dates);
 8071:     if (!$start && !$end) {
 8072:         return 'ok';
 8073:     }
 8074:     if (grep/^active$/,@{$status}) {
 8075:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 8076:             return 'ok';
 8077:         }
 8078:     }
 8079:     if (grep/^previous$/,@{$status}) {
 8080:         if ($end > $now ) {
 8081:             return 'ok';
 8082:         }
 8083:     }
 8084:     if (grep/^future$/,@{$status}) {
 8085:         if ($start > $now) {
 8086:             return 'ok';
 8087:         }
 8088:     }
 8089:     return; 
 8090: }
 8091: 
 8092: sub parse_portfolio_url {
 8093:     my ($url) = @_;
 8094: 
 8095:     my ($type,$udom,$unum,$group,$file_name);
 8096:     
 8097:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 8098: 	$type = 1;
 8099:         $udom = $1;
 8100:         $unum = $2;
 8101:         $file_name = $3;
 8102:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 8103: 	$type = 2;
 8104:         $udom = $1;
 8105:         $unum = $2;
 8106:         $group = $3;
 8107:         $file_name = $3.'/'.$4;
 8108:     }
 8109:     if (wantarray) {
 8110: 	return ($type,$udom,$unum,$file_name,$group);
 8111:     }
 8112:     return $type;
 8113: }
 8114: 
 8115: sub is_portfolio_url {
 8116:     my ($url) = @_;
 8117:     return scalar(&parse_portfolio_url($url));
 8118: }
 8119: 
 8120: sub is_portfolio_file {
 8121:     my ($file) = @_;
 8122:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 8123:         return 1;
 8124:     }
 8125:     return;
 8126: }
 8127: 
 8128: sub is_coursetool_logo {
 8129:     my ($uri) = @_;
 8130:     if ($env{'request.course.id'}) {
 8131:         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 8132:         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
 8133:             return 1;
 8134:         }
 8135:     }
 8136:     return;
 8137: }
 8138: 
 8139: sub usertools_access {
 8140:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 8141:     my ($access,%tools);
 8142:     if ($context eq '') {
 8143:         $context = 'tools';
 8144:     }
 8145:     if ($context eq 'requestcourses') {
 8146:         %tools = (
 8147:                       official   => 1,
 8148:                       unofficial => 1,
 8149:                       community  => 1,
 8150:                       textbook   => 1,
 8151:                       placement  => 1,
 8152:                       lti        => 1,
 8153:                  );
 8154:     } elsif ($context eq 'requestauthor') {
 8155:         %tools = (
 8156:                       requestauthor => 1,
 8157:                  );
 8158:     } else {
 8159:         %tools = (
 8160:                       aboutme   => 1,
 8161:                       blog      => 1,
 8162:                       webdav    => 1,
 8163:                       portfolio => 1,
 8164:                       timezone  => 1,
 8165:                  );
 8166:     }
 8167:     return if (!defined($tools{$tool}));
 8168: 
 8169:     if (($udom eq '') || ($uname eq '')) {
 8170:         $udom = $env{'user.domain'};
 8171:         $uname = $env{'user.name'};
 8172:     }
 8173: 
 8174:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8175:         if ($action ne 'reload') {
 8176:             if ($context eq 'requestcourses') {
 8177:                 return $env{'environment.canrequest.'.$tool};
 8178:             } elsif ($context eq 'requestauthor') {
 8179:                 return $env{'environment.canrequest.author'};
 8180:             } else {
 8181:                 return $env{'environment.availabletools.'.$tool};
 8182:             }
 8183:         }
 8184:     }
 8185: 
 8186:     my ($toolstatus,$inststatus,$envkey);
 8187:     if ($context eq 'requestauthor') {
 8188:         $envkey = $context; 
 8189:     } else {
 8190:         $envkey = $context.'.'.$tool;
 8191:     }
 8192: 
 8193:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8194:          ($action ne 'reload')) {
 8195:         $toolstatus = $env{'environment.'.$envkey};
 8196:         $inststatus = $env{'environment.inststatus'};
 8197:     } else {
 8198:         if (ref($userenvref) eq 'HASH') {
 8199:             $toolstatus = $userenvref->{$envkey};
 8200:             $inststatus = $userenvref->{'inststatus'};
 8201:         } else {
 8202:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 8203:             $toolstatus = $userenv{$envkey};
 8204:             $inststatus = $userenv{'inststatus'};
 8205:         }
 8206:     }
 8207: 
 8208:     if ($toolstatus ne '') {
 8209:         if ($toolstatus) {
 8210:             $access = 1;
 8211:         } else {
 8212:             $access = 0;
 8213:         }
 8214:         return $access;
 8215:     }
 8216: 
 8217:     my ($is_adv,%domdef);
 8218:     if (ref($is_advref) eq 'HASH') {
 8219:         $is_adv = $is_advref->{'is_adv'};
 8220:     } else {
 8221:         $is_adv = &is_advanced_user($udom,$uname);
 8222:     }
 8223:     if (ref($domdefref) eq 'HASH') {
 8224:         %domdef = %{$domdefref};
 8225:     } else {
 8226:         %domdef = &get_domain_defaults($udom);
 8227:     }
 8228:     if (ref($domdef{$tool}) eq 'HASH') {
 8229:         if ($is_adv) {
 8230:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 8231:                 if ($domdef{$tool}{'_LC_adv'}) { 
 8232:                     $access = 1;
 8233:                 } else {
 8234:                     $access = 0;
 8235:                 }
 8236:                 return $access;
 8237:             }
 8238:         }
 8239:         if ($inststatus ne '') {
 8240:             my ($hasaccess,$hasnoaccess);
 8241:             foreach my $affiliation (split(/:/,$inststatus)) {
 8242:                 if ($domdef{$tool}{$affiliation} ne '') { 
 8243:                     if ($domdef{$tool}{$affiliation}) {
 8244:                         $hasaccess = 1;
 8245:                     } else {
 8246:                         $hasnoaccess = 1;
 8247:                     }
 8248:                 }
 8249:             }
 8250:             if ($hasaccess || $hasnoaccess) {
 8251:                 if ($hasaccess) {
 8252:                     $access = 1;
 8253:                 } elsif ($hasnoaccess) {
 8254:                     $access = 0; 
 8255:                 }
 8256:                 return $access;
 8257:             }
 8258:         } else {
 8259:             if ($domdef{$tool}{'default'} ne '') {
 8260:                 if ($domdef{$tool}{'default'}) {
 8261:                     $access = 1;
 8262:                 } elsif ($domdef{$tool}{'default'} == 0) {
 8263:                     $access = 0;
 8264:                 }
 8265:                 return $access;
 8266:             }
 8267:         }
 8268:     } else {
 8269:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 8270:             $access = 1;
 8271:         } else {
 8272:             $access = 0;
 8273:         }
 8274:         return $access;
 8275:     }
 8276: }
 8277: 
 8278: sub is_course_owner {
 8279:     my ($cdom,$cnum,$udom,$uname) = @_;
 8280:     if (($udom eq '') || ($uname eq '')) {
 8281:         $udom = $env{'user.domain'};
 8282:         $uname = $env{'user.name'};
 8283:     }
 8284:     unless (($udom eq '') || ($uname eq '')) {
 8285:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 8286:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 8287:                 return 1;
 8288:             } else {
 8289:                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
 8290:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 8291:                     return 1;
 8292:                 }
 8293:             }
 8294:         }
 8295:     }
 8296:     return;
 8297: }
 8298: 
 8299: sub is_advanced_user {
 8300:     my ($udom,$uname,$nocache) = @_;
 8301:     my ($is_adv,$is_author,$use_cache,$hashid);
 8302:     if ($udom ne '' && $uname ne '') {
 8303:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8304:             if (wantarray) {
 8305:                 return ($env{'user.adv'},$env{'user.author'});
 8306:             } else {
 8307:                 return $env{'user.adv'};
 8308:             }
 8309:         } elsif (!$nocache) {
 8310:             $use_cache = 1;
 8311:             $hashid = "$udom:$uname";  
 8312:             my ($info,$cached)=&is_cached_new('isadvau',$hashid);
 8313:             if ($cached) {
 8314:                 ($is_adv,$is_author) = split(/:/,$info);
 8315:                 if (wantarray) {
 8316:                     return ($is_adv,$is_author);
 8317:                 }
 8318:                 return $is_adv; 
 8319:             }
 8320:         }
 8321:     }
 8322:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 8323:     my %allroles;
 8324:     foreach my $role (keys(%roleshash)) {
 8325:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 8326:         my $area = '/'.$tdomain.'/'.$trest;
 8327:         if ($sec ne '') {
 8328:             $area .= '/'.$sec;
 8329:         }
 8330:         if (($area ne '') && ($trole ne '')) {
 8331:             my $spec=$trole.'.'.$area;
 8332:             if ($trole =~ /^cr\//) {
 8333:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 8334:             } elsif ($trole ne 'gr') {
 8335:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 8336:             }
 8337:             if ($trole eq 'au') {
 8338:                 $is_author = 1;
 8339:             }
 8340:         }
 8341:     }
 8342:     foreach my $role (keys(%allroles)) {
 8343:         last if ($is_adv);
 8344:         foreach my $item (split(/:/,$allroles{$role})) {
 8345:             if ($item ne '') {
 8346:                 my ($privilege,$restrictions)=split(/&/,$item);
 8347:                 if ($privilege eq 'adv') {
 8348:                     $is_adv = 1;
 8349:                     last;
 8350:                 }
 8351:             }
 8352:         }
 8353:     }
 8354:     if ($use_cache) {
 8355:         my $cachetime = 600;
 8356:         &do_cache_new('isadvau',$hashid,$is_adv.':'.$is_author,$cachetime);
 8357:     }
 8358:     if (wantarray) {
 8359:         return ($is_adv,$is_author);
 8360:     }
 8361:     return $is_adv;
 8362: }
 8363: 
 8364: sub check_can_request {
 8365:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
 8366:     my $canreq = 0;
 8367:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8368:         $uname = $env{'user.name'};
 8369:         $udom = $env{'user.domain'};
 8370:     }
 8371:     my ($types,$typename) = &Apache::loncommon::course_types();
 8372:     my @options = ('approval','validate','autolimit');
 8373:     my $optregex = join('|',@options);
 8374:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 8375:         my %willtrust;
 8376:         foreach my $type (@{$types}) {
 8377:             if (&usertools_access($uname,$udom,$type,undef,
 8378:                                   'requestcourses')) {
 8379:                 $canreq ++;
 8380:                 if (ref($request_domains) eq 'HASH') {
 8381:                     push(@{$request_domains->{$type}},$udom);
 8382:                 }
 8383:                 if ($dom eq $udom) {
 8384:                     $can_request->{$type} = 1;
 8385:                 }
 8386:             }
 8387:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
 8388:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
 8389:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 8390:                 if (@curr > 0) {
 8391:                     foreach my $item (@curr) {
 8392:                         if (ref($request_domains) eq 'HASH') {
 8393:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 8394:                             if ($otherdom ne '') {
 8395:                                 unless (exists($willtrust{$otherdom})) {
 8396:                                     $willtrust{$otherdom} = &will_trust('reqcrs',$env{'user.domain'},$otherdom);
 8397:                                 }
 8398:                                 if ($willtrust{$otherdom}) {
 8399:                                     if (ref($request_domains->{$type}) eq 'ARRAY') {
 8400:                                         unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 8401:                                             push(@{$request_domains->{$type}},$otherdom);
 8402:                                         }
 8403:                                     } else {
 8404:                                         push(@{$request_domains->{$type}},$otherdom);
 8405:                                     }
 8406:                                 }
 8407:                             }
 8408:                         }
 8409:                     }
 8410:                     unless ($dom eq $env{'user.domain'}) {
 8411:                         $canreq ++;
 8412:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 8413:                             $can_request->{$type} = 1;
 8414:                         }
 8415:                     }
 8416:                 }
 8417:             }
 8418:         }
 8419:     }
 8420:     return $canreq;
 8421: }
 8422: 
 8423: # ---------------------------------------------- Custom access rule evaluation
 8424: 
 8425: sub customaccess {
 8426:     my ($priv,$uri)=@_;
 8427:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 8428:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 8429:     $udom = &LONCAPA::clean_domain($udom);
 8430:     $ucrs = &LONCAPA::clean_username($ucrs);
 8431:     my $access=0;
 8432:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 8433: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 8434: 	if ($type eq 'user') {
 8435: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8436: 		my ($tdom,$tuname)=split(m{/},$scope);
 8437: 		if ($tdom) {
 8438: 		    if ($tdom ne $env{'user.domain'}) { next; }
 8439: 		}
 8440: 		if ($tuname) {
 8441: 		    if ($tuname ne $env{'user.name'}) { next; }
 8442: 		}
 8443: 		$access=($effect eq 'allow');
 8444: 		last;
 8445: 	    }
 8446: 	} else {
 8447: 	    if ($role) {
 8448: 		if ($role ne $urole) { next; }
 8449: 	    }
 8450: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 8451: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 8452: 		if ($tdom) {
 8453: 		    if ($tdom ne $udom) { next; }
 8454: 		}
 8455: 		if ($tcrs) {
 8456: 		    if ($tcrs ne $ucrs) { next; }
 8457: 		}
 8458: 		if ($tsec) {
 8459: 		    if ($tsec ne $usec) { next; }
 8460: 		}
 8461: 		$access=($effect eq 'allow');
 8462: 		last;
 8463: 	    }
 8464: 	    if ($realm eq '' && $role eq '') {
 8465: 		$access=($effect eq 'allow');
 8466: 	    }
 8467: 	}
 8468:     }
 8469:     return $access;
 8470: }
 8471: 
 8472: # ------------------------------------------------- Check for a user privilege
 8473: 
 8474: sub allowed {
 8475:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
 8476:     my $ver_orguri=$uri;
 8477:     $uri=&deversion($uri);
 8478:     my $orguri=$uri;
 8479:     $uri=&declutter($uri);
 8480: 
 8481:     if ($priv eq 'evb') {
 8482: # Evade communication block restrictions for specified role in a course or domain
 8483:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 8484:             return $1;
 8485:         } else {
 8486:             return;
 8487:         }
 8488:     }
 8489: 
 8490:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 8491: # Free bre access to adm and meta resources
 8492:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
 8493: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 8494: 	&& ($priv eq 'bre')) {
 8495: 	return 'F';
 8496:     }
 8497: 
 8498: # Free bre access to user's own portfolio contents
 8499:     my ($space,$domain,$name,@dir)=split('/',$uri);
 8500:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 8501: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 8502:         my %setters;
 8503:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
 8504:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
 8505:         if (($startblock && $endblock) || ($by_ip)) {
 8506:             return 'B';
 8507:         } else {
 8508:             return 'F';
 8509:         }
 8510:     }
 8511: 
 8512: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 8513:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 8514:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 8515:         if (exists($env{'request.course.id'})) {
 8516:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8517:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8518:             if (($domain eq $cdom) && ($name eq $cnum)) {
 8519:                 my $courseprivid=$env{'request.course.id'};
 8520:                 $courseprivid=~s/\_/\//;
 8521:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 8522:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 8523:                     return $1; 
 8524:                 } else {
 8525:                     if ($env{'request.course.sec'}) {
 8526:                         $courseprivid.='/'.$env{'request.course.sec'};
 8527:                     }
 8528:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 8529:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 8530:                         return $2;
 8531:                     }
 8532:                 }
 8533:             }
 8534:         }
 8535:     }
 8536: 
 8537: # Free bre to public access
 8538: 
 8539:     if ($priv eq 'bre') {
 8540:         my $copyright;
 8541:         unless ($uri =~ /ext\.tool/) {
 8542:             $copyright=&metadata($uri,'copyright');
 8543:         }
 8544: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 8545:            return 'F'; 
 8546:         }
 8547:         if ($copyright eq 'priv') {
 8548:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8549: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 8550: 		return '';
 8551:             }
 8552:         }
 8553:         if ($copyright eq 'domain') {
 8554:             $uri=~/([^\/]+)\/([^\/]+)\//;
 8555: 	    unless (($env{'user.domain'} eq $1) ||
 8556:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 8557: 		return '';
 8558:             }
 8559:         }
 8560:         if ($env{'request.role'}=~ /li\.\//) {
 8561:             # Library role, so allow browsing of resources in this domain.
 8562:             return 'F';
 8563:         }
 8564:         if ($copyright eq 'custom') {
 8565: 	    unless (&customaccess($priv,$uri)) { return ''; }
 8566:         }
 8567:     }
 8568:     # Domain coordinator is trying to create a course
 8569:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 8570:         # uri is the requested domain in this case.
 8571:         # comparison to 'request.role.domain' shows if the user has selected
 8572:         # a role of dc for the domain in question.
 8573:         return 'F' if ($uri eq $env{'request.role.domain'});
 8574:     }
 8575: 
 8576:     my $thisallowed='';
 8577:     my $statecond=0;
 8578:     my $courseprivid='';
 8579: 
 8580:     my $ownaccess;
 8581:     # Community Coordinator or Assistant Co-author browsing resource space.
 8582:     if (($priv eq 'bro') && ($env{'user.author'})) {
 8583:         if ($uri eq '') {
 8584:             $ownaccess = 1;
 8585:         } else {
 8586:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 8587:                 my $udom = $env{'user.domain'};
 8588:                 my $uname = $env{'user.name'};
 8589:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 8590:                     $ownaccess = 1;
 8591:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 8592:                     unless ($uri =~ m{\.\./}) {
 8593:                         $ownaccess = 1;
 8594:                     }
 8595:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 8596:                     my $now = time;
 8597:                     if ($uri =~ m{^([^/]+)/?$}) {
 8598:                         my $adom = $1;
 8599:                         foreach my $key (keys(%env)) {
 8600:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 8601:                                 my ($start,$end) = split(/\./,$env{$key});
 8602:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8603:                                     $ownaccess = 1;
 8604:                                     last;
 8605:                                 }
 8606:                             }
 8607:                         }
 8608:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 8609:                         my $adom = $1;
 8610:                         my $aname = $2;
 8611:                         foreach my $role ('ca','aa') { 
 8612:                             if ($env{"user.role.$role./$adom/$aname"}) {
 8613:                                 my ($start,$end) =
 8614:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
 8615:                                 if (($now >= $start) && (!$end || $end > $now)) {
 8616:                                     $ownaccess = 1;
 8617:                                     last;
 8618:                                 }
 8619:                             }
 8620:                         }
 8621:                     }
 8622:                 }
 8623:             }
 8624:         }
 8625:     }
 8626: 
 8627: # Course
 8628: 
 8629:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 8630:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8631:             $thisallowed.=$1;
 8632:         }
 8633:     }
 8634: 
 8635: # Domain
 8636: 
 8637:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 8638:        =~/\Q$priv\E\&([^\:]*)/) {
 8639:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8640:             $thisallowed.=$1;
 8641:         }
 8642:     }
 8643: 
 8644: # User who is not author or co-author might still be able to edit
 8645: # resource of an author in the domain (e.g., if Domain Coordinator).
 8646:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8647:         (&allowed('mdc',$env{'request.course.id'}))) {
 8648:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8649:             $thisallowed.=$1;
 8650:         }
 8651:     }
 8652: 
 8653: # Course: uri itself is a course
 8654:     my $courseuri=$uri;
 8655:     $courseuri=~s/\_(\d)/\/$1/;
 8656:     $courseuri=~s/^([^\/])/\/$1/;
 8657: 
 8658:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8659:        =~/\Q$priv\E\&([^\:]*)/) {
 8660:         if ($priv eq 'mip') {
 8661:             my $rem = $1;
 8662:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8663:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8664:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8665:                 if ($cdom ne '') {
 8666:                     my %passwdconf = &get_passwdconf($cdom);
 8667:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8668:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8669:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8670:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8671:                                 unless (@inststatuses) {
 8672:                                     @inststatuses = ('default');
 8673:                                 }
 8674:                                 foreach my $status (@inststatuses) {
 8675:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8676:                                         $thisallowed.=$rem;
 8677:                                     }
 8678:                                 }
 8679:                             }
 8680:                         }
 8681:                     }
 8682:                 }
 8683:             }
 8684:         } else {
 8685:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8686:                 $thisallowed.=$1;
 8687:             }
 8688:         }
 8689:     }
 8690: 
 8691: # URI is an uploaded document for this course, default permissions don't matter
 8692: # not allowing 'edit' access (editupload) to uploaded course docs
 8693:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8694: 	$thisallowed='';
 8695:         my ($match)=&is_on_map($uri);
 8696:         if ($match) {
 8697:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8698:                   =~/\Q$priv\E\&([^\:]*)/) {
 8699:                 my $value = $1;
 8700:                 my $deeplinkblock;
 8701:                 unless ($nodeeplinkcheck) {
 8702:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8703:                 }
 8704:                 if ($deeplinkblock) {
 8705:                     $thisallowed='D';
 8706:                 } elsif ($noblockcheck) {
 8707:                     $thisallowed.=$value;
 8708:                 } else {
 8709:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8710:                     if (@blockers > 0) {
 8711:                         $thisallowed = 'B';
 8712:                     } else {
 8713:                         $thisallowed.=$value;
 8714:                     }
 8715:                 }
 8716:             }
 8717:         } else {
 8718:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8719:             if ($refuri) {
 8720:                 if ($refuri =~ m|^/adm/|) {
 8721:                     $thisallowed='F';
 8722:                 } else {
 8723:                     $refuri=&declutter($refuri);
 8724:                     my ($match) = &is_on_map($refuri);
 8725:                     if ($match) {
 8726:                         my $deeplinkblock;
 8727:                         unless ($nodeeplinkcheck) {
 8728:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8729:                         }
 8730:                         if ($deeplinkblock) {
 8731:                             $thisallowed='D';
 8732:                         } elsif ($noblockcheck) {
 8733:                             $thisallowed='F';
 8734:                         } else {
 8735:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8736:                             if (@blockers > 0) {
 8737:                                 $thisallowed = 'B';
 8738:                             } else {
 8739:                                 $thisallowed='F';
 8740:                             }
 8741:                         }
 8742:                     }
 8743:                 }
 8744:             }
 8745:         }
 8746:     }
 8747: 
 8748:     if ($priv eq 'bre'
 8749: 	&& $thisallowed ne 'F' 
 8750: 	&& $thisallowed ne '2'
 8751: 	&& &is_portfolio_url($uri)) {
 8752: 	$thisallowed = &portfolio_access($uri,$clientip);
 8753:     }
 8754: 
 8755: # Full access at system, domain or course-wide level? Exit.
 8756:     if ($thisallowed=~/F/) {
 8757: 	return 'F';
 8758:     }
 8759: 
 8760: # If this is generating or modifying users, exit with special codes
 8761: 
 8762:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8763: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8764: 	    my ($audom,$auname)=split('/',$uri);
 8765: # no author name given, so this just checks on the general right to make a co-author in this domain
 8766: 	    unless ($auname) { return $thisallowed; }
 8767: # an author name is given, so we are about to actually make a co-author for a certain account
 8768: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8769: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8770: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8771: 	}
 8772: 	return $thisallowed;
 8773:     }
 8774: #
 8775: # Gathered so far: system, domain and course wide privileges
 8776: #
 8777: # Course: See if uri or referer is an individual resource that is part of 
 8778: # the course
 8779: 
 8780:     if ($env{'request.course.id'}) {
 8781: 
 8782:         if ($priv eq 'bre') {
 8783:             if (&is_coursetool_logo($uri)) {
 8784:                 return 'F';
 8785:             }
 8786:         }
 8787: 
 8788: # If this is modifying password (internal auth) domains must match for user and user's role.
 8789: 
 8790:         if ($priv eq 'mip') {
 8791:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8792:                 return $thisallowed;
 8793:             } else {
 8794:                 return '';
 8795:             }
 8796:         }
 8797: 
 8798:        $courseprivid=$env{'request.course.id'};
 8799:        if ($env{'request.course.sec'}) {
 8800:           $courseprivid.='/'.$env{'request.course.sec'};
 8801:        }
 8802:        $courseprivid=~s/\_/\//;
 8803:        my $checkreferer=1;
 8804:        my ($match,$cond)=&is_on_map($uri);
 8805:        if ($match) {
 8806:            $statecond=$cond;
 8807:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8808:                =~/\Q$priv\E\&([^\:]*)/) {
 8809:                my $value = $1;
 8810:                if ($priv eq 'bre') {
 8811:                    my $deeplinkblock;
 8812:                    unless ($nodeeplinkcheck) {
 8813:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
 8814:                    }
 8815:                    if ($deeplinkblock) {
 8816:                        $thisallowed = 'D';
 8817:                    } elsif ($noblockcheck) {
 8818:                        $thisallowed.=$value;
 8819:                    } else {
 8820:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
 8821:                        if (@blockers > 0) {
 8822:                            $thisallowed = 'B';
 8823:                        } else {
 8824:                            $thisallowed.=$value;
 8825:                        }
 8826:                    }
 8827:                } else {
 8828:                    $thisallowed.=$value;
 8829:                }
 8830:                $checkreferer=0;
 8831:            }
 8832:        }
 8833: 
 8834:        if ($checkreferer) {
 8835: 	  my $refuri=$env{'httpref.'.$orguri};
 8836:             unless ($refuri) {
 8837:                 foreach my $key (keys(%env)) {
 8838: 		    if ($key=~/^httpref\..*\*/) {
 8839: 			my $pattern=$key;
 8840:                         $pattern=~s/^httpref\.\/res\///;
 8841:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8842:                         $pattern=~s/\//\\\//g;
 8843:                         if ($orguri=~/$pattern/) {
 8844: 			    $refuri=$env{$key};
 8845:                         }
 8846:                     }
 8847:                 }
 8848:             }
 8849: 
 8850:          if ($refuri) { 
 8851: 	  $refuri=&declutter($refuri);
 8852:           my ($match,$cond)=&is_on_map($refuri);
 8853:             if ($match) {
 8854:               my $refstatecond=$cond;
 8855:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8856:                   =~/\Q$priv\E\&([^\:]*)/) {
 8857:                   my $value = $1;
 8858:                   if ($priv eq 'bre') {
 8859:                       my $deeplinkblock;
 8860:                       unless ($nodeeplinkcheck) {
 8861:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
 8862:                       }
 8863:                       if ($deeplinkblock) {
 8864:                           $thisallowed = 'D';
 8865:                       } elsif ($noblockcheck) {
 8866:                           $thisallowed.=$value;
 8867:                       } else {
 8868:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
 8869:                           if (@blockers > 0) {
 8870:                               $thisallowed = 'B';
 8871:                           } else {
 8872:                               $thisallowed.=$value;
 8873:                           }
 8874:                       }
 8875:                   } else {
 8876:                       $thisallowed.=$value;
 8877:                   }
 8878:                   $uri=$refuri;
 8879:                   $statecond=$refstatecond;
 8880:               }
 8881:           }
 8882:         }
 8883:        }
 8884:    }
 8885: 
 8886: #
 8887: # Gathered now: all privileges that could apply, and condition number
 8888: # 
 8889: #
 8890: # Full or no access?
 8891: #
 8892: 
 8893:     if ($thisallowed=~/F/) {
 8894: 	return 'F';
 8895:     }
 8896: 
 8897:     unless ($thisallowed) {
 8898:         return '';
 8899:     }
 8900: 
 8901: # Restrictions exist, deal with them
 8902: #
 8903: #   C:according to course preferences
 8904: #   R:according to resource settings
 8905: #   L:unless locked
 8906: #   X:according to user session state
 8907: #
 8908: 
 8909: # Possibly locked functionality, check all courses
 8910: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
 8911: # Locks might take effect only after 10 minutes cache expiration for other
 8912: # courses, and 2 minutes for current course, in which user has st or ta role
 8913: # which is neither expired nor a future role (unless current course).
 8914: 
 8915:     my ($needlockcheck,$now,$crsonly);
 8916:     if ($thisallowed=~/L/) {
 8917:         $now = time;
 8918:         if ($priv eq 'bre') {
 8919:             if ($uri ne '') {
 8920:                 if ($orguri =~ m{^/+res/}) {
 8921:                     if ($uri =~ m{^lib/templates/}) {
 8922:                         if ($env{'request.course.id'}) {
 8923:                             $crsonly = 1;
 8924:                             $needlockcheck = 1;
 8925:                         }
 8926:                     } else {
 8927:                         $needlockcheck = 1;
 8928:                     }
 8929:                 } elsif ($env{'request.course.id'}) {
 8930:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
 8931:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
 8932:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
 8933:                         $crsonly = 1;
 8934:                     }
 8935:                     $needlockcheck = 1;
 8936:                 }
 8937:             }
 8938:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
 8939:             $needlockcheck = 1;
 8940:         }
 8941:     }
 8942:     if ($needlockcheck) {
 8943:         foreach my $envkey (keys(%env)) {
 8944:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8945:                my $courseid=$2;
 8946:                my $roleid=$1.'.'.$2;
 8947:                $courseid=~s/^\///;
 8948:                unless ($env{'request.role'} eq $roleid) {
 8949:                    my ($start,$end) = split(/\./,$env{$envkey});
 8950:                    next unless (($now >= $start) && (!$end || $end > $now));
 8951:                }
 8952:                my $expiretime=600;
 8953:                if ($env{'request.role'} eq $roleid) {
 8954: 		  $expiretime=120;
 8955:                }
 8956: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8957:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8958:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8959: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8960:                }
 8961:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8962:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8963: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8964:                        &log($env{'user.domain'},$env{'user.name'},
 8965:                             $env{'user.home'},
 8966:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8967:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8968:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8969: 		       return '';
 8970:                    }
 8971:                }
 8972:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8973:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8974: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
 8975:                        &log($env{'user.domain'},$env{'user.name'},
 8976:                             $env{'user.home'},
 8977:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8978:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8979:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8980: 		       return '';
 8981:                    }
 8982:                }
 8983: 	   }
 8984:        }
 8985:     }
 8986: 
 8987: #
 8988: # Rest of the restrictions depend on selected course
 8989: #
 8990: 
 8991:     unless ($env{'request.course.id'}) {
 8992: 	if ($thisallowed eq 'A') {
 8993: 	    return 'A';
 8994:         } elsif ($thisallowed eq 'B') {
 8995:             return 'B';
 8996: 	} else {
 8997: 	    return '1';
 8998: 	}
 8999:     }
 9000: 
 9001: #
 9002: # Now user is definitely in a course
 9003: #
 9004: 
 9005: 
 9006: # Course preferences
 9007: 
 9008:    if ($thisallowed=~/C/) {
 9009:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9010:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 9011:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 9012: 	   =~/\Q$rolecode\E/) {
 9013: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9014: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9015: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 9016: 			$env{'request.course.id'});
 9017: 	   }
 9018:            return '';
 9019:        }
 9020: 
 9021:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 9022: 	   =~/\Q$unamedom\E/) {
 9023: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 9024: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 9025: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 9026: 			$env{'request.course.id'});
 9027: 	   }
 9028:            return '';
 9029:        }
 9030:    }
 9031: 
 9032: # Resource preferences
 9033: 
 9034:    if ($thisallowed=~/R/) {
 9035:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 9036:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 9037: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 9038: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 9039: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 9040: 	   }
 9041: 	   return '';
 9042:        }
 9043:    }
 9044: 
 9045: # Restricted for deeplinked session?
 9046: 
 9047:     if ($env{'request.deeplink.login'}) {
 9048:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
 9049:             if (!$symb) { $symb=&symbread($uri,1); }
 9050:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
 9051:                 return '';
 9052:             }
 9053:         }
 9054:     }
 9055: 
 9056: # Restricted by state or randomout?
 9057: 
 9058:    if ($thisallowed=~/X/) {
 9059:       if ($env{'acc.randomout'}) {
 9060: 	 if (!$symb) { $symb=&symbread($uri,1); }
 9061:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 9062:             return ''; 
 9063:          }
 9064:       }
 9065:       if (&condval($statecond)) {
 9066: 	 return '2';
 9067:       } else {
 9068:          return '';
 9069:       }
 9070:    }
 9071: 
 9072:     if ($thisallowed eq 'A') {
 9073: 	return 'A';
 9074:     } elsif ($thisallowed eq 'B') {
 9075:         return 'B';
 9076:     } elsif ($thisallowed eq 'D') {
 9077:         return 'D';
 9078:     }
 9079:    return 'F';
 9080: }
 9081: 
 9082: # ------------------------------------------- Check construction space access
 9083: 
 9084: sub constructaccess {
 9085:     my ($url,$setpriv)=@_;
 9086: 
 9087: # We do not allow editing of previous versions of files
 9088:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 9089: 
 9090: # Get username and domain from URL
 9091:     my ($ownername,$ownerdomain,$ownerhome);
 9092: 
 9093:     ($ownerdomain,$ownername) =
 9094:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 9095: 
 9096: # The URL does not really point to any authorspace, forget it
 9097:     unless (($ownername) && ($ownerdomain)) { return ''; }
 9098: 
 9099: # Now we need to see if the user has access to the authorspace of
 9100: # $ownername at $ownerdomain
 9101: 
 9102:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 9103: # Real author for this?
 9104:        $ownerhome = $env{'user.home'};
 9105:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 9106:           return ($ownername,$ownerdomain,$ownerhome);
 9107:        }
 9108:     } elsif (&is_course($ownerdomain,$ownername)) {
 9109: # Course Authoring Space?
 9110:         if ($env{'request.course.id'}) {
 9111:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 9112:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 9113:                 if (&allowed('mdc',$env{'request.course.id'})) {
 9114:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 9115:                     return ($ownername,$ownerdomain,$ownerhome);
 9116:                 }
 9117:             }
 9118:         }
 9119:         return '';
 9120:     } else {
 9121: # Co-author for this?
 9122:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 9123:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 9124:             $ownerhome = &homeserver($ownername,$ownerdomain);
 9125:             return ($ownername,$ownerdomain,$ownerhome);
 9126:         }
 9127:     }
 9128: 
 9129: # We don't have any access right now. If we are not possibly going to do anything about this,
 9130: # we might as well leave
 9131:    unless ($setpriv) { return ''; }
 9132: 
 9133: # Backdoor access?
 9134:     my $allowed=&allowed('eco',$ownerdomain);
 9135: # Nope
 9136:     unless ($allowed) { return ''; }
 9137: # Looks like we may have access, but could be locked by the owner of the construction space
 9138:     if ($allowed eq 'U') {
 9139:         my %blocked=&get('environment',['domcoord.author'],
 9140:                          $ownerdomain,$ownername);
 9141: # Is blocked by owner
 9142:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 9143:     }
 9144:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 9145: # Grant temporary access
 9146:         my $then=$env{'user.login.time'};
 9147:         my $update=$env{'user.update.time'};
 9148:         if (!$update) { $update = $then; }
 9149:         my $refresh=$env{'user.refresh.time'};
 9150:         if (!$refresh) { $refresh = $update; }
 9151:         my $now = time;
 9152:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 9153:                            $now,'ca','constructaccess');
 9154:         $ownerhome = &homeserver($ownername,$ownerdomain);
 9155:         return($ownername,$ownerdomain,$ownerhome);
 9156:     }
 9157: # No business here
 9158:     return '';
 9159: }
 9160: 
 9161: # ----------------------------------------------------------- Content Blocking
 9162: 
 9163: {
 9164: # Caches for faster Course Contents display where content blocking
 9165: # is in operation (i.e., interval param set) for timed quiz.
 9166: #
 9167: # User for whom data are being temporarily cached.
 9168: my $cacheduser='';
 9169: # Course for which data are being temporarily cached.
 9170: my $cachedcid='';
 9171: # Cached blockers for this user (a hash of blocking items). 
 9172: my %cachedblockers=();
 9173: # When the data were last cached.
 9174: my $cachedlast='';
 9175: 
 9176: sub load_all_blockers {
 9177:     my ($uname,$udom)=@_;
 9178:     if (($uname ne '') && ($udom ne '')) { 
 9179:         if (($cacheduser eq $uname.':'.$udom) &&
 9180:             ($cachedcid eq $env{'request.course.id'}) &&
 9181:             (abs($cachedlast-time)<5)) {
 9182:             return;
 9183:         }
 9184:     }
 9185:     $cachedlast=time;
 9186:     $cacheduser=$uname.':'.$udom;
 9187:     $cachedcid=$env{'request.course.id'};
 9188:     %cachedblockers = &get_commblock_resources();
 9189:     return;
 9190: }
 9191: 
 9192: sub get_comm_blocks {
 9193:     my ($cdom,$cnum) = @_;
 9194:     if ($cdom eq '' || $cnum eq '') {
 9195:         return unless ($env{'request.course.id'});
 9196:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9197:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9198:     }
 9199:     my %commblocks;
 9200:     my $hashid=$cdom.'_'.$cnum;
 9201:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 9202:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 9203:         %commblocks = %{$blocksref};
 9204:     } else {
 9205:         %commblocks = &dump('comm_block',$cdom,$cnum);
 9206:         my $cachetime = 600;
 9207:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 9208:     }
 9209:     return %commblocks;
 9210: }
 9211: 
 9212: sub get_commblock_resources {
 9213:     my ($blocks) = @_;
 9214:     my %blockers = ();
 9215:     return %blockers unless ($env{'request.course.id'});
 9216:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9217:     if ($env{'request.course.sec'}) {
 9218:         $courseurl .= '/'.$env{'request.course.sec'};
 9219:     }
 9220:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9221:     my %commblocks;
 9222:     if (ref($blocks) eq 'HASH') {
 9223:         %commblocks = %{$blocks};
 9224:     } else {
 9225:         %commblocks = &get_comm_blocks();
 9226:     }
 9227:     return %blockers unless (keys(%commblocks) > 0); 
 9228:     my $navmap = Apache::lonnavmaps::navmap->new();
 9229:     return %blockers unless (ref($navmap));
 9230:     my $now = time;
 9231:     foreach my $block (keys(%commblocks)) {
 9232:         if ($block =~ /^(\d+)____(\d+)$/) {
 9233:             my ($start,$end) = ($1,$2);
 9234:             if ($start <= $now && $end >= $now) {
 9235:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9236:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9237:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9238:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9239:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 9240:                             }
 9241:                         }
 9242:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9243:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9244:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9245:                             }
 9246:                         }
 9247:                     }
 9248:                 }
 9249:             }
 9250:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 9251:             my $item = $1;
 9252:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 9253:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 9254:                     my (@interval,$mapname);
 9255:                     my $type = 'map';
 9256:                     if ($item eq 'course') {
 9257:                         $type = 'course';
 9258:                         @interval=&EXT("resource.0.interval");
 9259:                     } else {
 9260:                         if ($item =~ /___\d+___/) {
 9261:                             $type = 'resource';
 9262:                             @interval=&EXT("resource.0.interval",$item);
 9263:                         } else {
 9264:                             $mapname = &deversion($item);
 9265:                             if (ref($navmap)) {
 9266:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
 9267:                                 @interval = ($timelimit,'map');
 9268:                             }
 9269:                         }
 9270:                     }
 9271:                     if ($interval[0] =~ /^(\d+)/) {
 9272:                         my $timelimit = $1; 
 9273:                         my $first_access;
 9274:                         if ($type eq 'resource') {
 9275:                             $first_access=&get_first_access($interval[1],$item);
 9276:                         } elsif ($type eq 'map') {
 9277:                             $first_access=&get_first_access($interval[1],undef,$item);
 9278:                         } else {
 9279:                             $first_access=&get_first_access($interval[1]);
 9280:                         }
 9281:                         if ($first_access) {
 9282:                             my $timesup = $first_access+$timelimit;
 9283:                             if ($timesup > $now) {
 9284:                                 my $activeblock;
 9285:                                 if ($type eq 'resource') {
 9286:                                     if (ref($navmap)) {
 9287:                                         my $res = $navmap->getBySymb($item);
 9288:                                         if ($res->answerable()) {
 9289:                                             $activeblock = 1;
 9290:                                         }
 9291:                                     }
 9292:                                 } elsif ($type eq 'map') {
 9293:                                     my $mapsymb = &symbread($mapname,1);
 9294:                                     if (($mapsymb) && (ref($navmap))) {
 9295:                                         my $mapres = $navmap->getBySymb($mapsymb);
 9296:                                         if (ref($mapres)) {
 9297:                                             my $first = $mapres->map_start();
 9298:                                             my $finish = $mapres->map_finish();
 9299:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
 9300:                                             if (ref($it)) {
 9301:                                                 my $res;
 9302:                                                 while ($res = $it->next(undef,1)) {
 9303:                                                     next unless (ref($res));
 9304:                                                     my $symb = $res->symb();
 9305:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
 9306:                                                     @interval=&EXT("resource.0.interval",$symb);
 9307:                                                     if ($interval[1] eq 'map') {
 9308:                                                         if ($res->answerable()) {
 9309:                                                             $activeblock = 1;
 9310:                                                             last;
 9311:                                                         }
 9312:                                                     }
 9313:                                                 }
 9314:                                             }
 9315:                                         }
 9316:                                     }
 9317:                                 }
 9318:                                 if ($activeblock) {
 9319:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 9320:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 9321:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 9322:                                          }
 9323:                                     }
 9324:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 9325:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 9326:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 9327:                                         }
 9328:                                     }
 9329:                                 }
 9330:                             }
 9331:                         }
 9332:                     }
 9333:                 }
 9334:             }
 9335:         }
 9336:     }
 9337:     return %blockers;
 9338: }
 9339: 
 9340: sub has_comm_blocking {
 9341:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
 9342:     my @blockers;
 9343:     return unless ($env{'request.course.id'});
 9344:     return unless ($priv eq 'bre');
 9345:     return if ($env{'request.state'} eq 'construct');
 9346:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
 9347:     if ($env{'request.course.sec'}) {
 9348:         $courseurl .= '/'.$env{'request.course.sec'};
 9349:     }
 9350:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
 9351:     my %blockinfo;
 9352:     if (ref($blocks) eq 'HASH') {
 9353:         %blockinfo = &get_commblock_resources($blocks);
 9354:     } else {
 9355:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
 9356:         %blockinfo = %cachedblockers;
 9357:     }
 9358:     return unless (keys(%blockinfo) > 0);
 9359:     my (%possibles,@symbs);
 9360:     if (!$symb) {
 9361:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
 9362:     }
 9363:     if ($symb) {
 9364:         @symbs = ($symb);
 9365:     } elsif (keys(%possibles)) { 
 9366:         @symbs = keys(%possibles);
 9367:     }
 9368:     my $noblock;
 9369:     foreach my $symb (@symbs) {
 9370:         last if ($noblock);
 9371:         my ($map,$resid,$resurl)=&decode_symb($symb);
 9372:         foreach my $block (keys(%blockinfo)) {
 9373:             if ($block =~ /^firstaccess____(.+)$/) {
 9374:                 my $item = $1;
 9375:                 unless ($blocked) {
 9376:                     if (($item eq $map) || ($item eq $symb)) {
 9377:                         $noblock = 1;
 9378:                         last;
 9379:                     }
 9380:                 }
 9381:             }
 9382:             if (ref($blockinfo{$block}) eq 'HASH') {
 9383:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
 9384:                     if ($blockinfo{$block}{'resources'}{$symb}) {
 9385:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9386:                             push(@blockers,$block);
 9387:                         }
 9388:                     }
 9389:                 }
 9390:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
 9391:                     if ($blockinfo{$block}{'maps'}{$map}) {
 9392:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 9393:                             push(@blockers,$block);
 9394:                         }
 9395:                     }
 9396:                 }
 9397:             }
 9398:         }
 9399:     }
 9400:     unless ($noblock) { 
 9401:         return @blockers;
 9402:     }
 9403:     return;
 9404: }
 9405: }
 9406: 
 9407: sub deeplink_check {
 9408:     my ($priv,$symb,$uri) = @_;
 9409:     return unless ($env{'request.course.id'});
 9410:     return unless ($priv eq 'bre');
 9411:     return if ($env{'request.state'} eq 'construct');
 9412:     return if ($env{'request.role.adv'});
 9413:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9414:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9415:     my (%possibles,@symbs);
 9416:     if (!$symb) {
 9417:         $symb = &symbread($uri,1,1,1,\%possibles);
 9418:     }
 9419:     if ($symb) {
 9420:         @symbs = ($symb);
 9421:     } elsif (keys(%possibles)) {
 9422:         @symbs = keys(%possibles);
 9423:     }
 9424: 
 9425:     my ($deeplink_symb,$allow);
 9426:     if ($env{'request.deeplink.login'}) {
 9427:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
 9428:     }
 9429:     foreach my $symb (@symbs) {
 9430:         last if ($allow);
 9431:         my $deeplink = &EXT("resource.0.deeplink",$symb);
 9432:         if ($deeplink eq '') {
 9433:             $allow = 1;
 9434:         } else {
 9435:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
 9436:             if ($state ne 'only') {
 9437:                 $allow = 1;
 9438:             } else {
 9439:                 my $check_deeplink_entry;
 9440:                 if ($protect ne 'none') {
 9441:                     my ($acctype,$item) = split(/:/,$protect);
 9442:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
 9443:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
 9444:                             $check_deeplink_entry = 1
 9445:                         }
 9446:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
 9447:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
 9448:                             $check_deeplink_entry = 1;
 9449:                         }
 9450:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
 9451:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
 9452:                             $check_deeplink_entry = 1;
 9453:                         }
 9454:                     }
 9455:                 }
 9456:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
 9457:                     if ($scope eq 'res') {
 9458:                         if ($symb eq $deeplink_symb) {
 9459:                             $allow = 1;
 9460:                         }
 9461:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
 9462:                         my ($map_from_symb,$map_from_login);
 9463:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
 9464:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
 9465:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
 9466:                         } else {
 9467:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
 9468:                         }
 9469:                         if (($map_from_symb) && ($map_from_login)) {
 9470:                             if ($map_from_symb eq $map_from_login) {
 9471:                                 $allow = 1;
 9472:                             } elsif ($scope eq 'rec') {
 9473:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
 9474:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
 9475:                                     $allow = 1;
 9476:                                 }
 9477:                             }
 9478:                         }
 9479:                     }
 9480:                 }
 9481:             }
 9482:         }
 9483:     }
 9484:     return if ($allow);
 9485:     return 1;
 9486: }
 9487: 
 9488: # -------------------------------- Deversion and split uri into path an filename   
 9489: 
 9490: #
 9491: #   Removes the version from a URI and
 9492: #   splits it in to its filename and path to the filename.
 9493: #   Seems like File::Basename could have done this more clearly.
 9494: #   Parameters:
 9495: #      $uri   - input URI
 9496: #   Returns:
 9497: #     Two element list consisting of 
 9498: #     $pathname  - the URI up to and excluding the trailing /
 9499: #     $filename  - The part of the URI following the last /
 9500: #  NOTE:
 9501: #    Another realization of this is simply:
 9502: #    use File::Basename;
 9503: #    ...
 9504: #    $uri = shift;
 9505: #    $filename = basename($uri);
 9506: #    $path     = dirname($uri);
 9507: #    return ($filename, $path);
 9508: #
 9509: #     The implementation below is probably faster however.
 9510: #
 9511: sub split_uri_for_cond {
 9512:     my $uri=&deversion(&declutter(shift));
 9513:     my @uriparts=split(/\//,$uri);
 9514:     my $filename=pop(@uriparts);
 9515:     my $pathname=join('/',@uriparts);
 9516:     return ($pathname,$filename);
 9517: }
 9518: # --------------------------------------------------- Is a resource on the map?
 9519: 
 9520: sub is_on_map {
 9521:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 9522:     #Trying to find the conditional for the file
 9523:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 9524: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 9525:     if ($match) {
 9526: 	return (1,$1);
 9527:     } else {
 9528: 	return (0,0);
 9529:     }
 9530: }
 9531: 
 9532: # --------------------------------------------------------- Get symb from alias
 9533: 
 9534: sub get_symb_from_alias {
 9535:     my $symb=shift;
 9536:     my ($map,$resid,$url)=&decode_symb($symb);
 9537: # Already is a symb
 9538:     if ($url) { return $symb; }
 9539: # Must be an alias
 9540:     my $aliassymb='';
 9541:     my %bighash;
 9542:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9543:                             &GDBM_READER(),0640)) {
 9544:         my $rid=$bighash{'mapalias_'.$symb};
 9545: 	if ($rid) {
 9546: 	    my ($mapid,$resid)=split(/\./,$rid);
 9547: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 9548: 				    $resid,$bighash{'src_'.$rid});
 9549: 	}
 9550:         untie %bighash;
 9551:     }
 9552:     return $aliassymb;
 9553: }
 9554: 
 9555: # ----------------------------------------------------------------- Define Role
 9556: 
 9557: sub definerole {
 9558:   if (allowed('mcr','/')) {
 9559:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 9560:     foreach my $role (split(':',$sysrole)) {
 9561: 	my ($crole,$cqual)=split(/\&/,$role);
 9562:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 9563:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 9564: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9565:                return "refused:s:$crole&$cqual"; 
 9566:             }
 9567:         }
 9568:     }
 9569:     foreach my $role (split(':',$domrole)) {
 9570: 	my ($crole,$cqual)=split(/\&/,$role);
 9571:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 9572:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 9573: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 9574:                return "refused:d:$crole&$cqual"; 
 9575:             }
 9576:         }
 9577:     }
 9578:     foreach my $role (split(':',$courole)) {
 9579: 	my ($crole,$cqual)=split(/\&/,$role);
 9580:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 9581:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 9582: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 9583:                return "refused:c:$crole&$cqual"; 
 9584:             }
 9585:         }
 9586:     }
 9587:     my $uhome;
 9588:     if (($uname ne '') && ($udom ne '')) {
 9589:         $uhome = &homeserver($uname,$udom);
 9590:         return $uhome if ($uhome eq 'no_host');
 9591:     } else {
 9592:         $uname = $env{'user.name'};
 9593:         $udom = $env{'user.domain'};
 9594:         $uhome = $env{'user.home'};
 9595:     }
 9596:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9597:                 "$udom:$uname:rolesdef_$rolename=".
 9598:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 9599:     return reply($command,$uhome);
 9600:   } else {
 9601:     return 'refused';
 9602:   }
 9603: }
 9604: 
 9605: # ---------------- Make a metadata query against the network of library servers
 9606: 
 9607: sub metadata_query {
 9608:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 9609:     my %rhash;
 9610:     my %libserv = &all_library();
 9611:     my @server_list = (defined($server_array) ? @$server_array
 9612:                                               : keys(%libserv) );
 9613:     for my $server (@server_list) {
 9614:         my $domains = ''; 
 9615:         if (ref($domains_hash) eq 'HASH') {
 9616:             $domains = $domains_hash->{$server}; 
 9617:         }
 9618: 	unless ($custom or $customshow) {
 9619: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 9620: 	    $rhash{$server}=$reply;
 9621: 	}
 9622: 	else {
 9623: 	    my $reply=&reply("querysend:".&escape($query).':'.
 9624: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 9625: 			     $server);
 9626: 	    $rhash{$server}=$reply;
 9627: 	}
 9628:     }
 9629:     return \%rhash;
 9630: }
 9631: 
 9632: # ----------------------------------------- Send log queries and wait for reply
 9633: 
 9634: sub log_query {
 9635:     my ($uname,$udom,$query,%filters)=@_;
 9636:     my $uhome=&homeserver($uname,$udom);
 9637:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 9638:     my $uhost=&hostname($uhome);
 9639:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 9640:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 9641:                        $uhome);
 9642:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 9643:     return get_query_reply($queryid);
 9644: }
 9645: 
 9646: # -------------------------- Update MySQL table for portfolio file
 9647: 
 9648: sub update_portfolio_table {
 9649:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 9650:     if ($group ne '') {
 9651:         $file_name =~s /^\Q$group\E//;
 9652:     }
 9653:     my $homeserver = &homeserver($uname,$udom);
 9654:     my $queryid=
 9655:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 9656:                ':'.&escape($file_name).':'.$action,$homeserver);
 9657:     my $reply = &get_query_reply($queryid);
 9658:     return $reply;
 9659: }
 9660: 
 9661: # -------------------------- Update MySQL allusers table
 9662: 
 9663: sub update_allusers_table {
 9664:     my ($uname,$udom,$names) = @_;
 9665:     my $homeserver = &homeserver($uname,$udom);
 9666:     my $queryid=
 9667:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 9668:                'lastname='.&escape($names->{'lastname'}).'%%'.
 9669:                'firstname='.&escape($names->{'firstname'}).'%%'.
 9670:                'middlename='.&escape($names->{'middlename'}).'%%'.
 9671:                'generation='.&escape($names->{'generation'}).'%%'.
 9672:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 9673:                'id='.&escape($names->{'id'}),$homeserver);
 9674:     return;
 9675: }
 9676: 
 9677: # ------- Request retrieval of institutional classlists for course(s)
 9678: 
 9679: sub fetch_enrollment_query {
 9680:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 9681:     my ($homeserver,$sleep,$loopmax);
 9682:     my $maxtries = 1;
 9683:     if ($context eq 'automated') {
 9684:         $homeserver = $perlvar{'lonHostID'};
 9685:         $sleep = 2;
 9686:         $loopmax = 100;
 9687:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 9688:     } else {
 9689:         $homeserver = &homeserver($cnum,$dom);
 9690:     }
 9691:     my $host=&hostname($homeserver);
 9692:     my $cmd = '';
 9693:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9694:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9695:     }
 9696:     $cmd =~ s/%%$//;
 9697:     $cmd = &escape($cmd);
 9698:     my $query = 'fetchenrollment';
 9699:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 9700:     unless ($queryid=~/^\Q$host\E\_/) { 
 9701:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 9702:         return 'error: '.$queryid;
 9703:     }
 9704:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9705:     my $tries = 1;
 9706:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9707:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 9708:         $tries ++;
 9709:     }
 9710:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9711:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9712:     } else {
 9713:         my @responses = split(/:/,$reply);
 9714:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 9715:             foreach my $line (@responses) {
 9716:                 my ($key,$value) = split(/=/,$line,2);
 9717:                 $$replyref{$key} = $value;
 9718:             }
 9719:         } else {
 9720:             my $pathname = LONCAPA::tempdir();
 9721:             foreach my $line (@responses) {
 9722:                 my ($key,$value) = split(/=/,$line);
 9723:                 $$replyref{$key} = $value;
 9724:                 if ($value > 0) {
 9725:                     foreach my $item (@{$$affiliatesref{$key}}) {
 9726:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 9727:                         my $destname = $pathname.'/'.$filename;
 9728:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 9729:                         if ($xml_classlist =~ /^error/) {
 9730:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 9731:                         } else {
 9732:                             if ( open(FILE,">",$destname) ) {
 9733:                                 print FILE &unescape($xml_classlist);
 9734:                                 close(FILE);
 9735:                             } else {
 9736:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 9737:                             }
 9738:                         }
 9739:                     }
 9740:                 }
 9741:             }
 9742:         }
 9743:         return 'ok';
 9744:     }
 9745:     return 'error';
 9746: }
 9747: 
 9748: sub get_query_reply {
 9749:     my ($queryid,$sleep,$loopmax) = @_;
 9750:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 9751:         $sleep = 0.2;
 9752:     }
 9753:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 9754:         $loopmax = 100;
 9755:     }
 9756:     my $replyfile=LONCAPA::tempdir().$queryid;
 9757:     my $reply='';
 9758:     for (1..$loopmax) {
 9759: 	sleep($sleep);
 9760:         if (-e $replyfile.'.end') {
 9761: 	    if (open(my $fh,"<",$replyfile)) {
 9762: 		$reply = join('',<$fh>);
 9763: 		close($fh);
 9764: 	   } else { return 'error: reply_file_error'; }
 9765:            return &unescape($reply);
 9766: 	}
 9767:     }
 9768:     return 'timeout:'.$queryid;
 9769: }
 9770: 
 9771: sub courselog_query {
 9772: #
 9773: # possible filters:
 9774: # url: url or symb
 9775: # username
 9776: # domain
 9777: # action: view, submit, grade
 9778: # start: timestamp
 9779: # end: timestamp
 9780: #
 9781:     my (%filters)=@_;
 9782:     unless ($env{'request.course.id'}) { return 'no_course'; }
 9783:     if ($filters{'url'}) {
 9784: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 9785:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 9786:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 9787:     }
 9788:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 9789:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 9790:     return &log_query($cname,$cdom,'courselog',%filters);
 9791: }
 9792: 
 9793: sub userlog_query {
 9794: #
 9795: # possible filters:
 9796: # action: log check role
 9797: # start: timestamp
 9798: # end: timestamp
 9799: #
 9800:     my ($uname,$udom,%filters)=@_;
 9801:     return &log_query($uname,$udom,'userlog',%filters);
 9802: }
 9803: 
 9804: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 9805: 
 9806: sub auto_run {
 9807:     my ($cnum,$cdom) = @_;
 9808:     my $response = 0;
 9809:     my $settings;
 9810:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 9811:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 9812:         $settings = $domconfig{'autoenroll'};
 9813:         if ($settings->{'run'} eq '1') {
 9814:             $response = 1;
 9815:         }
 9816:     } else {
 9817:         my $homeserver;
 9818:         if (&is_course($cdom,$cnum)) {
 9819:             $homeserver = &homeserver($cnum,$cdom);
 9820:         } else {
 9821:             $homeserver = &domain($cdom,'primary');
 9822:         }
 9823:         if ($homeserver ne 'no_host') {
 9824:             $response = &reply('autorun:'.$cdom,$homeserver);
 9825:         }
 9826:     }
 9827:     return $response;
 9828: }
 9829: 
 9830: sub auto_get_sections {
 9831:     my ($cnum,$cdom,$inst_coursecode) = @_;
 9832:     my $homeserver;
 9833:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 9834:         $homeserver = &homeserver($cnum,$cdom);
 9835:     }
 9836:     if (!defined($homeserver)) { 
 9837:         if ($cdom =~ /^$match_domain$/) {
 9838:             $homeserver = &domain($cdom,'primary');
 9839:         }
 9840:     }
 9841:     my @secs;
 9842:     if (defined($homeserver)) {
 9843:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9844:         unless ($response eq 'refused') {
 9845:             @secs = split(/:/,$response);
 9846:         }
 9847:     }
 9848:     return @secs;
 9849: }
 9850: 
 9851: sub auto_new_course {
 9852:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9853:     my $homeserver = &homeserver($cnum,$cdom);
 9854:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9855:     return $response;
 9856: }
 9857: 
 9858: sub auto_validate_courseID {
 9859:     my ($cnum,$cdom,$inst_course_id) = @_;
 9860:     my $homeserver = &homeserver($cnum,$cdom);
 9861:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9862:     return $response;
 9863: }
 9864: 
 9865: sub auto_validate_instcode {
 9866:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9867:     my ($homeserver,$response);
 9868:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9869:         $homeserver = &homeserver($cnum,$cdom);
 9870:     }
 9871:     if (!defined($homeserver)) {
 9872:         if ($cdom =~ /^$match_domain$/) {
 9873:             $homeserver = &domain($cdom,'primary');
 9874:         }
 9875:     }
 9876:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9877:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9878:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9879:     return ($outcome,$description,$defaultcredits);
 9880: }
 9881: 
 9882: sub auto_validate_inst_crosslist {
 9883:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
 9884:     my ($homeserver,$response);
 9885:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9886:         $homeserver = &homeserver($cnum,$cdom);
 9887:     }
 9888:     if (!defined($homeserver)) {
 9889:         if ($cdom =~ /^$match_domain$/) {
 9890:             $homeserver = &domain($cdom,'primary');
 9891:         }
 9892:     }
 9893:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
 9894:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
 9895:                          &escape($instcode).':'.&escape($inst_xlist).':'.
 9896:                          &escape($coowner),$homeserver);
 9897:     }
 9898:     return $response;
 9899: }
 9900: 
 9901: sub auto_create_password {
 9902:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9903:     my ($homeserver,$response);
 9904:     my $create_passwd = 0;
 9905:     my $authchk = '';
 9906:     if ($udom =~ /^$match_domain$/) {
 9907:         $homeserver = &domain($udom,'primary');
 9908:     }
 9909:     if ($homeserver eq '') {
 9910:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9911:             $homeserver = &homeserver($cnum,$cdom);
 9912:         }
 9913:     }
 9914:     if ($homeserver eq '') {
 9915:         $authchk = 'nodomain';
 9916:     } else {
 9917:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9918:         if ($response eq 'refused') {
 9919:             $authchk = 'refused';
 9920:         } else {
 9921:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9922:         }
 9923:     }
 9924:     return ($authparam,$create_passwd,$authchk);
 9925: }
 9926: 
 9927: sub auto_photo_permission {
 9928:     my ($cnum,$cdom,$students) = @_;
 9929:     my $homeserver = &homeserver($cnum,$cdom);
 9930:     my ($outcome,$perm_reqd,$conditions) = 
 9931: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9932:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9933: 	return (undef,undef);
 9934:     }
 9935:     return ($outcome,$perm_reqd,$conditions);
 9936: }
 9937: 
 9938: sub auto_checkphotos {
 9939:     my ($uname,$udom,$pid) = @_;
 9940:     my $homeserver = &homeserver($uname,$udom);
 9941:     my ($result,$resulttype);
 9942:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9943: 				   &escape($uname).':'.&escape($pid),
 9944: 				   $homeserver));
 9945:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9946: 	return (undef,undef);
 9947:     }
 9948:     if ($outcome) {
 9949:         ($result,$resulttype) = split(/:/,$outcome);
 9950:     } 
 9951:     return ($result,$resulttype);
 9952: }
 9953: 
 9954: sub auto_photochoice {
 9955:     my ($cnum,$cdom) = @_;
 9956:     my $homeserver = &homeserver($cnum,$cdom);
 9957:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9958: 						       &escape($cdom),
 9959: 						       $homeserver)));
 9960:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9961: 	return (undef,undef);
 9962:     }
 9963:     return ($update,$comment);
 9964: }
 9965: 
 9966: sub auto_photoupdate {
 9967:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9968:     my $homeserver = &homeserver($cnum,$dom);
 9969:     my $host=&hostname($homeserver);
 9970:     my $cmd = '';
 9971:     my $maxtries = 1;
 9972:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9973:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9974:     }
 9975:     $cmd =~ s/%%$//;
 9976:     $cmd = &escape($cmd);
 9977:     my $query = 'institutionalphotos';
 9978:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9979:     unless ($queryid=~/^\Q$host\E\_/) {
 9980:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9981:         return 'error: '.$queryid;
 9982:     }
 9983:     my $reply = &get_query_reply($queryid);
 9984:     my $tries = 1;
 9985:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9986:         $reply = &get_query_reply($queryid);
 9987:         $tries ++;
 9988:     }
 9989:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9990:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9991:     } else {
 9992:         my @responses = split(/:/,$reply);
 9993:         my $outcome = shift(@responses); 
 9994:         foreach my $item (@responses) {
 9995:             my ($key,$value) = split(/=/,$item);
 9996:             $$photo{$key} = $value;
 9997:         }
 9998:         return $outcome;
 9999:     }
10000:     return 'error';
10001: }
10002: 
10003: sub auto_instcode_format {
10004:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
10005: 	$cat_order) = @_;
10006:     my $courses = '';
10007:     my @homeservers;
10008:     if ($caller eq 'global') {
10009: 	my %servers = &get_servers($codedom,'library');
10010: 	foreach my $tryserver (keys(%servers)) {
10011: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10012: 		push(@homeservers,$tryserver);
10013: 	    }
10014:         }
10015:     } elsif ($caller eq 'requests') {
10016:         if ($codedom =~ /^$match_domain$/) {
10017:             my $chome = &domain($codedom,'primary');
10018:             unless ($chome eq 'no_host') {
10019:                 push(@homeservers,$chome);
10020:             }
10021:         }
10022:     } else {
10023:         push(@homeservers,&homeserver($caller,$codedom));
10024:     }
10025:     foreach my $code (keys(%{$instcodes})) {
10026:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
10027:     }
10028:     chop($courses);
10029:     my $ok_response = 0;
10030:     my $response;
10031:     while (@homeservers > 0 && $ok_response == 0) {
10032:         my $server = shift(@homeservers); 
10033:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
10034:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
10035:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
10036: 		split(/:/,$response);
10037:             %{$codes} = (%{$codes},&str2hash($codes_str));
10038:             push(@{$codetitles},&str2array($codetitles_str));
10039:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
10040:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
10041:             $ok_response = 1;
10042:         }
10043:     }
10044:     if ($ok_response) {
10045:         return 'ok';
10046:     } else {
10047:         return $response;
10048:     }
10049: }
10050: 
10051: sub auto_instcode_defaults {
10052:     my ($domain,$returnhash,$code_order) = @_;
10053:     my @homeservers;
10054: 
10055:     my %servers = &get_servers($domain,'library');
10056:     foreach my $tryserver (keys(%servers)) {
10057: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10058: 	    push(@homeservers,$tryserver);
10059: 	}
10060:     }
10061: 
10062:     my $response;
10063:     foreach my $server (@homeservers) {
10064:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
10065:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10066: 	
10067: 	foreach my $pair (split(/\&/,$response)) {
10068: 	    my ($name,$value)=split(/\=/,$pair);
10069: 	    if ($name eq 'code_order') {
10070: 		@{$code_order} = split(/\&/,&unescape($value));
10071: 	    } else {
10072: 		$returnhash->{&unescape($name)}=&unescape($value);
10073: 	    }
10074: 	}
10075: 	return 'ok';
10076:     }
10077: 
10078:     return $response;
10079: }
10080: 
10081: sub auto_possible_instcodes {
10082:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
10083:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
10084:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10085:         return;
10086:     }
10087:     my (@homeservers,$uhome);
10088:     if (defined(&domain($domain,'primary'))) {
10089:         $uhome=&domain($domain,'primary');
10090:         push(@homeservers,&domain($domain,'primary'));
10091:     } else {
10092:         my %servers = &get_servers($domain,'library');
10093:         foreach my $tryserver (keys(%servers)) {
10094:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10095:                 push(@homeservers,$tryserver);
10096:             }
10097:         }
10098:     }
10099:     my $response;
10100:     foreach my $server (@homeservers) {
10101:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
10102:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
10103:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
10104:             split(':',$response);
10105:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
10106:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
10107:         foreach my $item (split('&',$cat_title)) {   
10108:             my ($name,$value)=split('=',$item);
10109:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
10110:         }
10111:         foreach my $item (split('&',$cat_order)) {
10112:             my ($name,$value)=split('=',$item);
10113:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
10114:         }
10115:         return 'ok';
10116:     }
10117:     return $response;
10118: }
10119: 
10120: sub auto_courserequest_checks {
10121:     my ($dom) = @_;
10122:     my ($homeserver,%validations);
10123:     if ($dom =~ /^$match_domain$/) {
10124:         $homeserver = &domain($dom,'primary');
10125:     }
10126:     unless ($homeserver eq 'no_host') {
10127:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
10128:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10129:             my @items = split(/&/,$response);
10130:             foreach my $item (@items) {
10131:                 my ($key,$value) = split('=',$item);
10132:                 $validations{&unescape($key)} = &thaw_unescape($value);
10133:             }
10134:         }
10135:     }
10136:     return %validations; 
10137: }
10138: 
10139: sub auto_courserequest_validation {
10140:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
10141:     my ($homeserver,$response);
10142:     if ($dom =~ /^$match_domain$/) {
10143:         $homeserver = &domain($dom,'primary');
10144:     }
10145:     unless ($homeserver eq 'no_host') {
10146:         my $customdata;
10147:         if (ref($custominfo) eq 'HASH') {
10148:             $customdata = &freeze_escape($custominfo);
10149:         }
10150:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
10151:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
10152:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
10153:                                     $customdata,$homeserver));
10154:     }
10155:     return $response;
10156: }
10157: 
10158: sub auto_validate_class_sec {
10159:     my ($cdom,$cnum,$owners,$inst_class) = @_;
10160:     my $homeserver = &homeserver($cnum,$cdom);
10161:     my $ownerlist;
10162:     if (ref($owners) eq 'ARRAY') {
10163:         $ownerlist = join(',',@{$owners});
10164:     } else {
10165:         $ownerlist = $owners;
10166:     }
10167:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
10168:                         &escape($ownerlist).':'.$cdom,$homeserver);
10169:     return $response;
10170: }
10171: 
10172: sub auto_instsec_reformat {
10173:     my ($cdom,$action,$instsecref) = @_;
10174:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
10175:     my @homeservers;
10176:     if (defined(&domain($cdom,'primary'))) {
10177:         push(@homeservers,&domain($cdom,'primary'));
10178:     } else {
10179:         my %servers = &get_servers($cdom,'library');
10180:         foreach my $tryserver (keys(%servers)) {
10181:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
10182:                 push(@homeservers,$tryserver);
10183:             }
10184:         }
10185:     }
10186:     my $response;
10187:     my %reformatted = %{$instsecref};
10188:     foreach my $server (@homeservers) {
10189:         if (ref($instsecref) eq 'HASH') {
10190:             my $info = &freeze_escape($instsecref);
10191:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
10192:                                 $action.':'.$info,$server);
10193:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
10194:             my @items = split(/&/,$response);
10195:             foreach my $item (@items) {
10196:                 my ($key,$value) = split(/=/,$item);
10197:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
10198:             }
10199:         }
10200:     }
10201:     return %reformatted;
10202: }
10203: 
10204: sub auto_validate_instclasses {
10205:     my ($cdom,$cnum,$owners,$classesref) = @_;
10206:     my ($homeserver,%validations);
10207:     $homeserver = &homeserver($cnum,$cdom);
10208:     unless ($homeserver eq 'no_host') {
10209:         my $ownerlist;
10210:         if (ref($owners) eq 'ARRAY') {
10211:             $ownerlist = join(',',@{$owners});
10212:         } else {
10213:             $ownerlist = $owners;
10214:         }
10215:         if (ref($classesref) eq 'HASH') {
10216:             my $classes = &freeze_escape($classesref);
10217:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
10218:                                 ':'.$cdom.':'.$classes,$homeserver);
10219:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10220:                 my @items = split(/&/,$response);
10221:                 foreach my $item (@items) {
10222:                     my ($key,$value) = split('=',$item);
10223:                     $validations{&unescape($key)} = &thaw_unescape($value);
10224:                 }
10225:             }
10226:         }
10227:     }
10228:     return %validations;
10229: }
10230: 
10231: sub auto_crsreq_update {
10232:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
10233:         $code,$accessstart,$accessend,$inbound) = @_;
10234:     my ($homeserver,%crsreqresponse);
10235:     if ($cdom =~ /^$match_domain$/) {
10236:         $homeserver = &domain($cdom,'primary');
10237:     }
10238:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10239:         my $info;
10240:         if (ref($inbound) eq 'HASH') {
10241:             $info = &freeze_escape($inbound);
10242:         }
10243:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
10244:                             ':'.&escape($action).':'.&escape($ownername).':'.
10245:                             &escape($ownerdomain).':'.&escape($fullname).':'.
10246:                             &escape($title).':'.&escape($code).':'.
10247:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
10248:                             $homeserver);
10249:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
10250:             my @items = split(/&/,$response);
10251:             foreach my $item (@items) {
10252:                 my ($key,$value) = split('=',$item);
10253:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
10254:             }
10255:         }
10256:     }
10257:     return \%crsreqresponse;
10258: }
10259: 
10260: sub auto_export_grades {
10261:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
10262:     my ($homeserver,%exportresponse);
10263:     if ($cdom =~ /^$match_domain$/) {
10264:         $homeserver = &domain($cdom,'primary');
10265:     }
10266:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
10267:         my $info;
10268:         if (ref($inforef) eq 'HASH') {
10269:             $info = &freeze_escape($inforef);
10270:         }
10271:         if (ref($gradesref) eq 'HASH') {
10272:             my $grades = &freeze_escape($gradesref);
10273:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
10274:                                 $info.':'.$grades,$homeserver);
10275:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
10276:                 my @items = split(/&/,$response);
10277:                 foreach my $item (@items) {
10278:                     my ($key,$value) = split('=',$item);
10279:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
10280:                 }
10281:             }
10282:         }
10283:     }
10284:     return \%exportresponse;
10285: }
10286: 
10287: sub check_instcode_cloning {
10288:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
10289:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
10290:         return;
10291:     }
10292:     my $canclone;
10293:     if (@{$code_order} > 0) {
10294:         my $instcoderegexp ='^';
10295:         my @clonecodes = split(/\&/,$cloner);
10296:         foreach my $item (@{$code_order}) {
10297:             if (grep(/^\Q$item\E=/,@clonecodes)) {
10298:                 foreach my $pair (@clonecodes) {
10299:                     my ($key,$val) = split(/\=/,$pair,2);
10300:                     $val = &unescape($val);
10301:                     if ($key eq $item) {
10302:                         $instcoderegexp .= '('.$val.')';
10303:                         last;
10304:                     }
10305:                 }
10306:             } else {
10307:                 $instcoderegexp .= $codedefaults->{$item};
10308:             }
10309:         }
10310:         $instcoderegexp .= '$';
10311:         my (@from,@to);
10312:         eval {
10313:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
10314:                (@to) = ($clonetocode =~ /$instcoderegexp/);
10315:         };
10316:         if ((@from > 0) && (@to > 0)) {
10317:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10318:             if (!@diffs) {
10319:                 $canclone = 1;
10320:             }
10321:         }
10322:     }
10323:     return $canclone;
10324: }
10325: 
10326: sub default_instcode_cloning {
10327:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
10328:     my (%codedefaults,@code_order,$canclone);
10329:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
10330:         %codedefaults = %{$codedefaultsref};
10331:         @code_order = @{$codeorderref};
10332:     } elsif ($clonedom) {
10333:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
10334:     }
10335:     if (($domdefclone) && (@code_order)) {
10336:         my @clonecodes = split(/\+/,$domdefclone);
10337:         my $instcoderegexp ='^';
10338:         foreach my $item (@code_order) {
10339:             if (grep(/^\Q$item\E$/,@clonecodes)) {
10340:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
10341:             } else {
10342:                 $instcoderegexp .= $codedefaults{$item};
10343:             }
10344:         }
10345:         $instcoderegexp .= '$';
10346:         my (@from,@to);
10347:         eval {
10348:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
10349:             (@to) = ($clonetocode =~ /$instcoderegexp/);
10350:         };
10351:         if ((@from > 0) && (@to > 0)) {
10352:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
10353:             if (!@diffs) {
10354:                 $canclone = 1;
10355:             }
10356:         }
10357:     }
10358:     return $canclone;
10359: }
10360: 
10361: # ------------------------------------------------------- Course Group routines
10362: 
10363: sub get_coursegroups {
10364:     my ($cdom,$cnum,$group,$namespace) = @_;
10365:     return(&dump($namespace,$cdom,$cnum,$group));
10366: }
10367: 
10368: sub modify_coursegroup {
10369:     my ($cdom,$cnum,$groupsettings) = @_;
10370:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
10371: }
10372: 
10373: sub toggle_coursegroup_status {
10374:     my ($cdom,$cnum,$group,$action) = @_;
10375:     my ($from_namespace,$to_namespace);
10376:     if ($action eq 'delete') {
10377:         $from_namespace = 'coursegroups';
10378:         $to_namespace = 'deleted_groups';
10379:     } else {
10380:         $from_namespace = 'deleted_groups';
10381:         $to_namespace = 'coursegroups';
10382:     }
10383:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
10384:     if (my $tmp = &error(%curr_group)) {
10385:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
10386:         return ('read error',$tmp);
10387:     } else {
10388:         my %savedsettings = %curr_group; 
10389:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
10390:         my $deloutcome;
10391:         if ($result eq 'ok') {
10392:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
10393:         } else {
10394:             return ('write error',$result);
10395:         }
10396:         if ($deloutcome eq 'ok') {
10397:             return 'ok';
10398:         } else {
10399:             return ('delete error',$deloutcome);
10400:         }
10401:     }
10402: }
10403: 
10404: sub modify_group_roles {
10405:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context,
10406:         $othdomby,$requester) = @_;
10407:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
10408:     my $role = 'gr/'.&escape($userprivs);
10409:     my ($uname,$udom) = split(/:/,$user);
10410:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context,
10411:                              $othdomby,$requester);
10412:     if ($result eq 'ok') {
10413:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
10414:     }
10415:     return $result;
10416: }
10417: 
10418: sub modify_coursegroup_membership {
10419:     my ($cdom,$cnum,$membership) = @_;
10420:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
10421:     return $result;
10422: }
10423: 
10424: sub get_active_groups {
10425:     my ($udom,$uname,$cdom,$cnum) = @_;
10426:     my $now = time;
10427:     my %groups = ();
10428:     foreach my $key (keys(%env)) {
10429:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
10430:             my ($start,$end) = split(/\./,$env{$key});
10431:             if (($end!=0) && ($end<$now)) { next; }
10432:             if (($start!=0) && ($start>$now)) { next; }
10433:             if ($1 eq $cdom && $2 eq $cnum) {
10434:                 $groups{$3} = $env{$key} ;
10435:             }
10436:         }
10437:     }
10438:     return %groups;
10439: }
10440: 
10441: sub get_group_membership {
10442:     my ($cdom,$cnum,$group) = @_;
10443:     return(&dump('groupmembership',$cdom,$cnum,$group));
10444: }
10445: 
10446: sub get_users_groups {
10447:     my ($udom,$uname,$courseid) = @_;
10448:     my @usersgroups;
10449:     my $cachetime=1800;
10450: 
10451:     my $hashid="$udom:$uname:$courseid";
10452:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
10453:     if (defined($cached)) {
10454:         @usersgroups = split(/:/,$grouplist);
10455:     } else {  
10456:         $grouplist = '';
10457:         my $courseurl = &courseid_to_courseurl($courseid);
10458:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
10459:         my $access_end = $env{'course.'.$courseid.
10460:                               '.default_enrollment_end_date'};
10461:         my $now = time;
10462:         foreach my $key (keys(%roleshash)) {
10463:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
10464:                 my $group = $1;
10465:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
10466:                     my $start = $2;
10467:                     my $end = $1;
10468:                     if ($start == -1) { next; } # deleted from group
10469:                     if (($start!=0) && ($start>$now)) { next; }
10470:                     if (($end!=0) && ($end<$now)) {
10471:                         if ($access_end && $access_end < $now) {
10472:                             if ($access_end - $end < 86400) {
10473:                                 push(@usersgroups,$group);
10474:                             }
10475:                         }
10476:                         next;
10477:                     }
10478:                     push(@usersgroups,$group);
10479:                 }
10480:             }
10481:         }
10482:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
10483:         $grouplist = join(':',@usersgroups);
10484:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
10485:     }
10486:     return @usersgroups;
10487: }
10488: 
10489: sub devalidate_getgroups_cache {
10490:     my ($udom,$uname,$cdom,$cnum)=@_;
10491:     my $courseid = $cdom.'_'.$cnum;
10492: 
10493:     my $hashid="$udom:$uname:$courseid";
10494:     &devalidate_cache_new('getgroups',$hashid);
10495: }
10496: 
10497: # ------------------------------------------------------------------ Plain Text
10498: 
10499: sub plaintext {
10500:     my ($short,$type,$cid,$forcedefault) = @_;
10501:     if ($short =~ m{^cr/}) {
10502: 	return (split('/',$short))[-1];
10503:     }
10504:     if (!defined($cid)) {
10505:         $cid = $env{'request.course.id'};
10506:     }
10507:     my %rolenames = (
10508:                       Course    => 'std',
10509:                       Community => 'alt1',
10510:                       Placement => 'std',
10511:                     );
10512:     if ($cid ne '') {
10513:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
10514:             unless ($forcedefault) {
10515:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
10516:                 &Apache::lonlocal::mt_escape(\$roletext);
10517:                 return &Apache::lonlocal::mt($roletext);
10518:             }
10519:         }
10520:     }
10521:     if ((defined($type)) && (defined($rolenames{$type})) &&
10522:         (defined($rolenames{$type})) && 
10523:         (defined($prp{$short}{$rolenames{$type}}))) {
10524:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
10525:     } elsif ($cid ne '') {
10526:         my $crstype = $env{'course.'.$cid.'.type'};
10527:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
10528:             (defined($prp{$short}{$rolenames{$crstype}}))) {
10529:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
10530:         }
10531:     }
10532:     return &Apache::lonlocal::mt($prp{$short}{'std'});
10533: }
10534: 
10535: # ----------------------------------------------------------------- Assign Role
10536: 
10537: sub assignrole {
10538:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
10539:         $context,$othdomby,$requester,$reqsec,$reqrole)=@_;
10540:     my $mrole;
10541:     if ($role =~ /^cr\//) {
10542:         my $cwosec=$url;
10543:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10544:         if ((!&allowed('ccr',$cwosec)) && (!&allowed('ccr',$udom))) {
10545:             my $refused = 1;
10546:             if ($context eq 'requestcourses') {
10547:                 if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
10548:                     if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
10549:                         if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
10550:                             my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10551:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10552:                             if ($crsenv{'internal.courseowner'} eq
10553:                                 $env{'user.name'}.':'.$env{'user.domain'}) {
10554:                                 $refused = '';
10555:                             }
10556:                         }
10557:                     }
10558:                 }
10559:             } elsif (($context eq 'course') && ($othdomby eq 'othdombyuser')) {
10560:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10561:                 my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10562:                 my $key = "$uname:$udom:$role:$sec";
10563:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10564:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10565:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10566:                         $refused = '';
10567:                     }
10568:                 }
10569:             }
10570:             if ($refused) {
10571:                 &logthis('Refused custom assignrole: '.
10572:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
10573:                          ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
10574:                 return 'refused';
10575:             }
10576:         }
10577:         $mrole='cr';
10578:     } elsif ($role =~ /^gr\//) {
10579:         my $cwogrp=$url;
10580:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
10581:         if (!&allowed('mdg',$cwogrp)) {
10582:             my $refused = 1;
10583:             if (($refused) && ($othdomby eq 'othdombyuser') && ($requester ne '') && ($reqrole ne '')) {
10584:                 my ($cdom,$cnum) = ($cwogrp =~ m{^/?($match_domain)/($match_courseid)$});
10585:                 my $key = "$uname:$udom:$reqrole:$reqsec";
10586:                 my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10587:                 if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10588:                     if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10589:                         $refused = '';
10590:                     }
10591:                 }
10592:             }
10593:             if ($refused) {
10594:                 &logthis('Refused group assignrole: '.
10595:                          $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
10596:                          $env{'user.name'}.' at '.$env{'user.domain'});
10597:                 return 'refused';
10598:             }
10599:         }
10600:         $mrole='gr';
10601:     } else {
10602:         my $cwosec=$url;
10603:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
10604:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
10605:             my $refused;
10606:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
10607:                 if (!(&allowed('c'.$role,$url))) {
10608:                     $refused = 1;
10609:                 }
10610:             } else {
10611:                 $refused = 1;
10612:             }
10613:             if ($refused) {
10614:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
10615:                 if (!$selfenroll && ($othdomby ne 'othdombyuser') &&
10616:                    (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
10617:                     my %crsenv;
10618:                     if ($role eq 'cc' || $role eq 'co') {
10619:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10620:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
10621:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
10622:                                 if ($crsenv{'internal.courseowner'} eq 
10623:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10624:                                     $refused = '';
10625:                                 }
10626:                             }
10627:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
10628:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
10629:                                 if ($crsenv{'internal.courseowner'} eq 
10630:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
10631:                                     $refused = '';
10632:                                 }
10633:                             }
10634:                         }
10635:                     }
10636:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
10637:                     if ($role eq 'st') {
10638:                         $refused = '';
10639:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
10640:                         $refused = '';
10641:                     }
10642:                 } elsif ($othdomby eq 'othdombyuser') {
10643:                     my ($key,%queuedrolereq);
10644:                     if ($context eq 'course') {
10645:                         my ($sec) = ($url =~ m{^/\Q$cwosec\E/(.*)$});
10646:                         $key = "$uname:$udom:$role:$sec";
10647:                         %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$cdom,$cnum);
10648:                         if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10649:                             if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10650:                                 if ((($role eq 'cc') && ($cnum !~ /^$match_community$/)) || 
10651:                                     (($role eq 'co') && ($cnum =~ /^$match_community$/))) {
10652:                                     my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10653:                                     if ($crsenv{'internal.courseowner'} eq $requester) {
10654:                                         $refused = '';
10655:                                     }
10656:                                 } elsif ($role =~ /^(?:in|ta|ep|st)$/) {
10657:                                     $refused = '';
10658:                                 }
10659:                             }
10660:                         }
10661:                     } elsif (($context eq 'author') && ($role =~ /^ca|aa$/)) {
10662:                         my $key = "$uname:$udom:$role"; 
10663:                         my ($audom,$auname) = ($url =~ m{^/($match_domain)/($match_username)$});
10664:                         if (($audom ne '') && ($auname ne '')) {
10665:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$audom,$auname);
10666:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10667:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10668:                                     $refused = '';
10669:                                 }
10670:                             }
10671:                         }
10672:                     } elsif (($context eq 'domain') && ($role ne 'dc') && ($role ne 'su')) {
10673:                         my $key = "$uname:$udom:$role";
10674:                         my ($roledom) = ($url =~ m{^/($match_domain)/\Q$role\E$});
10675:                         if ($roledom ne '') {
10676:                             my $confname = $roledom.'-domainconfig';
10677:                             my %queuedrolereq = &Apache::lonnet::get('nohist_othdomqueued',[$key],$roledom,$confname);
10678:                             if ((exists($queuedrolereq{$key})) && (ref($queuedrolereq{$key}) eq 'HASH')) {
10679:                                 if (($queuedrolereq{$key}{'adj'} eq 'user') && ($queuedrolereq{$key}{'requester'} eq $requester)) {
10680:                                     $refused = '';
10681:                                 }
10682:                             }
10683:                         }
10684:                     }
10685:                 } elsif ($context eq 'requestcourses') {
10686:                     my @possroles = ('st','ta','ep','in','cc','co');
10687:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
10688:                         my $wrongcc;
10689:                         if ($cnum =~ /^$match_community$/) {
10690:                             $wrongcc = 1 if ($role eq 'cc');
10691:                         } else {
10692:                             $wrongcc = 1 if ($role eq 'co');
10693:                         }
10694:                         unless ($wrongcc) {
10695:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
10696:                             if ($crsenv{'internal.courseowner'} eq 
10697:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
10698:                                 $refused = '';
10699:                             }
10700:                         }
10701:                     }
10702:                 } elsif ($context eq 'requestauthor') {
10703:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
10704:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
10705:                         if ($env{'environment.requestauthor'} eq 'automatic') {
10706:                             $refused = '';
10707:                         } else {
10708:                             my %domdefaults = &get_domain_defaults($udom);
10709:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
10710:                                 my $checkbystatus;
10711:                                 if ($env{'user.adv'}) { 
10712:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
10713:                                     if ($disposition eq 'automatic') {
10714:                                         $refused = '';
10715:                                     } elsif ($disposition eq '') {
10716:                                         $checkbystatus = 1;
10717:                                     } 
10718:                                 } else {
10719:                                     $checkbystatus = 1;
10720:                                 }
10721:                                 if ($checkbystatus) {
10722:                                     if ($env{'environment.inststatus'}) {
10723:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
10724:                                         foreach my $type (@inststatuses) {
10725:                                             if (($type ne '') &&
10726:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
10727:                                                 $refused = '';
10728:                                             }
10729:                                         }
10730:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
10731:                                         $refused = '';
10732:                                     }
10733:                                 }
10734:                             }
10735:                         }
10736:                     }
10737:                 }
10738:                 if ($refused) {
10739:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
10740:                              ' '.$role.' '.$end.' '.$start.' by '.
10741: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
10742:                     return 'refused';
10743:                 }
10744:             }
10745:         } elsif ($role eq 'au') {
10746:             if ($url ne '/'.$udom.'/') {
10747:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
10748:                          ' to assign author role for '.$uname.':'.$udom.
10749:                          ' in domain: '.$url.' refused (wrong domain).');
10750:                 return 'refused';
10751:             }
10752:         }
10753:         $mrole=$role;
10754:     }
10755:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
10756:                 "$udom:$uname:$url".'_'."$mrole=$role";
10757:     if ($end) { $command.='_'.$end; }
10758:     if ($start) {
10759: 	if ($end) { 
10760:            $command.='_'.$start; 
10761:         } else {
10762:            $command.='_0_'.$start;
10763:         }
10764:     }
10765:     my $origstart = $start;
10766:     my $origend = $end;
10767:     my $delflag;
10768: # actually delete
10769:     if ($deleteflag) {
10770: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
10771: # modify command to delete the role
10772:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
10773:                 "$udom:$uname:$url".'_'."$mrole";
10774: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
10775: # set start and finish to negative values for userrolelog
10776:            $start=-1;
10777:            $end=-1;
10778:            $delflag = 1;
10779:         }
10780:     }
10781: # send command
10782:     my $answer=&reply($command,&homeserver($uname,$udom));
10783: # log new user role if status is ok
10784:     if ($answer eq 'ok') {
10785: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
10786:         if (($role eq 'cc') || ($role eq 'in') ||
10787:             ($role eq 'ep') || ($role eq 'ad') ||
10788:             ($role eq 'ta') || ($role eq 'st') ||
10789:             ($role=~/^cr/) || ($role eq 'gr') ||
10790:             ($role eq 'co')) {
10791: # for course roles, perform group memberships changes triggered by role change.
10792:             unless ($role =~ /^gr/) {
10793:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
10794:                                                  $origstart,$selfenroll,$context);
10795:             }
10796:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10797:                            $selfenroll,$context,$othdomby,$requester);
10798:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
10799:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
10800:                  ($role eq 'da')) {
10801:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10802:                            $context,$othdomby,$requester);
10803:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
10804:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
10805:                              $context,$othdomby,$requester); 
10806:         }
10807:         if ($role eq 'cc') {
10808:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
10809:         }
10810:     }
10811:     return $answer;
10812: }
10813: 
10814: sub autoupdate_coowners {
10815:     my ($url,$end,$start,$uname,$udom) = @_;
10816:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
10817:     if (($cdom ne '') && ($cnum ne '')) {
10818:         my $now = time;
10819:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
10820:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
10821:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
10822:             my $instcode = $coursehash{'internal.coursecode'};
10823:             my $xlists = $coursehash{'internal.crosslistings'};
10824:             if ($instcode ne '') {
10825:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
10826:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
10827:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
10828:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
10829:                         unless ($result eq 'valid') {
10830:                             if ($xlists ne '') {
10831:                                 foreach my $xlist (split(',',$xlists)) {
10832:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
10833:                                     $result =
10834:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
10835:                                                                       $inst_crosslist,$uname.':'.$udom);
10836:                                     last if ($result eq 'valid');
10837:                                 }
10838:                             }
10839:                         }
10840:                         if ($result eq 'valid') {
10841:                             if ($coursehash{'internal.co-owners'}) {
10842:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10843:                                     push(@newcoowners,$coowner);
10844:                                 }
10845:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
10846:                                     push(@newcoowners,$uname.':'.$udom);
10847:                                 }
10848:                                 @newcoowners = sort(@newcoowners);
10849:                             } else {
10850:                                 push(@newcoowners,$uname.':'.$udom);
10851:                             }
10852:                         } elsif ($coursehash{'internal.co-owners'}) {
10853:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
10854:                                 unless ($coowner eq $uname.':'.$udom) {
10855:                                     push(@newcoowners,$coowner);
10856:                                 }
10857:                             }
10858:                             unless (@newcoowners > 0) {
10859:                                 $delcoowners = 1;
10860:                                 $coowners = '';
10861:                             }
10862:                         }
10863:                         if (@newcoowners || $delcoowners) {
10864:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
10865:                                             $delcoowners,@newcoowners);
10866:                         }
10867:                     }
10868:                 }
10869:             }
10870:         }
10871:     }
10872: }
10873: 
10874: sub store_coowners {
10875:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
10876:     my $cid = $cdom.'_'.$cnum;
10877:     my ($coowners,$delresult,$putresult);
10878:     if (@newcoowners) {
10879:         $coowners = join(',',@newcoowners);
10880:         my %coownershash = (
10881:                             'internal.co-owners' => $coowners,
10882:                            );
10883:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
10884:         if ($putresult eq 'ok') {
10885:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
10886:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
10887:             }
10888:         }
10889:     }
10890:     if ($delcoowners) {
10891:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
10892:         if ($delresult eq 'ok') {
10893:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
10894:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
10895:             }
10896:         }
10897:     }
10898:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
10899:         my %crsinfo =
10900:             &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
10901:         if (ref($crsinfo{$cid}) eq 'HASH') {
10902:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
10903:             my $cidput = &courseidput($cdom,\%crsinfo,$chome,'notime');
10904:         }
10905:     }
10906: }
10907: 
10908: # -------------------------------------------------- Modify user authentication
10909: # Overrides without validation
10910: 
10911: sub modifyuserauth {
10912:     my ($udom,$uname,$umode,$upass)=@_;
10913:     my $uhome=&homeserver($uname,$udom);
10914:     my $allowed;
10915:     if (&allowed('mau',$udom)) {
10916:         $allowed = 1;
10917:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
10918:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
10919:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
10920:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10921:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10922:         if (($cdom ne '') && ($cnum ne '')) {
10923:             my $is_owner = &is_course_owner($cdom,$cnum);
10924:             if ($is_owner) {
10925:                 $allowed = 1;
10926:             }
10927:         }
10928:     }
10929:     unless ($allowed) { return 'refused'; }
10930:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
10931:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10932:              ' in domain '.$env{'request.role.domain'});  
10933:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
10934: 		     &escape($upass),$uhome);
10935:     my $ip = &get_requestor_ip();
10936:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
10937:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
10938:          '(Remote '.$ip.'): '.$reply);
10939:     &log($udom,,$uname,$uhome,
10940:         'Authentication changed by '.$env{'user.domain'}.', '.
10941:                                      $env{'user.name'}.', '.$umode.
10942:          '(Remote '.$ip.'): '.$reply);
10943:     unless ($reply eq 'ok') {
10944:         &logthis('Authentication mode error: '.$reply);
10945: 	return 'error: '.$reply;
10946:     }   
10947:     return 'ok';
10948: }
10949: 
10950: # --------------------------------------------------------------- Modify a user
10951: 
10952: sub modifyuser {
10953:     my ($udom,    $uname, $uid,
10954:         $umode,   $upass, $first,
10955:         $middle,  $last,  $gene,
10956:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
10957:     $udom= &LONCAPA::clean_domain($udom);
10958:     $uname=&LONCAPA::clean_username($uname);
10959:     my $showcandelete = 'none';
10960:     if (ref($candelete) eq 'ARRAY') {
10961:         if (@{$candelete} > 0) {
10962:             $showcandelete = join(', ',@{$candelete});
10963:         }
10964:     }
10965:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10966:              $umode.', '.$first.', '.$middle.', '.
10967: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10968:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10969:                                      ' desiredhome not specified'). 
10970:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10971:              ' in domain '.$env{'request.role.domain'});
10972:     my $uhome=&homeserver($uname,$udom,'true');
10973:     my $newuser;
10974:     if ($uhome eq 'no_host') {
10975:         $newuser = 1;
10976:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
10977:                 ($umode eq 'lti')) {
10978:             return 'error: more information needed to create new user';
10979:         }
10980:     }
10981: # ----------------------------------------------------------------- Create User
10982:     if (($uhome eq 'no_host') && 
10983: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
10984:         my $unhome='';
10985:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10986:             $unhome = $desiredhome;
10987: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10988: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10989:         } else { # load balancing routine for determining $unhome
10990:             my $loadm=10000000;
10991: 	    my %servers = &get_servers($udom,'library');
10992: 	    foreach my $tryserver (keys(%servers)) {
10993: 		my $answer=reply('load',$tryserver);
10994: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10995: 		    $loadm=$answer;
10996: 		    $unhome=$tryserver;
10997: 		}
10998: 	    }
10999:         }
11000:         if (($unhome eq '') || ($unhome eq 'no_host')) {
11001: 	    return 'error: unable to find a home server for '.$uname.
11002:                    ' in domain '.$udom;
11003:         }
11004:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
11005:                          &escape($upass),$unhome);
11006: 	unless ($reply eq 'ok') {
11007:             return 'error: '.$reply;
11008:         }   
11009:         $uhome=&homeserver($uname,$udom,'true');
11010:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
11011: 	    return 'error: unable verify users home machine.';
11012:         }
11013:     }   # End of creation of new user
11014: # ---------------------------------------------------------------------- Add ID
11015:     if ($uid) {
11016:        $uid=~tr/A-Z/a-z/;
11017:        my %uidhash=&idrget($udom,$uname);
11018:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
11019:          && (!$forceid)) {
11020: 	  unless ($uid eq $uidhash{$uname}) {
11021: 	      return 'error: user id "'.$uid.'" does not match '.
11022:                   'current user id "'.$uidhash{$uname}.'".';
11023:           }
11024:        } else {
11025: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
11026:        }
11027:     }
11028: # -------------------------------------------------------------- Add names, etc
11029:     my @tmp=&get('environment',
11030: 		   ['firstname','middlename','lastname','generation','id',
11031:                     'permanentemail','inststatus'],
11032: 		   $udom,$uname);
11033:     my (%names,%oldnames);
11034:     if ($tmp[0] =~ m/^error:.*/) { 
11035:         %names=(); 
11036:     } else {
11037:         %names = @tmp;
11038:         %oldnames = %names;
11039:     }
11040: #
11041: # If name, email and/or uid are blank (e.g., because an uploaded file
11042: # of users did not contain them), do not overwrite existing values
11043: # unless field is in $candelete array ref.  
11044: #
11045: 
11046:     my @fields = ('firstname','middlename','lastname','generation',
11047:                   'permanentemail','id');
11048:     my %newvalues;
11049:     if (ref($candelete) eq 'ARRAY') {
11050:         foreach my $field (@fields) {
11051:             if (grep(/^\Q$field\E$/,@{$candelete})) {
11052:                 if ($field eq 'firstname') {
11053:                     $names{$field} = $first;
11054:                 } elsif ($field eq 'middlename') {
11055:                     $names{$field} = $middle;
11056:                 } elsif ($field eq 'lastname') {
11057:                     $names{$field} = $last;
11058:                 } elsif ($field eq 'generation') { 
11059:                     $names{$field} = $gene;
11060:                 } elsif ($field eq 'permanentemail') {
11061:                     $names{$field} = $email;
11062:                 } elsif ($field eq 'id') {
11063:                     $names{$field}  = $uid;
11064:                 }
11065:             }
11066:         }
11067:     }
11068:     if ($first)  { $names{'firstname'}  = $first; }
11069:     if (defined($middle)) { $names{'middlename'} = $middle; }
11070:     if ($last)   { $names{'lastname'}   = $last; }
11071:     if (defined($gene))   { $names{'generation'} = $gene; }
11072:     if ($email) {
11073:        $email=~s/[^\w\@\.\-\,]//gs;
11074:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
11075:     }
11076:     if ($uid) { $names{'id'}  = $uid; }
11077:     if (defined($inststatus)) {
11078:         $names{'inststatus'} = '';
11079:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
11080:         if (ref($usertypes) eq 'HASH') {
11081:             my @okstatuses; 
11082:             foreach my $item (split(/:/,$inststatus)) {
11083:                 if (defined($usertypes->{$item})) {
11084:                     push(@okstatuses,$item);  
11085:                 }
11086:             }
11087:             if (@okstatuses) {
11088:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
11089:             }
11090:         }
11091:     }
11092:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
11093:                  $umode.', '.$first.', '.$middle.', '.
11094:                  $last.', '.$gene.', '.$email.', '.$inststatus;
11095:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
11096:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
11097:     } else {
11098:         $logmsg .= ' during self creation';
11099:     }
11100:     my $changed;
11101:     if ($newuser) {
11102:         $changed = 1;
11103:     } else {
11104:         foreach my $field (@fields) {
11105:             if ($names{$field} ne $oldnames{$field}) {
11106:                 $changed = 1;
11107:                 last;
11108:             }
11109:         }
11110:     }
11111:     unless ($changed) {
11112:         $logmsg = 'No changes in user information needed for: '.$logmsg;
11113:         &logthis($logmsg);
11114:         return 'ok';
11115:     }
11116:     my $reply = &put('environment', \%names, $udom,$uname);
11117:     if ($reply ne 'ok') { 
11118:         return 'error: '.$reply;
11119:     }
11120:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
11121:         &devalidate_cache_new('emailscache',$uname.':'.$udom);
11122:     }
11123:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
11124:     &devalidate_cache_new('namescache',$uname.':'.$udom);
11125:     $logmsg = 'Success modifying user '.$logmsg;
11126:     &logthis($logmsg);
11127:     return 'ok';
11128: }
11129: 
11130: # -------------------------------------------------------------- Modify student
11131: 
11132: sub modifystudent {
11133:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
11134:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
11135:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
11136:     if (!$cid) {
11137: 	unless ($cid=$env{'request.course.id'}) {
11138: 	    return 'not_in_class';
11139: 	}
11140:     }
11141: # --------------------------------------------------------------- Make the user
11142:     my $reply=&modifyuser
11143: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
11144:          $desiredhome,$email,$inststatus);
11145:     unless ($reply eq 'ok') { return $reply; }
11146:     # This will cause &modify_student_enrollment to get the uid from the
11147:     # student's environment
11148:     $uid = undef if (!$forceid);
11149:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
11150:                                         $gene,$usec,$end,$start,$type,$locktype,
11151:                                         $cid,$selfenroll,$context,$credits,$instsec);
11152:     return $reply;
11153: }
11154: 
11155: sub modify_student_enrollment {
11156:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
11157:         $locktype,$cid,$selfenroll,$context,$credits,$instsec,$othdomby,$requester) = @_;
11158:     my ($cdom,$cnum,$chome);
11159:     if (!$cid) {
11160: 	unless ($cid=$env{'request.course.id'}) {
11161: 	    return 'not_in_class';
11162: 	}
11163: 	$cdom=$env{'course.'.$cid.'.domain'};
11164: 	$cnum=$env{'course.'.$cid.'.num'};
11165:     } else {
11166: 	($cdom,$cnum)=split(/_/,$cid);
11167:     }
11168:     $chome=$env{'course.'.$cid.'.home'};
11169:     if (!$chome) {
11170: 	$chome=&homeserver($cnum,$cdom);
11171:     }
11172:     if (!$chome) { return 'unknown_course'; }
11173:     # Make sure the user exists
11174:     my $uhome=&homeserver($uname,$udom);
11175:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11176: 	return 'error: no such user';
11177:     }
11178:     # Get student data if we were not given enough information
11179:     if (!defined($first)  || $first  eq '' || 
11180:         !defined($last)   || $last   eq '' || 
11181:         !defined($uid)    || $uid    eq '' || 
11182:         !defined($middle) || $middle eq '' || 
11183:         !defined($gene)   || $gene   eq '') {
11184:         # They did not supply us with enough data to enroll the student, so
11185:         # we need to pick up more information.
11186:         my %tmp = &get('environment',
11187:                        ['firstname','middlename','lastname', 'generation','id']
11188:                        ,$udom,$uname);
11189: 
11190:         #foreach my $key (keys(%tmp)) {
11191:         #    &logthis("key $key = ".$tmp{$key});
11192:         #}
11193:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
11194:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
11195:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
11196:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
11197:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
11198:     }
11199:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
11200:     my $user = "$uname:$udom";
11201:     my %old_entry = &get('classlist',[$user],$cdom,$cnum);
11202:     my $reply=cput('classlist',
11203: 		   {$user => 
11204: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
11205: 		   $cdom,$cnum);
11206:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
11207:         &devalidate_getsection_cache($udom,$uname,$cid);
11208:     } else { 
11209: 	return 'error: '.$reply;
11210:     }
11211:     # Add student role to user
11212:     my $uurl='/'.$cid;
11213:     $uurl=~s/\_/\//g;
11214:     if ($usec) {
11215: 	$uurl.='/'.$usec;
11216:     }
11217:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
11218:                              $selfenroll,$context,$othdomby,$requester);
11219:     if ($result ne 'ok') {
11220:         if ($old_entry{$user} ne '') {
11221:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
11222:         } else {
11223:             $reply = &del('classlist',[$user],$cdom,$cnum);
11224:         }
11225:     }
11226:     return $result; 
11227: }
11228: 
11229: sub format_name {
11230:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
11231:     my $name;
11232:     if ($first ne 'lastname') {
11233: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
11234:     } else {
11235: 	if ($lastname=~/\S/) {
11236: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
11237: 	    $name=~s/\s+,/,/;
11238: 	} else {
11239: 	    $name.= $firstname.' '.$middlename.' '.$generation;
11240: 	}
11241:     }
11242:     $name=~s/^\s+//;
11243:     $name=~s/\s+$//;
11244:     $name=~s/\s+/ /g;
11245:     return $name;
11246: }
11247: 
11248: # ------------------------------------------------- Write to course preferences
11249: 
11250: sub writecoursepref {
11251:     my ($courseid,%prefs)=@_;
11252:     $courseid=~s/^\///;
11253:     $courseid=~s/\_/\//g;
11254:     my ($cdomain,$cnum)=split(/\//,$courseid);
11255:     my $chome=homeserver($cnum,$cdomain);
11256:     if (($chome eq '') || ($chome eq 'no_host')) { 
11257: 	return 'error: no such course';
11258:     }
11259:     my $cstring='';
11260:     foreach my $pref (keys(%prefs)) {
11261: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
11262:     }
11263:     $cstring=~s/\&$//;
11264:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
11265: }
11266: 
11267: # ---------------------------------------------------------- Make/modify course
11268: 
11269: sub createcourse {
11270:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
11271:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
11272:     $url=&declutter($url);
11273:     my $cid='';
11274:     if ($context eq 'requestcourses') {
11275:         my $can_create = 0;
11276:         my ($ownername,$ownerdom) = split(':',$course_owner);
11277:         if ($udom eq $ownerdom) {
11278:             my $reload;
11279:             if (($callercontext eq 'auto') &&
11280:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
11281:                 $reload = 'reload';
11282:             }
11283:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
11284:                                   $context)) {
11285:                 $can_create = 1;
11286:             }
11287:         } else {
11288:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
11289:                                            $category);
11290:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
11291:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
11292:                 if (@curr > 0) {
11293:                     my @options = qw(approval validate autolimit);
11294:                     my $optregex = join('|',@options);
11295:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
11296:                         $can_create = 1;
11297:                     }
11298:                 }
11299:             }
11300:         }
11301:         if ($can_create) {
11302:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
11303:                 unless (&allowed('ccc',$udom)) {
11304:                     return 'refused'; 
11305:                 }
11306:             }
11307:         } else {
11308:             return 'refused';
11309:         }
11310:     } elsif (!&allowed('ccc',$udom)) {
11311:         return 'refused';
11312:     }
11313: # --------------------------------------------------------------- Get Unique ID
11314:     my $uname;
11315:     if ($cnum =~ /^$match_courseid$/) {
11316:         my $chome=&homeserver($cnum,$udom,'true');
11317:         if (($chome eq '') || ($chome eq 'no_host')) {
11318:             $uname = $cnum;
11319:         } else {
11320:             $uname = &generate_coursenum($udom,$crstype);
11321:         }
11322:     } else {
11323:         $uname = &generate_coursenum($udom,$crstype);
11324:     }
11325:     return $uname if ($uname =~ /^error/);
11326: # -------------------------------------------------- Check supplied server name
11327:     if (!defined($course_server)) {
11328:         if (defined(&domain($udom,'primary'))) {
11329:             $course_server = &domain($udom,'primary');
11330:         } else {
11331:             $course_server = $env{'user.home'}; 
11332:         }
11333:     }
11334:     my %host_servers =
11335:         &get_servers($udom,'library');
11336:     unless ($host_servers{$course_server}) {
11337:         return 'error: invalid home server for course: '.$course_server;
11338:     }
11339: # ------------------------------------------------------------- Make the course
11340:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
11341:                       $course_server);
11342:     unless ($reply eq 'ok') { return 'error: '.$reply; }
11343:     my $uhome=&homeserver($uname,$udom,'true');
11344:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
11345: 	return 'error: no such course';
11346:     }
11347: # ----------------------------------------------------------------- Course made
11348: # log existence
11349:     my $now = time;
11350:     my $newcourse = {
11351:                     $udom.'_'.$uname => {
11352:                                      description => $description,
11353:                                      inst_code   => $inst_code,
11354:                                      owner       => $course_owner,
11355:                                      type        => $crstype,
11356:                                      creator     => $env{'user.name'}.':'.
11357:                                                     $env{'user.domain'},
11358:                                      created     => $now,
11359:                                      context     => $context,
11360:                                                 },
11361:                     };
11362:     &courseidput($udom,$newcourse,$uhome,'notime');
11363: # set toplevel url
11364:     my $topurl=$url;
11365:     unless ($nonstandard) {
11366: # ------------------------------------------ For standard courses, make top url
11367:         my $mapurl=&clutter($url);
11368:         if ($mapurl eq '/res/') { $mapurl=''; }
11369:         $env{'form.initmap'}=(<<ENDINITMAP);
11370: <map>
11371: <resource id="1" type="start"></resource>
11372: <resource id="2" src="$mapurl"></resource>
11373: <resource id="3" type="finish"></resource>
11374: <link index="1" from="1" to="2"></link>
11375: <link index="2" from="2" to="3"></link>
11376: </map>
11377: ENDINITMAP
11378:         $topurl=&declutter(
11379:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
11380:                           );
11381:     }
11382: # ----------------------------------------------------------- Write preferences
11383:     &writecoursepref($udom.'_'.$uname,
11384:                      ('description'              => $description,
11385:                       'url'                      => $topurl,
11386:                       'internal.creator'         => $env{'user.name'}.':'.
11387:                                                     $env{'user.domain'},
11388:                       'internal.created'         => $now,
11389:                       'internal.creationcontext' => $context)
11390:                     );
11391:     return '/'.$udom.'/'.$uname;
11392: }
11393: 
11394: # ------------------------------------------------------------------- Create ID
11395: sub generate_coursenum {
11396:     my ($udom,$crstype) = @_;
11397:     my $domdesc = &domain($udom);
11398:     return 'error: invalid domain' if ($domdesc eq '');
11399:     my $first;
11400:     if ($crstype eq 'Community') {
11401:         $first = '0';
11402:     } else {
11403:         $first = int(1+rand(9)); 
11404:     } 
11405:     my $uname=$first.
11406:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11407:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
11408:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11409: # ----------------------------------------------- Make sure that does not exist
11410:     my $uhome=&homeserver($uname,$udom,'true');
11411:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
11412:         if ($crstype eq 'Community') {
11413:             $first = '0';
11414:         } else {
11415:             $first = int(1+rand(9));
11416:         }
11417:         $uname=$first.
11418:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
11419:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
11420:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
11421:         $uhome=&homeserver($uname,$udom,'true');
11422:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
11423:             return 'error: unable to generate unique course-ID';
11424:         }
11425:     }
11426:     return $uname;
11427: }
11428: 
11429: sub is_course {
11430:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
11431:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
11432: 
11433:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
11434:     my $uhome=&homeserver($cnum,$cdom);
11435:     my $iscourse;
11436:     if (grep { $_ eq $uhome } current_machine_ids()) {
11437:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
11438:     } else {
11439:         my $hashid = $cdom.':'.$cnum;
11440:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
11441:         unless (defined($cached)) {
11442:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
11443:                                         $cnum,undef,undef,'.');
11444:             $iscourse = 0;
11445:             if (exists($courses{$cdom.'_'.$cnum})) {
11446:                 $iscourse = 1;
11447:             }
11448:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
11449:         }
11450:     }
11451:     return unless ($iscourse);
11452:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
11453: }
11454: 
11455: sub store_userdata {
11456:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
11457:     my $result;
11458:     if ($datakey ne '') {
11459:         if (ref($storehash) eq 'HASH') {
11460:             if ($udom eq '' || $uname eq '') {
11461:                 $udom = $env{'user.domain'};
11462:                 $uname = $env{'user.name'};
11463:             }
11464:             my $uhome=&homeserver($uname,$udom);
11465:             if (($uhome eq '') || ($uhome eq 'no_host')) {
11466:                 $result = 'error: no_host';
11467:             } else {
11468:                 $storehash->{'ip'} = &get_requestor_ip();
11469:                 $storehash->{'host'} = $perlvar{'lonHostID'};
11470: 
11471:                 my $namevalue='';
11472:                 foreach my $key (keys(%{$storehash})) {
11473:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
11474:                 }
11475:                 $namevalue=~s/\&$//;
11476:                 unless ($namespace eq 'courserequests') {
11477:                     $datakey = &escape($datakey);
11478:                 }
11479:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
11480:                                   $namevalue,$uhome);
11481:             }
11482:         } else {
11483:             $result = 'error: data to store was not a hash reference'; 
11484:         }
11485:     } else {
11486:         $result= 'error: invalid requestkey'; 
11487:     }
11488:     return $result;
11489: }
11490: 
11491: # ---------------------------------------------------------- Assign Custom Role
11492: 
11493: sub assigncustomrole {
11494:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,
11495:         $selfenroll,$context,$othdomby,$requester)=@_;
11496:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
11497:                        $end,$start,$deleteflag,$selfenroll,$context,$othdomby,
11498:                        $requester);
11499: }
11500: 
11501: # ----------------------------------------------------------------- Revoke Role
11502: 
11503: sub revokerole {
11504:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
11505:     my $now=time;
11506:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
11507: }
11508: 
11509: # ---------------------------------------------------------- Revoke Custom Role
11510: 
11511: sub revokecustomrole {
11512:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
11513:     my $now=time;
11514:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
11515:            $deleteflag,$selfenroll,$context);
11516: }
11517: 
11518: # ------------------------------------------------------------ Disk usage
11519: sub diskusage {
11520:     my ($udom,$uname,$directorypath,$getpropath)=@_;
11521:     $directorypath =~ s/\/$//;
11522:     my $listing=&reply('du2:'.&escape($directorypath).':'
11523:                        .&escape($getpropath).':'.&escape($uname).':'
11524:                        .&escape($udom),homeserver($uname,$udom));
11525:     if ($listing eq 'unknown_cmd') {
11526:         if ($getpropath) {
11527:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
11528:         }
11529:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
11530:     }
11531:     return $listing;
11532: }
11533: 
11534: sub is_locked {
11535:     my ($file_name, $domain, $user, $which) = @_;
11536:     my @check;
11537:     my $is_locked;
11538:     push (@check,$file_name);
11539:     my %locked = &get('file_permissions',\@check,
11540: 		      $env{'user.domain'},$env{'user.name'});
11541:     my ($tmp)=keys(%locked);
11542:     if ($tmp=~/^error:/) { undef(%locked); }
11543:     
11544:     if (ref($locked{$file_name}) eq 'ARRAY') {
11545:         $is_locked = 'false';
11546:         foreach my $entry (@{$locked{$file_name}}) {
11547:            if (ref($entry) eq 'ARRAY') {
11548:                $is_locked = 'true';
11549:                if (ref($which) eq 'ARRAY') {
11550:                    push(@{$which},$entry);
11551:                } else {
11552:                    last;
11553:                }
11554:            }
11555:        }
11556:     } else {
11557:         $is_locked = 'false';
11558:     }
11559:     return $is_locked;
11560: }
11561: 
11562: sub declutter_portfile {
11563:     my ($file) = @_;
11564:     $file =~ s{^(/portfolio/|portfolio/)}{/};
11565:     return $file;
11566: }
11567: 
11568: # ------------------------------------------------------------- Mark as Read Only
11569: 
11570: sub mark_as_readonly {
11571:     my ($domain,$user,$files,$what) = @_;
11572:     my %current_permissions = &dump('file_permissions',$domain,$user);
11573:     my ($tmp)=keys(%current_permissions);
11574:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11575:     foreach my $file (@{$files}) {
11576: 	$file = &declutter_portfile($file);
11577:         push(@{$current_permissions{$file}},$what);
11578:     }
11579:     &put('file_permissions',\%current_permissions,$domain,$user);
11580:     return;
11581: }
11582: 
11583: # ------------------------------------------------------------Save Selected Files
11584: 
11585: sub save_selected_files {
11586:     my ($user, $path, @files) = @_;
11587:     my $filename = $user."savedfiles";
11588:     my @other_files = &files_not_in_path($user, $path);
11589:     open (OUT,'>',LONCAPA::tempdir().$filename);
11590:     foreach my $file (@files) {
11591:         print (OUT $env{'form.currentpath'}.$file."\n");
11592:     }
11593:     foreach my $file (@other_files) {
11594:         print (OUT $file."\n");
11595:     }
11596:     close (OUT);
11597:     return 'ok';
11598: }
11599: 
11600: sub clear_selected_files {
11601:     my ($user) = @_;
11602:     my $filename = $user."savedfiles";
11603:     open (OUT,'>',LONCAPA::tempdir().$filename);
11604:     print (OUT undef);
11605:     close (OUT);
11606:     return ("ok");    
11607: }
11608: 
11609: sub files_in_path {
11610:     my ($user, $path) = @_;
11611:     my $filename = $user."savedfiles";
11612:     my %return_files;
11613:     open (IN,'<',LONCAPA::tempdir().$filename);
11614:     while (my $line_in = <IN>) {
11615:         chomp ($line_in);
11616:         my @paths_and_file = split (m!/!, $line_in);
11617:         my $file_part = pop (@paths_and_file);
11618:         my $path_part = join ('/', @paths_and_file);
11619:         $path_part.='/';
11620:         my $path_and_file = $path_part.$file_part;
11621:         if ($path_part eq $path) {
11622:             $return_files{$file_part}= 'selected';
11623:         }
11624:     }
11625:     close (IN);
11626:     return (\%return_files);
11627: }
11628: 
11629: # called in portfolio select mode, to show files selected NOT in current directory
11630: sub files_not_in_path {
11631:     my ($user, $path) = @_;
11632:     my $filename = $user."savedfiles";
11633:     my @return_files;
11634:     my $path_part;
11635:     open(IN, '<',LONCAPA::tempdir().$filename);
11636:     while (my $line = <IN>) {
11637:         #ok, I know it's clunky, but I want it to work
11638:         my @paths_and_file = split(m|/|, $line);
11639:         my $file_part = pop(@paths_and_file);
11640:         chomp($file_part);
11641:         my $path_part = join('/', @paths_and_file);
11642:         $path_part .= '/';
11643:         my $path_and_file = $path_part.$file_part;
11644:         if ($path_part ne $path) {
11645:             push(@return_files, ($path_and_file));
11646:         }
11647:     }
11648:     close(OUT);
11649:     return (@return_files);
11650: }
11651: 
11652: #------------------------------Submitted/Handedback Portfolio Files Versioning
11653:  
11654: sub portfiles_versioning {
11655:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
11656:     my $portfolio_root = '/userfiles/portfolio';
11657:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
11658:     foreach my $file (@{$portfiles}) {
11659:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
11660:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
11661:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
11662:         my $getpropath = 1;
11663:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
11664:                                              $stu_name,$getpropath);
11665:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
11666:         my $new_answer = 
11667:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
11668:         if ($new_answer ne 'problem getting file') {
11669:             push(@{$versioned_portfiles}, $directory.$new_answer);
11670:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
11671:                               [$symb,$env{'request.course.id'},'graded']);
11672:         }
11673:     }
11674: }
11675: 
11676: sub get_next_version {
11677:     my ($answer_name, $answer_ext, $dir_list) = @_;
11678:     my $version;
11679:     if (ref($dir_list) eq 'ARRAY') {
11680:         foreach my $row (@{$dir_list}) {
11681:             my ($file) = split(/\&/,$row,2);
11682:             my ($file_name,$file_version,$file_ext) =
11683:                 &file_name_version_ext($file);
11684:             if (($file_name eq $answer_name) &&
11685:                 ($file_ext eq $answer_ext)) {
11686:                      # gets here if filename and extension match,
11687:                      # regardless of version
11688:                 if ($file_version ne '') {
11689:                     # a versioned file is found  so save it for later
11690:                     if ($file_version > $version) {
11691:                         $version = $file_version;
11692:                     }
11693:                 }
11694:             }
11695:         }
11696:     }
11697:     $version ++;
11698:     return($version);
11699: }
11700: 
11701: sub version_selected_portfile {
11702:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
11703:     my ($answer_name,$answer_ver,$answer_ext) =
11704:         &file_name_version_ext($file_name);
11705:     my $new_answer;
11706:     $env{'form.copy'} =
11707:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
11708:     if($env{'form.copy'} eq '-1') {
11709:         $new_answer = 'problem getting file';
11710:     } else {
11711:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
11712:         my $copy_result = 
11713:             &finishuserfileupload($stu_name,$domain,'copy',
11714:                                   '/portfolio'.$directory.$new_answer);
11715:     }
11716:     undef($env{'form.copy'});
11717:     return ($new_answer);
11718: }
11719: 
11720: sub file_name_version_ext {
11721:     my ($file)=@_;
11722:     my @file_parts = split(/\./, $file);
11723:     my ($name,$version,$ext);
11724:     if (@file_parts > 1) {
11725:         $ext=pop(@file_parts);
11726:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
11727:             $version=pop(@file_parts);
11728:         }
11729:         $name=join('.',@file_parts);
11730:     } else {
11731:         $name=join('.',@file_parts);
11732:     }
11733:     return($name,$version,$ext);
11734: }
11735: 
11736: #----------------------------------------------Get portfolio file permissions
11737: 
11738: sub get_portfile_permissions {
11739:     my ($domain,$user) = @_;
11740:     my %current_permissions = &dump('file_permissions',$domain,$user);
11741:     my ($tmp)=keys(%current_permissions);
11742:     if ($tmp=~/^error:/) { undef(%current_permissions); }
11743:     return \%current_permissions;
11744: }
11745: 
11746: #---------------------------------------------Get portfolio file access controls
11747: 
11748: sub get_access_controls {
11749:     my ($current_permissions,$group,$file) = @_;
11750:     my %access;
11751:     my $real_file = $file;
11752:     $file =~ s/\.meta$//;
11753:     if (defined($file)) {
11754:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
11755:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
11756:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
11757:             }
11758:         }
11759:     } else {
11760:         foreach my $key (keys(%{$current_permissions})) {
11761:             if ($key =~ /\0accesscontrol$/) {
11762:                 if (defined($group)) {
11763:                     if ($key !~ m-^\Q$group\E/-) {
11764:                         next;
11765:                     }
11766:                 }
11767:                 my ($fullpath) = split(/\0/,$key);
11768:                 if (ref($$current_permissions{$key}) eq 'HASH') {
11769:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
11770:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
11771:                     }
11772:                 }
11773:             }
11774:         }
11775:     }
11776:     return %access;
11777: }
11778: 
11779: sub modify_access_controls {
11780:     my ($file_name,$changes,$domain,$user)=@_;
11781:     my ($outcome,$deloutcome);
11782:     my %store_permissions;
11783:     my %new_values;
11784:     my %new_control;
11785:     my %translation;
11786:     my @deletions = ();
11787:     my $now = time;
11788:     if (exists($$changes{'activate'})) {
11789:         if (ref($$changes{'activate'}) eq 'HASH') {
11790:             my @newitems = sort(keys(%{$$changes{'activate'}}));
11791:             my $numnew = scalar(@newitems);
11792:             for (my $i=0; $i<$numnew; $i++) {
11793:                 my $newkey = $newitems[$i];
11794:                 my $newid = &Apache::loncommon::get_cgi_id();
11795:                 if ($newkey =~ /^\d+:/) { 
11796:                     $newkey =~ s/^(\d+)/$newid/;
11797:                     $translation{$1} = $newid;
11798:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
11799:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
11800:                     $translation{$1} = $newid;
11801:                 }
11802:                 $new_values{$file_name."\0".$newkey} = 
11803:                                           $$changes{'activate'}{$newitems[$i]};
11804:                 $new_control{$newkey} = $now;
11805:             }
11806:         }
11807:     }
11808:     my %todelete;
11809:     my %changed_items;
11810:     foreach my $action ('delete','update') {
11811:         if (exists($$changes{$action})) {
11812:             if (ref($$changes{$action}) eq 'HASH') {
11813:                 foreach my $key (keys(%{$$changes{$action}})) {
11814:                     my ($itemnum) = ($key =~ /^([^:]+):/);
11815:                     if ($action eq 'delete') { 
11816:                         $todelete{$itemnum} = 1;
11817:                     } else {
11818:                         $changed_items{$itemnum} = $key;
11819:                     }
11820:                 }
11821:             }
11822:         }
11823:     }
11824:     # get lock on access controls for file.
11825:     my $lockhash = {
11826:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
11827:                                                        ':'.$env{'user.domain'},
11828:                    }; 
11829:     my $tries = 0;
11830:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11831:    
11832:     while (($gotlock ne 'ok') && $tries < 10) {
11833:         $tries ++;
11834:         sleep(0.1);
11835:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
11836:     }
11837:     if ($gotlock eq 'ok') {
11838:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
11839:         my ($tmp)=keys(%curr_permissions);
11840:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
11841:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
11842:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
11843:             if (ref($curr_controls) eq 'HASH') {
11844:                 foreach my $control_item (keys(%{$curr_controls})) {
11845:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
11846:                     if (defined($todelete{$itemnum})) {
11847:                         push(@deletions,$file_name."\0".$control_item);
11848:                     } else {
11849:                         if (defined($changed_items{$itemnum})) {
11850:                             $new_control{$changed_items{$itemnum}} = $now;
11851:                             push(@deletions,$file_name."\0".$control_item);
11852:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
11853:                         } else {
11854:                             $new_control{$control_item} = $$curr_controls{$control_item};
11855:                         }
11856:                     }
11857:                 }
11858:             }
11859:         }
11860:         my ($group);
11861:         if (&is_course($domain,$user)) {
11862:             ($group,my $file) = split(/\//,$file_name,2);
11863:         }
11864:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
11865:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
11866:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
11867:         #  remove lock
11868:         my @del_lock = ($file_name."\0".'locked_access_records');
11869:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
11870:         my $sqlresult =
11871:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
11872:                                     $group);
11873:     } else {
11874:         $outcome = "error: could not obtain lockfile\n";  
11875:     }
11876:     return ($outcome,$deloutcome,\%new_values,\%translation);
11877: }
11878: 
11879: sub make_public_indefinitely {
11880:     my (@requrl) = @_;
11881:     return &automated_portfile_access('public',\@requrl);
11882: }
11883: 
11884: sub automated_portfile_access {
11885:     my ($accesstype,$addsref,$delsref,$info) = @_;
11886:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
11887:         return 'invalid';
11888:     }
11889:     my %urls;
11890:     if (ref($addsref) eq 'ARRAY') {
11891:         foreach my $requrl (@{$addsref}) {
11892:             if (&is_portfolio_url($requrl)) {
11893:                 unless (exists($urls{$requrl})) {
11894:                     $urls{$requrl} = 'add';
11895:                 }
11896:             }
11897:         }
11898:     }
11899:     if (ref($delsref) eq 'ARRAY') {
11900:         foreach my $requrl (@{$delsref}) { 
11901:             if (&is_portfolio_url($requrl)) {
11902:                 unless (exists($urls{$requrl})) {
11903:                     $urls{$requrl} = 'delete'; 
11904:                 }
11905:             }
11906:         }
11907:     }
11908:     unless (keys(%urls)) {
11909:         return 'invalid';
11910:     }
11911:     my $ip;
11912:     if ($accesstype eq 'ip') {
11913:         if (ref($info) eq 'HASH') {
11914:             if ($info->{'ip'} ne '') {
11915:                 $ip = $info->{'ip'};
11916:             }
11917:         }
11918:         if ($ip eq '') {
11919:             return 'invalid';
11920:         }
11921:     }
11922:     my $errors;
11923:     my $now = time;
11924:     my %current_perms;
11925:     foreach my $requrl (sort(keys(%urls))) {
11926:         my $action;
11927:         if ($urls{$requrl} eq 'add') {
11928:             $action = 'activate';
11929:         } else {
11930:             $action = 'none';
11931:         }
11932:         my $aclnum = 0;
11933:         my (undef,$udom,$unum,$file_name,$group) =
11934:             &parse_portfolio_url($requrl);
11935:         unless (exists($current_perms{$unum.':'.$udom})) {
11936:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
11937:         }
11938:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
11939:                                                    $group,$file_name);
11940:         foreach my $key (keys(%{$access_controls{$file_name}})) {
11941:             my ($num,$scope,$end,$start) = 
11942:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
11943:             if ($scope eq $accesstype) {
11944:                 if (($start <= $now) && ($end == 0)) {
11945:                     if ($accesstype eq 'ip') {
11946:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
11947:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
11948:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
11949:                                     if ($urls{$requrl} eq 'add') {
11950:                                         $action = 'none';
11951:                                         last;
11952:                                     } else {
11953:                                         $action = 'delete';
11954:                                         $aclnum = $num;
11955:                                         last;
11956:                                     }
11957:                                 }
11958:                             }
11959:                         }
11960:                     } elsif ($accesstype eq 'public') {
11961:                         if ($urls{$requrl} eq 'add') {
11962:                             $action = 'none';
11963:                             last;
11964:                         } else {
11965:                             $action = 'delete';
11966:                             $aclnum = $num;
11967:                             last;
11968:                         }
11969:                     }
11970:                 } elsif ($accesstype eq 'public') {
11971:                     $action = 'update';
11972:                     $aclnum = $num;
11973:                     last;
11974:                 }
11975:             }
11976:         }
11977:         if ($action eq 'none') {
11978:             next;
11979:         } else {
11980:             my %changes;
11981:             my $newend = 0;
11982:             my $newstart = $now;
11983:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
11984:             $changes{$action}{$newkey} = {
11985:                 type => $accesstype,
11986:                 time => {
11987:                     start => $newstart,
11988:                     end   => $newend,
11989:                 },
11990:             };
11991:             if ($accesstype eq 'ip') {
11992:                 $changes{$action}{$newkey}{'ip'} = [$ip];
11993:             }
11994:             my ($outcome,$deloutcome,$new_values,$translation) =
11995:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
11996:             unless ($outcome eq 'ok') {
11997:                 $errors .= $outcome.' ';
11998:             }
11999:         }
12000:     }
12001:     if ($errors) {
12002:         $errors =~ s/\s$//;
12003:         return $errors;
12004:     } else {
12005:         return 'ok';
12006:     }
12007: }
12008: 
12009: #------------------------------------------------------Get Marked as Read Only
12010: 
12011: sub get_marked_as_readonly {
12012:     my ($domain,$user,$what,$group) = @_;
12013:     my $current_permissions = &get_portfile_permissions($domain,$user);
12014:     my @readonly_files;
12015:     my $cmp1=$what;
12016:     if (ref($what)) { $cmp1=join('',@{$what}) };
12017:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12018:         if (defined($group)) {
12019:             if ($file_name !~ m-^\Q$group\E/-) {
12020:                 next;
12021:             }
12022:         }
12023:         if (ref($value) eq "ARRAY"){
12024:             foreach my $stored_what (@{$value}) {
12025:                 my $cmp2=$stored_what;
12026:                 if (ref($stored_what) eq 'ARRAY') {
12027:                     $cmp2=join('',@{$stored_what});
12028:                 }
12029:                 if ($cmp1 eq $cmp2) {
12030:                     push(@readonly_files, $file_name);
12031:                     last;
12032:                 } elsif (!defined($what)) {
12033:                     push(@readonly_files, $file_name);
12034:                     last;
12035:                 }
12036:             }
12037:         }
12038:     }
12039:     return @readonly_files;
12040: }
12041: #-----------------------------------------------------------Get Marked as Read Only Hash
12042: 
12043: sub get_marked_as_readonly_hash {
12044:     my ($current_permissions,$group,$what) = @_;
12045:     my %readonly_files;
12046:     while (my ($file_name,$value) = each(%{$current_permissions})) {
12047:         if (defined($group)) {
12048:             if ($file_name !~ m-^\Q$group\E/-) {
12049:                 next;
12050:             }
12051:         }
12052:         if (ref($value) eq "ARRAY"){
12053:             foreach my $stored_what (@{$value}) {
12054:                 if (ref($stored_what) eq 'ARRAY') {
12055:                     foreach my $lock_descriptor(@{$stored_what}) {
12056:                         if ($lock_descriptor eq 'graded') {
12057:                             $readonly_files{$file_name} = 'graded';
12058:                         } elsif ($lock_descriptor eq 'handback') {
12059:                             $readonly_files{$file_name} = 'handback';
12060:                         } else {
12061:                             if (!exists($readonly_files{$file_name})) {
12062:                                 $readonly_files{$file_name} = 'locked';
12063:                             }
12064:                         }
12065:                     }
12066:                 } 
12067:             }
12068:         } 
12069:     }
12070:     return %readonly_files;
12071: }
12072: # ------------------------------------------------------------ Unmark as Read Only
12073: 
12074: sub unmark_as_readonly {
12075:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
12076:     # for portfolio submissions, $what contains [$symb,$crsid] 
12077:     my ($domain,$user,$what,$file_name,$group) = @_;
12078:     $file_name = &declutter_portfile($file_name);
12079:     my $symb_crs = $what;
12080:     if (ref($what)) { $symb_crs=join('',@$what); }
12081:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
12082:     my ($tmp)=keys(%current_permissions);
12083:     if ($tmp=~/^error:/) { undef(%current_permissions); }
12084:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
12085:     foreach my $file (@readonly_files) {
12086: 	my $clean_file = &declutter_portfile($file);
12087: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
12088: 	my $current_locks = $current_permissions{$file};
12089:         my @new_locks;
12090:         my @del_keys;
12091:         if (ref($current_locks) eq "ARRAY"){
12092:             foreach my $locker (@{$current_locks}) {
12093:                 my $compare=$locker;
12094:                 if (ref($locker) eq 'ARRAY') {
12095:                     $compare=join('',@{$locker});
12096:                     if ($compare ne $symb_crs) {
12097:                         push(@new_locks, $locker);
12098:                     }
12099:                 }
12100:             }
12101:             if (scalar(@new_locks) > 0) {
12102:                 $current_permissions{$file} = \@new_locks;
12103:             } else {
12104:                 push(@del_keys, $file);
12105:                 &del('file_permissions',\@del_keys, $domain, $user);
12106:                 delete($current_permissions{$file});
12107:             }
12108:         }
12109:     }
12110:     &put('file_permissions',\%current_permissions,$domain,$user);
12111:     return;
12112: }
12113: 
12114: # ------------------------------------------------------------ Directory lister
12115: 
12116: sub dirlist {
12117:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
12118:     $uri=~s/^\///;
12119:     $uri=~s/\/$//;
12120:     my ($udom, $uname);
12121:     if ($getuserdir) {
12122:         $udom = $userdomain;
12123:         $uname = $username;
12124:     } else {
12125:         (undef,$udom,$uname)=split(/\//,$uri);
12126:         if(defined($userdomain)) {
12127:             $udom = $userdomain;
12128:         }
12129:         if(defined($username)) {
12130:             $uname = $username;
12131:         }
12132:     }
12133:     my ($dirRoot,$listing,@listing_results);
12134: 
12135:     $dirRoot = $perlvar{'lonDocRoot'};
12136:     if (defined($getpropath)) {
12137:         $dirRoot = &propath($udom,$uname);
12138:         $dirRoot =~ s/\/$//;
12139:     } elsif (defined($getuserdir)) {
12140:         my $subdir=$uname.'__';
12141:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
12142:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
12143:                    ."/$udom/$subdir/$uname";
12144:     } elsif (defined($alternateRoot)) {
12145:         $dirRoot = $alternateRoot;
12146:     }
12147: 
12148:     if($udom) {
12149:         if($uname) {
12150:             my $uhome = &homeserver($uname,$udom);
12151:             if ($uhome eq 'no_host') {
12152:                 return ([],'no_host');
12153:             }
12154:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
12155:                               .$getuserdir.':'.&escape($dirRoot)
12156:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
12157:             if ($listing eq 'unknown_cmd') {
12158:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
12159:             } else {
12160:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12161:             }
12162:             if ($listing eq 'unknown_cmd') {
12163:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
12164:                 @listing_results = split(/:/,$listing);
12165:             } else {
12166:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
12167:             }
12168:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
12169:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
12170:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12171:                 return ([],$listing);
12172:             } else {
12173:                 return (\@listing_results);
12174:             }
12175:         } elsif(!$alternateRoot) {
12176:             my (%allusers,%listerror);
12177: 	    my %servers = &get_servers($udom,'library');
12178:  	    foreach my $tryserver (keys(%servers)) {
12179:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
12180:                                   &escape($udom),$tryserver);
12181:                 if ($listing eq 'unknown_cmd') {
12182: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
12183: 				      $udom, $tryserver);
12184:                 } else {
12185:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
12186:                 }
12187: 		if ($listing eq 'unknown_cmd') {
12188: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
12189: 				      $udom, $tryserver);
12190: 		    @listing_results = split(/:/,$listing);
12191: 		} else {
12192: 		    @listing_results =
12193: 			map { &unescape($_); } split(/:/,$listing);
12194: 		}
12195:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
12196:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
12197:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
12198:                     $listerror{$tryserver} = $listing;
12199:                 } else {
12200: 		    foreach my $line (@listing_results) {
12201: 			my ($entry) = split(/&/,$line,2);
12202: 			$allusers{$entry} = 1;
12203: 		    }
12204: 		}
12205:             }
12206:             my @alluserslist=();
12207:             foreach my $user (sort(keys(%allusers))) {
12208:                 push(@alluserslist,$user.'&user');
12209:             }
12210: 
12211:             if (!%listerror) {
12212:                 # no errors
12213:                 return (\@alluserslist);
12214:             } elsif (scalar(keys(%servers)) == 1) {
12215:                 # one library server, one error 
12216:                 my ($key) = keys(%listerror);
12217:                 return (\@alluserslist, $listerror{$key});
12218:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
12219:                 # con_lost indicates that we might miss data from at least one
12220:                 # library server
12221:                 return (\@alluserslist, 'con_lost');
12222:             } else {
12223:                 # multiple library servers and no con_lost -> data should be
12224:                 # complete. 
12225:                 return (\@alluserslist);
12226:             }
12227: 
12228:         } else {
12229:             return ([],'missing username');
12230:         }
12231:     } elsif(!defined($getpropath)) {
12232:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
12233:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
12234:         return (\@all_domains);
12235:     } else {
12236:         return ([],'missing domain');
12237:     }
12238: }
12239: 
12240: # --------------------------------------------- GetFileTimestamp
12241: # This function utilizes dirlist and returns the date stamp for
12242: # when it was last modified.  It will also return an error of -1
12243: # if an error occurs
12244: 
12245: sub GetFileTimestamp {
12246:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
12247:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
12248:     $studentName   = &LONCAPA::clean_username($studentName);
12249:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
12250:                                     undef,$getuserdir);
12251:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12252:         return -1;
12253:     }
12254:     if (ref($fileref) eq 'ARRAY') {
12255:         my @stats = split('&',$fileref->[0]);
12256:         # @stats contains first the filename, then the stat output
12257:         return $stats[10]; # so this is 10 instead of 9.
12258:     } else {
12259:         return -1;
12260:     }
12261: }
12262: 
12263: sub stat_file {
12264:     my ($uri) = @_;
12265:     $uri = &clutter_with_no_wrapper($uri);
12266: 
12267:     my ($udom,$uname,$file);
12268:     if ($uri =~ m-^/(uploaded|editupload)/-) {
12269: 	($udom,$uname,$file) =
12270: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
12271: 	$file = 'userfiles/'.$file;
12272:     }
12273:     if ($uri =~ m-^/res/-) {
12274: 	($udom,$uname) = 
12275: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
12276: 	$file = $uri;
12277:     }
12278: 
12279:     if (!$udom || !$uname || !$file) {
12280: 	# unable to handle the uri
12281: 	return ();
12282:     }
12283:     my $getpropath;
12284:     if ($file =~ /^userfiles\//) {
12285:         $getpropath = 1;
12286:     }
12287:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
12288:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
12289:         return ();
12290:     } else {
12291:         if (ref($listref) eq 'ARRAY') {
12292:             my @stats = split('&',$listref->[0]);
12293: 	    shift(@stats); #filename is first
12294: 	    return @stats;
12295:         }
12296:     }
12297:     return ();
12298: }
12299: 
12300: # --------------------------------------------------------- recursedirs
12301: # Recursive function to traverse either a specific user's Authoring Space
12302: # or corresponding Published Resource Space, and populate the hash ref:
12303: # $dirhashref with URLs of all directories, and if $filehashref hash
12304: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
12305: # or .rights files in resource space, and .meta, .save, .log, .bak and
12306: # .rights files in Authoring Space.
12307: #
12308: # Inputs:
12309: #
12310: # $is_home - true if current server is home server for user's space
12311: # $recurse - if true will also traverse subdirectories recursively
12312: # $include - reference to hash containing allowed file extensions.  If provided,
12313: #             files which do not have a matching extension will be ignored.
12314: # $exclude - reference to hash containing excluded file extensions.  If provided,
12315: #             files which have a matching extension will be ignored.
12316: # $nonemptydir - if true, will only populate $fileshashref hash entry for a particular
12317: #             directory with first file found (with acceptable extension).
12318: # $addtopdir - if true, set $dirhashref->{'/'} = 1 
12319: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
12320: # $relpath - Current path (relative to top level).
12321: # $dirhashref - reference to hash to populate with URLs of directories (Required)
12322: # $filehashref - reference to hash to populate with URLs of files (Optional)
12323: #
12324: # Returns: nothing
12325: #
12326: # Side Effects: populates $dirhashref, and $filehashref (if provided).
12327: #
12328: # Currently used by interface/londocs.pm to create linked select boxes for
12329: # directory and filename to import a Course "Author" resource into a course, and
12330: # also to create linked select boxes for Authoring Space and Directory to choose
12331: # save location for creation of a new "standard" problem from the Course Editor.
12332: #
12333: 
12334: sub recursedirs {
12335:     my ($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$relpath,$dirhashref,$filehashref) = @_;
12336:     return unless (ref($dirhashref) eq 'HASH');
12337:     my $docroot = $perlvar{'lonDocRoot'};
12338:     my $currpath = $docroot.$toppath;
12339:     if ($relpath ne '') {
12340:         $currpath .= "/$relpath";
12341:     }
12342:     my ($savefile,$checkinc,$checkexc);
12343:     if (ref($filehashref)) {
12344:         $savefile = 1;
12345:     }
12346:     if (ref($include) eq 'HASH') {
12347:         $checkinc = 1;
12348:     }
12349:     if (ref($exclude) eq 'HASH') {
12350:         $checkexc = 1;
12351:     }
12352:     if ($is_home) {
12353:         if ((-e $currpath) && (opendir(my $dirh,$currpath))) {
12354:             my $filecount = 0;
12355:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
12356:                 next if ($item eq '');
12357:                 if (-d "$currpath/$item") {
12358:                     my $newpath;
12359:                     if ($relpath ne '') {
12360:                         $newpath = "$relpath/$item";
12361:                     } else {
12362:                         $newpath = $item;
12363:                     }
12364:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12365:                     if ($recurse) {
12366:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12367:                     }
12368:                 } elsif (($savefile) || ($relpath eq '')) {
12369:                     next if ($nonemptydir && $filecount);
12370:                     if ($checkinc || $checkexc) {
12371:                         my ($extension) = ($item =~ /\.(\w+)$/);
12372:                         if ($checkinc) {
12373:                             next unless ($extension && $include->{$extension});
12374:                         }
12375:                         if ($checkexc) {
12376:                             next if ($extension && $exclude->{$extension});
12377:                         }
12378:                     }
12379:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12380:                         $dirhashref->{'/'} = 1;
12381:                     }
12382:                     if ($savefile) {
12383:                         if ($relpath eq '') {
12384:                             $filehashref->{'/'}{$item} = 1;
12385:                         } else {
12386:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12387:                         }
12388:                     }
12389:                     $filecount ++;
12390:                 }
12391:             }
12392:             closedir($dirh);
12393:         }
12394:     } else {
12395:         my ($dirlistref,$listerror) =
12396:             &dirlist($toppath.$relpath);
12397:         my @dir_lines;
12398:         my $dirptr=16384;
12399:         if (ref($dirlistref) eq 'ARRAY') {
12400:             my $filecount = 0;
12401:             foreach my $dir_line (sort
12402:                               {
12403:                                   my ($afile)=split('&',$a,2);
12404:                                   my ($bfile)=split('&',$b,2);
12405:                                   return (lc($afile) cmp lc($bfile));
12406:                               } (@{$dirlistref})) {
12407:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
12408:                     split(/\&/,$dir_line,16);
12409:                 $item =~ s/\s+$//;
12410:                 next if (($item =~ /^\.\.?$/) || ($obs));
12411:                 if ($dirptr&$testdir) {
12412:                     my $newpath;
12413:                     if ($relpath) {
12414:                         $newpath = "$relpath/$item";
12415:                     } else {
12416:                         $newpath = $item;
12417:                     }
12418:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
12419:                     if ($recurse) {
12420:                         &recursedirs($is_home,$recurse,$include,$exclude,$nonemptydir,$addtopdir,$toppath,$newpath,$dirhashref,$filehashref);
12421:                     }
12422:                 } elsif (($savefile) || ($relpath eq '')) {
12423:                     next if ($nonemptydir && $filecount);
12424:                     if ($checkinc || $checkexc) {
12425:                         my $extension;
12426:                         if ($checkinc) {
12427:                             next unless ($extension && $include->{$extension});
12428:                         }
12429:                         if ($checkexc) {
12430:                             next if ($extension && $exclude->{$extension});
12431:                         }
12432:                     }
12433:                     if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12434:                         $dirhashref->{'/'} = 1;
12435:                     }
12436:                     if ($savefile) {
12437:                         if ($relpath eq '') {
12438:                             $filehashref->{'/'}{$item} = 1;
12439:                         } else {
12440:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
12441:                         }
12442:                     }
12443:                     $filecount ++; 
12444:                 }
12445:             }
12446:         }
12447:     }
12448:     if ($addtopdir) {
12449:         if (($relpath eq '') && (!exists($dirhashref->{'/'}))) {
12450:             $dirhashref->{'/'} = 1;
12451:         }
12452:     }
12453:     return;
12454: }
12455: 
12456: sub priv_exclude {
12457:     return {
12458:              meta => 1,
12459:              save => 1,
12460:              log => 1,
12461:              bak => 1,
12462:              rights => 1,
12463:              DS_Store => 1,
12464:            };
12465: }
12466: 
12467: # -------------------------------------------------------- Value of a Condition
12468: 
12469: # gets the value of a specific preevaluated condition
12470: #    stored in the string  $env{user.state.<cid>}
12471: # or looks up a condition reference in the bighash and if if hasn't
12472: # already been evaluated recurses into docondval to get the value of
12473: # the condition, then memoizing it to 
12474: #   $env{user.state.<cid>.<condition>}
12475: sub directcondval {
12476:     my $number=shift;
12477:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
12478: 	&Apache::lonuserstate::evalstate();
12479:     }
12480:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
12481: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
12482:     } elsif ($number =~ /^_/) {
12483: 	my $sub_condition;
12484: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12485: 		&GDBM_READER(),0640)) {
12486: 	    $sub_condition=$bighash{'conditions'.$number};
12487: 	    untie(%bighash);
12488: 	}
12489: 	my $value = &docondval($sub_condition);
12490: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
12491: 	return $value;
12492:     }
12493:     if ($env{'user.state.'.$env{'request.course.id'}}) {
12494:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
12495:     } else {
12496:        return 2;
12497:     }
12498: }
12499: 
12500: # get the collection of conditions for this resource
12501: sub condval {
12502:     my $condidx=shift;
12503:     my $allpathcond='';
12504:     foreach my $cond (split(/\|/,$condidx)) {
12505: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
12506: 	    $allpathcond.=
12507: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
12508: 	}
12509:     }
12510:     $allpathcond=~s/\|$//;
12511:     return &docondval($allpathcond);
12512: }
12513: 
12514: #evaluates an expression of conditions
12515: sub docondval {
12516:     my ($allpathcond) = @_;
12517:     my $result=0;
12518:     if ($env{'request.course.id'}
12519: 	&& defined($allpathcond)) {
12520: 	my $operand='|';
12521: 	my @stack;
12522: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
12523: 	    if ($chunk eq '(') {
12524: 		push @stack,($operand,$result);
12525: 	    } elsif ($chunk eq ')') {
12526: 		my $before=pop @stack;
12527: 		if (pop @stack eq '&') {
12528: 		    $result=$result>$before?$before:$result;
12529: 		} else {
12530: 		    $result=$result>$before?$result:$before;
12531: 		}
12532: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
12533: 		$operand=$chunk;
12534: 	    } else {
12535: 		my $new=directcondval($chunk);
12536: 		if ($operand eq '&') {
12537: 		    $result=$result>$new?$new:$result;
12538: 		} else {
12539: 		    $result=$result>$new?$result:$new;
12540: 		}
12541: 	    }
12542: 	}
12543:     }
12544:     return $result;
12545: }
12546: 
12547: # ---------------------------------------------------- Devalidate courseresdata
12548: 
12549: sub devalidatecourseresdata {
12550:     my ($coursenum,$coursedomain)=@_;
12551:     my $hashid=$coursenum.':'.$coursedomain;
12552:     &devalidate_cache_new('courseres',$hashid);
12553: }
12554: 
12555: 
12556: # --------------------------------------------------- Course Resourcedata Query
12557: #
12558: #  Parameters:
12559: #      $coursenum    - Number of the course.
12560: #      $coursedomain - Domain at which the course was created.
12561: #  Returns:
12562: #     A hash of the course parameters along (I think) with timestamps
12563: #     and version info.
12564: 
12565: sub get_courseresdata {
12566:     my ($coursenum,$coursedomain)=@_;
12567:     my $coursehom=&homeserver($coursenum,$coursedomain);
12568:     my $hashid=$coursenum.':'.$coursedomain;
12569:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
12570:     my %dumpreply;
12571:     unless (defined($cached)) {
12572: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
12573: 	$result=\%dumpreply;
12574: 	my ($tmp) = keys(%dumpreply);
12575: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12576: 	    &do_cache_new('courseres',$hashid,$result,600);
12577: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
12578: 	    return $tmp;
12579: 	} elsif ($tmp =~ /^(error)/) {
12580: 	    $result=undef;
12581: 	    &do_cache_new('courseres',$hashid,$result,600);
12582: 	}
12583:     }
12584:     return $result;
12585: }
12586: 
12587: sub devalidateuserresdata {
12588:     my ($uname,$udom)=@_;
12589:     my $hashid="$udom:$uname";
12590:     &devalidate_cache_new('userres',$hashid);
12591: }
12592: 
12593: sub get_userresdata {
12594:     my ($uname,$udom)=@_;
12595:     #most student don\'t have any data set, check if there is some data
12596:     if (&EXT_cache_status($udom,$uname)) { return undef; }
12597: 
12598:     my $hashid="$udom:$uname";
12599:     my ($result,$cached)=&is_cached_new('userres',$hashid);
12600:     if (!defined($cached)) {
12601: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
12602: 	$result=\%resourcedata;
12603: 	&do_cache_new('userres',$hashid,$result,600);
12604:     }
12605:     my ($tmp)=keys(%$result);
12606:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
12607: 	return $result;
12608:     }
12609:     #error 2 occurs when the .db doesn't exist
12610:     if ($tmp!~/error: 2 /) {
12611:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
12612: 	    &logthis("<font color=\"blue\">WARNING:".
12613: 		     " Trying to get resource data for ".
12614: 		     $uname." at ".$udom.": ".
12615: 		     $tmp."</font>");
12616:         }
12617:     } elsif ($tmp=~/error: 2 /) {
12618: 	#&EXT_cache_set($udom,$uname);
12619: 	&do_cache_new('userres',$hashid,undef,600);
12620: 	undef($tmp); # not really an error so don't send it back
12621:     }
12622:     return $tmp;
12623: }
12624: #----------------------------------------------- resdata - return resource data
12625: #  Purpose:
12626: #    Return resource data for either users or for a course.
12627: #  Parameters:
12628: #     $name      - Course/user name.
12629: #     $domain    - Name of the domain the user/course is registered on.
12630: #     $type      - Type of thing $name is (must be 'course' or 'user')
12631: #     $mapp      - decluttered URL of enclosing map  
12632: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
12633: #     $recurseup - Ref to array of map URLs, starting with map containing
12634: #                  $mapp up through hierarchy of nested maps to top level map.  
12635: #     $courseid  - CourseID (first part of param identifier).
12636: #     $modifier  - Middle part of param identifier.
12637: #     $what      - Last part of param identifier.
12638: #     @which     - Array of names of resources desired.
12639: #  Returns:
12640: #     The value of the first reasource in @which that is found in the
12641: #     resource hash.
12642: #  Exceptional Conditions:
12643: #     If the $type passed in is not valid (not the string 'course' or 
12644: #     'user', an undefined  reference is returned.
12645: #     If none of the resources are found, an undef is returned
12646: sub resdata {
12647:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
12648:         $modifier,$what,@which)=@_;
12649:     my $result;
12650:     if ($type eq 'course') {
12651: 	$result=&get_courseresdata($name,$domain);
12652:     } elsif ($type eq 'user') {
12653: 	$result=&get_userresdata($name,$domain);
12654:     }
12655:     if (!ref($result)) { return $result; }    
12656:     foreach my $item (@which) {
12657:         if ($item->[1] eq 'course') {
12658:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
12659:                 unless ($$recursed) {
12660:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
12661:                     $$recursed = 1;
12662:                 }
12663:                 foreach my $item (@${recurseup}) {
12664:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
12665:                     last if (defined($result->{$norecursechk}));
12666:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
12667:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
12668:                 }
12669:             }
12670:         }
12671:         if (defined($result->{$item->[0]})) {
12672: 	    return [$result->{$item->[0]},$item->[1]];
12673: 	}
12674:     }
12675:     return undef;
12676: }
12677: 
12678: sub get_domain_lti {
12679:     my ($cdom,$context) = @_;
12680:     my ($name,$cachename,%lti);
12681:     if ($context eq 'consumer') {
12682:         $name = 'ltitools';
12683:     } elsif ($context eq 'provider') {
12684:         $name = 'lti';
12685:     } elsif ($context eq 'linkprot') {
12686:         $name = 'ltisec';
12687:     } else {
12688:         return %lti;
12689:     }
12690:     if ($context eq 'linkprot') {
12691:         $cachename = $context;
12692:     } else {
12693:         $cachename = $name;
12694:     }
12695:     my ($result,$cached)=&is_cached_new($cachename,$cdom);
12696:     if (defined($cached)) {
12697:         if (ref($result) eq 'HASH') {
12698:             %lti = %{$result};
12699:         }
12700:     } else {
12701:         my %domconfig = &get_dom('configuration',[$name],$cdom);
12702:         if (ref($domconfig{$name}) eq 'HASH') {
12703:             if ($context eq 'linkprot') {
12704:                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
12705:                     %lti = %{$domconfig{$name}{'linkprot'}};
12706:                 }
12707:             } else {
12708:                 %lti = %{$domconfig{$name}};
12709:             }
12710:         }
12711:         my $cachetime = 24*60*60;
12712:         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
12713:     }
12714:     return %lti;
12715: }
12716: 
12717: sub get_course_lti {
12718:     my ($cnum,$cdom,$context) = @_;
12719:     my ($name,$cachename,%lti);
12720:     if ($context eq 'consumer') {
12721:         $name = 'ltitools';
12722:         $cachename = 'courseltitools';
12723:     } elsif ($context eq 'provider') {
12724:         $name = 'lti';
12725:         $cachename = 'courselti';
12726:     } else {
12727:         return %lti;
12728:     }
12729:     my $hashid=$cdom.'_'.$cnum;
12730:     my ($result,$cached)=&is_cached_new($cachename,$hashid);
12731:     if (defined($cached)) {
12732:         if (ref($result) eq 'HASH') {
12733:             %lti = %{$result};
12734:         }
12735:     } else {
12736:         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
12737:         my $cachetime = 24*60*60;
12738:         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
12739:     }
12740:     return %lti;
12741: }
12742: 
12743: sub courselti_itemid {
12744:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
12745:     my ($chome,$itemid);
12746:     $chome = &homeserver($cnum,$cdom);
12747:     return if ($chome eq 'no_host');
12748:     if (ref($params) eq 'HASH') {
12749:         my $rep;
12750:         if (grep { $_ eq $chome } current_machine_ids()) {
12751:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
12752:         } else {
12753:             my $escurl = &escape($url);
12754:             my $escmethod = &escape($method);
12755:             my $items = &freeze_escape($params);
12756:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
12757:         }
12758:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12759:                 ($rep eq 'unknown_cmd')) {
12760:             $itemid = $rep;
12761:         }
12762:     }
12763:     return $itemid;
12764: }
12765: 
12766: sub domainlti_itemid {
12767:     my ($cdom,$url,$method,$params,$context) = @_;
12768:     my ($primary_id,$itemid);
12769:     $primary_id = &domain($cdom,'primary');
12770:     return if ($primary_id eq '');
12771:     if (ref($params) eq 'HASH') {
12772:         my $rep;
12773:         if (grep { $_ eq $primary_id } current_machine_ids()) {
12774:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
12775:         } else {
12776:             my $cnum = '';
12777:             my $escurl = &escape($url);
12778:             my $escmethod = &escape($method);
12779:             my $items = &freeze_escape($params);
12780:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
12781:         }
12782:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
12783:                 ($rep eq 'unknown_cmd')) {
12784:             $itemid = $rep;
12785:         }
12786:     }
12787:     return $itemid;
12788: }
12789: 
12790: sub get_ltitools_id {
12791:     my ($context,$cdom,$cnum,$title) = @_;
12792:     my ($lockhash,$tries,$gotlock,$id,$error);
12793: 
12794:     # get lock on ltitools db
12795:     $lockhash = {
12796:                    lock => $env{'user.name'}.
12797:                            ':'.$env{'user.domain'},
12798:                 };
12799:     $tries = 0;
12800:     if ($context eq 'domain') {
12801:         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12802:     } else {
12803:         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12804:     }
12805:     while (($gotlock ne 'ok') && ($tries<10)) {
12806:         $tries ++;
12807:         sleep (0.1);
12808:         if ($context eq 'domain') {
12809:             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
12810:         } else {
12811:             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
12812:         }
12813:     }
12814:     if ($gotlock eq 'ok') {
12815:         my %currids;
12816:         if ($context eq 'domain') {
12817:             %currids = &dump_dom('ltitools',$cdom);
12818:         } else {
12819:             %currids = &dump('ltitools',$cdom,$cnum);
12820:         }
12821:         if ($currids{'lock'}) {
12822:             delete($currids{'lock'});
12823:             if (keys(%currids)) {
12824:                 my @curr = sort { $a <=> $b } keys(%currids);
12825:                 if ($curr[-1] =~ /^\d+$/) {
12826:                     $id = 1 + $curr[-1];
12827:                 }
12828:             } else {
12829:                 $id = 1;
12830:             }
12831:             if ($id) {
12832:                 if ($context eq 'domain') {
12833:                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
12834:                         $error = 'nostore';
12835:                     }
12836:                 } else {
12837:                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
12838:                         $error = 'nostore';
12839:                     }
12840:                 }
12841:             } else {
12842:                 $error = 'nonumber';
12843:             }
12844:         }
12845:         my $dellockoutcome;
12846:         if ($context eq 'domain') {
12847:             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
12848:         } else {
12849:             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
12850:         }
12851:     } else {
12852:         $error = 'nolock';
12853:     }
12854:     return ($id,$error);
12855: }
12856: 
12857: sub count_supptools {
12858:     my ($cnum,$cdom,$ignorecache,$reload)=@_;
12859:     my $hashid=$cnum.':'.$cdom;
12860:     my ($numexttools,$cached);
12861:     unless ($ignorecache) {
12862:         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
12863:     }
12864:     unless (defined($cached)) {
12865:         my $chome=&homeserver($cnum,$cdom);
12866:         $numexttools = 0;
12867:         unless ($chome eq 'no_host') {
12868:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
12869:             if (ref($supplemental) eq 'HASH') {
12870:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12871:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12872:                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
12873:                             $numexttools ++;
12874:                         }
12875:                     }
12876:                 }
12877:             }
12878:         }
12879:         &do_cache_new('supptools',$hashid,$numexttools,600);
12880:     }
12881:     return $numexttools;
12882: }
12883: 
12884: sub has_unhidden_suppfiles {
12885:     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
12886:     my $hashid=$cnum.':'.$cdom;
12887:     my ($showsupp,$cached);
12888:     unless ($ignorecache) {
12889:         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
12890:     }
12891:     unless (defined($cached)) {
12892:         my $chome=&homeserver($cnum,$cdom);
12893:         unless ($chome eq 'no_host') {
12894:             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
12895:             if (ref($supplemental) eq 'HASH') {
12896:                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
12897:                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
12898:                         next if ($key =~ /\.sequence$/);
12899:                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
12900:                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
12901:                                 unless ($supplemental->{'hidden'}->{$id}) {
12902:                                     $showsupp = 1;
12903:                                     last;
12904:                                 }
12905:                             }
12906:                         }
12907:                         last if ($showsupp);
12908:                     }
12909:                 }
12910:             }
12911:         }
12912:         &do_cache_new('showsupp',$hashid,$showsupp,600);
12913:     }
12914:     return $showsupp;
12915: }
12916: 
12917: #
12918: # EXT resource caching routines
12919: #
12920: 
12921: {
12922: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
12923: #
12924: # The course for which we cache
12925: my $cachedmapkey='';
12926: # The cached recursive maps for this course
12927: my %cachedmaps=();
12928: # When this was last done
12929: my $cachedmaptime='';
12930: 
12931: sub clear_EXT_cache_status {
12932:     &delenv('cache.EXT.');
12933: }
12934: 
12935: sub EXT_cache_status {
12936:     my ($target_domain,$target_user) = @_;
12937:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12938:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
12939:         # We know already the user has no data
12940:         return 1;
12941:     } else {
12942:         return 0;
12943:     }
12944: }
12945: 
12946: sub EXT_cache_set {
12947:     my ($target_domain,$target_user) = @_;
12948:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
12949:     #&appenv({$cachename => time});
12950: }
12951: 
12952: # --------------------------------------------------------- Value of a Variable
12953: sub EXT {
12954: 
12955:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
12956:     unless ($varname) { return ''; }
12957:     #get real user name/domain, courseid and symb
12958:     my $courseid;
12959:     my $publicuser;
12960:     if ($symbparm) {
12961: 	$symbparm=&get_symb_from_alias($symbparm);
12962:     }
12963:     if (!($uname && $udom)) {
12964:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
12965:       if (!$symbparm) {	$symbparm=$cursymb; }
12966:     } else {
12967: 	$courseid=$env{'request.course.id'};
12968:     }
12969:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
12970:     my $rest;
12971:     if (defined($therest[0])) {
12972:        $rest=join('.',@therest);
12973:     } else {
12974:        $rest='';
12975:     }
12976: 
12977:     my $qualifierrest=$qualifier;
12978:     if ($rest) { $qualifierrest.='.'.$rest; }
12979:     my $spacequalifierrest=$space;
12980:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
12981:     if ($realm eq 'user') {
12982: # --------------------------------------------------------------- user.resource
12983: 	if ($space eq 'resource') {
12984: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
12985: 		  || defined($Apache::lonhomework::parsing_a_task))
12986: 		 &&
12987: 		 ($symbparm eq &symbread()) ) {
12988: 		# if we are in the middle of processing the resource the
12989: 		# get the value we are planning on committing
12990:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
12991:                     return $Apache::lonhomework::results{$qualifierrest};
12992:                 } else {
12993:                     return $Apache::lonhomework::history{$qualifierrest};
12994:                 }
12995: 	    } else {
12996: 		my %restored;
12997: 		if ($publicuser || $env{'request.state'} eq 'construct') {
12998: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
12999: 		} else {
13000: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
13001: 		}
13002: 		return $restored{$qualifierrest};
13003: 	    }
13004: # ----------------------------------------------------------------- user.access
13005:         } elsif ($space eq 'access') {
13006: 	    # FIXME - not supporting calls for a specific user
13007:             return &allowed($qualifier,$rest);
13008: # ------------------------------------------ user.preferences, user.environment
13009:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
13010: 	    if (($uname eq $env{'user.name'}) &&
13011: 		($udom eq $env{'user.domain'})) {
13012: 		return $env{join('.',('environment',$qualifierrest))};
13013: 	    } else {
13014: 		my %returnhash;
13015: 		if (!$publicuser) {
13016: 		    %returnhash=&userenvironment($udom,$uname,
13017: 						 $qualifierrest);
13018: 		}
13019: 		return $returnhash{$qualifierrest};
13020: 	    }
13021: # ----------------------------------------------------------------- user.course
13022:         } elsif ($space eq 'course') {
13023: 	    # FIXME - not supporting calls for a specific user
13024:             return $env{join('.',('request.course',$qualifier))};
13025: # ------------------------------------------------------------------- user.role
13026:         } elsif ($space eq 'role') {
13027: 	    # FIXME - not supporting calls for a specific user
13028:             my ($role,$where)=split(/\./,$env{'request.role'});
13029:             if ($qualifier eq 'value') {
13030: 		return $role;
13031:             } elsif ($qualifier eq 'extent') {
13032:                 return $where;
13033:             }
13034: # ----------------------------------------------------------------- user.domain
13035:         } elsif ($space eq 'domain') {
13036:             return $udom;
13037: # ------------------------------------------------------------------- user.name
13038:         } elsif ($space eq 'name') {
13039:             return $uname;
13040: # ---------------------------------------------------- Any other user namespace
13041:         } else {
13042: 	    my %reply;
13043: 	    if (!$publicuser) {
13044: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
13045: 	    }
13046: 	    return $reply{$qualifierrest};
13047:         }
13048:     } elsif ($realm eq 'query') {
13049: # ---------------------------------------------- pull stuff out of query string
13050:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
13051: 						[$spacequalifierrest]);
13052: 	return $env{'form.'.$spacequalifierrest}; 
13053:    } elsif ($realm eq 'request') {
13054: # ------------------------------------------------------------- request.browser
13055:         if ($space eq 'browser') {
13056:             return $env{'browser.'.$qualifier};
13057: # ------------------------------------------------------------ request.filename
13058:         } else {
13059:             return $env{'request.'.$spacequalifierrest};
13060:         }
13061:     } elsif ($realm eq 'course') {
13062: # ---------------------------------------------------------- course.description
13063:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
13064:     } elsif ($realm eq 'resource') {
13065: 
13066: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
13067: 	    if (!$symbparm) { $symbparm=&symbread(); }
13068: 	}
13069: 
13070:         if ($qualifier eq '') {
13071: 	    if ($space eq 'title') {
13072: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
13073: 	        return &gettitle($symbparm);
13074: 	    }
13075: 	
13076: 	    if ($space eq 'map') {
13077: 	        my ($map) = &decode_symb($symbparm);
13078: 	        return &symbread($map);
13079: 	    }
13080:             if ($space eq 'maptitle') {
13081:                 my ($map) = &decode_symb($symbparm);
13082:                 return &gettitle($map);
13083:             }
13084: 	    if ($space eq 'filename') {
13085: 	        if ($symbparm) {
13086: 		    return &clutter((&decode_symb($symbparm))[2]);
13087: 	        }
13088: 	        return &hreflocation('',$env{'request.filename'});
13089: 	    }
13090: 
13091:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
13092:                 if ($space eq 'visibleparts') {
13093:                     my $navmap = Apache::lonnavmaps::navmap->new();
13094:                     my $item;
13095:                     if (ref($navmap)) {
13096:                         my $res = $navmap->getBySymb($symbparm);
13097:                         my $parts = $res->parts();
13098:                         if (ref($parts) eq 'ARRAY') {
13099:                             $item = join(',',@{$parts});
13100:                         }
13101:                         undef($navmap);
13102:                     }
13103:                     return $item;
13104:                 }
13105:             }
13106:         }
13107: 
13108: 	my ($section, $group, @groups, @recurseup, $recursed);
13109:         if (ref($recurseupref) eq 'ARRAY') {
13110:             @recurseup = @{$recurseupref};
13111:             $recursed = 1;
13112:         }
13113: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
13114:         if (($courseid eq '') && ($cid)) {
13115:             $courseid = $cid;
13116:         }
13117: 	if (($symbparm && $courseid) && 
13118: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
13119: 
13120: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
13121: 
13122: # ----------------------------------------------------- Cascading lookup scheme
13123: 	    my $symbp=$symbparm;
13124: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
13125: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
13126:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
13127: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
13128: 	    if (($env{'user.name'} eq $uname) &&
13129: 		($env{'user.domain'} eq $udom)) {
13130: 		$section=$env{'request.course.sec'};
13131:                 @groups = split(/:/,$env{'request.course.groups'});  
13132:                 @groups=&sort_course_groups($courseid,@groups); 
13133: 	    } else {
13134: 		if (! defined($usection)) {
13135: 		    $section=&getsection($udom,$uname,$courseid);
13136: 		} else {
13137: 		    $section = $usection;
13138: 		}
13139:                 @groups = &get_users_groups($udom,$uname,$courseid);
13140: 	    }
13141: 
13142: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
13143: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
13144:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
13145: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
13146: 
13147: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
13148: 	    my $courselevelr=$courseid.'.'.$symbparm;
13149:             $courseleveli=$courseid.'.'.$recurseparm;
13150: 	    $courselevelm=$courseid.'.'.$mapparm;
13151: 
13152: # ----------------------------------------------------------- first, check user
13153: 
13154: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
13155:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
13156: 				       ([$courselevelr,'resource'],
13157: 					[$courselevelm,'map'     ],
13158:                                         [$courseleveli,'map'     ],
13159: 					[$courselevel, 'course'  ]));
13160: 	    if (defined($userreply)) { return &get_reply($userreply); }
13161: 
13162: # ------------------------------------------------ second, check some of course
13163:             my $coursereply;
13164:             if (@groups > 0) {
13165:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
13166:                                        $recurseparm,$mapparm,$spacequalifierrest,
13167:                                        $mapp,\$recursed,\@recurseup);
13168:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
13169:             }
13170: 
13171: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13172: 				  $env{'course.'.$courseid.'.domain'},
13173: 				  'course',$mapp,\$recursed,\@recurseup,
13174:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
13175: 				  ([$seclevelr,   'resource'],
13176: 				   [$seclevelm,   'map'     ],
13177:                                    [$secleveli,   'map'     ],
13178: 				   [$seclevel,    'course'  ],
13179: 				   [$courselevelr,'resource']));
13180: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13181: 
13182: # ------------------------------------------------------ third, check map parms
13183: 	    my %parmhash=();
13184: 	    my $thisparm='';
13185: 	    if (tie(%parmhash,'GDBM_File',
13186: 		    $env{'request.course.fn'}.'_parms.db',
13187: 		    &GDBM_READER(),0640)) {
13188: 		$thisparm=$parmhash{$symbparm};
13189: 		untie(%parmhash);
13190: 	    }
13191: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
13192: 	}
13193: # ------------------------------------------ fourth, look in resource metadata
13194:  
13195:         my $what = $spacequalifierrest;
13196: 	$what=~s/\./\_/;
13197: 	my $filename;
13198: 	if (!$symbparm) { $symbparm=&symbread(); }
13199: 	if ($symbparm) {
13200: 	    $filename=(&decode_symb($symbparm))[2];
13201: 	} else {
13202: 	    $filename=$env{'request.filename'};
13203: 	}
13204:         my $toolsymb;
13205:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
13206:             $toolsymb = $symbparm;
13207:         }
13208: 	my $metadata=&metadata($filename,$what,$toolsymb);
13209: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13210: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
13211: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
13212: 
13213: # ----------------------------------------------- fifth, look in rest of course
13214: 	if ($symbparm && defined($courseid) && 
13215: 	    $courseid eq $env{'request.course.id'}) {
13216: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
13217: 				     $env{'course.'.$courseid.'.domain'},
13218: 				     'course',$mapp,\$recursed,\@recurseup,
13219:                                      $courseid,'.',$spacequalifierrest,
13220: 				     ([$courselevelm,'map'   ],
13221:                                       [$courseleveli,'map'   ],
13222: 				      [$courselevel, 'course']));
13223: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
13224: 	}
13225: # ------------------------------------------------------------------ Cascade up
13226: 	unless ($space eq '0') {
13227: 	    my @parts=split(/_/,$space);
13228: 	    my $id=pop(@parts);
13229: 	    my $part=join('_',@parts);
13230: 	    if ($part eq '') { $part='0'; }
13231: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
13232: 				 $symbparm,$udom,$uname,$section,1);
13233: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
13234: 	}
13235: 	if ($recurse) { return undef; }
13236: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
13237: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
13238: # ---------------------------------------------------- Any other user namespace
13239:     } elsif ($realm eq 'environment') {
13240: # ----------------------------------------------------------------- environment
13241: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
13242: 	    return $env{'environment.'.$spacequalifierrest};
13243: 	} else {
13244: 	    if ($uname eq 'anonymous' && $udom eq '') {
13245: 		return '';
13246: 	    }
13247: 	    my %returnhash=&userenvironment($udom,$uname,
13248: 					    $spacequalifierrest);
13249: 	    return $returnhash{$spacequalifierrest};
13250: 	}
13251:     } elsif ($realm eq 'system') {
13252: # ----------------------------------------------------------------- system.time
13253: 	if ($space eq 'time') {
13254: 	    return time;
13255:         }
13256:     } elsif ($realm eq 'server') {
13257: # ----------------------------------------------------------------- system.time
13258: 	if ($space eq 'name') {
13259: 	    return $ENV{'SERVER_NAME'};
13260:         }
13261:     } elsif ($realm eq 'client') {
13262:         if ($space eq 'remote_addr') {
13263:             return &get_requestor_ip();
13264:         }
13265:     }
13266:     return '';
13267: }
13268: 
13269: sub get_reply {
13270:     my ($reply_value) = @_;
13271:     if (ref($reply_value) eq 'ARRAY') {
13272:         if (wantarray) {
13273: 	    return @$reply_value;
13274:         }
13275:         return $reply_value->[0];
13276:     } else {
13277:         return $reply_value;
13278:     }
13279: }
13280: 
13281: sub check_group_parms {
13282:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
13283:         $recursed,$recurseupref) = @_;
13284:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
13285:                   [$what,'course']);
13286:     my $coursereply;
13287:     foreach my $group (@{$groups}) {
13288:         my @groupitems = ();
13289:         foreach my $level (@levels) {
13290:              my $item = $courseid.'.['.$group.'].'.$level->[0];
13291:              push(@groupitems,[$item,$level->[1]]);
13292:         }
13293:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
13294:                                    $env{'course.'.$courseid.'.domain'},
13295:                                    'course',$mapp,$recursed,$recurseupref,
13296:                                    $courseid,'.['.$group.'].',$what,
13297:                                    @groupitems);
13298:         last if (defined($coursereply));
13299:     }
13300:     return $coursereply;
13301: }
13302: 
13303: sub get_map_hierarchy {
13304:     my ($mapname,$courseid) = @_;
13305:     my @recurseup = ();
13306:     if ($mapname) {
13307:         if (($cachedmapkey eq $courseid) &&
13308:             (abs($cachedmaptime-time)<5)) {
13309:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
13310:                 return @{$cachedmaps{$mapname}};
13311:             }
13312:         }
13313:         my $navmap = Apache::lonnavmaps::navmap->new();
13314:         if (ref($navmap)) {
13315:             @recurseup = $navmap->recurseup_maps($mapname);
13316:             undef($navmap);
13317:             $cachedmaps{$mapname} = \@recurseup;
13318:             $cachedmaptime=time;
13319:             $cachedmapkey=$courseid;
13320:         }
13321:     }
13322:     return @recurseup;
13323: }
13324: 
13325: }
13326: 
13327: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
13328:     my ($courseid,@groups) = @_;
13329:     @groups = sort(@groups);
13330:     return @groups;
13331: }
13332: 
13333: sub packages_tab_default {
13334:     my ($uri,$varname,$toolsymb)=@_;
13335:     my (undef,$part,$name)=split(/\./,$varname);
13336: 
13337:     my (@extension,@specifics,$do_default);
13338:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
13339: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
13340: 	if ($pack_type eq 'default') {
13341: 	    $do_default=1;
13342: 	} elsif ($pack_type eq 'extension') {
13343: 	    push(@extension,[$package,$pack_type,$pack_part]);
13344: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
13345: 	    # only look at packages defaults for packages that this id is
13346: 	    push(@specifics,[$package,$pack_type,$pack_part]);
13347: 	}
13348:     }
13349:     # first look for a package that matches the requested part id
13350:     foreach my $package (@specifics) {
13351: 	my (undef,$pack_type,$pack_part)=@{$package};
13352: 	next if ($pack_part ne $part);
13353: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13354: 	    return $packagetab{"$pack_type&$name&default"};
13355: 	}
13356:     }
13357:     # look for any possible matching non extension_ package
13358:     foreach my $package (@specifics) {
13359: 	my (undef,$pack_type,$pack_part)=@{$package};
13360: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13361: 	    return $packagetab{"$pack_type&$name&default"};
13362: 	}
13363: 	if ($pack_type eq 'part') { $pack_part='0'; }
13364: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
13365: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
13366: 	}
13367:     }
13368:     # look for any posible extension_ match
13369:     foreach my $package (@extension) {
13370: 	my ($package,$pack_type)=@{$package};
13371: 	if (defined($packagetab{"$pack_type&$name&default"})) {
13372: 	    return $packagetab{"$pack_type&$name&default"};
13373: 	}
13374: 	if (defined($packagetab{$package."&$name&default"})) {
13375: 	    return $packagetab{$package."&$name&default"};
13376: 	}
13377:     }
13378:     # look for a global default setting
13379:     if ($do_default && defined($packagetab{"default&$name&default"})) {
13380: 	return $packagetab{"default&$name&default"};
13381:     }
13382:     return undef;
13383: }
13384: 
13385: sub add_prefix_and_part {
13386:     my ($prefix,$part)=@_;
13387:     my $keyroot;
13388:     if (defined($prefix) && $prefix !~ /^__/) {
13389: 	# prefix that has a part already
13390: 	$keyroot=$prefix;
13391:     } elsif (defined($prefix)) {
13392: 	# prefix that is missing a part
13393: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
13394:     } else {
13395: 	# no prefix at all
13396: 	if (defined($part)) { $keyroot='_'.$part; }
13397:     }
13398:     return $keyroot;
13399: }
13400: 
13401: # ---------------------------------------------------------------- Get metadata
13402: 
13403: my %metaentry;
13404: my %importedpartids;
13405: my %importedrespids;
13406: sub metadata {
13407:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
13408:     $uri=&declutter($uri);
13409:     # if it is a non metadata possible uri return quickly
13410:     if (($uri eq '') || 
13411: 	(($uri =~ m|^/*adm/|) && 
13412: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
13413:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
13414: 	return undef;
13415:     }
13416:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
13417: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
13418: 	return undef;
13419:     }
13420:     my $filename=$uri;
13421:     $uri=~s/\.meta$//;
13422: #
13423: # Is the metadata already cached?
13424: # Look at timestamp of caching
13425: # Everything is cached by the main uri, libraries are never directly cached
13426: #
13427:     if (!defined($liburi)) {
13428: 	my ($result,$cached)=&is_cached_new('meta',$uri);
13429: 	if (defined($cached)) { return $result->{':'.$what}; }
13430:     }
13431: 
13432: #
13433: # If the uri is for an external tool the file from
13434: # which metadata should be retrieved depends on whether
13435: # the tool had been configured to be gradable (set in the Course
13436: # Editor or Resource Editor).
13437: #
13438: # If a valid symb has been included as the third arg in the call
13439: # to &metadata() that can be used to retrieve the value of
13440: # parameter_0_gradable set for the resource, and included in the
13441: # uploaded map containing the tool. The value is retrieved via
13442: # &EXT(), if a valid symb is available.  Otherwise the value of
13443: # gradable in the exttool_$marker.db file for the tool instance
13444: # is retrieved via &get().
13445: #
13446: # When lonuserstate::traceroute() calls lonnet::EXT() for 
13447: # hiddenresource and encrypturl (during course initialization)
13448: # the map-level parameter for resource.0.gradable included in the 
13449: # uploaded map containing the tool will not yet have been stored
13450: # in the user_course_parms.db file for the user's session, so in 
13451: # this case fall back to retrieving gradable status from the
13452: # exttool_$marker.db file.
13453: #
13454: # In order to avoid an infinite loop, &metadata() will return
13455: # before a call to &EXT(), if the uri is for an external tool
13456: # and the $what for which metadata is being requested is
13457: # parameter_0_gradable or 0_gradable.
13458: #
13459: 
13460:     if ($uri =~ /ext\.tool$/) {
13461:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
13462:             return;
13463:         } else {
13464:             my ($checked,$use_passback);
13465:             if ($toolsymb ne '') {
13466:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
13467:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
13468:                     $checked = 1;
13469:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
13470:                         $use_passback = 1;
13471:                     }
13472:                 }
13473:             }
13474:             unless ($checked) {
13475:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
13476:                 $marker=~s/\D//g;
13477:                 if ($marker) {
13478:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
13479:                     $use_passback = $toolsettings{'gradable'};
13480:                 }
13481:             }
13482:             if ($use_passback) {
13483:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
13484:             } else {
13485:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
13486:             }
13487:         }
13488:     }
13489: 
13490:     {
13491: # Imported parts would go here
13492:         my @origfiletagids=();
13493:         my $importedparts=0;
13494: 
13495: # Imported responseids would go here
13496:         my $importedresponses=0;
13497: #
13498: # Is this a recursive call for a library?
13499: #
13500: #	if (! exists($metacache{$uri})) {
13501: #	    $metacache{$uri}={};
13502: #	}
13503: 	my $cachetime = 60*60;
13504:         if ($liburi) {
13505: 	    $liburi=&declutter($liburi);
13506:             $filename=$liburi;
13507:         } else {
13508: 	    &devalidate_cache_new('meta',$uri);
13509: 	    undef(%metaentry);
13510: 	}
13511:         my %metathesekeys=();
13512:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
13513: 	my $metastring;
13514: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
13515: 	    my $which = &hreflocation('','/'.($liburi || $uri));
13516: 	    $metastring = 
13517: 		&Apache::lonnet::ssi_body($which,
13518: 					  ('grade_target' => 'meta'));
13519: 	    $cachetime = 1; # only want this cached in the child not long term
13520: 	} elsif (($uri !~ m -^(editupload)/-) && 
13521:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
13522: 	    my $file=&filelocation('',&clutter($filename));
13523: 	    #push(@{$metaentry{$uri.'.file'}},$file);
13524: 	    $metastring=&getfile($file);
13525: 	}
13526:         my $parser=HTML::LCParser->new(\$metastring);
13527:         my $token;
13528:         undef %metathesekeys;
13529:         while ($token=$parser->get_token) {
13530: 	    if ($token->[0] eq 'S') {
13531: 		if (defined($token->[2]->{'package'})) {
13532: #
13533: # This is a package - get package info
13534: #
13535: 		    my $package=$token->[2]->{'package'};
13536: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13537: 		    if (defined($token->[2]->{'id'})) { 
13538: 			$keyroot.='_'.$token->[2]->{'id'}; 
13539: 		    }
13540: 		    if ($metaentry{':packages'}) {
13541: 			$metaentry{':packages'}.=','.$package.$keyroot;
13542: 		    } else {
13543: 			$metaentry{':packages'}=$package.$keyroot;
13544: 		    }
13545: 		    foreach my $pack_entry (keys(%packagetab)) {
13546: 			my $part=$keyroot;
13547: 			$part=~s/^\_//;
13548: 			if ($pack_entry=~/^\Q$package\E\&/ || 
13549: 			    $pack_entry=~/^\Q$package\E_0\&/) {
13550: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
13551: 			    # ignore package.tab specified default values
13552:                             # here &package_tab_default() will fetch those
13553: 			    if ($subp eq 'default') { next; }
13554: 			    my $value=$packagetab{$pack_entry};
13555: 			    my $unikey;
13556: 			    if ($pack =~ /_0$/) {
13557: 				$unikey='parameter_0_'.$name;
13558: 				$part=0;
13559: 			    } else {
13560: 				$unikey='parameter'.$keyroot.'_'.$name;
13561: 			    }
13562: 			    if ($subp eq 'display') {
13563: 				$value.=' [Part: '.$part.']';
13564: 			    }
13565: 			    $metaentry{':'.$unikey.'.part'}=$part;
13566: 			    $metathesekeys{$unikey}=1;
13567: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13568: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
13569: 			    }
13570: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
13571: 				$metaentry{':'.$unikey}=
13572: 				    $metaentry{':'.$unikey.'.default'};
13573: 			    }
13574: 			}
13575: 		    }
13576: 		} else {
13577: #
13578: # This is not a package - some other kind of start tag
13579: #
13580: 		    my $entry=$token->[1];
13581: 		    my $unikey='';
13582: 
13583: 		    if ($entry eq 'import') {
13584: #
13585: # Importing a library here
13586: #
13587:                         my $location=$parser->get_text('/import');
13588:                         my $dir=$filename;
13589:                         $dir=~s|[^/]*$||;
13590:                         $location=&filelocation($dir,$location);
13591: 
13592:                         my $importid=$token->[2]->{'id'};
13593:                         my $importmode=$token->[2]->{'importmode'};
13594: #
13595: # Check metadata for imported file to
13596: # see if it contained response items
13597: #
13598:                         my ($origfile,@libfilekeys);
13599:                         my %currmetaentry = %metaentry;
13600:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
13601:                                                            $depthcount+1));
13602:                         if (grep(/^responseorder$/,@libfilekeys)) {
13603:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
13604:                                                              undef,$depthcount+1);
13605:                             if ($libresponseorder ne '') {
13606:                                 if ($#origfiletagids<0) {
13607:                                     undef(%importedrespids);
13608:                                     undef(%importedpartids);
13609:                                 }
13610:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
13611:                                 if (@respids) {
13612:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
13613:                                 }
13614:                                 if ($importedrespids{$importid} ne '') {
13615:                                     $importedresponses = 1;
13616: # We need to get the original file and the imported file to get the response order correct
13617: # Load and inspect original file
13618:                                     if ($#origfiletagids<0) {
13619:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13620:                                         $origfile=&getfile($origfilelocation);
13621:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13622:                                     }
13623:                                 }
13624:                             }
13625:                         }
13626: # Do not overwrite contents of %metaentry hash for resource itself with 
13627: # hash populated for imported library file
13628:                         %metaentry = %currmetaentry;
13629:                         undef(%currmetaentry);
13630:                         if ($importmode eq 'part') {
13631: # Import as part(s)
13632:                            $importedparts=1;
13633: # We need to get the original file and the imported file to get the part order correct
13634: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
13635: # Load and inspect original file if we didn't do that already
13636:                            if ($#origfiletagids<0) {
13637:                                undef(%importedrespids);
13638:                                undef(%importedpartids);
13639:                                if ($origfile eq '') {
13640:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
13641:                                    $origfile=&getfile($origfilelocation);
13642:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13643:                                }
13644:                            }
13645:                            my @impfilepartids;
13646: # If <partorder> tag is included in metadata for the imported file
13647: # get the parts in the imported file from that.
13648:                            if (grep(/^partorder$/,@libfilekeys)) {
13649:                                %currmetaentry = %metaentry;
13650:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13651:                                                             $depthcount+1);
13652:                                %metaentry = %currmetaentry;
13653:                                undef(%currmetaentry);
13654:                                if ($libpartorder ne '') {
13655:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
13656:                                }
13657:                            } else {
13658: # If no <partorder> tag available, load and inspect imported file
13659:                                my $impfile=&getfile($location);
13660:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
13661:                            }
13662:                            if ($#impfilepartids>=0) {
13663: # This problem had parts
13664:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
13665:                            } else {
13666: # Importing by turning a single problem into a problem part
13667: # It gets the import-tags ID as part-ID
13668:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
13669:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
13670:                            }
13671:                         } else {
13672: # Import as problem or as normal import
13673:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
13674:                             unless ($importmode eq 'problem') {
13675: # Normal import
13676:                                 if (defined($token->[2]->{'id'})) {
13677:                                     $unikey.='_'.$token->[2]->{'id'};
13678:                                 }
13679:                             }
13680: # Check metadata for imported file to
13681: # see if it contained parts
13682:                             if (grep(/^partorder$/,@libfilekeys)) {
13683:                                 %currmetaentry = %metaentry;
13684:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
13685:                                                              $depthcount+1);
13686:                                 %metaentry = %currmetaentry;
13687:                                 undef(%currmetaentry);
13688:                                 if ($libpartorder ne '') {
13689:                                     $importedparts = 1;
13690:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
13691:                                 }
13692:                             }
13693:                         }
13694: 			if ($depthcount<20) {
13695: 			    my $metadata = 
13696: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
13697: 					  $depthcount+1);
13698: 			    foreach my $meta (split(',',$metadata)) {
13699: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
13700: 				$metathesekeys{$meta}=1;
13701: 			    }
13702:                         }
13703: 		    } else {
13704: #
13705: # Not importing, some other kind of non-package, non-library start tag
13706: # 
13707:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
13708:                         if (defined($token->[2]->{'id'})) {
13709:                             $unikey.='_'.$token->[2]->{'id'};
13710:                         }
13711: 			if (defined($token->[2]->{'name'})) { 
13712: 			    $unikey.='_'.$token->[2]->{'name'}; 
13713: 			}
13714: 			$metathesekeys{$unikey}=1;
13715: 			foreach my $param (@{$token->[3]}) {
13716: 			    $metaentry{':'.$unikey.'.'.$param} =
13717: 				$token->[2]->{$param};
13718: 			}
13719: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
13720: 			my $default=$metaentry{':'.$unikey.'.default'};
13721: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
13722: 		 # only ws inside the tag, and not in default, so use default
13723: 		 # as value
13724: 			    $metaentry{':'.$unikey}=$default;
13725: 			} elsif ( $internaltext =~ /\S/ ) {
13726: 		  # something interesting inside the tag
13727: 			    $metaentry{':'.$unikey}=$internaltext;
13728: 			} else {
13729: 		  # no interesting values, don't set a default
13730: 			}
13731: # end of not-a-package not-a-library import
13732: 		    }
13733: # end of not-a-package start tag
13734: 		}
13735: # the next is the end of "start tag"
13736: 	    }
13737: 	}
13738: 	my ($extension) = ($uri =~ /\.(\w+)$/);
13739: 	$extension = lc($extension);
13740: 	if ($extension eq 'htm') { $extension='html'; }
13741: 
13742: 	foreach my $key (keys(%packagetab)) {
13743: 	    #no specific packages #how's our extension
13744: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
13745: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
13746: 					 \%metathesekeys);
13747: 	}
13748: 
13749: 	if (!exists($metaentry{':packages'})
13750: 	    || $packagetab{"import_defaults&extension_$extension"}) {
13751: 	    foreach my $key (keys(%packagetab)) {
13752: 		#no specific packages well let's get default then
13753: 		if ($key!~/^default&/) { next; }
13754: 		&metadata_create_package_def($uri,$key,'default',
13755: 					     \%metathesekeys);
13756: 	    }
13757: 	}
13758: # are there custom rights to evaluate
13759: 	if ($metaentry{':copyright'} eq 'custom') {
13760: 
13761:     #
13762:     # Importing a rights file here
13763:     #
13764: 	    unless ($depthcount) {
13765: 		my $location=$metaentry{':customdistributionfile'};
13766: 		my $dir=$filename;
13767: 		$dir=~s|[^/]*$||;
13768: 		$location=&filelocation($dir,$location);
13769: 		my $rights_metadata =
13770: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
13771: 			      $depthcount+1);
13772: 		foreach my $rights (split(',',$rights_metadata)) {
13773: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
13774: 		    $metathesekeys{$rights}=1;
13775: 		}
13776: 	    }
13777: 	}
13778: 	# uniqifiy package listing
13779: 	my %seen;
13780: 	my @uniq_packages =
13781: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
13782: 	$metaentry{':packages'} = join(',',@uniq_packages);
13783: 
13784:         if (($importedresponses) || ($importedparts)) {
13785:             if ($importedparts) {
13786: # We had imported parts and need to rebuild partorder
13787:                 $metaentry{':partorder'}='';
13788:                 $metathesekeys{'partorder'}=1;
13789:             }
13790:             if ($importedresponses) {
13791: # We had imported responses and need to rebuil responseorder
13792:                 $metaentry{':responseorder'}='';
13793:                 $metathesekeys{'responseorder'}=1;
13794:             }
13795:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
13796:                 my $origid = $origfiletagids[$index+1];
13797:                 if ($origfiletagids[$index] eq 'part') {
13798: # Original part, part of the problem
13799:                     if ($importedparts) {
13800:                         $metaentry{':partorder'}.=','.$origid;
13801:                     }
13802:                 } elsif ($origfiletagids[$index] eq 'import') {
13803:                     if ($importedparts) {
13804: # We have imported parts at this position
13805:                         if ($importedpartids{$origid} ne '') {
13806:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
13807:                         }
13808:                     }
13809:                     if ($importedresponses) {
13810: # We have imported responses at this position
13811:                         if ($importedrespids{$origid} ne '') {
13812:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
13813:                         }
13814:                     }
13815:                 } else {
13816: # Original response item, part of the problem
13817:                     if ($importedresponses) {
13818:                         $metaentry{':responseorder'}.=','.$origid;
13819:                     }
13820:                 }
13821:             }
13822:             if ($importedparts) {
13823:                 $metaentry{':partorder'}=~s/^\,//;
13824:             }
13825:             if ($importedresponses) {
13826:                 $metaentry{':responseorder'}=~s/^\,//;
13827:             }
13828:         }
13829: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
13830: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
13831: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
13832:         unless ($liburi) {
13833: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
13834:         }
13835: # this is the end of "was not already recently cached
13836:     }
13837:     return $metaentry{':'.$what};
13838: }
13839: 
13840: sub metadata_create_package_def {
13841:     my ($uri,$key,$package,$metathesekeys)=@_;
13842:     my ($pack,$name,$subp)=split(/\&/,$key);
13843:     if ($subp eq 'default') { next; }
13844:     
13845:     if (defined($metaentry{':packages'})) {
13846: 	$metaentry{':packages'}.=','.$package;
13847:     } else {
13848: 	$metaentry{':packages'}=$package;
13849:     }
13850:     my $value=$packagetab{$key};
13851:     my $unikey;
13852:     $unikey='parameter_0_'.$name;
13853:     $metaentry{':'.$unikey.'.part'}=0;
13854:     $$metathesekeys{$unikey}=1;
13855:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
13856: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
13857:     }
13858:     if (defined($metaentry{':'.$unikey.'.default'})) {
13859: 	$metaentry{':'.$unikey}=
13860: 	    $metaentry{':'.$unikey.'.default'};
13861:     }
13862: }
13863: 
13864: sub metadata_generate_part0 {
13865:     my ($metadata,$metacache,$uri) = @_;
13866:     my %allnames;
13867:     foreach my $metakey (keys(%$metadata)) {
13868: 	if ($metakey=~/^parameter\_(.*)/) {
13869: 	  my $part=$$metacache{':'.$metakey.'.part'};
13870: 	  my $name=$$metacache{':'.$metakey.'.name'};
13871: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
13872: 	    $allnames{$name}=$part;
13873: 	  }
13874: 	}
13875:     }
13876:     foreach my $name (keys(%allnames)) {
13877:       $$metadata{"parameter_0_$name"}=1;
13878:       my $key=":parameter_0_$name";
13879:       $$metacache{"$key.part"}='0';
13880:       $$metacache{"$key.name"}=$name;
13881:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
13882: 					   $allnames{$name}.'_'.$name.
13883: 					   '.type'};
13884:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
13885: 			     '.display'};
13886:       my $expr='[Part: '.$allnames{$name}.']';
13887:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
13888:       $$metacache{"$key.display"}=$olddis;
13889:     }
13890: }
13891: 
13892: # ------------------------------------------------------ Devalidate title cache
13893: 
13894: sub devalidate_title_cache {
13895:     my ($url)=@_;
13896:     if (!$env{'request.course.id'}) { return; }
13897:     my $symb=&symbread($url);
13898:     if (!$symb) { return; }
13899:     my $key=$env{'request.course.id'}."\0".$symb;
13900:     &devalidate_cache_new('title',$key);
13901: }
13902: 
13903: # ------------------------------------------------- Get the title of a course
13904: 
13905: sub current_course_title {
13906:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
13907: }
13908: # ------------------------------------------------- Get the title of a resource
13909: 
13910: sub gettitle {
13911:     my $urlsymb=shift;
13912:     my $symb=&symbread($urlsymb);
13913:     if ($symb) {
13914: 	my $key=$env{'request.course.id'}."\0".$symb;
13915: 	my ($result,$cached)=&is_cached_new('title',$key);
13916: 	if (defined($cached)) { 
13917: 	    return $result;
13918: 	}
13919: 	my ($map,$resid,$url)=&decode_symb($symb);
13920: 	my $title='';
13921: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
13922: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
13923: 	} else {
13924: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
13925: 		    &GDBM_READER(),0640)) {
13926: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
13927: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
13928: 		untie(%bighash);
13929: 	    }
13930: 	}
13931: 	$title=~s/\&colon\;/\:/gs;
13932: 	if ($title) {
13933: # Remember both $symb and $title for dynamic metadata
13934:             $accesshash{$symb.'___crstitle'}=$title;
13935:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
13936: # Cache this title and then return it
13937: 	    return &do_cache_new('title',$key,$title,600);
13938: 	}
13939: 	$urlsymb=$url;
13940:     }
13941:     my $title=&metadata($urlsymb,'title');
13942:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
13943:     return $title;
13944: }
13945: 
13946: sub get_slot {
13947:     my ($which,$cnum,$cdom)=@_;
13948:     if (!$cnum || !$cdom) {
13949: 	(undef,my $courseid)=&whichuser();
13950: 	$cdom=$env{'course.'.$courseid.'.domain'};
13951: 	$cnum=$env{'course.'.$courseid.'.num'};
13952:     }
13953:     my $key=join("\0",'slots',$cdom,$cnum,$which);
13954:     my %slotinfo;
13955:     if (exists($remembered{$key})) {
13956: 	$slotinfo{$which} = $remembered{$key};
13957:     } else {
13958: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
13959: 	&Apache::lonhomework::showhash(%slotinfo);
13960: 	my ($tmp)=keys(%slotinfo);
13961: 	if ($tmp=~/^error:/) { return (); }
13962: 	$remembered{$key} = $slotinfo{$which};
13963:     }
13964:     if (ref($slotinfo{$which}) eq 'HASH') {
13965: 	return %{$slotinfo{$which}};
13966:     }
13967:     return $slotinfo{$which};
13968: }
13969: 
13970: sub get_reservable_slots {
13971:     my ($cnum,$cdom,$uname,$udom) = @_;
13972:     my $now = time;
13973:     my $reservable_info;
13974:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
13975:     if (exists($remembered{$key})) {
13976:         $reservable_info = $remembered{$key};
13977:     } else {
13978:         my %resv;
13979:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
13980:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
13981:         $reservable_info = \%resv;
13982:         $remembered{$key} = $reservable_info;
13983:     }
13984:     return $reservable_info;
13985: }
13986: 
13987: sub get_course_slots {
13988:     my ($cnum,$cdom) = @_;
13989:     my $hashid=$cnum.':'.$cdom;
13990:     my ($result,$cached) = &is_cached_new('allslots',$hashid);
13991:     if (defined($cached)) {
13992:         if (ref($result) eq 'HASH') {
13993:             return %{$result};
13994:         }
13995:     } else {
13996:         my %slots=&dump('slots',$cdom,$cnum);
13997:         my ($tmp) = keys(%slots);
13998:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
13999:             &do_cache_new('allslots',$hashid,\%slots,600);
14000:             return %slots;
14001:         }
14002:     }
14003:     return;
14004: }
14005: 
14006: sub devalidate_slots_cache {
14007:     my ($cnum,$cdom)=@_;
14008:     my $hashid=$cnum.':'.$cdom;
14009:     &devalidate_cache_new('allslots',$hashid);
14010: }
14011: 
14012: sub get_coursechange {
14013:     my ($cdom,$cnum) = @_;
14014:     if ($cdom eq '' || $cnum eq '') {
14015:         return unless ($env{'request.course.id'});
14016:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14017:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14018:     }
14019:     my $hashid=$cdom.'_'.$cnum;
14020:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
14021:     if ((defined($cached)) && ($change ne '')) {
14022:         return $change;
14023:     } else {
14024:         my %crshash;
14025:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
14026:         if ($crshash{'internal.contentchange'} eq '') {
14027:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14028:             if ($change eq '') {
14029:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14030:                 $change = $crshash{'internal.created'};
14031:             }
14032:         } else {
14033:             $change = $crshash{'internal.contentchange'};
14034:         }
14035:         my $cachetime = 600;
14036:         &do_cache_new('crschange',$hashid,$change,$cachetime);
14037:     }
14038:     return $change;
14039: }
14040: 
14041: sub devalidate_coursechange_cache {
14042:     my ($cdom,$cnum)=@_;
14043:     my $hashid=$cdom.'_'.$cnum;
14044:     &devalidate_cache_new('crschange',$hashid);
14045: }
14046: 
14047: sub get_suppchange {
14048:     my ($cdom,$cnum) = @_;
14049:     if ($cdom eq '' || $cnum eq '') {
14050:         return unless ($env{'request.course.id'});
14051:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
14052:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
14053:     }
14054:     my $hashid=$cdom.'_'.$cnum;
14055:     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
14056:     if ((defined($cached)) && ($change ne '')) {
14057:         return $change;
14058:     } else {
14059:         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
14060:         if ($crshash{'internal.supplementalchange'} eq '') {
14061:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
14062:             if ($change eq '') {
14063:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
14064:                 $change = $crshash{'internal.created'};
14065:             }
14066:         } else {
14067:             $change = $crshash{'internal.supplementalchange'};
14068:         }
14069:         my $cachetime = 600;
14070:         &do_cache_new('suppchange',$hashid,$change,$cachetime);
14071:     }
14072:     return $change;
14073: }
14074: 
14075: sub devalidate_suppchange_cache {
14076:     my ($cdom,$cnum)=@_;
14077:     my $hashid=$cdom.'_'.$cnum;
14078:     &devalidate_cache_new('suppchange',$hashid);
14079: }
14080: 
14081: sub update_supp_caches {
14082:     my ($cdom,$cnum) = @_;
14083:     my %servers = &internet_dom_servers($cdom);
14084:     my @ids=&current_machine_ids();
14085:     foreach my $server (keys(%servers)) {
14086:         next if (grep(/^\Q$server\E$/,@ids));
14087:         my $hashid=$cnum.':'.$cdom;
14088:         my $cachekey = &escape('showsupp').':'.&escape($hashid);
14089:         &remote_devalidate_cache($server,[$cachekey]);
14090:     }
14091:     &has_unhidden_suppfiles($cnum,$cdom,1,1);
14092:     &count_supptools($cnum,$cdom,1);
14093:     my $now = time;
14094:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
14095:         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
14096:     }
14097:     &put('environment',{'internal.supplementalchange' => $now},
14098:          $cdom,$cnum);
14099:     &Apache::lonnet::appenv(
14100:         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
14101:     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
14102: }
14103: 
14104: # ------------------------------------------------- Update symbolic store links
14105: 
14106: sub symblist {
14107:     my ($mapname,%newhash)=@_;
14108:     $mapname=&deversion(&declutter($mapname));
14109:     my %hash;
14110:     if (($env{'request.course.fn'}) && (%newhash)) {
14111:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14112:                       &GDBM_WRCREAT(),0640)) {
14113: 	    foreach my $url (keys(%newhash)) {
14114: 		next if ($url eq 'last_known'
14115: 			 && $env{'form.no_update_last_known'});
14116: 		$hash{declutter($url)}=&encode_symb($mapname,
14117: 						    $newhash{$url}->[1],
14118: 						    $newhash{$url}->[0]);
14119:             }
14120:             if (untie(%hash)) {
14121: 		return 'ok';
14122:             }
14123:         }
14124:     }
14125:     return 'error';
14126: }
14127: 
14128: # --------------------------------------------------------------- Verify a symb
14129: 
14130: sub symbverify {
14131:     my ($symb,$thisurl,$encstate)=@_;
14132:     my $thisfn=$thisurl;
14133:     $thisfn=&declutter($thisfn);
14134: # direct jump to resource in page or to a sequence - will construct own symbs
14135:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
14136: # check URL part
14137:     my ($map,$resid,$url)=&decode_symb($symb);
14138: 
14139:     unless ($url eq $thisfn) { return 0; }
14140: 
14141:     $symb=&symbclean($symb);
14142:     $thisurl=&deversion($thisurl);
14143:     $thisfn=&deversion($thisfn);
14144: 
14145:     my %bighash;
14146:     my $okay=0;
14147: 
14148:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14149:                             &GDBM_READER(),0640)) {
14150:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
14151:             $thisurl =~ s/\?.+$//;
14152:             if ($map =~ m{^uploaded/.+\.page$}) {
14153:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
14154:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
14155:             }
14156:         }
14157:         my $ids;
14158:         if ($map =~ m{^uploaded/.+\.page$}) {
14159:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
14160:         } else {
14161:             $ids=$bighash{'ids_'.&clutter($thisurl)};
14162:         }
14163:         unless ($ids) {
14164:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
14165:             $ids=$bighash{$idkey};
14166:         }
14167:         if ($ids) {
14168: # ------------------------------------------------------------------- Has ID(s)
14169:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
14170:                 $symb =~ s/\?.+$//;
14171:             }
14172: 	    foreach my $id (split(/\,/,$ids)) {
14173: 	       my ($mapid,$resid)=split(/\./,$id);
14174:                if (
14175:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
14176:    eq $symb) {
14177:                    if (ref($encstate)) {
14178:                        $$encstate = $bighash{'encrypted_'.$id};
14179:                    }
14180: 		   if (($env{'request.role.adv'}) ||
14181: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
14182:                        ($thisurl eq '/adm/navmaps')) {
14183: 		       $okay=1;
14184:                        last;
14185: 		   }
14186: 	       }
14187: 	   }
14188:         }
14189: 	untie(%bighash);
14190:     }
14191:     return $okay;
14192: }
14193: 
14194: # --------------------------------------------------------------- Clean-up symb
14195: 
14196: sub symbclean {
14197:     my $symb=shift;
14198:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14199: # remove version from map
14200:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
14201: 
14202: # remove version from URL
14203:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
14204: 
14205: # remove wrapper
14206: 
14207:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
14208:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
14209:     return $symb;
14210: }
14211: 
14212: # ---------------------------------------------- Split symb to find map and url
14213: 
14214: sub encode_symb {
14215:     my ($map,$resid,$url)=@_;
14216:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
14217: }
14218: 
14219: sub decode_symb {
14220:     my $symb=shift;
14221:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
14222:     my ($map,$resid,$url)=split(/___/,$symb);
14223:     return (&fixversion($map),$resid,&fixversion($url));
14224: }
14225: 
14226: sub fixversion {
14227:     my $fn=shift;
14228:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
14229:     my %bighash;
14230:     my $uri=&clutter($fn);
14231:     my $key=$env{'request.course.id'}.'_'.$uri;
14232: # is this cached?
14233:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
14234:     if (defined($cached)) { return $result; }
14235: # unfortunately not cached, or expired
14236:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14237: 	    &GDBM_READER(),0640)) {
14238:  	if ($bighash{'version_'.$uri}) {
14239:  	    my $version=$bighash{'version_'.$uri};
14240:  	    unless (($version eq 'mostrecent') || 
14241: 		    ($version==&getversion($uri))) {
14242:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
14243:  	    }
14244:  	}
14245:  	untie %bighash;
14246:     }
14247:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
14248: }
14249: 
14250: sub deversion {
14251:     my $url=shift;
14252:     $url=~s/\.\d+\.(\w+)$/\.$1/;
14253:     return $url;
14254: }
14255: 
14256: # ------------------------------------------------------ Return symb list entry
14257: 
14258: sub symbread {
14259:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
14260:         $ignoresymbdb,$noenccheck)=@_;
14261:     my $cache_str='request.symbread.cached.'.$thisfn;
14262:     if (defined($env{$cache_str})) {
14263:         unless (ref($possibles) eq 'HASH') {
14264:             if ($ignorecachednull) {
14265:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
14266:             } else {
14267:                 return $env{$cache_str};
14268:             }
14269:         }
14270:     }
14271: # no filename provided? try from environment
14272:     unless ($thisfn) {
14273:         if ($env{'request.symb'}) {
14274:             return $env{$cache_str}=&symbclean($env{'request.symb'});
14275: 	}
14276: 	$thisfn=$env{'request.filename'};
14277:     }
14278:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
14279: # is that filename actually a symb? Verify, clean, and return
14280:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
14281: 	if (&symbverify($thisfn,$1)) {
14282: 	    return $env{$cache_str}=&symbclean($thisfn);
14283: 	}
14284:     }
14285:     $thisfn=declutter($thisfn);
14286:     my %hash;
14287:     my %bighash;
14288:     my $syval='';
14289:     if (($env{'request.course.fn'}) && ($thisfn)) {
14290:         unless ($ignoresymbdb) {
14291:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
14292:                           &GDBM_READER(),0640)) {
14293: 	        $syval=$hash{$thisfn};
14294:                 untie(%hash);
14295:             }
14296:             if ($syval && $checkforblock) {
14297:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
14298:                 if (@blockers) {
14299:                     $syval='';
14300:                 }
14301:             }
14302:         }
14303: # ---------------------------------------------------------- There was an entry
14304:         if ($syval) {
14305: 	    #unless ($syval=~/\_\d+$/) {
14306: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
14307: 		    #&appenv({'request.ambiguous' => $thisfn});
14308: 		    #return $env{$cache_str}='';
14309: 		#}    
14310: 		#$syval.=$1;
14311: 	    #}
14312:         } else {
14313: # ------------------------------------------------------- Was not in symb table
14314:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
14315:                             &GDBM_READER(),0640)) {
14316: # ---------------------------------------------- Get ID(s) for current resource
14317:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
14318:               unless ($ids) { 
14319:                  $ids=$bighash{'ids_/'.$thisfn};
14320:               }
14321:               unless ($ids) {
14322: # alias?
14323: 		  $ids=$bighash{'mapalias_'.$thisfn};
14324:               }
14325:               if ($ids) {
14326: # ------------------------------------------------------------------- Has ID(s)
14327:                  my @possibilities=split(/\,/,$ids);
14328:                  if ($#possibilities==0) {
14329: # ----------------------------------------------- There is only one possibility
14330: 		     my ($mapid,$resid)=split(/\./,$ids);
14331: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
14332: 						    $resid,$thisfn);
14333:                      if (ref($possibles) eq 'HASH') {
14334:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14335:                              $possibles->{$syval} = 1;
14336:                          }
14337:                      }
14338:                      if ($checkforblock) {
14339:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
14340:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
14341:                              if (@blockers) {
14342:                                  $syval = '';
14343:                                  untie(%bighash);
14344:                                  return $env{$cache_str}='';
14345:                              }
14346:                          }
14347:                      }
14348:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
14349: # ------------------------------------------ There is more than one possibility
14350:                      my $realpossible=0;
14351:                      foreach my $id (@possibilities) {
14352: 			 my $file=$bighash{'src_'.$id};
14353:                          my $canaccess;
14354:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
14355:                              $canaccess = 1;
14356:                          } else { 
14357:                              $canaccess = &allowed('bre',$file);
14358:                          }
14359:                          if ($canaccess) {
14360:          		     my ($mapid,$resid)=split(/\./,$id);
14361:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
14362:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
14363: 						             $resid,$thisfn);
14364:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
14365:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
14366:                                  if ($checkforblock) {
14367:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
14368:                                      if (@blockers > 0) {
14369:                                          $syval = '';
14370:                                      } else {
14371:                                          $syval = $poss_syval;
14372:                                          $realpossible++;
14373:                                      }
14374:                                  } else {
14375:                                      $syval = $poss_syval;
14376:                                      $realpossible++;
14377:                                  }
14378:                                  if ($syval) {
14379:                                      if (ref($possibles) eq 'HASH') {
14380:                                          $possibles->{$syval} = 1;
14381:                                      }
14382:                                  }
14383:                              }
14384: 			 }
14385:                      }
14386: 		     if ($realpossible!=1) { $syval=''; }
14387:                  } else {
14388:                      $syval='';
14389:                  }
14390: 	      }
14391:               untie(%bighash);
14392:            }
14393:         }
14394:         if ($syval) {
14395: 	    return $env{$cache_str}=$syval;
14396:         }
14397:     }
14398:     &appenv({'request.ambiguous' => $thisfn});
14399:     return $env{$cache_str}='';
14400: }
14401: 
14402: # ---------------------------------------------------------- Return random seed
14403: 
14404: sub numval {
14405:     my $txt=shift;
14406:     $txt=~tr/A-J/0-9/;
14407:     $txt=~tr/a-j/0-9/;
14408:     $txt=~tr/K-T/0-9/;
14409:     $txt=~tr/k-t/0-9/;
14410:     $txt=~tr/U-Z/0-5/;
14411:     $txt=~tr/u-z/0-5/;
14412:     $txt=~s/\D//g;
14413:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
14414:     return int($txt);
14415: }
14416: 
14417: sub numval2 {
14418:     my $txt=shift;
14419:     $txt=~tr/A-J/0-9/;
14420:     $txt=~tr/a-j/0-9/;
14421:     $txt=~tr/K-T/0-9/;
14422:     $txt=~tr/k-t/0-9/;
14423:     $txt=~tr/U-Z/0-5/;
14424:     $txt=~tr/u-z/0-5/;
14425:     $txt=~s/\D//g;
14426:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14427:     my $total;
14428:     foreach my $val (@txts) { $total+=$val; }
14429:     if ($_64bit) { if ($total > 2**32) { return -1; } }
14430:     return int($total);
14431: }
14432: 
14433: sub numval3 {
14434:     use integer;
14435:     my $txt=shift;
14436:     $txt=~tr/A-J/0-9/;
14437:     $txt=~tr/a-j/0-9/;
14438:     $txt=~tr/K-T/0-9/;
14439:     $txt=~tr/k-t/0-9/;
14440:     $txt=~tr/U-Z/0-5/;
14441:     $txt=~tr/u-z/0-5/;
14442:     $txt=~s/\D//g;
14443:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
14444:     my $total;
14445:     foreach my $val (@txts) { $total+=$val; }
14446:     if ($_64bit) { $total=(($total<<32)>>32); }
14447:     return $total;
14448: }
14449: 
14450: sub digest {
14451:     my ($data)=@_;
14452:     my $digest=&Digest::MD5::md5($data);
14453:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
14454:     my ($e,$f);
14455:     {
14456:         use integer;
14457:         $e=($a+$b);
14458:         $f=($c+$d);
14459:         if ($_64bit) {
14460:             $e=(($e<<32)>>32);
14461:             $f=(($f<<32)>>32);
14462:         }
14463:     }
14464:     if (wantarray) {
14465: 	return ($e,$f);
14466:     } else {
14467: 	my $g;
14468: 	{
14469: 	    use integer;
14470: 	    $g=($e+$f);
14471: 	    if ($_64bit) {
14472: 		$g=(($g<<32)>>32);
14473: 	    }
14474: 	}
14475: 	return $g;
14476:     }
14477: }
14478: 
14479: sub latest_rnd_algorithm_id {
14480:     return '64bit5';
14481: }
14482: 
14483: sub get_rand_alg {
14484:     my ($courseid)=@_;
14485:     if (!$courseid) { $courseid=(&whichuser())[1]; }
14486:     if ($courseid) {
14487: 	return $env{"course.$courseid.rndseed"};
14488:     }
14489:     return &latest_rnd_algorithm_id();
14490: }
14491: 
14492: sub validCODE {
14493:     my ($CODE)=@_;
14494:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
14495:     return 0;
14496: }
14497: 
14498: sub getCODE {
14499:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
14500:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
14501: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
14502: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
14503: 	return $Apache::lonhomework::history{'resource.CODE'};
14504:     }
14505:     return undef;
14506: }
14507: #
14508: #  Determines the random seed for a specific context:
14509: #
14510: # parameters:
14511: #   symb      - in course context the symb for the seed.
14512: #   course_id - The course id of the form domain_coursenum.
14513: #   domain    - Domain for the user.
14514: #   course    - Course for the user.
14515: #   cenv      - environment of the course.
14516: #
14517: # NOTE:
14518: #   All parameters are picked out of the environment if missing
14519: #   or not defined.
14520: #   If a symb cannot be determined the current time is used instead.
14521: #
14522: #  For a given well defined symb, courside, domain, username,
14523: #  and course environment, the seed is reproducible.
14524: #
14525: sub rndseed {
14526:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
14527:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
14528:     if (!defined($symb)) {
14529: 	unless ($symb=$wsymb) { return time; }
14530:     }
14531:     if (!defined $courseid) { 
14532: 	$courseid=$wcourseid; 
14533:     }
14534:     if (!defined $domain) { $domain=$wdomain; }
14535:     if (!defined $username) { $username=$wusername }
14536: 
14537:     my $which;
14538:     if (defined($cenv->{'rndseed'})) {
14539: 	$which = $cenv->{'rndseed'};
14540:     } else {
14541: 	$which =&get_rand_alg($courseid);
14542:     }
14543:     if (defined(&getCODE())) {
14544: 
14545: 	if ($which eq '64bit5') {
14546: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
14547: 	} elsif ($which eq '64bit4') {
14548: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
14549: 	} else {
14550: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
14551: 	}
14552:     } elsif ($which eq '64bit5') {
14553: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
14554:     } elsif ($which eq '64bit4') {
14555: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
14556:     } elsif ($which eq '64bit3') {
14557: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
14558:     } elsif ($which eq '64bit2') {
14559: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
14560:     } elsif ($which eq '64bit') {
14561: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
14562:     }
14563:     return &rndseed_32bit($symb,$courseid,$domain,$username);
14564: }
14565: 
14566: sub rndseed_32bit {
14567:     my ($symb,$courseid,$domain,$username)=@_;
14568:     {
14569: 	use integer;
14570: 	my $symbchck=unpack("%32C*",$symb) << 27;
14571: 	my $symbseed=numval($symb) << 22;
14572: 	my $namechck=unpack("%32C*",$username) << 17;
14573: 	my $nameseed=numval($username) << 12;
14574: 	my $domainseed=unpack("%32C*",$domain) << 7;
14575: 	my $courseseed=unpack("%32C*",$courseid);
14576: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
14577: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14578: 	#&logthis("rndseed :$num:$symb");
14579: 	if ($_64bit) { $num=(($num<<32)>>32); }
14580: 	return $num;
14581:     }
14582: }
14583: 
14584: sub rndseed_64bit {
14585:     my ($symb,$courseid,$domain,$username)=@_;
14586:     {
14587: 	use integer;
14588: 	my $symbchck=unpack("%32S*",$symb) << 21;
14589: 	my $symbseed=numval($symb) << 10;
14590: 	my $namechck=unpack("%32S*",$username);
14591: 	
14592: 	my $nameseed=numval($username) << 21;
14593: 	my $domainseed=unpack("%32S*",$domain) << 10;
14594: 	my $courseseed=unpack("%32S*",$courseid);
14595: 	
14596: 	my $num1=$symbchck+$symbseed+$namechck;
14597: 	my $num2=$nameseed+$domainseed+$courseseed;
14598: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14599: 	#&logthis("rndseed :$num:$symb");
14600: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14601: 	return "$num1,$num2";
14602:     }
14603: }
14604: 
14605: sub rndseed_64bit2 {
14606:     my ($symb,$courseid,$domain,$username)=@_;
14607:     {
14608: 	use integer;
14609: 	# strings need to be an even # of cahracters long, it it is odd the
14610:         # last characters gets thrown away
14611: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14612: 	my $symbseed=numval($symb) << 10;
14613: 	my $namechck=unpack("%32S*",$username.' ');
14614: 	
14615: 	my $nameseed=numval($username) << 21;
14616: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14617: 	my $courseseed=unpack("%32S*",$courseid.' ');
14618: 	
14619: 	my $num1=$symbchck+$symbseed+$namechck;
14620: 	my $num2=$nameseed+$domainseed+$courseseed;
14621: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14622: 	#&logthis("rndseed :$num:$symb");
14623: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14624: 	return "$num1,$num2";
14625:     }
14626: }
14627: 
14628: sub rndseed_64bit3 {
14629:     my ($symb,$courseid,$domain,$username)=@_;
14630:     {
14631: 	use integer;
14632: 	# strings need to be an even # of cahracters long, it it is odd the
14633:         # last characters gets thrown away
14634: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14635: 	my $symbseed=numval2($symb) << 10;
14636: 	my $namechck=unpack("%32S*",$username.' ');
14637: 	
14638: 	my $nameseed=numval2($username) << 21;
14639: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14640: 	my $courseseed=unpack("%32S*",$courseid.' ');
14641: 	
14642: 	my $num1=$symbchck+$symbseed+$namechck;
14643: 	my $num2=$nameseed+$domainseed+$courseseed;
14644: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14645: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14646: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14647: 	
14648: 	return "$num1:$num2";
14649:     }
14650: }
14651: 
14652: sub rndseed_64bit4 {
14653:     my ($symb,$courseid,$domain,$username)=@_;
14654:     {
14655: 	use integer;
14656: 	# strings need to be an even # of cahracters long, it it is odd the
14657:         # last characters gets thrown away
14658: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
14659: 	my $symbseed=numval3($symb) << 10;
14660: 	my $namechck=unpack("%32S*",$username.' ');
14661: 	
14662: 	my $nameseed=numval3($username) << 21;
14663: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
14664: 	my $courseseed=unpack("%32S*",$courseid.' ');
14665: 	
14666: 	my $num1=$symbchck+$symbseed+$namechck;
14667: 	my $num2=$nameseed+$domainseed+$courseseed;
14668: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
14669: 	#&logthis("rndseed :$num1:$num2:$_64bit");
14670: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
14671: 	
14672: 	return "$num1:$num2";
14673:     }
14674: }
14675: 
14676: sub rndseed_64bit5 {
14677:     my ($symb,$courseid,$domain,$username)=@_;
14678:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
14679:     return "$num1:$num2";
14680: }
14681: 
14682: sub rndseed_CODE_64bit {
14683:     my ($symb,$courseid,$domain,$username)=@_;
14684:     {
14685: 	use integer;
14686: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14687: 	my $symbseed=numval2($symb);
14688: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14689: 	my $CODEseed=numval(&getCODE());
14690: 	my $courseseed=unpack("%32S*",$courseid.' ');
14691: 	my $num1=$symbseed+$CODEchck;
14692: 	my $num2=$CODEseed+$courseseed+$symbchck;
14693: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14694: 	#&logthis("rndseed :$num1:$num2:$symb");
14695: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14696: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14697: 	return "$num1:$num2";
14698:     }
14699: }
14700: 
14701: sub rndseed_CODE_64bit4 {
14702:     my ($symb,$courseid,$domain,$username)=@_;
14703:     {
14704: 	use integer;
14705: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
14706: 	my $symbseed=numval3($symb);
14707: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
14708: 	my $CODEseed=numval3(&getCODE());
14709: 	my $courseseed=unpack("%32S*",$courseid.' ');
14710: 	my $num1=$symbseed+$CODEchck;
14711: 	my $num2=$CODEseed+$courseseed+$symbchck;
14712: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
14713: 	#&logthis("rndseed :$num1:$num2:$symb");
14714: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
14715: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
14716: 	return "$num1:$num2";
14717:     }
14718: }
14719: 
14720: sub rndseed_CODE_64bit5 {
14721:     my ($symb,$courseid,$domain,$username)=@_;
14722:     my $code = &getCODE();
14723:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
14724:     return "$num1:$num2";
14725: }
14726: 
14727: sub setup_random_from_rndseed {
14728:     my ($rndseed)=@_;
14729:     if ($rndseed =~/([,:])/) {
14730:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
14731:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
14732:             &Math::Random::random_set_seed_from_phrase($rndseed);
14733:         } else {
14734:             &Math::Random::random_set_seed($num1,$num2);
14735:         }
14736:     } else {
14737: 	&Math::Random::random_set_seed_from_phrase($rndseed);
14738:     }
14739: }
14740: 
14741: sub latest_receipt_algorithm_id {
14742:     return 'receipt3';
14743: }
14744: 
14745: sub recunique {
14746:     my $fucourseid=shift;
14747:     my $unique;
14748:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
14749: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14750: 	$unique=$env{"course.$fucourseid.internal.encseed"};
14751:     } else {
14752: 	$unique=$perlvar{'lonReceipt'};
14753:     }
14754:     return unpack("%32C*",$unique);
14755: }
14756: 
14757: sub recprefix {
14758:     my $fucourseid=shift;
14759:     my $prefix;
14760:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
14761: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
14762: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
14763:     } else {
14764: 	$prefix=$perlvar{'lonHostID'};
14765:     }
14766:     return unpack("%32C*",$prefix);
14767: }
14768: 
14769: sub ireceipt {
14770:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
14771: 
14772:     my $return =&recprefix($fucourseid).'-';
14773: 
14774:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
14775: 	$env{'request.state'} eq 'construct') {
14776: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
14777: 	return $return;
14778:     }
14779: 
14780:     my $cuname=unpack("%32C*",$funame);
14781:     my $cudom=unpack("%32C*",$fudom);
14782:     my $cucourseid=unpack("%32C*",$fucourseid);
14783:     my $cusymb=unpack("%32C*",$fusymb);
14784:     my $cunique=&recunique($fucourseid);
14785:     my $cpart=unpack("%32S*",$part);
14786:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
14787: 
14788: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
14789: 			       
14790: 	$return.= ($cunique%$cuname+
14791: 		   $cunique%$cudom+
14792: 		   $cusymb%$cuname+
14793: 		   $cusymb%$cudom+
14794: 		   $cucourseid%$cuname+
14795: 		   $cucourseid%$cudom+
14796: 		   $cpart%$cuname+
14797: 		   $cpart%$cudom);
14798:     } else {
14799: 	$return.= ($cunique%$cuname+
14800: 		   $cunique%$cudom+
14801: 		   $cusymb%$cuname+
14802: 		   $cusymb%$cudom+
14803: 		   $cucourseid%$cuname+
14804: 		   $cucourseid%$cudom);
14805:     }
14806:     return $return;
14807: }
14808: 
14809: sub receipt {
14810:     my ($part)=@_;
14811:     my ($symb,$courseid,$domain,$name) = &whichuser();
14812:     return &ireceipt($name,$domain,$courseid,$symb,$part);
14813: }
14814: 
14815: sub whichuser {
14816:     my ($passedsymb)=@_;
14817:     my ($symb,$courseid,$domain,$name,$publicuser);
14818:     if (defined($env{'form.grade_symb'})) {
14819: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
14820: 	my $allowed=&allowed('vgr',$tmp_courseid);
14821: 	if (!$allowed &&
14822: 	    exists($env{'request.course.sec'}) &&
14823: 	    $env{'request.course.sec'} !~ /^\s*$/) {
14824: 	    $allowed=&allowed('vgr',$tmp_courseid.
14825: 			      '/'.$env{'request.course.sec'});
14826: 	}
14827: 	if ($allowed) {
14828: 	    ($symb)=&get_env_multiple('form.grade_symb');
14829: 	    $courseid=$tmp_courseid;
14830: 	    ($domain)=&get_env_multiple('form.grade_domain');
14831: 	    ($name)=&get_env_multiple('form.grade_username');
14832: 	    return ($symb,$courseid,$domain,$name,$publicuser);
14833: 	}
14834:     }
14835:     if (!$passedsymb) {
14836: 	$symb=&symbread();
14837:     } else {
14838: 	$symb=$passedsymb;
14839:     }
14840:     $courseid=$env{'request.course.id'};
14841:     $domain=$env{'user.domain'};
14842:     $name=$env{'user.name'};
14843:     if ($name eq 'public' && $domain eq 'public') {
14844: 	if (!defined($env{'form.username'})) {
14845: 	    $env{'form.username'}.=time.rand(10000000);
14846: 	}
14847: 	$name.=$env{'form.username'};
14848:     }
14849:     return ($symb,$courseid,$domain,$name,$publicuser);
14850: 
14851: }
14852: 
14853: # ------------------------------------------------------------ Serves up a file
14854: # returns either the contents of the file or 
14855: # -1 if the file doesn't exist
14856: #
14857: # if the target is a file that was uploaded via DOCS, 
14858: # a check will be made to see if a current copy exists on the local server,
14859: # if it does this will be served, otherwise a copy will be retrieved from
14860: # the home server for the course and stored in /home/httpd/html/userfiles on
14861: # the local server.   
14862: 
14863: sub getfile {
14864:     my ($file) = @_;
14865:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
14866:     &repcopy($file);
14867:     return &readfile($file);
14868: }
14869: 
14870: sub repcopy_userfile {
14871:     my ($file)=@_;
14872:     my $londocroot = $perlvar{'lonDocRoot'};
14873:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
14874:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
14875:     my ($cdom,$cnum,$filename) = 
14876: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
14877:     my $uri="/uploaded/$cdom/$cnum/$filename";
14878:     if (-e "$file") {
14879: # we already have a local copy, check it out
14880: 	my @fileinfo = stat($file);
14881: 	my $rtncode;
14882: 	my $info;
14883: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
14884: 	if ($lwpresp ne 'ok') {
14885: # there is no such file anymore, even though we had a local copy
14886: 	    if ($rtncode eq '404') {
14887: 		unlink($file);
14888: 	    }
14889: 	    return -1;
14890: 	}
14891: 	if ($info < $fileinfo[9]) {
14892: # nice, the file we have is up-to-date, just say okay
14893: 	    return 'ok';
14894: 	} else {
14895: # the file is outdated, get rid of it
14896: 	    unlink($file);
14897: 	}
14898:     }
14899: # one way or the other, at this point, we don't have the file
14900: # construct the correct path for the file
14901:     my @parts = ($cdom,$cnum); 
14902:     if ($filename =~ m|^(.+)/[^/]+$|) {
14903: 	push @parts, split(/\//,$1);
14904:     }
14905:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
14906:     foreach my $part (@parts) {
14907: 	$path .= '/'.$part;
14908: 	if (!-e $path) {
14909: 	    mkdir($path,0770);
14910: 	}
14911:     }
14912: # now the path exists for sure
14913: # get a user agent
14914:     my $transferfile=$file.'.in.transfer';
14915: # FIXME: this should flock
14916:     if (-e $transferfile) { return 'ok'; }
14917:     my $request;
14918:     $uri=~s/^\///;
14919:     my $homeserver = &homeserver($cnum,$cdom);
14920:     my $hostname = &hostname($homeserver);
14921:     my $protocol = $protocol{$homeserver};
14922:     $protocol = 'http' if ($protocol ne 'https');
14923:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
14924:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
14925: # did it work?
14926:     if ($response->is_error()) {
14927: 	unlink($transferfile);
14928: 	&logthis("Userfile repcopy failed for $uri");
14929: 	return -1;
14930:     }
14931: # worked, rename the transfer file
14932:     rename($transferfile,$file);
14933:     return 'ok';
14934: }
14935: 
14936: sub tokenwrapper {
14937:     my $uri=shift;
14938:     $uri=~s|^https?\://([^/]+)||;
14939:     $uri=~s|^/||;
14940:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
14941:     my $token=$1;
14942:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
14943:     if ($udom && $uname && $file) {
14944: 	$file=~s|(\?\.*)*$||;
14945:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
14946:         my $homeserver = &homeserver($uname,$udom);
14947:         my $hostname = &hostname($homeserver);
14948:         my $protocol = $protocol{$homeserver};
14949:         $protocol = 'http' if ($protocol ne 'https');
14950:         return $protocol.'://'.$hostname.'/'.$uri.
14951:                (($uri=~/\?/)?'&':'?').'token='.$token.
14952:                                '&tokenissued='.$perlvar{'lonHostID'};
14953:     } else {
14954:         return '/adm/notfound.html';
14955:     }
14956: }
14957: 
14958: # call with reqtype HEAD: get last modification time
14959: # call with reqtype GET: get the file contents
14960: # Do not call this with reqtype GET for large files! It loads everything into memory
14961: #
14962: sub getuploaded {
14963:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
14964:     $uri=~s/^\///;
14965:     my $homeserver = &homeserver($cnum,$cdom);
14966:     my $hostname = &hostname($homeserver);
14967:     my $protocol = $protocol{$homeserver};
14968:     $protocol = 'http' if ($protocol ne 'https');
14969:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
14970:     my $request=new HTTP::Request($reqtype,$uri);
14971:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
14972:     $$rtncode = $response->code;
14973:     if (! $response->is_success()) {
14974: 	return 'failed';
14975:     }      
14976:     if ($reqtype eq 'HEAD') {
14977: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
14978:     } elsif ($reqtype eq 'GET') {
14979: 	$$info = $response->content;
14980:     }
14981:     return 'ok';
14982: }
14983: 
14984: sub readfile {
14985:     my $file = shift;
14986:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
14987:     my $fh;
14988:     open($fh,"<",$file);
14989:     my $a='';
14990:     while (my $line = <$fh>) { $a .= $line; }
14991:     return $a;
14992: }
14993: 
14994: sub filelocation {
14995:     my ($dir,$file) = @_;
14996:     my $location;
14997:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
14998: 
14999:     if ($file =~ m-^/adm/-) {
15000: 	$file=~s-^/adm/wrapper/-/-;
15001: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15002:     }
15003: 
15004:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
15005:         $location = $file;
15006:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
15007:         my ($udom,$uname,$filename)=
15008:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
15009:         my $home=&homeserver($uname,$udom);
15010:         my $is_me=0;
15011:         my @ids=&current_machine_ids();
15012:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
15013:         if ($is_me) {
15014:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
15015:         } else {
15016:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
15017:   	      $udom.'/'.$uname.'/'.$filename;
15018:         }
15019:     } elsif ($file =~ m-^/adm/-) {
15020: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
15021:     } else {
15022:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
15023:         $file=~s:^/(res|priv)/:/:;
15024:         my $space=$1;
15025:         if ( !( $file =~ m:^/:) ) {
15026:             $location = $dir. '/'.$file;
15027:         } else {
15028:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
15029:         }
15030:     }
15031:     $location=~s://+:/:g; # remove duplicate /
15032:     while ($location=~m{/\.\./}) {
15033: 	if ($location =~ m{/[^/]+/\.\./}) {
15034: 	    $location=~ s{/[^/]+/\.\./}{/}g;
15035: 	} else {
15036: 	    $location=~ s{/\.\./}{/}g;
15037: 	}
15038:     } #remove dir/..
15039:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
15040:     return $location;
15041: }
15042: 
15043: sub hreflocation {
15044:     my ($dir,$file)=@_;
15045:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
15046: 	$file=filelocation($dir,$file);
15047:     } elsif ($file=~m-^/adm/-) {
15048: 	$file=~s-^/adm/wrapper/-/-;
15049: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
15050:     }
15051:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
15052: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
15053:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
15054: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
15055: 	        {/uploaded/$1/$2/}x;
15056:     }
15057:     if ($file=~ m{^/userfiles/}) {
15058: 	$file =~ s{^/userfiles/}{/uploaded/};
15059:     }
15060:     return $file;
15061: }
15062: 
15063: 
15064: 
15065: 
15066: 
15067: sub current_machine_domains {
15068:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
15069: }
15070: 
15071: sub machine_domains {
15072:     my ($hostname) = @_;
15073:     my @domains;
15074:     my %hostname = &all_hostnames();
15075:     while( my($id, $name) = each(%hostname)) {
15076: #	&logthis("-$id-$name-$hostname-");
15077: 	if ($hostname eq $name) {
15078: 	    push(@domains,&host_domain($id));
15079: 	}
15080:     }
15081:     return @domains;
15082: }
15083: 
15084: sub current_machine_ids {
15085:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
15086: }
15087: 
15088: sub machine_ids {
15089:     my ($hostname) = @_;
15090:     $hostname ||= &hostname($perlvar{'lonHostID'});
15091:     my @ids;
15092:     my %name_to_host = &all_names();
15093:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
15094: 	return @{ $name_to_host{$hostname} };
15095:     }
15096:     return;
15097: }
15098: 
15099: sub additional_machine_domains {
15100:     my @domains;
15101:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
15102:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
15103:             while (my $line = <$fh>) {
15104:                 chomp($line);           
15105:                 $line =~ s/\s//g;
15106:                 push(@domains,$line);
15107:             }
15108:             close($fh);
15109:         }
15110:     }
15111:     return @domains;
15112: }
15113: 
15114: sub default_login_domain {
15115:     my $domain = $perlvar{'lonDefDomain'};
15116:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
15117:     foreach my $posdom (&current_machine_domains(),
15118:                         &additional_machine_domains()) {
15119:         if (lc($posdom) eq lc($testdomain)) {
15120:             $domain=$posdom;
15121:             last;
15122:         }
15123:     }
15124:     return $domain;
15125: }
15126: 
15127: sub shared_institution {
15128:     my ($dom,$lonhost) = @_;
15129:     if ($lonhost eq '') {
15130:         $lonhost = $perlvar{'lonHostID'};
15131:     }
15132:     my $same_intdom;
15133:     my $hostintdom = &internet_dom($lonhost);
15134:     if ($hostintdom ne '') {
15135:         my %iphost = &get_iphost();
15136:         my $primary_id = &domain($dom,'primary');
15137:         my $primary_ip = &get_host_ip($primary_id);
15138:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
15139:             foreach my $id (@{$iphost{$primary_ip}}) {
15140:                 my $intdom = &internet_dom($id);
15141:                 if ($intdom eq $hostintdom) {
15142:                     $same_intdom = 1;
15143:                     last;
15144:                 }
15145:             }
15146:         }
15147:     }
15148:     return $same_intdom;
15149: }
15150: 
15151: sub uses_sts {
15152:     my ($ignore_cache) = @_;
15153:     my $lonhost = $perlvar{'lonHostID'};
15154:     my $hostname = &hostname($lonhost);
15155:     my $sts_on;
15156:     if ($protocol{$lonhost} eq 'https') {
15157:         my $cachetime = 12*3600;
15158:         if (!$ignore_cache) {
15159:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
15160:             if (defined($cached)) {
15161:                 return $sts_on;
15162:             }
15163:         }
15164:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
15165:         my $request=new HTTP::Request('HEAD',$url);
15166:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
15167:         if ($response->is_success) {
15168:             my $has_sts = $response->header('Strict-Transport-Security');
15169:             if ($has_sts eq '') {
15170:                 $sts_on = 0;
15171:             } else {
15172:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
15173:                     my $maxage = $1;
15174:                     if ($maxage) {
15175:                         $sts_on = 1;
15176:                     } else {
15177:                         $sts_on = 0;
15178:                     }
15179:                 } else {
15180:                     $sts_on = 0;
15181:                 }
15182:             }
15183:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
15184:         }
15185:     }
15186:     return;
15187: }
15188: 
15189: sub waf_allssl {
15190:     my ($host_name) = @_;
15191:     my $alias = &get_proxy_alias();
15192:     if ($host_name eq '') {
15193:         $host_name = $ENV{'SERVER_NAME'};
15194:     }
15195:     if (($host_name ne '') && ($alias eq $host_name)) {
15196:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
15197:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
15198:         if ($defdomdefaults{'waf_sslopt'}) {
15199:             return $defdomdefaults{'waf_sslopt'};
15200:         }
15201:     }
15202:     return;
15203: }
15204: 
15205: sub get_requestor_ip {
15206:     my ($r,$nolookup,$noproxy) = @_;
15207:     my $from_ip;
15208:     if (ref($r)) {
15209:         if ($r->can('useragent_ip')) {
15210:             if ($noproxy && $r->can('client_ip')) {
15211:                 $from_ip = $r->client_ip();
15212:             } else {
15213:                 $from_ip = $r->useragent_ip();
15214:             }
15215:         } elsif ($r->connection->can('remote_ip')) {
15216:             $from_ip = $r->connection->remote_ip();
15217:         } else {
15218:             $from_ip = $r->get_remote_host($nolookup);
15219:         }
15220:     } else {
15221:         $from_ip = $ENV{'REMOTE_ADDR'};
15222:     }
15223:     return $from_ip if ($noproxy); 
15224:     # Who controls proxy settings for server
15225:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
15226:     my $proxyinfo = &get_proxy_settings($dom_in_use);
15227:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
15228:         if ($proxyinfo->{'vpnint'}) {
15229:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
15230:                 return $from_ip;
15231:             }
15232:         }
15233:         if ($proxyinfo->{'trusted'}) {
15234:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
15235:                 my $ipheader = $proxyinfo->{'ipheader'};
15236:                 my ($ip,$xfor);
15237:                 if (ref($r)) {
15238:                     if ($ipheader) {
15239:                         $ip = $r->headers_in->{$ipheader};
15240:                     }
15241:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
15242:                 } else {
15243:                     if ($ipheader) {
15244:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
15245:                     }
15246:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
15247:                 }
15248:                 if (($ip eq '') && ($xfor ne '')) {
15249:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
15250:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
15251:                             $ip = $poss_ip;
15252:                             last;
15253:                         }
15254:                     }
15255:                 }
15256:                 if ($ip ne '') {
15257:                     return $ip;
15258:                 }
15259:             }
15260:         }
15261:     }
15262:     return $from_ip;
15263: }
15264: 
15265: sub get_proxy_settings {
15266:     my ($dom_in_use) = @_;
15267:     my %domdefaults = &get_domain_defaults($dom_in_use);
15268:     my $proxyinfo = {
15269:                        ipheader => $domdefaults{'waf_ipheader'},
15270:                        trusted  => $domdefaults{'waf_trusted'},
15271:                        vpnint   => $domdefaults{'waf_vpnint'},
15272:                        vpnext   => $domdefaults{'waf_vpnext'},
15273:                        sslopt   => $domdefaults{'waf_sslopt'},
15274:                     };
15275:     return $proxyinfo;
15276: }
15277: 
15278: sub ip_match {
15279:     my ($ip,$pattern_str) = @_;
15280:     $ip=Net::CIDR::cidrvalidate($ip);
15281:     if ($ip) {
15282:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
15283:     }
15284:     return;
15285: }
15286: 
15287: sub get_proxy_alias {
15288:     my ($lonid) = @_;
15289:     if ($lonid eq '') {
15290:         $lonid = $perlvar{'lonHostID'};
15291:     }
15292:     if (!defined(&hostname($lonid))) {
15293:         return;
15294:     }
15295:     if ($lonid ne '') {
15296:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
15297:         if ($cached) {
15298:             return $alias;
15299:         }
15300:         my $dom = &host_domain($lonid);
15301:         if ($dom ne '') {
15302:             my $cachetime = 60*60*24;
15303:             my %domconfig =
15304:                 &get_dom('configuration',['wafproxy'],$dom);
15305:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15306:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
15307:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
15308:                 }
15309:             }
15310:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
15311:         }
15312:     }
15313:     return;
15314: }
15315: 
15316: sub use_proxy_alias {
15317:     my ($r,$lonid) = @_;
15318:     my $alias = &get_proxy_alias($lonid);
15319:     if ($alias) {
15320:         my $dom = &host_domain($lonid);
15321:         if ($dom ne '') {
15322:             my $proxyinfo = &get_proxy_settings($dom);
15323:             my ($vpnint,$remote_ip);
15324:             if (ref($proxyinfo) eq 'HASH') {
15325:                 $vpnint = $proxyinfo->{'vpnint'};
15326:                 if ($vpnint) {
15327:                     $remote_ip = &get_requestor_ip($r,1,1);
15328:                 }
15329:             }
15330:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
15331:                 return $alias;
15332:             }
15333:         }
15334:     }
15335:     return;
15336: }
15337: 
15338: sub alias_sso {
15339:     my ($lonid) = @_;
15340:     if ($lonid eq '') {
15341:         $lonid = $perlvar{'lonHostID'};
15342:     }
15343:     if (!defined(&hostname($lonid))) {
15344:         return;
15345:     }
15346:     if ($lonid ne '') {
15347:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
15348:         if ($cached) {
15349:             return $use_alias;
15350:         }
15351:         my $dom = &host_domain($lonid);
15352:         if ($dom ne '') {
15353:             my $cachetime = 60*60*24;
15354:             my %domconfig =
15355:                 &get_dom('configuration',['wafproxy'],$dom);
15356:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
15357:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
15358:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
15359:                 }
15360:             }
15361:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
15362:         }
15363:     }
15364:     return;
15365: }
15366: 
15367: sub get_saml_landing {
15368:     my ($lonid) = @_;
15369:     if ($lonid eq '') {
15370:         my $defdom = &default_login_domain();
15371:         my @hosts = &current_machine_ids();
15372:         if (@hosts > 1) {
15373:             foreach my $hostid (@hosts) {
15374:                 if (&host_domain($hostid) eq $defdom) {
15375:                     $lonid = $hostid;
15376:                     last;
15377:                 }
15378:             }
15379:         } else {
15380:             $lonid = $perlvar{'lonHostID'};
15381:         }
15382:         if ($lonid) {
15383:             unless (&host_domain($lonid) eq $defdom) {
15384:                 return;
15385:             }
15386:         } else {
15387:             return;
15388:         }
15389:     } elsif (!defined(&hostname($lonid))) {
15390:         return;
15391:     }
15392:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
15393:     if ($cached) {
15394:         return $landing;
15395:     }
15396:     my $dom = &host_domain($lonid);
15397:     if ($dom ne '') {
15398:         my $cachetime = 60*60*24;
15399:         my %domconfig =
15400:             &get_dom('configuration',['login'],$dom);
15401:         if (ref($domconfig{'login'}) eq 'HASH') {
15402:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
15403:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
15404:                     $landing = 1;
15405:                 }
15406:             }
15407:         }
15408:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
15409:     }
15410:     return;
15411: }
15412: 
15413: # ------------------------------------------------------------- Declutters URLs
15414: 
15415: sub declutter {
15416:     my $thisfn=shift;
15417:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
15418:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
15419:         $thisfn=~s{^/home/httpd/html}{};
15420:     }
15421:     $thisfn=~s/^\///;
15422:     $thisfn=~s|^adm/wrapper/||;
15423:     $thisfn=~s|^adm/coursedocs/showdoc/||;
15424:     $thisfn=~s/^res\///;
15425:     $thisfn=~s/^priv\///;
15426:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
15427:         $thisfn=~s/\?.+$//;
15428:     }
15429:     return $thisfn;
15430: }
15431: 
15432: # ------------------------------------------------------------- Clutter up URLs
15433: 
15434: sub clutter {
15435:     my $thisfn='/'.&declutter(shift);
15436:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
15437: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
15438:        $thisfn='/res'.$thisfn; 
15439:     }
15440:     if ($thisfn !~m|^/adm|) {
15441: 	if ($thisfn =~ m|^/ext/|) {
15442: 	    $thisfn='/adm/wrapper'.$thisfn;
15443: 	} else {
15444: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
15445: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
15446: 	    if ($embstyle eq 'ssi'
15447: 		|| ($embstyle eq 'hdn')
15448: 		|| ($embstyle eq 'rat')
15449: 		|| ($embstyle eq 'prv')
15450: 		|| ($embstyle eq 'ign')) {
15451: 		#do nothing with these
15452: 	    } elsif (($embstyle eq 'img') 
15453: 		|| ($embstyle eq 'emb')
15454: 		|| ($embstyle eq 'wrp')) {
15455: 		$thisfn='/adm/wrapper'.$thisfn;
15456: 	    } elsif ($embstyle eq 'unk'
15457: 		     && $thisfn!~/\.(sequence|page)$/) {
15458: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
15459: 	    } else {
15460: #		&logthis("Got a blank emb style");
15461: 	    }
15462: 	}
15463:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
15464:         $thisfn='/adm/wrapper'.$thisfn;
15465:     }
15466:     return $thisfn;
15467: }
15468: 
15469: sub clutter_with_no_wrapper {
15470:     my $uri = &clutter(shift);
15471:     if ($uri =~ m-^/adm/-) {
15472: 	$uri =~ s-^/adm/wrapper/-/-;
15473: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
15474:     }
15475:     return $uri;
15476: }
15477: 
15478: sub freeze_escape {
15479:     my ($value)=@_;
15480:     if (ref($value)) {
15481: 	$value=&nfreeze($value);
15482: 	return '__FROZEN__'.&escape($value);
15483:     }
15484:     return &escape($value);
15485: }
15486: 
15487: 
15488: sub thaw_unescape {
15489:     my ($value)=@_;
15490:     if ($value =~ /^__FROZEN__/) {
15491: 	substr($value,0,10,undef);
15492: 	$value=&unescape($value);
15493: 	return &thaw($value);
15494:     }
15495:     return &unescape($value);
15496: }
15497: 
15498: sub correct_line_ends {
15499:     my ($result)=@_;
15500:     $$result =~s/\r\n/\n/mg;
15501:     $$result =~s/\r/\n/mg;
15502: }
15503: # ================================================================ Main Program
15504: 
15505: sub goodbye {
15506:    &logthis("Starting Shut down");
15507: #not converted to using infrastruture and probably shouldn't be
15508:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
15509: #converted
15510: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
15511:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
15512: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
15513: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
15514: #1.1 only
15515: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
15516: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
15517: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
15518: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
15519:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
15520:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
15521:    &logthis(sprintf("%-20s is %s",'hits',$hits));
15522:    &flushcourselogs();
15523:    &logthis("Shutting down");
15524: }
15525: 
15526: sub get_dns {
15527:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
15528:     if (!$ignore_cache) {
15529: 	my ($content,$cached)=
15530: 	    &is_cached_new('dns',$url);
15531: 	if ($cached) {
15532: 	    &$func($content,$hashref);
15533: 	    return;
15534: 	}
15535:     }
15536: 
15537:     my %alldns;
15538:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
15539:         foreach my $dns (<$config>) {
15540: 	    next if ($dns !~ /^\^(\S*)/x);
15541:             my $line = $1;
15542:             my ($host,$protocol) = split(/:/,$line);
15543:             if ($protocol ne 'https') {
15544:                 $protocol = 'http';
15545:             }
15546: 	    $alldns{$host} = $protocol;
15547:         }
15548:         close($config);
15549:     }
15550:     while (%alldns) {
15551: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
15552:         my ($contents,@content);
15553:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
15554:             my $command = (split('/',$url))[3];
15555:             my ($dir,$file) = &parse_getdns_url($command,$url);
15556:             delete($alldns{$dns});
15557:             next if (($dir eq '') || ($file eq ''));
15558:             if (open(my $config,'<',"$dir/$file")) {
15559:                 @content = <$config>;
15560:                 close($config);
15561:             }
15562:             if ($url eq '/adm/dns/loncapaCRL') {
15563:                 $contents = join('',@content);
15564:             }
15565:         } else {
15566: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
15567:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
15568:             delete($alldns{$dns});
15569: 	    next if ($response->is_error());
15570:             if ($url eq '/adm/dns/loncapaCRL') {
15571:                 $contents = $response->content;
15572:             } else {
15573:                 @content = split("\n",$response->content);
15574:             }
15575:         }
15576:         if ($url eq '/adm/dns/loncapaCRL') {
15577:             return &$func($contents);
15578:         } else {
15579: 	    unless ($nocache) {
15580: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
15581: 	    }
15582: 	    &$func(\@content,$hashref);
15583:             return;
15584:         }
15585:     }
15586:     my $which = (split('/',$url,4))[3];
15587:     if ($which eq 'loncapaCRL') {
15588:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15589:         if (-e $diskfile) {
15590:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
15591:         } else {
15592:             &logthis("unable to contact DNS, no on disk file $diskfile available");
15593:         }
15594:     } else {
15595:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
15596:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
15597:             my @content = <$config>;
15598:             close($config);
15599:             &$func(\@content,$hashref);
15600:         }
15601:     }
15602:     return;
15603: }
15604: 
15605: # ------------------------------------------------------Get DNS checksums file
15606: sub parse_dns_checksums_tab {
15607:     my ($lines,$hashref) = @_;
15608:     my $lonhost = $perlvar{'lonHostID'};
15609:     my $machine_dom = &host_domain($lonhost);
15610:     my $loncaparev = &get_server_loncaparev($machine_dom);
15611:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
15612:     my $webconfdir = '/etc/httpd/conf';
15613:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
15614:         $webconfdir = '/etc/apache2';
15615:     } elsif ($distro =~ /^sles(\d+)$/) {
15616:         if ($1 >= 10) {
15617:             $webconfdir = '/etc/apache2';
15618:         }
15619:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
15620:         if ($1 >= 10.0) {
15621:             $webconfdir = '/etc/apache2';
15622:         }
15623:     }
15624:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15625:     my (%chksum,%revnum);
15626:     if (ref($lines) eq 'ARRAY') {
15627:         chomp(@{$lines});
15628:         my $version = shift(@{$lines});
15629:         if ($version eq $release) {  
15630:             foreach my $line (@{$lines}) {
15631:                 my ($file,$version,$shasum) = split(/,/,$line);
15632:                 if ($file =~ m{^/etc/httpd/conf}) {
15633:                     if ($webconfdir eq '/etc/apache2') {
15634:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
15635:                     }
15636:                 }
15637:                 $chksum{$file} = $shasum;
15638:                 $revnum{$file} = $version;
15639:             }
15640:             if (ref($hashref) eq 'HASH') {
15641:                 %{$hashref} = (
15642:                                 sums     => \%chksum,
15643:                                 versions => \%revnum,
15644:                               );
15645:             }
15646:         }
15647:     }
15648:     return;
15649: }
15650: 
15651: sub fetch_dns_checksums {
15652:     my %checksums;
15653:     my $machine_dom = &host_domain($perlvar{'lonHostID'});
15654:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
15655:     my ($release,$timestamp) = split(/\-/,$loncaparev);
15656:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
15657:              \%checksums);
15658:     return \%checksums;
15659: }
15660: 
15661: sub fetch_crl_pemfile {
15662:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
15663: }
15664: 
15665: sub save_crl_pem {
15666:     my ($content) = @_;
15667:     my ($msg,$hadchanges);
15668:     if ($content ne '') {
15669:         my $now = time;
15670:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
15671:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
15672:         if (open(my $fh,'>',"$tmpcrl")) {
15673:             print $fh $content;
15674:             close($fh);
15675:             if (-e $lonca) {
15676:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
15677:                     my $check = <PIPE>;
15678:                     close(PIPE);
15679:                     chomp($check);
15680:                     if ($check eq 'verify OK') {
15681:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
15682:                         my $backup;
15683:                         if (-e $dest) {
15684:                             if (&File::Copy::move($dest,"$dest.bak")) {
15685:                                 $backup = 'ok';
15686:                             }
15687:                         }
15688:                         if (&File::Copy::move($tmpcrl,$dest)) {
15689:                             $msg = 'ok';
15690:                             if ($backup) {
15691:                                 my (%oldnums,%newnums);
15692:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
15693:                                     while (<PIPE>) {
15694:                                         $oldnums{(split(/:/))[1]} = 1;
15695:                                     }
15696:                                     close(PIPE);
15697:                                 }
15698:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
15699:                                     while(<PIPE>) {
15700:                                         $newnums{(split(/:/))[1]} = 1;
15701:                                     }
15702:                                     close(PIPE);
15703:                                 }
15704:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
15705:                                     unless (exists($oldnums{$key})) {
15706:                                         $hadchanges = 1;
15707:                                         last;
15708:                                     }
15709:                                 }
15710:                                 unless ($hadchanges) {
15711:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
15712:                                         unless (exists($newnums{$key})) {
15713:                                             $hadchanges = 1;
15714:                                             last;
15715:                                         }
15716:                                     }
15717:                                 }
15718:                             }
15719:                         }
15720:                     } else {
15721:                         unlink($tmpcrl);
15722:                     }
15723:                 } else {
15724:                     unlink($tmpcrl);
15725:                 }
15726:             } else {
15727:                 unlink($tmpcrl);
15728:             }
15729:         }
15730:     }
15731:     return ($msg,$hadchanges);
15732: }
15733: 
15734: sub parse_getdns_url {
15735:     my ($command,$url) = @_;
15736:     my $dir = $perlvar{'lonTabDir'};
15737:     my $file;
15738:     if ($command eq 'hosts') {
15739:         $file = 'dns_hosts.tab';
15740:     } elsif ($command eq 'domain') {
15741:         $file = 'dns_domain.tab';
15742:     } elsif ($command eq 'checksums') {
15743:         my $version = (split('/',$url))[4];
15744:         $file = "dns_checksums/$version.tab",
15745:     } elsif ($command eq 'loncapaCRL') {
15746:         $dir = $perlvar{'lonCertificateDirectory'};
15747:         $file = $perlvar{'lonnetCertRevocationList'};
15748:     }
15749:     return ($dir,$file);
15750: }
15751: 
15752: # ------------------------------------------------------------ Read domain file
15753: {
15754:     my $loaded;
15755:     my %domain;
15756: 
15757:     sub parse_domain_tab {
15758: 	my ($lines) = @_;
15759: 	foreach my $line (@$lines) {
15760: 	    next if ($line =~ /^(\#|\s*$ )/x);
15761: 
15762: 	    chomp($line);
15763: 	    my ($name,@elements) = split(/:/,$line,9);
15764: 	    my %this_domain;
15765: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
15766: 			       'lang_def', 'city', 'longi', 'lati',
15767: 			       'primary') {
15768: 		$this_domain{$field} = shift(@elements);
15769: 	    }
15770: 	    $domain{$name} = \%this_domain;
15771: 	}
15772:     }
15773: 
15774:     sub reset_domain_info {
15775: 	undef($loaded);
15776: 	undef(%domain);
15777:     }
15778: 
15779:     sub load_domain_tab {
15780: 	my ($ignore_cache,$nocache) = @_;
15781: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
15782: 	my $fh;
15783: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
15784: 	    my @lines = <$fh>;
15785: 	    &parse_domain_tab(\@lines);
15786: 	}
15787: 	close($fh);
15788: 	$loaded = 1;
15789:     }
15790: 
15791:     sub domain {
15792: 	&load_domain_tab() if (!$loaded);
15793: 
15794: 	my ($name,$what) = @_;
15795: 	return if ( !exists($domain{$name}) );
15796: 
15797: 	if (!$what) {
15798: 	    return $domain{$name}{'description'};
15799: 	}
15800: 	return $domain{$name}{$what};
15801:     }
15802: 
15803:     sub domain_info {
15804:         &load_domain_tab() if (!$loaded);
15805:         return %domain;
15806:     }
15807: 
15808: }
15809: 
15810: 
15811: # ------------------------------------------------------------- Read hosts file
15812: {
15813:     my %hostname;
15814:     my %hostdom;
15815:     my %libserv;
15816:     my $loaded;
15817:     my %name_to_host;
15818:     my %internetdom;
15819:     my %LC_dns_serv;
15820: 
15821:     sub parse_hosts_tab {
15822: 	my ($file) = @_;
15823: 	foreach my $configline (@$file) {
15824: 	    next if ($configline =~ /^(\#|\s*$ )/x);
15825:             chomp($configline);
15826: 	    if ($configline =~ /^\^/) {
15827:                 if ($configline =~ /^\^([\w.\-]+)/) {
15828:                     $LC_dns_serv{$1} = 1;
15829:                 }
15830:                 next;
15831:             }
15832: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
15833: 	    $name=~s/\s//g;
15834: 	    if ($id && $domain && $role && $name) {
15835:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
15836:                     my $curr = $hostname{$id};
15837:                     my $skip;
15838:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
15839:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
15840:                             $skip = 1;
15841:                         } else {
15842:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
15843:                         }
15844:                     }
15845:                     unless ($skip) {
15846:                         push(@{$name_to_host{$name}},$id);
15847:                     }
15848:                 } else {
15849:                     push(@{$name_to_host{$name}},$id);
15850:                 }
15851: 		$hostname{$id}=$name;
15852: 		$hostdom{$id}=$domain;
15853: 		if ($role eq 'library') { $libserv{$id}=$name; }
15854:                 if (defined($protocol)) {
15855:                     if ($protocol eq 'https') {
15856:                         $protocol{$id} = $protocol;
15857:                     } else {
15858:                         $protocol{$id} = 'http'; 
15859:                     }
15860:                 } else {
15861:                     $protocol{$id} = 'http';
15862:                 }
15863:                 if (defined($intdom)) {
15864:                     $internetdom{$id} = $intdom;
15865:                 }
15866: 	    }
15867: 	}
15868:     }
15869:     
15870:     sub reset_hosts_info {
15871: 	&purge_remembered();
15872: 	&reset_domain_info();
15873: 	&reset_hosts_ip_info();
15874:         undef(%internetdom);
15875: 	undef(%name_to_host);
15876: 	undef(%hostname);
15877: 	undef(%hostdom);
15878: 	undef(%libserv);
15879: 	undef($loaded);
15880:     }
15881: 
15882:     sub load_hosts_tab {
15883: 	my ($ignore_cache,$nocache) = @_;
15884: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
15885: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
15886: 	my @config = <$config>;
15887: 	&parse_hosts_tab(\@config);
15888: 	close($config);
15889: 	$loaded=1;
15890:     }
15891: 
15892:     sub hostname {
15893: 	&load_hosts_tab() if (!$loaded);
15894: 
15895: 	my ($lonid) = @_;
15896: 	return $hostname{$lonid};
15897:     }
15898: 
15899:     sub all_hostnames {
15900: 	&load_hosts_tab() if (!$loaded);
15901: 
15902: 	return %hostname;
15903:     }
15904: 
15905:     sub all_names {
15906:         my ($ignore_cache,$nocache) = @_;
15907: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
15908: 
15909: 	return %name_to_host;
15910:     }
15911: 
15912:     sub all_host_domain {
15913:         &load_hosts_tab() if (!$loaded);
15914:         return %hostdom;
15915:     }
15916: 
15917:     sub all_host_intdom {
15918:         &load_hosts_tab() if (!$loaded);
15919:         return %internetdom;
15920:     }
15921: 
15922:     sub is_library {
15923: 	&load_hosts_tab() if (!$loaded);
15924: 
15925: 	return exists($libserv{$_[0]});
15926:     }
15927: 
15928:     sub all_library {
15929: 	&load_hosts_tab() if (!$loaded);
15930: 
15931: 	return %libserv;
15932:     }
15933: 
15934:     sub unique_library {
15935: 	#2x reverse removes all hostnames that appear more than once
15936:         my %unique = reverse &all_library();
15937:         return reverse %unique;
15938:     }
15939: 
15940:     sub get_servers {
15941: 	&load_hosts_tab() if (!$loaded);
15942: 
15943: 	my ($domain,$type) = @_;
15944: 	my %possible_hosts = ($type eq 'library') ? %libserv
15945: 	                                          : %hostname;
15946: 	my %result;
15947: 	if (ref($domain) eq 'ARRAY') {
15948: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15949: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
15950: 		    $result{$host} = $hostname;
15951: 		}
15952: 	    }
15953: 	} else {
15954: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
15955: 		if ($hostdom{$host} eq $domain) {
15956: 		    $result{$host} = $hostname;
15957: 		}
15958: 	    }
15959: 	}
15960: 	return %result;
15961:     }
15962: 
15963:     sub get_unique_servers {
15964:         my %unique = reverse &get_servers(@_);
15965: 	return reverse %unique;
15966:     }
15967: 
15968:     sub host_domain {
15969: 	&load_hosts_tab() if (!$loaded);
15970: 
15971: 	my ($lonid) = @_;
15972: 	return $hostdom{$lonid};
15973:     }
15974: 
15975:     sub all_domains {
15976: 	&load_hosts_tab() if (!$loaded);
15977: 
15978: 	my %seen;
15979: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
15980: 	return @uniq;
15981:     }
15982: 
15983:     sub internet_dom {
15984:         &load_hosts_tab() if (!$loaded);
15985: 
15986:         my ($lonid) = @_;
15987:         return $internetdom{$lonid};
15988:     }
15989: 
15990:     sub is_LC_dns {
15991:         &load_hosts_tab() if (!$loaded);
15992: 
15993:         my ($hostname) = @_;
15994:         return exists($LC_dns_serv{$hostname});
15995:     }
15996: 
15997: }
15998: 
15999: { 
16000:     my %iphost;
16001:     my %name_to_ip;
16002:     my %lonid_to_ip;
16003: 
16004:     sub get_hosts_from_ip {
16005: 	my ($ip) = @_;
16006: 	my %iphosts = &get_iphost();
16007: 	if (ref($iphosts{$ip})) {
16008: 	    return @{$iphosts{$ip}};
16009: 	}
16010: 	return;
16011:     }
16012:     
16013:     sub reset_hosts_ip_info {
16014: 	undef(%iphost);
16015: 	undef(%name_to_ip);
16016: 	undef(%lonid_to_ip);
16017:     }
16018: 
16019:     sub get_host_ip {
16020: 	my ($lonid) = @_;
16021: 	if (exists($lonid_to_ip{$lonid})) {
16022: 	    return $lonid_to_ip{$lonid};
16023: 	}
16024: 	my $name=&hostname($lonid);
16025:    	my $ip = gethostbyname($name);
16026: 	return if (!$ip || length($ip) ne 4);
16027: 	$ip=inet_ntoa($ip);
16028: 	$name_to_ip{$name}   = $ip;
16029: 	$lonid_to_ip{$lonid} = $ip;
16030: 	return $ip;
16031:     }
16032:     
16033:     sub get_iphost {
16034: 	my ($ignore_cache,$nocache) = @_;
16035: 
16036: 	if (!$ignore_cache) {
16037: 	    if (%iphost) {
16038: 		return %iphost;
16039: 	    }
16040: 	    my ($ip_info,$cached)=
16041: 		&is_cached_new('iphost','iphost');
16042: 	    if ($cached) {
16043: 		%iphost      = %{$ip_info->[0]};
16044: 		%name_to_ip  = %{$ip_info->[1]};
16045: 		%lonid_to_ip = %{$ip_info->[2]};
16046: 		return %iphost;
16047: 	    }
16048: 	}
16049: 
16050: 	# get yesterday's info for fallback
16051: 	my %old_name_to_ip;
16052: 	my ($ip_info,$cached)=
16053: 	    &is_cached_new('iphost','iphost');
16054: 	if ($cached) {
16055: 	    %old_name_to_ip = %{$ip_info->[1]};
16056: 	}
16057: 
16058: 	my %name_to_host = &all_names($ignore_cache,$nocache);
16059: 	foreach my $name (keys(%name_to_host)) {
16060: 	    my $ip;
16061: 	    if (!exists($name_to_ip{$name})) {
16062: 		$ip = gethostbyname($name);
16063: 		if (!$ip || length($ip) ne 4) {
16064: 		    if (defined($old_name_to_ip{$name})) {
16065: 			$ip = $old_name_to_ip{$name};
16066: 			&logthis("Can't find $name defaulting to old $ip");
16067: 		    } else {
16068: 			&logthis("Name $name no IP found");
16069: 			next;
16070: 		    }
16071: 		} else {
16072: 		    $ip=inet_ntoa($ip);
16073: 		}
16074: 		$name_to_ip{$name} = $ip;
16075: 	    } else {
16076: 		$ip = $name_to_ip{$name};
16077: 	    }
16078: 	    foreach my $id (@{ $name_to_host{$name} }) {
16079: 		$lonid_to_ip{$id} = $ip;
16080: 	    }
16081: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
16082: 	}
16083:         unless ($nocache) {
16084: 	    &do_cache_new('iphost','iphost',
16085: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
16086: 		          48*60*60);
16087:         }
16088: 
16089: 	return %iphost;
16090:     }
16091: 
16092:     #
16093:     #  Given a DNS returns the loncapa host name for that DNS 
16094:     # 
16095:     sub host_from_dns {
16096:         my ($dns) = @_;
16097:         my @hosts;
16098:         my $ip;
16099: 
16100:         if (exists($name_to_ip{$dns})) {
16101:             $ip = $name_to_ip{$dns};
16102:         }
16103:         if (!$ip) {
16104:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
16105:             if (length($ip) == 4) { 
16106: 	        $ip   = &IO::Socket::inet_ntoa($ip);
16107:             }
16108:         }
16109:         if ($ip) {
16110: 	    @hosts = get_hosts_from_ip($ip);
16111: 	    return $hosts[0];
16112:         }
16113:         return undef;
16114:     }
16115: 
16116:     sub get_internet_names {
16117:         my ($lonid) = @_;
16118:         return if ($lonid eq '');
16119:         my ($idnref,$cached)=
16120:             &is_cached_new('internetnames',$lonid);
16121:         if ($cached) {
16122:             return $idnref;
16123:         }
16124:         my $ip = &get_host_ip($lonid);
16125:         my @hosts = &get_hosts_from_ip($ip);
16126:         my %iphost = &get_iphost();
16127:         my (@idns,%seen);
16128:         foreach my $id (@hosts) {
16129:             my $dom = &host_domain($id);
16130:             my $prim_id = &domain($dom,'primary');
16131:             my $prim_ip = &get_host_ip($prim_id);
16132:             next if ($seen{$prim_ip});
16133:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
16134:                 foreach my $id (@{$iphost{$prim_ip}}) {
16135:                     my $intdom = &internet_dom($id);
16136:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
16137:                         push(@idns,$intdom);
16138:                     }
16139:                 }
16140:             }
16141:             $seen{$prim_ip} = 1;
16142:         }
16143:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
16144:     }
16145: 
16146: }
16147: 
16148: sub all_loncaparevs {
16149:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
16150: }
16151: 
16152: # ---------------------------------------------------------- Read loncaparev table
16153: {
16154:     sub load_loncaparevs { 
16155:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
16156:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
16157:                 while (my $configline=<$config>) {
16158:                     chomp($configline);
16159:                     my ($hostid,$loncaparev)=split(/:/,$configline);
16160:                     $loncaparevs{$hostid}=$loncaparev;
16161:                 }
16162:                 close($config);
16163:             }
16164:         }
16165:     }
16166: }
16167: 
16168: # ---------------------------------------------------------- Read serverhostID table
16169: {
16170:     sub load_serverhomeIDs {
16171:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
16172:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
16173:                 while (my $configline=<$config>) {
16174:                     chomp($configline);
16175:                     my ($name,$id)=split(/:/,$configline);
16176:                     $serverhomeIDs{$name}=$id;
16177:                 }
16178:                 close($config);
16179:             }
16180:         }
16181:     }
16182: }
16183: 
16184: 
16185: BEGIN {
16186: 
16187: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
16188:     unless ($readit) {
16189: {
16190:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
16191:     %perlvar = (%perlvar,%{$configvars});
16192: }
16193: 
16194: 
16195: # ------------------------------------------------------ Read spare server file
16196: {
16197:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
16198: 
16199:     while (my $configline=<$config>) {
16200:        chomp($configline);
16201:        if ($configline) {
16202: 	   my ($host,$type) = split(':',$configline,2);
16203: 	   if (!defined($type) || $type eq '') { $type = 'default' };
16204: 	   push(@{ $spareid{$type} }, $host);
16205:        }
16206:     }
16207:     close($config);
16208: }
16209: # ------------------------------------------------------------ Read permissions
16210: {
16211:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
16212: 
16213:     while (my $configline=<$config>) {
16214: 	chomp($configline);
16215: 	if ($configline) {
16216: 	    my ($role,$perm)=split(/ /,$configline);
16217: 	    if ($perm ne '') { $pr{$role}=$perm; }
16218: 	}
16219:     }
16220:     close($config);
16221: }
16222: 
16223: # -------------------------------------------- Read plain texts for permissions
16224: {
16225:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
16226: 
16227:     while (my $configline=<$config>) {
16228: 	chomp($configline);
16229: 	if ($configline) {
16230: 	    my ($short,@plain)=split(/:/,$configline);
16231:             %{$prp{$short}} = ();
16232: 	    if (@plain > 0) {
16233:                 $prp{$short}{'std'} = $plain[0];
16234:                 for (my $i=1; $i<@plain; $i++) {
16235:                     $prp{$short}{'alt'.$i} = $plain[$i];  
16236:                 }
16237:             }
16238: 	}
16239:     }
16240:     close($config);
16241: }
16242: 
16243: # ---------------------------------------------------------- Read package table
16244: {
16245:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
16246: 
16247:     while (my $configline=<$config>) {
16248: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
16249: 	chomp($configline);
16250: 	my ($short,$plain)=split(/:/,$configline);
16251: 	my ($pack,$name)=split(/\&/,$short);
16252: 	if ($plain ne '') {
16253: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
16254: 	    $packagetab{$short}=$plain; 
16255: 	}
16256:     }
16257:     close($config);
16258: }
16259: 
16260: # ---------------------------------------------------------- Read loncaparev table
16261: 
16262: &load_loncaparevs();
16263: 
16264: # ---------------------------------------------------------- Read serverhostID table
16265: 
16266: &load_serverhomeIDs();
16267: 
16268: # ---------------------------------------------------------- Read releaseslist XML
16269: {
16270:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
16271:     if (-e $file) {
16272:         my $parser = HTML::LCParser->new($file);
16273:         while (my $token = $parser->get_token()) {
16274:             if ($token->[0] eq 'S') {
16275:                 my $item = $token->[1];
16276:                 my $name = $token->[2]{'name'};
16277:                 my $value = $token->[2]{'value'};
16278:                 my $valuematch = $token->[2]{'valuematch'};
16279:                 my $namematch = $token->[2]{'namematch'};
16280:                 if ($item eq 'parameter') {
16281:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
16282:                         my $release = $parser->get_text();
16283:                         $release =~ s/(^\s*|\s*$ )//gx;
16284:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
16285:                     }
16286:                 } elsif ($item ne '' && $name ne '') {
16287:                     my $release = $parser->get_text();
16288:                     $release =~ s/(^\s*|\s*$ )//gx;
16289:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
16290:                 }
16291:             }
16292:         }
16293:     }
16294: }
16295: 
16296: # ---------------------------------------------------------- Read managers table
16297: {
16298:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
16299:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
16300:             while (my $configline=<$config>) {
16301:                 chomp($configline);
16302:                 next if ($configline =~ /^\#/);
16303:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
16304:                     $managerstab{$configline} = 1;
16305:                 }
16306:             }
16307:             close($config);
16308:         }
16309:     }
16310: }
16311: 
16312: # ------------- set up temporary directory
16313: {
16314:     $tmpdir = LONCAPA::tempdir();
16315: 
16316: }
16317: 
16318: # ------------- set default texengine (domain default overrides this)
16319: {
16320:     $deftex = LONCAPA::texengine();
16321: }
16322: 
16323: # ------------- set default minimum length for passwords for internal auth users
16324: {
16325:     $passwdmin = LONCAPA::passwd_min();
16326: }
16327: 
16328: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
16329: 				'compress_threshold'=> 20_000,
16330:  			        });
16331: 
16332: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
16333: $dumpcount=0;
16334: $locknum=0;
16335: 
16336: &logtouch();
16337: &logthis('<font color="yellow">INFO: Read configuration</font>');
16338: $readit=1;
16339:     {
16340: 	use integer;
16341: 	my $test=(2**32)+1;
16342: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
16343: 	&logthis(" Detected 64bit platform ($_64bit)");
16344:     }
16345: }
16346: }
16347: 
16348: 1;
16349: __END__
16350: 
16351: =pod
16352: 
16353: =head1 NAME
16354: 
16355: Apache::lonnet - Subroutines to ask questions about things in the network.
16356: 
16357: =head1 SYNOPSIS
16358: 
16359: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
16360: 
16361:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
16362: 
16363: Common parameters:
16364: 
16365: =over 4
16366: 
16367: =item *
16368: 
16369: $uname : an internal username (if $cname expecting a course Id specifically)
16370: 
16371: =item *
16372: 
16373: $udom : a domain (if $cdom expecting a course's domain specifically)
16374: 
16375: =item *
16376: 
16377: $symb : a resource instance identifier
16378: 
16379: =item *
16380: 
16381: $namespace : the name of a .db file that contains the data needed or
16382: being set.
16383: 
16384: =back
16385: 
16386: =head1 OVERVIEW
16387: 
16388: lonnet provides subroutines which interact with the
16389: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
16390: about classes, users, and resources.
16391: 
16392: For many of these objects you can also use this to store data about
16393: them or modify them in various ways.
16394: 
16395: =head2 Symbs
16396: 
16397: To identify a specific instance of a resource, LON-CAPA uses symbols
16398: or "symbs"X<symb>. These identifiers are built from the URL of the
16399: map, the resource number of the resource in the map, and the URL of
16400: the resource itself. The latter is somewhat redundant, but might help
16401: if maps change.
16402: 
16403: An example is
16404: 
16405:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
16406: 
16407: The respective map entry is
16408: 
16409:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
16410:   title="Problem 2">
16411:  </resource>
16412: 
16413: Symbs are used by the random number generator, as well as to store and
16414: restore data specific to a certain instance of for example a problem.
16415: 
16416: =head2 Storing And Retrieving Data
16417: 
16418: X<store()>X<cstore()>X<restore()>Three of the most important functions
16419: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
16420: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
16421: is is the non-critical message twin of cstore. These functions are for
16422: handlers to store a perl hash to a user's permanent data space in an
16423: easy manner, and to retrieve it again on another call. It is expected
16424: that a handler would use this once at the beginning to retrieve data,
16425: and then again once at the end to send only the new data back.
16426: 
16427: The data is stored in the user's data directory on the user's
16428: homeserver under the ID of the course.
16429: 
16430: The hash that is returned by restore will have all of the previous
16431: value for all of the elements of the hash.
16432: 
16433: Example:
16434: 
16435:  #creating a hash
16436:  my %hash;
16437:  $hash{'foo'}='bar';
16438: 
16439:  #storing it
16440:  &Apache::lonnet::cstore(\%hash);
16441: 
16442:  #changing a value
16443:  $hash{'foo'}='notbar';
16444: 
16445:  #adding a new value
16446:  $hash{'bar'}='foo';
16447:  &Apache::lonnet::cstore(\%hash);
16448: 
16449:  #retrieving the hash
16450:  my %history=&Apache::lonnet::restore();
16451: 
16452:  #print the hash
16453:  foreach my $key (sort(keys(%history))) {
16454:    print("\%history{$key} = $history{$key}");
16455:  }
16456: 
16457: Will print out:
16458: 
16459:  %history{1:foo} = bar
16460:  %history{1:keys} = foo:timestamp
16461:  %history{1:timestamp} = 990455579
16462:  %history{2:bar} = foo
16463:  %history{2:foo} = notbar
16464:  %history{2:keys} = foo:bar:timestamp
16465:  %history{2:timestamp} = 990455580
16466:  %history{bar} = foo
16467:  %history{foo} = notbar
16468:  %history{timestamp} = 990455580
16469:  %history{version} = 2
16470: 
16471: Note that the special hash entries C<keys>, C<version> and
16472: C<timestamp> were added to the hash. C<version> will be equal to the
16473: total number of versions of the data that have been stored. The
16474: C<timestamp> attribute will be the UNIX time the hash was
16475: stored. C<keys> is available in every historical section to list which
16476: keys were added or changed at a specific historical revision of a
16477: hash.
16478: 
16479: B<Warning>: do not store the hash that restore returns directly. This
16480: will cause a mess since it will restore the historical keys as if the
16481: were new keys. I.E. 1:foo will become 1:1:foo etc.
16482: 
16483: Calling convention:
16484: 
16485:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
16486:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
16487: 
16488: For more detailed information, see lonnet specific documentation.
16489: 
16490: =head1 RETURN MESSAGES
16491: 
16492: =over 4
16493: 
16494: =item * B<con_lost>: unable to contact remote host
16495: 
16496: =item * B<con_delayed>: unable to contact remote host, message will be delivered
16497: when the connection is brought back up
16498: 
16499: =item * B<con_failed>: unable to contact remote host and unable to save message
16500: for later delivery
16501: 
16502: =item * B<error:>: an error a occurred, a description of the error follows the :
16503: 
16504: =item * B<no_such_host>: unable to fund a host associated with the user/domain
16505: that was requested
16506: 
16507: =back
16508: 
16509: =head1 PUBLIC SUBROUTINES
16510: 
16511: =head2 Session Environment Functions
16512: 
16513: =over 4
16514: 
16515: =item * 
16516: X<appenv()>
16517: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
16518: the user envirnoment file, and will be restored for each access this
16519: user makes during this session, also modifies the %env for the current
16520: process. Optional rolesarrayref - if defined contains a reference to an array
16521: of roles which are exempt from the restriction on modifying user.role entries 
16522: in the user's environment.db and in %env.    
16523: 
16524: =item *
16525: X<delenv()>
16526: B<delenv($delthis,$regexp)>: removes all items from the session
16527: environment file that begin with $delthis. If the 
16528: optional second arg - $regexp - is true, $delthis is treated as a 
16529: regular expression, otherwise \Q$delthis\E is used. 
16530: The values are also deleted from the current processes %env.
16531: 
16532: =item * get_env_multiple($name) 
16533: 
16534: gets $name from the %env hash, it seemlessly handles the cases where multiple
16535: values may be defined and end up as an array ref.
16536: 
16537: returns an array of values
16538: 
16539: =back
16540: 
16541: =head2 User Information
16542: 
16543: =over 4
16544: 
16545: =item *
16546: X<queryauthenticate()>
16547: B<queryauthenticate($uname,$udom)>: try to determine user's current 
16548: authentication scheme
16549: 
16550: =item *
16551: X<authenticate()>
16552: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
16553: authenticate user from domain's lib servers (first use the current
16554: one). C<$upass> should be the users password.
16555: $checkdefauth is optional (value is 1 if a check should be made to
16556:    authenticate user using default authentication method, and allow
16557:    account creation if username does not have account in the domain).
16558: $clientcancheckhost is optional (value is 1 if checking whether the
16559:    server can host will occur on the client side in lonauth.pm).   
16560: 
16561: =item *
16562: X<homeserver()>
16563: B<homeserver($uname,$udom)>: find the server which has
16564: the user's directory and files (there must be only one), this caches
16565: the answer, and also caches if there is a borken connection.
16566: 
16567: =item *
16568: X<idget()>
16569: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
16570: a list of student/employee IDs or clicker IDs
16571: (student/employee IDs are a unique resource in a domain, there must be 
16572: only 1 ID per username, and only 1 username per ID in a specific domain).
16573: clickerIDs are not necessarily unique, as students might share clickers.
16574: (returns hash: id=>name,id=>name)
16575: 
16576: =item *
16577: X<idrget()>
16578: B<idrget($udom,@unames)>: find the IDs behind a list of
16579: usernames (returns hash: name=>id,name=>id)
16580: 
16581: =item *
16582: X<idput()>
16583: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
16584: names and associated student/employee IDs or clicker IDs.
16585: 
16586: =item *
16587: X<iddel()>
16588: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
16589: student/employee ID or clicker ID username look-ups from domain.
16590: The homeserver ($uhome) and namespace ($namespace) are optional.
16591: If no $uhome is provided, it will be determined usig &homeserver()
16592: for each user.  If no $namespace is provided, the default is ids.
16593: 
16594: =item *
16595: X<updateclickers()>
16596: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
16597: clicker ID-to-username look-ups in clickers.db on library server.
16598: Permitted actions are add or del (i.e., add or delete). The 
16599: clickers.db contains clickerID as keys (escaped), and each corresponding
16600: value is an escaped comma-separated list of usernames (for whom the
16601: library server is the homeserver), who registered that particular ID.
16602: If $critical is true, the update will be sent via &critical, otherwise
16603: &reply() will be used.
16604: 
16605: =item *
16606: X<rolesinit()>
16607: B<rolesinit($udom,$username)>: get user privileges.
16608: returns user role, first access and timer interval hashes
16609: 
16610: =item *
16611: X<privileged()>
16612: B<privileged($username,$domain)>: returns a true if user has a
16613: privileged and active role (i.e. su or dc), false otherwise.
16614: 
16615: =item *
16616: X<getsection()>
16617: B<getsection($udom,$uname,$cname)>: finds the section of student in the
16618: course $cname, return section name/number or '' for "not in course"
16619: and '-1' for "no section"
16620: 
16621: =item *
16622: X<userenvironment()>
16623: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
16624: passed in @what from the requested user's environment, returns a hash
16625: 
16626: =item * 
16627: X<userlog_query()>
16628: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
16629: activity.log file. %filters defines filters applied when parsing the
16630: log file. These can be start or end timestamps, or the type of action
16631: - log to look for Login or Logout events, check for Checkin or
16632: Checkout, role for role selection. The response is in the form
16633: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
16634: escaped strings of the action recorded in the activity.log file.
16635: 
16636: =back
16637: 
16638: =head2 User Roles
16639: 
16640: =over 4
16641: 
16642: =item *
16643: 
16644: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
16645: returns codes for allowed actions.
16646: 
16647: The first argument is required, all others are optional.
16648: 
16649: $priv is the privilege being checked.
16650: $uri contains additional information about what is being checked for access (e.g.,
16651: URL, course ID etc.). 
16652: $symb is the unique resource instance identifier in a course; if needed,
16653: but not provided, it will be retrieved via a call to &symbread(). 
16654: $role is the role for which a priv is being checked (only used if priv is evb). 
16655: $clientip is the user's IP address (only used when checking for access to portfolio 
16656: files).
16657: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
16658: prevents recursive calls to &allowed.
16659: 
16660:  F: full access
16661:  U,I,K: authentication modes (cxx only)
16662:  '': forbidden
16663:  1: user needs to choose course
16664:  2: browse allowed
16665:  A: passphrase authentication needed
16666:  B: access temporarily blocked because of a blocking event in a course.
16667:  D: access blocked because access is required via session initiated via deep-link 
16668: 
16669: =item *
16670: 
16671: constructaccess($url,$setpriv) : check for access to construction space URL
16672: 
16673: See if the owner domain and name in the URL match those in the
16674: expected environment.  If so, return three element list
16675: ($ownername,$ownerdomain,$ownerhome).
16676: 
16677: Otherwise return the null string.
16678: 
16679: If second argument 'setpriv' is true, it assigns the privileges,
16680: and returns the same three element list, unless the owner has
16681: blocked "ad hoc" Domain Coordinator access to the Author Space,
16682: in which case the null string is returned.
16683: 
16684: =item *
16685: 
16686: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
16687: define a custom role rolename set privileges in format of lonTabs/roles.tab
16688: for system, domain, and course level. $uname and $udom are optional (current
16689: user's username and domain will be used when either of $uname or $udom are absent.
16690: 
16691: =item *
16692: 
16693: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
16694: (rolesplain.tab); plain text explanation of a user role term.
16695: $type is Course (default) or Community.
16696: If $forcedefault evaluates to true, text returned will be default 
16697: text for $type. Otherwise, if this is a course, the text returned 
16698: will be a custom name for the role (if defined in the course's 
16699: environment).  If no custom name is defined the default is returned.
16700:    
16701: =item *
16702: 
16703: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
16704: All arguments are optional. Returns a hash of a roles, either for
16705: co-author/assistant author roles for a user's Construction Space
16706: (default), or if $context is 'userroles', roles for the user himself,
16707: In the hash, keys are set to colon-separated $uname,$udom,$role, and
16708: (optionally) if $withsec is true, a fourth colon-separated item - $section.
16709: For each key, value is set to colon-separated start and end times for
16710: the role.  If no username and domain are specified, will default to
16711: current user/domain. Types, roles, and roledoms are references to arrays
16712: of role statuses (active, future or previous), roles 
16713: (e.g., cc,in, st etc.) and domains of the roles which can be used
16714: to restrict the list of roles reported. If no array ref is 
16715: provided for types, will default to return only active roles.
16716: 
16717: =item *
16718: 
16719: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
16720: user: $uname:$udom has a role in the course: $cdom_$cnum. 
16721: 
16722: Additional optional arguments are: $type (if role checking is to be restricted 
16723: to certain user status types -- previous (expired roles), active (currently
16724: available roles) or future (roles available in the future), and
16725: $hideprivileged -- if true will not report course roles for users who
16726: have active Domain Coordinator role in course's domain or in additional
16727: domains (specified in 'Domains to check for privileged users' in course
16728: environment -- set via:  Course Settings -> Classlists and staff listing).
16729: 
16730: =item *
16731: 
16732: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
16733: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
16734: $possdomains and $possroles are optional array refs -- to domains to check and
16735: roles to check.  If $possdomains is not specified, a dump will be done of the
16736: users' roles.db to check for a dc or su role in any domain. This can be
16737: time consuming if &privileged is called repeatedly (e.g., when displaying a
16738: classlist), so in such cases, supplying a $possdomains array is preferred, as
16739: this then allows &privileged_by_domain() to be used, which caches the identity
16740: of privileged users, eliminating the need for repeated calls to &dump().
16741: 
16742: =item *
16743: 
16744: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
16745: where the outer hash keys are domains specified in the $possdomains array ref,
16746: next inner hash keys are privileged roles specified in the $roles array ref,
16747: and the innermost hash contains key = value pairs for username:domain = end:start
16748: for active or future "privileged" users with that role in that domain. To avoid
16749: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
16750: innerhash are cached using priv_$role and $dom as the identifiers.
16751: 
16752: =back
16753: 
16754: =head2 User Modification
16755: 
16756: =over 4
16757: 
16758: =item *
16759: 
16760: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
16761: user for the level given by URL.  Optional start and end dates (leave empty
16762: string or zero for "no date")
16763: 
16764: =item *
16765: 
16766: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
16767: change a users, password, possible return values are: ok,
16768: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
16769: refused
16770: 
16771: =item *
16772: 
16773: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
16774: 
16775: =item *
16776: 
16777: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
16778:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
16779: 
16780: will update user information (firstname,middlename,lastname,generation,
16781: permanentemail), and if forceid is true, student/employee ID also.
16782: A user's institutional affiliation(s) can also be updated.
16783: User information fields will not be overwritten with empty entries 
16784: unless the field is included in the $candelete array reference.
16785: This array is included when a single user is modified via "Manage Users",
16786: or when Autoupdate.pl is run by cron in a domain.
16787: 
16788: =item *
16789: 
16790: modifystudent
16791: 
16792: modify a student's enrollment and identification information.
16793: The course id is resolved based on the current user's environment.  
16794: This means the invoking user must be a course coordinator or otherwise
16795: associated with a course.
16796: 
16797: This call is essentially a wrapper for lonnet::modifyuser and
16798: lonnet::modify_student_enrollment
16799: 
16800: Inputs: 
16801: 
16802: =over 4
16803: 
16804: =item B<$udom> Student's loncapa domain
16805: 
16806: =item B<$uname> Student's loncapa login name
16807: 
16808: =item B<$uid> Student/Employee ID
16809: 
16810: =item B<$umode> Student's authentication mode
16811: 
16812: =item B<$upass> Student's password
16813: 
16814: =item B<$first> Student's first name
16815: 
16816: =item B<$middle> Student's middle name
16817: 
16818: =item B<$last> Student's last name
16819: 
16820: =item B<$gene> Student's generation
16821: 
16822: =item B<$usec> Student's section in course
16823: 
16824: =item B<$end> Unix time of the roles expiration
16825: 
16826: =item B<$start> Unix time of the roles start date
16827: 
16828: =item B<$forceid> If defined, allow $uid to be changed
16829: 
16830: =item B<$desiredhome> server to use as home server for student
16831: 
16832: =item B<$email> Student's permanent e-mail address
16833: 
16834: =item B<$type> Type of enrollment (auto or manual)
16835: 
16836: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
16837: 
16838: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
16839: 
16840: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
16841: 
16842: =item B<$context> role change context (shown in User Management Logs display in a course)
16843: 
16844: =item B<$inststatus> institutional status of user - : separated string of escaped status types
16845: 
16846: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
16847: 
16848: =back
16849: 
16850: =item *
16851: 
16852: modify_student_enrollment
16853: 
16854: Change a student's enrollment status in a class.  The environment variable
16855: 'role.request.course' must be defined for this function to proceed.
16856: 
16857: Inputs:
16858: 
16859: =over 4
16860: 
16861: =item $udom, student's domain
16862: 
16863: =item $uname, student's name
16864: 
16865: =item $uid, student's user id
16866: 
16867: =item $first, student's first name
16868: 
16869: =item $middle
16870: 
16871: =item $last
16872: 
16873: =item $gene
16874: 
16875: =item $usec
16876: 
16877: =item $end
16878: 
16879: =item $start
16880: 
16881: =item $type
16882: 
16883: =item $locktype
16884: 
16885: =item $cid
16886: 
16887: =item $selfenroll
16888: 
16889: =item $context
16890: 
16891: =item $credits, number of credits student will earn from this class
16892: 
16893: =item $instsec, institutional course section code for student
16894: 
16895: =back
16896: 
16897: 
16898: =item *
16899: 
16900: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
16901: custom role; give a custom role to a user for the level given by URL.  Specify
16902: name and domain of role author, and role name
16903: 
16904: =item *
16905: 
16906: revokerole($udom,$uname,$url,$role) : revoke a role for url
16907: 
16908: =item *
16909: 
16910: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
16911: 
16912: =back
16913: 
16914: =head2 Course Infomation
16915: 
16916: =over 4
16917: 
16918: =item *
16919: 
16920: coursedescription($courseid,$options) : returns a hash of information about the
16921: specified course id, including all environment settings for the
16922: course, the description of the course will be in the hash under the
16923: key 'description'
16924: 
16925: $options is an optional parameter that if supplied is a hash reference that controls
16926: what how this function works.  It has the following key/values:
16927: 
16928: =over 4
16929: 
16930: =item freshen_cache
16931: 
16932: If defined, and the environment cache for the course is valid, it is 
16933: returned in the returned hash.
16934: 
16935: =item one_time
16936: 
16937: If defined, the last cache time is set to _now_
16938: 
16939: =item user
16940: 
16941: If defined, the supplied username is used instead of the current user.
16942: 
16943: 
16944: =back
16945: 
16946: =item *
16947: 
16948: resdata($name,$domain,$type,@which) : request for current parameter
16949: setting for a specific $type, where $type is either 'course' or 'user',
16950: @what should be a list of parameters to ask about. This routine caches
16951: answers for 10 minutes.
16952: 
16953: =item *
16954: 
16955: get_courseresdata($courseid, $domain) : dump the entire course resource
16956: data base, returning a hash that is keyed by the resource name and has
16957: values that are the resource value.  I believe that the timestamps and
16958: versions are also returned.
16959: 
16960: =back
16961: 
16962: =head2 Course Modification
16963: 
16964: =over 4
16965: 
16966: =item *
16967: 
16968: writecoursepref($courseid,%prefs) : write preferences (environment
16969: database) for a course
16970: 
16971: =item *
16972: 
16973: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
16974: 
16975: =item *
16976: 
16977: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
16978: 
16979: =item *
16980: 
16981: is_course($courseid), is_course($cdom, $cnum)
16982: 
16983: Accepts either a combined $courseid (in the form of domain_courseid) or the
16984: two component version $cdom, $cnum. It checks if the specified course exists.
16985: 
16986: Returns:
16987:     undef if the course doesn't exist, otherwise
16988:     in scalar context the combined courseid.
16989:     in list context the two components of the course identifier, domain and 
16990:     courseid.    
16991: 
16992: =back
16993: 
16994: =head2 Bubblesheet Configuration
16995: 
16996: =over 4
16997: 
16998: =item *
16999: 
17000: get_scantron_config($which)
17001: 
17002: $which - the name of the configuration to parse from the file.
17003: 
17004: Parses and returns the bubblesheet configuration line selected as a
17005: hash of configuration file fields.
17006: 
17007: 
17008: Returns:
17009:     If the named configuration is not in the file, an empty
17010:     hash is returned.
17011: 
17012:     a hash with the fields
17013:       name         - internal name for the this configuration setup
17014:       description  - text to display to operator that describes this config
17015:       CODElocation - if 0 or the string 'none'
17016:                           - no CODE exists for this config
17017:                      if -1 || the string 'letter'
17018:                           - a CODE exists for this config and is
17019:                             a string of letters
17020:                      Unsupported value (but planned for future support)
17021:                           if a positive integer
17022:                                - The CODE exists as the first n items from
17023:                                  the question section of the form
17024:                           if the string 'number'
17025:                                - The CODE exists for this config and is
17026:                                  a string of numbers
17027:       CODEstart   - (only matter if a CODE exists) column in the line where
17028:                      the CODE starts
17029:       CODElength  - length of the CODE
17030:       IDstart     - column where the student/employee ID starts
17031:       IDlength    - length of the student/employee ID info
17032:       Qstart      - column where the information from the bubbled
17033:                     'questions' start
17034:       Qlength     - number of columns comprising a single bubble line from
17035:                     the sheet. (usually either 1 or 10)
17036:       Qon         - either a single character representing the character used
17037:                     to signal a bubble was chosen in the positional setup, or
17038:                     the string 'letter' if the letter of the chosen bubble is
17039:                     in the final, or 'number' if a number representing the
17040:                     chosen bubble is in the file (1->A 0->J)
17041:       Qoff        - the character used to represent that a bubble was
17042:                     left blank
17043:       PaperID     - if the scanning process generates a unique number for each
17044:                     sheet scanned the column that this ID number starts in
17045:       PaperIDlength - number of columns that comprise the unique ID number
17046:                       for the sheet of paper
17047:       FirstName   - column that the first name starts in
17048:       FirstNameLength - number of columns that the first name spans
17049:       LastName    - column that the last name starts in
17050:       LastNameLength - number of columns that the last name spans
17051:       BubblesPerRow - number of bubbles available in each row used to
17052:                       bubble an answer. (If not specified, 10 assumed).
17053: 
17054: 
17055: =item *
17056: 
17057: get_scantronformat_file($cdom)
17058: 
17059: $cdom - the course's domain (optional); if not supplied, uses
17060: domain for current $env{'request.course.id'}.
17061: 
17062: Returns an array containing lines from the scantron format file for
17063: the domain of the course.
17064: 
17065: If a url for a custom.tab file is listed in domain's configuration.db,
17066: lines are from this file.
17067: 
17068: Otherwise, if a default.tab has been published in RES space by the
17069: domainconfig user, lines are from this file.
17070: 
17071: Otherwise, fall back to getting lines from the legacy file on the
17072: local server:  /home/httpd/lonTabs/default_scantronformat.tab
17073: 
17074: =back
17075: 
17076: =head2 Resource Subroutines
17077: 
17078: =over 4
17079: 
17080: =item *
17081: 
17082: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
17083: 
17084: =item *
17085: 
17086: repcopy($filename) : subscribes to the requested file, and attempts to
17087: replicate from the owning library server, Might return
17088: 'unavailable', 'not_found', 'forbidden', 'ok', or
17089: 'bad_request', also attempts to grab the metadata for the
17090: resource. Expects the local filesystem pathname
17091: (/home/httpd/html/res/....)
17092: 
17093: =back
17094: 
17095: =head2 Resource Information
17096: 
17097: =over 4
17098: 
17099: =item *
17100: 
17101: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
17102: and returns the value of a variety of different possible values,
17103: $varname should be a request string, and the other parameters can be
17104: used to specify who and what one is asking about. Ordinarily, $cid 
17105: does not need to be specified, as it is retrived from 
17106: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
17107: within lonuserstate::loadmap() when initializing a course, before
17108: $env{'request.course.id'} has been set, so it needs to be provided
17109: in that one case.
17110: 
17111: Possible values for $varname are environment.lastname (or other item
17112: from the envirnment hash), user.name (or someother aspect about the
17113: user), resource.0.maxtries (or some other part and parameter of a
17114: resource)
17115: 
17116: =item *
17117: 
17118: directcondval($number) : get current value of a condition; reads from a state
17119: string
17120: 
17121: =item *
17122: 
17123: condval($condidx) : value of condition index based on state
17124: 
17125: =item *
17126: 
17127: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
17128: resource's metadata, $what should be either a specific key, or either
17129: 'keys' (to get a list of possible keys) or 'packages' to get a list of
17130: packages that this resource currently uses, the last 3 arguments are 
17131: only used internally for recursive metadata.
17132: 
17133: the toolsymb is only used where the uri is for an external tool (for which
17134: the uri as well as the symb are guaranteed to be unique).
17135: 
17136: this function automatically caches all requests except any made recursively
17137: to retrieve a list of metadata keys for an imported library file ($liburi is 
17138: defined).
17139: 
17140: =item *
17141: 
17142: metadata_query($query,$custom,$customshow) : make a metadata query against the
17143: network of library servers; returns file handle of where SQL and regex results
17144: will be stored for query
17145: 
17146: =item *
17147: 
17148: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
17149: return symbolic list entry (all arguments optional). 
17150: 
17151: Args: filename is the filename (including path) for the file for which a symb 
17152: is required; donotrecurse, if true will prevent calls to allowed() being made 
17153: to check access status if more than one resource was found in the bighash 
17154: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
17155: a randompick); ignorecachednull, if true will prevent a symb of '' being 
17156: returned if $env{$cache_str} is defined as ''; checkforblock if true will
17157: cause possible symbs to be checked to determine if they are subject to content
17158: blocking, if so they will not be included as possible symbs; possibles is a
17159: ref to a hash, which, as a side effect, will be populated with all possible 
17160: symbs (content blocking not tested).
17161:  
17162: returns the data handle
17163: 
17164: =item *
17165: 
17166: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
17167: and is a possible symb for the URL in $thisfn, and if is an encrypted
17168: resource that the user accessed using /enc/ returns a 1 on success, 0
17169: on failure, user must be in a course, as it assumes the existence of
17170: the course initial hash, and uses $env('request.course.id'}.  The third
17171: arg is an optional reference to a scalar.  If this arg is passed in the 
17172: call to symbverify, it will be set to 1 if the symb has been set to be 
17173: encrypted; otherwise it will be null.  
17174: 
17175: =item *
17176: 
17177: symbclean($symb) : removes versions numbers from a symb, returns the
17178: cleaned symb
17179: 
17180: =item *
17181: 
17182: is_on_map($uri) : checks if the $uri is somewhere on the current
17183: course map, user must be in a course for it to work.
17184: 
17185: =item *
17186: 
17187: numval($salt) : return random seed value (addend for rndseed)
17188: 
17189: =item *
17190: 
17191: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
17192: a random seed, all arguments are optional, if they aren't sent it uses the
17193: environment to derive them. Note: if symb isn't sent and it can't get one
17194: from &symbread it will use the current time as its return value
17195: 
17196: =item *
17197: 
17198: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
17199: unfakeable, receipt
17200: 
17201: =item *
17202: 
17203: receipt() : API to ireceipt working off of env values; given out to users
17204: 
17205: =item *
17206: 
17207: countacc($url) : count the number of accesses to a given URL
17208: 
17209: =item *
17210: 
17211: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
17212: 
17213: =item *
17214: 
17215: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
17216: 
17217: =item *
17218: 
17219: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
17220: 
17221: =item *
17222: 
17223: devalidate($symb) : devalidate temporary spreadsheet calculations,
17224: forcing spreadsheet to reevaluate the resource scores next time.
17225: 
17226: =item * 
17227: 
17228: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
17229: when viewing in course context.
17230: 
17231:  input: six args -- filename (decluttered), course number, course domain,
17232:                     url, symb (if registered) and group (if this is a 
17233:                     group item -- e.g., bulletin board, group page etc.).
17234: 
17235:  output: array of five scalars --
17236:          $cfile -- url for file editing if editable on current server
17237:          $home -- homeserver of resource (i.e., for author if published,
17238:                                           or course if uploaded.).
17239:          $switchserver --  1 if server switch will be needed.
17240:          $forceedit -- 1 if icon/link should be to go to edit mode 
17241:          $forceview -- 1 if icon/link should be to go to view mode
17242: 
17243: =item *
17244: 
17245: is_course_upload($file,$cnum,$cdom)
17246: 
17247: Used in course context to determine if current file was uploaded to 
17248: the course (i.e., would be found in /userfiles/docs on the course's 
17249: homeserver.
17250: 
17251:   input: 3 args -- filename (decluttered), course number and course domain.
17252:   output: boolean -- 1 if file was uploaded.
17253: 
17254: =back
17255: 
17256: =head2 Storing/Retreiving Data
17257: 
17258: =over 4
17259: 
17260: =item *
17261: 
17262: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
17263: permanently for this url; hashref needs to be given and should be a \%hashname;
17264: the remaining args aren't required and if they aren't passed or are '' they will
17265: be derived from the env (with the exception of $laststore, which is an 
17266: optional arg used when a user's submission is stored in grading).
17267: $laststore is $version=$timestamp, where $version is the most recent version
17268: number retrieved for the corresponding $symb in the $namespace db file, and
17269: $timestamp is the timestamp for that transaction (UNIX time).
17270: $laststore is currently only passed when cstore() is called by 
17271: structuretags::finalize_storage().
17272: 
17273: =item *
17274: 
17275: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
17276: but uses critical subroutine
17277: 
17278: =item *
17279: 
17280: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
17281: all args are optional
17282: 
17283: =item *
17284: 
17285: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
17286: dumps the complete (or key matching regexp) namespace into a hash
17287: ($udom, $uname, $regexp, $range are optional) for a namespace that is
17288: normally &store()ed into
17289: 
17290: $range should be either an integer '100' (give me the first 100
17291:                                            matching records)
17292:               or be  two integers sperated by a - with no spaces
17293:                  '30-50' (give me the 30th through the 50th matching
17294:                           records)
17295: 
17296: 
17297: =item *
17298: 
17299: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
17300: replaces a &store() version of data with a replacement set of data
17301: for a particular resource in a namespace passed in the $storehash hash 
17302: reference. If $tolog is true, the transaction is logged in the courselog
17303: with an action=PUTSTORE.
17304: 
17305: =item *
17306: 
17307: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
17308: works very similar to store/cstore, but all data is stored in a
17309: temporary location and can be reset using tmpreset, $storehash should
17310: be a hash reference, returns nothing on success
17311: 
17312: =item *
17313: 
17314: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
17315: similar to restore, but all data is stored in a temporary location and
17316: can be reset using tmpreset. Returns a hash of values on success,
17317: error string otherwise.
17318: 
17319: =item *
17320: 
17321: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
17322: deltes all keys for $symb form the temporary storage hash.
17323: 
17324: =item *
17325: 
17326: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17327: reference filled in from namesp ($udom and $uname are optional)
17328: 
17329: =item *
17330: 
17331: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
17332: namesp ($udom and $uname are optional)
17333: 
17334: =item *
17335: 
17336: dump($namespace,$udom,$uname,$regexp,$range) : 
17337: dumps the complete (or key matching regexp) namespace into a hash
17338: ($udom, $uname, $regexp, $range are optional)
17339: 
17340: $range should be either an integer '100' (give me the first 100
17341:                                            matching records)
17342:               or be  two integers sperated by a - with no spaces
17343:                  '30-50' (give me the 30th through the 50th matching
17344:                           records)
17345: =item *
17346: 
17347: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
17348: $store can be a scalar, an array reference, or if the amount to be 
17349: incremented is > 1, a hash reference.
17350: 
17351: ($udom and $uname are optional)
17352: 
17353: =item *
17354: 
17355: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
17356: ($udom and $uname are optional)
17357: 
17358: =item *
17359: 
17360: cput($namespace,$storehash,$udom,$uname) : critical put
17361: ($udom and $uname are optional)
17362: 
17363: =item *
17364: 
17365: newput($namespace,$storehash,$udom,$uname) :
17366: 
17367: Attempts to store the items in the $storehash, but only if they don't
17368: currently exist, if this succeeds you can be certain that you have 
17369: successfully created a new key value pair in the $namespace db.
17370: 
17371: 
17372: Args:
17373:  $namespace: name of database to store values to
17374:  $storehash: hashref to store to the db
17375:  $udom: (optional) domain of user containing the db
17376:  $uname: (optional) name of user caontaining the db
17377: 
17378: Returns:
17379:  'ok' -> succeeded in storing all keys of $storehash
17380:  'key_exists: <key>' -> failed to anything out of $storehash, as at
17381:                         least <key> already existed in the db (other
17382:                         requested keys may also already exist)
17383:  'error: <msg>' -> unable to tie the DB or other error occurred
17384:  'con_lost' -> unable to contact request server
17385:  'refused' -> action was not allowed by remote machine
17386: 
17387: 
17388: =item *
17389: 
17390: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
17391: reference filled in from namesp (encrypts the return communication)
17392: ($udom and $uname are optional)
17393: 
17394: =item *
17395: 
17396: log($udom,$name,$home,$message) : write to permanent log for user; use
17397: critical subroutine
17398: 
17399: =item *
17400: 
17401: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
17402: array reference filled in from namespace found in domain level on either
17403: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
17404: 
17405: =item *
17406: 
17407: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
17408: domain level either on specified domain server ($uhome) or primary domain 
17409: server ($udom and $uhome are optional)
17410: 
17411: =item * 
17412: 
17413: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
17414: for: authentication, language, quotas, timezone, date locale, and portal URL in
17415: the target domain.
17416: 
17417: May also include additional key => value pairs for the following groups:
17418: 
17419: =over
17420: 
17421: =item
17422: disk quotas (MB allocated by default to portfolios and authoring spaces).
17423: 
17424: =over
17425: 
17426: =item defaultquota, authorquota
17427: 
17428: =back
17429: 
17430: =item
17431: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
17432: portfolio for users).
17433: 
17434: =over
17435: 
17436: =item
17437: aboutme, blog, webdav, portfolio
17438: 
17439: =back
17440: 
17441: =item
17442: requestcourses: ability to request courses, and how requests are processed.
17443: 
17444: =over
17445: 
17446: =item
17447: official, unofficial, community, textbook, placement
17448: 
17449: =back
17450: 
17451: =item
17452: inststatus: types of institutional affiliation, and order in which they are displayed.
17453: 
17454: =over
17455: 
17456: =item
17457: inststatustypes, inststatusorder, inststatusguest
17458: 
17459: =back
17460: 
17461: =item
17462: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
17463: for course's uploaded content.
17464: 
17465: =over
17466: 
17467: =item
17468: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
17469: communityquota, textbookquota, placementquota
17470: 
17471: =back
17472: 
17473: =item
17474: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
17475: on your servers.
17476: 
17477: =over
17478: 
17479: =item 
17480: remotesessions, hostedsessions
17481: 
17482: =back
17483: 
17484: =back
17485: 
17486: In cases where a domain coordinator has never used the "Set Domain Configuration"
17487: utility to create a configuration.db file on a domain's primary library server 
17488: only the following domain defaults: auth_def, auth_arg_def, lang_def
17489: -- corresponding values are authentication type (internal, krb4, krb5,
17490: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
17491: will be available. Values are retrieved from cache (if current), unless the
17492: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
17493: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
17494: 
17495: Typical usage:
17496: 
17497: %domdefaults = &get_domain_defaults($target_domain);
17498: 
17499: =back
17500: 
17501: =head2 Network Status Functions
17502: 
17503: =over 4
17504: 
17505: =item *
17506: 
17507: dirlist() : return directory list based on URI (first arg).
17508: 
17509: Inputs: 1 required, 5 optional.
17510: 
17511: =over
17512: 
17513: =item 
17514: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
17515: 
17516: =item
17517: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
17518: 
17519: =item
17520: $username -  username of user/course to be listed. Extracted from $uri if absent. 
17521: 
17522: =item
17523: $getpropath - boolean: 1 if prepend path using &propath(). 
17524: 
17525: =item
17526: $getuserdir - boolean: 1 if prepend path for "userfiles".
17527: 
17528: =item 
17529: $alternateRoot - path to prepend in place of path from $uri.
17530: 
17531: =back
17532: 
17533: Returns: Array of up to two items.
17534: 
17535: =over
17536: 
17537: a reference to an array of files/subdirectories
17538: 
17539: =over
17540: 
17541: Each element in the array of files/subdirectories is a & separated list of
17542: item name and the result of running stat on the item.  If dirlist was requested
17543: for a file instead of a directory, the item name will be ''. For a directory 
17544: listing, if the item is a metadata file, the element will end &N&M 
17545: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
17546: default copyright set (1).  
17547: 
17548: =back
17549: 
17550: a scalar containing error condition (if encountered).
17551: 
17552: =over
17553: 
17554: =item 
17555: no_host (no homeserver identified for $username:$domain).
17556: 
17557: =item 
17558: no_such_host (server contacted for listing not identified as valid host).
17559: 
17560: =item 
17561: con_lost (connection to remote server failed).
17562: 
17563: =item 
17564: refused (invalid $username:$domain received on lond side).
17565: 
17566: =item 
17567: no_such_dir (directory at specified path on lond side does not exist). 
17568: 
17569: =item 
17570: empty (directory at specified path on lond side is empty).
17571: 
17572: =over
17573: 
17574: This is currently not encountered because the &ls3, &ls2, 
17575: &ls (_handler) routines on the lond side do not filter out
17576: . and .. from a directory listing. 
17577: 
17578: =back
17579: 
17580: =back
17581: 
17582: =back
17583: 
17584: =item *
17585: 
17586: spareserver() : find server with least workload from spare.tab
17587: 
17588: 
17589: =item *
17590: 
17591: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
17592: if there is no corresponding loncapa host.
17593: 
17594: =back
17595: 
17596: 
17597: =head2 Apache Request
17598: 
17599: =over 4
17600: 
17601: =item *
17602: 
17603: ssi($url,%hash) : server side include, does a complete request cycle on url to
17604: localhost, posts hash
17605: 
17606: =back
17607: 
17608: =head2 Data to String to Data
17609: 
17610: =over 4
17611: 
17612: =item *
17613: 
17614: hash2str(%hash) : convert a hash into a string complete with escaping and '='
17615: and '&' separators, supports elements that are arrayrefs and hashrefs
17616: 
17617: =item *
17618: 
17619: hashref2str($hashref) : convert a hashref into a string complete with
17620: escaping and '=' and '&' separators, supports elements that are
17621: arrayrefs and hashrefs
17622: 
17623: =item *
17624: 
17625: arrayref2str($arrayref) : convert an arrayref into a string complete
17626: with escaping and '&' separators, supports elements that are arrayrefs
17627: and hashrefs
17628: 
17629: =item *
17630: 
17631: str2hash($string) : convert string to hash using unescaping and
17632: splitting on '=' and '&', supports elements that are arrayrefs and
17633: hashrefs
17634: 
17635: =item *
17636: 
17637: str2array($string) : convert string to hash using unescaping and
17638: splitting on '&', supports elements that are arrayrefs and hashrefs
17639: 
17640: =back
17641: 
17642: =head2 Logging Routines
17643: 
17644: 
17645: These routines allow one to make log messages in the lonnet.log and
17646: lonnet.perm logfiles.
17647: 
17648: =over 4
17649: 
17650: =item *
17651: 
17652: logtouch() : make sure the logfile, lonnet.log, exists
17653: 
17654: =item *
17655: 
17656: logthis() : append message to the normal lonnet.log file, it gets
17657: preiodically rolled over and deleted.
17658: 
17659: =item *
17660: 
17661: logperm() : append a permanent message to lonnet.perm.log, this log
17662: file never gets deleted by any automated portion of the system, only
17663: messages of critical importance should go in here.
17664: 
17665: 
17666: =back
17667: 
17668: =head2 General File Helper Routines
17669: 
17670: =over 4
17671: 
17672: =item *
17673: 
17674: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
17675: (a) files in /uploaded
17676:   (i) If a local copy of the file exists - 
17677:       compares modification date of local copy with last-modified date for 
17678:       definitive version stored on home server for course. If local copy is 
17679:       stale, requests a new version from the home server and stores it. 
17680:       If the original has been removed from the home server, then local copy 
17681:       is unlinked.
17682:   (ii) If local copy does not exist -
17683:       requests the file from the home server and stores it. 
17684:   
17685:   If $caller is 'uploadrep':  
17686:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
17687:     for request for files originally uploaded via DOCS. 
17688:      - returns 'ok' if fresh local copy now available, -1 otherwise.
17689:   
17690:   Otherwise:
17691:      This indicates a call from the content generation phase of the request.
17692:      -  returns the entire contents of the file or -1.
17693:      
17694: (b) files in /res
17695:    - returns the entire contents of a file or -1; 
17696:    it properly subscribes to and replicates the file if neccessary.
17697: 
17698: 
17699: =item *
17700: 
17701: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
17702:                   reference
17703: 
17704: returns either a stat() list of data about the file or an empty list
17705: if the file doesn't exist or couldn't find out about it (connection
17706: problems or user unknown)
17707: 
17708: =item *
17709: 
17710: filelocation($dir,$file) : returns file system location of a file
17711: based on URI; meant to be "fairly clean" absolute reference, $dir is a
17712: directory that relative $file lookups are to looked in ($dir of /a/dir
17713: and a file of ../bob will become /a/bob)
17714: 
17715: =item *
17716: 
17717: hreflocation($dir,$file) : returns file system location or a URL; same as
17718: filelocation except for hrefs
17719: 
17720: =item *
17721: 
17722: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
17723: also removes beginning /home/httpd/html unless /priv/ follows it.
17724: 
17725: =back
17726: 
17727: =head2 Usererfile file routines (/uploaded*)
17728: 
17729: =over 4
17730: 
17731: =item *
17732: 
17733: userfileupload(): main rotine for putting a file in a user or course's
17734:                   filespace, arguments are,
17735: 
17736:  formname - required - this is the name of the element in $env where the
17737:            filename, and the contents of the file to create/modifed exist
17738:            the filename is in $env{'form.'.$formname.'.filename'} and the
17739:            contents of the file is located in $env{'form.'.$formname}
17740:  context - if coursedoc, store the file in the course of the active role
17741:              of the current user; 
17742:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
17743:            if 'canceloverwrite': delete file in tmp/overwrites directory
17744:  subdir - required - subdirectory to put the file in under ../userfiles/
17745:          if undefined, it will be placed in "unknown"
17746: 
17747:  (This routine calls clean_filename() to remove any dangerous
17748:  characters from the filename, and then calls finuserfileupload() to
17749:  complete the transaction)
17750: 
17751:  returns either the url of the uploaded file (/uploaded/....) if successful
17752:  and /adm/notfound.html if unsuccessful
17753: 
17754: =item *
17755: 
17756: clean_filename(): routine for cleaing a filename up for storage in
17757:                  userfile space, argument is:
17758: 
17759:  filename - proposed filename
17760: 
17761: returns: the new clean filename
17762: 
17763: =item *
17764: 
17765: finishuserfileupload(): routine that creates and sends the file to
17766: userspace, probably shouldn't be called directly
17767: 
17768:   docuname: username or courseid of destination for the file
17769:   docudom: domain of user/course of destination for the file
17770:   formname: same as for userfileupload()
17771:   fname: filename (including subdirectories) for the file
17772:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
17773:           if hashref, and context is scantron, will convert csv format to standard format
17774:   allfiles: reference to hash used to store objects found by parser
17775:   codebase: reference to hash used for codebases of java objects found by parser
17776:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
17777:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
17778:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
17779:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
17780:   context: if 'overwrite', will move the uploaded file from its temporary location to
17781:             userfiles to facilitate overwriting a previously uploaded file with same name.
17782:   mimetype: reference to scalar to accommodate mime type determined
17783:             from File::MMagic if $parser = parse.
17784: 
17785:  returns either the url of the uploaded file (/uploaded/....) if successful
17786:  and /adm/notfound.html if unsuccessful (or an error message if context 
17787:  was 'overwrite').
17788:  
17789: 
17790: =item *
17791: 
17792: renameuserfile(): renames an existing userfile to a new name
17793: 
17794:   Args:
17795:    docuname: username or courseid of destination for the file
17796:    docudom: domain of user/course of destination for the file
17797:    old: current file name (including any subdirs under userfiles)
17798:    new: desired file name (including any subdirs under userfiles)
17799: 
17800: =item *
17801: 
17802: mkdiruserfile(): creates a directory is a userfiles dir
17803: 
17804:   Args:
17805:    docuname: username or courseid of destination for the file
17806:    docudom: domain of user/course of destination for the file
17807:    dir: dir to create (including any subdirs under userfiles)
17808: 
17809: =item *
17810: 
17811: removeuserfile(): removes a file that exists in userfiles
17812: 
17813:   Args:
17814:    docuname: username or courseid of destination for the file
17815:    docudom: domain of user/course of destination for the file
17816:    fname: filname to delete (including any subdirs under userfiles)
17817: 
17818: =item *
17819: 
17820: removeuploadedurl(): convience function for removeuserfile()
17821: 
17822:   Args:
17823:    url:  a full /uploaded/... url to delete
17824: 
17825: =item * 
17826: 
17827: get_portfile_permissions():
17828:   Args:
17829:     domain: domain of user or course contain the portfolio files
17830:     user: name of user or num of course contain the portfolio files
17831:   Returns:
17832:     hashref of a dump of the proper file_permissions.db
17833:    
17834: 
17835: =item * 
17836: 
17837: get_access_controls():
17838: 
17839: Args:
17840:   current_permissions: the hash ref returned from get_portfile_permissions()
17841:   group: (optional) the group you want the files associated with
17842:   file: (optional) the file you want access info on
17843: 
17844: Returns:
17845:     a hash (keys are file names) of hashes containing
17846:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
17847:         values are XML containing access control settings (see below) 
17848: 
17849: Internal notes:
17850: 
17851:  access controls are stored in file_permissions.db as key=value pairs.
17852:     key -> path to file/file_name\0uniqueID:scope_end_start
17853:         where scope -> public,guest,course,group,domains or users.
17854:               end -> UNIX time for end of access (0 -> no end date)
17855:               start -> UNIX time for start of access
17856: 
17857:     value -> XML description of access control
17858:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
17859:             <start></start>
17860:             <end></end>
17861: 
17862:             <password></password>  for scope type = guest
17863: 
17864:             <domain></domain>     for scope type = course or group
17865:             <number></number>
17866:             <roles id="">
17867:              <role></role>
17868:              <access></access>
17869:              <section></section>
17870:              <group></group>
17871:             </roles>
17872: 
17873:             <dom></dom>         for scope type = domains
17874: 
17875:             <users>             for scope type = users
17876:              <user>
17877:               <uname></uname>
17878:               <udom></udom>
17879:              </user>
17880:             </users>
17881:            </scope> 
17882:               
17883:  Access data is also aggregated for each file in an additional key=value pair:
17884:  key -> path to file/file_name\0accesscontrol 
17885:  value -> reference to hash
17886:           hash contains key = value pairs
17887:           where key = uniqueID:scope_end_start
17888:                 value = UNIX time record was last updated
17889: 
17890:           Used to improve speed of look-ups of access controls for each file.  
17891:  
17892:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
17893: 
17894: =item *
17895: 
17896: modify_access_controls():
17897: 
17898: Modifies access controls for a portfolio file
17899: Args
17900: 1. file name
17901: 2. reference to hash of required changes,
17902: 3. domain
17903: 4. username
17904:   where domain,username are the domain of the portfolio owner 
17905:   (either a user or a course) 
17906: 
17907: Returns:
17908: 1. result of additions or updates ('ok' or 'error', with error message). 
17909: 2. result of deletions ('ok' or 'error', with error message).
17910: 3. reference to hash of any new or updated access controls.
17911: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
17912:    key = integer (inbound ID)
17913:    value = uniqueID
17914: 
17915: =item *
17916: 
17917: get_timebased_id():
17918: 
17919: Attempts to get a unique timestamp-based suffix for use with items added to a 
17920: course via the Course Editor (e.g., folders, composite pages, 
17921: group bulletin boards).
17922: 
17923: Args: (first three required; six others optional)
17924: 
17925: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
17926:    docssequence, or name of group
17927: 
17928: 2. keyid (alphanumeric): name of temporary locking key in hash,
17929:    e.g., num, boardids
17930: 
17931: 3. namespace: name of gdbm file used to store suffixes already assigned;  
17932:    file will be named nohist_namespace.db
17933: 
17934: 4. cdom: domain of course; default is current course domain from %env
17935: 
17936: 5. cnum: course number; default is current course number from %env
17937: 
17938: 6. idtype: set to concat if an additional digit is to be appended to the 
17939:    unix timestamp to form the suffix, if the plain timestamp is already
17940:    in use.  Default is to not do this, but simply increment the unix 
17941:    timestamp by 1 until a unique key is obtained.
17942: 
17943: 7. who: holder of locking key; defaults to user:domain for user.
17944: 
17945: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
17946:    retrying); default is 3.
17947: 
17948: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
17949: 
17950: Returns:
17951: 
17952: 1. suffix obtained (numeric)
17953: 
17954: 2. result of deleting locking key (ok if deleted, or lock never obtained)
17955: 
17956: 3. error: contains (localized) error message if an error occurred.
17957: 
17958: 
17959: =back
17960: 
17961: =head2 HTTP Helper Routines
17962: 
17963: =over 4
17964: 
17965: =item *
17966: 
17967: escape() : unpack non-word characters into CGI-compatible hex codes
17968: 
17969: =item *
17970: 
17971: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
17972: 
17973: =back
17974: 
17975: =head1 PRIVATE SUBROUTINES
17976: 
17977: =head2 Underlying communication routines (Shouldn't call)
17978: 
17979: =over 4
17980: 
17981: =item *
17982: 
17983: subreply() : tries to pass a message to lonc, returns con_lost if incapable
17984: 
17985: =item *
17986: 
17987: reply() : uses subreply to send a message to remote machine, logs all failures
17988: 
17989: =item *
17990: 
17991: critical() : passes a critical message to another server; if cannot
17992: get through then place message in connection buffer directory and
17993: returns con_delayed, if incapable of saving message, returns
17994: con_failed
17995: 
17996: =item *
17997: 
17998: reconlonc() : tries to reconnect lonc client processes.
17999: 
18000: =back
18001: 
18002: =head2 Resource Access Logging
18003: 
18004: =over 4
18005: 
18006: =item *
18007: 
18008: flushcourselogs() : flush (save) buffer logs and access logs
18009: 
18010: =item *
18011: 
18012: courselog($what) : save message for course in hash
18013: 
18014: =item *
18015: 
18016: courseacclog($what) : save message for course using &courselog().  Perform
18017: special processing for specific resource types (problems, exams, quizzes, etc).
18018: 
18019: =item *
18020: 
18021: goodbye() : flush course logs and log shutting down; it is called in srm.conf
18022: as a PerlChildExitHandler
18023: 
18024: =back
18025: 
18026: =head2 Other
18027: 
18028: =over 4
18029: 
18030: =item *
18031: 
18032: symblist($mapname,%newhash) : update symbolic storage links
18033: 
18034: =back
18035: 
18036: =cut
18037: 

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