File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.687: download - view: text, annotated - select for diffs
Thu Dec 22 20:56:28 2005 UTC (18 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- /ext/ resource are known in the _symb.db cahce as ext/.... not adm/wrapper/ext/....

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

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