File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.685: download - view: text, annotated - select for diffs
Fri Dec 9 00:08:51 2005 UTC (18 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Unify storage of DCmail on domain's primary domain server

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

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