File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.587.2.3.2.1: download - view: text, annotated - select for diffs
Thu Feb 10 08:16:31 2005 UTC (19 years, 4 months ago) by albertel
Branches: version_1_3_X_memcached
Diff to branchpoint 1.587.2.3: preferred, unified
- forward porting the memcached changes

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

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