File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.587.2.3.2.4: download - view: text, annotated - select for diffs
Mon Feb 14 02:17:51 2005 UTC (19 years, 4 months ago) by albertel
Branches: version_1_3_X_memcached
Diff to branchpoint 1.587.2.3: preferred, unified
- titles were being cached again $symb  which isn't specific enough need to toss a courseid in there

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.587.2.3.2.4 2005/02/14 02:17:51 albertel 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: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab %courseresversioncache %resversioncache
   40:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %courseresdatacache 
   42:    %userresdatacache %getsectioncache %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit);
   44: 
   45: use IO::Socket;
   46: use GDBM_File;
   47: use Apache::Constants qw(:common :http);
   48: use HTML::LCParser;
   49: use Fcntl qw(:flock);
   50: use Apache::lonlocal;
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: my $readit;
   55: my $max_connection_retries = 10;     # Or some such value.
   56: 
   57: =pod
   58: 
   59: =head1 Package Variables
   60: 
   61: These are largely undocumented, so if you decipher one please note it here.
   62: 
   63: =over 4
   64: 
   65: =item $processmarker
   66: 
   67: Contains the time this process was started and this servers host id.
   68: 
   69: =item $dumpcount
   70: 
   71: Counts the number of times a message log flush has been attempted (regardless
   72: of success) by this process.  Used as part of the filename when messages are
   73: delayed.
   74: 
   75: =back
   76: 
   77: =cut
   78: 
   79: 
   80: # --------------------------------------------------------------------- Logging
   81: 
   82: sub logtouch {
   83:     my $execdir=$perlvar{'lonDaemons'};
   84:     unless (-e "$execdir/logs/lonnet.log") {	
   85: 	open(my $fh,">>$execdir/logs/lonnet.log");
   86: 	close $fh;
   87:     }
   88:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
   89:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
   90: }
   91: 
   92: sub logthis {
   93:     my $message=shift;
   94:     my $execdir=$perlvar{'lonDaemons'};
   95:     my $now=time;
   96:     my $local=localtime($now);
   97:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
   98: 	print $fh "$local ($$): $message\n";
   99: 	close($fh);
  100:     }
  101:     return 1;
  102: }
  103: 
  104: sub logperm {
  105:     my $message=shift;
  106:     my $execdir=$perlvar{'lonDaemons'};
  107:     my $now=time;
  108:     my $local=localtime($now);
  109:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  110: 	print $fh "$now:$message:$local\n";
  111: 	close($fh);
  112:     }
  113:     return 1;
  114: }
  115: 
  116: # -------------------------------------------------- Non-critical communication
  117: sub subreply {
  118:     my ($cmd,$server)=@_;
  119:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  120:     #
  121:     #  With loncnew process trimming, there's a timing hole between lonc server
  122:     #  process exit and the master server picking up the listen on the AF_UNIX
  123:     #  socket.  In that time interval, a lock file will exist:
  124: 
  125:     my $lockfile=$peerfile.".lock";
  126:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  127: 	sleep(1);
  128:     }
  129:     # At this point, either a loncnew parent is listening or an old lonc
  130:     # or loncnew child is listening so we can connect or everything's dead.
  131:     #
  132:     #   We'll give the connection a few tries before abandoning it.  If
  133:     #   connection is not possible, we'll con_lost back to the client.
  134:     #   
  135:     my $client;
  136:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  137: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  138: 				      Type    => SOCK_STREAM,
  139: 				      Timeout => 10);
  140: 	if($client) {
  141: 	    last;		# Connected!
  142: 	}
  143: 	sleep(1);		# Try again later if failed connection.
  144:     }
  145:     my $answer;
  146:     if ($client) {
  147: 	print $client "$cmd\n";
  148: 	$answer=<$client>;
  149: 	if (!$answer) { $answer="con_lost"; }
  150: 	chomp($answer);
  151:     } else {
  152: 	$answer = 'con_lost';	# Failed connection.
  153:     }
  154:     return $answer;
  155: }
  156: 
  157: sub reply {
  158:     my ($cmd,$server)=@_;
  159:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  160:     my $answer=subreply($cmd,$server);
  161:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  162:        &logthis("<font color=blue>WARNING:".
  163:                 " $cmd to $server returned $answer</font>");
  164:     }
  165:     return $answer;
  166: }
  167: 
  168: # ----------------------------------------------------------- Send USR1 to lonc
  169: 
  170: sub reconlonc {
  171:     my $peerfile=shift;
  172:     &logthis("Trying to reconnect for $peerfile");
  173:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  174:     if (open(my $fh,"<$loncfile")) {
  175: 	my $loncpid=<$fh>;
  176:         chomp($loncpid);
  177:         if (kill 0 => $loncpid) {
  178: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  179:             kill USR1 => $loncpid;
  180:             sleep 1;
  181:             if (-e "$peerfile") { return; }
  182:             &logthis("$peerfile still not there, give it another try");
  183:             sleep 5;
  184:             if (-e "$peerfile") { return; }
  185:             &logthis(
  186:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  187:         } else {
  188: 	    &logthis(
  189:                "<font color=blue>WARNING:".
  190:                " lonc at pid $loncpid not responding, giving up</font>");
  191:         }
  192:     } else {
  193:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  194:     }
  195: }
  196: 
  197: # ------------------------------------------------------ Critical communication
  198: 
  199: sub critical {
  200:     my ($cmd,$server)=@_;
  201:     unless ($hostname{$server}) {
  202:         &logthis("<font color=blue>WARNING:".
  203:                " Critical message to unknown server ($server)</font>");
  204:         return 'no_such_host';
  205:     }
  206:     my $answer=reply($cmd,$server);
  207:     if ($answer eq 'con_lost') {
  208: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  209: 	my $answer=reply($cmd,$server);
  210:         if ($answer eq 'con_lost') {
  211:             my $now=time;
  212:             my $middlename=$cmd;
  213:             $middlename=substr($middlename,0,16);
  214:             $middlename=~s/\W//g;
  215:             my $dfilename=
  216:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  217:             $dumpcount++;
  218:             {
  219: 		my $dfh;
  220: 		if (open($dfh,">$dfilename")) {
  221: 		    print $dfh "$cmd\n"; 
  222: 		    close($dfh);
  223: 		}
  224:             }
  225:             sleep 2;
  226:             my $wcmd='';
  227:             {
  228: 		my $dfh;
  229: 		if (open($dfh,"<$dfilename")) {
  230: 		    $wcmd=<$dfh>; 
  231: 		    close($dfh);
  232: 		}
  233:             }
  234:             chomp($wcmd);
  235:             if ($wcmd eq $cmd) {
  236: 		&logthis("<font color=blue>WARNING: ".
  237:                          "Connection buffer $dfilename: $cmd</font>");
  238:                 &logperm("D:$server:$cmd");
  239: 	        return 'con_delayed';
  240:             } else {
  241:                 &logthis("<font color=red>CRITICAL:"
  242:                         ." Critical connection failed: $server $cmd</font>");
  243:                 &logperm("F:$server:$cmd");
  244:                 return 'con_failed';
  245:             }
  246:         }
  247:     }
  248:     return $answer;
  249: }
  250: 
  251: #
  252: # -------------- Remove all key from the env that start witha lowercase letter
  253: #                (Which is always a lon-capa value)
  254: 
  255: sub cleanenv {
  256: #    unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; }
  257: #    unless (&Apache::exists_config_define("MODPERL2")) { return; }
  258:     foreach my $key (keys(%ENV)) {
  259: 	if ($key =~ /^[a-z]/) {
  260: 	    delete($ENV{$key});
  261: 	}
  262:     }
  263: }
  264:  
  265: # ------------------------------------------- Transfer profile into environment
  266: 
  267: sub transfer_profile_to_env {
  268:     my ($lonidsdir,$handle)=@_;
  269:     my @profile;
  270:     {
  271: 	open(my $idf,"$lonidsdir/$handle.id");
  272: 	flock($idf,LOCK_SH);
  273: 	@profile=<$idf>;
  274: 	close($idf);
  275:     }
  276:     my $envi;
  277:     my %Remove;
  278:     for ($envi=0;$envi<=$#profile;$envi++) {
  279: 	chomp($profile[$envi]);
  280: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
  281: 	$ENV{$envname} = $envvalue;
  282:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  283:             if ($time < time-300) {
  284:                 $Remove{$key}++;
  285:             }
  286:         }
  287:     }
  288:     $ENV{'user.environment'} = "$lonidsdir/$handle.id";
  289:     foreach my $expired_key (keys(%Remove)) {
  290:         &delenv($expired_key);
  291:     }
  292: }
  293: 
  294: # ---------------------------------------------------------- Append Environment
  295: 
  296: sub appenv {
  297:     my %newenv=@_;
  298:     foreach (keys %newenv) {
  299: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  300:             &logthis("<font color=blue>WARNING: ".
  301:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  302:                 .'</font>');
  303: 	    delete($newenv{$_});
  304:         } else {
  305:             $ENV{$_}=$newenv{$_};
  306:         }
  307:     }
  308: 
  309:     my $lockfh;
  310:     unless (open($lockfh,"$ENV{'user.environment'}")) {
  311: 	return 'error: '.$!;
  312:     }
  313:     unless (flock($lockfh,LOCK_EX)) {
  314:          &logthis("<font color=blue>WARNING: ".
  315:                   'Could not obtain exclusive lock in appenv: '.$!);
  316:          close($lockfh);
  317:          return 'error: '.$!;
  318:     }
  319: 
  320:     my @oldenv;
  321:     {
  322: 	my $fh;
  323: 	unless (open($fh,"$ENV{'user.environment'}")) {
  324: 	    return 'error: '.$!;
  325: 	}
  326: 	@oldenv=<$fh>;
  327: 	close($fh);
  328:     }
  329:     for (my $i=0; $i<=$#oldenv; $i++) {
  330:         chomp($oldenv[$i]);
  331:         if ($oldenv[$i] ne '') {
  332: 	    my ($name,$value)=split(/=/,$oldenv[$i]);
  333: 	    unless (defined($newenv{$name})) {
  334: 		$newenv{$name}=$value;
  335: 	    }
  336:         }
  337:     }
  338:     {
  339: 	my $fh;
  340: 	unless (open($fh,">$ENV{'user.environment'}")) {
  341: 	    return 'error';
  342: 	}
  343: 	my $newname;
  344: 	foreach $newname (keys %newenv) {
  345: 	    print $fh "$newname=$newenv{$newname}\n";
  346: 	}
  347: 	close($fh);
  348:     }
  349: 	
  350:     close($lockfh);
  351:     return 'ok';
  352: }
  353: # ----------------------------------------------------- Delete from Environment
  354: 
  355: sub delenv {
  356:     my $delthis=shift;
  357:     my %newenv=();
  358:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  359:         &logthis("<font color=blue>WARNING: ".
  360:                 "Attempt to delete from environment ".$delthis);
  361:         return 'error';
  362:     }
  363:     my @oldenv;
  364:     {
  365: 	my $fh;
  366: 	unless (open($fh,"$ENV{'user.environment'}")) {
  367: 	    return 'error';
  368: 	}
  369: 	unless (flock($fh,LOCK_SH)) {
  370: 	    &logthis("<font color=blue>WARNING: ".
  371: 		     'Could not obtain shared lock in delenv: '.$!);
  372: 	    close($fh);
  373: 	    return 'error: '.$!;
  374: 	}
  375: 	@oldenv=<$fh>;
  376: 	close($fh);
  377:     }
  378:     {
  379: 	my $fh;
  380: 	unless (open($fh,">$ENV{'user.environment'}")) {
  381: 	    return 'error';
  382: 	}
  383: 	unless (flock($fh,LOCK_EX)) {
  384: 	    &logthis("<font color=blue>WARNING: ".
  385: 		     'Could not obtain exclusive lock in delenv: '.$!);
  386: 	    close($fh);
  387: 	    return 'error: '.$!;
  388: 	}
  389: 	foreach (@oldenv) {
  390: 	    if ($_=~/^$delthis/) { 
  391:                 my ($key,undef) = split('=',$_);
  392:                 delete($ENV{$key});
  393:             } else {
  394:                 print $fh $_; 
  395:             }
  396: 	}
  397: 	close($fh);
  398:     }
  399:     return 'ok';
  400: }
  401: 
  402: # ------------------------------------------ Find out current server userload
  403: # there is a copy in lond
  404: sub userload {
  405:     my $numusers=0;
  406:     {
  407: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  408: 	my $filename;
  409: 	my $curtime=time;
  410: 	while ($filename=readdir(LONIDS)) {
  411: 	    if ($filename eq '.' || $filename eq '..') {next;}
  412: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  413: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  414: 	}
  415: 	closedir(LONIDS);
  416:     }
  417:     my $userloadpercent=0;
  418:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  419:     if ($maxuserload) {
  420: 	$userloadpercent=100*$numusers/$maxuserload;
  421:     }
  422:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  423:     return $userloadpercent;
  424: }
  425: 
  426: # ------------------------------------------ Fight off request when overloaded
  427: 
  428: sub overloaderror {
  429:     my ($r,$checkserver)=@_;
  430:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  431:     my $loadavg;
  432:     if ($checkserver eq $perlvar{'lonHostID'}) {
  433:        open(my $loadfile,'/proc/loadavg');
  434:        $loadavg=<$loadfile>;
  435:        $loadavg =~ s/\s.*//g;
  436:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  437:        close($loadfile);
  438:     } else {
  439:        $loadavg=&reply('load',$checkserver);
  440:     }
  441:     my $overload=$loadavg-100;
  442:     if ($overload>0) {
  443: 	$r->err_headers_out->{'Retry-After'}=$overload;
  444:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  445:         return 413;
  446:     }    
  447:     return '';
  448: }
  449: 
  450: # ------------------------------ Find server with least workload from spare.tab
  451: 
  452: sub spareserver {
  453:     my ($loadpercent,$userloadpercent) = @_;
  454:     my $tryserver;
  455:     my $spareserver='';
  456:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  457:     my $lowestserver=$loadpercent > $userloadpercent?
  458: 	             $loadpercent :  $userloadpercent;
  459:     foreach $tryserver (keys %spareid) {
  460: 	my $loadans=reply('load',$tryserver);
  461: 	my $userloadans=reply('userload',$tryserver);
  462: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  463: 	    next; #didn't get a number from the server
  464: 	}
  465: 	my $answer;
  466: 	if ($loadans =~ /\d/) {
  467: 	    if ($userloadans =~ /\d/) {
  468: 		#both are numbers, pick the bigger one
  469: 		$answer=$loadans > $userloadans?
  470: 		    $loadans :  $userloadans;
  471: 	    } else {
  472: 		$answer = $loadans;
  473: 	    }
  474: 	} else {
  475: 	    $answer = $userloadans;
  476: 	}
  477: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  478: 	    $spareserver="http://$hostname{$tryserver}";
  479: 	    $lowestserver=$answer;
  480: 	}
  481:     }
  482:     return $spareserver;
  483: }
  484: 
  485: # --------------------------------------------- Try to change a user's password
  486: 
  487: sub changepass {
  488:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  489:     $currentpass = &escape($currentpass);
  490:     $newpass     = &escape($newpass);
  491:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  492: 		       $server);
  493:     if (! $answer) {
  494: 	&logthis("No reply on password change request to $server ".
  495: 		 "by $uname in domain $udom.");
  496:     } elsif ($answer =~ "^ok") {
  497:         &logthis("$uname in $udom successfully changed their password ".
  498: 		 "on $server.");
  499:     } elsif ($answer =~ "^pwchange_failure") {
  500: 	&logthis("$uname in $udom was unable to change their password ".
  501: 		 "on $server.  The action was blocked by either lcpasswd ".
  502: 		 "or pwchange");
  503:     } elsif ($answer =~ "^non_authorized") {
  504:         &logthis("$uname in $udom did not get their password correct when ".
  505: 		 "attempting to change it on $server.");
  506:     } elsif ($answer =~ "^auth_mode_error") {
  507:         &logthis("$uname in $udom attempted to change their password despite ".
  508: 		 "not being locally or internally authenticated on $server.");
  509:     } elsif ($answer =~ "^unknown_user") {
  510:         &logthis("$uname in $udom attempted to change their password ".
  511: 		 "on $server but were unable to because $server is not ".
  512: 		 "their home server.");
  513:     } elsif ($answer =~ "^refused") {
  514: 	&logthis("$server refused to change $uname in $udom password because ".
  515: 		 "it was sent an unencrypted request to change the password.");
  516:     }
  517:     return $answer;
  518: }
  519: 
  520: # ----------------------- Try to determine user's current authentication scheme
  521: 
  522: sub queryauthenticate {
  523:     my ($uname,$udom)=@_;
  524:     my $uhome=&homeserver($uname,$udom);
  525:     if (!$uhome) {
  526: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  527: 	return 'no_host';
  528:     }
  529:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  530:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  531: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  532:     }
  533:     return $answer;
  534: }
  535: 
  536: # --------- Try to authenticate user from domain's lib servers (first this one)
  537: 
  538: sub authenticate {
  539:     my ($uname,$upass,$udom)=@_;
  540:     $upass=escape($upass);
  541:     $uname=~s/\W//g;
  542:     my $uhome=&homeserver($uname,$udom);
  543:     if (!$uhome) {
  544: 	&logthis("User $uname at $udom is unknown in authenticate");
  545: 	return 'no_host';
  546:     }
  547:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  548:     if ($answer eq 'authorized') {
  549: 	&logthis("User $uname at $udom authorized by $uhome"); 
  550: 	return $uhome; 
  551:     }
  552:     if ($answer eq 'non_authorized') {
  553: 	&logthis("User $uname at $udom rejected by $uhome");
  554: 	return 'no_host'; 
  555:     }
  556:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  557:     return 'no_host';
  558: }
  559: 
  560: # ---------------------- Find the homebase for a user from domain's lib servers
  561: 
  562: sub homeserver {
  563:     my ($uname,$udom,$ignoreBadCache)=@_;
  564:     my $index="$uname:$udom";
  565: 
  566:     my ($result,$cached)=&is_cached(\%homecache,$index,'home',86400);
  567:     if (defined($cached)) { return $result; }
  568:     my $tryserver;
  569:     foreach $tryserver (keys %libserv) {
  570:         next if ($ignoreBadCache ne 'true' && 
  571: 		 exists($badServerCache{$tryserver}));
  572: 	if ($hostdom{$tryserver} eq $udom) {
  573:            my $answer=reply("home:$udom:$uname",$tryserver);
  574:            if ($answer eq 'found') { 
  575: 	       return &do_cache(\%homecache,$index,$tryserver,'home');
  576:            } elsif ($answer eq 'no_host') {
  577: 	       $badServerCache{$tryserver}=1;
  578:            }
  579:        }
  580:     }    
  581:     return 'no_host';
  582: }
  583: 
  584: # ------------------------------------- Find the usernames behind a list of IDs
  585: 
  586: sub idget {
  587:     my ($udom,@ids)=@_;
  588:     my %returnhash=();
  589:     
  590:     my $tryserver;
  591:     foreach $tryserver (keys %libserv) {
  592:        if ($hostdom{$tryserver} eq $udom) {
  593: 	  my $idlist=join('&',@ids);
  594:           $idlist=~tr/A-Z/a-z/; 
  595: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  596:           my @answer=();
  597:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  598: 	      @answer=split(/\&/,$reply);
  599:           }                    ;
  600:           my $i;
  601:           for ($i=0;$i<=$#ids;$i++) {
  602:               if ($answer[$i]) {
  603: 		  $returnhash{$ids[$i]}=$answer[$i];
  604:               } 
  605:           }
  606:        }
  607:     }    
  608:     return %returnhash;
  609: }
  610: 
  611: # ------------------------------------- Find the IDs behind a list of usernames
  612: 
  613: sub idrget {
  614:     my ($udom,@unames)=@_;
  615:     my %returnhash=();
  616:     foreach (@unames) {
  617:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  618:     }
  619:     return %returnhash;
  620: }
  621: 
  622: # ------------------------------- Store away a list of names and associated IDs
  623: 
  624: sub idput {
  625:     my ($udom,%ids)=@_;
  626:     my %servers=();
  627:     foreach (keys %ids) {
  628: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  629:         my $uhom=&homeserver($_,$udom);
  630:         if ($uhom ne 'no_host') {
  631:             my $id=&escape($ids{$_});
  632:             $id=~tr/A-Z/a-z/;
  633:             my $unam=&escape($_);
  634: 	    if ($servers{$uhom}) {
  635: 		$servers{$uhom}.='&'.$id.'='.$unam;
  636:             } else {
  637:                 $servers{$uhom}=$id.'='.$unam;
  638:             }
  639:         }
  640:     }
  641:     foreach (keys %servers) {
  642:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  643:     }
  644: }
  645: 
  646: # --------------------------------------------------- Assign a key to a student
  647: 
  648: sub assign_access_key {
  649: #
  650: # a valid key looks like uname:udom#comments
  651: # comments are being appended
  652: #
  653:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  654:     $kdom=
  655:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($kdom));
  656:     $knum=
  657:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($knum));
  658:     $cdom=
  659:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  660:     $cnum=
  661:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  662:     $udom=$ENV{'user.name'} unless (defined($udom));
  663:     $uname=$ENV{'user.domain'} unless (defined($uname));
  664:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  665:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  666:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  667:                                                   # assigned to this person
  668:                                                   # - this should not happen,
  669:                                                   # unless something went wrong
  670:                                                   # the first time around
  671: # ready to assign
  672:         $logentry=$1.'; '.$logentry;
  673:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  674:                                                  $kdom,$knum) eq 'ok') {
  675: # key now belongs to user
  676: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  677:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  678:                 &appenv('environment.'.$envkey => $ckey);
  679:                 return 'ok';
  680:             } else {
  681:                 return 
  682:   'error: Count not permanently assign key, will need to be re-entered later.';
  683: 	    }
  684:         } else {
  685:             return 'error: Could not assign key, try again later.';
  686:         }
  687:     } elsif (!$existing{$ckey}) {
  688: # the key does not exist
  689: 	return 'error: The key does not exist';
  690:     } else {
  691: # the key is somebody else's
  692: 	return 'error: The key is already in use';
  693:     }
  694: }
  695: 
  696: # ------------------------------------------ put an additional comment on a key
  697: 
  698: sub comment_access_key {
  699: #
  700: # a valid key looks like uname:udom#comments
  701: # comments are being appended
  702: #
  703:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  704:     $cdom=
  705:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  706:     $cnum=
  707:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  708:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  709:     if ($existing{$ckey}) {
  710:         $existing{$ckey}.='; '.$logentry;
  711: # ready to assign
  712:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  713:                                                  $cdom,$cnum) eq 'ok') {
  714: 	    return 'ok';
  715:         } else {
  716: 	    return 'error: Count not store comment.';
  717:         }
  718:     } else {
  719: # the key does not exist
  720: 	return 'error: The key does not exist';
  721:     }
  722: }
  723: 
  724: # ------------------------------------------------------ Generate a set of keys
  725: 
  726: sub generate_access_keys {
  727:     my ($number,$cdom,$cnum,$logentry)=@_;
  728:     $cdom=
  729:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  730:     $cnum=
  731:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  732:     unless (&allowed('mky',$cdom)) { return 0; }
  733:     unless (($cdom) && ($cnum)) { return 0; }
  734:     if ($number>10000) { return 0; }
  735:     sleep(2); # make sure don't get same seed twice
  736:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  737:     my $total=0;
  738:     for (my $i=1;$i<=$number;$i++) {
  739:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  740:                   sprintf("%lx",int(100000*rand)).'-'.
  741:                   sprintf("%lx",int(100000*rand));
  742:        $newkey=~s/1/g/g; # folks mix up 1 and l
  743:        $newkey=~s/0/h/g; # and also 0 and O
  744:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  745:        if ($existing{$newkey}) {
  746:            $i--;
  747:        } else {
  748: 	  if (&put('accesskeys',
  749:               { $newkey => '# generated '.localtime().
  750:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
  751:                            '; '.$logentry },
  752: 		   $cdom,$cnum) eq 'ok') {
  753:               $total++;
  754: 	  }
  755:        }
  756:     }
  757:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
  758:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  759:     return $total;
  760: }
  761: 
  762: # ------------------------------------------------------- Validate an accesskey
  763: 
  764: sub validate_access_key {
  765:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  766:     $cdom=
  767:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  768:     $cnum=
  769:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  770:     $udom=$ENV{'user.domain'} unless (defined($udom));
  771:     $uname=$ENV{'user.name'} unless (defined($uname));
  772:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  773:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  774: }
  775: 
  776: # ------------------------------------- Find the section of student in a course
  777: 
  778: sub getsection {
  779:     my ($udom,$unam,$courseid)=@_;
  780:     $courseid=~s/\_/\//g;
  781:     $courseid=~s/^(\w)/\/$1/;
  782: 
  783:     my $hashid="$udom:$unam:$courseid";
  784:     my ($result,$cached)=&is_cached(\%getsectioncache,$hashid,'getsection');
  785:     if (defined($cached)) { return $result; }
  786: 
  787:     my %Pending; 
  788:     my %Expired;
  789:     #
  790:     # Each role can either have not started yet (pending), be active, 
  791:     #    or have expired.
  792:     #
  793:     # If there is an active role, we are done.
  794:     #
  795:     # If there is more than one role which has not started yet, 
  796:     #     choose the one which will start sooner
  797:     # If there is one role which has not started yet, return it.
  798:     #
  799:     # If there is more than one expired role, choose the one which ended last.
  800:     # If there is a role which has expired, return it.
  801:     #
  802:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  803:                         &homeserver($unam,$udom)))) {
  804:         my ($key,$value)=split(/\=/,$_);
  805:         $key=&unescape($key);
  806:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  807:         my $section=$1;
  808:         if ($key eq $courseid.'_st') { $section=''; }
  809:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  810:         my $now=time;
  811:         if (defined($end) && $end && ($now > $end)) {
  812:             $Expired{$end}=$section;
  813:             next;
  814:         }
  815:         if (defined($start) && $start && ($now < $start)) {
  816:             $Pending{$start}=$section;
  817:             next;
  818:         }
  819:         return &do_cache(\%getsectioncache,$hashid,$section,'getsection');
  820:     }
  821:     #
  822:     # Presumedly there will be few matching roles from the above
  823:     # loop and the sorting time will be negligible.
  824:     if (scalar(keys(%Pending))) {
  825:         my ($time) = sort {$a <=> $b} keys(%Pending);
  826:         return &do_cache(\%getsectioncache,$hashid,$Pending{$time},'getsection');
  827:     } 
  828:     if (scalar(keys(%Expired))) {
  829:         my @sorted = sort {$a <=> $b} keys(%Expired);
  830:         my $time = pop(@sorted);
  831:         return &do_cache(\%getsectioncache,$hashid,$Expired{$time},'getsection');
  832:     }
  833:     return &do_cache(\%getsectioncache,$hashid,'-1','getsection');
  834: }
  835: 
  836: 
  837: my $disk_caching_disabled=1;
  838: 
  839: sub devalidate_cache {
  840:     my ($cache,$id,$name) = @_;
  841:     delete $$cache{$id.'.time'};
  842:     delete $$cache{$id.'.file'};
  843:     delete $$cache{$id};
  844:     if (1 || $disk_caching_disabled) { return; }
  845:     my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
  846:     if (!-e $filename) { return; }
  847:     open(DB,">$filename.lock");
  848:     flock(DB,LOCK_EX);
  849:     my %hash;
  850:     if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
  851: 	eval <<'EVALBLOCK';
  852: 	    delete($hash{$id});
  853: 	    delete($hash{$id.'.time'});
  854: EVALBLOCK
  855:         if ($@) {
  856: 	    &logthis("<font color='red'>devalidate_cache blew up :$@:$name</font>");
  857: 	    unlink($filename);
  858: 	}
  859:     } else {
  860: 	if (-e $filename) {
  861: 	    &logthis("Unable to tie hash (devalidate cache): $name");
  862: 	    unlink($filename);
  863: 	}
  864:     }
  865:     untie(%hash);
  866:     flock(DB,LOCK_UN);
  867:     close(DB);
  868: }
  869: 
  870: sub is_cached {
  871:     my ($cache,$id,$name,$time) = @_;
  872:     if (!$time) { $time=300; }
  873:     if (!exists($$cache{$id.'.time'})) {
  874: 	&load_cache_item($cache,$name,$id,$time);
  875:     }
  876:     if (!exists($$cache{$id.'.time'})) {
  877: #	&logthis("Didn't find $id");
  878: 	return (undef,undef);
  879:     } else {
  880: 	if (time-($$cache{$id.'.time'})>$time) {
  881: 	    if (exists($$cache{$id.'.file'})) {
  882: 		foreach my $filename (@{ $$cache{$id.'.file'} }) {
  883: 		    my $mtime=(stat($filename))[9];
  884: 		    #+1 is to take care of edge effects
  885: 		    if ($mtime && (($mtime+1) < ($$cache{$id.'.time'}))) {
  886: #			&logthis("Upping $mtime - ".$$cache{$id.'.time'}.
  887: #				 "$id because of $filename");
  888: 		    } else {
  889: 			&logthis("Devalidating $filename $id - ".(time-($$cache{$id.'.time'})));
  890: 			&devalidate_cache($cache,$id,$name);
  891: 			return (undef,undef);
  892: 		    }
  893: 		}
  894: 		$$cache{$id.'.time'}=time;
  895: 	    } else {
  896: #		&logthis("Devalidating $id - ".time-($$cache{$id.'.time'}));
  897: 		&devalidate_cache($cache,$id,$name);
  898: 		return (undef,undef);
  899: 	    }
  900: 	}
  901:     }
  902:     return ($$cache{$id},1);
  903: }
  904: 
  905: sub do_cache {
  906:     my ($cache,$id,$value,$name) = @_;
  907:     $$cache{$id.'.time'}=time;
  908:     $$cache{$id}=$value;
  909: #    &logthis("Caching $id as :$value:");
  910:     &save_cache_item($cache,$name,$id);
  911:     # do_cache implictly return the set value
  912:     $$cache{$id};
  913: }
  914: 
  915: my %do_save_item;
  916: my %do_save;
  917: sub save_cache_item {
  918:     my ($cache,$name,$id)=@_;
  919:     if ($disk_caching_disabled) { return; }
  920:     $do_save{$name}=$cache;
  921:     if (!exists($do_save_item{$name})) { $do_save_item{$name}={} }
  922:     $do_save_item{$name}->{$id}=1;
  923:     return;
  924: }
  925: 
  926: sub save_cache {
  927:     &purge_remembered();
  928:     if ($disk_caching_disabled) { return; }
  929:     my ($cache,$name,$id);
  930:     foreach $name (keys(%do_save)) {
  931: 	$cache=$do_save{$name};
  932: 
  933: 	my $starttime=&Time::HiRes::time();
  934: 	&logthis("Saving :$name:");
  935: 	my %hash;
  936: 	my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
  937: 	open(DB,">$filename.lock");
  938: 	flock(DB,LOCK_EX);
  939: 	if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) {
  940: 	    foreach $id (keys(%{ $do_save_item{$name} })) {
  941: 		eval <<'EVALBLOCK';
  942: 		$hash{$id.'.time'}=$$cache{$id.'.time'};
  943: 		$hash{$id}=freeze({'item'=>$$cache{$id}});
  944: 		if (exists($$cache{$id.'.file'})) {
  945: 		    $hash{$id.'.file'}=freeze({'item'=>$$cache{$id.'.file'}});
  946: 		}
  947: EVALBLOCK
  948:                 if ($@) {
  949: 		    &logthis("<font color='red'>save_cache blew up :$@:$name</font>");
  950: 		    unlink($filename);
  951: 		    last;
  952: 		}
  953: 	    }
  954: 	} else {
  955: 	    if (-e $filename) {
  956: 		&logthis("Unable to tie hash (save cache): $name ($!)");
  957: 		unlink($filename);
  958: 	    }
  959: 	}
  960: 	untie(%hash);
  961: 	flock(DB,LOCK_UN);
  962: 	close(DB);
  963: 	&logthis("save_cache $name took ".(&Time::HiRes::time()-$starttime));
  964:     }
  965:     undef(%do_save);
  966:     undef(%do_save_item);
  967: 
  968: }
  969: 
  970: sub load_cache_item {
  971:     my ($cache,$name,$id,$time)=@_;
  972:     if ($disk_caching_disabled) { return; }
  973:     my $starttime=&Time::HiRes::time();
  974: #    &logthis("Before Loading $name  for $id size is ".scalar(%$cache));
  975:     my %hash;
  976:     my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db";
  977:     if (!-e $filename) { return; }
  978:     open(DB,">$filename.lock");
  979:     flock(DB,LOCK_SH);
  980:     if (tie(%hash,'GDBM_File',$filename,&GDBM_READER(),0640)) {
  981: 	eval <<'EVALBLOCK';
  982: 	    if (!%$cache) {
  983: 		my $count;
  984: 		while (my ($key,$value)=each(%hash)) { 
  985: 		    $count++;
  986: 		    if ($key =~ /\.time$/) {
  987: 			$$cache{$key}=$value;
  988: 		    } else {
  989: 			my $hashref=thaw($value);
  990: 			$$cache{$key}=$hashref->{'item'};
  991: 		    }
  992: 		}
  993: #	    &logthis("Initial load: $count");
  994: 	    } else {
  995: 		if (($$cache{$id.'.time'}+$time) < time) {
  996: 		    $$cache{$id.'.time'}=$hash{$id.'.time'};
  997: 		    {
  998: 			my $hashref=thaw($hash{$id});
  999: 			$$cache{$id}=$hashref->{'item'};
 1000: 		    }
 1001: 		    if (exists($hash{$id.'.file'})) {
 1002: 			my $hashref=thaw($hash{$id.'.file'});
 1003: 			$$cache{$id.'.file'}=$hashref->{'item'};
 1004: 		    }
 1005: 		}
 1006: 	    }
 1007: EVALBLOCK
 1008:         if ($@) {
 1009: 	    &logthis("<font color='red'>load_cache blew up :$@:$name</font>");
 1010: 	    unlink($filename);
 1011: 	}        
 1012:     } else {
 1013: 	if (-e $filename) {
 1014: 	    &logthis("Unable to tie hash (load cache item): $name ($!)");
 1015: 	    unlink($filename);
 1016: 	}
 1017:     }
 1018:     untie(%hash);
 1019:     flock(DB,LOCK_UN);
 1020:     close(DB);
 1021: #    &logthis("After Loading $name size is ".scalar(%$cache));
 1022: #    &logthis("load_cache_item $name took ".(&Time::HiRes::time()-$starttime));
 1023: }
 1024: 
 1025: sub devalidate_cache_new {
 1026:     my ($name,$id) = @_;
 1027:     if (1) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1028:     $memcache->delete(&escape($name.':'.$id));
 1029: }
 1030: 
 1031: my $to_remember=10;
 1032: my %remembered;
 1033: my %accessed;
 1034: my $kicks=0;
 1035: my $hits=0;
 1036: sub is_cached_new {
 1037:     my ($name,$id,$debug) = @_;
 1038:     $debug=0;
 1039:     $id=&escape($name.':'.$id);
 1040:     if (exists($remembered{$id})) {
 1041: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1042: 	$accessed{$id}=[&gettimeofday()];
 1043: 	$hits++;
 1044: 	return ($remembered{$id},1);
 1045:     }
 1046:     my $value = $memcache->get($id);
 1047:     if (!(defined($value))) {
 1048: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1049: 	return (undef,undef);
 1050:     }
 1051:     &make_room($id,$value);
 1052:     if ($value eq '__undef__') {
 1053: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1054: 	return (undef,1);
 1055:     }
 1056:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1057:     return ($value,1);
 1058: }
 1059: 
 1060: sub do_cache_new {
 1061:     my ($name,$id,$value,$time,$debug) = @_;
 1062:     $debug=0;
 1063:     $id=&escape($name.':'.$id);
 1064:     my $setvalue=$value;
 1065:     if (!defined($setvalue)) {
 1066: 	$setvalue='__undef__';
 1067:     }
 1068:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1069:     $memcache->set($id,$setvalue,300);
 1070:     return $value;
 1071: }
 1072: 
 1073: sub make_room {
 1074:     my ($id,$value)=@_;
 1075:     my $debug=0;
 1076:     $remembered{$id}=$value;
 1077:     $accessed{$id}=[&gettimeofday()];
 1078:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1079:     my $to_kick;
 1080:     my $max_time=0;
 1081:     foreach my $other (keys(%accessed)) {
 1082: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1083: 	    $to_kick=$other;
 1084: 	    $max_time=&tv_interval($accessed{$other});
 1085: 	}
 1086:     }
 1087:     delete($remembered{$to_kick});
 1088:     delete($accessed{$to_kick});
 1089:     $kicks++;
 1090:     if ($debug) { &logthis("kicking $max_time $kicks\n"); }
 1091:     return;
 1092: }
 1093: 
 1094: sub purge_remembered {
 1095:     &logthis("Tossing ".scalar(keys(%remembered)));
 1096:     undef(%remembered);
 1097:     undef(%accessed);
 1098: }
 1099: # ------------------------------------- Read an entry from a user's environment
 1100: 
 1101: sub userenvironment {
 1102:     my ($udom,$unam,@what)=@_;
 1103:     my %returnhash=();
 1104:     my @answer=split(/\&/,
 1105:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1106:                       &homeserver($unam,$udom)));
 1107:     my $i;
 1108:     for ($i=0;$i<=$#what;$i++) {
 1109: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1110:     }
 1111:     return %returnhash;
 1112: }
 1113: 
 1114: # -------------------------------------------------------------------- New chat
 1115: 
 1116: sub chatsend {
 1117:     my ($newentry,$anon)=@_;
 1118:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1119:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1120:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1121:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1122: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
 1123: 		   &escape($newentry)),$chome);
 1124: }
 1125: 
 1126: # ------------------------------------------ Find current version of a resource
 1127: 
 1128: sub getversion {
 1129:     my $fname=&clutter(shift);
 1130:     unless ($fname=~/^\/res\//) { return -1; }
 1131:     return &currentversion(&filelocation('',$fname));
 1132: }
 1133: 
 1134: sub currentversion {
 1135:     my $fname=shift;
 1136:     my ($result,$cached)=&is_cached(\%resversioncache,$fname,'resversion',600);
 1137:     if (defined($cached)) { return $result; }
 1138:     my $author=$fname;
 1139:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1140:     my ($udom,$uname)=split(/\//,$author);
 1141:     my $home=homeserver($uname,$udom);
 1142:     if ($home eq 'no_host') { 
 1143:         return -1; 
 1144:     }
 1145:     my $answer=reply("currentversion:$fname",$home);
 1146:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1147: 	return -1;
 1148:     }
 1149:     return &do_cache(\%resversioncache,$fname,$answer,'resversion');
 1150: }
 1151: 
 1152: # ----------------------------- Subscribe to a resource, return URL if possible
 1153: 
 1154: sub subscribe {
 1155:     my $fname=shift;
 1156:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1157:     $fname=~s/[\n\r]//g;
 1158:     my $author=$fname;
 1159:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1160:     my ($udom,$uname)=split(/\//,$author);
 1161:     my $home=homeserver($uname,$udom);
 1162:     if ($home eq 'no_host') {
 1163:         return 'not_found';
 1164:     }
 1165:     my $answer=reply("sub:$fname",$home);
 1166:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1167: 	$answer.=' by '.$home;
 1168:     }
 1169:     return $answer;
 1170: }
 1171:     
 1172: # -------------------------------------------------------------- Replicate file
 1173: 
 1174: sub repcopy {
 1175:     my $filename=shift;
 1176:     $filename=~s/\/+/\//g;
 1177:     if ($filename=~m|^/home/httpd/html/adm/|) { return OK; }
 1178:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return OK; }
 1179:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1180: 	$filename=~m|^/*uploaded/|) { 
 1181: 	return &repcopy_userfile($filename);
 1182:     }
 1183:     $filename=~s/[\n\r]//g;
 1184:     my $transname="$filename.in.transfer";
 1185:     if ((-e $filename) || (-e $transname)) { return OK; }
 1186:     my $remoteurl=subscribe($filename);
 1187:     if ($remoteurl =~ /^con_lost by/) {
 1188: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1189:            return HTTP_SERVICE_UNAVAILABLE;
 1190:     } elsif ($remoteurl eq 'not_found') {
 1191: 	   #&logthis("Subscribe returned not_found: $filename");
 1192: 	   return HTTP_NOT_FOUND;
 1193:     } elsif ($remoteurl =~ /^rejected by/) {
 1194: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1195:            return FORBIDDEN;
 1196:     } elsif ($remoteurl eq 'directory') {
 1197:            return OK;
 1198:     } else {
 1199:         my $author=$filename;
 1200:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1201:         my ($udom,$uname)=split(/\//,$author);
 1202:         my $home=homeserver($uname,$udom);
 1203:         unless ($home eq $perlvar{'lonHostID'}) {
 1204:            my @parts=split(/\//,$filename);
 1205:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1206:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1207:                &logthis("Malconfiguration for replication: $filename");
 1208: 	       return HTTP_BAD_REQUEST;
 1209:            }
 1210:            my $count;
 1211:            for ($count=5;$count<$#parts;$count++) {
 1212:                $path.="/$parts[$count]";
 1213:                if ((-e $path)!=1) {
 1214: 		   mkdir($path,0777);
 1215:                }
 1216:            }
 1217:            my $ua=new LWP::UserAgent;
 1218:            my $request=new HTTP::Request('GET',"$remoteurl");
 1219:            my $response=$ua->request($request,$transname);
 1220:            if ($response->is_error()) {
 1221: 	       unlink($transname);
 1222:                my $message=$response->status_line;
 1223:                &logthis("<font color=blue>WARNING:"
 1224:                        ." LWP get: $message: $filename</font>");
 1225:                return HTTP_SERVICE_UNAVAILABLE;
 1226:            } else {
 1227: 	       if ($remoteurl!~/\.meta$/) {
 1228:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1229:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1230:                   if ($mresponse->is_error()) {
 1231: 		      unlink($filename.'.meta');
 1232:                       &logthis(
 1233:                      "<font color=yellow>INFO: No metadata: $filename</font>");
 1234:                   }
 1235: 	       }
 1236:                rename($transname,$filename);
 1237:                return OK;
 1238:            }
 1239:        }
 1240:     }
 1241: }
 1242: 
 1243: # ------------------------------------------------ Get server side include body
 1244: sub ssi_body {
 1245:     my ($filelink,%form)=@_;
 1246:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1247:                                      &ssi($filelink,%form));
 1248:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
 1249:     $output=~s/^.*?\<body[^\>]*\>//si;
 1250:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1251:     return $output;
 1252: }
 1253: 
 1254: # --------------------------------------------------------- Server Side Include
 1255: 
 1256: sub ssi {
 1257: 
 1258:     my ($fn,%form)=@_;
 1259: 
 1260:     my $ua=new LWP::UserAgent;
 1261:     
 1262:     my $request;
 1263:     
 1264:     if (%form) {
 1265:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1266:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1267:     } else {
 1268:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1269:     }
 1270: 
 1271:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1272:     my $response=$ua->request($request);
 1273: 
 1274:     return $response->content;
 1275: }
 1276: 
 1277: sub externalssi {
 1278:     my ($url)=@_;
 1279:     my $ua=new LWP::UserAgent;
 1280:     my $request=new HTTP::Request('GET',$url);
 1281:     my $response=$ua->request($request);
 1282:     return $response->content;
 1283: }
 1284: 
 1285: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1286: 
 1287: sub allowuploaded {
 1288:     my ($srcurl,$url)=@_;
 1289:     $url=&clutter(&declutter($url));
 1290:     my $dir=$url;
 1291:     $dir=~s/\/[^\/]+$//;
 1292:     my %httpref=();
 1293:     my $httpurl=&hreflocation('',$url);
 1294:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1295:     &Apache::lonnet::appenv(%httpref);
 1296: }
 1297: 
 1298: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1299: # input: action, courseID, current domain, home server for course, intended
 1300: #        path to file, source of file.
 1301: # output: url to file (if action was uploaddoc), 
 1302: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1303: #
 1304: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1305: # course.
 1306: #
 1307: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1308: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1309: #          course's home server.
 1310: #
 1311: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1312: #          be copied from $source (current location) to 
 1313: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1314: #         and will then be copied to
 1315: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1316: #         course's home server.
 1317: #
 1318: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1319: #         will be retrived from $ENV{form.uploaddoc} (from DOCS interface) to
 1320: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1321: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1322: #         in course's home server.
 1323: 
 1324: 
 1325: sub process_coursefile {
 1326:     my ($action,$docuname,$docudom,$docuhome,$file,$source)=@_;
 1327:     my $fetchresult;
 1328:     if ($action eq 'propagate') {
 1329:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file
 1330:                             ,$docuhome);
 1331:     } else {
 1332:         my $fetchresult = '';
 1333:         my $fpath = '';
 1334:         my $fname = $file;
 1335:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1336:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1337:         my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1338:         unless ($fpath eq '') {
 1339:             my @parts=split('/',$fpath);
 1340:             foreach my $part (@parts) {
 1341:                 $filepath.= '/'.$part;
 1342:                 if ((-e $filepath)!=1) {
 1343:                     mkdir($filepath,0777);
 1344:                 }
 1345:             }
 1346:         }
 1347:         if ($action eq 'copy') {
 1348:             if ($source eq '') {
 1349:                 $fetchresult = 'no source file';
 1350:                 return $fetchresult;
 1351:             } else {
 1352:                 my $destination = $filepath.'/'.$fname;
 1353:                 rename($source,$destination);
 1354:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1355:                                  $docuhome);
 1356:             }
 1357:         } elsif ($action eq 'uploaddoc') {
 1358:             open(my $fh,'>'.$filepath.'/'.$fname);
 1359:             print $fh $ENV{'form.'.$source};
 1360:             close($fh);
 1361:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1362:                                  $docuhome);
 1363:             if ($fetchresult eq 'ok') {
 1364:                 return '/uploaded/'.$fpath.'/'.$fname;
 1365:             } else {
 1366:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1367:                         ' to host '.$docuhome.': '.$fetchresult);
 1368:                 return '/adm/notfound.html';
 1369:             }
 1370:         }
 1371:     }
 1372:     unless ( $fetchresult eq 'ok') {
 1373:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1374:              ' to host '.$docuhome.': '.$fetchresult);
 1375:     }
 1376:     return $fetchresult;
 1377: }
 1378: 
 1379: # --------------- Take an uploaded file and put it into the userfiles directory
 1380: # input: name of form element, coursedoc=1 means this is for the course
 1381: # output: url of file in userspace
 1382: 
 1383: sub clean_filename {
 1384:     my ($fname)=@_;
 1385: # Replace Windows backslashes by forward slashes
 1386:     $fname=~s/\\/\//g;
 1387: # Get rid of everything but the actual filename
 1388:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1389: # Replace spaces by underscores
 1390:     $fname=~s/\s+/\_/g;
 1391: # Replace all other weird characters by nothing
 1392:     $fname=~s/[^\w\.\-]//g;
 1393: # Replace all .\d. sequences with _\d. so they no longer look like version
 1394: # numbers
 1395:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1396:     return $fname;
 1397: }
 1398: 
 1399: sub userfileupload {
 1400:     my ($formname,$coursedoc,$subdir)=@_;
 1401:     if (!defined($subdir)) { $subdir='unknown'; }
 1402:     my $fname=$ENV{'form.'.$formname.'.filename'};
 1403:     $fname=&clean_filename($fname);
 1404: # See if there is anything left
 1405:     unless ($fname) { return 'error: no uploaded file'; }
 1406:     chop($ENV{'form.'.$formname});
 1407:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1408:         my $now = time;
 1409:         my $filepath = 'tmp/helprequests/'.$now;
 1410:         my @parts=split(/\//,$filepath);
 1411:         my $fullpath = $perlvar{'lonDaemons'};
 1412:         for (my $i=0;$i<@parts;$i++) {
 1413:             $fullpath .= '/'.$parts[$i];
 1414:             if ((-e $fullpath)!=1) {
 1415:                 mkdir($fullpath,0777);
 1416:             }
 1417:         }
 1418:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1419:         print $fh $ENV{'form.'.$formname};
 1420:         close($fh);
 1421:         return $fullpath.'/'.$fname; 
 1422:     }
 1423: # Create the directory if not present
 1424:     my $docuname='';
 1425:     my $docudom='';
 1426:     my $docuhome='';
 1427:     $fname="$subdir/$fname";
 1428:     if ($coursedoc) {
 1429: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1430: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1431: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1432:         if ($ENV{'form.folder'} =~ m/^default/) {
 1433:             return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
 1434:         } else {
 1435:             $fname=$ENV{'form.folder'}.'/'.$fname;
 1436:             return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname);
 1437:         }
 1438:     } else {
 1439:         $docuname=$ENV{'user.name'};
 1440:         $docudom=$ENV{'user.domain'};
 1441:         $docuhome=$ENV{'user.home'};
 1442:         return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
 1443:     }
 1444: }
 1445: 
 1446: sub finishuserfileupload {
 1447:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
 1448:     my $path=$docudom.'/'.$docuname.'/';
 1449:     my $filepath=$perlvar{'lonDocRoot'};
 1450:     my ($fnamepath,$file);
 1451:     $file=$fname;
 1452:     if ($fname=~m|/|) {
 1453:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1454: 	$path.=$fnamepath.'/';
 1455:     }
 1456:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1457:     my $count;
 1458:     for ($count=4;$count<=$#parts;$count++) {
 1459:         $filepath.="/$parts[$count]";
 1460:         if ((-e $filepath)!=1) {
 1461: 	    mkdir($filepath,0777);
 1462:         }
 1463:     }
 1464: # Save the file
 1465:     {
 1466: 	open(FH,'>'.$filepath.'/'.$file);
 1467: 	print FH $ENV{'form.'.$formname};
 1468: 	close(FH);
 1469:     }
 1470: # Notify homeserver to grep it
 1471: #
 1472:     &Apache::lonnet::logthis("fetching ".$path.$file);
 1473:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1474:     if ($fetchresult eq 'ok') {
 1475: #
 1476: # Return the URL to it
 1477:         return '/uploaded/'.$path.$file;
 1478:     } else {
 1479:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1480: 		 ': '.$fetchresult);
 1481:         return '/adm/notfound.html';
 1482:     }    
 1483: }
 1484: 
 1485: sub removeuploadedurl {
 1486:     my ($url)=@_;
 1487:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1488:     return &Apache::lonnet::removeuserfile($uname,$udom,$fname);
 1489: }
 1490: 
 1491: sub removeuserfile {
 1492:     my ($docuname,$docudom,$fname)=@_;
 1493:     my $home=&homeserver($docuname,$docudom);
 1494:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1495: }
 1496: 
 1497: sub mkdiruserfile {
 1498:     my ($docuname,$docudom,$dir)=@_;
 1499:     my $home=&homeserver($docuname,$docudom);
 1500:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1501: }
 1502: 
 1503: sub renameuserfile {
 1504:     my ($docuname,$docudom,$old,$new)=@_;
 1505:     my $home=&homeserver($docuname,$docudom);
 1506:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1507: 		  &escape("$new"),$home);
 1508: }
 1509: 
 1510: # ------------------------------------------------------------------------- Log
 1511: 
 1512: sub log {
 1513:     my ($dom,$nam,$hom,$what)=@_;
 1514:     return critical("log:$dom:$nam:$what",$hom);
 1515: }
 1516: 
 1517: # ------------------------------------------------------------------ Course Log
 1518: #
 1519: # This routine flushes several buffers of non-mission-critical nature
 1520: #
 1521: 
 1522: sub flushcourselogs {
 1523:     &logthis('Flushing log buffers');
 1524: #
 1525: # course logs
 1526: # This is a log of all transactions in a course, which can be used
 1527: # for data mining purposes
 1528: #
 1529: # It also collects the courseid database, which lists last transaction
 1530: # times and course titles for all courseids
 1531: #
 1532:     my %courseidbuffer=();
 1533:     foreach (keys %courselogs) {
 1534:         my $crsid=$_;
 1535:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1536: 		          &escape($courselogs{$crsid}),
 1537: 		          $coursehombuf{$crsid}) eq 'ok') {
 1538: 	    delete $courselogs{$crsid};
 1539:         } else {
 1540:             &logthis('Failed to flush log buffer for '.$crsid);
 1541:             if (length($courselogs{$crsid})>40000) {
 1542:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
 1543:                         " exceeded maximum size, deleting.</font>");
 1544:                delete $courselogs{$crsid};
 1545:             }
 1546:         }
 1547:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1548:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1549: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1550:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1551:         } else {
 1552:            $courseidbuffer{$coursehombuf{$crsid}}=
 1553: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1554:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1555:         }
 1556:     }
 1557: #
 1558: # Write course id database (reverse lookup) to homeserver of courses 
 1559: # Is used in pickcourse
 1560: #
 1561:     foreach (keys %courseidbuffer) {
 1562:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1563:     }
 1564: #
 1565: # File accesses
 1566: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1567: #
 1568:     foreach my $entry (keys(%accesshash)) {
 1569:         if ($entry =~ /___count$/) {
 1570:             my ($dom,$name);
 1571:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1572:             if (! defined($dom) || $dom eq '' || 
 1573:                 ! defined($name) || $name eq '') {
 1574:                 my $cid = $ENV{'request.course.id'};
 1575:                 $dom  = $ENV{'request.'.$cid.'.domain'};
 1576:                 $name = $ENV{'request.'.$cid.'.num'};
 1577:             }
 1578:             my $value = $accesshash{$entry};
 1579:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1580:             my %temphash=($url => $value);
 1581:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1582:             if ($result eq 'ok') {
 1583:                 delete $accesshash{$entry};
 1584:             } elsif ($result eq 'unknown_cmd') {
 1585:                 # Target server has old code running on it.
 1586:                 my %temphash=($entry => $value);
 1587:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1588:                     delete $accesshash{$entry};
 1589:                 }
 1590:             }
 1591:         } else {
 1592:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1593:             my %temphash=($entry => $accesshash{$entry});
 1594:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1595:                 delete $accesshash{$entry};
 1596:             }
 1597:         }
 1598:     }
 1599: #
 1600: # Roles
 1601: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1602: #
 1603:     foreach (keys %userrolehash) {
 1604:         my $entry=$_;
 1605:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1606: 	    split(/\:/,$entry);
 1607:         if (&Apache::lonnet::put('nohist_userroles',
 1608:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1609:                 $rudom,$runame) eq 'ok') {
 1610: 	    delete $userrolehash{$entry};
 1611:         }
 1612:     }
 1613:     $dumpcount++;
 1614: }
 1615: 
 1616: sub courselog {
 1617:     my $what=shift;
 1618:     $what=time.':'.$what;
 1619:     unless ($ENV{'request.course.id'}) { return ''; }
 1620:     $coursedombuf{$ENV{'request.course.id'}}=
 1621:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1622:     $coursenumbuf{$ENV{'request.course.id'}}=
 1623:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1624:     $coursehombuf{$ENV{'request.course.id'}}=
 1625:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1626:     $coursedescrbuf{$ENV{'request.course.id'}}=
 1627:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1628:     $courseinstcodebuf{$ENV{'request.course.id'}}=
 1629:        $ENV{'course.'.$ENV{'request.course.id'}.'.internal.coursecode'};
 1630:     $courseownerbuf{$ENV{'request.course.id'}}=
 1631:        $ENV{'course.'.$ENV{'request.course.id'}.'.internal.courseowner'};
 1632:     if (defined $courselogs{$ENV{'request.course.id'}}) {
 1633: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
 1634:     } else {
 1635: 	$courselogs{$ENV{'request.course.id'}}.=$what;
 1636:     }
 1637:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
 1638: 	&flushcourselogs();
 1639:     }
 1640: }
 1641: 
 1642: sub courseacclog {
 1643:     my $fnsymb=shift;
 1644:     unless ($ENV{'request.course.id'}) { return ''; }
 1645:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
 1646:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) {
 1647:         $what.=':POST';
 1648:         # FIXME: Probably ought to escape things....
 1649: 	foreach (keys %ENV) {
 1650:             if ($_=~/^form\.(.*)/) {
 1651: 		$what.=':'.$1.'='.$ENV{$_};
 1652:             }
 1653:         }
 1654:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1655:         # FIXME: We should not be depending on a form parameter that someone
 1656:         # editing lonsearchcat.pm might change in the future.
 1657:         if ($ENV{'form.phase'} eq 'course_search') {
 1658:             $what.= ':POST';
 1659:             # FIXME: Probably ought to escape things....
 1660:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1661:                                  'crsdiscuss') {
 1662:                 $what.=':'.$element.'='.$ENV{'form.'.$element};
 1663:             }
 1664:         }
 1665:     }
 1666:     &courselog($what);
 1667: }
 1668: 
 1669: sub countacc {
 1670:     my $url=&declutter(shift);
 1671:     return if (! defined($url) || $url eq '');
 1672:     unless ($ENV{'request.course.id'}) { return ''; }
 1673:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
 1674:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1675:     $accesshash{$key}++;
 1676: }
 1677: 
 1678: sub linklog {
 1679:     my ($from,$to)=@_;
 1680:     $from=&declutter($from);
 1681:     $to=&declutter($to);
 1682:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1683:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1684: }
 1685:   
 1686: sub userrolelog {
 1687:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1688:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
 1689:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
 1690:         ($trole=~/^cr/) || ($trole=~/^ta/)) {
 1691:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1692:        $userrolehash
 1693:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1694:                     =$tend.':'.$tstart;
 1695:    }
 1696: }
 1697: 
 1698: sub get_course_adv_roles {
 1699:     my $cid=shift;
 1700:     $cid=$ENV{'request.course.id'} unless (defined($cid));
 1701:     my %coursehash=&coursedescription($cid);
 1702:     my %nothide=();
 1703:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1704: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1705:     }
 1706:     my %returnhash=();
 1707:     my %dumphash=
 1708:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1709:     my $now=time;
 1710:     foreach (keys %dumphash) {
 1711: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1712:         if (($tstart) && ($tstart<0)) { next; }
 1713:         if (($tend) && ($tend<$now)) { next; }
 1714:         if (($tstart) && ($now<$tstart)) { next; }
 1715:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1716: 	if ($username eq '' || $domain eq '') { next; }
 1717: 	if ((&privileged($username,$domain)) && 
 1718: 	    (!$nothide{$username.':'.$domain})) { next; }
 1719:         my $key=&plaintext($role);
 1720:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1721:         if ($returnhash{$key}) {
 1722: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1723:         } else {
 1724:             $returnhash{$key}=$username.':'.$domain;
 1725:         }
 1726:      }
 1727:     return %returnhash;
 1728: }
 1729: 
 1730: sub get_my_roles {
 1731:     my ($uname,$udom)=@_;
 1732:     unless (defined($uname)) { $uname=$ENV{'user.name'}; }
 1733:     unless (defined($udom)) { $udom=$ENV{'user.domain'}; }
 1734:     my %dumphash=
 1735:             &dump('nohist_userroles',$udom,$uname);
 1736:     my %returnhash=();
 1737:     my $now=time;
 1738:     foreach (keys %dumphash) {
 1739: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1740:         if (($tstart) && ($tstart<0)) { next; }
 1741:         if (($tend) && ($tend<$now)) { next; }
 1742:         if (($tstart) && ($now<$tstart)) { next; }
 1743:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1744: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1745:      }
 1746:     return %returnhash;
 1747: }
 1748: 
 1749: # ----------------------------------------------------- Frontpage Announcements
 1750: #
 1751: #
 1752: 
 1753: sub postannounce {
 1754:     my ($server,$text)=@_;
 1755:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1756:     unless ($text=~/\w/) { $text=''; }
 1757:     return &reply('setannounce:'.&escape($text),$server);
 1758: }
 1759: 
 1760: sub getannounce {
 1761: 
 1762:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1763: 	my $announcement='';
 1764: 	while (<$fh>) { $announcement .=$_; }
 1765: 	close($fh);
 1766: 	if ($announcement=~/\w/) { 
 1767: 	    return 
 1768:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1769:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1770: 	} else {
 1771: 	    return '';
 1772: 	}
 1773:     } else {
 1774: 	return '';
 1775:     }
 1776: }
 1777: 
 1778: # ---------------------------------------------------------- Course ID routines
 1779: # Deal with domain's nohist_courseid.db files
 1780: #
 1781: 
 1782: sub courseidput {
 1783:     my ($domain,$what,$coursehome)=@_;
 1784:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1785: }
 1786: 
 1787: sub courseiddump {
 1788:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$hostidflag,$hostidref)=@_;
 1789:     my %returnhash=();
 1790:     unless ($domfilter) { $domfilter=''; }
 1791:     foreach my $tryserver (keys %libserv) {
 1792:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1793: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1794: 	        foreach (
 1795:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1796: 			       $sincefilter.':'.&escape($descfilter).':'.
 1797:                                &escape($instcodefilter).':'.&escape($ownerfilter),
 1798:                                $tryserver))) {
 1799: 		    my ($key,$value)=split(/\=/,$_);
 1800:                     if (($key) && ($value)) {
 1801: 		        $returnhash{&unescape($key)}=$value;
 1802:                     }
 1803:                 }
 1804:             }
 1805:         }
 1806:     }
 1807:     return %returnhash;
 1808: }
 1809: 
 1810: #
 1811: # ----------------------------------------------------------- Check out an item
 1812: 
 1813: sub get_first_access {
 1814:     my ($type,$argsymb)=@_;
 1815:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 1816:     if ($argsymb) { $symb=$argsymb; }
 1817:     my ($map,$id,$res)=&decode_symb($symb);
 1818:     if ($type eq 'map') { $res=$map; }
 1819:     my %times=&get('firstaccesstimes',[$res],$udom,$uname);
 1820:     return $times{$res};
 1821: }
 1822: 
 1823: sub set_first_access {
 1824:     my ($type)=@_;
 1825:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 1826:     my ($map,$id,$res)=&decode_symb($symb);
 1827:     if ($type eq 'map') { $res=$map; }
 1828:     my $firstaccess=&get_first_access($type);
 1829:     if (!$firstaccess) {
 1830: 	return &put('firstaccesstimes',{$res=>time},$udom,$uname);
 1831:     }
 1832:     return 'already_set';
 1833: }
 1834: 
 1835: sub checkout {
 1836:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 1837:     my $now=time;
 1838:     my $lonhost=$perlvar{'lonHostID'};
 1839:     my $infostr=&escape(
 1840:                  'CHECKOUTTOKEN&'.
 1841:                  $tuname.'&'.
 1842:                  $tudom.'&'.
 1843:                  $tcrsid.'&'.
 1844:                  $symb.'&'.
 1845: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 1846:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 1847:     if ($token=~/^error\:/) { 
 1848:         &logthis("<font color=blue>WARNING: ".
 1849:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 1850:                  "</font>");
 1851:         return ''; 
 1852:     }
 1853: 
 1854:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 1855:     $token=~tr/a-z/A-Z/;
 1856: 
 1857:     my %infohash=('resource.0.outtoken' => $token,
 1858:                   'resource.0.checkouttime' => $now,
 1859:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 1860: 
 1861:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1862:        return '';
 1863:     } else {
 1864:         &logthis("<font color=blue>WARNING: ".
 1865:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 1866:                  "</font>");
 1867:     }    
 1868: 
 1869:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1870:                          &escape('Checkout '.$infostr.' - '.
 1871:                                                  $token)) ne 'ok') {
 1872: 	return '';
 1873:     } else {
 1874:         &logthis("<font color=blue>WARNING: ".
 1875:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 1876:                  "</font>");
 1877:     }
 1878:     return $token;
 1879: }
 1880: 
 1881: # ------------------------------------------------------------ Check in an item
 1882: 
 1883: sub checkin {
 1884:     my $token=shift;
 1885:     my $now=time;
 1886:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 1887:     $lonhost=~tr/A-Z/a-z/;
 1888:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
 1889:     $dtoken=~s/\W/\_/g;
 1890:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 1891:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 1892: 
 1893:     unless (($tuname) && ($tudom)) {
 1894:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 1895:         return '';
 1896:     }
 1897:     
 1898:     unless (&allowed('mgr',$tcrsid)) {
 1899:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 1900:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
 1901:         return '';
 1902:     }
 1903: 
 1904:     my %infohash=('resource.0.intoken' => $token,
 1905:                   'resource.0.checkintime' => $now,
 1906:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 1907: 
 1908:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1909:        return '';
 1910:     }    
 1911: 
 1912:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1913:                          &escape('Checkin - '.$token)) ne 'ok') {
 1914: 	return '';
 1915:     }
 1916: 
 1917:     return ($symb,$tuname,$tudom,$tcrsid);    
 1918: }
 1919: 
 1920: # --------------------------------------------- Set Expire Date for Spreadsheet
 1921: 
 1922: sub expirespread {
 1923:     my ($uname,$udom,$stype,$usymb)=@_;
 1924:     my $cid=$ENV{'request.course.id'}; 
 1925:     if ($cid) {
 1926:        my $now=time;
 1927:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1928:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1929:                             $ENV{'course.'.$cid.'.num'}.
 1930: 	        	    ':nohist_expirationdates:'.
 1931:                             &escape($key).'='.$now,
 1932:                             $ENV{'course.'.$cid.'.home'})
 1933:     }
 1934:     return 'ok';
 1935: }
 1936: 
 1937: # ----------------------------------------------------- Devalidate Spreadsheets
 1938: 
 1939: sub devalidate {
 1940:     my ($symb,$uname,$udom)=@_;
 1941:     my $cid=$ENV{'request.course.id'}; 
 1942:     if ($cid) {
 1943:         # delete the stored spreadsheets for
 1944:         # - the student level sheet of this user in course's homespace
 1945:         # - the assessment level sheet for this resource 
 1946:         #   for this user in user's homespace
 1947: 	# - current conditional state info
 1948: 	my $key=$uname.':'.$udom.':';
 1949:         my $status=
 1950: 	    &del('nohist_calculatedsheets',
 1951: 		 [$key.'studentcalc:'],
 1952: 		 $ENV{'course.'.$cid.'.domain'},
 1953: 		 $ENV{'course.'.$cid.'.num'})
 1954: 		.' '.
 1955: 	    &del('nohist_calculatedsheets_'.$cid,
 1956: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 1957:         unless ($status eq 'ok ok') {
 1958:            &logthis('Could not devalidate spreadsheet '.
 1959:                     $uname.' at '.$udom.' for '.
 1960: 		    $symb.': '.$status);
 1961:         }
 1962: 	&delenv('user.state.'.$cid);
 1963:     }
 1964: }
 1965: 
 1966: sub get_scalar {
 1967:     my ($string,$end) = @_;
 1968:     my $value;
 1969:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 1970: 	$value = $1;
 1971:     } elsif ($$string =~ s/^([^&]*?)&//) {
 1972: 	$value = $1;
 1973:     }
 1974:     return &unescape($value);
 1975: }
 1976: 
 1977: sub array2str {
 1978:   my (@array) = @_;
 1979:   my $result=&arrayref2str(\@array);
 1980:   $result=~s/^__ARRAY_REF__//;
 1981:   $result=~s/__END_ARRAY_REF__$//;
 1982:   return $result;
 1983: }
 1984: 
 1985: sub arrayref2str {
 1986:   my ($arrayref) = @_;
 1987:   my $result='__ARRAY_REF__';
 1988:   foreach my $elem (@$arrayref) {
 1989:     if(ref($elem) eq 'ARRAY') {
 1990:       $result.=&arrayref2str($elem).'&';
 1991:     } elsif(ref($elem) eq 'HASH') {
 1992:       $result.=&hashref2str($elem).'&';
 1993:     } elsif(ref($elem)) {
 1994:       #print("Got a ref of ".(ref($elem))." skipping.");
 1995:     } else {
 1996:       $result.=&escape($elem).'&';
 1997:     }
 1998:   }
 1999:   $result=~s/\&$//;
 2000:   $result .= '__END_ARRAY_REF__';
 2001:   return $result;
 2002: }
 2003: 
 2004: sub hash2str {
 2005:   my (%hash) = @_;
 2006:   my $result=&hashref2str(\%hash);
 2007:   $result=~s/^__HASH_REF__//;
 2008:   $result=~s/__END_HASH_REF__$//;
 2009:   return $result;
 2010: }
 2011: 
 2012: sub hashref2str {
 2013:   my ($hashref)=@_;
 2014:   my $result='__HASH_REF__';
 2015:   foreach (sort(keys(%$hashref))) {
 2016:     if (ref($_) eq 'ARRAY') {
 2017:       $result.=&arrayref2str($_).'=';
 2018:     } elsif (ref($_) eq 'HASH') {
 2019:       $result.=&hashref2str($_).'=';
 2020:     } elsif (ref($_)) {
 2021:       $result.='=';
 2022:       #print("Got a ref of ".(ref($_))." skipping.");
 2023:     } else {
 2024: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2025:     }
 2026: 
 2027:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2028:       $result.=&arrayref2str($hashref->{$_}).'&';
 2029:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2030:       $result.=&hashref2str($hashref->{$_}).'&';
 2031:     } elsif(ref($hashref->{$_})) {
 2032:        $result.='&';
 2033:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2034:     } else {
 2035:       $result.=&escape($hashref->{$_}).'&';
 2036:     }
 2037:   }
 2038:   $result=~s/\&$//;
 2039:   $result .= '__END_HASH_REF__';
 2040:   return $result;
 2041: }
 2042: 
 2043: sub str2hash {
 2044:     my ($string)=@_;
 2045:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2046:     return %$hash;
 2047: }
 2048: 
 2049: sub str2hashref {
 2050:   my ($string) = @_;
 2051: 
 2052:   my %hash;
 2053: 
 2054:   if($string !~ /^__HASH_REF__/) {
 2055:       if (! ($string eq '' || !defined($string))) {
 2056: 	  $hash{'error'}='Not hash reference';
 2057:       }
 2058:       return (\%hash, $string);
 2059:   }
 2060: 
 2061:   $string =~ s/^__HASH_REF__//;
 2062: 
 2063:   while($string !~ /^__END_HASH_REF__/) {
 2064:       #key
 2065:       my $key='';
 2066:       if($string =~ /^__HASH_REF__/) {
 2067:           ($key, $string)=&str2hashref($string);
 2068:           if(defined($key->{'error'})) {
 2069:               $hash{'error'}='Bad data';
 2070:               return (\%hash, $string);
 2071:           }
 2072:       } elsif($string =~ /^__ARRAY_REF__/) {
 2073:           ($key, $string)=&str2arrayref($string);
 2074:           if($key->[0] eq 'Array reference error') {
 2075:               $hash{'error'}='Bad data';
 2076:               return (\%hash, $string);
 2077:           }
 2078:       } else {
 2079:           $string =~ s/^(.*?)=//;
 2080: 	  $key=&unescape($1);
 2081:       }
 2082:       $string =~ s/^=//;
 2083: 
 2084:       #value
 2085:       my $value='';
 2086:       if($string =~ /^__HASH_REF__/) {
 2087:           ($value, $string)=&str2hashref($string);
 2088:           if(defined($value->{'error'})) {
 2089:               $hash{'error'}='Bad data';
 2090:               return (\%hash, $string);
 2091:           }
 2092:       } elsif($string =~ /^__ARRAY_REF__/) {
 2093:           ($value, $string)=&str2arrayref($string);
 2094:           if($value->[0] eq 'Array reference error') {
 2095:               $hash{'error'}='Bad data';
 2096:               return (\%hash, $string);
 2097:           }
 2098:       } else {
 2099: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2100:       }
 2101:       $string =~ s/^&//;
 2102: 
 2103:       $hash{$key}=$value;
 2104:   }
 2105: 
 2106:   $string =~ s/^__END_HASH_REF__//;
 2107: 
 2108:   return (\%hash, $string);
 2109: }
 2110: 
 2111: sub str2array {
 2112:     my ($string)=@_;
 2113:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2114:     return @$array;
 2115: }
 2116: 
 2117: sub str2arrayref {
 2118:   my ($string) = @_;
 2119:   my @array;
 2120: 
 2121:   if($string !~ /^__ARRAY_REF__/) {
 2122:       if (! ($string eq '' || !defined($string))) {
 2123: 	  $array[0]='Array reference error';
 2124:       }
 2125:       return (\@array, $string);
 2126:   }
 2127: 
 2128:   $string =~ s/^__ARRAY_REF__//;
 2129: 
 2130:   while($string !~ /^__END_ARRAY_REF__/) {
 2131:       my $value='';
 2132:       if($string =~ /^__HASH_REF__/) {
 2133:           ($value, $string)=&str2hashref($string);
 2134:           if(defined($value->{'error'})) {
 2135:               $array[0] ='Array reference error';
 2136:               return (\@array, $string);
 2137:           }
 2138:       } elsif($string =~ /^__ARRAY_REF__/) {
 2139:           ($value, $string)=&str2arrayref($string);
 2140:           if($value->[0] eq 'Array reference error') {
 2141:               $array[0] ='Array reference error';
 2142:               return (\@array, $string);
 2143:           }
 2144:       } else {
 2145: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2146:       }
 2147:       $string =~ s/^&//;
 2148: 
 2149:       push(@array, $value);
 2150:   }
 2151: 
 2152:   $string =~ s/^__END_ARRAY_REF__//;
 2153: 
 2154:   return (\@array, $string);
 2155: }
 2156: 
 2157: # -------------------------------------------------------------------Temp Store
 2158: 
 2159: sub tmpreset {
 2160:   my ($symb,$namespace,$domain,$stuname) = @_;
 2161:   if (!$symb) {
 2162:     $symb=&symbread();
 2163:     if (!$symb) { $symb= $ENV{'request.url'}; }
 2164:   }
 2165:   $symb=escape($symb);
 2166: 
 2167:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 2168:   $namespace=~s/\//\_/g;
 2169:   $namespace=~s/\W//g;
 2170: 
 2171:   #FIXME needs to do something for /pub resources
 2172:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 2173:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2174:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2175:   my %hash;
 2176:   if (tie(%hash,'GDBM_File',
 2177: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2178: 	  &GDBM_WRCREAT(),0640)) {
 2179:     foreach my $key (keys %hash) {
 2180:       if ($key=~ /:$symb/) {
 2181: 	delete($hash{$key});
 2182:       }
 2183:     }
 2184:   }
 2185: }
 2186: 
 2187: sub tmpstore {
 2188:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2189: 
 2190:   if (!$symb) {
 2191:     $symb=&symbread();
 2192:     if (!$symb) { $symb= $ENV{'request.url'}; }
 2193:   }
 2194:   $symb=escape($symb);
 2195: 
 2196:   if (!$namespace) {
 2197:     # I don't think we would ever want to store this for a course.
 2198:     # it seems this will only be used if we don't have a course.
 2199:     #$namespace=$ENV{'request.course.id'};
 2200:     #if (!$namespace) {
 2201:       $namespace=$ENV{'request.state'};
 2202:     #}
 2203:   }
 2204:   $namespace=~s/\//\_/g;
 2205:   $namespace=~s/\W//g;
 2206: #FIXME needs to do something for /pub resources
 2207:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 2208:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2209:   my $now=time;
 2210:   my %hash;
 2211:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2212:   if (tie(%hash,'GDBM_File',
 2213: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2214: 	  &GDBM_WRCREAT(),0640)) {
 2215:     $hash{"version:$symb"}++;
 2216:     my $version=$hash{"version:$symb"};
 2217:     my $allkeys=''; 
 2218:     foreach my $key (keys(%$storehash)) {
 2219:       $allkeys.=$key.':';
 2220:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 2221:     }
 2222:     $hash{"$version:$symb:timestamp"}=$now;
 2223:     $allkeys.='timestamp';
 2224:     $hash{"$version:keys:$symb"}=$allkeys;
 2225:     if (untie(%hash)) {
 2226:       return 'ok';
 2227:     } else {
 2228:       return "error:$!";
 2229:     }
 2230:   } else {
 2231:     return "error:$!";
 2232:   }
 2233: }
 2234: 
 2235: # -----------------------------------------------------------------Temp Restore
 2236: 
 2237: sub tmprestore {
 2238:   my ($symb,$namespace,$domain,$stuname) = @_;
 2239: 
 2240:   if (!$symb) {
 2241:     $symb=&symbread();
 2242:     if (!$symb) { $symb= $ENV{'request.url'}; }
 2243:   }
 2244:   $symb=escape($symb);
 2245: 
 2246:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 2247:   #FIXME needs to do something for /pub resources
 2248:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 2249:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2250: 
 2251:   my %returnhash;
 2252:   $namespace=~s/\//\_/g;
 2253:   $namespace=~s/\W//g;
 2254:   my %hash;
 2255:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2256:   if (tie(%hash,'GDBM_File',
 2257: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2258: 	  &GDBM_READER(),0640)) {
 2259:     my $version=$hash{"version:$symb"};
 2260:     $returnhash{'version'}=$version;
 2261:     my $scope;
 2262:     for ($scope=1;$scope<=$version;$scope++) {
 2263:       my $vkeys=$hash{"$scope:keys:$symb"};
 2264:       my @keys=split(/:/,$vkeys);
 2265:       my $key;
 2266:       $returnhash{"$scope:keys"}=$vkeys;
 2267:       foreach $key (@keys) {
 2268: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 2269: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 2270:       }
 2271:     }
 2272:     if (!(untie(%hash))) {
 2273:       return "error:$!";
 2274:     }
 2275:   } else {
 2276:     return "error:$!";
 2277:   }
 2278:   return %returnhash;
 2279: }
 2280: 
 2281: # ----------------------------------------------------------------------- Store
 2282: 
 2283: sub store {
 2284:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2285:     my $home='';
 2286: 
 2287:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2288: 
 2289:     $symb=&symbclean($symb);
 2290:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2291: 
 2292:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 2293:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2294: 
 2295:     &devalidate($symb,$stuname,$domain);
 2296: 
 2297:     $symb=escape($symb);
 2298:     if (!$namespace) { 
 2299:        unless ($namespace=$ENV{'request.course.id'}) { 
 2300:           return ''; 
 2301:        } 
 2302:     }
 2303:     if (!$home) { $home=$ENV{'user.home'}; }
 2304: 
 2305:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2306:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2307: 
 2308:     my $namevalue='';
 2309:     foreach (keys %$storehash) {
 2310:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 2311:     }
 2312:     $namevalue=~s/\&$//;
 2313:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2314:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2315: }
 2316: 
 2317: # -------------------------------------------------------------- Critical Store
 2318: 
 2319: sub cstore {
 2320:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2321:     my $home='';
 2322: 
 2323:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2324: 
 2325:     $symb=&symbclean($symb);
 2326:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2327: 
 2328:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 2329:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2330: 
 2331:     &devalidate($symb,$stuname,$domain);
 2332: 
 2333:     $symb=escape($symb);
 2334:     if (!$namespace) { 
 2335:        unless ($namespace=$ENV{'request.course.id'}) { 
 2336:           return ''; 
 2337:        } 
 2338:     }
 2339:     if (!$home) { $home=$ENV{'user.home'}; }
 2340: 
 2341:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2342:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2343: 
 2344:     my $namevalue='';
 2345:     foreach (keys %$storehash) {
 2346:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 2347:     }
 2348:     $namevalue=~s/\&$//;
 2349:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2350:     return critical
 2351:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2352: }
 2353: 
 2354: # --------------------------------------------------------------------- Restore
 2355: 
 2356: sub restore {
 2357:     my ($symb,$namespace,$domain,$stuname) = @_;
 2358:     my $home='';
 2359: 
 2360:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2361: 
 2362:     if (!$symb) {
 2363:       unless ($symb=escape(&symbread())) { return ''; }
 2364:     } else {
 2365:       $symb=&escape(&symbclean($symb));
 2366:     }
 2367:     if (!$namespace) { 
 2368:        unless ($namespace=$ENV{'request.course.id'}) { 
 2369:           return ''; 
 2370:        } 
 2371:     }
 2372:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 2373:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 2374:     if (!$home) { $home=$ENV{'user.home'}; }
 2375:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2376: 
 2377:     my %returnhash=();
 2378:     foreach (split(/\&/,$answer)) {
 2379: 	my ($name,$value)=split(/\=/,$_);
 2380:         $returnhash{&unescape($name)}=&unescape($value);
 2381:     }
 2382:     my $version;
 2383:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2384:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2385:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2386:        }
 2387:     }
 2388:     return %returnhash;
 2389: }
 2390: 
 2391: # ---------------------------------------------------------- Course Description
 2392: 
 2393: sub coursedescription {
 2394:     my $courseid=shift;
 2395:     $courseid=~s/^\///;
 2396:     $courseid=~s/\_/\//g;
 2397:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2398:     my $chome=&homeserver($cnum,$cdomain);
 2399:     my $normalid=$cdomain.'_'.$cnum;
 2400:     # need to always cache even if we get errors otherwise we keep 
 2401:     # trying and trying and trying to get the course description.
 2402:     my %envhash=();
 2403:     my %returnhash=();
 2404:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 2405:     if ($chome ne 'no_host') {
 2406:        %returnhash=&dump('environment',$cdomain,$cnum);
 2407:        if (!exists($returnhash{'con_lost'})) {
 2408:            $returnhash{'home'}= $chome;
 2409: 	   $returnhash{'domain'} = $cdomain;
 2410: 	   $returnhash{'num'} = $cnum;
 2411:            while (my ($name,$value) = each %returnhash) {
 2412:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2413:            }
 2414:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2415:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2416: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2417:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2418:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2419:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2420:        }
 2421:     }
 2422:     &appenv(%envhash);
 2423:     return %returnhash;
 2424: }
 2425: 
 2426: # -------------------------------------------------See if a user is privileged
 2427: 
 2428: sub privileged {
 2429:     my ($username,$domain)=@_;
 2430:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2431: 			&homeserver($username,$domain));
 2432:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2433:     my $now=time;
 2434:     if ($rolesdump ne '') {
 2435:         foreach (split(/&/,$rolesdump)) {
 2436: 	    if ($_!~/^rolesdef_/) {
 2437: 		my ($area,$role)=split(/=/,$_);
 2438: 		$area=~s/\_\w\w$//;
 2439: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2440: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2441: 		    my $active=1;
 2442: 		    if ($tend) {
 2443: 			if ($tend<$now) { $active=0; }
 2444: 		    }
 2445: 		    if ($tstart) {
 2446: 			if ($tstart>$now) { $active=0; }
 2447: 		    }
 2448: 		    if ($active) { return 1; }
 2449: 		}
 2450: 	    }
 2451: 	}
 2452:     }
 2453:     return 0;
 2454: }
 2455: 
 2456: # -------------------------------------------------------- Get user privileges
 2457: 
 2458: sub rolesinit {
 2459:     my ($domain,$username,$authhost)=@_;
 2460:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2461:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2462:     my %allroles=();
 2463:     my $now=time;
 2464:     my $userroles="user.login.time=$now\n";
 2465: 
 2466:     if ($rolesdump ne '') {
 2467:         foreach (split(/&/,$rolesdump)) {
 2468: 	  if ($_!~/^rolesdef_/) {
 2469:             my ($area,$role)=split(/=/,$_);
 2470: 	    $area=~s/\_\w\w$//;
 2471: 	    
 2472:             my ($trole,$tend,$tstart);
 2473: 	    if ($role=~/^cr/) { 
 2474: 		($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2475: 		($tend,$tstart)=split('_',$trest);
 2476: 	    } else {
 2477: 		($trole,$tend,$tstart)=split(/_/,$role);
 2478: 	    }
 2479:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
 2480:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2481:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2482:             if (($area ne '') && ($trole ne '')) {
 2483: 		my $spec=$trole.'.'.$area;
 2484: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2485: 		if ($trole =~ /^cr\//) {
 2486:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2487: 		} else {
 2488:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2489: 		}
 2490:             }
 2491:           } 
 2492:         }
 2493:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
 2494:         $userroles.='user.adv='.$adv."\n".
 2495: 	            'user.author='.$author."\n";
 2496:         $ENV{'user.adv'}=$adv;
 2497:     }
 2498:     return $userroles;  
 2499: }
 2500: 
 2501: sub set_arearole {
 2502:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2503: # log the associated role with the area
 2504:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2505:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
 2506: }
 2507: 
 2508: sub custom_roleprivs {
 2509:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2510:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2511:     my $homsvr=homeserver($rauthor,$rdomain);
 2512:     if ($hostname{$homsvr} ne '') {
 2513:         my ($rdummy,$roledef)=
 2514:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2515:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2516:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2517:             if (defined($syspriv)) {
 2518:                 $$allroles{'cm./'}.=':'.$syspriv;
 2519:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2520:             }
 2521:             if ($tdomain ne '') {
 2522:                 if (defined($dompriv)) {
 2523:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2524:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2525:                 }
 2526:                 if (($trest ne '') && (defined($coursepriv))) {
 2527:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2528:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2529:                 }
 2530:             }
 2531:         }
 2532:     }
 2533: }
 2534: 
 2535: 
 2536: sub standard_roleprivs {
 2537:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2538:     if (defined($pr{$trole.':s'})) {
 2539:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2540:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2541:     }
 2542:     if ($tdomain ne '') {
 2543:         if (defined($pr{$trole.':d'})) {
 2544:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2545:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2546:         }
 2547:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2548:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2549:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2550:         }
 2551:     }
 2552: }
 2553: 
 2554: sub set_userprivs {
 2555:     my ($userroles,$allroles) = @_; 
 2556:     my $author=0;
 2557:     my $adv=0;
 2558:     foreach (keys %{$allroles}) {
 2559:         my %thesepriv=();
 2560:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2561:         foreach (split(/:/,$$allroles{$_})) {
 2562:             if ($_ ne '') {
 2563:                 my ($privilege,$restrictions)=split(/&/,$_);
 2564:                 if ($restrictions eq '') {
 2565:                     $thesepriv{$privilege}='F';
 2566:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2567:                     $thesepriv{$privilege}.=$restrictions;
 2568:                 }
 2569:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2570:             }
 2571:         }
 2572:         my $thesestr='';
 2573:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2574:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2575:     }
 2576:     return ($author,$adv);
 2577: }
 2578: 
 2579: # --------------------------------------------------------------- get interface
 2580: 
 2581: sub get {
 2582:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2583:    my $items='';
 2584:    foreach (@$storearr) {
 2585:        $items.=escape($_).'&';
 2586:    }
 2587:    $items=~s/\&$//;
 2588:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2589:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2590:    my $uhome=&homeserver($uname,$udomain);
 2591: 
 2592:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2593:    my @pairs=split(/\&/,$rep);
 2594:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2595:      return @pairs;
 2596:    }
 2597:    my %returnhash=();
 2598:    my $i=0;
 2599:    foreach (@$storearr) {
 2600:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2601:       $i++;
 2602:    }
 2603:    return %returnhash;
 2604: }
 2605: 
 2606: # --------------------------------------------------------------- del interface
 2607: 
 2608: sub del {
 2609:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2610:    my $items='';
 2611:    foreach (@$storearr) {
 2612:        $items.=escape($_).'&';
 2613:    }
 2614:    $items=~s/\&$//;
 2615:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2616:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2617:    my $uhome=&homeserver($uname,$udomain);
 2618: 
 2619:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2620: }
 2621: 
 2622: # -------------------------------------------------------------- dump interface
 2623: 
 2624: sub dump {
 2625:    my ($namespace,$udomain,$uname,$regexp)=@_;
 2626:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2627:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2628:    my $uhome=&homeserver($uname,$udomain);
 2629:    if ($regexp) {
 2630:        $regexp=&escape($regexp);
 2631:    } else {
 2632:        $regexp='.';
 2633:    }
 2634:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 2635:    my @pairs=split(/\&/,$rep);
 2636:    my %returnhash=();
 2637:    foreach (@pairs) {
 2638:       my ($key,$value)=split(/=/,$_);
 2639:       $returnhash{unescape($key)}=&thaw_unescape($value);
 2640:    }
 2641:    return %returnhash;
 2642: }
 2643: 
 2644: # -------------------------------------------------------------- keys interface
 2645: 
 2646: sub getkeys {
 2647:    my ($namespace,$udomain,$uname)=@_;
 2648:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2649:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2650:    my $uhome=&homeserver($uname,$udomain);
 2651:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2652:    my @keyarray=();
 2653:    foreach (split(/\&/,$rep)) {
 2654:       push (@keyarray,&unescape($_));
 2655:    }
 2656:    return @keyarray;
 2657: }
 2658: 
 2659: # --------------------------------------------------------------- currentdump
 2660: sub currentdump {
 2661:    my ($courseid,$sdom,$sname)=@_;
 2662:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2663:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
 2664:    $sname    = $ENV{'user.name'}         if (! defined($sname));
 2665:    my $uhome = &homeserver($sname,$sdom);
 2666:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2667:    return if ($rep =~ /^(error:|no_such_host)/);
 2668:    #
 2669:    my %returnhash=();
 2670:    #
 2671:    if ($rep eq "unknown_cmd") { 
 2672:        # an old lond will not know currentdump
 2673:        # Do a dump and make it look like a currentdump
 2674:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2675:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2676:        my %hash = @tmp;
 2677:        @tmp=();
 2678:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2679:    } else {
 2680:        my @pairs=split(/\&/,$rep);
 2681:        foreach (@pairs) {
 2682:            my ($key,$value)=split(/=/,$_);
 2683:            my ($symb,$param) = split(/:/,$key);
 2684:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2685:                                                         &thaw_unescape($value);
 2686:        }
 2687:    }
 2688:    return %returnhash;
 2689: }
 2690: 
 2691: sub convert_dump_to_currentdump{
 2692:     my %hash = %{shift()};
 2693:     my %returnhash;
 2694:     # Code ripped from lond, essentially.  The only difference
 2695:     # here is the unescaping done by lonnet::dump().  Conceivably
 2696:     # we might run in to problems with parameter names =~ /^v\./
 2697:     while (my ($key,$value) = each(%hash)) {
 2698:         my ($v,$symb,$param) = split(/:/,$key);
 2699:         next if ($v eq 'version' || $symb eq 'keys');
 2700:         next if (exists($returnhash{$symb}) &&
 2701:                  exists($returnhash{$symb}->{$param}) &&
 2702:                  $returnhash{$symb}->{'v.'.$param} > $v);
 2703:         $returnhash{$symb}->{$param}=$value;
 2704:         $returnhash{$symb}->{'v.'.$param}=$v;
 2705:     }
 2706:     #
 2707:     # Remove all of the keys in the hashes which keep track of
 2708:     # the version of the parameter.
 2709:     while (my ($symb,$param_hash) = each(%returnhash)) {
 2710:         # use a foreach because we are going to delete from the hash.
 2711:         foreach my $key (keys(%$param_hash)) {
 2712:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 2713:         }
 2714:     }
 2715:     return \%returnhash;
 2716: }
 2717: 
 2718: # --------------------------------------------------------------- inc interface
 2719: 
 2720: sub inc {
 2721:     my ($namespace,$store,$udomain,$uname) = @_;
 2722:     if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2723:     if (!$uname) { $uname=$ENV{'user.name'}; }
 2724:     my $uhome=&homeserver($uname,$udomain);
 2725:     my $items='';
 2726:     if (! ref($store)) {
 2727:         # got a single value, so use that instead
 2728:         $items = &escape($store).'=&';
 2729:     } elsif (ref($store) eq 'SCALAR') {
 2730:         $items = &escape($$store).'=&';        
 2731:     } elsif (ref($store) eq 'ARRAY') {
 2732:         $items = join('=&',map {&escape($_);} @{$store});
 2733:     } elsif (ref($store) eq 'HASH') {
 2734:         while (my($key,$value) = each(%{$store})) {
 2735:             $items.= &escape($key).'='.&escape($value).'&';
 2736:         }
 2737:     }
 2738:     $items=~s/\&$//;
 2739:     return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 2740: }
 2741: 
 2742: # --------------------------------------------------------------- put interface
 2743: 
 2744: sub put {
 2745:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2746:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2747:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2748:    my $uhome=&homeserver($uname,$udomain);
 2749:    my $items='';
 2750:    foreach (keys %$storehash) {
 2751:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2752:    }
 2753:    $items=~s/\&$//;
 2754:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2755: }
 2756: 
 2757: # ---------------------------------------------------------- putstore interface
 2758:                                                                                      
 2759: sub putstore {
 2760:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2761:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2762:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2763:    my $uhome=&homeserver($uname,$udomain);
 2764:    my $items='';
 2765:    my %allitems = ();
 2766:    foreach (keys %$storehash) {
 2767:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 2768:            my $key = $1.':keys:'.$2;
 2769:            $allitems{$key} .= $3.':';
 2770:        }
 2771:        $items.=$_.'='.&escape($$storehash{$_}).'&';
 2772:    }
 2773:    foreach (keys %allitems) {
 2774:        $allitems{$_} =~ s/\:$//;
 2775:        $items.= $_.'='.$allitems{$_}.'&';
 2776:    }
 2777:    $items=~s/\&$//;
 2778:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2779: }
 2780: 
 2781: # ------------------------------------------------------ critical put interface
 2782: 
 2783: sub cput {
 2784:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2785:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2786:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2787:    my $uhome=&homeserver($uname,$udomain);
 2788:    my $items='';
 2789:    foreach (keys %$storehash) {
 2790:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2791:    }
 2792:    $items=~s/\&$//;
 2793:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2794: }
 2795: 
 2796: # -------------------------------------------------------------- eget interface
 2797: 
 2798: sub eget {
 2799:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2800:    my $items='';
 2801:    foreach (@$storearr) {
 2802:        $items.=escape($_).'&';
 2803:    }
 2804:    $items=~s/\&$//;
 2805:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2806:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2807:    my $uhome=&homeserver($uname,$udomain);
 2808:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2809:    my @pairs=split(/\&/,$rep);
 2810:    my %returnhash=();
 2811:    my $i=0;
 2812:    foreach (@$storearr) {
 2813:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2814:       $i++;
 2815:    }
 2816:    return %returnhash;
 2817: }
 2818: 
 2819: # ---------------------------------------------- Custom access rule evaluation
 2820: 
 2821: sub customaccess {
 2822:     my ($priv,$uri)=@_;
 2823:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
 2824:     $urealm=~s/^\W//;
 2825:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2826:     my $access=0;
 2827:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2828: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2829:         if ($role) {
 2830: 	   if ($role ne $urole) { next; }
 2831:         }
 2832:         foreach (split(/\s*\,\s*/,$realm)) {
 2833:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2834:             if ($tdom) {
 2835: 		if ($tdom ne $udom) { next; }
 2836:             }
 2837:             if ($tcrs) {
 2838: 		if ($tcrs ne $ucrs) { next; }
 2839:             }
 2840:             if ($tsec) {
 2841: 		if ($tsec ne $usec) { next; }
 2842:             }
 2843:             $access=($effect eq 'allow');
 2844:             last;
 2845:         }
 2846: 	if ($realm eq '' && $role eq '') {
 2847:             $access=($effect eq 'allow');
 2848: 	}
 2849:     }
 2850:     return $access;
 2851: }
 2852: 
 2853: # ------------------------------------------------- Check for a user privilege
 2854: 
 2855: sub allowed {
 2856:     my ($priv,$uri,$symb)=@_;
 2857:     $uri=&deversion($uri);
 2858:     my $orguri=$uri;
 2859:     $uri=&declutter($uri);
 2860:     
 2861:     
 2862:     
 2863:     if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; }
 2864: # Free bre access to adm and meta resources
 2865:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 2866: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 2867: 	return 'F';
 2868:     }
 2869: 
 2870: # Free bre access to user's own portfolio contents
 2871:     my ($space,$domain,$name,$dir)=split('/',$uri);
 2872:     if (('uploaded' eq $space) && ($ENV{'user.name'} eq $name) && 
 2873: 	($ENV{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
 2874:         return 'F';
 2875:     }
 2876: 
 2877: # Free bre to public access
 2878: 
 2879:     if ($priv eq 'bre') {
 2880:         my $copyright=&metadata($uri,'copyright');
 2881: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
 2882:            return 'F'; 
 2883:         }
 2884:         if ($copyright eq 'priv') {
 2885:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2886: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 2887: 		return '';
 2888:             }
 2889:         }
 2890:         if ($copyright eq 'domain') {
 2891:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2892: 	    unless (($ENV{'user.domain'} eq $1) ||
 2893:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 2894: 		return '';
 2895:             }
 2896:         }
 2897:         if ($ENV{'request.role'}=~ /li\.\//) {
 2898:             # Library role, so allow browsing of resources in this domain.
 2899:             return 'F';
 2900:         }
 2901:         if ($copyright eq 'custom') {
 2902: 	    unless (&customaccess($priv,$uri)) { return ''; }
 2903:         }
 2904:     }
 2905:     # Domain coordinator is trying to create a course
 2906:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 2907:         # uri is the requested domain in this case.
 2908:         # comparison to 'request.role.domain' shows if the user has selected
 2909:         # a role of dc for the domain in question. 
 2910:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 2911:     }
 2912: 
 2913:     my $thisallowed='';
 2914:     my $statecond=0;
 2915:     my $courseprivid='';
 2916: 
 2917: # Course
 2918: 
 2919:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 2920:        $thisallowed.=$1;
 2921:     }
 2922: 
 2923: # Domain
 2924: 
 2925:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 2926:        =~/\Q$priv\E\&([^\:]*)/) {
 2927:        $thisallowed.=$1;
 2928:     }
 2929: 
 2930: # Course: uri itself is a course
 2931:     my $courseuri=$uri;
 2932:     $courseuri=~s/\_(\d)/\/$1/;
 2933:     $courseuri=~s/^([^\/])/\/$1/;
 2934: 
 2935:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 2936:        =~/\Q$priv\E\&([^\:]*)/) {
 2937:        $thisallowed.=$1;
 2938:     }
 2939: 
 2940: # URI is an uploaded document for this course
 2941: 
 2942:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 2943: 	my $refuri=$ENV{'httpref.'.$orguri};
 2944: 	if ($refuri) {
 2945: 	    if ($refuri =~ m|^/adm/|) {
 2946: 		$thisallowed='F';
 2947: 	    }
 2948: 	}
 2949:     }
 2950: 
 2951: # Full access at system, domain or course-wide level? Exit.
 2952: 
 2953:     if ($thisallowed=~/F/) {
 2954: 	return 'F';
 2955:     }
 2956: 
 2957: # If this is generating or modifying users, exit with special codes
 2958: 
 2959:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) {
 2960: 	return $thisallowed;
 2961:     }
 2962: #
 2963: # Gathered so far: system, domain and course wide privileges
 2964: #
 2965: # Course: See if uri or referer is an individual resource that is part of 
 2966: # the course
 2967: 
 2968:     if ($ENV{'request.course.id'}) {
 2969: 
 2970:        $courseprivid=$ENV{'request.course.id'};
 2971:        if ($ENV{'request.course.sec'}) {
 2972:           $courseprivid.='/'.$ENV{'request.course.sec'};
 2973:        }
 2974:        $courseprivid=~s/\_/\//;
 2975:        my $checkreferer=1;
 2976:        my ($match,$cond)=&is_on_map($uri);
 2977:        if ($match) {
 2978:            $statecond=$cond;
 2979:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2980:                =~/\Q$priv\E\&([^\:]*)/) {
 2981:                $thisallowed.=$1;
 2982:                $checkreferer=0;
 2983:            }
 2984:        }
 2985:        
 2986:        if ($checkreferer) {
 2987: 	  my $refuri=$ENV{'httpref.'.$orguri};
 2988:             unless ($refuri) {
 2989:                 foreach (keys %ENV) {
 2990: 		    if ($_=~/^httpref\..*\*/) {
 2991: 			my $pattern=$_;
 2992:                         $pattern=~s/^httpref\.\/res\///;
 2993:                         $pattern=~s/\*/\[\^\/\]\+/g;
 2994:                         $pattern=~s/\//\\\//g;
 2995:                         if ($orguri=~/$pattern/) {
 2996: 			    $refuri=$ENV{$_};
 2997:                         }
 2998:                     }
 2999:                 }
 3000:             }
 3001: 
 3002:          if ($refuri) { 
 3003: 	  $refuri=&declutter($refuri);
 3004:           my ($match,$cond)=&is_on_map($refuri);
 3005:             if ($match) {
 3006:               my $refstatecond=$cond;
 3007:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 3008:                   =~/\Q$priv\E\&([^\:]*)/) {
 3009:                   $thisallowed.=$1;
 3010:                   $uri=$refuri;
 3011:                   $statecond=$refstatecond;
 3012:               }
 3013:           }
 3014:         }
 3015:        }
 3016:    }
 3017: 
 3018: #
 3019: # Gathered now: all privileges that could apply, and condition number
 3020: # 
 3021: #
 3022: # Full or no access?
 3023: #
 3024: 
 3025:     if ($thisallowed=~/F/) {
 3026: 	return 'F';
 3027:     }
 3028: 
 3029:     unless ($thisallowed) {
 3030:         return '';
 3031:     }
 3032: 
 3033: # Restrictions exist, deal with them
 3034: #
 3035: #   C:according to course preferences
 3036: #   R:according to resource settings
 3037: #   L:unless locked
 3038: #   X:according to user session state
 3039: #
 3040: 
 3041: # Possibly locked functionality, check all courses
 3042: # Locks might take effect only after 10 minutes cache expiration for other
 3043: # courses, and 2 minutes for current course
 3044: 
 3045:     my $envkey;
 3046:     if ($thisallowed=~/L/) {
 3047:         foreach $envkey (keys %ENV) {
 3048:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3049:                my $courseid=$2;
 3050:                my $roleid=$1.'.'.$2;
 3051:                $courseid=~s/^\///;
 3052:                my $expiretime=600;
 3053:                if ($ENV{'request.role'} eq $roleid) {
 3054: 		  $expiretime=120;
 3055:                }
 3056: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3057:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3058:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 3059: 		   &coursedescription($courseid);
 3060:                }
 3061:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3062:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3063: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3064:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 3065:                             $ENV{'user.home'},
 3066:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3067:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3068:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 3069: 		       return '';
 3070:                    }
 3071:                }
 3072:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3073:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3074: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 3075:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 3076:                             $ENV{'user.home'},
 3077:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3078:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3079:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 3080: 		       return '';
 3081:                    }
 3082:                }
 3083: 	   }
 3084:        }
 3085:     }
 3086:    
 3087: #
 3088: # Rest of the restrictions depend on selected course
 3089: #
 3090: 
 3091:     unless ($ENV{'request.course.id'}) {
 3092:        return '1';
 3093:     }
 3094: 
 3095: #
 3096: # Now user is definitely in a course
 3097: #
 3098: 
 3099: 
 3100: # Course preferences
 3101: 
 3102:    if ($thisallowed=~/C/) {
 3103:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 3104:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 3105:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3106: 	   =~/\Q$rolecode\E/) {
 3107:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 3108:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3109:                 $ENV{'request.course.id'});
 3110:            return '';
 3111:        }
 3112: 
 3113:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 3114: 	   =~/\Q$unamedom\E/) {
 3115:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 3116:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3117:                 $ENV{'request.course.id'});
 3118:            return '';
 3119:        }
 3120:    }
 3121: 
 3122: # Resource preferences
 3123: 
 3124:    if ($thisallowed=~/R/) {
 3125:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 3126:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3127: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 3128:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3129:           return '';
 3130:        }
 3131:    }
 3132: 
 3133: # Restricted by state or randomout?
 3134: 
 3135:    if ($thisallowed=~/X/) {
 3136:       if ($ENV{'acc.randomout'}) {
 3137: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3138:          if (($symb) && ($ENV{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3139:             return ''; 
 3140:          }
 3141:       }
 3142:       if (&condval($statecond)) {
 3143: 	 return '2';
 3144:       } else {
 3145:          return '';
 3146:       }
 3147:    }
 3148: 
 3149:    return 'F';
 3150: }
 3151: 
 3152: # --------------------------------------------------- Is a resource on the map?
 3153: 
 3154: sub is_on_map {
 3155:     my $uri=&declutter(shift);
 3156:     $uri=~s/\.\d+\.(\w+)$/\.$1/;
 3157:     my @uriparts=split(/\//,$uri);
 3158:     my $filename=$uriparts[$#uriparts];
 3159:     my $pathname=$uri;
 3160:     $pathname=~s|/\Q$filename\E$||;
 3161:     $pathname=~s/^adm\/wrapper\///;    
 3162:     #Trying to find the conditional for the file
 3163:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 3164: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3165:     if ($match) {
 3166: 	return (1,$1);
 3167:     } else {
 3168: 	return (0,0);
 3169:     }
 3170: }
 3171: 
 3172: # --------------------------------------------------------- Get symb from alias
 3173: 
 3174: sub get_symb_from_alias {
 3175:     my $symb=shift;
 3176:     my ($map,$resid,$url)=&decode_symb($symb);
 3177: # Already is a symb
 3178:     if ($url) { return $symb; }
 3179: # Must be an alias
 3180:     my $aliassymb='';
 3181:     my %bighash;
 3182:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3183:                             &GDBM_READER(),0640)) {
 3184:         my $rid=$bighash{'mapalias_'.$symb};
 3185: 	if ($rid) {
 3186: 	    my ($mapid,$resid)=split(/\./,$rid);
 3187: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3188: 				    $resid,$bighash{'src_'.$rid});
 3189: 	}
 3190:         untie %bighash;
 3191:     }
 3192:     return $aliassymb;
 3193: }
 3194: 
 3195: # ----------------------------------------------------------------- Define Role
 3196: 
 3197: sub definerole {
 3198:   if (allowed('mcr','/')) {
 3199:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3200:     foreach (split(':',$sysrole)) {
 3201: 	my ($crole,$cqual)=split(/\&/,$_);
 3202:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3203:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3204: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3205:                return "refused:s:$crole&$cqual"; 
 3206:             }
 3207:         }
 3208:     }
 3209:     foreach (split(':',$domrole)) {
 3210: 	my ($crole,$cqual)=split(/\&/,$_);
 3211:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3212:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3213: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3214:                return "refused:d:$crole&$cqual"; 
 3215:             }
 3216:         }
 3217:     }
 3218:     foreach (split(':',$courole)) {
 3219: 	my ($crole,$cqual)=split(/\&/,$_);
 3220:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3221:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3222: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3223:                return "refused:c:$crole&$cqual"; 
 3224:             }
 3225:         }
 3226:     }
 3227:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 3228:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 3229: 	        "rolesdef_$rolename=".
 3230:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3231:     return reply($command,$ENV{'user.home'});
 3232:   } else {
 3233:     return 'refused';
 3234:   }
 3235: }
 3236: 
 3237: # ---------------- Make a metadata query against the network of library servers
 3238: 
 3239: sub metadata_query {
 3240:     my ($query,$custom,$customshow,$server_array)=@_;
 3241:     my %rhash;
 3242:     my @server_list = (defined($server_array) ? @$server_array
 3243:                                               : keys(%libserv) );
 3244:     for my $server (@server_list) {
 3245: 	unless ($custom or $customshow) {
 3246: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3247: 	    $rhash{$server}=$reply;
 3248: 	}
 3249: 	else {
 3250: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3251: 			     &escape($custom).':'.&escape($customshow),
 3252: 			     $server);
 3253: 	    $rhash{$server}=$reply;
 3254: 	}
 3255:     }
 3256:     return \%rhash;
 3257: }
 3258: 
 3259: # ----------------------------------------- Send log queries and wait for reply
 3260: 
 3261: sub log_query {
 3262:     my ($uname,$udom,$query,%filters)=@_;
 3263:     my $uhome=&homeserver($uname,$udom);
 3264:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3265:     my $uhost=$hostname{$uhome};
 3266:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3267:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3268:                        $uhome);
 3269:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3270:     return get_query_reply($queryid);
 3271: }
 3272: 
 3273: # ------- Request retrieval of institutional classlists for course(s)
 3274: 
 3275: sub fetch_enrollment_query {
 3276:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3277:     my $homeserver;
 3278:     my $maxtries = 1;
 3279:     if ($context eq 'automated') {
 3280:         $homeserver = $perlvar{'lonHostID'};
 3281:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3282:     } else {
 3283:         $homeserver = &homeserver($cnum,$dom);
 3284:     }
 3285:     my $host=$hostname{$homeserver};
 3286:     my $cmd = '';
 3287:     foreach (keys %{$affiliatesref}) {
 3288:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3289:     }
 3290:     $cmd =~ s/%%$//;
 3291:     $cmd = &escape($cmd);
 3292:     my $query = 'fetchenrollment';
 3293:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$ENV{'user.name'}.':'.$cmd,$homeserver);
 3294:     unless ($queryid=~/^\Q$host\E\_/) { 
 3295:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3296:         return 'error: '.$queryid;
 3297:     }
 3298:     my $reply = &get_query_reply($queryid);
 3299:     my $tries = 1;
 3300:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3301:         $reply = &get_query_reply($queryid);
 3302:         $tries ++;
 3303:     }
 3304:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3305:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$ENV{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3306:     } else {
 3307:         my @responses = split/:/,$reply;
 3308:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3309:             foreach (@responses) {
 3310:                 my ($key,$value) = split/=/,$_;
 3311:                 $$replyref{$key} = $value;
 3312:             }
 3313:         } else {
 3314:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3315:             foreach (@responses) {
 3316:                 my ($key,$value) = split/=/,$_;
 3317:                 $$replyref{$key} = $value;
 3318:                 if ($value > 0) {
 3319:                     foreach (@{$$affiliatesref{$key}}) {
 3320:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3321:                         my $destname = $pathname.'/'.$filename;
 3322:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3323:                         if ($xml_classlist =~ /^error/) {
 3324:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3325:                         } else {
 3326:                             if ( open(FILE,">$destname") ) {
 3327:                                 print FILE &unescape($xml_classlist);
 3328:                                 close(FILE);
 3329:                             } else {
 3330:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3331:                             }
 3332:                         }
 3333:                     }
 3334:                 }
 3335:             }
 3336:         }
 3337:         return 'ok';
 3338:     }
 3339:     return 'error';
 3340: }
 3341: 
 3342: sub get_query_reply {
 3343:     my $queryid=shift;
 3344:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3345:     my $reply='';
 3346:     for (1..100) {
 3347: 	sleep 2;
 3348:         if (-e $replyfile.'.end') {
 3349: 	    if (open(my $fh,$replyfile)) {
 3350:                $reply.=<$fh>;
 3351:                close($fh);
 3352: 	   } else { return 'error: reply_file_error'; }
 3353:            return &unescape($reply);
 3354: 	}
 3355:     }
 3356:     return 'timeout:'.$queryid;
 3357: }
 3358: 
 3359: sub courselog_query {
 3360: #
 3361: # possible filters:
 3362: # url: url or symb
 3363: # username
 3364: # domain
 3365: # action: view, submit, grade
 3366: # start: timestamp
 3367: # end: timestamp
 3368: #
 3369:     my (%filters)=@_;
 3370:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 3371:     if ($filters{'url'}) {
 3372: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3373:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3374:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3375:     }
 3376:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 3377:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 3378:     return &log_query($cname,$cdom,'courselog',%filters);
 3379: }
 3380: 
 3381: sub userlog_query {
 3382:     my ($uname,$udom,%filters)=@_;
 3383:     return &log_query($uname,$udom,'userlog',%filters);
 3384: }
 3385: 
 3386: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3387: 
 3388: sub auto_run {
 3389:     my ($cnum,$cdom) = @_;
 3390:     my $homeserver = &homeserver($cnum,$cdom);
 3391:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3392:     return $response;
 3393: }
 3394:                                                                                    
 3395: sub auto_get_sections {
 3396:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3397:     my $homeserver = &homeserver($cnum,$cdom);
 3398:     my @secs = ();
 3399:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3400:     unless ($response eq 'refused') {
 3401:         @secs = split/:/,$response;
 3402:     }
 3403:     return @secs;
 3404: }
 3405:                                                                                    
 3406: sub auto_new_course {
 3407:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3408:     my $homeserver = &homeserver($cnum,$cdom);
 3409:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3410:     return $response;
 3411: }
 3412:                                                                                    
 3413: sub auto_validate_courseID {
 3414:     my ($cnum,$cdom,$inst_course_id) = @_;
 3415:     my $homeserver = &homeserver($cnum,$cdom);
 3416:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3417:     return $response;
 3418: }
 3419:                                                                                    
 3420: sub auto_create_password {
 3421:     my ($cnum,$cdom,$authparam) = @_;
 3422:     my $homeserver = &homeserver($cnum,$cdom); 
 3423:     my $create_passwd = 0;
 3424:     my $authchk = '';
 3425:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3426:     if ($response eq 'refused') {
 3427:         $authchk = 'refused';
 3428:     } else {
 3429:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3430:     }
 3431:     return ($authparam,$create_passwd,$authchk);
 3432: }
 3433: 
 3434: sub auto_instcode_format {
 3435:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3436:     my $courses = '';
 3437:     my $homeserver;
 3438:     if ($caller eq 'global') {
 3439:         foreach my $tryserver (keys %libserv) {
 3440:             if ($hostdom{$tryserver} eq $codedom) {
 3441:                 $homeserver = $tryserver;
 3442:                 last;
 3443:             }
 3444:         }
 3445:         if (($ENV{'user.name'}) && ($ENV{'user.domain'} eq $codedom)) {
 3446:             $homeserver = &homeserver($ENV{'user.name'},$codedom);
 3447:         }
 3448:     } else {
 3449:         $homeserver = &homeserver($caller,$codedom);
 3450:     }
 3451:     foreach (keys %{$instcodes}) {
 3452:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3453:     }
 3454:     chop($courses);
 3455:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3456:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3457:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3458:         %{$codes} = &str2hash($codes_str);
 3459:         @{$codetitles} = &str2array($codetitles_str);
 3460:         %{$cat_titles} = &str2hash($cat_titles_str);
 3461:         %{$cat_order} = &str2hash($cat_order_str);
 3462:         return 'ok';
 3463:     }
 3464:     return $response;
 3465: }
 3466: 
 3467: # ------------------------------------------------------------------ Plain Text
 3468: 
 3469: sub plaintext {
 3470:     my $short=shift;
 3471:     return &mt($prp{$short});
 3472: }
 3473: 
 3474: # ----------------------------------------------------------------- Assign Role
 3475: 
 3476: sub assignrole {
 3477:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 3478:     my $mrole;
 3479:     if ($role =~ /^cr\//) {
 3480:         my $cwosec=$url;
 3481:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 3482: 	unless (&allowed('ccr',$cwosec)) {
 3483:            &logthis('Refused custom assignrole: '.
 3484:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 3485: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 3486:            return 'refused'; 
 3487:         }
 3488:         $mrole='cr';
 3489:     } else {
 3490:         my $cwosec=$url;
 3491:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 3492:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 3493:            &logthis('Refused assignrole: '.
 3494:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 3495: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 3496:            return 'refused'; 
 3497:         }
 3498:         $mrole=$role;
 3499:     }
 3500:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 3501:                 "$udom:$uname:$url".'_'."$mrole=$role";
 3502:     if ($end) { $command.='_'.$end; }
 3503:     if ($start) {
 3504: 	if ($end) { 
 3505:            $command.='_'.$start; 
 3506:         } else {
 3507:            $command.='_0_'.$start;
 3508:         }
 3509:     }
 3510: # actually delete
 3511:     if ($deleteflag) {
 3512: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 3513: # modify command to delete the role
 3514:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
 3515:                 "$udom:$uname:$url".'_'."$mrole";
 3516: 	   &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 3517: # set start and finish to negative values for userrolelog
 3518:            $start=-1;
 3519:            $end=-1;
 3520:         }
 3521:     }
 3522: # send command
 3523:     my $answer=&reply($command,&homeserver($uname,$udom));
 3524: # log new user role if status is ok
 3525:     if ($answer eq 'ok') {
 3526: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
 3527:     }
 3528:     return $answer;
 3529: }
 3530: 
 3531: # -------------------------------------------------- Modify user authentication
 3532: # Overrides without validation
 3533: 
 3534: sub modifyuserauth {
 3535:     my ($udom,$uname,$umode,$upass)=@_;
 3536:     my $uhome=&homeserver($uname,$udom);
 3537:     unless (&allowed('mau',$udom)) { return 'refused'; }
 3538:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 3539:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 3540:              ' in domain '.$ENV{'request.role.domain'});  
 3541:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 3542: 		     &escape($upass),$uhome);
 3543:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 3544:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 3545:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 3546:     &log($udom,,$uname,$uhome,
 3547:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 3548:                                      $ENV{'user.name'}.', '.$umode.
 3549:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 3550:     unless ($reply eq 'ok') {
 3551:         &logthis('Authentication mode error: '.$reply);
 3552: 	return 'error: '.$reply;
 3553:     }   
 3554:     return 'ok';
 3555: }
 3556: 
 3557: # --------------------------------------------------------------- Modify a user
 3558: 
 3559: sub modifyuser {
 3560:     my ($udom,    $uname, $uid,
 3561:         $umode,   $upass, $first,
 3562:         $middle,  $last,  $gene,
 3563:         $forceid, $desiredhome, $email)=@_;
 3564:     $udom=~s/\W//g;
 3565:     $uname=~s/\W//g;
 3566:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 3567:              $umode.', '.$first.', '.$middle.', '.
 3568: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 3569:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 3570:                                      ' desiredhome not specified'). 
 3571:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 3572:              ' in domain '.$ENV{'request.role.domain'});
 3573:     my $uhome=&homeserver($uname,$udom,'true');
 3574: # ----------------------------------------------------------------- Create User
 3575:     if (($uhome eq 'no_host') && 
 3576: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 3577:         my $unhome='';
 3578:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 3579:             $unhome = $desiredhome;
 3580: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 3581: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 3582:         } else { # load balancing routine for determining $unhome
 3583:             my $tryserver;
 3584:             my $loadm=10000000;
 3585:             foreach $tryserver (keys %libserv) {
 3586: 	       if ($hostdom{$tryserver} eq $udom) {
 3587:                   my $answer=reply('load',$tryserver);
 3588:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 3589: 		      $loadm=$answer;
 3590:                       $unhome=$tryserver;
 3591:                   }
 3592: 	       }
 3593: 	    }
 3594:         }
 3595:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 3596: 	    return 'error: unable to find a home server for '.$uname.
 3597:                    ' in domain '.$udom;
 3598:         }
 3599:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 3600:                          &escape($upass),$unhome);
 3601: 	unless ($reply eq 'ok') {
 3602:             return 'error: '.$reply;
 3603:         }   
 3604:         $uhome=&homeserver($uname,$udom,'true');
 3605:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 3606: 	    return 'error: unable verify users home machine.';
 3607:         }
 3608:     }   # End of creation of new user
 3609: # ---------------------------------------------------------------------- Add ID
 3610:     if ($uid) {
 3611:        $uid=~tr/A-Z/a-z/;
 3612:        my %uidhash=&idrget($udom,$uname);
 3613:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 3614:          && (!$forceid)) {
 3615: 	  unless ($uid eq $uidhash{$uname}) {
 3616: 	      return 'error: user id "'.$uid.'" does not match '.
 3617:                   'current user id "'.$uidhash{$uname}.'".';
 3618:           }
 3619:        } else {
 3620: 	  &idput($udom,($uname => $uid));
 3621:        }
 3622:     }
 3623: # -------------------------------------------------------------- Add names, etc
 3624:     my @tmp=&get('environment',
 3625: 		   ['firstname','middlename','lastname','generation'],
 3626: 		   $udom,$uname);
 3627:     my %names;
 3628:     if ($tmp[0] =~ m/^error:.*/) { 
 3629:         %names=(); 
 3630:     } else {
 3631:         %names = @tmp;
 3632:     }
 3633: #
 3634: # Make sure to not trash student environment if instructor does not bother
 3635: # to supply name and email information
 3636: #
 3637:     if ($first)  { $names{'firstname'}  = $first; }
 3638:     if (defined($middle)) { $names{'middlename'} = $middle; }
 3639:     if ($last)   { $names{'lastname'}   = $last; }
 3640:     if (defined($gene))   { $names{'generation'} = $gene; }
 3641:     if ($email)  { $names{'notification'} = $email;
 3642:                    $names{'critnotification'} = $email; }
 3643: 
 3644:     my $reply = &put('environment', \%names, $udom,$uname);
 3645:     if ($reply ne 'ok') { return 'error: '.$reply; }
 3646:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 3647:              $umode.', '.$first.', '.$middle.', '.
 3648: 	     $last.', '.$gene.' by '.
 3649:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 3650:     return 'ok';
 3651: }
 3652: 
 3653: # -------------------------------------------------------------- Modify student
 3654: 
 3655: sub modifystudent {
 3656:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 3657:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 3658:     if (!$cid) {
 3659: 	unless ($cid=$ENV{'request.course.id'}) {
 3660: 	    return 'not_in_class';
 3661: 	}
 3662:     }
 3663: # --------------------------------------------------------------- Make the user
 3664:     my $reply=&modifyuser
 3665: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 3666:          $desiredhome,$email);
 3667:     unless ($reply eq 'ok') { return $reply; }
 3668:     # This will cause &modify_student_enrollment to get the uid from the
 3669:     # students environment
 3670:     $uid = undef if (!$forceid);
 3671:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 3672: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 3673:     return $reply;
 3674: }
 3675: 
 3676: sub modify_student_enrollment {
 3677:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 3678:     my ($cdom,$cnum,$chome);
 3679:     if (!$cid) {
 3680: 	unless ($cid=$ENV{'request.course.id'}) {
 3681: 	    return 'not_in_class';
 3682: 	}
 3683: 	$cdom=$ENV{'course.'.$cid.'.domain'};
 3684: 	$cnum=$ENV{'course.'.$cid.'.num'};
 3685:     } else {
 3686: 	($cdom,$cnum)=split(/_/,$cid);
 3687:     }
 3688:     $chome=$ENV{'course.'.$cid.'.home'};
 3689:     if (!$chome) {
 3690: 	$chome=&homeserver($cnum,$cdom);
 3691:     }
 3692:     if (!$chome) { return 'unknown_course'; }
 3693:     # Make sure the user exists
 3694:     my $uhome=&homeserver($uname,$udom);
 3695:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 3696: 	return 'error: no such user';
 3697:     }
 3698:     # Get student data if we were not given enough information
 3699:     if (!defined($first)  || $first  eq '' || 
 3700:         !defined($last)   || $last   eq '' || 
 3701:         !defined($uid)    || $uid    eq '' || 
 3702:         !defined($middle) || $middle eq '' || 
 3703:         !defined($gene)   || $gene   eq '') {
 3704:         # They did not supply us with enough data to enroll the student, so
 3705:         # we need to pick up more information.
 3706:         my %tmp = &get('environment',
 3707:                        ['firstname','middlename','lastname', 'generation','id']
 3708:                        ,$udom,$uname);
 3709: 
 3710:         #foreach (keys(%tmp)) {
 3711:         #    &logthis("key $_ = ".$tmp{$_});
 3712:         #}
 3713:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 3714:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 3715:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 3716:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 3717:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 3718:     }
 3719:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 3720:     my $reply=cput('classlist',
 3721: 		   {"$uname:$udom" => 
 3722: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 3723: 		   $cdom,$cnum);
 3724:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 3725: 	return 'error: '.$reply;
 3726:     }
 3727:     # Add student role to user
 3728:     my $uurl='/'.$cid;
 3729:     $uurl=~s/\_/\//g;
 3730:     if ($usec) {
 3731: 	$uurl.='/'.$usec;
 3732:     }
 3733:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 3734: }
 3735: 
 3736: sub format_name {
 3737:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 3738:     my $name;
 3739:     if ($first ne 'lastname') {
 3740: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 3741:     } else {
 3742: 	if ($lastname=~/\S/) {
 3743: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 3744: 	    $name=~s/\s+,/,/;
 3745: 	} else {
 3746: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 3747: 	}
 3748:     }
 3749:     $name=~s/^\s+//;
 3750:     $name=~s/\s+$//;
 3751:     $name=~s/\s+/ /g;
 3752:     return $name;
 3753: }
 3754: 
 3755: # ------------------------------------------------- Write to course preferences
 3756: 
 3757: sub writecoursepref {
 3758:     my ($courseid,%prefs)=@_;
 3759:     $courseid=~s/^\///;
 3760:     $courseid=~s/\_/\//g;
 3761:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3762:     my $chome=homeserver($cnum,$cdomain);
 3763:     if (($chome eq '') || ($chome eq 'no_host')) { 
 3764: 	return 'error: no such course';
 3765:     }
 3766:     my $cstring='';
 3767:     foreach (keys %prefs) {
 3768: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 3769:     }
 3770:     $cstring=~s/\&$//;
 3771:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 3772: }
 3773: 
 3774: # ---------------------------------------------------------- Make/modify course
 3775: 
 3776: sub createcourse {
 3777:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
 3778:     $url=&declutter($url);
 3779:     my $cid='';
 3780:     unless (&allowed('ccc',$udom)) {
 3781:         return 'refused';
 3782:     }
 3783: # ------------------------------------------------------------------- Create ID
 3784:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 3785:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 3786: # ----------------------------------------------- Make sure that does not exist
 3787:    my $uhome=&homeserver($uname,$udom,'true');
 3788:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 3789:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 3790:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 3791:        $uhome=&homeserver($uname,$udom,'true');       
 3792:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 3793:            return 'error: unable to generate unique course-ID';
 3794:        } 
 3795:    }
 3796: # ------------------------------------------------ Check supplied server name
 3797:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 3798:     if (! exists($libserv{$course_server})) {
 3799:         return 'error:bad server name '.$course_server;
 3800:     }
 3801: # ------------------------------------------------------------- Make the course
 3802:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 3803:                       $course_server);
 3804:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 3805:     $uhome=&homeserver($uname,$udom,'true');
 3806:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 3807: 	return 'error: no such course';
 3808:     }
 3809: # ----------------------------------------------------------------- Course made
 3810: # log existence
 3811:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 3812:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
 3813:     &flushcourselogs();
 3814: # set toplevel url
 3815:     my $topurl=$url;
 3816:     unless ($nonstandard) {
 3817: # ------------------------------------------ For standard courses, make top url
 3818:         my $mapurl=&clutter($url);
 3819:         if ($mapurl eq '/res/') { $mapurl=''; }
 3820:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 3821: <map>
 3822: <resource id="1" type="start"></resource>
 3823: <resource id="2" src="$mapurl"></resource>
 3824: <resource id="3" type="finish"></resource>
 3825: <link index="1" from="1" to="2"></link>
 3826: <link index="2" from="2" to="3"></link>
 3827: </map>
 3828: ENDINITMAP
 3829:         $topurl=&declutter(
 3830:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 3831:                           );
 3832:     }
 3833: # ----------------------------------------------------------- Write preferences
 3834:     &writecoursepref($udom.'_'.$uname,
 3835:                      ('description' => $description,
 3836:                       'url'         => $topurl));
 3837:     return '/'.$udom.'/'.$uname;
 3838: }
 3839: 
 3840: # ---------------------------------------------------------- Assign Custom Role
 3841: 
 3842: sub assigncustomrole {
 3843:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 3844:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 3845:                        $end,$start,$deleteflag);
 3846: }
 3847: 
 3848: # ----------------------------------------------------------------- Revoke Role
 3849: 
 3850: sub revokerole {
 3851:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 3852:     my $now=time;
 3853:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 3854: }
 3855: 
 3856: # ---------------------------------------------------------- Revoke Custom Role
 3857: 
 3858: sub revokecustomrole {
 3859:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 3860:     my $now=time;
 3861:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 3862:            $deleteflag);
 3863: }
 3864: 
 3865: # ------------------------------------------------------------ Disk usage
 3866: sub diskusage {
 3867:     my ($udom,$uname,$directoryRoot)=@_;
 3868:     $directoryRoot =~ s/\/$//;
 3869:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 3870:     return $listing;
 3871: }
 3872: 
 3873: sub is_locked {
 3874:     my ($file_name, $domain, $user) = @_;
 3875:     my @check;
 3876:     my $is_locked;
 3877:     push @check, $file_name;
 3878:     my %locked = &Apache::lonnet::get('file_permissions',\@check,
 3879:                                         $ENV{'user.domain'},$ENV{'user.name'});
 3880:     if (ref($locked{$file_name}) eq 'ARRAY') {
 3881:         $is_locked = 'true';
 3882:     } else {
 3883:         $is_locked = 'false';
 3884:     }
 3885: }
 3886: 
 3887: # ------------------------------------------------------------- Mark as Read Only
 3888: 
 3889: sub mark_as_readonly {
 3890:     my ($domain,$user,$files,$what) = @_;
 3891:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3892:     foreach my $file (@{$files}) {
 3893:         push(@{$current_permissions{$file}},$what);
 3894:     }
 3895:     &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user);
 3896:     return;
 3897: }
 3898: 
 3899: # ------------------------------------------------------------Save Selected Files
 3900: 
 3901: sub save_selected_files {
 3902:     my ($user, $path, @files) = @_;
 3903:     my $filename = $user."savedfiles";
 3904:     my @other_files = &files_not_in_path($user, $path);
 3905:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3906:     foreach my $file (@files) {
 3907:         print (OUT $ENV{'form.currentpath'}.$file."\n");
 3908:     }
 3909:     foreach my $file (@other_files) {
 3910:         print (OUT $file."\n");
 3911:     }
 3912:     close (OUT);
 3913:     return 'ok';
 3914: }
 3915: 
 3916: sub clear_selected_files {
 3917:     my ($user) = @_;
 3918:     my $filename = $user."savedfiles";
 3919:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3920:     print (OUT undef);
 3921:     close (OUT);
 3922:     return ("ok");    
 3923: }
 3924: 
 3925: sub files_in_path {
 3926:     my ($user, $path) = @_;
 3927:     my $filename = $user."savedfiles";
 3928:     my %return_files;
 3929:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3930:     while (my $line_in = <IN>) {
 3931:         chomp ($line_in);
 3932:         my @paths_and_file = split (m!/!, $line_in);
 3933:         my $file_part = pop (@paths_and_file);
 3934:         my $path_part = join ('/', @paths_and_file);
 3935:         $path_part.='/';
 3936:         my $path_and_file = $path_part.$file_part;
 3937:         if ($path_part eq $path) {
 3938:             $return_files{$file_part}= 'selected';
 3939:         }
 3940:     }
 3941:     close (IN);
 3942:     return (\%return_files);
 3943: }
 3944: 
 3945: # called in portfolio select mode, to show files selected NOT in current directory
 3946: sub files_not_in_path {
 3947:     my ($user, $path) = @_;
 3948:     my $filename = $user."savedfiles";
 3949:     my @return_files;
 3950:     my $path_part;
 3951:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 3952:     while (<IN>) {
 3953:         #ok, I know it's clunky, but I want it to work
 3954:         my @paths_and_file = split m!/!, $_;
 3955:         my $file_part = pop (@paths_and_file);
 3956:         chomp ($file_part);
 3957:         my $path_part = join ('/', @paths_and_file);
 3958:         $path_part .= '/';
 3959:         my $path_and_file = $path_part.$file_part;
 3960:         if ($path_part ne $path) {
 3961:             push (@return_files, ($path_and_file));
 3962:         }
 3963:     }
 3964:     close (OUT);
 3965:     return (@return_files);
 3966: }
 3967: 
 3968: #--------------------------------------------------------------Get Marked as Read Only
 3969: 
 3970: sub get_marked_as_readonly {
 3971:     my ($domain,$user,$what) = @_;
 3972:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3973:     my @readonly_files;
 3974:     while (my ($file_name,$value) = each(%current_permissions)) {
 3975:         if (ref($value) eq "ARRAY"){
 3976:             foreach my $stored_what (@{$value}) {
 3977:                 if ($stored_what eq $what) {
 3978:                     push(@readonly_files, $file_name);
 3979:                 } elsif (!defined($what)) {
 3980:                     push(@readonly_files, $file_name);
 3981:                 }
 3982:             }
 3983:         } 
 3984:     }
 3985:     return @readonly_files;
 3986: }
 3987: #-----------------------------------------------------------Get Marked as Read Only Hash
 3988: 
 3989: sub get_marked_as_readonly_hash {
 3990:     my ($domain,$user,$what) = @_;
 3991:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 3992:     my %readonly_files;
 3993:     while (my ($file_name,$value) = each(%current_permissions)) {
 3994:         if (ref($value) eq "ARRAY"){
 3995:             foreach my $stored_what (@{$value}) {
 3996:                 if ($stored_what eq $what) {
 3997:                     $readonly_files{$file_name} = 'locked';
 3998:                 } elsif (!defined($what)) {
 3999:                     $readonly_files{$file_name} = 'locked';
 4000:                 }
 4001:             }
 4002:         } 
 4003:     }
 4004:     return %readonly_files;
 4005: }
 4006: # ------------------------------------------------------------ Unmark as Read Only
 4007: 
 4008: sub unmark_as_readonly {
 4009:     # unmarks all files locked by $what 
 4010:     # for portfolio submissions, $what contains $crsid and $symb
 4011:     my ($domain,$user,$what) = @_;
 4012:     my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user);
 4013:     my @readonly_files = &Apache::lonnet::get_marked_as_readonly($domain,$user,$what);
 4014:     foreach my $file(@readonly_files){
 4015:         my $current_locks = $current_permissions{$file};
 4016:         my @new_locks;
 4017:         my @del_keys;
 4018:         if (ref($current_locks) eq "ARRAY"){
 4019:             foreach my $locker (@{$current_locks}) {
 4020:                 unless ($locker eq $what) {
 4021:                     push(@new_locks, $what);
 4022:                 }
 4023:             }
 4024:             if (@new_locks > 0) {
 4025:                 $current_permissions{$file} = \@new_locks;
 4026:             } else {
 4027:                 push(@del_keys, $file);
 4028:                 &Apache::lonnet::del('file_permissions',\@del_keys, $domain, $user);
 4029:                 delete $current_permissions{$file};
 4030:             }
 4031:         }
 4032:     }
 4033:     &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user);
 4034:     return;
 4035: }
 4036: 
 4037: # ------------------------------------------------------------ Directory lister
 4038: 
 4039: sub dirlist {
 4040:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 4041: 
 4042:     $uri=~s/^\///;
 4043:     $uri=~s/\/$//;
 4044:     my ($udom, $uname);
 4045:     (undef,$udom,$uname)=split(/\//,$uri);
 4046:     if(defined($userdomain)) {
 4047:         $udom = $userdomain;
 4048:     }
 4049:     if(defined($username)) {
 4050:         $uname = $username;
 4051:     }
 4052: 
 4053:     my $dirRoot = $perlvar{'lonDocRoot'};
 4054:     if(defined($alternateDirectoryRoot)) {
 4055:         $dirRoot = $alternateDirectoryRoot;
 4056:         $dirRoot =~ s/\/$//;
 4057:     }
 4058: 
 4059:     if($udom) {
 4060:         if($uname) {
 4061:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4062:                               homeserver($uname,$udom));
 4063:             return split(/:/,$listing);
 4064:         } elsif(!defined($alternateDirectoryRoot)) {
 4065:             my $tryserver;
 4066:             my %allusers=();
 4067:             foreach $tryserver (keys %libserv) {
 4068:                 if($hostdom{$tryserver} eq $udom) {
 4069:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 4070:                                       $udom, $tryserver);
 4071:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 4072:                         && ($listing ne 'con_lost')) {
 4073:                         foreach (split(/:/,$listing)) {
 4074:                             my ($entry,@stat)=split(/&/,$_);
 4075:                             $allusers{$entry}=1;
 4076:                         }
 4077:                     }
 4078:                 }
 4079:             }
 4080:             my $alluserstr='';
 4081:             foreach (sort keys %allusers) {
 4082:                 $alluserstr.=$_.'&user:';
 4083:             }
 4084:             $alluserstr=~s/:$//;
 4085:             return split(/:/,$alluserstr);
 4086:         } else {
 4087:             my @emptyResults = ();
 4088:             push(@emptyResults, 'missing user name');
 4089:             return split(':',@emptyResults);
 4090:         }
 4091:     } elsif(!defined($alternateDirectoryRoot)) {
 4092:         my $tryserver;
 4093:         my %alldom=();
 4094:         foreach $tryserver (keys %libserv) {
 4095:             $alldom{$hostdom{$tryserver}}=1;
 4096:         }
 4097:         my $alldomstr='';
 4098:         foreach (sort keys %alldom) {
 4099:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 4100:         }
 4101:         $alldomstr=~s/:$//;
 4102:         return split(/:/,$alldomstr);       
 4103:     } else {
 4104:         my @emptyResults = ();
 4105:         push(@emptyResults, 'missing domain');
 4106:         return split(':',@emptyResults);
 4107:     }
 4108: }
 4109: 
 4110: # --------------------------------------------- GetFileTimestamp
 4111: # This function utilizes dirlist and returns the date stamp for
 4112: # when it was last modified.  It will also return an error of -1
 4113: # if an error occurs
 4114: 
 4115: ##
 4116: ## FIXME: This subroutine assumes its caller knows something about the
 4117: ## directory structure of the home server for the student ($root).
 4118: ## Not a good assumption to make.  Since this is for looking up files
 4119: ## in user directories, the full path should be constructed by lond, not
 4120: ## whatever machine we request data from.
 4121: ##
 4122: sub GetFileTimestamp {
 4123:     my ($studentDomain,$studentName,$filename,$root)=@_;
 4124:     $studentDomain=~s/\W//g;
 4125:     $studentName=~s/\W//g;
 4126:     my $subdir=$studentName.'__';
 4127:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4128:     my $proname="$studentDomain/$subdir/$studentName";
 4129:     $proname .= '/'.$filename;
 4130:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 4131:                                               $studentName, $root);
 4132:     my @stats = split('&', $fileStat);
 4133:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4134:         # @stats contains first the filename, then the stat output
 4135:         return $stats[10]; # so this is 10 instead of 9.
 4136:     } else {
 4137:         return -1;
 4138:     }
 4139: }
 4140: 
 4141: # -------------------------------------------------------- Value of a Condition
 4142: 
 4143: sub directcondval {
 4144:     my $number=shift;
 4145:     if (!defined($ENV{'user.state.'.$ENV{'request.course.id'}})) {
 4146: 	&Apache::lonuserstate::evalstate();
 4147:     }
 4148:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 4149:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 4150:     } else {
 4151:        return 2;
 4152:     }
 4153: }
 4154: 
 4155: sub condval {
 4156:     my $condidx=shift;
 4157:     my $result=0;
 4158:     my $allpathcond='';
 4159:     foreach (split(/\|/,$condidx)) {
 4160:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 4161: 	   $allpathcond.=
 4162:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 4163:        }
 4164:     }
 4165:     $allpathcond=~s/\|$//;
 4166:     if ($ENV{'request.course.id'}) {
 4167:        if ($allpathcond) {
 4168:           my $operand='|';
 4169: 	  my @stack;
 4170:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 4171:               if ($_ eq '(') {
 4172:                  push @stack,($operand,$result)
 4173:               } elsif ($_ eq ')') {
 4174:                   my $before=pop @stack;
 4175: 		  if (pop @stack eq '&') {
 4176: 		      $result=$result>$before?$before:$result;
 4177:                   } else {
 4178:                       $result=$result>$before?$result:$before;
 4179:                   }
 4180:               } elsif (($_ eq '&') || ($_ eq '|')) {
 4181:                   $operand=$_;
 4182:               } else {
 4183:                   my $new=directcondval($_);
 4184:                   if ($operand eq '&') {
 4185:                      $result=$result>$new?$new:$result;
 4186:                   } else {
 4187:                      $result=$result>$new?$result:$new;
 4188:                   }
 4189:               }
 4190:           }
 4191:        }
 4192:     }
 4193:     return $result;
 4194: }
 4195: 
 4196: # ---------------------------------------------------- Devalidate courseresdata
 4197: 
 4198: sub devalidatecourseresdata {
 4199:     my ($coursenum,$coursedomain)=@_;
 4200:     my $hashid=$coursenum.':'.$coursedomain;
 4201:     &devalidate_cache(\%courseresdatacache,$hashid,'courseres');
 4202: }
 4203: 
 4204: # --------------------------------------------------- Course Resourcedata Query
 4205: 
 4206: sub courseresdata {
 4207:     my ($coursenum,$coursedomain,@which)=@_;
 4208:     my $coursehom=&homeserver($coursenum,$coursedomain);
 4209:     my $hashid=$coursenum.':'.$coursedomain;
 4210:     my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres');
 4211:     unless (defined($cached)) {
 4212: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 4213: 	$result=\%dumpreply;
 4214: 	my ($tmp) = keys(%dumpreply);
 4215: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4216: 	    &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
 4217: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4218: 	    return $tmp;
 4219: 	} elsif ($tmp =~ /^(error)/) {
 4220: 	    $result=undef;
 4221: 	    &do_cache(\%courseresdatacache,$hashid,$result,'courseres');
 4222: 	}
 4223:     }
 4224:     foreach my $item (@which) {
 4225: 	if (defined($result->{$item})) {
 4226: 	    return $result->{$item};
 4227: 	}
 4228:     }
 4229:     return undef;
 4230: }
 4231: 
 4232: #
 4233: # EXT resource caching routines
 4234: #
 4235: 
 4236: sub clear_EXT_cache_status {
 4237:     &delenv('cache.EXT.');
 4238: }
 4239: 
 4240: sub EXT_cache_status {
 4241:     my ($target_domain,$target_user) = @_;
 4242:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4243:     if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) {
 4244:         # We know already the user has no data
 4245:         return 1;
 4246:     } else {
 4247:         return 0;
 4248:     }
 4249: }
 4250: 
 4251: sub EXT_cache_set {
 4252:     my ($target_domain,$target_user) = @_;
 4253:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4254:     &appenv($cachename => time);
 4255: }
 4256: 
 4257: # --------------------------------------------------------- Value of a Variable
 4258: sub EXT {
 4259:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 4260: 
 4261:     unless ($varname) { return ''; }
 4262:     #get real user name/domain, courseid and symb
 4263:     my $courseid;
 4264:     my $publicuser;
 4265:     if ($symbparm) {
 4266: 	$symbparm=&get_symb_from_alias($symbparm);
 4267:     }
 4268:     if (!($uname && $udom)) {
 4269:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 4270: 	  &Apache::lonxml::whichuser($symbparm);
 4271:       if (!$symbparm) {	$symbparm=$cursymb; }
 4272:     } else {
 4273: 	$courseid=$ENV{'request.course.id'};
 4274:     }
 4275:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 4276:     my $rest;
 4277:     if (defined($therest[0])) {
 4278:        $rest=join('.',@therest);
 4279:     } else {
 4280:        $rest='';
 4281:     }
 4282: 
 4283:     my $qualifierrest=$qualifier;
 4284:     if ($rest) { $qualifierrest.='.'.$rest; }
 4285:     my $spacequalifierrest=$space;
 4286:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 4287:     if ($realm eq 'user') {
 4288: # --------------------------------------------------------------- user.resource
 4289: 	if ($space eq 'resource') {
 4290: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
 4291: 		return $Apache::lonhomework::history{$qualifierrest};
 4292: 	    } else {
 4293: 		my %restored;
 4294: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
 4295: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 4296: 		} else {
 4297: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 4298: 		}
 4299: 		return $restored{$qualifierrest};
 4300: 	    }
 4301: # ----------------------------------------------------------------- user.access
 4302:         } elsif ($space eq 'access') {
 4303: 	    # FIXME - not supporting calls for a specific user
 4304:             return &allowed($qualifier,$rest);
 4305: # ------------------------------------------ user.preferences, user.environment
 4306:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 4307: 	    if (($uname eq $ENV{'user.name'}) &&
 4308: 		($udom eq $ENV{'user.domain'})) {
 4309: 		return $ENV{join('.',('environment',$qualifierrest))};
 4310: 	    } else {
 4311: 		my %returnhash;
 4312: 		if (!$publicuser) {
 4313: 		    %returnhash=&userenvironment($udom,$uname,
 4314: 						 $qualifierrest);
 4315: 		}
 4316: 		return $returnhash{$qualifierrest};
 4317: 	    }
 4318: # ----------------------------------------------------------------- user.course
 4319:         } elsif ($space eq 'course') {
 4320: 	    # FIXME - not supporting calls for a specific user
 4321:             return $ENV{join('.',('request.course',$qualifier))};
 4322: # ------------------------------------------------------------------- user.role
 4323:         } elsif ($space eq 'role') {
 4324: 	    # FIXME - not supporting calls for a specific user
 4325:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 4326:             if ($qualifier eq 'value') {
 4327: 		return $role;
 4328:             } elsif ($qualifier eq 'extent') {
 4329:                 return $where;
 4330:             }
 4331: # ----------------------------------------------------------------- user.domain
 4332:         } elsif ($space eq 'domain') {
 4333:             return $udom;
 4334: # ------------------------------------------------------------------- user.name
 4335:         } elsif ($space eq 'name') {
 4336:             return $uname;
 4337: # ---------------------------------------------------- Any other user namespace
 4338:         } else {
 4339: 	    my %reply;
 4340: 	    if (!$publicuser) {
 4341: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 4342: 	    }
 4343: 	    return $reply{$qualifierrest};
 4344:         }
 4345:     } elsif ($realm eq 'query') {
 4346: # ---------------------------------------------- pull stuff out of query string
 4347:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4348: 						[$spacequalifierrest]);
 4349: 	return $ENV{'form.'.$spacequalifierrest}; 
 4350:    } elsif ($realm eq 'request') {
 4351: # ------------------------------------------------------------- request.browser
 4352:         if ($space eq 'browser') {
 4353: 	    if ($qualifier eq 'textremote') {
 4354: 		if (&mt('textual_remote_display') eq 'on') {
 4355: 		    return 1;
 4356: 		} else {
 4357: 		    return 0;
 4358: 		}
 4359: 	    } else {
 4360: 		return $ENV{'browser.'.$qualifier};
 4361: 	    }
 4362: # ------------------------------------------------------------ request.filename
 4363:         } else {
 4364:             return $ENV{'request.'.$spacequalifierrest};
 4365:         }
 4366:     } elsif ($realm eq 'course') {
 4367: # ---------------------------------------------------------- course.description
 4368:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 4369:     } elsif ($realm eq 'resource') {
 4370: 
 4371: 	my $section;
 4372: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
 4373: 	    if (!$symbparm) { $symbparm=&symbread(); }
 4374: 	}
 4375: 	if ($symbparm && defined($courseid) && 
 4376: 	    $courseid eq $ENV{'request.course.id'}) {
 4377: 
 4378: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 4379: 
 4380: # ----------------------------------------------------- Cascading lookup scheme
 4381: 	    my $symbp=$symbparm;
 4382: 	    my $mapp=(&decode_symb($symbp))[0];
 4383: 
 4384: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 4385: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 4386: 
 4387: 	    if (($ENV{'user.name'} eq $uname) &&
 4388: 		($ENV{'user.domain'} eq $udom)) {
 4389: 		$section=$ENV{'request.course.sec'};
 4390: 	    } else {
 4391: 		if (! defined($usection)) {
 4392: 		    $section=&getsection($udom,$uname,$courseid);
 4393: 		} else {
 4394: 		    $section = $usection;
 4395: 		}
 4396: 	    }
 4397: 
 4398: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 4399: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 4400: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 4401: 
 4402: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 4403: 	    my $courselevelr=$courseid.'.'.$symbparm;
 4404: 	    my $courselevelm=$courseid.'.'.$mapparm;
 4405: 
 4406: # ----------------------------------------------------------- first, check user
 4407: 	    #most student don\'t have any data set, check if there is some data
 4408: 	    if (! &EXT_cache_status($udom,$uname)) {
 4409: 		my $hashid="$udom:$uname";
 4410: 		my ($result,$cached)=&is_cached(\%userresdatacache,$hashid,
 4411: 						'userres');
 4412: 		if (!defined($cached)) {
 4413: 		    my %resourcedata=&dump('resourcedata',$udom,$uname);
 4414: 		    $result=\%resourcedata;
 4415: 		    &do_cache(\%userresdatacache,$hashid,$result,'userres');
 4416: 		}
 4417: 		my ($tmp)=keys(%$result);
 4418: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 4419: 		    if ($$result{$courselevelr}) {
 4420: 			return $$result{$courselevelr}; }
 4421: 		    if ($$result{$courselevelm}) {
 4422: 			return $$result{$courselevelm}; }
 4423: 		    if ($$result{$courselevel}) {
 4424: 			return $$result{$courselevel}; }
 4425: 		} else {
 4426: 		    #error 2 occurs when the .db doesn't exist
 4427: 		    if ($tmp!~/error: 2 /) {
 4428: 			&logthis("<font color=blue>WARNING:".
 4429: 				 " Trying to get resource data for ".
 4430: 				 $uname." at ".$udom.": ".
 4431: 				 $tmp."</font>");
 4432: 		    } elsif ($tmp=~/error: 2 /) {
 4433: 			&EXT_cache_set($udom,$uname);
 4434: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4435: 			return $tmp;
 4436: 		    }
 4437: 		}
 4438: 	    }
 4439: 
 4440: # -------------------------------------------------------- second, check course
 4441: 
 4442: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 4443: 					   $ENV{'course.'.$courseid.'.domain'},
 4444: 					   ($seclevelr,$seclevelm,$seclevel,
 4445: 					    $courselevelr,$courselevelm,
 4446: 					    $courselevel));
 4447: 	    if (defined($coursereply)) { return $coursereply; }
 4448: 
 4449: # ------------------------------------------------------ third, check map parms
 4450: 	    my %parmhash=();
 4451: 	    my $thisparm='';
 4452: 	    if (tie(%parmhash,'GDBM_File',
 4453: 		    $ENV{'request.course.fn'}.'_parms.db',
 4454: 		    &GDBM_READER(),0640)) {
 4455: 		$thisparm=$parmhash{$symbparm};
 4456: 		untie(%parmhash);
 4457: 	    }
 4458: 	    if ($thisparm) { return $thisparm; }
 4459: 	}
 4460: # --------------------------------------------- last, look in resource metadata
 4461: 
 4462: 	$spacequalifierrest=~s/\./\_/;
 4463: 	my $filename;
 4464: 	if (!$symbparm) { $symbparm=&symbread(); }
 4465: 	if ($symbparm) {
 4466: 	    $filename=(&decode_symb($symbparm))[2];
 4467: 	} else {
 4468: 	    $filename=$ENV{'request.filename'};
 4469: 	}
 4470: 	my $metadata=&metadata($filename,$spacequalifierrest);
 4471: 	if (defined($metadata)) { return $metadata; }
 4472: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 4473: 	if (defined($metadata)) { return $metadata; }
 4474: 
 4475: # ------------------------------------------------------------------ Cascade up
 4476: 	unless ($space eq '0') {
 4477: 	    my @parts=split(/_/,$space);
 4478: 	    my $id=pop(@parts);
 4479: 	    my $part=join('_',@parts);
 4480: 	    if ($part eq '') { $part='0'; }
 4481: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 4482: 				 $symbparm,$udom,$uname,$section,1);
 4483: 	    if (defined($partgeneral)) { return $partgeneral; }
 4484: 	}
 4485: 	if ($recurse) { return undef; }
 4486: 	my $pack_def=&packages_tab_default($filename,$varname);
 4487: 	if (defined($pack_def)) { return $pack_def; }
 4488: 
 4489: # ---------------------------------------------------- Any other user namespace
 4490:     } elsif ($realm eq 'environment') {
 4491: # ----------------------------------------------------------------- environment
 4492: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 4493: 	    return $ENV{'environment.'.$spacequalifierrest};
 4494: 	} else {
 4495: 	    my %returnhash=&userenvironment($udom,$uname,
 4496: 					    $spacequalifierrest);
 4497: 	    return $returnhash{$spacequalifierrest};
 4498: 	}
 4499:     } elsif ($realm eq 'system') {
 4500: # ----------------------------------------------------------------- system.time
 4501: 	if ($space eq 'time') {
 4502: 	    return time;
 4503:         }
 4504:     }
 4505:     return '';
 4506: }
 4507: 
 4508: sub packages_tab_default {
 4509:     my ($uri,$varname)=@_;
 4510:     my (undef,$part,$name)=split(/\./,$varname);
 4511:     my $packages=&metadata($uri,'packages');
 4512:     foreach my $package (split(/,/,$packages)) {
 4513: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 4514: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 4515: 	    return $packagetab{"$pack_type&$name&default"};
 4516: 	}
 4517: 	if ($pack_type eq 'part') { $pack_part='0'; }
 4518: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 4519: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 4520: 	}
 4521:     }
 4522:     return undef;
 4523: }
 4524: 
 4525: sub add_prefix_and_part {
 4526:     my ($prefix,$part)=@_;
 4527:     my $keyroot;
 4528:     if (defined($prefix) && $prefix !~ /^__/) {
 4529: 	# prefix that has a part already
 4530: 	$keyroot=$prefix;
 4531:     } elsif (defined($prefix)) {
 4532: 	# prefix that is missing a part
 4533: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 4534:     } else {
 4535: 	# no prefix at all
 4536: 	if (defined($part)) { $keyroot='_'.$part; }
 4537:     }
 4538:     return $keyroot;
 4539: }
 4540: 
 4541: # ---------------------------------------------------------------- Get metadata
 4542: 
 4543: my %metaentry;
 4544: sub metadata {
 4545:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 4546:     $uri=&declutter($uri);
 4547:     # if it is a non metadata possible uri return quickly
 4548:     if (($uri eq '') || 
 4549: 	(($uri =~ m|^/*adm/|) && 
 4550: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 4551:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 4552: 	($uri =~ m|home/[^/]+/public_html/|)) {
 4553: 	return undef;
 4554:     }
 4555:     my $filename=$uri;
 4556:     $uri=~s/\.meta$//;
 4557: #
 4558: # Is the metadata already cached?
 4559: # Look at timestamp of caching
 4560: # Everything is cached by the main uri, libraries are never directly cached
 4561: #
 4562:     if (!defined($liburi)) {
 4563: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 4564: 	if (defined($cached)) { return $result->{':'.$what}; }
 4565:     }
 4566:     {
 4567: #
 4568: # Is this a recursive call for a library?
 4569: #
 4570: #	if (! exists($metacache{$uri})) {
 4571: #	    $metacache{$uri}={};
 4572: #	}
 4573:         if ($liburi) {
 4574: 	    $liburi=&declutter($liburi);
 4575:             $filename=$liburi;
 4576:         } else {
 4577: 	    &devalidate_cache_new('meta',$uri);
 4578: 	    undef(%metaentry);
 4579: 	}
 4580:         my %metathesekeys=();
 4581:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 4582: 	my $metastring;
 4583: 	if ($uri !~ m|^uploaded/|) {
 4584: 	    my $file=&filelocation('',&clutter($filename));
 4585: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 4586: 	    $metastring=&getfile($file);
 4587: 	}
 4588:         my $parser=HTML::LCParser->new(\$metastring);
 4589:         my $token;
 4590:         undef %metathesekeys;
 4591:         while ($token=$parser->get_token) {
 4592: 	    if ($token->[0] eq 'S') {
 4593: 		if (defined($token->[2]->{'package'})) {
 4594: #
 4595: # This is a package - get package info
 4596: #
 4597: 		    my $package=$token->[2]->{'package'};
 4598: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 4599: 		    if (defined($token->[2]->{'id'})) { 
 4600: 			$keyroot.='_'.$token->[2]->{'id'}; 
 4601: 		    }
 4602: 		    if ($metaentry{':packages'}) {
 4603: 			$metaentry{':packages'}.=','.$package.$keyroot;
 4604: 		    } else {
 4605: 			$metaentry{':packages'}=$package.$keyroot;
 4606: 		    }
 4607: 		    foreach (keys %packagetab) {
 4608: 			my $part=$keyroot;
 4609: 			$part=~s/^\_//;
 4610: 			if ($_=~/^\Q$package\E\&/ || 
 4611: 			    $_=~/^\Q$package\E_0\&/) {
 4612: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 4613: 			    # ignore package.tab specified default values
 4614:                             # here &package_tab_default() will fetch those
 4615: 			    if ($subp eq 'default') { next; }
 4616: 			    my $value=$packagetab{$_};
 4617: 			    my $unikey;
 4618: 			    if ($pack =~ /_0$/) {
 4619: 				$unikey='parameter_0_'.$name;
 4620: 				$part=0;
 4621: 			    } else {
 4622: 				$unikey='parameter'.$keyroot.'_'.$name;
 4623: 			    }
 4624: 			    if ($subp eq 'display') {
 4625: 				$value.=' [Part: '.$part.']';
 4626: 			    }
 4627: 			    $metaentry{':'.$unikey.'.part'}=$part;
 4628: 			    $metathesekeys{$unikey}=1;
 4629: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 4630: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 4631: 			    }
 4632: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 4633: 				$metaentry{':'.$unikey}=
 4634: 				    $metaentry{':'.$unikey.'.default'};
 4635: 			    }
 4636: 			}
 4637: 		    }
 4638: 		} else {
 4639: #
 4640: # This is not a package - some other kind of start tag
 4641: #
 4642: 		    my $entry=$token->[1];
 4643: 		    my $unikey;
 4644: 		    if ($entry eq 'import') {
 4645: 			$unikey='';
 4646: 		    } else {
 4647: 			$unikey=$entry;
 4648: 		    }
 4649: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 4650: 
 4651: 		    if (defined($token->[2]->{'id'})) { 
 4652: 			$unikey.='_'.$token->[2]->{'id'}; 
 4653: 		    }
 4654: 
 4655: 		    if ($entry eq 'import') {
 4656: #
 4657: # Importing a library here
 4658: #
 4659: 			if ($depthcount<20) {
 4660: 			    my $location=$parser->get_text('/import');
 4661: 			    my $dir=$filename;
 4662: 			    $dir=~s|[^/]*$||;
 4663: 			    $location=&filelocation($dir,$location);
 4664: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 4665: 							       $location,$unikey,
 4666: 							       $depthcount+1)))) {
 4667: 				$metaentry{':'.$_}=$metaentry{':'.$_};
 4668: 				$metathesekeys{$_}=1;
 4669: 			    }
 4670: 			}
 4671: 		    } else { 
 4672: 			
 4673: 			if (defined($token->[2]->{'name'})) { 
 4674: 			    $unikey.='_'.$token->[2]->{'name'}; 
 4675: 			}
 4676: 			$metathesekeys{$unikey}=1;
 4677: 			foreach (@{$token->[3]}) {
 4678: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
 4679: 			}
 4680: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 4681: 			my $default=$metaentry{':'.$unikey.'.default'};
 4682: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 4683: 		 # only ws inside the tag, and not in default, so use default
 4684: 		 # as value
 4685: 			    $metaentry{':'.$unikey}=$default;
 4686: 			} else {
 4687: 		  # either something interesting inside the tag or default
 4688:                   # uninteresting
 4689: 			    $metaentry{':'.$unikey}=$internaltext;
 4690: 			}
 4691: # end of not-a-package not-a-library import
 4692: 		    }
 4693: # end of not-a-package start tag
 4694: 		}
 4695: # the next is the end of "start tag"
 4696: 	    }
 4697: 	}
 4698: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 4699: 	foreach my $key (sort(keys(%packagetab))) {
 4700: 	    #&logthis("extsion1 $extension $key !!");
 4701: 	    #no specific packages #how's our extension
 4702: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 4703: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 4704: 					 \%metathesekeys);
 4705: 	}
 4706: 	if (!exists($metaentry{':packages'})) {
 4707: 	    foreach my $key (sort(keys(%packagetab))) {
 4708: 		#no specific packages well let's get default then
 4709: 		if ($key!~/^default&/) { next; }
 4710: 		&metadata_create_package_def($uri,$key,'default',
 4711: 					     \%metathesekeys);
 4712: 	    }
 4713: 	}
 4714: # are there custom rights to evaluate
 4715: 	if ($metaentry{':copyright'} eq 'custom') {
 4716: 
 4717:     #
 4718:     # Importing a rights file here
 4719:     #
 4720: 	    unless ($depthcount) {
 4721: 		my $location=$metaentry{':customdistributionfile'};
 4722: 		my $dir=$filename;
 4723: 		$dir=~s|[^/]*$||;
 4724: 		$location=&filelocation($dir,$location);
 4725: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 4726: 						   $location,'_rights',
 4727: 						   $depthcount+1)))) {
 4728: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
 4729: 		    $metathesekeys{$_}=1;
 4730: 		}
 4731: 	    }
 4732: 	}
 4733: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
 4734: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 4735: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 4736: 	&do_cache_new('meta',$uri,\%metaentry);
 4737: # this is the end of "was not already recently cached
 4738:     }
 4739:     return $metaentry{':'.$what};
 4740: }
 4741: 
 4742: sub metadata_create_package_def {
 4743:     my ($uri,$key,$package,$metathesekeys)=@_;
 4744:     my ($pack,$name,$subp)=split(/\&/,$key);
 4745:     if ($subp eq 'default') { next; }
 4746:     
 4747:     if (defined($metaentry{':packages'})) {
 4748: 	$metaentry{':packages'}.=','.$package;
 4749:     } else {
 4750: 	$metaentry{':packages'}=$package;
 4751:     }
 4752:     my $value=$packagetab{$key};
 4753:     my $unikey;
 4754:     $unikey='parameter_0_'.$name;
 4755:     $metaentry{':'.$unikey.'.part'}=0;
 4756:     $$metathesekeys{$unikey}=1;
 4757:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 4758: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 4759:     }
 4760:     if (defined($metaentry{':'.$unikey.'.default'})) {
 4761: 	$metaentry{':'.$unikey}=
 4762: 	    $metaentry{':'.$unikey.'.default'};
 4763:     }
 4764: }
 4765: 
 4766: sub metadata_generate_part0 {
 4767:     my ($metadata,$metacache,$uri) = @_;
 4768:     my %allnames;
 4769:     foreach my $metakey (sort keys %$metadata) {
 4770: 	if ($metakey=~/^parameter\_(.*)/) {
 4771: 	  my $part=$$metacache{':'.$metakey.'.part'};
 4772: 	  my $name=$$metacache{':'.$metakey.'.name'};
 4773: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 4774: 	    $allnames{$name}=$part;
 4775: 	  }
 4776: 	}
 4777:     }
 4778:     foreach my $name (keys(%allnames)) {
 4779:       $$metadata{"parameter_0_$name"}=1;
 4780:       my $key=":parameter_0_$name";
 4781:       $$metacache{"$key.part"}='0';
 4782:       $$metacache{"$key.name"}=$name;
 4783:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 4784: 					   $allnames{$name}.'_'.$name.
 4785: 					   '.type'};
 4786:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 4787: 			     '.display'};
 4788:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 4789:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 4790:       $$metacache{"$key.display"}=$olddis;
 4791:     }
 4792: }
 4793: 
 4794: # ------------------------------------------------- Get the title of a resource
 4795: 
 4796: sub gettitle {
 4797:     my $urlsymb=shift;
 4798:     my $symb=&symbread($urlsymb);
 4799:     if ($symb) {
 4800: 	my $key=$ENV{'request.course.id'}."\0".$symb;
 4801: 	my ($result,$cached)=&is_cached_new('title',$key);
 4802: 	if (defined($cached)) { 
 4803: 	    return $result;
 4804: 	}
 4805: 	my ($map,$resid,$url)=&decode_symb($symb);
 4806: 	my $title='';
 4807: 	my %bighash;
 4808: 	if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4809: 		&GDBM_READER(),0640)) {
 4810: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 4811: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 4812: 	    untie %bighash;
 4813: 	}
 4814: 	$title=~s/\&colon\;/\:/gs;
 4815: 	if ($title) {
 4816: 	    return &do_cache_new('title',$key,$title,600);
 4817: 	}
 4818: 	$urlsymb=$url;
 4819:     }
 4820:     my $title=&metadata($urlsymb,'title');
 4821:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 4822:     return $title;
 4823: }
 4824:     
 4825: # ------------------------------------------------- Update symbolic store links
 4826: 
 4827: sub symblist {
 4828:     my ($mapname,%newhash)=@_;
 4829:     $mapname=&deversion(&declutter($mapname));
 4830:     my %hash;
 4831:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 4832:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 4833:                       &GDBM_WRCREAT(),0640)) {
 4834: 	    foreach (keys %newhash) {
 4835:                 $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_});
 4836:             }
 4837:             if (untie(%hash)) {
 4838: 		return 'ok';
 4839:             }
 4840:         }
 4841:     }
 4842:     return 'error';
 4843: }
 4844: 
 4845: # --------------------------------------------------------------- Verify a symb
 4846: 
 4847: sub symbverify {
 4848:     my ($symb,$thisurl)=@_;
 4849:     my $thisfn=$thisurl;
 4850: # wrapper not part of symbs
 4851:     $thisfn=~s/^\/adm\/wrapper//;
 4852:     $thisfn=&declutter($thisfn);
 4853: # direct jump to resource in page or to a sequence - will construct own symbs
 4854:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 4855: # check URL part
 4856:     my ($map,$resid,$url)=&decode_symb($symb);
 4857: 
 4858:     unless ($url eq $thisfn) { return 0; }
 4859: 
 4860:     $symb=&symbclean($symb);
 4861:     $thisurl=&deversion($thisurl);
 4862:     $thisfn=&deversion($thisfn);
 4863: 
 4864:     my %bighash;
 4865:     my $okay=0;
 4866: 
 4867:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4868:                             &GDBM_READER(),0640)) {
 4869:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 4870:         unless ($ids) { 
 4871:            $ids=$bighash{'ids_/'.$thisurl};
 4872:         }
 4873:         if ($ids) {
 4874: # ------------------------------------------------------------------- Has ID(s)
 4875: 	    foreach (split(/\,/,$ids)) {
 4876:                my ($mapid,$resid)=split(/\./,$_);
 4877:                if (
 4878:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 4879:    eq $symb) { 
 4880: 		   if (($ENV{'request.role.adv'}) ||
 4881: 		       $bighash{'encrypted_'.$_} eq $ENV{'request.enc'}) {
 4882: 		       $okay=1; 
 4883: 		   }
 4884: 	       }
 4885: 	   }
 4886:         }
 4887: 	untie(%bighash);
 4888:     }
 4889:     return $okay;
 4890: }
 4891: 
 4892: # --------------------------------------------------------------- Clean-up symb
 4893: 
 4894: sub symbclean {
 4895:     my $symb=shift;
 4896:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 4897: # remove version from map
 4898:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 4899: 
 4900: # remove version from URL
 4901:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 4902: 
 4903: # remove wrapper
 4904: 
 4905:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 4906:     return $symb;
 4907: }
 4908: 
 4909: # ---------------------------------------------- Split symb to find map and url
 4910: 
 4911: sub encode_symb {
 4912:     my ($map,$resid,$url)=@_;
 4913:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 4914: }
 4915: 
 4916: sub decode_symb {
 4917:     my $symb=shift;
 4918:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 4919:     my ($map,$resid,$url)=split(/___/,$symb);
 4920:     return (&fixversion($map),$resid,&fixversion($url));
 4921: }
 4922: 
 4923: sub fixversion {
 4924:     my $fn=shift;
 4925:     if ($fn=~/^(adm|uploaded|public)/) { return $fn; }
 4926:     my %bighash;
 4927:     my $uri=&clutter($fn);
 4928:     my $key=$ENV{'request.course.id'}.'_'.$uri;
 4929: # is this cached?
 4930:     my ($result,$cached)=&is_cached(\%courseresversioncache,$key,
 4931: 				    'courseresversion',600);
 4932:     if (defined($cached)) { return $result; }
 4933: # unfortunately not cached, or expired
 4934:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 4935: 	    &GDBM_READER(),0640)) {
 4936:  	if ($bighash{'version_'.$uri}) {
 4937:  	    my $version=$bighash{'version_'.$uri};
 4938:  	    unless (($version eq 'mostrecent') || 
 4939: 		    ($version==&getversion($uri))) {
 4940:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 4941:  	    }
 4942:  	}
 4943:  	untie %bighash;
 4944:     }
 4945:     return &do_cache
 4946: 	(\%courseresversioncache,$key,&declutter($uri),'courseresversion');
 4947: }
 4948: 
 4949: sub deversion {
 4950:     my $url=shift;
 4951:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 4952:     return $url;
 4953: }
 4954: 
 4955: # ------------------------------------------------------ Return symb list entry
 4956: 
 4957: sub symbread {
 4958:     my ($thisfn,$donotrecurse)=@_;
 4959:     my $cache_str='request.symbread.cached.'.$thisfn;
 4960:     if (defined($ENV{$cache_str})) { return $ENV{$cache_str}; }
 4961: # no filename provided? try from environment
 4962:     unless ($thisfn) {
 4963:         if ($ENV{'request.symb'}) {
 4964: 	    return $ENV{$cache_str}=&symbclean($ENV{'request.symb'});
 4965: 	}
 4966: 	$thisfn=$ENV{'request.filename'};
 4967:     }
 4968:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 4969: # is that filename actually a symb? Verify, clean, and return
 4970:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 4971: 	if (&symbverify($thisfn,$1)) {
 4972: 	    return $ENV{$cache_str}=&symbclean($thisfn);
 4973: 	}
 4974:     }
 4975:     $thisfn=declutter($thisfn);
 4976:     my %hash;
 4977:     my %bighash;
 4978:     my $syval='';
 4979:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 4980:         my $targetfn = $thisfn;
 4981:         if ( ($thisfn =~ m/^uploaded\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 4982:             $targetfn = 'adm/wrapper/'.$thisfn;
 4983:         }
 4984:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 4985:                       &GDBM_READER(),0640)) {
 4986: 	    $syval=$hash{$targetfn};
 4987:             untie(%hash);
 4988:         }
 4989: # ---------------------------------------------------------- There was an entry
 4990:         if ($syval) {
 4991:            unless ($syval=~/\_\d+$/) {
 4992: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 4993:                   &appenv('request.ambiguous' => $thisfn);
 4994: 		  return $ENV{$cache_str}='';
 4995:                }    
 4996:                $syval.=$1;
 4997: 	   }
 4998:         } else {
 4999: # ------------------------------------------------------- Was not in symb table
 5000:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 5001:                             &GDBM_READER(),0640)) {
 5002: # ---------------------------------------------- Get ID(s) for current resource
 5003:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 5004:               unless ($ids) { 
 5005:                  $ids=$bighash{'ids_/'.$thisfn};
 5006:               }
 5007:               unless ($ids) {
 5008: # alias?
 5009: 		  $ids=$bighash{'mapalias_'.$thisfn};
 5010:               }
 5011:               if ($ids) {
 5012: # ------------------------------------------------------------------- Has ID(s)
 5013:                  my @possibilities=split(/\,/,$ids);
 5014:                  if ($#possibilities==0) {
 5015: # ----------------------------------------------- There is only one possibility
 5016: 		     my ($mapid,$resid)=split(/\./,$ids);
 5017:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 5018:                  } elsif (!$donotrecurse) {
 5019: # ------------------------------------------ There is more than one possibility
 5020:                      my $realpossible=0;
 5021:                      foreach (@possibilities) {
 5022: 			 my $file=$bighash{'src_'.$_};
 5023:                          if (&allowed('bre',$file)) {
 5024:          		    my ($mapid,$resid)=split(/\./,$_);
 5025:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 5026: 				$realpossible++;
 5027:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 5028:                                        '___'.$resid;
 5029:                             }
 5030: 			 }
 5031:                      }
 5032: 		     if ($realpossible!=1) { $syval=''; }
 5033:                  } else {
 5034:                      $syval='';
 5035:                  }
 5036: 	      }
 5037:               untie(%bighash)
 5038:            }
 5039:         }
 5040:         if ($syval) {
 5041: 	    return $ENV{$cache_str}=&symbclean($syval.'___'.$thisfn);
 5042:         }
 5043:     }
 5044:     &appenv('request.ambiguous' => $thisfn);
 5045:     return $ENV{$cache_str}='';
 5046: }
 5047: 
 5048: # ---------------------------------------------------------- Return random seed
 5049: 
 5050: sub numval {
 5051:     my $txt=shift;
 5052:     $txt=~tr/A-J/0-9/;
 5053:     $txt=~tr/a-j/0-9/;
 5054:     $txt=~tr/K-T/0-9/;
 5055:     $txt=~tr/k-t/0-9/;
 5056:     $txt=~tr/U-Z/0-5/;
 5057:     $txt=~tr/u-z/0-5/;
 5058:     $txt=~s/\D//g;
 5059:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 5060:     return int($txt);
 5061: }
 5062: 
 5063: sub numval2 {
 5064:     my $txt=shift;
 5065:     $txt=~tr/A-J/0-9/;
 5066:     $txt=~tr/a-j/0-9/;
 5067:     $txt=~tr/K-T/0-9/;
 5068:     $txt=~tr/k-t/0-9/;
 5069:     $txt=~tr/U-Z/0-5/;
 5070:     $txt=~tr/u-z/0-5/;
 5071:     $txt=~s/\D//g;
 5072:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5073:     my $total;
 5074:     foreach my $val (@txts) { $total+=$val; }
 5075:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 5076:     return int($total);
 5077: }
 5078: 
 5079: sub numval3 {
 5080:     use integer;
 5081:     my $txt=shift;
 5082:     $txt=~tr/A-J/0-9/;
 5083:     $txt=~tr/a-j/0-9/;
 5084:     $txt=~tr/K-T/0-9/;
 5085:     $txt=~tr/k-t/0-9/;
 5086:     $txt=~tr/U-Z/0-5/;
 5087:     $txt=~tr/u-z/0-5/;
 5088:     $txt=~s/\D//g;
 5089:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5090:     my $total;
 5091:     foreach my $val (@txts) { $total+=$val; }
 5092:     if ($_64bit) { $total=(($total<<32)>>32); }
 5093:     return $total;
 5094: }
 5095: 
 5096: sub latest_rnd_algorithm_id {
 5097:     return '64bit4';
 5098: }
 5099: 
 5100: sub get_rand_alg {
 5101:     my ($courseid)=@_;
 5102:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 5103:     if ($courseid) {
 5104: 	return $ENV{"course.$courseid.rndseed"};
 5105:     }
 5106:     return &latest_rnd_algorithm_id();
 5107: }
 5108: 
 5109: sub validCODE {
 5110:     my ($CODE)=@_;
 5111:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 5112:     return 0;
 5113: }
 5114: 
 5115: sub getCODE {
 5116:     if (&validCODE($ENV{'form.CODE'})) { return $ENV{'form.CODE'}; }
 5117:     if (defined($Apache::lonhomework::parsing_a_problem) &&
 5118: 	&validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 5119: 	return $Apache::lonhomework::history{'resource.CODE'};
 5120:     }
 5121:     return undef;
 5122: }
 5123: 
 5124: sub rndseed {
 5125:     my ($symb,$courseid,$domain,$username)=@_;
 5126: 
 5127:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 5128:     if (!$symb) {
 5129: 	unless ($symb=$wsymb) { return time; }
 5130:     }
 5131:     if (!$courseid) { $courseid=$wcourseid; }
 5132:     if (!$domain) { $domain=$wdomain; }
 5133:     if (!$username) { $username=$wusername }
 5134:     my $which=&get_rand_alg();
 5135:     if (defined(&getCODE())) {
 5136: 	if ($which eq '64bit4') {
 5137: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 5138: 	} else {
 5139: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 5140: 	}
 5141:     } elsif ($which eq '64bit4') {
 5142: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 5143:     } elsif ($which eq '64bit3') {
 5144: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 5145:     } elsif ($which eq '64bit2') {
 5146: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 5147:     } elsif ($which eq '64bit') {
 5148: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 5149:     }
 5150:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 5151: }
 5152: 
 5153: sub rndseed_32bit {
 5154:     my ($symb,$courseid,$domain,$username)=@_;
 5155:     {
 5156: 	use integer;
 5157: 	my $symbchck=unpack("%32C*",$symb) << 27;
 5158: 	my $symbseed=numval($symb) << 22;
 5159: 	my $namechck=unpack("%32C*",$username) << 17;
 5160: 	my $nameseed=numval($username) << 12;
 5161: 	my $domainseed=unpack("%32C*",$domain) << 7;
 5162: 	my $courseseed=unpack("%32C*",$courseid);
 5163: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 5164: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5165: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5166: 	if ($_64bit) { $num=(($num<<32)>>32); }
 5167: 	return $num;
 5168:     }
 5169: }
 5170: 
 5171: sub rndseed_64bit {
 5172:     my ($symb,$courseid,$domain,$username)=@_;
 5173:     {
 5174: 	use integer;
 5175: 	my $symbchck=unpack("%32S*",$symb) << 21;
 5176: 	my $symbseed=numval($symb) << 10;
 5177: 	my $namechck=unpack("%32S*",$username);
 5178: 	
 5179: 	my $nameseed=numval($username) << 21;
 5180: 	my $domainseed=unpack("%32S*",$domain) << 10;
 5181: 	my $courseseed=unpack("%32S*",$courseid);
 5182: 	
 5183: 	my $num1=$symbchck+$symbseed+$namechck;
 5184: 	my $num2=$nameseed+$domainseed+$courseseed;
 5185: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5186: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5187: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5188: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5189: 	return "$num1,$num2";
 5190:     }
 5191: }
 5192: 
 5193: sub rndseed_64bit2 {
 5194:     my ($symb,$courseid,$domain,$username)=@_;
 5195:     {
 5196: 	use integer;
 5197: 	# strings need to be an even # of cahracters long, it it is odd the
 5198:         # last characters gets thrown away
 5199: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5200: 	my $symbseed=numval($symb) << 10;
 5201: 	my $namechck=unpack("%32S*",$username.' ');
 5202: 	
 5203: 	my $nameseed=numval($username) << 21;
 5204: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5205: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5206: 	
 5207: 	my $num1=$symbchck+$symbseed+$namechck;
 5208: 	my $num2=$nameseed+$domainseed+$courseseed;
 5209: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5210: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5211: 	return "$num1,$num2";
 5212:     }
 5213: }
 5214: 
 5215: sub rndseed_64bit3 {
 5216:     my ($symb,$courseid,$domain,$username)=@_;
 5217:     {
 5218: 	use integer;
 5219: 	# strings need to be an even # of cahracters long, it it is odd the
 5220:         # last characters gets thrown away
 5221: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5222: 	my $symbseed=numval2($symb) << 10;
 5223: 	my $namechck=unpack("%32S*",$username.' ');
 5224: 	
 5225: 	my $nameseed=numval2($username) << 21;
 5226: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5227: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5228: 	
 5229: 	my $num1=$symbchck+$symbseed+$namechck;
 5230: 	my $num2=$nameseed+$domainseed+$courseseed;
 5231: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5232: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 5233: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5234: 	
 5235: 	return "$num1:$num2";
 5236:     }
 5237: }
 5238: 
 5239: sub rndseed_64bit4 {
 5240:     my ($symb,$courseid,$domain,$username)=@_;
 5241:     {
 5242: 	use integer;
 5243: 	# strings need to be an even # of cahracters long, it it is odd the
 5244:         # last characters gets thrown away
 5245: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5246: 	my $symbseed=numval3($symb) << 10;
 5247: 	my $namechck=unpack("%32S*",$username.' ');
 5248: 	
 5249: 	my $nameseed=numval3($username) << 21;
 5250: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5251: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5252: 	
 5253: 	my $num1=$symbchck+$symbseed+$namechck;
 5254: 	my $num2=$nameseed+$domainseed+$courseseed;
 5255: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5256: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 5257: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5258: 	
 5259: 	return "$num1:$num2";
 5260:     }
 5261: }
 5262: 
 5263: sub rndseed_CODE_64bit {
 5264:     my ($symb,$courseid,$domain,$username)=@_;
 5265:     {
 5266: 	use integer;
 5267: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 5268: 	my $symbseed=numval2($symb);
 5269: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 5270: 	my $CODEseed=numval(&getCODE());
 5271: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5272: 	my $num1=$symbseed+$CODEchck;
 5273: 	my $num2=$CODEseed+$courseseed+$symbchck;
 5274: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 5275: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 5276: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 5277: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 5278: 	return "$num1:$num2";
 5279:     }
 5280: }
 5281: 
 5282: sub rndseed_CODE_64bit4 {
 5283:     my ($symb,$courseid,$domain,$username)=@_;
 5284:     {
 5285: 	use integer;
 5286: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 5287: 	my $symbseed=numval3($symb);
 5288: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 5289: 	my $CODEseed=numval3(&getCODE());
 5290: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5291: 	my $num1=$symbseed+$CODEchck;
 5292: 	my $num2=$CODEseed+$courseseed+$symbchck;
 5293: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 5294: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 5295: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 5296: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 5297: 	return "$num1:$num2";
 5298:     }
 5299: }
 5300: 
 5301: sub setup_random_from_rndseed {
 5302:     my ($rndseed)=@_;
 5303:     if ($rndseed =~/([,:])/) {
 5304: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 5305: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 5306:     } else {
 5307: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 5308:     }
 5309: }
 5310: 
 5311: sub latest_receipt_algorithm_id {
 5312:     return 'receipt2';
 5313: }
 5314: 
 5315: sub recunique {
 5316:     my $fucourseid=shift;
 5317:     my $unique;
 5318:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 5319: 	$unique=$ENV{"course.$fucourseid.internal.encseed"};
 5320:     } else {
 5321: 	$unique=$perlvar{'lonReceipt'};
 5322:     }
 5323:     return unpack("%32C*",$unique);
 5324: }
 5325: 
 5326: sub recprefix {
 5327:     my $fucourseid=shift;
 5328:     my $prefix;
 5329:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 5330: 	$prefix=$ENV{"course.$fucourseid.internal.encpref"};
 5331:     } else {
 5332: 	$prefix=$perlvar{'lonHostID'};
 5333:     }
 5334:     return unpack("%32C*",$prefix);
 5335: }
 5336: 
 5337: sub ireceipt {
 5338:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 5339:     my $cuname=unpack("%32C*",$funame);
 5340:     my $cudom=unpack("%32C*",$fudom);
 5341:     my $cucourseid=unpack("%32C*",$fucourseid);
 5342:     my $cusymb=unpack("%32C*",$fusymb);
 5343:     my $cunique=&recunique($fucourseid);
 5344:     my $cpart=unpack("%32S*",$part);
 5345:     my $return =&recprefix($fucourseid).'-';
 5346:     if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 5347: 	$ENV{'request.state'} eq 'construct') {
 5348: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 5349: 			       " and ".($cpart%$cudom));
 5350: 			       
 5351: 	$return.= ($cunique%$cuname+
 5352: 		   $cunique%$cudom+
 5353: 		   $cusymb%$cuname+
 5354: 		   $cusymb%$cudom+
 5355: 		   $cucourseid%$cuname+
 5356: 		   $cucourseid%$cudom+
 5357: 		   $cpart%$cuname+
 5358: 		   $cpart%$cudom);
 5359:     } else {
 5360: 	$return.= ($cunique%$cuname+
 5361: 		   $cunique%$cudom+
 5362: 		   $cusymb%$cuname+
 5363: 		   $cusymb%$cudom+
 5364: 		   $cucourseid%$cuname+
 5365: 		   $cucourseid%$cudom);
 5366:     }
 5367:     return $return;
 5368: }
 5369: 
 5370: sub receipt {
 5371:     my ($part)=@_;
 5372:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 5373:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 5374: }
 5375: 
 5376: # ------------------------------------------------------------ Serves up a file
 5377: # returns either the contents of the file or 
 5378: # -1 if the file doesn't exist
 5379: #
 5380: # if the target is a file that was uploaded via DOCS, 
 5381: # a check will be made to see if a current copy exists on the local server,
 5382: # if it does this will be served, otherwise a copy will be retrieved from
 5383: # the home server for the course and stored in /home/httpd/html/userfiles on
 5384: # the local server.   
 5385: 
 5386: sub getfile {
 5387:     my ($file) = @_;
 5388: 
 5389:     if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); }
 5390:     &repcopy($file);
 5391:     return &readfile($file);
 5392: }
 5393: 
 5394: sub repcopy_userfile {
 5395:     my ($file)=@_;
 5396: 
 5397:     if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); }
 5398:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return OK; }
 5399: 
 5400:     my ($cdom,$cnum,$filename) = 
 5401: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 5402:     my ($info,$rtncode);
 5403:     my $uri="/uploaded/$cdom/$cnum/$filename";
 5404:     if (-e "$file") {
 5405: 	my @fileinfo = stat($file);
 5406: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 5407: 	if ($lwpresp ne 'ok') {
 5408: 	    if ($rtncode eq '404') {
 5409: 		unlink($file);
 5410: 	    }
 5411: 	    #my $ua=new LWP::UserAgent;
 5412: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 5413: 	    #my $response=$ua->request($request);
 5414: 	    #if ($response->is_success()) {
 5415: 	#	return $response->content;
 5416: 	#    } else {
 5417: 	#	return -1;
 5418: 	#    }
 5419: 	    return -1;
 5420: 	}
 5421: 	if ($info < $fileinfo[9]) {
 5422: 	    return OK;
 5423: 	}
 5424: 	$info = '';
 5425: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 5426: 	if ($lwpresp ne 'ok') {
 5427: 	    return -1;
 5428: 	}
 5429:     } else {
 5430: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 5431: 	if ($lwpresp ne 'ok') {
 5432: 	    my $ua=new LWP::UserAgent;
 5433: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 5434: 	    my $response=$ua->request($request);
 5435: 	    if ($response->is_success()) {
 5436: 		$info=$response->content;
 5437: 	    } else {
 5438: 		return -1;
 5439: 	    }
 5440: 	}
 5441: 	my @parts = ($cdom,$cnum); 
 5442: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 5443: 	    push @parts, split(/\//,$1);
 5444: 	}
 5445: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 5446: 	foreach my $part (@parts) {
 5447: 	    $path .= '/'.$part;
 5448: 	    if (!-e $path) {
 5449: 		mkdir($path,0770);
 5450: 	    }
 5451: 	}
 5452:     }
 5453:     open(FILE,">$file");
 5454:     print FILE $info;
 5455:     close(FILE);
 5456:     return OK;
 5457: }
 5458: 
 5459: sub tokenwrapper {
 5460:     my $uri=shift;
 5461:     $uri=~s|^http\://([^/]+)||;
 5462:     $uri=~s|^/||;
 5463:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
 5464:     my $token=$1;
 5465:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 5466:     if ($udom && $uname && $file) {
 5467: 	$file=~s|(\?\.*)*$||;
 5468:         &appenv("userfile.$udom/$uname/$file" => $ENV{'request.course.id'});
 5469:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 5470:                (($uri=~/\?/)?'&':'?').'token='.$token.
 5471:                                '&tokenissued='.$perlvar{'lonHostID'};
 5472:     } else {
 5473:         return '/adm/notfound.html';
 5474:     }
 5475: }
 5476: 
 5477: sub getuploaded {
 5478:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 5479:     $uri=~s/^\///;
 5480:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 5481:     my $ua=new LWP::UserAgent;
 5482:     my $request=new HTTP::Request($reqtype,$uri);
 5483:     my $response=$ua->request($request);
 5484:     $$rtncode = $response->code;
 5485:     if (! $response->is_success()) {
 5486: 	return 'failed';
 5487:     }      
 5488:     if ($reqtype eq 'HEAD') {
 5489: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 5490:     } elsif ($reqtype eq 'GET') {
 5491: 	$$info = $response->content;
 5492:     }
 5493:     return 'ok';
 5494: }
 5495: 
 5496: sub readfile {
 5497:     my $file = shift;
 5498:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 5499:     my $fh;
 5500:     open($fh,"<$file");
 5501:     my $a='';
 5502:     while (<$fh>) { $a .=$_; }
 5503:     return $a;
 5504: }
 5505: 
 5506: sub filelocation {
 5507:   my ($dir,$file) = @_;
 5508:   my $location;
 5509:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 5510:   if ($file=~m:^/~:) { # is a contruction space reference
 5511:     $location = $file;
 5512:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 5513:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 5514:       my ($udom,$uname,$filename)=
 5515: 	  ($file=~m|^/+uploaded/+([^/]+)/+([^/]+)/+(.*)$|);
 5516:       my $home=&homeserver($uname,$udom);
 5517:       my $is_me=0;
 5518:       my @ids=&current_machine_ids();
 5519:       foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 5520:       if ($is_me) {
 5521: 	  $location=&Apache::loncommon::propath($udom,$uname).
 5522: 	      '/userfiles/'.$filename;
 5523:       } else {
 5524: 	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 5525: 	      $udom.'/'.$uname.'/'.$filename;
 5526:       }
 5527:   } else {
 5528:     $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 5529:     $file=~s:^/res/:/:;
 5530:     if ( !( $file =~ m:^/:) ) {
 5531:       $location = $dir. '/'.$file;
 5532:     } else {
 5533:       $location = '/home/httpd/html/res'.$file;
 5534:     }
 5535:   }
 5536:   $location=~s://+:/:g; # remove duplicate /
 5537:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 5538:   while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 5539:   return $location;
 5540: }
 5541: 
 5542: sub hreflocation {
 5543:     my ($dir,$file)=@_;
 5544:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 5545: 	my $finalpath=filelocation($dir,$file);
 5546: 	$finalpath=~s-^/home/httpd/html--;
 5547: 	$finalpath=~s-^/home/(\w+)/public_html/-/~$1/-;
 5548: 	return $finalpath;
 5549:     } elsif ($file=~m-^/home-) {
 5550: 	$file=~s-^/home/httpd/html--;
 5551: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 5552: 	return $file;
 5553:     }
 5554:     return $file;
 5555: }
 5556: 
 5557: sub current_machine_domains {
 5558:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 5559:     my @domains;
 5560:     while( my($id, $name) = each(%hostname)) {
 5561: #	&logthis("-$id-$name-$hostname-");
 5562: 	if ($hostname eq $name) {
 5563: 	    push(@domains,$hostdom{$id});
 5564: 	}
 5565:     }
 5566:     return @domains;
 5567: }
 5568: 
 5569: sub current_machine_ids {
 5570:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 5571:     my @ids;
 5572:     while( my($id, $name) = each(%hostname)) {
 5573: #	&logthis("-$id-$name-$hostname-");
 5574: 	if ($hostname eq $name) {
 5575: 	    push(@ids,$id);
 5576: 	}
 5577:     }
 5578:     return @ids;
 5579: }
 5580: 
 5581: # ------------------------------------------------------------- Declutters URLs
 5582: 
 5583: sub declutter {
 5584:     my $thisfn=shift;
 5585:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5586:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 5587:     $thisfn=~s/^\///;
 5588:     $thisfn=~s/^res\///;
 5589:     $thisfn=~s/\?.+$//;
 5590:     return $thisfn;
 5591: }
 5592: 
 5593: # ------------------------------------------------------------- Clutter up URLs
 5594: 
 5595: sub clutter {
 5596:     my $thisfn='/'.&declutter(shift);
 5597:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv|public)\//) { 
 5598:        $thisfn='/res'.$thisfn; 
 5599:     }
 5600:     return $thisfn;
 5601: }
 5602: 
 5603: sub freeze_escape {
 5604:     my ($value)=@_;
 5605:     if (ref($value)) {
 5606: 	$value=&nfreeze($value);
 5607: 	return '__FROZEN__'.&escape($value);
 5608:     }
 5609:     return &escape($value);
 5610: }
 5611: 
 5612: # -------------------------------------------------------- Escape Special Chars
 5613: 
 5614: sub escape {
 5615:     my $str=shift;
 5616:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 5617:     return $str;
 5618: }
 5619: 
 5620: # ----------------------------------------------------- Un-Escape Special Chars
 5621: 
 5622: sub unescape {
 5623:     my $str=shift;
 5624:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 5625:     return $str;
 5626: }
 5627: 
 5628: sub thaw_unescape {
 5629:     my ($value)=@_;
 5630:     if ($value =~ /^__FROZEN__/) {
 5631: 	substr($value,0,10,undef);
 5632: 	$value=&unescape($value);
 5633: 	return &thaw($value);
 5634:     }
 5635:     return &unescape($value);
 5636: }
 5637: 
 5638: sub mod_perl_version {
 5639:     return 1;
 5640:     if (defined($perlvar{'MODPERL2'})) {
 5641: 	return 2;
 5642:     }
 5643: }
 5644: 
 5645: sub correct_line_ends {
 5646:     my ($result)=@_;
 5647:     $$result =~s/\r\n/\n/mg;
 5648:     $$result =~s/\r/\n/mg;
 5649: }
 5650: # ================================================================ Main Program
 5651: 
 5652: sub goodbye {
 5653:    &logthis("Starting Shut down");
 5654: #not converted to using infrastruture and probably shouldn't be
 5655:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 5656: #converted
 5657: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 5658:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 5659: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 5660:    &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 5661: #1.1 only
 5662:    &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 5663:    &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 5664:    &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 5665:    &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 5666:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 5667:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 5668:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 5669:    &flushcourselogs();
 5670:    &logthis("Shutting down");
 5671:    return DONE;
 5672: }
 5673: 
 5674: BEGIN {
 5675: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 5676:     unless ($readit) {
 5677: {
 5678:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 5679:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 5680: 
 5681:     while (my $configline=<$config>) {
 5682:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 5683: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 5684:            chomp($varvalue);
 5685:            $perlvar{$varname}=$varvalue;
 5686:         }
 5687:     }
 5688:     close($config);
 5689: }
 5690: {
 5691:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 5692: 
 5693:     while (my $configline=<$config>) {
 5694:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 5695: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 5696:            chomp($varvalue);
 5697:            $perlvar{$varname}=$varvalue;
 5698:         }
 5699:     }
 5700:     close($config);
 5701: }
 5702: 
 5703: # ------------------------------------------------------------ Read domain file
 5704: {
 5705:     %domaindescription = ();
 5706:     %domain_auth_def = ();
 5707:     %domain_auth_arg_def = ();
 5708:     my $fh;
 5709:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 5710:        while (<$fh>) {
 5711:            next if (/^(\#|\s*$)/);
 5712: #           next if /^\#/;
 5713:            chomp;
 5714:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 5715: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
 5716: 	   $domain_auth_def{$domain}=$def_auth;
 5717:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 5718: 	   $domaindescription{$domain}=$domain_description;
 5719: 	   $domain_lang_def{$domain}=$def_lang;
 5720: 	   $domain_city{$domain}=$city;
 5721: 	   $domain_longi{$domain}=$longi;
 5722: 	   $domain_lati{$domain}=$lati;
 5723: 
 5724:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 5725: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 5726: 	}
 5727:     }
 5728:     close ($fh);
 5729: }
 5730: 
 5731: 
 5732: # ------------------------------------------------------------- Read hosts file
 5733: {
 5734:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 5735: 
 5736:     while (my $configline=<$config>) {
 5737:        next if ($configline =~ /^(\#|\s*$)/);
 5738:        chomp($configline);
 5739:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 5740:        if ($id && $domain && $role && $name && $ip) {
 5741: 	 $hostname{$id}=$name;
 5742: 	 $hostdom{$id}=$domain;
 5743: 	 $hostip{$id}=$ip;
 5744: 	 $iphost{$ip}=$id;
 5745: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 5746:        }
 5747:     }
 5748:     close($config);
 5749: }
 5750: 
 5751: # ------------------------------------------------------ Read spare server file
 5752: {
 5753:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 5754: 
 5755:     while (my $configline=<$config>) {
 5756:        chomp($configline);
 5757:        if ($configline) {
 5758:           $spareid{$configline}=1;
 5759:        }
 5760:     }
 5761:     close($config);
 5762: }
 5763: # ------------------------------------------------------------ Read permissions
 5764: {
 5765:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 5766: 
 5767:     while (my $configline=<$config>) {
 5768: 	chomp($configline);
 5769: 	if ($configline) {
 5770: 	    my ($role,$perm)=split(/ /,$configline);
 5771: 	    if ($perm ne '') { $pr{$role}=$perm; }
 5772: 	}
 5773:     }
 5774:     close($config);
 5775: }
 5776: 
 5777: # -------------------------------------------- Read plain texts for permissions
 5778: {
 5779:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 5780: 
 5781:     while (my $configline=<$config>) {
 5782: 	chomp($configline);
 5783: 	if ($configline) {
 5784: 	    my ($short,$plain)=split(/:/,$configline);
 5785: 	    if ($plain ne '') { $prp{$short}=$plain; }
 5786: 	}
 5787:     }
 5788:     close($config);
 5789: }
 5790: 
 5791: # ---------------------------------------------------------- Read package table
 5792: {
 5793:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 5794: 
 5795:     while (my $configline=<$config>) {
 5796: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 5797: 	chomp($configline);
 5798: 	my ($short,$plain)=split(/:/,$configline);
 5799: 	my ($pack,$name)=split(/\&/,$short);
 5800: 	if ($plain ne '') {
 5801: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 5802: 	    $packagetab{$short}=$plain; 
 5803: 	}
 5804:     }
 5805:     close($config);
 5806: }
 5807: 
 5808: # ------------- set up temporary directory
 5809: {
 5810:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 5811: 
 5812: }
 5813: 
 5814: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 5815: 
 5816: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 5817: $dumpcount=0;
 5818: 
 5819: &logtouch();
 5820: &logthis('<font color=yellow>INFO: Read configuration</font>');
 5821: $readit=1;
 5822:     {
 5823: 	use integer;
 5824: 	my $test=(2**32)+1;
 5825: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 5826: 	&logthis(" Detected 64bit platform ($_64bit)");
 5827:     }
 5828: }
 5829: }
 5830: 
 5831: 1;
 5832: __END__
 5833: 
 5834: =pod
 5835: 
 5836: =head1 NAME
 5837: 
 5838: Apache::lonnet - Subroutines to ask questions about things in the network.
 5839: 
 5840: =head1 SYNOPSIS
 5841: 
 5842: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 5843: 
 5844:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 5845: 
 5846: Common parameters:
 5847: 
 5848: =over 4
 5849: 
 5850: =item *
 5851: 
 5852: $uname : an internal username (if $cname expecting a course Id specifically)
 5853: 
 5854: =item *
 5855: 
 5856: $udom : a domain (if $cdom expecting a course's domain specifically)
 5857: 
 5858: =item *
 5859: 
 5860: $symb : a resource instance identifier
 5861: 
 5862: =item *
 5863: 
 5864: $namespace : the name of a .db file that contains the data needed or
 5865: being set.
 5866: 
 5867: =back
 5868: 
 5869: =head1 OVERVIEW
 5870: 
 5871: lonnet provides subroutines which interact with the
 5872: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 5873: about classes, users, and resources.
 5874: 
 5875: For many of these objects you can also use this to store data about
 5876: them or modify them in various ways.
 5877: 
 5878: =head2 Symbs
 5879: 
 5880: To identify a specific instance of a resource, LON-CAPA uses symbols
 5881: or "symbs"X<symb>. These identifiers are built from the URL of the
 5882: map, the resource number of the resource in the map, and the URL of
 5883: the resource itself. The latter is somewhat redundant, but might help
 5884: if maps change.
 5885: 
 5886: An example is
 5887: 
 5888:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 5889: 
 5890: The respective map entry is
 5891: 
 5892:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 5893:   title="Problem 2">
 5894:  </resource>
 5895: 
 5896: Symbs are used by the random number generator, as well as to store and
 5897: restore data specific to a certain instance of for example a problem.
 5898: 
 5899: =head2 Storing And Retrieving Data
 5900: 
 5901: X<store()>X<cstore()>X<restore()>Three of the most important functions
 5902: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 5903: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 5904: is is the non-critical message twin of cstore. These functions are for
 5905: handlers to store a perl hash to a user's permanent data space in an
 5906: easy manner, and to retrieve it again on another call. It is expected
 5907: that a handler would use this once at the beginning to retrieve data,
 5908: and then again once at the end to send only the new data back.
 5909: 
 5910: The data is stored in the user's data directory on the user's
 5911: homeserver under the ID of the course.
 5912: 
 5913: The hash that is returned by restore will have all of the previous
 5914: value for all of the elements of the hash.
 5915: 
 5916: Example:
 5917: 
 5918:  #creating a hash
 5919:  my %hash;
 5920:  $hash{'foo'}='bar';
 5921: 
 5922:  #storing it
 5923:  &Apache::lonnet::cstore(\%hash);
 5924: 
 5925:  #changing a value
 5926:  $hash{'foo'}='notbar';
 5927: 
 5928:  #adding a new value
 5929:  $hash{'bar'}='foo';
 5930:  &Apache::lonnet::cstore(\%hash);
 5931: 
 5932:  #retrieving the hash
 5933:  my %history=&Apache::lonnet::restore();
 5934: 
 5935:  #print the hash
 5936:  foreach my $key (sort(keys(%history))) {
 5937:    print("\%history{$key} = $history{$key}");
 5938:  }
 5939: 
 5940: Will print out:
 5941: 
 5942:  %history{1:foo} = bar
 5943:  %history{1:keys} = foo:timestamp
 5944:  %history{1:timestamp} = 990455579
 5945:  %history{2:bar} = foo
 5946:  %history{2:foo} = notbar
 5947:  %history{2:keys} = foo:bar:timestamp
 5948:  %history{2:timestamp} = 990455580
 5949:  %history{bar} = foo
 5950:  %history{foo} = notbar
 5951:  %history{timestamp} = 990455580
 5952:  %history{version} = 2
 5953: 
 5954: Note that the special hash entries C<keys>, C<version> and
 5955: C<timestamp> were added to the hash. C<version> will be equal to the
 5956: total number of versions of the data that have been stored. The
 5957: C<timestamp> attribute will be the UNIX time the hash was
 5958: stored. C<keys> is available in every historical section to list which
 5959: keys were added or changed at a specific historical revision of a
 5960: hash.
 5961: 
 5962: B<Warning>: do not store the hash that restore returns directly. This
 5963: will cause a mess since it will restore the historical keys as if the
 5964: were new keys. I.E. 1:foo will become 1:1:foo etc.
 5965: 
 5966: Calling convention:
 5967: 
 5968:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 5969:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 5970: 
 5971: For more detailed information, see lonnet specific documentation.
 5972: 
 5973: =head1 RETURN MESSAGES
 5974: 
 5975: =over 4
 5976: 
 5977: =item * B<con_lost>: unable to contact remote host
 5978: 
 5979: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 5980: when the connection is brought back up
 5981: 
 5982: =item * B<con_failed>: unable to contact remote host and unable to save message
 5983: for later delivery
 5984: 
 5985: =item * B<error:>: an error a occured, a description of the error follows the :
 5986: 
 5987: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 5988: that was requested
 5989: 
 5990: =back
 5991: 
 5992: =head1 PUBLIC SUBROUTINES
 5993: 
 5994: =head2 Session Environment Functions
 5995: 
 5996: =over 4
 5997: 
 5998: =item * 
 5999: X<appenv()>
 6000: B<appenv(%hash)>: the value of %hash is written to
 6001: the user envirnoment file, and will be restored for each access this
 6002: user makes during this session, also modifies the %ENV for the current
 6003: process
 6004: 
 6005: =item *
 6006: X<delenv()>
 6007: B<delenv($regexp)>: removes all items from the session
 6008: environment file that matches the regular expression in $regexp. The
 6009: values are also delted from the current processes %ENV.
 6010: 
 6011: =back
 6012: 
 6013: =head2 User Information
 6014: 
 6015: =over 4
 6016: 
 6017: =item *
 6018: X<queryauthenticate()>
 6019: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 6020: authentication scheme
 6021: 
 6022: =item *
 6023: X<authenticate()>
 6024: B<authenticate($uname,$upass,$udom)>: try to
 6025: authenticate user from domain's lib servers (first use the current
 6026: one). C<$upass> should be the users password.
 6027: 
 6028: =item *
 6029: X<homeserver()>
 6030: B<homeserver($uname,$udom)>: find the server which has
 6031: the user's directory and files (there must be only one), this caches
 6032: the answer, and also caches if there is a borken connection.
 6033: 
 6034: =item *
 6035: X<idget()>
 6036: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 6037: (IDs are a unique resource in a domain, there must be only 1 ID per
 6038: username, and only 1 username per ID in a specific domain) (returns
 6039: hash: id=>name,id=>name)
 6040: 
 6041: =item *
 6042: X<idrget()>
 6043: B<idrget($udom,@unames)>: find the IDs behind a list of
 6044: usernames (returns hash: name=>id,name=>id)
 6045: 
 6046: =item *
 6047: X<idput()>
 6048: B<idput($udom,%ids)>: store away a list of names and associated IDs
 6049: 
 6050: =item *
 6051: X<rolesinit()>
 6052: B<rolesinit($udom,$username,$authhost)>: get user privileges
 6053: 
 6054: =item *
 6055: X<getsection()>
 6056: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 6057: course $cname, return section name/number or '' for "not in course"
 6058: and '-1' for "no section"
 6059: 
 6060: =item *
 6061: X<userenvironment()>
 6062: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 6063: passed in @what from the requested user's environment, returns a hash
 6064: 
 6065: =back
 6066: 
 6067: =head2 User Roles
 6068: 
 6069: =over 4
 6070: 
 6071: =item *
 6072: 
 6073: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 6074: actions
 6075:  F: full access
 6076:  U,I,K: authentication modes (cxx only)
 6077:  '': forbidden
 6078:  1: user needs to choose course
 6079:  2: browse allowed
 6080: 
 6081: =item *
 6082: 
 6083: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 6084: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 6085: and course level
 6086: 
 6087: =item *
 6088: 
 6089: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 6090: explanation of a user role term
 6091: 
 6092: =back
 6093: 
 6094: =head2 User Modification
 6095: 
 6096: =over 4
 6097: 
 6098: =item *
 6099: 
 6100: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 6101: user for the level given by URL.  Optional start and end dates (leave empty
 6102: string or zero for "no date")
 6103: 
 6104: =item *
 6105: 
 6106: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 6107: change a users, password, possible return values are: ok,
 6108: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 6109: refused
 6110: 
 6111: =item *
 6112: 
 6113: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 6114: 
 6115: =item *
 6116: 
 6117: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 6118: modify user
 6119: 
 6120: =item *
 6121: 
 6122: modifystudent
 6123: 
 6124: modify a students enrollment and identification information.
 6125: The course id is resolved based on the current users environment.  
 6126: This means the envoking user must be a course coordinator or otherwise
 6127: associated with a course.
 6128: 
 6129: This call is essentially a wrapper for lonnet::modifyuser and
 6130: lonnet::modify_student_enrollment
 6131: 
 6132: Inputs: 
 6133: 
 6134: =over 4
 6135: 
 6136: =item B<$udom> Students loncapa domain
 6137: 
 6138: =item B<$uname> Students loncapa login name
 6139: 
 6140: =item B<$uid> Students id/student number
 6141: 
 6142: =item B<$umode> Students authentication mode
 6143: 
 6144: =item B<$upass> Students password
 6145: 
 6146: =item B<$first> Students first name
 6147: 
 6148: =item B<$middle> Students middle name
 6149: 
 6150: =item B<$last> Students last name
 6151: 
 6152: =item B<$gene> Students generation
 6153: 
 6154: =item B<$usec> Students section in course
 6155: 
 6156: =item B<$end> Unix time of the roles expiration
 6157: 
 6158: =item B<$start> Unix time of the roles start date
 6159: 
 6160: =item B<$forceid> If defined, allow $uid to be changed
 6161: 
 6162: =item B<$desiredhome> server to use as home server for student
 6163: 
 6164: =back
 6165: 
 6166: =item *
 6167: 
 6168: modify_student_enrollment
 6169: 
 6170: Change a students enrollment status in a class.  The environment variable
 6171: 'role.request.course' must be defined for this function to proceed.
 6172: 
 6173: Inputs:
 6174: 
 6175: =over 4
 6176: 
 6177: =item $udom, students domain
 6178: 
 6179: =item $uname, students name
 6180: 
 6181: =item $uid, students user id
 6182: 
 6183: =item $first, students first name
 6184: 
 6185: =item $middle
 6186: 
 6187: =item $last
 6188: 
 6189: =item $gene
 6190: 
 6191: =item $usec
 6192: 
 6193: =item $end
 6194: 
 6195: =item $start
 6196: 
 6197: =back
 6198: 
 6199: 
 6200: =item *
 6201: 
 6202: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 6203: custom role; give a custom role to a user for the level given by URL.  Specify
 6204: name and domain of role author, and role name
 6205: 
 6206: =item *
 6207: 
 6208: revokerole($udom,$uname,$url,$role) : revoke a role for url
 6209: 
 6210: =item *
 6211: 
 6212: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 6213: 
 6214: =back
 6215: 
 6216: =head2 Course Infomation
 6217: 
 6218: =over 4
 6219: 
 6220: =item *
 6221: 
 6222: coursedescription($courseid) : course description
 6223: 
 6224: =item *
 6225: 
 6226: courseresdata($coursenum,$coursedomain,@which) : request for current
 6227: parameter setting for a specific course, @what should be a list of
 6228: parameters to ask about. This routine caches answers for 5 minutes.
 6229: 
 6230: =back
 6231: 
 6232: =head2 Course Modification
 6233: 
 6234: =over 4
 6235: 
 6236: =item *
 6237: 
 6238: writecoursepref($courseid,%prefs) : write preferences (environment
 6239: database) for a course
 6240: 
 6241: =item *
 6242: 
 6243: createcourse($udom,$description,$url) : make/modify course
 6244: 
 6245: =back
 6246: 
 6247: =head2 Resource Subroutines
 6248: 
 6249: =over 4
 6250: 
 6251: =item *
 6252: 
 6253: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 6254: 
 6255: =item *
 6256: 
 6257: repcopy($filename) : subscribes to the requested file, and attempts to
 6258: replicate from the owning library server, Might return
 6259: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 6260: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 6261: resource. Expects the local filesystem pathname
 6262: (/home/httpd/html/res/....)
 6263: 
 6264: =back
 6265: 
 6266: =head2 Resource Information
 6267: 
 6268: =over 4
 6269: 
 6270: =item *
 6271: 
 6272: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 6273: a vairety of different possible values, $varname should be a request
 6274: string, and the other parameters can be used to specify who and what
 6275: one is asking about.
 6276: 
 6277: Possible values for $varname are environment.lastname (or other item
 6278: from the envirnment hash), user.name (or someother aspect about the
 6279: user), resource.0.maxtries (or some other part and parameter of a
 6280: resource)
 6281: 
 6282: =item *
 6283: 
 6284: directcondval($number) : get current value of a condition; reads from a state
 6285: string
 6286: 
 6287: =item *
 6288: 
 6289: condval($condidx) : value of condition index based on state
 6290: 
 6291: =item *
 6292: 
 6293: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 6294: resource's metadata, $what should be either a specific key, or either
 6295: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 6296: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 6297: 
 6298: this function automatically caches all requests
 6299: 
 6300: =item *
 6301: 
 6302: metadata_query($query,$custom,$customshow) : make a metadata query against the
 6303: network of library servers; returns file handle of where SQL and regex results
 6304: will be stored for query
 6305: 
 6306: =item *
 6307: 
 6308: symbread($filename) : return symbolic list entry (filename argument optional);
 6309: returns the data handle
 6310: 
 6311: =item *
 6312: 
 6313: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 6314: a possible symb for the URL in $thisfn, and if is an encryypted
 6315: resource that the user accessed using /enc/ returns a 1 on success, 0
 6316: on failure, user must be in a course, as it assumes the existance of
 6317: the course initial hash, and uses $ENV('request.course.id'}
 6318: 
 6319: 
 6320: =item *
 6321: 
 6322: symbclean($symb) : removes versions numbers from a symb, returns the
 6323: cleaned symb
 6324: 
 6325: =item *
 6326: 
 6327: is_on_map($uri) : checks if the $uri is somewhere on the current
 6328: course map, user must be in a course for it to work.
 6329: 
 6330: =item *
 6331: 
 6332: numval($salt) : return random seed value (addend for rndseed)
 6333: 
 6334: =item *
 6335: 
 6336: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 6337: a random seed, all arguments are optional, if they aren't sent it uses the
 6338: environment to derive them. Note: if symb isn't sent and it can't get one
 6339: from &symbread it will use the current time as its return value
 6340: 
 6341: =item *
 6342: 
 6343: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 6344: unfakeable, receipt
 6345: 
 6346: =item *
 6347: 
 6348: receipt() : API to ireceipt working off of ENV values; given out to users
 6349: 
 6350: =item *
 6351: 
 6352: countacc($url) : count the number of accesses to a given URL
 6353: 
 6354: =item *
 6355: 
 6356: 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
 6357: 
 6358: =item *
 6359: 
 6360: 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)
 6361: 
 6362: =item *
 6363: 
 6364: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 6365: 
 6366: =item *
 6367: 
 6368: devalidate($symb) : devalidate temporary spreadsheet calculations,
 6369: forcing spreadsheet to reevaluate the resource scores next time.
 6370: 
 6371: =back
 6372: 
 6373: =head2 Storing/Retreiving Data
 6374: 
 6375: =over 4
 6376: 
 6377: =item *
 6378: 
 6379: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 6380: for this url; hashref needs to be given and should be a \%hashname; the
 6381: remaining args aren't required and if they aren't passed or are '' they will
 6382: be derived from the ENV
 6383: 
 6384: =item *
 6385: 
 6386: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 6387: uses critical subroutine
 6388: 
 6389: =item *
 6390: 
 6391: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 6392: all args are optional
 6393: 
 6394: =item *
 6395: 
 6396: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 6397: works very similar to store/cstore, but all data is stored in a
 6398: temporary location and can be reset using tmpreset, $storehash should
 6399: be a hash reference, returns nothing on success
 6400: 
 6401: =item *
 6402: 
 6403: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 6404: similar to restore, but all data is stored in a temporary location and
 6405: can be reset using tmpreset. Returns a hash of values on success,
 6406: error string otherwise.
 6407: 
 6408: =item *
 6409: 
 6410: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 6411: deltes all keys for $symb form the temporary storage hash.
 6412: 
 6413: =item *
 6414: 
 6415: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 6416: reference filled in from namesp ($udom and $uname are optional)
 6417: 
 6418: =item *
 6419: 
 6420: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 6421: namesp ($udom and $uname are optional)
 6422: 
 6423: =item *
 6424: 
 6425: dump($namespace,$udom,$uname,$regexp) : 
 6426: dumps the complete (or key matching regexp) namespace into a hash
 6427: ($udom, $uname and $regexp are optional)
 6428: 
 6429: =item *
 6430: 
 6431: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 6432: $store can be a scalar, an array reference, or if the amount to be 
 6433: incremented is > 1, a hash reference.
 6434: 
 6435: ($udom and $uname are optional)
 6436: 
 6437: =item *
 6438: 
 6439: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 6440: ($udom and $uname are optional)
 6441: 
 6442: =item *
 6443: 
 6444: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
 6445: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
 6446: used in records written by &store and retrieved by &restore.  This function 
 6447: was created for use in editing discussion posts, without incrementing the
 6448: version number included in the key for a particular post. The colon 
 6449: separated list of attribute names (e.g., the value associated with the key 
 6450: 1:keys:$symb) is also generated and passed in the ampersand separated 
 6451: items sent to lonnet::reply().  
 6452: 
 6453: =item *
 6454: 
 6455: cput($namespace,$storehash,$udom,$uname) : critical put
 6456: ($udom and $uname are optional)
 6457: 
 6458: =item *
 6459: 
 6460: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 6461: reference filled in from namesp (encrypts the return communication)
 6462: ($udom and $uname are optional)
 6463: 
 6464: =item *
 6465: 
 6466: log($udom,$name,$home,$message) : write to permanent log for user; use
 6467: critical subroutine
 6468: 
 6469: =back
 6470: 
 6471: =head2 Network Status Functions
 6472: 
 6473: =over 4
 6474: 
 6475: =item *
 6476: 
 6477: dirlist($uri) : return directory list based on URI
 6478: 
 6479: =item *
 6480: 
 6481: spareserver() : find server with least workload from spare.tab
 6482: 
 6483: =back
 6484: 
 6485: =head2 Apache Request
 6486: 
 6487: =over 4
 6488: 
 6489: =item *
 6490: 
 6491: ssi($url,%hash) : server side include, does a complete request cycle on url to
 6492: localhost, posts hash
 6493: 
 6494: =back
 6495: 
 6496: =head2 Data to String to Data
 6497: 
 6498: =over 4
 6499: 
 6500: =item *
 6501: 
 6502: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 6503: and '&' separators, supports elements that are arrayrefs and hashrefs
 6504: 
 6505: =item *
 6506: 
 6507: hashref2str($hashref) : convert a hashref into a string complete with
 6508: escaping and '=' and '&' separators, supports elements that are
 6509: arrayrefs and hashrefs
 6510: 
 6511: =item *
 6512: 
 6513: arrayref2str($arrayref) : convert an arrayref into a string complete
 6514: with escaping and '&' separators, supports elements that are arrayrefs
 6515: and hashrefs
 6516: 
 6517: =item *
 6518: 
 6519: str2hash($string) : convert string to hash using unescaping and
 6520: splitting on '=' and '&', supports elements that are arrayrefs and
 6521: hashrefs
 6522: 
 6523: =item *
 6524: 
 6525: str2array($string) : convert string to hash using unescaping and
 6526: splitting on '&', supports elements that are arrayrefs and hashrefs
 6527: 
 6528: =back
 6529: 
 6530: =head2 Logging Routines
 6531: 
 6532: =over 4
 6533: 
 6534: These routines allow one to make log messages in the lonnet.log and
 6535: lonnet.perm logfiles.
 6536: 
 6537: =item *
 6538: 
 6539: logtouch() : make sure the logfile, lonnet.log, exists
 6540: 
 6541: =item *
 6542: 
 6543: logthis() : append message to the normal lonnet.log file, it gets
 6544: preiodically rolled over and deleted.
 6545: 
 6546: =item *
 6547: 
 6548: logperm() : append a permanent message to lonnet.perm.log, this log
 6549: file never gets deleted by any automated portion of the system, only
 6550: messages of critical importance should go in here.
 6551: 
 6552: =back
 6553: 
 6554: =head2 General File Helper Routines
 6555: 
 6556: =over 4
 6557: 
 6558: =item *
 6559: 
 6560: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 6561: (a) files in /uploaded
 6562:   (i) If a local copy of the file exists - 
 6563:       compares modification date of local copy with last-modified date for 
 6564:       definitive version stored on home server for course. If local copy is 
 6565:       stale, requests a new version from the home server and stores it. 
 6566:       If the original has been removed from the home server, then local copy 
 6567:       is unlinked.
 6568:   (ii) If local copy does not exist -
 6569:       requests the file from the home server and stores it. 
 6570:   
 6571:   If $caller is 'uploadrep':  
 6572:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 6573:     for request for files originally uploaded via DOCS. 
 6574:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 6575:   
 6576:   Otherwise:
 6577:      This indicates a call from the content generation phase of the request.
 6578:      -  returns the entire contents of the file or -1.
 6579:      
 6580: (b) files in /res
 6581:    - returns the entire contents of a file or -1; 
 6582:    it properly subscribes to and replicates the file if neccessary.
 6583: 
 6584: =item *
 6585: 
 6586: filelocation($dir,$file) : returns file system location of a file
 6587: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 6588: directory that relative $file lookups are to looked in ($dir of /a/dir
 6589: and a file of ../bob will become /a/bob)
 6590: 
 6591: =item *
 6592: 
 6593: hreflocation($dir,$file) : returns file system location or a URL; same as
 6594: filelocation except for hrefs
 6595: 
 6596: =item *
 6597: 
 6598: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 6599: 
 6600: =back
 6601: 
 6602: =head2 HTTP Helper Routines
 6603: 
 6604: =over 4
 6605: 
 6606: =item *
 6607: 
 6608: escape() : unpack non-word characters into CGI-compatible hex codes
 6609: 
 6610: =item *
 6611: 
 6612: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 6613: 
 6614: =back
 6615: 
 6616: =head1 PRIVATE SUBROUTINES
 6617: 
 6618: =head2 Underlying communication routines (Shouldn't call)
 6619: 
 6620: =over 4
 6621: 
 6622: =item *
 6623: 
 6624: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 6625: 
 6626: =item *
 6627: 
 6628: reply() : uses subreply to send a message to remote machine, logs all failures
 6629: 
 6630: =item *
 6631: 
 6632: critical() : passes a critical message to another server; if cannot
 6633: get through then place message in connection buffer directory and
 6634: returns con_delayed, if incapable of saving message, returns
 6635: con_failed
 6636: 
 6637: =item *
 6638: 
 6639: reconlonc() : tries to reconnect lonc client processes.
 6640: 
 6641: =back
 6642: 
 6643: =head2 Resource Access Logging
 6644: 
 6645: =over 4
 6646: 
 6647: =item *
 6648: 
 6649: flushcourselogs() : flush (save) buffer logs and access logs
 6650: 
 6651: =item *
 6652: 
 6653: courselog($what) : save message for course in hash
 6654: 
 6655: =item *
 6656: 
 6657: courseacclog($what) : save message for course using &courselog().  Perform
 6658: special processing for specific resource types (problems, exams, quizzes, etc).
 6659: 
 6660: =item *
 6661: 
 6662: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 6663: as a PerlChildExitHandler
 6664: 
 6665: =back
 6666: 
 6667: =head2 Other
 6668: 
 6669: =over 4
 6670: 
 6671: =item *
 6672: 
 6673: symblist($mapname,%newhash) : update symbolic storage links
 6674: 
 6675: =back
 6676: 
 6677: =cut

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