File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.702: download - view: text, annotated - select for diffs
Sat Jan 21 08:27:02 2006 UTC (18 years, 6 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- bug #4608
   - adding optional 'range' attribute to dump for controlling the number of results

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

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