File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.870: download - view: text, annotated - select for diffs
Thu Apr 12 00:03:08 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminate some unused modules

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.870 2007/04/12 00:03:08 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::Date;
   35: # use Date::Parse;
   36: use vars 
   37: qw(%perlvar %badServerCache %spareid 
   38:    %pr %prp $memcache %packagetab 
   39:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   40:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   41:    $tmpdir $_64bit %env);
   42: 
   43: use IO::Socket;
   44: use GDBM_File;
   45: use HTML::LCParser;
   46: use Fcntl qw(:flock);
   47: use Storable qw(thaw nfreeze);
   48: use Time::HiRes qw( gettimeofday tv_interval );
   49: use Cache::Memcached;
   50: use Digest::MD5;
   51: use Math::Random;
   52: use LONCAPA qw(:DEFAULT :match);
   53: use LONCAPA::Configuration;
   54: 
   55: my $readit;
   56: my $max_connection_retries = 10;     # Or some such value.
   57: 
   58: require Exporter;
   59: 
   60: our @ISA = qw (Exporter);
   61: our @EXPORT = qw(%env);
   62: 
   63: =pod
   64: 
   65: =head1 Package Variables
   66: 
   67: These are largely undocumented, so if you decipher one please note it here.
   68: 
   69: =over 4
   70: 
   71: =item $processmarker
   72: 
   73: Contains the time this process was started and this servers host id.
   74: 
   75: =item $dumpcount
   76: 
   77: Counts the number of times a message log flush has been attempted (regardless
   78: of success) by this process.  Used as part of the filename when messages are
   79: delayed.
   80: 
   81: =back
   82: 
   83: =cut
   84: 
   85: 
   86: # --------------------------------------------------------------------- Logging
   87: {
   88:     my $logid;
   89:     sub instructor_log {
   90: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   91: 	$logid++;
   92: 	my $id=time().'00000'.$$.'00000'.$logid;
   93: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   94: 				    { $id => {
   95: 					'exe_uname' => $env{'user.name'},
   96: 					'exe_udom'  => $env{'user.domain'},
   97: 					'exe_time'  => time(),
   98: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
   99: 					'delflag'   => $delflag,
  100: 					'logentry'  => $storehash,
  101: 					'uname'     => $uname,
  102: 					'udom'      => $udom,
  103: 				    }
  104: 				  },
  105: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  106: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  107: 				    );
  108:     }
  109: }
  110: 
  111: sub logtouch {
  112:     my $execdir=$perlvar{'lonDaemons'};
  113:     unless (-e "$execdir/logs/lonnet.log") {	
  114: 	open(my $fh,">>$execdir/logs/lonnet.log");
  115: 	close $fh;
  116:     }
  117:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  118:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  119: }
  120: 
  121: sub logthis {
  122:     my $message=shift;
  123:     my $execdir=$perlvar{'lonDaemons'};
  124:     my $now=time;
  125:     my $local=localtime($now);
  126:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  127: 	print $fh "$local ($$): $message\n";
  128: 	close($fh);
  129:     }
  130:     return 1;
  131: }
  132: 
  133: sub logperm {
  134:     my $message=shift;
  135:     my $execdir=$perlvar{'lonDaemons'};
  136:     my $now=time;
  137:     my $local=localtime($now);
  138:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  139: 	print $fh "$now:$message:$local\n";
  140: 	close($fh);
  141:     }
  142:     return 1;
  143: }
  144: 
  145: sub create_connection {
  146:     my ($hostname,$lonid) = @_;
  147:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  148: 				     Type    => SOCK_STREAM,
  149: 				     Timeout => 10);
  150:     return 0 if (!$client);
  151:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
  152:     my $result = <$client>;
  153:     chomp($result);
  154:     return 1 if ($result eq 'done');
  155:     return 0;
  156: }
  157: 
  158: 
  159: # -------------------------------------------------- Non-critical communication
  160: sub subreply {
  161:     my ($cmd,$server)=@_;
  162:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  163:     #
  164:     #  With loncnew process trimming, there's a timing hole between lonc server
  165:     #  process exit and the master server picking up the listen on the AF_UNIX
  166:     #  socket.  In that time interval, a lock file will exist:
  167: 
  168:     my $lockfile=$peerfile.".lock";
  169:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  170: 	sleep(1);
  171:     }
  172:     # At this point, either a loncnew parent is listening or an old lonc
  173:     # or loncnew child is listening so we can connect or everything's dead.
  174:     #
  175:     #   We'll give the connection a few tries before abandoning it.  If
  176:     #   connection is not possible, we'll con_lost back to the client.
  177:     #   
  178:     my $client;
  179:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  180: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  181: 				      Type    => SOCK_STREAM,
  182: 				      Timeout => 10);
  183: 	if ($client) {
  184: 	    last;		# Connected!
  185: 	} else {
  186: 	    &create_connection(&hostname($server),$server);
  187: 	}
  188:         sleep(1);		# Try again later if failed connection.
  189:     }
  190:     my $answer;
  191:     if ($client) {
  192: 	print $client "sethost:$server:$cmd\n";
  193: 	$answer=<$client>;
  194: 	if (!$answer) { $answer="con_lost"; }
  195: 	chomp($answer);
  196:     } else {
  197: 	$answer = 'con_lost';	# Failed connection.
  198:     }
  199:     return $answer;
  200: }
  201: 
  202: sub reply {
  203:     my ($cmd,$server)=@_;
  204:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  205:     my $answer=subreply($cmd,$server);
  206:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  207:        &logthis("<font color=\"blue\">WARNING:".
  208:                 " $cmd to $server returned $answer</font>");
  209:     }
  210:     return $answer;
  211: }
  212: 
  213: # ----------------------------------------------------------- Send USR1 to lonc
  214: 
  215: sub reconlonc {
  216:     &logthis("Trying to reconnect lonc");
  217:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  218:     if (open(my $fh,"<$loncfile")) {
  219: 	my $loncpid=<$fh>;
  220:         chomp($loncpid);
  221:         if (kill 0 => $loncpid) {
  222: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  223:             kill USR1 => $loncpid;
  224:             sleep 1;
  225:          } else {
  226: 	    &logthis(
  227:                "<font color=\"blue\">WARNING:".
  228:                " lonc at pid $loncpid not responding, giving up</font>");
  229:         }
  230:     } else {
  231: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  232:     }
  233: }
  234: 
  235: # ------------------------------------------------------ Critical communication
  236: 
  237: sub critical {
  238:     my ($cmd,$server)=@_;
  239:     unless (&hostname($server)) {
  240:         &logthis("<font color=\"blue\">WARNING:".
  241:                " Critical message to unknown server ($server)</font>");
  242:         return 'no_such_host';
  243:     }
  244:     my $answer=reply($cmd,$server);
  245:     if ($answer eq 'con_lost') {
  246: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  247: 	my $answer=reply($cmd,$server);
  248:         if ($answer eq 'con_lost') {
  249:             my $now=time;
  250:             my $middlename=$cmd;
  251:             $middlename=substr($middlename,0,16);
  252:             $middlename=~s/\W//g;
  253:             my $dfilename=
  254:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  255:             $dumpcount++;
  256:             {
  257: 		my $dfh;
  258: 		if (open($dfh,">$dfilename")) {
  259: 		    print $dfh "$cmd\n"; 
  260: 		    close($dfh);
  261: 		}
  262:             }
  263:             sleep 2;
  264:             my $wcmd='';
  265:             {
  266: 		my $dfh;
  267: 		if (open($dfh,"<$dfilename")) {
  268: 		    $wcmd=<$dfh>; 
  269: 		    close($dfh);
  270: 		}
  271:             }
  272:             chomp($wcmd);
  273:             if ($wcmd eq $cmd) {
  274: 		&logthis("<font color=\"blue\">WARNING: ".
  275:                          "Connection buffer $dfilename: $cmd</font>");
  276:                 &logperm("D:$server:$cmd");
  277: 	        return 'con_delayed';
  278:             } else {
  279:                 &logthis("<font color=\"red\">CRITICAL:"
  280:                         ." Critical connection failed: $server $cmd</font>");
  281:                 &logperm("F:$server:$cmd");
  282:                 return 'con_failed';
  283:             }
  284:         }
  285:     }
  286:     return $answer;
  287: }
  288: 
  289: # ------------------------------------------- check if return value is an error
  290: 
  291: sub error {
  292:     my ($result) = @_;
  293:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  294: 	if ($2 == 2) { return undef; }
  295: 	return $1;
  296:     }
  297:     return undef;
  298: }
  299: 
  300: sub convert_and_load_session_env {
  301:     my ($lonidsdir,$handle)=@_;
  302:     my @profile;
  303:     {
  304: 	open(my $idf,"$lonidsdir/$handle.id");
  305: 	flock($idf,LOCK_SH);
  306: 	@profile=<$idf>;
  307: 	close($idf);
  308:     }
  309:     my %temp_env;
  310:     foreach my $line (@profile) {
  311: 	if ($line !~ m/=/) {
  312: 	    return 0;
  313: 	}
  314: 	chomp($line);
  315: 	my ($envname,$envvalue)=split(/=/,$line,2);
  316: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  317:     }
  318:     unlink("$lonidsdir/$handle.id");
  319:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  320: 	    0640)) {
  321: 	%disk_env = %temp_env;
  322: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  323: 	untie(%disk_env);
  324:     }
  325:     return 1;
  326: }
  327: 
  328: # ------------------------------------------- Transfer profile into environment
  329: my $env_loaded;
  330: sub transfer_profile_to_env {
  331:     my ($lonidsdir,$handle,$force_transfer) = @_;
  332:     if (!$force_transfer && $env_loaded) { return; } 
  333: 
  334:     if (!defined($lonidsdir)) {
  335: 	$lonidsdir = $perlvar{'lonIDsDir'};
  336:     }
  337:     if (!defined($handle)) {
  338:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  339:     }
  340: 
  341:     my $convert;
  342:     {
  343:     	open(my $idf,"$lonidsdir/$handle.id");
  344: 	flock($idf,LOCK_SH);
  345: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  346: 		&GDBM_READER(),0640)) {
  347: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  348: 	    untie(%disk_env);
  349: 	} else {
  350: 	    $convert = 1;
  351: 	}
  352:     }
  353:     if ($convert) {
  354: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  355: 	    &logthis("Failed to load session, or convert session.");
  356: 	}
  357:     }
  358: 
  359:     my %remove;
  360:     while ( my $envname = each(%env) ) {
  361:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  362:             if ($time < time-300) {
  363:                 $remove{$key}++;
  364:             }
  365:         }
  366:     }
  367: 
  368:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  369:     $env_loaded=1;
  370:     foreach my $expired_key (keys(%remove)) {
  371:         &delenv($expired_key);
  372:     }
  373: }
  374: 
  375: sub timed_flock {
  376:     my ($file,$lock_type) = @_;
  377:     my $failed=0;
  378:     eval {
  379: 	local $SIG{__DIE__}='DEFAULT';
  380: 	local $SIG{ALRM}=sub {
  381: 	    $failed=1;
  382: 	    die("failed lock");
  383: 	};
  384: 	alarm(13);
  385: 	flock($file,$lock_type);
  386: 	alarm(0);
  387:     };
  388:     if ($failed) {
  389: 	return undef;
  390:     } else {
  391: 	return 1;
  392:     }
  393: }
  394: 
  395: # ---------------------------------------------------------- Append Environment
  396: 
  397: sub appenv {
  398:     my %newenv=@_;
  399:     foreach my $key (keys(%newenv)) {
  400: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  401:             &logthis("<font color=\"blue\">WARNING: ".
  402:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  403:                 .'</font>');
  404: 	    delete($newenv{$key});
  405:         } else {
  406:             $env{$key}=$newenv{$key};
  407:         }
  408:     }
  409:     open(my $env_file,$env{'user.environment'});
  410:     if (&timed_flock($env_file,LOCK_EX)
  411: 	&&
  412: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  413: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  414: 	while (my ($key,$value) = each(%newenv)) {
  415: 	    $disk_env{$key} = $value;
  416: 	}
  417: 	untie(%disk_env);
  418:     }
  419:     return 'ok';
  420: }
  421: # ----------------------------------------------------- Delete from Environment
  422: 
  423: sub delenv {
  424:     my $delthis=shift;
  425:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  426:         &logthis("<font color=\"blue\">WARNING: ".
  427:                 "Attempt to delete from environment ".$delthis);
  428:         return 'error';
  429:     }
  430:     open(my $env_file,$env{'user.environment'});
  431:     if (&timed_flock($env_file,LOCK_EX)
  432: 	&&
  433: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  434: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  435: 	foreach my $key (keys(%disk_env)) {
  436: 	    if ($key=~/^$delthis/) { 
  437:                 delete($env{$key});
  438:                 delete($disk_env{$key});
  439:             }
  440: 	}
  441: 	untie(%disk_env);
  442:     }
  443:     return 'ok';
  444: }
  445: 
  446: sub get_env_multiple {
  447:     my ($name) = @_;
  448:     my @values;
  449:     if (defined($env{$name})) {
  450:         # exists is it an array
  451:         if (ref($env{$name})) {
  452:             @values=@{ $env{$name} };
  453:         } else {
  454:             $values[0]=$env{$name};
  455:         }
  456:     }
  457:     return(@values);
  458: }
  459: 
  460: # ------------------------------------------ Find out current server userload
  461: # there is a copy in lond
  462: sub userload {
  463:     my $numusers=0;
  464:     {
  465: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  466: 	my $filename;
  467: 	my $curtime=time;
  468: 	while ($filename=readdir(LONIDS)) {
  469: 	    if ($filename eq '.' || $filename eq '..') {next;}
  470: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  471: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  472: 	}
  473: 	closedir(LONIDS);
  474:     }
  475:     my $userloadpercent=0;
  476:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  477:     if ($maxuserload) {
  478: 	$userloadpercent=100*$numusers/$maxuserload;
  479:     }
  480:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  481:     return $userloadpercent;
  482: }
  483: 
  484: # ------------------------------------------ Fight off request when overloaded
  485: 
  486: sub overloaderror {
  487:     my ($r,$checkserver)=@_;
  488:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  489:     my $loadavg;
  490:     if ($checkserver eq $perlvar{'lonHostID'}) {
  491:        open(my $loadfile,'/proc/loadavg');
  492:        $loadavg=<$loadfile>;
  493:        $loadavg =~ s/\s.*//g;
  494:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  495:        close($loadfile);
  496:     } else {
  497:        $loadavg=&reply('load',$checkserver);
  498:     }
  499:     my $overload=$loadavg-100;
  500:     if ($overload>0) {
  501: 	$r->err_headers_out->{'Retry-After'}=$overload;
  502:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  503:         return 413;
  504:     }    
  505:     return '';
  506: }
  507: 
  508: # ------------------------------ Find server with least workload from spare.tab
  509: 
  510: sub spareserver {
  511:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  512:     my $spare_server;
  513:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  514:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  515:                                                      :  $userloadpercent;
  516:     
  517:     foreach my $try_server (@{ $spareid{'primary'} }) {
  518: 	($spare_server, $lowest_load) =
  519: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  520:     }
  521: 
  522:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  523: 
  524:     if (!$found_server) {
  525: 	foreach my $try_server (@{ $spareid{'default'} }) {
  526: 	    ($spare_server, $lowest_load) =
  527: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  528: 	}
  529:     }
  530: 
  531:     if (!$want_server_name) {
  532: 	$spare_server="http://".&hostname($spare_server);
  533:     }
  534:     return $spare_server;
  535: }
  536: 
  537: sub compare_server_load {
  538:     my ($try_server, $spare_server, $lowest_load) = @_;
  539: 
  540:     my $loadans     = &reply('load',    $try_server);
  541:     my $userloadans = &reply('userload',$try_server);
  542: 
  543:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  544: 	next; #didn't get a number from the server
  545:     }
  546: 
  547:     my $load;
  548:     if ($loadans =~ /\d/) {
  549: 	if ($userloadans =~ /\d/) {
  550: 	    #both are numbers, pick the bigger one
  551: 	    $load = ($loadans > $userloadans) ? $loadans 
  552: 		                              : $userloadans;
  553: 	} else {
  554: 	    $load = $loadans;
  555: 	}
  556:     } else {
  557: 	$load = $userloadans;
  558:     }
  559: 
  560:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  561: 	$spare_server = $try_server;
  562: 	$lowest_load  = $load;
  563:     }
  564:     return ($spare_server,$lowest_load);
  565: }
  566: # --------------------------------------------- Try to change a user's password
  567: 
  568: sub changepass {
  569:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  570:     $currentpass = &escape($currentpass);
  571:     $newpass     = &escape($newpass);
  572:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  573: 		       $server);
  574:     if (! $answer) {
  575: 	&logthis("No reply on password change request to $server ".
  576: 		 "by $uname in domain $udom.");
  577:     } elsif ($answer =~ "^ok") {
  578:         &logthis("$uname in $udom successfully changed their password ".
  579: 		 "on $server.");
  580:     } elsif ($answer =~ "^pwchange_failure") {
  581: 	&logthis("$uname in $udom was unable to change their password ".
  582: 		 "on $server.  The action was blocked by either lcpasswd ".
  583: 		 "or pwchange");
  584:     } elsif ($answer =~ "^non_authorized") {
  585:         &logthis("$uname in $udom did not get their password correct when ".
  586: 		 "attempting to change it on $server.");
  587:     } elsif ($answer =~ "^auth_mode_error") {
  588:         &logthis("$uname in $udom attempted to change their password despite ".
  589: 		 "not being locally or internally authenticated on $server.");
  590:     } elsif ($answer =~ "^unknown_user") {
  591:         &logthis("$uname in $udom attempted to change their password ".
  592: 		 "on $server but were unable to because $server is not ".
  593: 		 "their home server.");
  594:     } elsif ($answer =~ "^refused") {
  595: 	&logthis("$server refused to change $uname in $udom password because ".
  596: 		 "it was sent an unencrypted request to change the password.");
  597:     }
  598:     return $answer;
  599: }
  600: 
  601: # ----------------------- Try to determine user's current authentication scheme
  602: 
  603: sub queryauthenticate {
  604:     my ($uname,$udom)=@_;
  605:     my $uhome=&homeserver($uname,$udom);
  606:     if (!$uhome) {
  607: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  608: 	return 'no_host';
  609:     }
  610:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  611:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  612: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  613:     }
  614:     return $answer;
  615: }
  616: 
  617: # --------- Try to authenticate user from domain's lib servers (first this one)
  618: 
  619: sub authenticate {
  620:     my ($uname,$upass,$udom)=@_;
  621:     $upass=&escape($upass);
  622:     $uname= &LONCAPA::clean_username($uname);
  623:     my $uhome=&homeserver($uname,$udom,1);
  624:     if ((!$uhome) || ($uhome eq 'no_host')) {
  625: # Maybe the machine was offline and only re-appeared again recently?
  626:         &reconlonc();
  627: # One more
  628: 	my $uhome=&homeserver($uname,$udom,1);
  629: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  630: 	    &logthis("User $uname at $udom is unknown in authenticate");
  631: 	}
  632: 	return 'no_host';
  633:     }
  634:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  635:     if ($answer eq 'authorized') {
  636: 	&logthis("User $uname at $udom authorized by $uhome"); 
  637: 	return $uhome; 
  638:     }
  639:     if ($answer eq 'non_authorized') {
  640: 	&logthis("User $uname at $udom rejected by $uhome");
  641: 	return 'no_host'; 
  642:     }
  643:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  644:     return 'no_host';
  645: }
  646: 
  647: # ---------------------- Find the homebase for a user from domain's lib servers
  648: 
  649: my %homecache;
  650: sub homeserver {
  651:     my ($uname,$udom,$ignoreBadCache)=@_;
  652:     my $index="$uname:$udom";
  653: 
  654:     if (exists($homecache{$index})) { return $homecache{$index}; }
  655: 
  656:     my %servers = &get_servers($udom,'library');
  657:     foreach my $tryserver (keys(%servers)) {
  658:         next if ($ignoreBadCache ne 'true' && 
  659: 		 exists($badServerCache{$tryserver}));
  660: 
  661: 	my $answer=reply("home:$udom:$uname",$tryserver);
  662: 	if ($answer eq 'found') {
  663: 	    delete($badServerCache{$tryserver}); 
  664: 	    return $homecache{$index}=$tryserver;
  665: 	} elsif ($answer eq 'no_host') {
  666: 	    $badServerCache{$tryserver}=1;
  667: 	}
  668:     }    
  669:     return 'no_host';
  670: }
  671: 
  672: # ------------------------------------- Find the usernames behind a list of IDs
  673: 
  674: sub idget {
  675:     my ($udom,@ids)=@_;
  676:     my %returnhash=();
  677:     
  678:     my %servers = &get_servers($udom,'library');
  679:     foreach my $tryserver (keys(%servers)) {
  680: 	my $idlist=join('&',@ids);
  681: 	$idlist=~tr/A-Z/a-z/; 
  682: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  683: 	my @answer=();
  684: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  685: 	    @answer=split(/\&/,$reply);
  686: 	}                    ;
  687: 	my $i;
  688: 	for ($i=0;$i<=$#ids;$i++) {
  689: 	    if ($answer[$i]) {
  690: 		$returnhash{$ids[$i]}=$answer[$i];
  691: 	    } 
  692: 	}
  693:     } 
  694:     return %returnhash;
  695: }
  696: 
  697: # ------------------------------------- Find the IDs behind a list of usernames
  698: 
  699: sub idrget {
  700:     my ($udom,@unames)=@_;
  701:     my %returnhash=();
  702:     foreach my $uname (@unames) {
  703:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  704:     }
  705:     return %returnhash;
  706: }
  707: 
  708: # ------------------------------- Store away a list of names and associated IDs
  709: 
  710: sub idput {
  711:     my ($udom,%ids)=@_;
  712:     my %servers=();
  713:     foreach my $uname (keys(%ids)) {
  714: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  715:         my $uhom=&homeserver($uname,$udom);
  716:         if ($uhom ne 'no_host') {
  717:             my $id=&escape($ids{$uname});
  718:             $id=~tr/A-Z/a-z/;
  719:             my $esc_unam=&escape($uname);
  720: 	    if ($servers{$uhom}) {
  721: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  722:             } else {
  723:                 $servers{$uhom}=$id.'='.$esc_unam;
  724:             }
  725:         }
  726:     }
  727:     foreach my $server (keys(%servers)) {
  728:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  729:     }
  730: }
  731: 
  732: # ------------------------------------------- get items from domain db files   
  733: 
  734: sub get_dom {
  735:     my ($namespace,$storearr,$udom,$uhome)=@_;
  736:     my $items='';
  737:     foreach my $item (@$storearr) {
  738:         $items.=&escape($item).'&';
  739:     }
  740:     $items=~s/\&$//;
  741:     if (!$udom) {
  742:         $udom=$env{'user.domain'};
  743:         if (defined(&domain($udom,'primary'))) {
  744:             $uhome=&domain($udom,'primary');
  745:         } else {
  746:             $uhome eq '';
  747:         }
  748:     } else {
  749:         if (!$uhome) {
  750:             if (defined(&domain($udom,'primary'))) {
  751:                 $uhome=&domain($udom,'primary');
  752:             }
  753:         }
  754:     }
  755:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  756:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  757:         my %returnhash;
  758:         if ($rep =~ /^error: 2 /) {
  759:             return %returnhash;
  760:         }
  761:         my @pairs=split(/\&/,$rep);
  762:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  763:             return @pairs;
  764:         }
  765:         my %returnhash=();
  766:         my $i=0;
  767:         foreach my $item (@$storearr) {
  768:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  769:             $i++;
  770:         }
  771:         return %returnhash;
  772:     } else {
  773:         &logthis("get_dom failed - no homeserver and/or domain");
  774:     }
  775: }
  776: 
  777: # -------------------------------------------- put items in domain db files 
  778: 
  779: sub put_dom {
  780:     my ($namespace,$storehash,$udom,$uhome)=@_;
  781:     if (!$udom) {
  782:         $udom=$env{'user.domain'};
  783:         if (defined(&domain($udom,'primary'))) {
  784:             $uhome=&domain($udom,'primary');
  785:         } else {
  786:             $uhome eq '';
  787:         }
  788:     } else {
  789:         if (!$uhome) {
  790:             if (defined(&domain($udom,'primary'))) {
  791:                 $uhome=&domain($udom,'primary');
  792:             }
  793:         }
  794:     } 
  795:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  796:         my $items='';
  797:         foreach my $item (keys(%$storehash)) {
  798:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  799:         }
  800:         $items=~s/\&$//;
  801:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  802:     } else {
  803:         &logthis("put_dom failed - no homeserver and/or domain");
  804:     }
  805: }
  806: 
  807: sub retrieve_inst_usertypes {
  808:     my ($udom) = @_;
  809:     my (%returnhash,@order);
  810:     if (defined(&domain($udom,'primary'))) {
  811:         my $uhome=&domain($udom,'primary');
  812:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  813:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  814:         my @pairs=split(/\&/,$hashitems);
  815:         foreach my $item (@pairs) {
  816:             my ($key,$value)=split(/=/,$item,2);
  817:             $key = &unescape($key);
  818:             next if ($key =~ /^error: 2 /);
  819:             $returnhash{$key}=&thaw_unescape($value);
  820:         }
  821:         my @esc_order = split(/\&/,$orderitems);
  822:         foreach my $item (@esc_order) {
  823:             push(@order,&unescape($item));
  824:         }
  825:     } else {
  826:         &logthis("get_dom failed - no primary domain server for $udom");
  827:     }
  828:     return (\%returnhash,\@order);
  829: }
  830: 
  831: sub is_domainimage {
  832:     my ($url) = @_;
  833:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  834:         if (&domain($1) ne '') {
  835:             return '1';
  836:         }
  837:     }
  838:     return;
  839: }
  840: 
  841: # --------------------------------------------------- Assign a key to a student
  842: 
  843: sub assign_access_key {
  844: #
  845: # a valid key looks like uname:udom#comments
  846: # comments are being appended
  847: #
  848:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  849:     $kdom=
  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  851:     $knum=
  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  853:     $cdom=
  854:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  855:     $cnum=
  856:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  857:     $udom=$env{'user.name'} unless (defined($udom));
  858:     $uname=$env{'user.domain'} unless (defined($uname));
  859:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  860:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  861:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  862:                                                   # assigned to this person
  863:                                                   # - this should not happen,
  864:                                                   # unless something went wrong
  865:                                                   # the first time around
  866: # ready to assign
  867:         $logentry=$1.'; '.$logentry;
  868:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  869:                                                  $kdom,$knum) eq 'ok') {
  870: # key now belongs to user
  871: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  872:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  873:                 &appenv('environment.'.$envkey => $ckey);
  874:                 return 'ok';
  875:             } else {
  876:                 return 
  877:   'error: Count not permanently assign key, will need to be re-entered later.';
  878: 	    }
  879:         } else {
  880:             return 'error: Could not assign key, try again later.';
  881:         }
  882:     } elsif (!$existing{$ckey}) {
  883: # the key does not exist
  884: 	return 'error: The key does not exist';
  885:     } else {
  886: # the key is somebody else's
  887: 	return 'error: The key is already in use';
  888:     }
  889: }
  890: 
  891: # ------------------------------------------ put an additional comment on a key
  892: 
  893: sub comment_access_key {
  894: #
  895: # a valid key looks like uname:udom#comments
  896: # comments are being appended
  897: #
  898:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  899:     $cdom=
  900:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  901:     $cnum=
  902:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  903:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  904:     if ($existing{$ckey}) {
  905:         $existing{$ckey}.='; '.$logentry;
  906: # ready to assign
  907:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  908:                                                  $cdom,$cnum) eq 'ok') {
  909: 	    return 'ok';
  910:         } else {
  911: 	    return 'error: Count not store comment.';
  912:         }
  913:     } else {
  914: # the key does not exist
  915: 	return 'error: The key does not exist';
  916:     }
  917: }
  918: 
  919: # ------------------------------------------------------ Generate a set of keys
  920: 
  921: sub generate_access_keys {
  922:     my ($number,$cdom,$cnum,$logentry)=@_;
  923:     $cdom=
  924:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  925:     $cnum=
  926:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  927:     unless (&allowed('mky',$cdom)) { return 0; }
  928:     unless (($cdom) && ($cnum)) { return 0; }
  929:     if ($number>10000) { return 0; }
  930:     sleep(2); # make sure don't get same seed twice
  931:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  932:     my $total=0;
  933:     for (my $i=1;$i<=$number;$i++) {
  934:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  935:                   sprintf("%lx",int(100000*rand)).'-'.
  936:                   sprintf("%lx",int(100000*rand));
  937:        $newkey=~s/1/g/g; # folks mix up 1 and l
  938:        $newkey=~s/0/h/g; # and also 0 and O
  939:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  940:        if ($existing{$newkey}) {
  941:            $i--;
  942:        } else {
  943: 	  if (&put('accesskeys',
  944:               { $newkey => '# generated '.localtime().
  945:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  946:                            '; '.$logentry },
  947: 		   $cdom,$cnum) eq 'ok') {
  948:               $total++;
  949: 	  }
  950:        }
  951:     }
  952:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  953:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  954:     return $total;
  955: }
  956: 
  957: # ------------------------------------------------------- Validate an accesskey
  958: 
  959: sub validate_access_key {
  960:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  961:     $cdom=
  962:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  963:     $cnum=
  964:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  965:     $udom=$env{'user.domain'} unless (defined($udom));
  966:     $uname=$env{'user.name'} unless (defined($uname));
  967:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  968:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  969: }
  970: 
  971: # ------------------------------------- Find the section of student in a course
  972: sub devalidate_getsection_cache {
  973:     my ($udom,$unam,$courseid)=@_;
  974:     my $hashid="$udom:$unam:$courseid";
  975:     &devalidate_cache_new('getsection',$hashid);
  976: }
  977: 
  978: sub courseid_to_courseurl {
  979:     my ($courseid) = @_;
  980:     #already url style courseid
  981:     return $courseid if ($courseid =~ m{^/});
  982: 
  983:     if (exists($env{'course.'.$courseid.'.num'})) {
  984: 	my $cnum = $env{'course.'.$courseid.'.num'};
  985: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  986: 	return "/$cdom/$cnum";
  987:     }
  988: 
  989:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  990:     if (exists($courseinfo{'num'})) {
  991: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  992:     }
  993: 
  994:     return undef;
  995: }
  996: 
  997: sub getsection {
  998:     my ($udom,$unam,$courseid)=@_;
  999:     my $cachetime=1800;
 1000: 
 1001:     my $hashid="$udom:$unam:$courseid";
 1002:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1003:     if (defined($cached)) { return $result; }
 1004: 
 1005:     my %Pending; 
 1006:     my %Expired;
 1007:     #
 1008:     # Each role can either have not started yet (pending), be active, 
 1009:     #    or have expired.
 1010:     #
 1011:     # If there is an active role, we are done.
 1012:     #
 1013:     # If there is more than one role which has not started yet, 
 1014:     #     choose the one which will start sooner
 1015:     # If there is one role which has not started yet, return it.
 1016:     #
 1017:     # If there is more than one expired role, choose the one which ended last.
 1018:     # If there is a role which has expired, return it.
 1019:     #
 1020:     $courseid = &courseid_to_courseurl($courseid);
 1021:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1022:     foreach my $key (keys(%roleshash)) {
 1023:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1024:         my $section=$1;
 1025:         if ($key eq $courseid.'_st') { $section=''; }
 1026:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1027:         my $now=time;
 1028:         if (defined($end) && $end && ($now > $end)) {
 1029:             $Expired{$end}=$section;
 1030:             next;
 1031:         }
 1032:         if (defined($start) && $start && ($now < $start)) {
 1033:             $Pending{$start}=$section;
 1034:             next;
 1035:         }
 1036:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1037:     }
 1038:     #
 1039:     # Presumedly there will be few matching roles from the above
 1040:     # loop and the sorting time will be negligible.
 1041:     if (scalar(keys(%Pending))) {
 1042:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1043:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1044:     } 
 1045:     if (scalar(keys(%Expired))) {
 1046:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1047:         my $time = pop(@sorted);
 1048:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1049:     }
 1050:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1051: }
 1052: 
 1053: sub save_cache {
 1054:     &purge_remembered();
 1055:     #&Apache::loncommon::validate_page();
 1056:     undef(%env);
 1057:     undef($env_loaded);
 1058: }
 1059: 
 1060: my $to_remember=-1;
 1061: my %remembered;
 1062: my %accessed;
 1063: my $kicks=0;
 1064: my $hits=0;
 1065: sub make_key {
 1066:     my ($name,$id) = @_;
 1067:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
 1068:     return &escape($name.':'.$id);
 1069: }
 1070: 
 1071: sub devalidate_cache_new {
 1072:     my ($name,$id,$debug) = @_;
 1073:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1074:     $id=&make_key($name,$id);
 1075:     $memcache->delete($id);
 1076:     delete($remembered{$id});
 1077:     delete($accessed{$id});
 1078: }
 1079: 
 1080: sub is_cached_new {
 1081:     my ($name,$id,$debug) = @_;
 1082:     $id=&make_key($name,$id);
 1083:     if (exists($remembered{$id})) {
 1084: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1085: 	$accessed{$id}=[&gettimeofday()];
 1086: 	$hits++;
 1087: 	return ($remembered{$id},1);
 1088:     }
 1089:     my $value = $memcache->get($id);
 1090:     if (!(defined($value))) {
 1091: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1092: 	return (undef,undef);
 1093:     }
 1094:     if ($value eq '__undef__') {
 1095: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1096: 	$value=undef;
 1097:     }
 1098:     &make_room($id,$value,$debug);
 1099:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1100:     return ($value,1);
 1101: }
 1102: 
 1103: sub do_cache_new {
 1104:     my ($name,$id,$value,$time,$debug) = @_;
 1105:     $id=&make_key($name,$id);
 1106:     my $setvalue=$value;
 1107:     if (!defined($setvalue)) {
 1108: 	$setvalue='__undef__';
 1109:     }
 1110:     if (!defined($time) ) {
 1111: 	$time=600;
 1112:     }
 1113:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1114:     $memcache->set($id,$setvalue,$time);
 1115:     # need to make a copy of $value
 1116:     #&make_room($id,$value,$debug);
 1117:     return $value;
 1118: }
 1119: 
 1120: sub make_room {
 1121:     my ($id,$value,$debug)=@_;
 1122:     $remembered{$id}=$value;
 1123:     if ($to_remember<0) { return; }
 1124:     $accessed{$id}=[&gettimeofday()];
 1125:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1126:     my $to_kick;
 1127:     my $max_time=0;
 1128:     foreach my $other (keys(%accessed)) {
 1129: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1130: 	    $to_kick=$other;
 1131: 	    $max_time=&tv_interval($accessed{$other});
 1132: 	}
 1133:     }
 1134:     delete($remembered{$to_kick});
 1135:     delete($accessed{$to_kick});
 1136:     $kicks++;
 1137:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1138:     return;
 1139: }
 1140: 
 1141: sub purge_remembered {
 1142:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1143:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1144:     undef(%remembered);
 1145:     undef(%accessed);
 1146: }
 1147: # ------------------------------------- Read an entry from a user's environment
 1148: 
 1149: sub userenvironment {
 1150:     my ($udom,$unam,@what)=@_;
 1151:     my %returnhash=();
 1152:     my @answer=split(/\&/,
 1153:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1154:                       &homeserver($unam,$udom)));
 1155:     my $i;
 1156:     for ($i=0;$i<=$#what;$i++) {
 1157: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1158:     }
 1159:     return %returnhash;
 1160: }
 1161: 
 1162: # ---------------------------------------------------------- Get a studentphoto
 1163: sub studentphoto {
 1164:     my ($udom,$unam,$ext) = @_;
 1165:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1166:     if (defined($env{'request.course.id'})) {
 1167:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1168:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1169:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1170:             } else {
 1171:                 my ($result,$perm_reqd)=
 1172: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1173:                 if ($result eq 'ok') {
 1174:                     if (!($perm_reqd eq 'yes')) {
 1175:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1176:                     }
 1177:                 }
 1178:             }
 1179:         }
 1180:     } else {
 1181:         my ($result,$perm_reqd) = 
 1182: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1183:         if ($result eq 'ok') {
 1184:             if (!($perm_reqd eq 'yes')) {
 1185:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1186:             }
 1187:         }
 1188:     }
 1189:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1190: }
 1191: 
 1192: sub retrievestudentphoto {
 1193:     my ($udom,$unam,$ext,$type) = @_;
 1194:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1195:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1196:     if ($ret eq 'ok') {
 1197:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1198:         if ($type eq 'thumbnail') {
 1199:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1200:         }
 1201:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1202:         return $tokenurl;
 1203:     } else {
 1204:         if ($type eq 'thumbnail') {
 1205:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1206:         } else { 
 1207:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1208:         }
 1209:     }
 1210: }
 1211: 
 1212: # -------------------------------------------------------------------- New chat
 1213: 
 1214: sub chatsend {
 1215:     my ($newentry,$anon,$group)=@_;
 1216:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1217:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1218:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1219:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1220: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1221: 		   &escape($newentry)).':'.$group,$chome);
 1222: }
 1223: 
 1224: # ------------------------------------------ Find current version of a resource
 1225: 
 1226: sub getversion {
 1227:     my $fname=&clutter(shift);
 1228:     unless ($fname=~/^\/res\//) { return -1; }
 1229:     return &currentversion(&filelocation('',$fname));
 1230: }
 1231: 
 1232: sub currentversion {
 1233:     my $fname=shift;
 1234:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1235:     if (defined($cached)) { return $result; }
 1236:     my $author=$fname;
 1237:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1238:     my ($udom,$uname)=split(/\//,$author);
 1239:     my $home=homeserver($uname,$udom);
 1240:     if ($home eq 'no_host') { 
 1241:         return -1; 
 1242:     }
 1243:     my $answer=reply("currentversion:$fname",$home);
 1244:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1245: 	return -1;
 1246:     }
 1247:     return &do_cache_new('resversion',$fname,$answer,600);
 1248: }
 1249: 
 1250: # ----------------------------- Subscribe to a resource, return URL if possible
 1251: 
 1252: sub subscribe {
 1253:     my $fname=shift;
 1254:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1255:     $fname=~s/[\n\r]//g;
 1256:     my $author=$fname;
 1257:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1258:     my ($udom,$uname)=split(/\//,$author);
 1259:     my $home=homeserver($uname,$udom);
 1260:     if ($home eq 'no_host') {
 1261:         return 'not_found';
 1262:     }
 1263:     my $answer=reply("sub:$fname",$home);
 1264:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1265: 	$answer.=' by '.$home;
 1266:     }
 1267:     return $answer;
 1268: }
 1269:     
 1270: # -------------------------------------------------------------- Replicate file
 1271: 
 1272: sub repcopy {
 1273:     my $filename=shift;
 1274:     $filename=~s/\/+/\//g;
 1275:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1276:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1277:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1278: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1279: 	return &repcopy_userfile($filename);
 1280:     }
 1281:     $filename=~s/[\n\r]//g;
 1282:     my $transname="$filename.in.transfer";
 1283: # FIXME: this should flock
 1284:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1285:     my $remoteurl=subscribe($filename);
 1286:     if ($remoteurl =~ /^con_lost by/) {
 1287: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1288:            return 'unavailable';
 1289:     } elsif ($remoteurl eq 'not_found') {
 1290: 	   #&logthis("Subscribe returned not_found: $filename");
 1291: 	   return 'not_found';
 1292:     } elsif ($remoteurl =~ /^rejected by/) {
 1293: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1294:            return 'forbidden';
 1295:     } elsif ($remoteurl eq 'directory') {
 1296:            return 'ok';
 1297:     } else {
 1298:         my $author=$filename;
 1299:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1300:         my ($udom,$uname)=split(/\//,$author);
 1301:         my $home=homeserver($uname,$udom);
 1302:         unless ($home eq $perlvar{'lonHostID'}) {
 1303:            my @parts=split(/\//,$filename);
 1304:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1305:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1306:                &logthis("Malconfiguration for replication: $filename");
 1307: 	       return 'bad_request';
 1308:            }
 1309:            my $count;
 1310:            for ($count=5;$count<$#parts;$count++) {
 1311:                $path.="/$parts[$count]";
 1312:                if ((-e $path)!=1) {
 1313: 		   mkdir($path,0777);
 1314:                }
 1315:            }
 1316:            my $ua=new LWP::UserAgent;
 1317:            my $request=new HTTP::Request('GET',"$remoteurl");
 1318:            my $response=$ua->request($request,$transname);
 1319:            if ($response->is_error()) {
 1320: 	       unlink($transname);
 1321:                my $message=$response->status_line;
 1322:                &logthis("<font color=\"blue\">WARNING:"
 1323:                        ." LWP get: $message: $filename</font>");
 1324:                return 'unavailable';
 1325:            } else {
 1326: 	       if ($remoteurl!~/\.meta$/) {
 1327:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1328:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1329:                   if ($mresponse->is_error()) {
 1330: 		      unlink($filename.'.meta');
 1331:                       &logthis(
 1332:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1333:                   }
 1334: 	       }
 1335:                rename($transname,$filename);
 1336:                return 'ok';
 1337:            }
 1338:        }
 1339:     }
 1340: }
 1341: 
 1342: # ------------------------------------------------ Get server side include body
 1343: sub ssi_body {
 1344:     my ($filelink,%form)=@_;
 1345:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1346:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1347:     }
 1348:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1349:                                      &ssi($filelink,%form));
 1350:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1351:     $output=~s/^.*?\<body[^\>]*\>//si;
 1352:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1353:     return $output;
 1354: }
 1355: 
 1356: # --------------------------------------------------------- Server Side Include
 1357: 
 1358: sub absolute_url {
 1359:     my ($host_name) = @_;
 1360:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1361:     if ($host_name eq '') {
 1362: 	$host_name = $ENV{'SERVER_NAME'};
 1363:     }
 1364:     return $protocol.$host_name;
 1365: }
 1366: 
 1367: sub ssi {
 1368: 
 1369:     my ($fn,%form)=@_;
 1370: 
 1371:     my $ua=new LWP::UserAgent;
 1372:     
 1373:     my $request;
 1374: 
 1375:     $form{'no_update_last_known'}=1;
 1376: 
 1377:     if (%form) {
 1378:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1379:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1380:     } else {
 1381:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1382:     }
 1383: 
 1384:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1385:     my $response=$ua->request($request);
 1386: 
 1387:     return $response->content;
 1388: }
 1389: 
 1390: sub externalssi {
 1391:     my ($url)=@_;
 1392:     my $ua=new LWP::UserAgent;
 1393:     my $request=new HTTP::Request('GET',$url);
 1394:     my $response=$ua->request($request);
 1395:     return $response->content;
 1396: }
 1397: 
 1398: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1399: 
 1400: sub allowuploaded {
 1401:     my ($srcurl,$url)=@_;
 1402:     $url=&clutter(&declutter($url));
 1403:     my $dir=$url;
 1404:     $dir=~s/\/[^\/]+$//;
 1405:     my %httpref=();
 1406:     my $httpurl=&hreflocation('',$url);
 1407:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1408:     &Apache::lonnet::appenv(%httpref);
 1409: }
 1410: 
 1411: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1412: # input: action, courseID, current domain, intended
 1413: #        path to file, source of file, instruction to parse file for objects,
 1414: #        ref to hash for embedded objects,
 1415: #        ref to hash for codebase of java objects.
 1416: #
 1417: # output: url to file (if action was uploaddoc), 
 1418: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1419: #
 1420: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1421: # course.
 1422: #
 1423: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1424: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1425: #          course's home server.
 1426: #
 1427: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1428: #          be copied from $source (current location) to 
 1429: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1430: #         and will then be copied to
 1431: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1432: #         course's home server.
 1433: #
 1434: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1435: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1436: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1437: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1438: #         in course's home server.
 1439: #
 1440: 
 1441: sub process_coursefile {
 1442:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1443:     my $fetchresult;
 1444:     my $home=&homeserver($docuname,$docudom);
 1445:     if ($action eq 'propagate') {
 1446:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1447: 			     $home);
 1448:     } else {
 1449:         my $fpath = '';
 1450:         my $fname = $file;
 1451:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1452:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1453:         my $filepath = &build_filepath($fpath);
 1454:         if ($action eq 'copy') {
 1455:             if ($source eq '') {
 1456:                 $fetchresult = 'no source file';
 1457:                 return $fetchresult;
 1458:             } else {
 1459:                 my $destination = $filepath.'/'.$fname;
 1460:                 rename($source,$destination);
 1461:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1462:                                  $home);
 1463:             }
 1464:         } elsif ($action eq 'uploaddoc') {
 1465:             open(my $fh,'>'.$filepath.'/'.$fname);
 1466:             print $fh $env{'form.'.$source};
 1467:             close($fh);
 1468:             if ($parser eq 'parse') {
 1469:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1470:                 unless ($parse_result eq 'ok') {
 1471:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1472:                 }
 1473:             }
 1474:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1475:                                  $home);
 1476:             if ($fetchresult eq 'ok') {
 1477:                 return '/uploaded/'.$fpath.'/'.$fname;
 1478:             } else {
 1479:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1480:                         ' to host '.$home.': '.$fetchresult);
 1481:                 return '/adm/notfound.html';
 1482:             }
 1483:         }
 1484:     }
 1485:     unless ( $fetchresult eq 'ok') {
 1486:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1487:              ' to host '.$home.': '.$fetchresult);
 1488:     }
 1489:     return $fetchresult;
 1490: }
 1491: 
 1492: sub build_filepath {
 1493:     my ($fpath) = @_;
 1494:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1495:     unless ($fpath eq '') {
 1496:         my @parts=split('/',$fpath);
 1497:         foreach my $part (@parts) {
 1498:             $filepath.= '/'.$part;
 1499:             if ((-e $filepath)!=1) {
 1500:                 mkdir($filepath,0777);
 1501:             }
 1502:         }
 1503:     }
 1504:     return $filepath;
 1505: }
 1506: 
 1507: sub store_edited_file {
 1508:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1509:     my $file = $primary_url;
 1510:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1511:     my $fpath = '';
 1512:     my $fname = $file;
 1513:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1514:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1515:     my $filepath = &build_filepath($fpath);
 1516:     open(my $fh,'>'.$filepath.'/'.$fname);
 1517:     print $fh $content;
 1518:     close($fh);
 1519:     my $home=&homeserver($docuname,$docudom);
 1520:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1521: 			  $home);
 1522:     if ($$fetchresult eq 'ok') {
 1523:         return '/uploaded/'.$fpath.'/'.$fname;
 1524:     } else {
 1525:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1526: 		 ' to host '.$home.': '.$$fetchresult);
 1527:         return '/adm/notfound.html';
 1528:     }
 1529: }
 1530: 
 1531: sub clean_filename {
 1532:     my ($fname,$args)=@_;
 1533: # Replace Windows backslashes by forward slashes
 1534:     $fname=~s/\\/\//g;
 1535:     if (!$args->{'keep_path'}) {
 1536:         # Get rid of everything but the actual filename
 1537: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1538:     }
 1539: # Replace spaces by underscores
 1540:     $fname=~s/\s+/\_/g;
 1541: # Replace all other weird characters by nothing
 1542:     $fname=~s{[^/\w\.\-]}{}g;
 1543: # Replace all .\d. sequences with _\d. so they no longer look like version
 1544: # numbers
 1545:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1546:     return $fname;
 1547: }
 1548: 
 1549: # --------------- Take an uploaded file and put it into the userfiles directory
 1550: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1551: #                    the desired filenam is in $env{"form.$formname.filename"}
 1552: #        $coursedoc - if true up to the current course
 1553: #                     if false
 1554: #        $subdir - directory in userfile to store the file into
 1555: #        $parser - instruction to parse file for objects ($parser = parse)    
 1556: #        $allfiles - reference to hash for embedded objects
 1557: #        $codebase - reference to hash for codebase of java objects
 1558: #        $desuname - username for permanent storage of uploaded file
 1559: #        $dsetudom - domain for permanaent storage of uploaded file
 1560: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1561: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1562: # 
 1563: # output: url of file in userspace, or error: <message> 
 1564: #             or /adm/notfound.html if failure to upload occurse
 1565: 
 1566: 
 1567: sub userfileupload {
 1568:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1569:         $destudom,$thumbwidth,$thumbheight)=@_;
 1570:     if (!defined($subdir)) { $subdir='unknown'; }
 1571:     my $fname=$env{'form.'.$formname.'.filename'};
 1572:     $fname=&clean_filename($fname);
 1573: # See if there is anything left
 1574:     unless ($fname) { return 'error: no uploaded file'; }
 1575:     chop($env{'form.'.$formname});
 1576:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1577:         my $now = time;
 1578:         my $filepath = 'tmp/helprequests/'.$now;
 1579:         my @parts=split(/\//,$filepath);
 1580:         my $fullpath = $perlvar{'lonDaemons'};
 1581:         for (my $i=0;$i<@parts;$i++) {
 1582:             $fullpath .= '/'.$parts[$i];
 1583:             if ((-e $fullpath)!=1) {
 1584:                 mkdir($fullpath,0777);
 1585:             }
 1586:         }
 1587:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1588:         print $fh $env{'form.'.$formname};
 1589:         close($fh);
 1590:         return $fullpath.'/'.$fname;
 1591:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1592:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1593:                        '_'.$env{'user.domain'}.'/pending';
 1594:         my @parts=split(/\//,$filepath);
 1595:         my $fullpath = $perlvar{'lonDaemons'};
 1596:         for (my $i=0;$i<@parts;$i++) {
 1597:             $fullpath .= '/'.$parts[$i];
 1598:             if ((-e $fullpath)!=1) {
 1599:                 mkdir($fullpath,0777);
 1600:             }
 1601:         }
 1602:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1603:         print $fh $env{'form.'.$formname};
 1604:         close($fh);
 1605:         return $fullpath.'/'.$fname;
 1606:     }
 1607:     
 1608: # Create the directory if not present
 1609:     $fname="$subdir/$fname";
 1610:     if ($coursedoc) {
 1611: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1612: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1613:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1614:             return &finishuserfileupload($docuname,$docudom,
 1615: 					 $formname,$fname,$parser,$allfiles,
 1616: 					 $codebase,$thumbwidth,$thumbheight);
 1617:         } else {
 1618:             $fname=$env{'form.folder'}.'/'.$fname;
 1619:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1620: 				       $fname,$formname,$parser,
 1621: 				       $allfiles,$codebase);
 1622:         }
 1623:     } elsif (defined($destuname)) {
 1624:         my $docuname=$destuname;
 1625:         my $docudom=$destudom;
 1626: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1627: 				     $parser,$allfiles,$codebase,
 1628:                                      $thumbwidth,$thumbheight);
 1629:         
 1630:     } else {
 1631:         my $docuname=$env{'user.name'};
 1632:         my $docudom=$env{'user.domain'};
 1633:         if (exists($env{'form.group'})) {
 1634:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1635:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1636:         }
 1637: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1638: 				     $parser,$allfiles,$codebase,
 1639:                                      $thumbwidth,$thumbheight);
 1640:     }
 1641: }
 1642: 
 1643: sub finishuserfileupload {
 1644:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1645:         $thumbwidth,$thumbheight) = @_;
 1646:     my $path=$docudom.'/'.$docuname.'/';
 1647:     my $filepath=$perlvar{'lonDocRoot'};
 1648:     my ($fnamepath,$file,$fetchthumb);
 1649:     $file=$fname;
 1650:     if ($fname=~m|/|) {
 1651:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1652: 	$path.=$fnamepath.'/';
 1653:     }
 1654:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1655:     my $count;
 1656:     for ($count=4;$count<=$#parts;$count++) {
 1657:         $filepath.="/$parts[$count]";
 1658:         if ((-e $filepath)!=1) {
 1659: 	    mkdir($filepath,0777);
 1660:         }
 1661:     }
 1662: # Save the file
 1663:     {
 1664: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1665: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1666: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1667: 	    return '/adm/notfound.html';
 1668: 	}
 1669: 	if (!print FH ($env{'form.'.$formname})) {
 1670: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1671: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1672: 	    return '/adm/notfound.html';
 1673: 	}
 1674: 	close(FH);
 1675:     }
 1676:     if ($parser eq 'parse') {
 1677:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1678: 						   $codebase);
 1679:         unless ($parse_result eq 'ok') {
 1680:             &logthis('Failed to parse '.$filepath.$file.
 1681: 		     ' for embedded media: '.$parse_result); 
 1682:         }
 1683:     }
 1684:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1685:         my $input = $filepath.'/'.$file;
 1686:         my $output = $filepath.'/'.'tn-'.$file;
 1687:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1688:         system("convert -sample $thumbsize $input $output");
 1689:         if (-e $filepath.'/'.'tn-'.$file) {
 1690:             $fetchthumb  = 1; 
 1691:         }
 1692:     }
 1693:  
 1694: # Notify homeserver to grep it
 1695: #
 1696:     my $docuhome=&homeserver($docuname,$docudom);
 1697:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1698:     if ($fetchresult eq 'ok') {
 1699:         if ($fetchthumb) {
 1700:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1701:             if ($thumbresult ne 'ok') {
 1702:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1703:                          $docuhome.': '.$thumbresult);
 1704:             }
 1705:         }
 1706: #
 1707: # Return the URL to it
 1708:         return '/uploaded/'.$path.$file;
 1709:     } else {
 1710:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1711: 		 ': '.$fetchresult);
 1712:         return '/adm/notfound.html';
 1713:     }
 1714: }
 1715: 
 1716: sub extract_embedded_items {
 1717:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1718:     my @state = ();
 1719:     my %javafiles = (
 1720:                       codebase => '',
 1721:                       code => '',
 1722:                       archive => ''
 1723:                     );
 1724:     my %mediafiles = (
 1725:                       src => '',
 1726:                       movie => '',
 1727:                      );
 1728:     my $p;
 1729:     if ($content) {
 1730:         $p = HTML::LCParser->new($content);
 1731:     } else {
 1732:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1733:     }
 1734:     while (my $t=$p->get_token()) {
 1735: 	if ($t->[0] eq 'S') {
 1736: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1737: 	    push (@state, $tagname);
 1738:             if (lc($tagname) eq 'allow') {
 1739:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1740:             }
 1741: 	    if (lc($tagname) eq 'img') {
 1742: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1743: 	    }
 1744:             if (lc($tagname) eq 'script') {
 1745:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1746:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1747:                 } else {
 1748:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1749:                 }
 1750:             }
 1751:             if (lc($tagname) eq 'link') {
 1752:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1753:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1754:                 }
 1755:             }
 1756: 	    if (lc($tagname) eq 'object' ||
 1757: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1758: 		foreach my $item (keys(%javafiles)) {
 1759: 		    $javafiles{$item} = '';
 1760: 		}
 1761: 	    }
 1762: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1763: 		my $name = lc($attr->{'name'});
 1764: 		foreach my $item (keys(%javafiles)) {
 1765: 		    if ($name eq $item) {
 1766: 			$javafiles{$item} = $attr->{'value'};
 1767: 			last;
 1768: 		    }
 1769: 		}
 1770: 		foreach my $item (keys(%mediafiles)) {
 1771: 		    if ($name eq $item) {
 1772: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1773: 			last;
 1774: 		    }
 1775: 		}
 1776: 	    }
 1777: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1778: 		foreach my $item (keys(%javafiles)) {
 1779: 		    if ($attr->{$item}) {
 1780: 			$javafiles{$item} = $attr->{$item};
 1781: 			last;
 1782: 		    }
 1783: 		}
 1784: 		foreach my $item (keys(%mediafiles)) {
 1785: 		    if ($attr->{$item}) {
 1786: 			&add_filetype($allfiles,$attr->{$item},$item);
 1787: 			last;
 1788: 		    }
 1789: 		}
 1790: 	    }
 1791: 	} elsif ($t->[0] eq 'E') {
 1792: 	    my ($tagname) = ($t->[1]);
 1793: 	    if ($javafiles{'codebase'} ne '') {
 1794: 		$javafiles{'codebase'} .= '/';
 1795: 	    }  
 1796: 	    if (lc($tagname) eq 'applet' ||
 1797: 		lc($tagname) eq 'object' ||
 1798: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1799: 		) {
 1800: 		foreach my $item (keys(%javafiles)) {
 1801: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1802: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1803: 			&add_filetype($allfiles,$file,$item);
 1804: 		    }
 1805: 		}
 1806: 	    } 
 1807: 	    pop @state;
 1808: 	}
 1809:     }
 1810:     return 'ok';
 1811: }
 1812: 
 1813: sub add_filetype {
 1814:     my ($allfiles,$file,$type)=@_;
 1815:     if (exists($allfiles->{$file})) {
 1816: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1817: 	    push(@{$allfiles->{$file}}, &escape($type));
 1818: 	}
 1819:     } else {
 1820: 	@{$allfiles->{$file}} = (&escape($type));
 1821:     }
 1822: }
 1823: 
 1824: sub removeuploadedurl {
 1825:     my ($url)=@_;
 1826:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1827:     return &removeuserfile($uname,$udom,$fname);
 1828: }
 1829: 
 1830: sub removeuserfile {
 1831:     my ($docuname,$docudom,$fname)=@_;
 1832:     my $home=&homeserver($docuname,$docudom);
 1833:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1834:     if ($result eq 'ok') {
 1835:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1836:             my $metafile = $fname.'.meta';
 1837:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1838: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1839:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1840:             my $sqlresult = 
 1841:                 &update_portfolio_table($docuname,$docudom,$file,
 1842:                                         'portfolio_metadata',$group,
 1843:                                         'delete');
 1844:         }
 1845:     }
 1846:     return $result;
 1847: }
 1848: 
 1849: sub mkdiruserfile {
 1850:     my ($docuname,$docudom,$dir)=@_;
 1851:     my $home=&homeserver($docuname,$docudom);
 1852:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1853: }
 1854: 
 1855: sub renameuserfile {
 1856:     my ($docuname,$docudom,$old,$new)=@_;
 1857:     my $home=&homeserver($docuname,$docudom);
 1858:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1859:                         &escape("$old").':'.&escape("$new"),$home);
 1860:     if ($result eq 'ok') {
 1861:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1862:             my $oldmeta = $old.'.meta';
 1863:             my $newmeta = $new.'.meta';
 1864:             my $metaresult = 
 1865:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1866: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1867:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1868:             my $sqlresult = 
 1869:                 &update_portfolio_table($docuname,$docudom,$file,
 1870:                                         'portfolio_metadata',$group,
 1871:                                         'delete');
 1872:         }
 1873:     }
 1874:     return $result;
 1875: }
 1876: 
 1877: # ------------------------------------------------------------------------- Log
 1878: 
 1879: sub log {
 1880:     my ($dom,$nam,$hom,$what)=@_;
 1881:     return critical("log:$dom:$nam:$what",$hom);
 1882: }
 1883: 
 1884: # ------------------------------------------------------------------ Course Log
 1885: #
 1886: # This routine flushes several buffers of non-mission-critical nature
 1887: #
 1888: 
 1889: sub flushcourselogs {
 1890:     &logthis('Flushing log buffers');
 1891: #
 1892: # course logs
 1893: # This is a log of all transactions in a course, which can be used
 1894: # for data mining purposes
 1895: #
 1896: # It also collects the courseid database, which lists last transaction
 1897: # times and course titles for all courseids
 1898: #
 1899:     my %courseidbuffer=();
 1900:     foreach my $crsid (keys %courselogs) {
 1901:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1902: 		          &escape($courselogs{$crsid}),
 1903: 		          $coursehombuf{$crsid}) eq 'ok') {
 1904: 	    delete $courselogs{$crsid};
 1905:         } else {
 1906:             &logthis('Failed to flush log buffer for '.$crsid);
 1907:             if (length($courselogs{$crsid})>40000) {
 1908:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1909:                         " exceeded maximum size, deleting.</font>");
 1910:                delete $courselogs{$crsid};
 1911:             }
 1912:         }
 1913:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1914:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1915: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1916:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1917:         } else {
 1918:            $courseidbuffer{$coursehombuf{$crsid}}=
 1919: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1920:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1921:         }
 1922:     }
 1923: #
 1924: # Write course id database (reverse lookup) to homeserver of courses 
 1925: # Is used in pickcourse
 1926: #
 1927:     foreach my $crs_home (keys(%courseidbuffer)) {
 1928:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1929: 		     $crs_home);
 1930:     }
 1931: #
 1932: # File accesses
 1933: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1934: #
 1935:     foreach my $entry (keys(%accesshash)) {
 1936:         if ($entry =~ /___count$/) {
 1937:             my ($dom,$name);
 1938:             ($dom,$name,undef)=
 1939: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1940:             if (! defined($dom) || $dom eq '' || 
 1941:                 ! defined($name) || $name eq '') {
 1942:                 my $cid = $env{'request.course.id'};
 1943:                 $dom  = $env{'request.'.$cid.'.domain'};
 1944:                 $name = $env{'request.'.$cid.'.num'};
 1945:             }
 1946:             my $value = $accesshash{$entry};
 1947:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1948:             my %temphash=($url => $value);
 1949:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1950:             if ($result eq 'ok') {
 1951:                 delete $accesshash{$entry};
 1952:             } elsif ($result eq 'unknown_cmd') {
 1953:                 # Target server has old code running on it.
 1954:                 my %temphash=($entry => $value);
 1955:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1956:                     delete $accesshash{$entry};
 1957:                 }
 1958:             }
 1959:         } else {
 1960:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1961:             my %temphash=($entry => $accesshash{$entry});
 1962:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1963:                 delete $accesshash{$entry};
 1964:             }
 1965:         }
 1966:     }
 1967: #
 1968: # Roles
 1969: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1970: #
 1971:     foreach my $entry (keys(%userrolehash)) {
 1972:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1973: 	    split(/\:/,$entry);
 1974:         if (&Apache::lonnet::put('nohist_userroles',
 1975:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1976:                 $rudom,$runame) eq 'ok') {
 1977: 	    delete $userrolehash{$entry};
 1978:         }
 1979:     }
 1980: #
 1981: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1982: #
 1983:     my %domrolebuffer = ();
 1984:     foreach my $entry (keys %domainrolehash) {
 1985:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1986:         if ($domrolebuffer{$rudom}) {
 1987:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1988:                       '='.&escape($domainrolehash{$entry});
 1989:         } else {
 1990:             $domrolebuffer{$rudom}.=&escape($entry).
 1991:                       '='.&escape($domainrolehash{$entry});
 1992:         }
 1993:         delete $domainrolehash{$entry};
 1994:     }
 1995:     foreach my $dom (keys(%domrolebuffer)) {
 1996: 	my %servers = &get_servers($dom,'library');
 1997: 	foreach my $tryserver (keys(%servers)) {
 1998: 	    unless (&reply('domroleput:'.$dom.':'.
 1999: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2000: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2001: 	    }
 2002:         }
 2003:     }
 2004:     $dumpcount++;
 2005: }
 2006: 
 2007: sub courselog {
 2008:     my $what=shift;
 2009:     $what=time.':'.$what;
 2010:     unless ($env{'request.course.id'}) { return ''; }
 2011:     $coursedombuf{$env{'request.course.id'}}=
 2012:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2013:     $coursenumbuf{$env{'request.course.id'}}=
 2014:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2015:     $coursehombuf{$env{'request.course.id'}}=
 2016:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2017:     $coursedescrbuf{$env{'request.course.id'}}=
 2018:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2019:     $courseinstcodebuf{$env{'request.course.id'}}=
 2020:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2021:     $courseownerbuf{$env{'request.course.id'}}=
 2022:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2023:     $coursetypebuf{$env{'request.course.id'}}=
 2024:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2025:     if (defined $courselogs{$env{'request.course.id'}}) {
 2026: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2027:     } else {
 2028: 	$courselogs{$env{'request.course.id'}}.=$what;
 2029:     }
 2030:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2031: 	&flushcourselogs();
 2032:     }
 2033: }
 2034: 
 2035: sub courseacclog {
 2036:     my $fnsymb=shift;
 2037:     unless ($env{'request.course.id'}) { return ''; }
 2038:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2039:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2040:         $what.=':POST';
 2041:         # FIXME: Probably ought to escape things....
 2042: 	foreach my $key (keys(%env)) {
 2043:             if ($key=~/^form\.(.*)/) {
 2044: 		$what.=':'.$1.'='.$env{$key};
 2045:             }
 2046:         }
 2047:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2048:         # FIXME: We should not be depending on a form parameter that someone
 2049:         # editing lonsearchcat.pm might change in the future.
 2050:         if ($env{'form.phase'} eq 'course_search') {
 2051:             $what.= ':POST';
 2052:             # FIXME: Probably ought to escape things....
 2053:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2054:                                  'crsdiscuss') {
 2055:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2056:             }
 2057:         }
 2058:     }
 2059:     &courselog($what);
 2060: }
 2061: 
 2062: sub countacc {
 2063:     my $url=&declutter(shift);
 2064:     return if (! defined($url) || $url eq '');
 2065:     unless ($env{'request.course.id'}) { return ''; }
 2066:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2067:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2068:     $accesshash{$key}++;
 2069: }
 2070: 
 2071: sub linklog {
 2072:     my ($from,$to)=@_;
 2073:     $from=&declutter($from);
 2074:     $to=&declutter($to);
 2075:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2076:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2077: }
 2078:   
 2079: sub userrolelog {
 2080:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2081:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2082:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2083:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2084:         ($trole=~/^ta/)) {
 2085:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2086:        $userrolehash
 2087:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2088:                     =$tend.':'.$tstart;
 2089:     }
 2090:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2091:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2092:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2093:         ($trole=~/^sc/)) {
 2094:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2095:        $domainrolehash
 2096:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2097:                     = $tend.':'.$tstart;
 2098:     }
 2099: }
 2100: 
 2101: sub get_course_adv_roles {
 2102:     my $cid=shift;
 2103:     $cid=$env{'request.course.id'} unless (defined($cid));
 2104:     my %coursehash=&coursedescription($cid);
 2105:     my %nothide=();
 2106:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2107: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2108:     }
 2109:     my %returnhash=();
 2110:     my %dumphash=
 2111:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2112:     my $now=time;
 2113:     foreach my $entry (keys %dumphash) {
 2114: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2115:         if (($tstart) && ($tstart<0)) { next; }
 2116:         if (($tend) && ($tend<$now)) { next; }
 2117:         if (($tstart) && ($now<$tstart)) { next; }
 2118:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2119: 	if ($username eq '' || $domain eq '') { next; }
 2120: 	if ((&privileged($username,$domain)) && 
 2121: 	    (!$nothide{$username.':'.$domain})) { next; }
 2122: 	if ($role eq 'cr') { next; }
 2123:         my $key=&plaintext($role);
 2124:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2125:         if ($returnhash{$key}) {
 2126: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2127:         } else {
 2128:             $returnhash{$key}=$username.':'.$domain;
 2129:         }
 2130:      }
 2131:     return %returnhash;
 2132: }
 2133: 
 2134: sub get_my_roles {
 2135:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2136:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2137:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2138:     my %dumphash;
 2139:     if ($context eq 'userroles') { 
 2140:         %dumphash = &dump('roles',$udom,$uname);
 2141:     } else {
 2142:         %dumphash=
 2143:             &dump('nohist_userroles',$udom,$uname);
 2144:     }
 2145:     my %returnhash=();
 2146:     my $now=time;
 2147:     foreach my $entry (keys(%dumphash)) {
 2148:         my ($role,$tend,$tstart);
 2149:         if ($context eq 'userroles') {
 2150: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2151:         } else {
 2152:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2153:         }
 2154:         if (($tstart) && ($tstart<0)) { next; }
 2155:         my $status = 'active';
 2156:         if (($tend) && ($tend<$now)) {
 2157:             $status = 'previous';
 2158:         } 
 2159:         if (($tstart) && ($now<$tstart)) {
 2160:             $status = 'future';
 2161:         }
 2162:         if (ref($types) eq 'ARRAY') {
 2163:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2164:                 next;
 2165:             } 
 2166:         } else {
 2167:             if ($status ne 'active') {
 2168:                 next;
 2169:             }
 2170:         }
 2171:         my ($rolecode,$username,$domain,$section,$area);
 2172:         if ($context eq 'userroles') {
 2173:             ($area,$rolecode) = split(/_/,$entry);
 2174:             (undef,$domain,$username,$section) = split(/\//,$area);
 2175:         } else {
 2176:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2177:         }
 2178:         if (ref($roledoms) eq 'ARRAY') {
 2179:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2180:                 next;
 2181:             }
 2182:         }
 2183:         if (ref($roles) eq 'ARRAY') {
 2184:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2185:                 next;
 2186:             }
 2187:         }
 2188: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2189:     }
 2190:     return %returnhash;
 2191: }
 2192: 
 2193: # ----------------------------------------------------- Frontpage Announcements
 2194: #
 2195: #
 2196: 
 2197: sub postannounce {
 2198:     my ($server,$text)=@_;
 2199:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2200:     unless ($text=~/\w/) { $text=''; }
 2201:     return &reply('setannounce:'.&escape($text),$server);
 2202: }
 2203: 
 2204: sub getannounce {
 2205: 
 2206:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2207: 	my $announcement='';
 2208: 	while (my $line = <$fh>) { $announcement .= $line; }
 2209: 	close($fh);
 2210: 	if ($announcement=~/\w/) { 
 2211: 	    return 
 2212:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2213:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2214: 	} else {
 2215: 	    return '';
 2216: 	}
 2217:     } else {
 2218: 	return '';
 2219:     }
 2220: }
 2221: 
 2222: # ---------------------------------------------------------- Course ID routines
 2223: # Deal with domain's nohist_courseid.db files
 2224: #
 2225: 
 2226: sub courseidput {
 2227:     my ($domain,$what,$coursehome)=@_;
 2228:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2229: }
 2230: 
 2231: sub courseiddump {
 2232:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2233:     my %returnhash=();
 2234:     unless ($domfilter) { $domfilter=''; }
 2235:     my %libserv = &all_library();
 2236:     foreach my $tryserver (keys(%libserv)) {
 2237:         if ( (  $hostidflag == 1 
 2238: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2239: 	     || (!defined($hostidflag)) ) {
 2240: 
 2241: 	    if ($domfilter eq ''
 2242: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2243: 	        foreach my $line (
 2244:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2245: 			       $sincefilter.':'.&escape($descfilter).':'.
 2246:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2247:                                $tryserver))) {
 2248: 		    my ($key,$value)=split(/\=/,$line,2);
 2249:                     if (($key) && ($value)) {
 2250: 		        $returnhash{&unescape($key)}=$value;
 2251:                     }
 2252:                 }
 2253:             }
 2254:         }
 2255:     }
 2256:     return %returnhash;
 2257: }
 2258: 
 2259: # ---------------------------------------------------------- DC e-mail
 2260: 
 2261: sub dcmailput {
 2262:     my ($domain,$msgid,$message,$server)=@_;
 2263:     my $status = &Apache::lonnet::critical(
 2264:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2265:        &escape($message),$server);
 2266:     return $status;
 2267: }
 2268: 
 2269: sub dcmaildump {
 2270:     my ($dom,$startdate,$enddate,$senders) = @_;
 2271:     my %returnhash=();
 2272: 
 2273:     if (defined(&domain($dom,'primary'))) {
 2274:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2275:                                                          &escape($enddate).':';
 2276: 	my @esc_senders=map { &escape($_)} @$senders;
 2277: 	$cmd.=&escape(join('&',@esc_senders));
 2278: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2279:             my ($key,$value) = split(/\=/,$line,2);
 2280:             if (($key) && ($value)) {
 2281:                 $returnhash{&unescape($key)} = &unescape($value);
 2282:             }
 2283:         }
 2284:     }
 2285:     return %returnhash;
 2286: }
 2287: # ---------------------------------------------------------- Domain roles
 2288: 
 2289: sub get_domain_roles {
 2290:     my ($dom,$roles,$startdate,$enddate)=@_;
 2291:     if (undef($startdate) || $startdate eq '') {
 2292:         $startdate = '.';
 2293:     }
 2294:     if (undef($enddate) || $enddate eq '') {
 2295:         $enddate = '.';
 2296:     }
 2297:     my $rolelist = join(':',@{$roles});
 2298:     my %personnel = ();
 2299: 
 2300:     my %servers = &get_servers($dom,'library');
 2301:     foreach my $tryserver (keys(%servers)) {
 2302: 	%{$personnel{$tryserver}}=();
 2303: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2304: 					    &escape($startdate).':'.
 2305: 					    &escape($enddate).':'.
 2306: 					    &escape($rolelist), $tryserver))) {
 2307: 	    my ($key,$value) = split(/\=/,$line,2);
 2308: 	    if (($key) && ($value)) {
 2309: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2310: 	    }
 2311: 	}
 2312:     }
 2313:     return %personnel;
 2314: }
 2315: 
 2316: # ----------------------------------------------------------- Check out an item
 2317: 
 2318: sub get_first_access {
 2319:     my ($type,$argsymb)=@_;
 2320:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2321:     if ($argsymb) { $symb=$argsymb; }
 2322:     my ($map,$id,$res)=&decode_symb($symb);
 2323:     if ($type eq 'map') {
 2324: 	$res=&symbread($map);
 2325:     } else {
 2326: 	$res=$symb;
 2327:     }
 2328:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2329:     return $times{"$courseid\0$res"};
 2330: }
 2331: 
 2332: sub set_first_access {
 2333:     my ($type)=@_;
 2334:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2335:     my ($map,$id,$res)=&decode_symb($symb);
 2336:     if ($type eq 'map') {
 2337: 	$res=&symbread($map);
 2338:     } else {
 2339: 	$res=$symb;
 2340:     }
 2341:     my $firstaccess=&get_first_access($type,$symb);
 2342:     if (!$firstaccess) {
 2343: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2344:     }
 2345:     return 'already_set';
 2346: }
 2347: 
 2348: sub checkout {
 2349:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2350:     my $now=time;
 2351:     my $lonhost=$perlvar{'lonHostID'};
 2352:     my $infostr=&escape(
 2353:                  'CHECKOUTTOKEN&'.
 2354:                  $tuname.'&'.
 2355:                  $tudom.'&'.
 2356:                  $tcrsid.'&'.
 2357:                  $symb.'&'.
 2358: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2359:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2360:     if ($token=~/^error\:/) { 
 2361:         &logthis("<font color=\"blue\">WARNING: ".
 2362:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2363:                  "</font>");
 2364:         return ''; 
 2365:     }
 2366: 
 2367:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2368:     $token=~tr/a-z/A-Z/;
 2369: 
 2370:     my %infohash=('resource.0.outtoken' => $token,
 2371:                   'resource.0.checkouttime' => $now,
 2372:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2373: 
 2374:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2375:        return '';
 2376:     } else {
 2377:         &logthis("<font color=\"blue\">WARNING: ".
 2378:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2379:                  "</font>");
 2380:     }    
 2381: 
 2382:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2383:                          &escape('Checkout '.$infostr.' - '.
 2384:                                                  $token)) ne 'ok') {
 2385: 	return '';
 2386:     } else {
 2387:         &logthis("<font color=\"blue\">WARNING: ".
 2388:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2389:                  "</font>");
 2390:     }
 2391:     return $token;
 2392: }
 2393: 
 2394: # ------------------------------------------------------------ Check in an item
 2395: 
 2396: sub checkin {
 2397:     my $token=shift;
 2398:     my $now=time;
 2399:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2400:     $lonhost=~tr/A-Z/a-z/;
 2401:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2402:     $dtoken=~s/\W/\_/g;
 2403:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2404:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2405: 
 2406:     unless (($tuname) && ($tudom)) {
 2407:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2408:         return '';
 2409:     }
 2410:     
 2411:     unless (&allowed('mgr',$tcrsid)) {
 2412:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2413:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2414:         return '';
 2415:     }
 2416: 
 2417:     my %infohash=('resource.0.intoken' => $token,
 2418:                   'resource.0.checkintime' => $now,
 2419:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2420: 
 2421:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2422:        return '';
 2423:     }    
 2424: 
 2425:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2426:                          &escape('Checkin - '.$token)) ne 'ok') {
 2427: 	return '';
 2428:     }
 2429: 
 2430:     return ($symb,$tuname,$tudom,$tcrsid);    
 2431: }
 2432: 
 2433: # --------------------------------------------- Set Expire Date for Spreadsheet
 2434: 
 2435: sub expirespread {
 2436:     my ($uname,$udom,$stype,$usymb)=@_;
 2437:     my $cid=$env{'request.course.id'}; 
 2438:     if ($cid) {
 2439:        my $now=time;
 2440:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2441:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2442:                             $env{'course.'.$cid.'.num'}.
 2443: 	        	    ':nohist_expirationdates:'.
 2444:                             &escape($key).'='.$now,
 2445:                             $env{'course.'.$cid.'.home'})
 2446:     }
 2447:     return 'ok';
 2448: }
 2449: 
 2450: # ----------------------------------------------------- Devalidate Spreadsheets
 2451: 
 2452: sub devalidate {
 2453:     my ($symb,$uname,$udom)=@_;
 2454:     my $cid=$env{'request.course.id'}; 
 2455:     if ($cid) {
 2456:         # delete the stored spreadsheets for
 2457:         # - the student level sheet of this user in course's homespace
 2458:         # - the assessment level sheet for this resource 
 2459:         #   for this user in user's homespace
 2460: 	# - current conditional state info
 2461: 	my $key=$uname.':'.$udom.':';
 2462:         my $status=
 2463: 	    &del('nohist_calculatedsheets',
 2464: 		 [$key.'studentcalc:'],
 2465: 		 $env{'course.'.$cid.'.domain'},
 2466: 		 $env{'course.'.$cid.'.num'})
 2467: 		.' '.
 2468: 	    &del('nohist_calculatedsheets_'.$cid,
 2469: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2470:         unless ($status eq 'ok ok') {
 2471:            &logthis('Could not devalidate spreadsheet '.
 2472:                     $uname.' at '.$udom.' for '.
 2473: 		    $symb.': '.$status);
 2474:         }
 2475: 	&delenv('user.state.'.$cid);
 2476:     }
 2477: }
 2478: 
 2479: sub get_scalar {
 2480:     my ($string,$end) = @_;
 2481:     my $value;
 2482:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2483: 	$value = $1;
 2484:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2485: 	$value = $1;
 2486:     }
 2487:     return &unescape($value);
 2488: }
 2489: 
 2490: sub array2str {
 2491:   my (@array) = @_;
 2492:   my $result=&arrayref2str(\@array);
 2493:   $result=~s/^__ARRAY_REF__//;
 2494:   $result=~s/__END_ARRAY_REF__$//;
 2495:   return $result;
 2496: }
 2497: 
 2498: sub arrayref2str {
 2499:   my ($arrayref) = @_;
 2500:   my $result='__ARRAY_REF__';
 2501:   foreach my $elem (@$arrayref) {
 2502:     if(ref($elem) eq 'ARRAY') {
 2503:       $result.=&arrayref2str($elem).'&';
 2504:     } elsif(ref($elem) eq 'HASH') {
 2505:       $result.=&hashref2str($elem).'&';
 2506:     } elsif(ref($elem)) {
 2507:       #print("Got a ref of ".(ref($elem))." skipping.");
 2508:     } else {
 2509:       $result.=&escape($elem).'&';
 2510:     }
 2511:   }
 2512:   $result=~s/\&$//;
 2513:   $result .= '__END_ARRAY_REF__';
 2514:   return $result;
 2515: }
 2516: 
 2517: sub hash2str {
 2518:   my (%hash) = @_;
 2519:   my $result=&hashref2str(\%hash);
 2520:   $result=~s/^__HASH_REF__//;
 2521:   $result=~s/__END_HASH_REF__$//;
 2522:   return $result;
 2523: }
 2524: 
 2525: sub hashref2str {
 2526:   my ($hashref)=@_;
 2527:   my $result='__HASH_REF__';
 2528:   foreach my $key (sort(keys(%$hashref))) {
 2529:     if (ref($key) eq 'ARRAY') {
 2530:       $result.=&arrayref2str($key).'=';
 2531:     } elsif (ref($key) eq 'HASH') {
 2532:       $result.=&hashref2str($key).'=';
 2533:     } elsif (ref($key)) {
 2534:       $result.='=';
 2535:       #print("Got a ref of ".(ref($key))." skipping.");
 2536:     } else {
 2537: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2538:     }
 2539: 
 2540:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2541:       $result.=&arrayref2str($hashref->{$key}).'&';
 2542:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2543:       $result.=&hashref2str($hashref->{$key}).'&';
 2544:     } elsif(ref($hashref->{$key})) {
 2545:        $result.='&';
 2546:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2547:     } else {
 2548:       $result.=&escape($hashref->{$key}).'&';
 2549:     }
 2550:   }
 2551:   $result=~s/\&$//;
 2552:   $result .= '__END_HASH_REF__';
 2553:   return $result;
 2554: }
 2555: 
 2556: sub str2hash {
 2557:     my ($string)=@_;
 2558:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2559:     return %$hash;
 2560: }
 2561: 
 2562: sub str2hashref {
 2563:   my ($string) = @_;
 2564: 
 2565:   my %hash;
 2566: 
 2567:   if($string !~ /^__HASH_REF__/) {
 2568:       if (! ($string eq '' || !defined($string))) {
 2569: 	  $hash{'error'}='Not hash reference';
 2570:       }
 2571:       return (\%hash, $string);
 2572:   }
 2573: 
 2574:   $string =~ s/^__HASH_REF__//;
 2575: 
 2576:   while($string !~ /^__END_HASH_REF__/) {
 2577:       #key
 2578:       my $key='';
 2579:       if($string =~ /^__HASH_REF__/) {
 2580:           ($key, $string)=&str2hashref($string);
 2581:           if(defined($key->{'error'})) {
 2582:               $hash{'error'}='Bad data';
 2583:               return (\%hash, $string);
 2584:           }
 2585:       } elsif($string =~ /^__ARRAY_REF__/) {
 2586:           ($key, $string)=&str2arrayref($string);
 2587:           if($key->[0] eq 'Array reference error') {
 2588:               $hash{'error'}='Bad data';
 2589:               return (\%hash, $string);
 2590:           }
 2591:       } else {
 2592:           $string =~ s/^(.*?)=//;
 2593: 	  $key=&unescape($1);
 2594:       }
 2595:       $string =~ s/^=//;
 2596: 
 2597:       #value
 2598:       my $value='';
 2599:       if($string =~ /^__HASH_REF__/) {
 2600:           ($value, $string)=&str2hashref($string);
 2601:           if(defined($value->{'error'})) {
 2602:               $hash{'error'}='Bad data';
 2603:               return (\%hash, $string);
 2604:           }
 2605:       } elsif($string =~ /^__ARRAY_REF__/) {
 2606:           ($value, $string)=&str2arrayref($string);
 2607:           if($value->[0] eq 'Array reference error') {
 2608:               $hash{'error'}='Bad data';
 2609:               return (\%hash, $string);
 2610:           }
 2611:       } else {
 2612: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2613:       }
 2614:       $string =~ s/^&//;
 2615: 
 2616:       $hash{$key}=$value;
 2617:   }
 2618: 
 2619:   $string =~ s/^__END_HASH_REF__//;
 2620: 
 2621:   return (\%hash, $string);
 2622: }
 2623: 
 2624: sub str2array {
 2625:     my ($string)=@_;
 2626:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2627:     return @$array;
 2628: }
 2629: 
 2630: sub str2arrayref {
 2631:   my ($string) = @_;
 2632:   my @array;
 2633: 
 2634:   if($string !~ /^__ARRAY_REF__/) {
 2635:       if (! ($string eq '' || !defined($string))) {
 2636: 	  $array[0]='Array reference error';
 2637:       }
 2638:       return (\@array, $string);
 2639:   }
 2640: 
 2641:   $string =~ s/^__ARRAY_REF__//;
 2642: 
 2643:   while($string !~ /^__END_ARRAY_REF__/) {
 2644:       my $value='';
 2645:       if($string =~ /^__HASH_REF__/) {
 2646:           ($value, $string)=&str2hashref($string);
 2647:           if(defined($value->{'error'})) {
 2648:               $array[0] ='Array reference error';
 2649:               return (\@array, $string);
 2650:           }
 2651:       } elsif($string =~ /^__ARRAY_REF__/) {
 2652:           ($value, $string)=&str2arrayref($string);
 2653:           if($value->[0] eq 'Array reference error') {
 2654:               $array[0] ='Array reference error';
 2655:               return (\@array, $string);
 2656:           }
 2657:       } else {
 2658: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2659:       }
 2660:       $string =~ s/^&//;
 2661: 
 2662:       push(@array, $value);
 2663:   }
 2664: 
 2665:   $string =~ s/^__END_ARRAY_REF__//;
 2666: 
 2667:   return (\@array, $string);
 2668: }
 2669: 
 2670: # -------------------------------------------------------------------Temp Store
 2671: 
 2672: sub tmpreset {
 2673:   my ($symb,$namespace,$domain,$stuname) = @_;
 2674:   if (!$symb) {
 2675:     $symb=&symbread();
 2676:     if (!$symb) { $symb= $env{'request.url'}; }
 2677:   }
 2678:   $symb=escape($symb);
 2679: 
 2680:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2681:   $namespace=~s/\//\_/g;
 2682:   $namespace=~s/\W//g;
 2683: 
 2684:   if (!$domain) { $domain=$env{'user.domain'}; }
 2685:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2686:   if ($domain eq 'public' && $stuname eq 'public') {
 2687:       $stuname=$ENV{'REMOTE_ADDR'};
 2688:   }
 2689:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2690:   my %hash;
 2691:   if (tie(%hash,'GDBM_File',
 2692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2693: 	  &GDBM_WRCREAT(),0640)) {
 2694:     foreach my $key (keys %hash) {
 2695:       if ($key=~ /:$symb/) {
 2696: 	delete($hash{$key});
 2697:       }
 2698:     }
 2699:   }
 2700: }
 2701: 
 2702: sub tmpstore {
 2703:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2704: 
 2705:   if (!$symb) {
 2706:     $symb=&symbread();
 2707:     if (!$symb) { $symb= $env{'request.url'}; }
 2708:   }
 2709:   $symb=escape($symb);
 2710: 
 2711:   if (!$namespace) {
 2712:     # I don't think we would ever want to store this for a course.
 2713:     # it seems this will only be used if we don't have a course.
 2714:     #$namespace=$env{'request.course.id'};
 2715:     #if (!$namespace) {
 2716:       $namespace=$env{'request.state'};
 2717:     #}
 2718:   }
 2719:   $namespace=~s/\//\_/g;
 2720:   $namespace=~s/\W//g;
 2721:   if (!$domain) { $domain=$env{'user.domain'}; }
 2722:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2723:   if ($domain eq 'public' && $stuname eq 'public') {
 2724:       $stuname=$ENV{'REMOTE_ADDR'};
 2725:   }
 2726:   my $now=time;
 2727:   my %hash;
 2728:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2729:   if (tie(%hash,'GDBM_File',
 2730: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2731: 	  &GDBM_WRCREAT(),0640)) {
 2732:     $hash{"version:$symb"}++;
 2733:     my $version=$hash{"version:$symb"};
 2734:     my $allkeys=''; 
 2735:     foreach my $key (keys(%$storehash)) {
 2736:       $allkeys.=$key.':';
 2737:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2738:     }
 2739:     $hash{"$version:$symb:timestamp"}=$now;
 2740:     $allkeys.='timestamp';
 2741:     $hash{"$version:keys:$symb"}=$allkeys;
 2742:     if (untie(%hash)) {
 2743:       return 'ok';
 2744:     } else {
 2745:       return "error:$!";
 2746:     }
 2747:   } else {
 2748:     return "error:$!";
 2749:   }
 2750: }
 2751: 
 2752: # -----------------------------------------------------------------Temp Restore
 2753: 
 2754: sub tmprestore {
 2755:   my ($symb,$namespace,$domain,$stuname) = @_;
 2756: 
 2757:   if (!$symb) {
 2758:     $symb=&symbread();
 2759:     if (!$symb) { $symb= $env{'request.url'}; }
 2760:   }
 2761:   $symb=escape($symb);
 2762: 
 2763:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2764: 
 2765:   if (!$domain) { $domain=$env{'user.domain'}; }
 2766:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2767:   if ($domain eq 'public' && $stuname eq 'public') {
 2768:       $stuname=$ENV{'REMOTE_ADDR'};
 2769:   }
 2770:   my %returnhash;
 2771:   $namespace=~s/\//\_/g;
 2772:   $namespace=~s/\W//g;
 2773:   my %hash;
 2774:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2775:   if (tie(%hash,'GDBM_File',
 2776: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2777: 	  &GDBM_READER(),0640)) {
 2778:     my $version=$hash{"version:$symb"};
 2779:     $returnhash{'version'}=$version;
 2780:     my $scope;
 2781:     for ($scope=1;$scope<=$version;$scope++) {
 2782:       my $vkeys=$hash{"$scope:keys:$symb"};
 2783:       my @keys=split(/:/,$vkeys);
 2784:       my $key;
 2785:       $returnhash{"$scope:keys"}=$vkeys;
 2786:       foreach $key (@keys) {
 2787: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2788: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2789:       }
 2790:     }
 2791:     if (!(untie(%hash))) {
 2792:       return "error:$!";
 2793:     }
 2794:   } else {
 2795:     return "error:$!";
 2796:   }
 2797:   return %returnhash;
 2798: }
 2799: 
 2800: # ----------------------------------------------------------------------- Store
 2801: 
 2802: sub store {
 2803:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2804:     my $home='';
 2805: 
 2806:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2807: 
 2808:     $symb=&symbclean($symb);
 2809:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2810: 
 2811:     if (!$domain) { $domain=$env{'user.domain'}; }
 2812:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2813: 
 2814:     &devalidate($symb,$stuname,$domain);
 2815: 
 2816:     $symb=escape($symb);
 2817:     if (!$namespace) { 
 2818:        unless ($namespace=$env{'request.course.id'}) { 
 2819:           return ''; 
 2820:        } 
 2821:     }
 2822:     if (!$home) { $home=$env{'user.home'}; }
 2823: 
 2824:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2825:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2826: 
 2827:     my $namevalue='';
 2828:     foreach my $key (keys(%$storehash)) {
 2829:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2830:     }
 2831:     $namevalue=~s/\&$//;
 2832:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2833:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2834: }
 2835: 
 2836: # -------------------------------------------------------------- Critical Store
 2837: 
 2838: sub cstore {
 2839:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2840:     my $home='';
 2841: 
 2842:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2843: 
 2844:     $symb=&symbclean($symb);
 2845:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2846: 
 2847:     if (!$domain) { $domain=$env{'user.domain'}; }
 2848:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2849: 
 2850:     &devalidate($symb,$stuname,$domain);
 2851: 
 2852:     $symb=escape($symb);
 2853:     if (!$namespace) { 
 2854:        unless ($namespace=$env{'request.course.id'}) { 
 2855:           return ''; 
 2856:        } 
 2857:     }
 2858:     if (!$home) { $home=$env{'user.home'}; }
 2859: 
 2860:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2861:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2862: 
 2863:     my $namevalue='';
 2864:     foreach my $key (keys(%$storehash)) {
 2865:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2866:     }
 2867:     $namevalue=~s/\&$//;
 2868:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2869:     return critical
 2870:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2871: }
 2872: 
 2873: # --------------------------------------------------------------------- Restore
 2874: 
 2875: sub restore {
 2876:     my ($symb,$namespace,$domain,$stuname) = @_;
 2877:     my $home='';
 2878: 
 2879:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2880: 
 2881:     if (!$symb) {
 2882:       unless ($symb=escape(&symbread())) { return ''; }
 2883:     } else {
 2884:       $symb=&escape(&symbclean($symb));
 2885:     }
 2886:     if (!$namespace) { 
 2887:        unless ($namespace=$env{'request.course.id'}) { 
 2888:           return ''; 
 2889:        } 
 2890:     }
 2891:     if (!$domain) { $domain=$env{'user.domain'}; }
 2892:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2893:     if (!$home) { $home=$env{'user.home'}; }
 2894:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2895: 
 2896:     my %returnhash=();
 2897:     foreach my $line (split(/\&/,$answer)) {
 2898: 	my ($name,$value)=split(/\=/,$line);
 2899:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2900:     }
 2901:     my $version;
 2902:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2903:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2904:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2905:        }
 2906:     }
 2907:     return %returnhash;
 2908: }
 2909: 
 2910: # ---------------------------------------------------------- Course Description
 2911: 
 2912: sub coursedescription {
 2913:     my ($courseid,$args)=@_;
 2914:     $courseid=~s/^\///;
 2915:     $courseid=~s/\_/\//g;
 2916:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2917:     my $chome=&homeserver($cnum,$cdomain);
 2918:     my $normalid=$cdomain.'_'.$cnum;
 2919:     # need to always cache even if we get errors otherwise we keep 
 2920:     # trying and trying and trying to get the course description.
 2921:     my %envhash=();
 2922:     my %returnhash=();
 2923:     
 2924:     my $expiretime=600;
 2925:     if ($env{'request.course.id'} eq $normalid) {
 2926: 	$expiretime=120;
 2927:     }
 2928: 
 2929:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2930:     if (!$args->{'freshen_cache'}
 2931: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2932: 	foreach my $key (keys(%env)) {
 2933: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2934: 	    my ($setting) = $1;
 2935: 	    $returnhash{$setting} = $env{$key};
 2936: 	}
 2937: 	return %returnhash;
 2938:     }
 2939: 
 2940:     # get the data agin
 2941:     if (!$args->{'one_time'}) {
 2942: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2943:     }
 2944: 
 2945:     if ($chome ne 'no_host') {
 2946:        %returnhash=&dump('environment',$cdomain,$cnum);
 2947:        if (!exists($returnhash{'con_lost'})) {
 2948:            $returnhash{'home'}= $chome;
 2949: 	   $returnhash{'domain'} = $cdomain;
 2950: 	   $returnhash{'num'} = $cnum;
 2951:            if (!defined($returnhash{'type'})) {
 2952:                $returnhash{'type'} = 'Course';
 2953:            }
 2954:            while (my ($name,$value) = each %returnhash) {
 2955:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2956:            }
 2957:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2958:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2959: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2960:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2961:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2962:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2963:        }
 2964:     }
 2965:     if (!$args->{'one_time'}) {
 2966: 	&appenv(%envhash);
 2967:     }
 2968:     return %returnhash;
 2969: }
 2970: 
 2971: # -------------------------------------------------See if a user is privileged
 2972: 
 2973: sub privileged {
 2974:     my ($username,$domain)=@_;
 2975:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2976: 			&homeserver($username,$domain));
 2977:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2978:     my $now=time;
 2979:     if ($rolesdump ne '') {
 2980:         foreach my $entry (split(/&/,$rolesdump)) {
 2981: 	    if ($entry!~/^rolesdef_/) {
 2982: 		my ($area,$role)=split(/=/,$entry);
 2983: 		$area=~s/\_\w\w$//;
 2984: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2985: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2986: 		    my $active=1;
 2987: 		    if ($tend) {
 2988: 			if ($tend<$now) { $active=0; }
 2989: 		    }
 2990: 		    if ($tstart) {
 2991: 			if ($tstart>$now) { $active=0; }
 2992: 		    }
 2993: 		    if ($active) { return 1; }
 2994: 		}
 2995: 	    }
 2996: 	}
 2997:     }
 2998:     return 0;
 2999: }
 3000: 
 3001: # -------------------------------------------------------- Get user privileges
 3002: 
 3003: sub rolesinit {
 3004:     my ($domain,$username,$authhost)=@_;
 3005:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3006:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3007:     my %allroles=();
 3008:     my %allgroups=();   
 3009:     my $now=time;
 3010:     my %userroles = ('user.login.time' => $now);
 3011:     my $group_privs;
 3012: 
 3013:     if ($rolesdump ne '') {
 3014:         foreach my $entry (split(/&/,$rolesdump)) {
 3015: 	  if ($entry!~/^rolesdef_/) {
 3016:             my ($area,$role)=split(/=/,$entry);
 3017: 	    $area=~s/\_\w\w$//;
 3018:             my ($trole,$tend,$tstart,$group_privs);
 3019: 	    if ($role=~/^cr/) { 
 3020: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3021: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3022: 		    ($tend,$tstart)=split('_',$trest);
 3023: 		} else {
 3024: 		    $trole=$role;
 3025: 		}
 3026:             } elsif ($role =~ m|^gr/|) {
 3027:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3028:                 ($trole,$group_privs) = split(/\//,$trole);
 3029:                 $group_privs = &unescape($group_privs);
 3030: 	    } else {
 3031: 		($trole,$tend,$tstart)=split(/_/,$role);
 3032: 	    }
 3033: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3034: 					 $username);
 3035: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3036:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3037:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3038:             if (($area ne '') && ($trole ne '')) {
 3039: 		my $spec=$trole.'.'.$area;
 3040: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3041: 		if ($trole =~ /^cr\//) {
 3042:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3043:                 } elsif ($trole eq 'gr') {
 3044:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3045: 		} else {
 3046:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3047: 		}
 3048:             }
 3049:           }
 3050:         }
 3051:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3052:         $userroles{'user.adv'}    = $adv;
 3053: 	$userroles{'user.author'} = $author;
 3054:         $env{'user.adv'}=$adv;
 3055:     }
 3056:     return \%userroles;  
 3057: }
 3058: 
 3059: sub set_arearole {
 3060:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3061: # log the associated role with the area
 3062:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3063:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3064: }
 3065: 
 3066: sub custom_roleprivs {
 3067:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3068:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3069:     my $homsvr=homeserver($rauthor,$rdomain);
 3070:     if (&hostname($homsvr) ne '') {
 3071:         my ($rdummy,$roledef)=
 3072:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3073:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3074:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3075:             if (defined($syspriv)) {
 3076:                 $$allroles{'cm./'}.=':'.$syspriv;
 3077:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3078:             }
 3079:             if ($tdomain ne '') {
 3080:                 if (defined($dompriv)) {
 3081:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3082:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3083:                 }
 3084:                 if (($trest ne '') && (defined($coursepriv))) {
 3085:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3086:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3087:                 }
 3088:             }
 3089:         }
 3090:     }
 3091: }
 3092: 
 3093: sub group_roleprivs {
 3094:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3095:     my $access = 1;
 3096:     my $now = time;
 3097:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3098:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3099:     if ($access) {
 3100:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3101:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3102:     }
 3103: }
 3104: 
 3105: sub standard_roleprivs {
 3106:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3107:     if (defined($pr{$trole.':s'})) {
 3108:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3109:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3110:     }
 3111:     if ($tdomain ne '') {
 3112:         if (defined($pr{$trole.':d'})) {
 3113:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3114:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3115:         }
 3116:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3117:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3118:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3119:         }
 3120:     }
 3121: }
 3122: 
 3123: sub set_userprivs {
 3124:     my ($userroles,$allroles,$allgroups) = @_; 
 3125:     my $author=0;
 3126:     my $adv=0;
 3127:     my %grouproles = ();
 3128:     if (keys(%{$allgroups}) > 0) {
 3129:         foreach my $role (keys %{$allroles}) {
 3130:             my ($trole,$area,$sec,$extendedarea);
 3131:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3132:                 $trole = $1;
 3133:                 $area = $2;
 3134:                 $sec = $3;
 3135:                 $extendedarea = $area.$sec;
 3136:                 if (exists($$allgroups{$area})) {
 3137:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3138:                         my $spec = $trole.'.'.$extendedarea;
 3139:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3140:                                                 $$allgroups{$area}{$group};
 3141:                     }
 3142:                 }
 3143:             }
 3144:         }
 3145:     }
 3146:     foreach my $group (keys(%grouproles)) {
 3147:         $$allroles{$group} = $grouproles{$group};
 3148:     }
 3149:     foreach my $role (keys(%{$allroles})) {
 3150:         my %thesepriv;
 3151:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3152:         foreach my $item (split(/:/,$$allroles{$role})) {
 3153:             if ($item ne '') {
 3154:                 my ($privilege,$restrictions)=split(/&/,$item);
 3155:                 if ($restrictions eq '') {
 3156:                     $thesepriv{$privilege}='F';
 3157:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3158:                     $thesepriv{$privilege}.=$restrictions;
 3159:                 }
 3160:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3161:             }
 3162:         }
 3163:         my $thesestr='';
 3164:         foreach my $priv (keys(%thesepriv)) {
 3165: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3166: 	}
 3167:         $userroles->{'user.priv.'.$role} = $thesestr;
 3168:     }
 3169:     return ($author,$adv);
 3170: }
 3171: 
 3172: # --------------------------------------------------------------- get interface
 3173: 
 3174: sub get {
 3175:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3176:    my $items='';
 3177:    foreach my $item (@$storearr) {
 3178:        $items.=&escape($item).'&';
 3179:    }
 3180:    $items=~s/\&$//;
 3181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3182:    if (!$uname) { $uname=$env{'user.name'}; }
 3183:    my $uhome=&homeserver($uname,$udomain);
 3184: 
 3185:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3186:    my @pairs=split(/\&/,$rep);
 3187:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3188:      return @pairs;
 3189:    }
 3190:    my %returnhash=();
 3191:    my $i=0;
 3192:    foreach my $item (@$storearr) {
 3193:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3194:       $i++;
 3195:    }
 3196:    return %returnhash;
 3197: }
 3198: 
 3199: # --------------------------------------------------------------- del interface
 3200: 
 3201: sub del {
 3202:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3203:    my $items='';
 3204:    foreach my $item (@$storearr) {
 3205:        $items.=&escape($item).'&';
 3206:    }
 3207:    $items=~s/\&$//;
 3208:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3209:    if (!$uname) { $uname=$env{'user.name'}; }
 3210:    my $uhome=&homeserver($uname,$udomain);
 3211: 
 3212:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3213: }
 3214: 
 3215: # -------------------------------------------------------------- dump interface
 3216: 
 3217: sub dump {
 3218:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3219:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3220:     if (!$uname) { $uname=$env{'user.name'}; }
 3221:     my $uhome=&homeserver($uname,$udomain);
 3222:     if ($regexp) {
 3223: 	$regexp=&escape($regexp);
 3224:     } else {
 3225: 	$regexp='.';
 3226:     }
 3227:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3228:     my @pairs=split(/\&/,$rep);
 3229:     my %returnhash=();
 3230:     foreach my $item (@pairs) {
 3231: 	my ($key,$value)=split(/=/,$item,2);
 3232: 	$key = &unescape($key);
 3233: 	next if ($key =~ /^error: 2 /);
 3234: 	$returnhash{$key}=&thaw_unescape($value);
 3235:     }
 3236:     return %returnhash;
 3237: }
 3238: 
 3239: # --------------------------------------------------------- dumpstore interface
 3240: 
 3241: sub dumpstore {
 3242:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3243:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3244:    if (!$uname) { $uname=$env{'user.name'}; }
 3245:    my $uhome=&homeserver($uname,$udomain);
 3246:    if ($regexp) {
 3247:        $regexp=&escape($regexp);
 3248:    } else {
 3249:        $regexp='.';
 3250:    }
 3251:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3252:    my @pairs=split(/\&/,$rep);
 3253:    my %returnhash=();
 3254:    foreach my $item (@pairs) {
 3255:        my ($key,$value)=split(/=/,$item,2);
 3256:        next if ($key =~ /^error: 2 /);
 3257:        $returnhash{$key}=&thaw_unescape($value);
 3258:    }
 3259:    return %returnhash;
 3260: }
 3261: 
 3262: # -------------------------------------------------------------- keys interface
 3263: 
 3264: sub getkeys {
 3265:    my ($namespace,$udomain,$uname)=@_;
 3266:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3267:    if (!$uname) { $uname=$env{'user.name'}; }
 3268:    my $uhome=&homeserver($uname,$udomain);
 3269:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3270:    my @keyarray=();
 3271:    foreach my $key (split(/\&/,$rep)) {
 3272:       next if ($key =~ /^error: 2 /);
 3273:       push(@keyarray,&unescape($key));
 3274:    }
 3275:    return @keyarray;
 3276: }
 3277: 
 3278: # --------------------------------------------------------------- currentdump
 3279: sub currentdump {
 3280:    my ($courseid,$sdom,$sname)=@_;
 3281:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3282:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3283:    $sname    = $env{'user.name'}         if (! defined($sname));
 3284:    my $uhome = &homeserver($sname,$sdom);
 3285:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3286:    return if ($rep =~ /^(error:|no_such_host)/);
 3287:    #
 3288:    my %returnhash=();
 3289:    #
 3290:    if ($rep eq "unknown_cmd") { 
 3291:        # an old lond will not know currentdump
 3292:        # Do a dump and make it look like a currentdump
 3293:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3294:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3295:        my %hash = @tmp;
 3296:        @tmp=();
 3297:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3298:    } else {
 3299:        my @pairs=split(/\&/,$rep);
 3300:        foreach my $pair (@pairs) {
 3301:            my ($key,$value)=split(/=/,$pair,2);
 3302:            my ($symb,$param) = split(/:/,$key);
 3303:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3304:                                                         &thaw_unescape($value);
 3305:        }
 3306:    }
 3307:    return %returnhash;
 3308: }
 3309: 
 3310: sub convert_dump_to_currentdump{
 3311:     my %hash = %{shift()};
 3312:     my %returnhash;
 3313:     # Code ripped from lond, essentially.  The only difference
 3314:     # here is the unescaping done by lonnet::dump().  Conceivably
 3315:     # we might run in to problems with parameter names =~ /^v\./
 3316:     while (my ($key,$value) = each(%hash)) {
 3317:         my ($v,$symb,$param) = split(/:/,$key);
 3318: 	$symb  = &unescape($symb);
 3319: 	$param = &unescape($param);
 3320:         next if ($v eq 'version' || $symb eq 'keys');
 3321:         next if (exists($returnhash{$symb}) &&
 3322:                  exists($returnhash{$symb}->{$param}) &&
 3323:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3324:         $returnhash{$symb}->{$param}=$value;
 3325:         $returnhash{$symb}->{'v.'.$param}=$v;
 3326:     }
 3327:     #
 3328:     # Remove all of the keys in the hashes which keep track of
 3329:     # the version of the parameter.
 3330:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3331:         # use a foreach because we are going to delete from the hash.
 3332:         foreach my $key (keys(%$param_hash)) {
 3333:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3334:         }
 3335:     }
 3336:     return \%returnhash;
 3337: }
 3338: 
 3339: # ------------------------------------------------------ critical inc interface
 3340: 
 3341: sub cinc {
 3342:     return &inc(@_,'critical');
 3343: }
 3344: 
 3345: # --------------------------------------------------------------- inc interface
 3346: 
 3347: sub inc {
 3348:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3349:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3350:     if (!$uname) { $uname=$env{'user.name'}; }
 3351:     my $uhome=&homeserver($uname,$udomain);
 3352:     my $items='';
 3353:     if (! ref($store)) {
 3354:         # got a single value, so use that instead
 3355:         $items = &escape($store).'=&';
 3356:     } elsif (ref($store) eq 'SCALAR') {
 3357:         $items = &escape($$store).'=&';        
 3358:     } elsif (ref($store) eq 'ARRAY') {
 3359:         $items = join('=&',map {&escape($_);} @{$store});
 3360:     } elsif (ref($store) eq 'HASH') {
 3361:         while (my($key,$value) = each(%{$store})) {
 3362:             $items.= &escape($key).'='.&escape($value).'&';
 3363:         }
 3364:     }
 3365:     $items=~s/\&$//;
 3366:     if ($critical) {
 3367: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3368:     } else {
 3369: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3370:     }
 3371: }
 3372: 
 3373: # --------------------------------------------------------------- put interface
 3374: 
 3375: sub put {
 3376:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3378:    if (!$uname) { $uname=$env{'user.name'}; }
 3379:    my $uhome=&homeserver($uname,$udomain);
 3380:    my $items='';
 3381:    foreach my $item (keys(%$storehash)) {
 3382:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3383:    }
 3384:    $items=~s/\&$//;
 3385:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3386: }
 3387: 
 3388: # ------------------------------------------------------------ newput interface
 3389: 
 3390: sub newput {
 3391:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3392:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3393:    if (!$uname) { $uname=$env{'user.name'}; }
 3394:    my $uhome=&homeserver($uname,$udomain);
 3395:    my $items='';
 3396:    foreach my $key (keys(%$storehash)) {
 3397:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3398:    }
 3399:    $items=~s/\&$//;
 3400:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3401: }
 3402: 
 3403: # ---------------------------------------------------------  putstore interface
 3404: 
 3405: sub putstore {
 3406:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3407:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3408:    if (!$uname) { $uname=$env{'user.name'}; }
 3409:    my $uhome=&homeserver($uname,$udomain);
 3410:    my $items='';
 3411:    foreach my $key (keys(%$storehash)) {
 3412:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3413:    }
 3414:    $items=~s/\&$//;
 3415:    my $esc_symb=&escape($symb);
 3416:    my $esc_v=&escape($version);
 3417:    my $reply =
 3418:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3419: 	      $uhome);
 3420:    if ($reply eq 'unknown_cmd') {
 3421:        # gfall back to way things use to be done
 3422:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3423: 			    $uname);
 3424:    }
 3425:    return $reply;
 3426: }
 3427: 
 3428: sub old_putstore {
 3429:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3430:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3431:     if (!$uname) { $uname=$env{'user.name'}; }
 3432:     my $uhome=&homeserver($uname,$udomain);
 3433:     my %newstorehash;
 3434:     foreach my $item (keys(%$storehash)) {
 3435: 	my $key = $version.':'.&escape($symb).':'.$item;
 3436: 	$newstorehash{$key} = $storehash->{$item};
 3437:     }
 3438:     my $items='';
 3439:     my %allitems = ();
 3440:     foreach my $item (keys(%newstorehash)) {
 3441: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3442: 	    my $key = $1.':keys:'.$2;
 3443: 	    $allitems{$key} .= $3.':';
 3444: 	}
 3445: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3446:     }
 3447:     foreach my $item (keys(%allitems)) {
 3448: 	$allitems{$item} =~ s/\:$//;
 3449: 	$items.= $item.'='.$allitems{$item}.'&';
 3450:     }
 3451:     $items=~s/\&$//;
 3452:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3453: }
 3454: 
 3455: # ------------------------------------------------------ critical put interface
 3456: 
 3457: sub cput {
 3458:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3459:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3460:    if (!$uname) { $uname=$env{'user.name'}; }
 3461:    my $uhome=&homeserver($uname,$udomain);
 3462:    my $items='';
 3463:    foreach my $item (keys(%$storehash)) {
 3464:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3465:    }
 3466:    $items=~s/\&$//;
 3467:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3468: }
 3469: 
 3470: # -------------------------------------------------------------- eget interface
 3471: 
 3472: sub eget {
 3473:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3474:    my $items='';
 3475:    foreach my $item (@$storearr) {
 3476:        $items.=&escape($item).'&';
 3477:    }
 3478:    $items=~s/\&$//;
 3479:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3480:    if (!$uname) { $uname=$env{'user.name'}; }
 3481:    my $uhome=&homeserver($uname,$udomain);
 3482:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3483:    my @pairs=split(/\&/,$rep);
 3484:    my %returnhash=();
 3485:    my $i=0;
 3486:    foreach my $item (@$storearr) {
 3487:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3488:       $i++;
 3489:    }
 3490:    return %returnhash;
 3491: }
 3492: 
 3493: # ------------------------------------------------------------ tmpput interface
 3494: sub tmpput {
 3495:     my ($storehash,$server,$context)=@_;
 3496:     my $items='';
 3497:     foreach my $item (keys(%$storehash)) {
 3498: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3499:     }
 3500:     $items=~s/\&$//;
 3501:     if (defined($context)) {
 3502:         $items .= ':'.&escape($context);
 3503:     }
 3504:     return &reply("tmpput:$items",$server);
 3505: }
 3506: 
 3507: # ------------------------------------------------------------ tmpget interface
 3508: sub tmpget {
 3509:     my ($token,$server)=@_;
 3510:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3511:     my $rep=&reply("tmpget:$token",$server);
 3512:     my %returnhash;
 3513:     foreach my $item (split(/\&/,$rep)) {
 3514: 	my ($key,$value)=split(/=/,$item);
 3515: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3516:     }
 3517:     return %returnhash;
 3518: }
 3519: 
 3520: # ------------------------------------------------------------ tmpget interface
 3521: sub tmpdel {
 3522:     my ($token,$server)=@_;
 3523:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3524:     return &reply("tmpdel:$token",$server);
 3525: }
 3526: 
 3527: # -------------------------------------------------- portfolio access checking
 3528: 
 3529: sub portfolio_access {
 3530:     my ($requrl) = @_;
 3531:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3532:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3533:     if ($result) {
 3534:         my %setters;
 3535:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3536:             my ($startblock,$endblock) =
 3537:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3538:             if ($startblock && $endblock) {
 3539:                 return 'B';
 3540:             }
 3541:         } else {
 3542:             my ($startblock,$endblock) =
 3543:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3544:             if ($startblock && $endblock) {
 3545:                 return 'B';
 3546:             }
 3547:         }
 3548:     }
 3549:     if ($result eq 'ok') {
 3550:        return 'F';
 3551:     } elsif ($result =~ /^[^:]+:guest_/) {
 3552:        return 'A';
 3553:     }
 3554:     return '';
 3555: }
 3556: 
 3557: sub get_portfolio_access {
 3558:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3559: 
 3560:     if (!ref($access_hash)) {
 3561: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3562: 	my %access_controls = &get_access_controls($current_perms,$group,
 3563: 						   $file_name);
 3564: 	$access_hash = $access_controls{$file_name};
 3565:     }
 3566: 
 3567:     my ($public,$guest,@domains,@users,@courses,@groups);
 3568:     my $now = time;
 3569:     if (ref($access_hash) eq 'HASH') {
 3570:         foreach my $key (keys(%{$access_hash})) {
 3571:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3572:             if ($start > $now) {
 3573:                 next;
 3574:             }
 3575:             if ($end && $end<$now) {
 3576:                 next;
 3577:             }
 3578:             if ($scope eq 'public') {
 3579:                 $public = $key;
 3580:                 last;
 3581:             } elsif ($scope eq 'guest') {
 3582:                 $guest = $key;
 3583:             } elsif ($scope eq 'domains') {
 3584:                 push(@domains,$key);
 3585:             } elsif ($scope eq 'users') {
 3586:                 push(@users,$key);
 3587:             } elsif ($scope eq 'course') {
 3588:                 push(@courses,$key);
 3589:             } elsif ($scope eq 'group') {
 3590:                 push(@groups,$key);
 3591:             }
 3592:         }
 3593:         if ($public) {
 3594:             return 'ok';
 3595:         }
 3596:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3597:             if ($guest) {
 3598:                 return $guest;
 3599:             }
 3600:         } else {
 3601:             if (@domains > 0) {
 3602:                 foreach my $domkey (@domains) {
 3603:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3604:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3605:                             return 'ok';
 3606:                         }
 3607:                     }
 3608:                 }
 3609:             }
 3610:             if (@users > 0) {
 3611:                 foreach my $userkey (@users) {
 3612:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3613:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3614:                             if (ref($item) eq 'HASH') {
 3615:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3616:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3617:                                     return 'ok';
 3618:                                 }
 3619:                             }
 3620:                         }
 3621:                     } 
 3622:                 }
 3623:             }
 3624:             my %roleshash;
 3625:             my @courses_and_groups = @courses;
 3626:             push(@courses_and_groups,@groups); 
 3627:             if (@courses_and_groups > 0) {
 3628:                 my (%allgroups,%allroles); 
 3629:                 my ($start,$end,$role,$sec,$group);
 3630:                 foreach my $envkey (%env) {
 3631:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3632:                         my $cid = $2.'_'.$3; 
 3633:                         if ($1 eq 'gr') {
 3634:                             $group = $4;
 3635:                             $allgroups{$cid}{$group} = $env{$envkey};
 3636:                         } else {
 3637:                             if ($4 eq '') {
 3638:                                 $sec = 'none';
 3639:                             } else {
 3640:                                 $sec = $4;
 3641:                             }
 3642:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3643:                         }
 3644:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3645:                         my $cid = $2.'_'.$3;
 3646:                         if ($4 eq '') {
 3647:                             $sec = 'none';
 3648:                         } else {
 3649:                             $sec = $4;
 3650:                         }
 3651:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3652:                     }
 3653:                 }
 3654:                 if (keys(%allroles) == 0) {
 3655:                     return;
 3656:                 }
 3657:                 foreach my $key (@courses_and_groups) {
 3658:                     my %content = %{$$access_hash{$key}};
 3659:                     my $cnum = $content{'number'};
 3660:                     my $cdom = $content{'domain'};
 3661:                     my $cid = $cdom.'_'.$cnum;
 3662:                     if (!exists($allroles{$cid})) {
 3663:                         next;
 3664:                     }    
 3665:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3666:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3667:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3668:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3669:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3670:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3671:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3672:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3673:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3674:                                         if (grep/^all$/,@sections) {
 3675:                                             return 'ok';
 3676:                                         } else {
 3677:                                             if (grep/^$sec$/,@sections) {
 3678:                                                 return 'ok';
 3679:                                             }
 3680:                                         }
 3681:                                     }
 3682:                                 }
 3683:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3684:                                     if (grep/^none$/,@groups) {
 3685:                                         return 'ok';
 3686:                                     }
 3687:                                 } else {
 3688:                                     if (grep/^all$/,@groups) {
 3689:                                         return 'ok';
 3690:                                     } 
 3691:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3692:                                         if (grep/^$group$/,@groups) {
 3693:                                             return 'ok';
 3694:                                         }
 3695:                                     }
 3696:                                 } 
 3697:                             }
 3698:                         }
 3699:                     }
 3700:                 }
 3701:             }
 3702:             if ($guest) {
 3703:                 return $guest;
 3704:             }
 3705:         }
 3706:     }
 3707:     return;
 3708: }
 3709: 
 3710: sub course_group_datechecker {
 3711:     my ($dates,$now,$status) = @_;
 3712:     my ($start,$end) = split(/\./,$dates);
 3713:     if (!$start && !$end) {
 3714:         return 'ok';
 3715:     }
 3716:     if (grep/^active$/,@{$status}) {
 3717:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3718:             return 'ok';
 3719:         }
 3720:     }
 3721:     if (grep/^previous$/,@{$status}) {
 3722:         if ($end > $now ) {
 3723:             return 'ok';
 3724:         }
 3725:     }
 3726:     if (grep/^future$/,@{$status}) {
 3727:         if ($start > $now) {
 3728:             return 'ok';
 3729:         }
 3730:     }
 3731:     return; 
 3732: }
 3733: 
 3734: sub parse_portfolio_url {
 3735:     my ($url) = @_;
 3736: 
 3737:     my ($type,$udom,$unum,$group,$file_name);
 3738:     
 3739:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3740: 	$type = 1;
 3741:         $udom = $1;
 3742:         $unum = $2;
 3743:         $file_name = $3;
 3744:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3745: 	$type = 2;
 3746:         $udom = $1;
 3747:         $unum = $2;
 3748:         $group = $3;
 3749:         $file_name = $3.'/'.$4;
 3750:     }
 3751:     if (wantarray) {
 3752: 	return ($type,$udom,$unum,$file_name,$group);
 3753:     }
 3754:     return $type;
 3755: }
 3756: 
 3757: sub is_portfolio_url {
 3758:     my ($url) = @_;
 3759:     return scalar(&parse_portfolio_url($url));
 3760: }
 3761: 
 3762: sub is_portfolio_file {
 3763:     my ($file) = @_;
 3764:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3765:         return 1;
 3766:     }
 3767:     return;
 3768: }
 3769: 
 3770: 
 3771: # ---------------------------------------------- Custom access rule evaluation
 3772: 
 3773: sub customaccess {
 3774:     my ($priv,$uri)=@_;
 3775:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3776:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3777:     $udom = &LONCAPA::clean_domain($udom);
 3778:     $ucrs = &LONCAPA::clean_username($ucrs);
 3779:     my $access=0;
 3780:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3781: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3782:         if ($role) {
 3783: 	   if ($role ne $urole) { next; }
 3784:         }
 3785:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3786:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3787:             if ($tdom) {
 3788: 		if ($tdom ne $udom) { next; }
 3789:             }
 3790:             if ($tcrs) {
 3791: 		if ($tcrs ne $ucrs) { next; }
 3792:             }
 3793:             if ($tsec) {
 3794: 		if ($tsec ne $usec) { next; }
 3795:             }
 3796:             $access=($effect eq 'allow');
 3797:             last;
 3798:         }
 3799: 	if ($realm eq '' && $role eq '') {
 3800:             $access=($effect eq 'allow');
 3801: 	}
 3802:     }
 3803:     return $access;
 3804: }
 3805: 
 3806: # ------------------------------------------------- Check for a user privilege
 3807: 
 3808: sub allowed {
 3809:     my ($priv,$uri,$symb,$role)=@_;
 3810:     my $ver_orguri=$uri;
 3811:     $uri=&deversion($uri);
 3812:     my $orguri=$uri;
 3813:     $uri=&declutter($uri);
 3814: 
 3815:     if ($priv eq 'evb') {
 3816: # Evade communication block restrictions for specified role in a course
 3817:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3818:             return $1;
 3819:         } else {
 3820:             return;
 3821:         }
 3822:     }
 3823: 
 3824:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3825: # Free bre access to adm and meta resources
 3826:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3827: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3828: 	&& ($priv eq 'bre')) {
 3829: 	return 'F';
 3830:     }
 3831: 
 3832: # Free bre access to user's own portfolio contents
 3833:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3834:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3835: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3836:         my %setters;
 3837:         my ($startblock,$endblock) = 
 3838:             &Apache::loncommon::blockcheck(\%setters,'port');
 3839:         if ($startblock && $endblock) {
 3840:             return 'B';
 3841:         } else {
 3842:             return 'F';
 3843:         }
 3844:     }
 3845: 
 3846: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3847:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3848:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3849:         if (exists($env{'request.course.id'})) {
 3850:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3851:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3852:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3853:                 my $courseprivid=$env{'request.course.id'};
 3854:                 $courseprivid=~s/\_/\//;
 3855:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3856:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3857:                     return $1; 
 3858:                 } else {
 3859:                     if ($env{'request.course.sec'}) {
 3860:                         $courseprivid.='/'.$env{'request.course.sec'};
 3861:                     }
 3862:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3863:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3864:                         return $2;
 3865:                     }
 3866:                 }
 3867:             }
 3868:         }
 3869:     }
 3870: 
 3871: # Free bre to public access
 3872: 
 3873:     if ($priv eq 'bre') {
 3874:         my $copyright=&metadata($uri,'copyright');
 3875: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3876:            return 'F'; 
 3877:         }
 3878:         if ($copyright eq 'priv') {
 3879:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3880: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3881: 		return '';
 3882:             }
 3883:         }
 3884:         if ($copyright eq 'domain') {
 3885:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3886: 	    unless (($env{'user.domain'} eq $1) ||
 3887:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3888: 		return '';
 3889:             }
 3890:         }
 3891:         if ($env{'request.role'}=~ /li\.\//) {
 3892:             # Library role, so allow browsing of resources in this domain.
 3893:             return 'F';
 3894:         }
 3895:         if ($copyright eq 'custom') {
 3896: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3897:         }
 3898:     }
 3899:     # Domain coordinator is trying to create a course
 3900:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3901:         # uri is the requested domain in this case.
 3902:         # comparison to 'request.role.domain' shows if the user has selected
 3903:         # a role of dc for the domain in question.
 3904:         return 'F' if ($uri eq $env{'request.role.domain'});
 3905:     }
 3906: 
 3907:     my $thisallowed='';
 3908:     my $statecond=0;
 3909:     my $courseprivid='';
 3910: 
 3911: # Course
 3912: 
 3913:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3914:        $thisallowed.=$1;
 3915:     }
 3916: 
 3917: # Domain
 3918: 
 3919:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3920:        =~/\Q$priv\E\&([^\:]*)/) {
 3921:        $thisallowed.=$1;
 3922:     }
 3923: 
 3924: # Course: uri itself is a course
 3925:     my $courseuri=$uri;
 3926:     $courseuri=~s/\_(\d)/\/$1/;
 3927:     $courseuri=~s/^([^\/])/\/$1/;
 3928: 
 3929:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3930:        =~/\Q$priv\E\&([^\:]*)/) {
 3931:        $thisallowed.=$1;
 3932:     }
 3933: 
 3934: # URI is an uploaded document for this course, default permissions don't matter
 3935: # not allowing 'edit' access (editupload) to uploaded course docs
 3936:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3937: 	$thisallowed='';
 3938:         my ($match)=&is_on_map($uri);
 3939:         if ($match) {
 3940:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3941:                   =~/\Q$priv\E\&([^\:]*)/) {
 3942:                 $thisallowed.=$1;
 3943:             }
 3944:         } else {
 3945:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3946:             if ($refuri) {
 3947:                 if ($refuri =~ m|^/adm/|) {
 3948:                     $thisallowed='F';
 3949:                 } else {
 3950:                     $refuri=&declutter($refuri);
 3951:                     my ($match) = &is_on_map($refuri);
 3952:                     if ($match) {
 3953:                         $thisallowed='F';
 3954:                     }
 3955:                 }
 3956:             }
 3957:         }
 3958:     }
 3959: 
 3960:     if ($priv eq 'bre'
 3961: 	&& $thisallowed ne 'F' 
 3962: 	&& $thisallowed ne '2'
 3963: 	&& &is_portfolio_url($uri)) {
 3964: 	$thisallowed = &portfolio_access($uri);
 3965:     }
 3966:     
 3967: # Full access at system, domain or course-wide level? Exit.
 3968: 
 3969:     if ($thisallowed=~/F/) {
 3970: 	return 'F';
 3971:     }
 3972: 
 3973: # If this is generating or modifying users, exit with special codes
 3974: 
 3975:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3976: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3977: 	    my ($audom,$auname)=split('/',$uri);
 3978: # no author name given, so this just checks on the general right to make a co-author in this domain
 3979: 	    unless ($auname) { return $thisallowed; }
 3980: # an author name is given, so we are about to actually make a co-author for a certain account
 3981: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3982: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3983: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3984: 	}
 3985: 	return $thisallowed;
 3986:     }
 3987: #
 3988: # Gathered so far: system, domain and course wide privileges
 3989: #
 3990: # Course: See if uri or referer is an individual resource that is part of 
 3991: # the course
 3992: 
 3993:     if ($env{'request.course.id'}) {
 3994: 
 3995:        $courseprivid=$env{'request.course.id'};
 3996:        if ($env{'request.course.sec'}) {
 3997:           $courseprivid.='/'.$env{'request.course.sec'};
 3998:        }
 3999:        $courseprivid=~s/\_/\//;
 4000:        my $checkreferer=1;
 4001:        my ($match,$cond)=&is_on_map($uri);
 4002:        if ($match) {
 4003:            $statecond=$cond;
 4004:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4005:                =~/\Q$priv\E\&([^\:]*)/) {
 4006:                $thisallowed.=$1;
 4007:                $checkreferer=0;
 4008:            }
 4009:        }
 4010:        
 4011:        if ($checkreferer) {
 4012: 	  my $refuri=$env{'httpref.'.$orguri};
 4013:             unless ($refuri) {
 4014:                 foreach my $key (keys(%env)) {
 4015: 		    if ($key=~/^httpref\..*\*/) {
 4016: 			my $pattern=$key;
 4017:                         $pattern=~s/^httpref\.\/res\///;
 4018:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4019:                         $pattern=~s/\//\\\//g;
 4020:                         if ($orguri=~/$pattern/) {
 4021: 			    $refuri=$env{$key};
 4022:                         }
 4023:                     }
 4024:                 }
 4025:             }
 4026: 
 4027:          if ($refuri) { 
 4028: 	  $refuri=&declutter($refuri);
 4029:           my ($match,$cond)=&is_on_map($refuri);
 4030:             if ($match) {
 4031:               my $refstatecond=$cond;
 4032:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4033:                   =~/\Q$priv\E\&([^\:]*)/) {
 4034:                   $thisallowed.=$1;
 4035:                   $uri=$refuri;
 4036:                   $statecond=$refstatecond;
 4037:               }
 4038:           }
 4039:         }
 4040:        }
 4041:    }
 4042: 
 4043: #
 4044: # Gathered now: all privileges that could apply, and condition number
 4045: # 
 4046: #
 4047: # Full or no access?
 4048: #
 4049: 
 4050:     if ($thisallowed=~/F/) {
 4051: 	return 'F';
 4052:     }
 4053: 
 4054:     unless ($thisallowed) {
 4055:         return '';
 4056:     }
 4057: 
 4058: # Restrictions exist, deal with them
 4059: #
 4060: #   C:according to course preferences
 4061: #   R:according to resource settings
 4062: #   L:unless locked
 4063: #   X:according to user session state
 4064: #
 4065: 
 4066: # Possibly locked functionality, check all courses
 4067: # Locks might take effect only after 10 minutes cache expiration for other
 4068: # courses, and 2 minutes for current course
 4069: 
 4070:     my $envkey;
 4071:     if ($thisallowed=~/L/) {
 4072:         foreach $envkey (keys %env) {
 4073:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4074:                my $courseid=$2;
 4075:                my $roleid=$1.'.'.$2;
 4076:                $courseid=~s/^\///;
 4077:                my $expiretime=600;
 4078:                if ($env{'request.role'} eq $roleid) {
 4079: 		  $expiretime=120;
 4080:                }
 4081: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4082:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4083:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4084: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4085:                }
 4086:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4087:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4088: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4089:                        &log($env{'user.domain'},$env{'user.name'},
 4090:                             $env{'user.home'},
 4091:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4092:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4093:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4094: 		       return '';
 4095:                    }
 4096:                }
 4097:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4098:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4099: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4100:                        &log($env{'user.domain'},$env{'user.name'},
 4101:                             $env{'user.home'},
 4102:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4103:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4104:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4105: 		       return '';
 4106:                    }
 4107:                }
 4108: 	   }
 4109:        }
 4110:     }
 4111:    
 4112: #
 4113: # Rest of the restrictions depend on selected course
 4114: #
 4115: 
 4116:     unless ($env{'request.course.id'}) {
 4117: 	if ($thisallowed eq 'A') {
 4118: 	    return 'A';
 4119:         } elsif ($thisallowed eq 'B') {
 4120:             return 'B';
 4121: 	} else {
 4122: 	    return '1';
 4123: 	}
 4124:     }
 4125: 
 4126: #
 4127: # Now user is definitely in a course
 4128: #
 4129: 
 4130: 
 4131: # Course preferences
 4132: 
 4133:    if ($thisallowed=~/C/) {
 4134:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4135:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4136:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4137: 	   =~/\Q$rolecode\E/) {
 4138: 	   if ($priv ne 'pch') { 
 4139: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4140: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4141: 			$env{'request.course.id'});
 4142: 	   }
 4143:            return '';
 4144:        }
 4145: 
 4146:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4147: 	   =~/\Q$unamedom\E/) {
 4148: 	   if ($priv ne 'pch') { 
 4149: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4150: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4151: 			$env{'request.course.id'});
 4152: 	   }
 4153:            return '';
 4154:        }
 4155:    }
 4156: 
 4157: # Resource preferences
 4158: 
 4159:    if ($thisallowed=~/R/) {
 4160:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4161:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4162: 	   if ($priv ne 'pch') { 
 4163: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4164: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4165: 	   }
 4166: 	   return '';
 4167:        }
 4168:    }
 4169: 
 4170: # Restricted by state or randomout?
 4171: 
 4172:    if ($thisallowed=~/X/) {
 4173:       if ($env{'acc.randomout'}) {
 4174: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4175:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4176:             return ''; 
 4177:          }
 4178:       }
 4179:       if (&condval($statecond)) {
 4180: 	 return '2';
 4181:       } else {
 4182:          return '';
 4183:       }
 4184:    }
 4185: 
 4186:     if ($thisallowed eq 'A') {
 4187: 	return 'A';
 4188:     } elsif ($thisallowed eq 'B') {
 4189:         return 'B';
 4190:     }
 4191:    return 'F';
 4192: }
 4193: 
 4194: sub split_uri_for_cond {
 4195:     my $uri=&deversion(&declutter(shift));
 4196:     my @uriparts=split(/\//,$uri);
 4197:     my $filename=pop(@uriparts);
 4198:     my $pathname=join('/',@uriparts);
 4199:     return ($pathname,$filename);
 4200: }
 4201: # --------------------------------------------------- Is a resource on the map?
 4202: 
 4203: sub is_on_map {
 4204:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4205:     #Trying to find the conditional for the file
 4206:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4207: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4208:     if ($match) {
 4209: 	return (1,$1);
 4210:     } else {
 4211: 	return (0,0);
 4212:     }
 4213: }
 4214: 
 4215: # --------------------------------------------------------- Get symb from alias
 4216: 
 4217: sub get_symb_from_alias {
 4218:     my $symb=shift;
 4219:     my ($map,$resid,$url)=&decode_symb($symb);
 4220: # Already is a symb
 4221:     if ($url) { return $symb; }
 4222: # Must be an alias
 4223:     my $aliassymb='';
 4224:     my %bighash;
 4225:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4226:                             &GDBM_READER(),0640)) {
 4227:         my $rid=$bighash{'mapalias_'.$symb};
 4228: 	if ($rid) {
 4229: 	    my ($mapid,$resid)=split(/\./,$rid);
 4230: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4231: 				    $resid,$bighash{'src_'.$rid});
 4232: 	}
 4233:         untie %bighash;
 4234:     }
 4235:     return $aliassymb;
 4236: }
 4237: 
 4238: # ----------------------------------------------------------------- Define Role
 4239: 
 4240: sub definerole {
 4241:   if (allowed('mcr','/')) {
 4242:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4243:     foreach my $role (split(':',$sysrole)) {
 4244: 	my ($crole,$cqual)=split(/\&/,$role);
 4245:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4246:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4247: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4248:                return "refused:s:$crole&$cqual"; 
 4249:             }
 4250:         }
 4251:     }
 4252:     foreach my $role (split(':',$domrole)) {
 4253: 	my ($crole,$cqual)=split(/\&/,$role);
 4254:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4255:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4256: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4257:                return "refused:d:$crole&$cqual"; 
 4258:             }
 4259:         }
 4260:     }
 4261:     foreach my $role (split(':',$courole)) {
 4262: 	my ($crole,$cqual)=split(/\&/,$role);
 4263:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4264:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4265: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4266:                return "refused:c:$crole&$cqual"; 
 4267:             }
 4268:         }
 4269:     }
 4270:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4271:                 "$env{'user.domain'}:$env{'user.name'}:".
 4272: 	        "rolesdef_$rolename=".
 4273:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4274:     return reply($command,$env{'user.home'});
 4275:   } else {
 4276:     return 'refused';
 4277:   }
 4278: }
 4279: 
 4280: # ---------------- Make a metadata query against the network of library servers
 4281: 
 4282: sub metadata_query {
 4283:     my ($query,$custom,$customshow,$server_array)=@_;
 4284:     my %rhash;
 4285:     my %libserv = &all_library();
 4286:     my @server_list = (defined($server_array) ? @$server_array
 4287:                                               : keys(%libserv) );
 4288:     for my $server (@server_list) {
 4289: 	unless ($custom or $customshow) {
 4290: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4291: 	    $rhash{$server}=$reply;
 4292: 	}
 4293: 	else {
 4294: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4295: 			     &escape($custom).':'.&escape($customshow),
 4296: 			     $server);
 4297: 	    $rhash{$server}=$reply;
 4298: 	}
 4299:     }
 4300:     return \%rhash;
 4301: }
 4302: 
 4303: # ----------------------------------------- Send log queries and wait for reply
 4304: 
 4305: sub log_query {
 4306:     my ($uname,$udom,$query,%filters)=@_;
 4307:     my $uhome=&homeserver($uname,$udom);
 4308:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4309:     my $uhost=&hostname($uhome);
 4310:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4311:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4312:                        $uhome);
 4313:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4314:     return get_query_reply($queryid);
 4315: }
 4316: 
 4317: # -------------------------- Update MySQL table for portfolio file
 4318: 
 4319: sub update_portfolio_table {
 4320:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4321:     my $homeserver = &homeserver($uname,$udom);
 4322:     my $queryid=
 4323:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4324:                ':'.&escape($file_name).':'.$action,$homeserver);
 4325:     my $reply = &get_query_reply($queryid);
 4326:     return $reply;
 4327: }
 4328: 
 4329: # ------- Request retrieval of institutional classlists for course(s)
 4330: 
 4331: sub fetch_enrollment_query {
 4332:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4333:     my $homeserver;
 4334:     my $maxtries = 1;
 4335:     if ($context eq 'automated') {
 4336:         $homeserver = $perlvar{'lonHostID'};
 4337:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4338:     } else {
 4339:         $homeserver = &homeserver($cnum,$dom);
 4340:     }
 4341:     my $host=&hostname($homeserver);
 4342:     my $cmd = '';
 4343:     foreach my $affiliate (keys %{$affiliatesref}) {
 4344:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4345:     }
 4346:     $cmd =~ s/%%$//;
 4347:     $cmd = &escape($cmd);
 4348:     my $query = 'fetchenrollment';
 4349:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4350:     unless ($queryid=~/^\Q$host\E\_/) { 
 4351:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4352:         return 'error: '.$queryid;
 4353:     }
 4354:     my $reply = &get_query_reply($queryid);
 4355:     my $tries = 1;
 4356:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4357:         $reply = &get_query_reply($queryid);
 4358:         $tries ++;
 4359:     }
 4360:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4361:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4362:     } else {
 4363:         my @responses = split/:/,$reply;
 4364:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4365:             foreach my $line (@responses) {
 4366:                 my ($key,$value) = split(/=/,$line,2);
 4367:                 $$replyref{$key} = $value;
 4368:             }
 4369:         } else {
 4370:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4371:             foreach my $line (@responses) {
 4372:                 my ($key,$value) = split(/=/,$line);
 4373:                 $$replyref{$key} = $value;
 4374:                 if ($value > 0) {
 4375:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4376:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4377:                         my $destname = $pathname.'/'.$filename;
 4378:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4379:                         if ($xml_classlist =~ /^error/) {
 4380:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4381:                         } else {
 4382:                             if ( open(FILE,">$destname") ) {
 4383:                                 print FILE &unescape($xml_classlist);
 4384:                                 close(FILE);
 4385:                             } else {
 4386:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4387:                             }
 4388:                         }
 4389:                     }
 4390:                 }
 4391:             }
 4392:         }
 4393:         return 'ok';
 4394:     }
 4395:     return 'error';
 4396: }
 4397: 
 4398: sub get_query_reply {
 4399:     my $queryid=shift;
 4400:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4401:     my $reply='';
 4402:     for (1..100) {
 4403: 	sleep 2;
 4404:         if (-e $replyfile.'.end') {
 4405: 	    if (open(my $fh,$replyfile)) {
 4406:                $reply.=<$fh>;
 4407:                close($fh);
 4408: 	   } else { return 'error: reply_file_error'; }
 4409:            return &unescape($reply);
 4410: 	}
 4411:     }
 4412:     return 'timeout:'.$queryid;
 4413: }
 4414: 
 4415: sub courselog_query {
 4416: #
 4417: # possible filters:
 4418: # url: url or symb
 4419: # username
 4420: # domain
 4421: # action: view, submit, grade
 4422: # start: timestamp
 4423: # end: timestamp
 4424: #
 4425:     my (%filters)=@_;
 4426:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4427:     if ($filters{'url'}) {
 4428: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4429:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4430:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4431:     }
 4432:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4433:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4434:     return &log_query($cname,$cdom,'courselog',%filters);
 4435: }
 4436: 
 4437: sub userlog_query {
 4438: #
 4439: # possible filters:
 4440: # action: log check role
 4441: # start: timestamp
 4442: # end: timestamp
 4443: #
 4444:     my ($uname,$udom,%filters)=@_;
 4445:     return &log_query($uname,$udom,'userlog',%filters);
 4446: }
 4447: 
 4448: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4449: 
 4450: sub auto_run {
 4451:     my ($cnum,$cdom) = @_;
 4452:     my $homeserver = &homeserver($cnum,$cdom);
 4453:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4454:     return $response;
 4455: }
 4456: 
 4457: sub auto_get_sections {
 4458:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4459:     my $homeserver = &homeserver($cnum,$cdom);
 4460:     my @secs = ();
 4461:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4462:     unless ($response eq 'refused') {
 4463:         @secs = split/:/,$response;
 4464:     }
 4465:     return @secs;
 4466: }
 4467: 
 4468: sub auto_new_course {
 4469:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4470:     my $homeserver = &homeserver($cnum,$cdom);
 4471:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4472:     return $response;
 4473: }
 4474: 
 4475: sub auto_validate_courseID {
 4476:     my ($cnum,$cdom,$inst_course_id) = @_;
 4477:     my $homeserver = &homeserver($cnum,$cdom);
 4478:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4479:     return $response;
 4480: }
 4481: 
 4482: sub auto_create_password {
 4483:     my ($cnum,$cdom,$authparam) = @_;
 4484:     my $homeserver = &homeserver($cnum,$cdom); 
 4485:     my $create_passwd = 0;
 4486:     my $authchk = '';
 4487:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4488:     if ($response eq 'refused') {
 4489:         $authchk = 'refused';
 4490:     } else {
 4491:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4492:     }
 4493:     return ($authparam,$create_passwd,$authchk);
 4494: }
 4495: 
 4496: sub auto_photo_permission {
 4497:     my ($cnum,$cdom,$students) = @_;
 4498:     my $homeserver = &homeserver($cnum,$cdom);
 4499:     my ($outcome,$perm_reqd,$conditions) = 
 4500: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4501:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4502: 	return (undef,undef);
 4503:     }
 4504:     return ($outcome,$perm_reqd,$conditions);
 4505: }
 4506: 
 4507: sub auto_checkphotos {
 4508:     my ($uname,$udom,$pid) = @_;
 4509:     my $homeserver = &homeserver($uname,$udom);
 4510:     my ($result,$resulttype);
 4511:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4512: 				   &escape($uname).':'.&escape($pid),
 4513: 				   $homeserver));
 4514:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4515: 	return (undef,undef);
 4516:     }
 4517:     if ($outcome) {
 4518:         ($result,$resulttype) = split(/:/,$outcome);
 4519:     } 
 4520:     return ($result,$resulttype);
 4521: }
 4522: 
 4523: sub auto_photochoice {
 4524:     my ($cnum,$cdom) = @_;
 4525:     my $homeserver = &homeserver($cnum,$cdom);
 4526:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4527: 						       &escape($cdom),
 4528: 						       $homeserver)));
 4529:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4530: 	return (undef,undef);
 4531:     }
 4532:     return ($update,$comment);
 4533: }
 4534: 
 4535: sub auto_photoupdate {
 4536:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4537:     my $homeserver = &homeserver($cnum,$dom);
 4538:     my $host=&hostname($homeserver);
 4539:     my $cmd = '';
 4540:     my $maxtries = 1;
 4541:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4542:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4543:     }
 4544:     $cmd =~ s/%%$//;
 4545:     $cmd = &escape($cmd);
 4546:     my $query = 'institutionalphotos';
 4547:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4548:     unless ($queryid=~/^\Q$host\E\_/) {
 4549:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4550:         return 'error: '.$queryid;
 4551:     }
 4552:     my $reply = &get_query_reply($queryid);
 4553:     my $tries = 1;
 4554:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4555:         $reply = &get_query_reply($queryid);
 4556:         $tries ++;
 4557:     }
 4558:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4559:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4560:     } else {
 4561:         my @responses = split(/:/,$reply);
 4562:         my $outcome = shift(@responses); 
 4563:         foreach my $item (@responses) {
 4564:             my ($key,$value) = split(/=/,$item);
 4565:             $$photo{$key} = $value;
 4566:         }
 4567:         return $outcome;
 4568:     }
 4569:     return 'error';
 4570: }
 4571: 
 4572: sub auto_instcode_format {
 4573:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4574: 	$cat_order) = @_;
 4575:     my $courses = '';
 4576:     my @homeservers;
 4577:     if ($caller eq 'global') {
 4578: 	my %servers = &get_servers($codedom,'library');
 4579: 	foreach my $tryserver (keys(%servers)) {
 4580: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4581: 		push(@homeservers,$tryserver);
 4582: 	    }
 4583:         }
 4584:     } else {
 4585:         push(@homeservers,&homeserver($caller,$codedom));
 4586:     }
 4587:     foreach my $code (keys(%{$instcodes})) {
 4588:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4589:     }
 4590:     chop($courses);
 4591:     my $ok_response = 0;
 4592:     my $response;
 4593:     while (@homeservers > 0 && $ok_response == 0) {
 4594:         my $server = shift(@homeservers); 
 4595:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4596:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4597:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4598: 		split/:/,$response;
 4599:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4600:             push(@{$codetitles},&str2array($codetitles_str));
 4601:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4602:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4603:             $ok_response = 1;
 4604:         }
 4605:     }
 4606:     if ($ok_response) {
 4607:         return 'ok';
 4608:     } else {
 4609:         return $response;
 4610:     }
 4611: }
 4612: 
 4613: sub auto_instcode_defaults {
 4614:     my ($domain,$returnhash,$code_order) = @_;
 4615:     my @homeservers;
 4616: 
 4617:     my %servers = &get_servers($domain,'library');
 4618:     foreach my $tryserver (keys(%servers)) {
 4619: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4620: 	    push(@homeservers,$tryserver);
 4621: 	}
 4622:     }
 4623: 
 4624:     my $response;
 4625:     foreach my $server (@homeservers) {
 4626:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4627:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4628: 	
 4629: 	foreach my $pair (split(/\&/,$response)) {
 4630: 	    my ($name,$value)=split(/\=/,$pair);
 4631: 	    if ($name eq 'code_order') {
 4632: 		@{$code_order} = split(/\&/,&unescape($value));
 4633: 	    } else {
 4634: 		$returnhash->{&unescape($name)}=&unescape($value);
 4635: 	    }
 4636: 	}
 4637: 	return 'ok';
 4638:     }
 4639: 
 4640:     return $response;
 4641: } 
 4642: 
 4643: sub auto_validate_class_sec {
 4644:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4645:     my $homeserver = &homeserver($cnum,$cdom);
 4646:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4647:                         &escape($owner).':'.$cdom,$homeserver);
 4648:     return $response;
 4649: }
 4650: 
 4651: # ------------------------------------------------------- Course Group routines
 4652: 
 4653: sub get_coursegroups {
 4654:     my ($cdom,$cnum,$group,$namespace) = @_;
 4655:     return(&dump($namespace,$cdom,$cnum,$group));
 4656: }
 4657: 
 4658: sub modify_coursegroup {
 4659:     my ($cdom,$cnum,$groupsettings) = @_;
 4660:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4661: }
 4662: 
 4663: sub toggle_coursegroup_status {
 4664:     my ($cdom,$cnum,$group,$action) = @_;
 4665:     my ($from_namespace,$to_namespace);
 4666:     if ($action eq 'delete') {
 4667:         $from_namespace = 'coursegroups';
 4668:         $to_namespace = 'deleted_groups';
 4669:     } else {
 4670:         $from_namespace = 'deleted_groups';
 4671:         $to_namespace = 'coursegroups';
 4672:     }
 4673:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4674:     if (my $tmp = &error(%curr_group)) {
 4675:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4676:         return ('read error',$tmp);
 4677:     } else {
 4678:         my %savedsettings = %curr_group; 
 4679:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4680:         my $deloutcome;
 4681:         if ($result eq 'ok') {
 4682:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4683:         } else {
 4684:             return ('write error',$result);
 4685:         }
 4686:         if ($deloutcome eq 'ok') {
 4687:             return 'ok';
 4688:         } else {
 4689:             return ('delete error',$deloutcome);
 4690:         }
 4691:     }
 4692: }
 4693: 
 4694: sub modify_group_roles {
 4695:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4696:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4697:     my $role = 'gr/'.&escape($userprivs);
 4698:     my ($uname,$udom) = split(/:/,$user);
 4699:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4700:     if ($result eq 'ok') {
 4701:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4702:     }
 4703:     return $result;
 4704: }
 4705: 
 4706: sub modify_coursegroup_membership {
 4707:     my ($cdom,$cnum,$membership) = @_;
 4708:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4709:     return $result;
 4710: }
 4711: 
 4712: sub get_active_groups {
 4713:     my ($udom,$uname,$cdom,$cnum) = @_;
 4714:     my $now = time;
 4715:     my %groups = ();
 4716:     foreach my $key (keys(%env)) {
 4717:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4718:             my ($start,$end) = split(/\./,$env{$key});
 4719:             if (($end!=0) && ($end<$now)) { next; }
 4720:             if (($start!=0) && ($start>$now)) { next; }
 4721:             if ($1 eq $cdom && $2 eq $cnum) {
 4722:                 $groups{$3} = $env{$key} ;
 4723:             }
 4724:         }
 4725:     }
 4726:     return %groups;
 4727: }
 4728: 
 4729: sub get_group_membership {
 4730:     my ($cdom,$cnum,$group) = @_;
 4731:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4732: }
 4733: 
 4734: sub get_users_groups {
 4735:     my ($udom,$uname,$courseid) = @_;
 4736:     my @usersgroups;
 4737:     my $cachetime=1800;
 4738: 
 4739:     my $hashid="$udom:$uname:$courseid";
 4740:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4741:     if (defined($cached)) {
 4742:         @usersgroups = split(/:/,$grouplist);
 4743:     } else {  
 4744:         $grouplist = '';
 4745:         my $courseurl = &courseid_to_courseurl($courseid);
 4746:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4747:         my $access_end = $env{'course.'.$courseid.
 4748:                               '.default_enrollment_end_date'};
 4749:         my $now = time;
 4750:         foreach my $key (keys(%roleshash)) {
 4751:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4752:                 my $group = $1;
 4753:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4754:                     my $start = $2;
 4755:                     my $end = $1;
 4756:                     if ($start == -1) { next; } # deleted from group
 4757:                     if (($start!=0) && ($start>$now)) { next; }
 4758:                     if (($end!=0) && ($end<$now)) {
 4759:                         if ($access_end && $access_end < $now) {
 4760:                             if ($access_end - $end < 86400) {
 4761:                                 push(@usersgroups,$group);
 4762:                             }
 4763:                         }
 4764:                         next;
 4765:                     }
 4766:                     push(@usersgroups,$group);
 4767:                 }
 4768:             }
 4769:         }
 4770:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4771:         $grouplist = join(':',@usersgroups);
 4772:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4773:     }
 4774:     return @usersgroups;
 4775: }
 4776: 
 4777: sub devalidate_getgroups_cache {
 4778:     my ($udom,$uname,$cdom,$cnum)=@_;
 4779:     my $courseid = $cdom.'_'.$cnum;
 4780: 
 4781:     my $hashid="$udom:$uname:$courseid";
 4782:     &devalidate_cache_new('getgroups',$hashid);
 4783: }
 4784: 
 4785: # ------------------------------------------------------------------ Plain Text
 4786: 
 4787: sub plaintext {
 4788:     my ($short,$type,$cid) = @_;
 4789:     if ($short =~ /^cr/) {
 4790: 	return (split('/',$short))[-1];
 4791:     }
 4792:     if (!defined($cid)) {
 4793:         $cid = $env{'request.course.id'};
 4794:     }
 4795:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4796:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4797:                                           '.plaintext'});
 4798:     }
 4799:     my %rolenames = (
 4800:                       Course => 'std',
 4801:                       Group => 'alt1',
 4802:                     );
 4803:     if (defined($type) && 
 4804:          defined($rolenames{$type}) && 
 4805:          defined($prp{$short}{$rolenames{$type}})) {
 4806:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4807:     } else {
 4808:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4809:     }
 4810: }
 4811: 
 4812: # ----------------------------------------------------------------- Assign Role
 4813: 
 4814: sub assignrole {
 4815:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4816:     my $mrole;
 4817:     if ($role =~ /^cr\//) {
 4818:         my $cwosec=$url;
 4819:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4820: 	unless (&allowed('ccr',$cwosec)) {
 4821:            &logthis('Refused custom assignrole: '.
 4822:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4823: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4824:            return 'refused'; 
 4825:         }
 4826:         $mrole='cr';
 4827:     } elsif ($role =~ /^gr\//) {
 4828:         my $cwogrp=$url;
 4829:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4830:         unless (&allowed('mdg',$cwogrp)) {
 4831:             &logthis('Refused group assignrole: '.
 4832:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4833:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4834:             return 'refused';
 4835:         }
 4836:         $mrole='gr';
 4837:     } else {
 4838:         my $cwosec=$url;
 4839:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4840:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4841:            &logthis('Refused assignrole: '.
 4842:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4843: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4844:            return 'refused'; 
 4845:         }
 4846:         $mrole=$role;
 4847:     }
 4848:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4849:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4850:     if ($end) { $command.='_'.$end; }
 4851:     if ($start) {
 4852: 	if ($end) { 
 4853:            $command.='_'.$start; 
 4854:         } else {
 4855:            $command.='_0_'.$start;
 4856:         }
 4857:     }
 4858:     my $origstart = $start;
 4859:     my $origend = $end;
 4860: # actually delete
 4861:     if ($deleteflag) {
 4862: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4863: # modify command to delete the role
 4864:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4865:                 "$udom:$uname:$url".'_'."$mrole";
 4866: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4867: # set start and finish to negative values for userrolelog
 4868:            $start=-1;
 4869:            $end=-1;
 4870:         }
 4871:     }
 4872: # send command
 4873:     my $answer=&reply($command,&homeserver($uname,$udom));
 4874: # log new user role if status is ok
 4875:     if ($answer eq 'ok') {
 4876: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4877: # for course roles, perform group memberships changes triggered by role change.
 4878:         unless ($role =~ /^gr/) {
 4879:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4880:                                              $origstart);
 4881:         }
 4882:     }
 4883:     return $answer;
 4884: }
 4885: 
 4886: # -------------------------------------------------- Modify user authentication
 4887: # Overrides without validation
 4888: 
 4889: sub modifyuserauth {
 4890:     my ($udom,$uname,$umode,$upass)=@_;
 4891:     my $uhome=&homeserver($uname,$udom);
 4892:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4893:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4894:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4895:              ' in domain '.$env{'request.role.domain'});  
 4896:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4897: 		     &escape($upass),$uhome);
 4898:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4899:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4900:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4901:     &log($udom,,$uname,$uhome,
 4902:         'Authentication changed by '.$env{'user.domain'}.', '.
 4903:                                      $env{'user.name'}.', '.$umode.
 4904:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4905:     unless ($reply eq 'ok') {
 4906:         &logthis('Authentication mode error: '.$reply);
 4907: 	return 'error: '.$reply;
 4908:     }   
 4909:     return 'ok';
 4910: }
 4911: 
 4912: # --------------------------------------------------------------- Modify a user
 4913: 
 4914: sub modifyuser {
 4915:     my ($udom,    $uname, $uid,
 4916:         $umode,   $upass, $first,
 4917:         $middle,  $last,  $gene,
 4918:         $forceid, $desiredhome, $email)=@_;
 4919:     $udom= &LONCAPA::clean_domain($udom);
 4920:     $uname=&LONCAPA::clean_username($uname);
 4921:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4922:              $umode.', '.$first.', '.$middle.', '.
 4923: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4924:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4925:                                      ' desiredhome not specified'). 
 4926:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4927:              ' in domain '.$env{'request.role.domain'});
 4928:     my $uhome=&homeserver($uname,$udom,'true');
 4929: # ----------------------------------------------------------------- Create User
 4930:     if (($uhome eq 'no_host') && 
 4931: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4932:         my $unhome='';
 4933:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4934:             $unhome = $desiredhome;
 4935: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4936: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4937:         } else { # load balancing routine for determining $unhome
 4938:             my $loadm=10000000;
 4939: 	    my %servers = &get_servers($udom,'library');
 4940: 	    foreach my $tryserver (keys(%servers)) {
 4941: 		my $answer=reply('load',$tryserver);
 4942: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4943: 		    $loadm=$answer;
 4944: 		    $unhome=$tryserver;
 4945: 		}
 4946: 	    }
 4947:         }
 4948:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4949: 	    return 'error: unable to find a home server for '.$uname.
 4950:                    ' in domain '.$udom;
 4951:         }
 4952:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4953:                          &escape($upass),$unhome);
 4954: 	unless ($reply eq 'ok') {
 4955:             return 'error: '.$reply;
 4956:         }   
 4957:         $uhome=&homeserver($uname,$udom,'true');
 4958:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4959: 	    return 'error: unable verify users home machine.';
 4960:         }
 4961:     }   # End of creation of new user
 4962: # ---------------------------------------------------------------------- Add ID
 4963:     if ($uid) {
 4964:        $uid=~tr/A-Z/a-z/;
 4965:        my %uidhash=&idrget($udom,$uname);
 4966:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4967:          && (!$forceid)) {
 4968: 	  unless ($uid eq $uidhash{$uname}) {
 4969: 	      return 'error: user id "'.$uid.'" does not match '.
 4970:                   'current user id "'.$uidhash{$uname}.'".';
 4971:           }
 4972:        } else {
 4973: 	  &idput($udom,($uname => $uid));
 4974:        }
 4975:     }
 4976: # -------------------------------------------------------------- Add names, etc
 4977:     my @tmp=&get('environment',
 4978: 		   ['firstname','middlename','lastname','generation'],
 4979: 		   $udom,$uname);
 4980:     my %names;
 4981:     if ($tmp[0] =~ m/^error:.*/) { 
 4982:         %names=(); 
 4983:     } else {
 4984:         %names = @tmp;
 4985:     }
 4986: #
 4987: # Make sure to not trash student environment if instructor does not bother
 4988: # to supply name and email information
 4989: #
 4990:     if ($first)  { $names{'firstname'}  = $first; }
 4991:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4992:     if ($last)   { $names{'lastname'}   = $last; }
 4993:     if (defined($gene))   { $names{'generation'} = $gene; }
 4994:     if ($email) {
 4995:        $email=~s/[^\w\@\.\-\,]//gs;
 4996:        if ($email=~/\@/) { $names{'notification'} = $email;
 4997: 			   $names{'critnotification'} = $email;
 4998: 			   $names{'permanentemail'} = $email; }
 4999:     }
 5000:     my $reply = &put('environment', \%names, $udom,$uname);
 5001:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5002:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5003:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5004:              $umode.', '.$first.', '.$middle.', '.
 5005: 	     $last.', '.$gene.' by '.
 5006:              $env{'user.name'}.' at '.$env{'user.domain'});
 5007:     return 'ok';
 5008: }
 5009: 
 5010: # -------------------------------------------------------------- Modify student
 5011: 
 5012: sub modifystudent {
 5013:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5014:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5015:     if (!$cid) {
 5016: 	unless ($cid=$env{'request.course.id'}) {
 5017: 	    return 'not_in_class';
 5018: 	}
 5019:     }
 5020: # --------------------------------------------------------------- Make the user
 5021:     my $reply=&modifyuser
 5022: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5023:          $desiredhome,$email);
 5024:     unless ($reply eq 'ok') { return $reply; }
 5025:     # This will cause &modify_student_enrollment to get the uid from the
 5026:     # students environment
 5027:     $uid = undef if (!$forceid);
 5028:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5029: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5030:     return $reply;
 5031: }
 5032: 
 5033: sub modify_student_enrollment {
 5034:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5035:     my ($cdom,$cnum,$chome);
 5036:     if (!$cid) {
 5037: 	unless ($cid=$env{'request.course.id'}) {
 5038: 	    return 'not_in_class';
 5039: 	}
 5040: 	$cdom=$env{'course.'.$cid.'.domain'};
 5041: 	$cnum=$env{'course.'.$cid.'.num'};
 5042:     } else {
 5043: 	($cdom,$cnum)=split(/_/,$cid);
 5044:     }
 5045:     $chome=$env{'course.'.$cid.'.home'};
 5046:     if (!$chome) {
 5047: 	$chome=&homeserver($cnum,$cdom);
 5048:     }
 5049:     if (!$chome) { return 'unknown_course'; }
 5050:     # Make sure the user exists
 5051:     my $uhome=&homeserver($uname,$udom);
 5052:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5053: 	return 'error: no such user';
 5054:     }
 5055:     # Get student data if we were not given enough information
 5056:     if (!defined($first)  || $first  eq '' || 
 5057:         !defined($last)   || $last   eq '' || 
 5058:         !defined($uid)    || $uid    eq '' || 
 5059:         !defined($middle) || $middle eq '' || 
 5060:         !defined($gene)   || $gene   eq '') {
 5061:         # They did not supply us with enough data to enroll the student, so
 5062:         # we need to pick up more information.
 5063:         my %tmp = &get('environment',
 5064:                        ['firstname','middlename','lastname', 'generation','id']
 5065:                        ,$udom,$uname);
 5066: 
 5067:         #foreach my $key (keys(%tmp)) {
 5068:         #    &logthis("key $key = ".$tmp{$key});
 5069:         #}
 5070:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5071:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5072:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5073:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5074:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5075:     }
 5076:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5077:     my $reply=cput('classlist',
 5078: 		   {"$uname:$udom" => 
 5079: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5080: 		   $cdom,$cnum);
 5081:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5082: 	return 'error: '.$reply;
 5083:     } else {
 5084: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5085:     }
 5086:     # Add student role to user
 5087:     my $uurl='/'.$cid;
 5088:     $uurl=~s/\_/\//g;
 5089:     if ($usec) {
 5090: 	$uurl.='/'.$usec;
 5091:     }
 5092:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5093: }
 5094: 
 5095: sub format_name {
 5096:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5097:     my $name;
 5098:     if ($first ne 'lastname') {
 5099: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5100:     } else {
 5101: 	if ($lastname=~/\S/) {
 5102: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5103: 	    $name=~s/\s+,/,/;
 5104: 	} else {
 5105: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5106: 	}
 5107:     }
 5108:     $name=~s/^\s+//;
 5109:     $name=~s/\s+$//;
 5110:     $name=~s/\s+/ /g;
 5111:     return $name;
 5112: }
 5113: 
 5114: # ------------------------------------------------- Write to course preferences
 5115: 
 5116: sub writecoursepref {
 5117:     my ($courseid,%prefs)=@_;
 5118:     $courseid=~s/^\///;
 5119:     $courseid=~s/\_/\//g;
 5120:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5121:     my $chome=homeserver($cnum,$cdomain);
 5122:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5123: 	return 'error: no such course';
 5124:     }
 5125:     my $cstring='';
 5126:     foreach my $pref (keys(%prefs)) {
 5127: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5128:     }
 5129:     $cstring=~s/\&$//;
 5130:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5131: }
 5132: 
 5133: # ---------------------------------------------------------- Make/modify course
 5134: 
 5135: sub createcourse {
 5136:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5137:         $course_owner,$crstype)=@_;
 5138:     $url=&declutter($url);
 5139:     my $cid='';
 5140:     unless (&allowed('ccc',$udom)) {
 5141:         return 'refused';
 5142:     }
 5143: # ------------------------------------------------------------------- Create ID
 5144:    my $uname=int(1+rand(9)).
 5145:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5146:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5147:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5148: # ----------------------------------------------- Make sure that does not exist
 5149:    my $uhome=&homeserver($uname,$udom,'true');
 5150:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5151:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5152:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5153:        $uhome=&homeserver($uname,$udom,'true');       
 5154:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5155:            return 'error: unable to generate unique course-ID';
 5156:        } 
 5157:    }
 5158: # ------------------------------------------------ Check supplied server name
 5159:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5160:     if (! &is_library($course_server)) {
 5161:         return 'error:bad server name '.$course_server;
 5162:     }
 5163: # ------------------------------------------------------------- Make the course
 5164:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5165:                       $course_server);
 5166:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5167:     $uhome=&homeserver($uname,$udom,'true');
 5168:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5169: 	return 'error: no such course';
 5170:     }
 5171: # ----------------------------------------------------------------- Course made
 5172: # log existence
 5173:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5174:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5175:                   &escape($crstype),$uhome);
 5176:     &flushcourselogs();
 5177: # set toplevel url
 5178:     my $topurl=$url;
 5179:     unless ($nonstandard) {
 5180: # ------------------------------------------ For standard courses, make top url
 5181:         my $mapurl=&clutter($url);
 5182:         if ($mapurl eq '/res/') { $mapurl=''; }
 5183:         $env{'form.initmap'}=(<<ENDINITMAP);
 5184: <map>
 5185: <resource id="1" type="start"></resource>
 5186: <resource id="2" src="$mapurl"></resource>
 5187: <resource id="3" type="finish"></resource>
 5188: <link index="1" from="1" to="2"></link>
 5189: <link index="2" from="2" to="3"></link>
 5190: </map>
 5191: ENDINITMAP
 5192:         $topurl=&declutter(
 5193:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5194:                           );
 5195:     }
 5196: # ----------------------------------------------------------- Write preferences
 5197:     &writecoursepref($udom.'_'.$uname,
 5198:                      ('description' => $description,
 5199:                       'url'         => $topurl));
 5200:     return '/'.$udom.'/'.$uname;
 5201: }
 5202: 
 5203: sub is_course {
 5204:     my ($cdom,$cnum) = @_;
 5205:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5206: 				undef,'.');
 5207:     if (exists($courses{$cdom.'_'.$cnum})) {
 5208:         return 1;
 5209:     }
 5210:     return 0;
 5211: }
 5212: 
 5213: # ---------------------------------------------------------- Assign Custom Role
 5214: 
 5215: sub assigncustomrole {
 5216:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5217:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5218:                        $end,$start,$deleteflag);
 5219: }
 5220: 
 5221: # ----------------------------------------------------------------- Revoke Role
 5222: 
 5223: sub revokerole {
 5224:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5225:     my $now=time;
 5226:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5227: }
 5228: 
 5229: # ---------------------------------------------------------- Revoke Custom Role
 5230: 
 5231: sub revokecustomrole {
 5232:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5233:     my $now=time;
 5234:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5235:            $deleteflag);
 5236: }
 5237: 
 5238: # ------------------------------------------------------------ Disk usage
 5239: sub diskusage {
 5240:     my ($udom,$uname,$directoryRoot)=@_;
 5241:     $directoryRoot =~ s/\/$//;
 5242:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5243:     return $listing;
 5244: }
 5245: 
 5246: sub is_locked {
 5247:     my ($file_name, $domain, $user) = @_;
 5248:     my @check;
 5249:     my $is_locked;
 5250:     push @check, $file_name;
 5251:     my %locked = &get('file_permissions',\@check,
 5252: 		      $env{'user.domain'},$env{'user.name'});
 5253:     my ($tmp)=keys(%locked);
 5254:     if ($tmp=~/^error:/) { undef(%locked); }
 5255:     
 5256:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5257:         $is_locked = 'false';
 5258:         foreach my $entry (@{$locked{$file_name}}) {
 5259:            if (ref($entry) eq 'ARRAY') { 
 5260:                $is_locked = 'true';
 5261:                last;
 5262:            }
 5263:        }
 5264:     } else {
 5265:         $is_locked = 'false';
 5266:     }
 5267: }
 5268: 
 5269: sub declutter_portfile {
 5270:     my ($file) = @_;
 5271:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5272:     return $file;
 5273: }
 5274: 
 5275: # ------------------------------------------------------------- Mark as Read Only
 5276: 
 5277: sub mark_as_readonly {
 5278:     my ($domain,$user,$files,$what) = @_;
 5279:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5280:     my ($tmp)=keys(%current_permissions);
 5281:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5282:     foreach my $file (@{$files}) {
 5283: 	$file = &declutter_portfile($file);
 5284:         push(@{$current_permissions{$file}},$what);
 5285:     }
 5286:     &put('file_permissions',\%current_permissions,$domain,$user);
 5287:     return;
 5288: }
 5289: 
 5290: # ------------------------------------------------------------Save Selected Files
 5291: 
 5292: sub save_selected_files {
 5293:     my ($user, $path, @files) = @_;
 5294:     my $filename = $user."savedfiles";
 5295:     my @other_files = &files_not_in_path($user, $path);
 5296:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5297:     foreach my $file (@files) {
 5298:         print (OUT $env{'form.currentpath'}.$file."\n");
 5299:     }
 5300:     foreach my $file (@other_files) {
 5301:         print (OUT $file."\n");
 5302:     }
 5303:     close (OUT);
 5304:     return 'ok';
 5305: }
 5306: 
 5307: sub clear_selected_files {
 5308:     my ($user) = @_;
 5309:     my $filename = $user."savedfiles";
 5310:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5311:     print (OUT undef);
 5312:     close (OUT);
 5313:     return ("ok");    
 5314: }
 5315: 
 5316: sub files_in_path {
 5317:     my ($user, $path) = @_;
 5318:     my $filename = $user."savedfiles";
 5319:     my %return_files;
 5320:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5321:     while (my $line_in = <IN>) {
 5322:         chomp ($line_in);
 5323:         my @paths_and_file = split (m!/!, $line_in);
 5324:         my $file_part = pop (@paths_and_file);
 5325:         my $path_part = join ('/', @paths_and_file);
 5326:         $path_part.='/';
 5327:         my $path_and_file = $path_part.$file_part;
 5328:         if ($path_part eq $path) {
 5329:             $return_files{$file_part}= 'selected';
 5330:         }
 5331:     }
 5332:     close (IN);
 5333:     return (\%return_files);
 5334: }
 5335: 
 5336: # called in portfolio select mode, to show files selected NOT in current directory
 5337: sub files_not_in_path {
 5338:     my ($user, $path) = @_;
 5339:     my $filename = $user."savedfiles";
 5340:     my @return_files;
 5341:     my $path_part;
 5342:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5343:     while (my $line = <IN>) {
 5344:         #ok, I know it's clunky, but I want it to work
 5345:         my @paths_and_file = split(m|/|, $line);
 5346:         my $file_part = pop(@paths_and_file);
 5347:         chomp($file_part);
 5348:         my $path_part = join('/', @paths_and_file);
 5349:         $path_part .= '/';
 5350:         my $path_and_file = $path_part.$file_part;
 5351:         if ($path_part ne $path) {
 5352:             push(@return_files, ($path_and_file));
 5353:         }
 5354:     }
 5355:     close(OUT);
 5356:     return (@return_files);
 5357: }
 5358: 
 5359: #----------------------------------------------Get portfolio file permissions
 5360: 
 5361: sub get_portfile_permissions {
 5362:     my ($domain,$user) = @_;
 5363:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5364:     my ($tmp)=keys(%current_permissions);
 5365:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5366:     return \%current_permissions;
 5367: }
 5368: 
 5369: #---------------------------------------------Get portfolio file access controls
 5370: 
 5371: sub get_access_controls {
 5372:     my ($current_permissions,$group,$file) = @_;
 5373:     my %access;
 5374:     my $real_file = $file;
 5375:     $file =~ s/\.meta$//;
 5376:     if (defined($file)) {
 5377:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5378:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5379:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5380:             }
 5381:         }
 5382:     } else {
 5383:         foreach my $key (keys(%{$current_permissions})) {
 5384:             if ($key =~ /\0accesscontrol$/) {
 5385:                 if (defined($group)) {
 5386:                     if ($key !~ m-^\Q$group\E/-) {
 5387:                         next;
 5388:                     }
 5389:                 }
 5390:                 my ($fullpath) = split(/\0/,$key);
 5391:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5392:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5393:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5394:                     }
 5395:                 }
 5396:             }
 5397:         }
 5398:     }
 5399:     return %access;
 5400: }
 5401: 
 5402: sub modify_access_controls {
 5403:     my ($file_name,$changes,$domain,$user)=@_;
 5404:     my ($outcome,$deloutcome);
 5405:     my %store_permissions;
 5406:     my %new_values;
 5407:     my %new_control;
 5408:     my %translation;
 5409:     my @deletions = ();
 5410:     my $now = time;
 5411:     if (exists($$changes{'activate'})) {
 5412:         if (ref($$changes{'activate'}) eq 'HASH') {
 5413:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5414:             my $numnew = scalar(@newitems);
 5415:             for (my $i=0; $i<$numnew; $i++) {
 5416:                 my $newkey = $newitems[$i];
 5417:                 my $newid = &Apache::loncommon::get_cgi_id();
 5418:                 if ($newkey =~ /^\d+:/) { 
 5419:                     $newkey =~ s/^(\d+)/$newid/;
 5420:                     $translation{$1} = $newid;
 5421:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5422:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5423:                     $translation{$1} = $newid;
 5424:                 }
 5425:                 $new_values{$file_name."\0".$newkey} = 
 5426:                                           $$changes{'activate'}{$newitems[$i]};
 5427:                 $new_control{$newkey} = $now;
 5428:             }
 5429:         }
 5430:     }
 5431:     my %todelete;
 5432:     my %changed_items;
 5433:     foreach my $action ('delete','update') {
 5434:         if (exists($$changes{$action})) {
 5435:             if (ref($$changes{$action}) eq 'HASH') {
 5436:                 foreach my $key (keys(%{$$changes{$action}})) {
 5437:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5438:                     if ($action eq 'delete') { 
 5439:                         $todelete{$itemnum} = 1;
 5440:                     } else {
 5441:                         $changed_items{$itemnum} = $key;
 5442:                     }
 5443:                 }
 5444:             }
 5445:         }
 5446:     }
 5447:     # get lock on access controls for file.
 5448:     my $lockhash = {
 5449:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5450:                                                        ':'.$env{'user.domain'},
 5451:                    }; 
 5452:     my $tries = 0;
 5453:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5454:    
 5455:     while (($gotlock ne 'ok') && $tries <3) {
 5456:         $tries ++;
 5457:         sleep 1;
 5458:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5459:     }
 5460:     if ($gotlock eq 'ok') {
 5461:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5462:         my ($tmp)=keys(%curr_permissions);
 5463:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5464:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5465:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5466:             if (ref($curr_controls) eq 'HASH') {
 5467:                 foreach my $control_item (keys(%{$curr_controls})) {
 5468:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5469:                     if (defined($todelete{$itemnum})) {
 5470:                         push(@deletions,$file_name."\0".$control_item);
 5471:                     } else {
 5472:                         if (defined($changed_items{$itemnum})) {
 5473:                             $new_control{$changed_items{$itemnum}} = $now;
 5474:                             push(@deletions,$file_name."\0".$control_item);
 5475:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5476:                         } else {
 5477:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5478:                         }
 5479:                     }
 5480:                 }
 5481:             }
 5482:         }
 5483:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5484:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5485:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5486:         #  remove lock
 5487:         my @del_lock = ($file_name."\0".'locked_access_records');
 5488:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5489:         my ($file,$group);
 5490:         if (&is_course($domain,$user)) {
 5491:             ($group,$file) = split(/\//,$file_name,2);
 5492:         } else {
 5493:             $file = $file_name;
 5494:         }
 5495:         my $sqlresult =
 5496:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5497:                                     $group);
 5498:     } else {
 5499:         $outcome = "error: could not obtain lockfile\n";  
 5500:     }
 5501:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5502: }
 5503: 
 5504: sub make_public_indefinitely {
 5505:     my ($requrl) = @_;
 5506:     my $now = time;
 5507:     my $action = 'activate';
 5508:     my $aclnum = 0;
 5509:     if (&is_portfolio_url($requrl)) {
 5510:         my (undef,$udom,$unum,$file_name,$group) =
 5511:             &parse_portfolio_url($requrl);
 5512:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5513:         my %access_controls = &get_access_controls($current_perms,
 5514:                                                    $group,$file_name);
 5515:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5516:             my ($num,$scope,$end,$start) = 
 5517:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5518:             if ($scope eq 'public') {
 5519:                 if ($start <= $now && $end == 0) {
 5520:                     $action = 'none';
 5521:                 } else {
 5522:                     $action = 'update';
 5523:                     $aclnum = $num;
 5524:                 }
 5525:                 last;
 5526:             }
 5527:         }
 5528:         if ($action eq 'none') {
 5529:              return 'ok';
 5530:         } else {
 5531:             my %changes;
 5532:             my $newend = 0;
 5533:             my $newstart = $now;
 5534:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5535:             $changes{$action}{$newkey} = {
 5536:                 type => 'public',
 5537:                 time => {
 5538:                     start => $newstart,
 5539:                     end   => $newend,
 5540:                 },
 5541:             };
 5542:             my ($outcome,$deloutcome,$new_values,$translation) =
 5543:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5544:             return $outcome;
 5545:         }
 5546:     } else {
 5547:         return 'invalid';
 5548:     }
 5549: }
 5550: 
 5551: #------------------------------------------------------Get Marked as Read Only
 5552: 
 5553: sub get_marked_as_readonly {
 5554:     my ($domain,$user,$what,$group) = @_;
 5555:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5556:     my @readonly_files;
 5557:     my $cmp1=$what;
 5558:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5559:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5560:         if (defined($group)) {
 5561:             if ($file_name !~ m-^\Q$group\E/-) {
 5562:                 next;
 5563:             }
 5564:         }
 5565:         if (ref($value) eq "ARRAY"){
 5566:             foreach my $stored_what (@{$value}) {
 5567:                 my $cmp2=$stored_what;
 5568:                 if (ref($stored_what) eq 'ARRAY') {
 5569:                     $cmp2=join('',@{$stored_what});
 5570:                 }
 5571:                 if ($cmp1 eq $cmp2) {
 5572:                     push(@readonly_files, $file_name);
 5573:                     last;
 5574:                 } elsif (!defined($what)) {
 5575:                     push(@readonly_files, $file_name);
 5576:                     last;
 5577:                 }
 5578:             }
 5579:         }
 5580:     }
 5581:     return @readonly_files;
 5582: }
 5583: #-----------------------------------------------------------Get Marked as Read Only Hash
 5584: 
 5585: sub get_marked_as_readonly_hash {
 5586:     my ($current_permissions,$group,$what) = @_;
 5587:     my %readonly_files;
 5588:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5589:         if (defined($group)) {
 5590:             if ($file_name !~ m-^\Q$group\E/-) {
 5591:                 next;
 5592:             }
 5593:         }
 5594:         if (ref($value) eq "ARRAY"){
 5595:             foreach my $stored_what (@{$value}) {
 5596:                 if (ref($stored_what) eq 'ARRAY') {
 5597:                     foreach my $lock_descriptor(@{$stored_what}) {
 5598:                         if ($lock_descriptor eq 'graded') {
 5599:                             $readonly_files{$file_name} = 'graded';
 5600:                         } elsif ($lock_descriptor eq 'handback') {
 5601:                             $readonly_files{$file_name} = 'handback';
 5602:                         } else {
 5603:                             if (!exists($readonly_files{$file_name})) {
 5604:                                 $readonly_files{$file_name} = 'locked';
 5605:                             }
 5606:                         }
 5607:                     }
 5608:                 } 
 5609:             }
 5610:         } 
 5611:     }
 5612:     return %readonly_files;
 5613: }
 5614: # ------------------------------------------------------------ Unmark as Read Only
 5615: 
 5616: sub unmark_as_readonly {
 5617:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5618:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5619:     my ($domain,$user,$what,$file_name,$group) = @_;
 5620:     $file_name = &declutter_portfile($file_name);
 5621:     my $symb_crs = $what;
 5622:     if (ref($what)) { $symb_crs=join('',@$what); }
 5623:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5624:     my ($tmp)=keys(%current_permissions);
 5625:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5626:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5627:     foreach my $file (@readonly_files) {
 5628: 	my $clean_file = &declutter_portfile($file);
 5629: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5630: 	my $current_locks = $current_permissions{$file};
 5631:         my @new_locks;
 5632:         my @del_keys;
 5633:         if (ref($current_locks) eq "ARRAY"){
 5634:             foreach my $locker (@{$current_locks}) {
 5635:                 my $compare=$locker;
 5636:                 if (ref($locker) eq 'ARRAY') {
 5637:                     $compare=join('',@{$locker});
 5638:                     if ($compare ne $symb_crs) {
 5639:                         push(@new_locks, $locker);
 5640:                     }
 5641:                 }
 5642:             }
 5643:             if (scalar(@new_locks) > 0) {
 5644:                 $current_permissions{$file} = \@new_locks;
 5645:             } else {
 5646:                 push(@del_keys, $file);
 5647:                 &del('file_permissions',\@del_keys, $domain, $user);
 5648:                 delete($current_permissions{$file});
 5649:             }
 5650:         }
 5651:     }
 5652:     &put('file_permissions',\%current_permissions,$domain,$user);
 5653:     return;
 5654: }
 5655: 
 5656: # ------------------------------------------------------------ Directory lister
 5657: 
 5658: sub dirlist {
 5659:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5660: 
 5661:     $uri=~s/^\///;
 5662:     $uri=~s/\/$//;
 5663:     my ($udom, $uname);
 5664:     (undef,$udom,$uname)=split(/\//,$uri);
 5665:     if(defined($userdomain)) {
 5666:         $udom = $userdomain;
 5667:     }
 5668:     if(defined($username)) {
 5669:         $uname = $username;
 5670:     }
 5671: 
 5672:     my $dirRoot = $perlvar{'lonDocRoot'};
 5673:     if(defined($alternateDirectoryRoot)) {
 5674:         $dirRoot = $alternateDirectoryRoot;
 5675:         $dirRoot =~ s/\/$//;
 5676:     }
 5677: 
 5678:     if($udom) {
 5679:         if($uname) {
 5680:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5681: 				 &homeserver($uname,$udom));
 5682:             my @listing_results;
 5683:             if ($listing eq 'unknown_cmd') {
 5684:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5685: 				  &homeserver($uname,$udom));
 5686:                 @listing_results = split(/:/,$listing);
 5687:             } else {
 5688:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5689:             }
 5690:             return @listing_results;
 5691:         } elsif(!defined($alternateDirectoryRoot)) {
 5692:             my %allusers;
 5693: 	    my %servers = &get_servers($udom,'library');
 5694: 	    foreach my $tryserver (keys(%servers)) {
 5695: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5696: 				     $udom, $tryserver);
 5697: 		my @listing_results;
 5698: 		if ($listing eq 'unknown_cmd') {
 5699: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5700: 				      $udom, $tryserver);
 5701: 		    @listing_results = split(/:/,$listing);
 5702: 		} else {
 5703: 		    @listing_results =
 5704: 			map { &unescape($_); } split(/:/,$listing);
 5705: 		}
 5706: 		if ($listing_results[0] ne 'no_such_dir' && 
 5707: 		    $listing_results[0] ne 'empty'       &&
 5708: 		    $listing_results[0] ne 'con_lost') {
 5709: 		    foreach my $line (@listing_results) {
 5710: 			my ($entry) = split(/&/,$line,2);
 5711: 			$allusers{$entry} = 1;
 5712: 		    }
 5713: 		}
 5714:             }
 5715:             my $alluserstr='';
 5716:             foreach my $user (sort(keys(%allusers))) {
 5717:                 $alluserstr.=$user.'&user:';
 5718:             }
 5719:             $alluserstr=~s/:$//;
 5720:             return split(/:/,$alluserstr);
 5721:         } else {
 5722:             return ('missing user name');
 5723:         }
 5724:     } elsif(!defined($alternateDirectoryRoot)) {
 5725:         my @all_domains = sort(&all_domains());
 5726:          foreach my $domain (@all_domains) {
 5727:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5728:          }
 5729:          return @all_domains;
 5730:      } else {
 5731:         return ('missing domain');
 5732:     }
 5733: }
 5734: 
 5735: # --------------------------------------------- GetFileTimestamp
 5736: # This function utilizes dirlist and returns the date stamp for
 5737: # when it was last modified.  It will also return an error of -1
 5738: # if an error occurs
 5739: 
 5740: ##
 5741: ## FIXME: This subroutine assumes its caller knows something about the
 5742: ## directory structure of the home server for the student ($root).
 5743: ## Not a good assumption to make.  Since this is for looking up files
 5744: ## in user directories, the full path should be constructed by lond, not
 5745: ## whatever machine we request data from.
 5746: ##
 5747: sub GetFileTimestamp {
 5748:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5749:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5750:     $studentName   = &LONCAPA::clean_username($studentName);
 5751:     my $subdir=$studentName.'__';
 5752:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5753:     my $proname="$studentDomain/$subdir/$studentName";
 5754:     $proname .= '/'.$filename;
 5755:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5756:                                               $studentName, $root);
 5757:     my @stats = split('&', $fileStat);
 5758:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5759:         # @stats contains first the filename, then the stat output
 5760:         return $stats[10]; # so this is 10 instead of 9.
 5761:     } else {
 5762:         return -1;
 5763:     }
 5764: }
 5765: 
 5766: sub stat_file {
 5767:     my ($uri) = @_;
 5768:     $uri = &clutter_with_no_wrapper($uri);
 5769: 
 5770:     my ($udom,$uname,$file,$dir);
 5771:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5772: 	($udom,$uname,$file) =
 5773: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5774: 	$file = 'userfiles/'.$file;
 5775: 	$dir = &propath($udom,$uname);
 5776:     }
 5777:     if ($uri =~ m-^/res/-) {
 5778: 	($udom,$uname) = 
 5779: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5780: 	$file = $uri;
 5781:     }
 5782: 
 5783:     if (!$udom || !$uname || !$file) {
 5784: 	# unable to handle the uri
 5785: 	return ();
 5786:     }
 5787: 
 5788:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5789:     my @stats = split('&', $result);
 5790:     
 5791:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5792: 	shift(@stats); #filename is first
 5793: 	return @stats;
 5794:     }
 5795:     return ();
 5796: }
 5797: 
 5798: # -------------------------------------------------------- Value of a Condition
 5799: 
 5800: # gets the value of a specific preevaluated condition
 5801: #    stored in the string  $env{user.state.<cid>}
 5802: # or looks up a condition reference in the bighash and if if hasn't
 5803: # already been evaluated recurses into docondval to get the value of
 5804: # the condition, then memoizing it to 
 5805: #   $env{user.state.<cid>.<condition>}
 5806: sub directcondval {
 5807:     my $number=shift;
 5808:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5809: 	&Apache::lonuserstate::evalstate();
 5810:     }
 5811:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5812: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5813:     } elsif ($number =~ /^_/) {
 5814: 	my $sub_condition;
 5815: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5816: 		&GDBM_READER(),0640)) {
 5817: 	    $sub_condition=$bighash{'conditions'.$number};
 5818: 	    untie(%bighash);
 5819: 	}
 5820: 	my $value = &docondval($sub_condition);
 5821: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5822: 	return $value;
 5823:     }
 5824:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5825:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5826:     } else {
 5827:        return 2;
 5828:     }
 5829: }
 5830: 
 5831: # get the collection of conditions for this resource
 5832: sub condval {
 5833:     my $condidx=shift;
 5834:     my $allpathcond='';
 5835:     foreach my $cond (split(/\|/,$condidx)) {
 5836: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5837: 	    $allpathcond.=
 5838: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5839: 	}
 5840:     }
 5841:     $allpathcond=~s/\|$//;
 5842:     return &docondval($allpathcond);
 5843: }
 5844: 
 5845: #evaluates an expression of conditions
 5846: sub docondval {
 5847:     my ($allpathcond) = @_;
 5848:     my $result=0;
 5849:     if ($env{'request.course.id'}
 5850: 	&& defined($allpathcond)) {
 5851: 	my $operand='|';
 5852: 	my @stack;
 5853: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5854: 	    if ($chunk eq '(') {
 5855: 		push @stack,($operand,$result);
 5856: 	    } elsif ($chunk eq ')') {
 5857: 		my $before=pop @stack;
 5858: 		if (pop @stack eq '&') {
 5859: 		    $result=$result>$before?$before:$result;
 5860: 		} else {
 5861: 		    $result=$result>$before?$result:$before;
 5862: 		}
 5863: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5864: 		$operand=$chunk;
 5865: 	    } else {
 5866: 		my $new=directcondval($chunk);
 5867: 		if ($operand eq '&') {
 5868: 		    $result=$result>$new?$new:$result;
 5869: 		} else {
 5870: 		    $result=$result>$new?$result:$new;
 5871: 		}
 5872: 	    }
 5873: 	}
 5874:     }
 5875:     return $result;
 5876: }
 5877: 
 5878: # ---------------------------------------------------- Devalidate courseresdata
 5879: 
 5880: sub devalidatecourseresdata {
 5881:     my ($coursenum,$coursedomain)=@_;
 5882:     my $hashid=$coursenum.':'.$coursedomain;
 5883:     &devalidate_cache_new('courseres',$hashid);
 5884: }
 5885: 
 5886: 
 5887: # --------------------------------------------------- Course Resourcedata Query
 5888: 
 5889: sub get_courseresdata {
 5890:     my ($coursenum,$coursedomain)=@_;
 5891:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5892:     my $hashid=$coursenum.':'.$coursedomain;
 5893:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5894:     my %dumpreply;
 5895:     unless (defined($cached)) {
 5896: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5897: 	$result=\%dumpreply;
 5898: 	my ($tmp) = keys(%dumpreply);
 5899: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5900: 	    &do_cache_new('courseres',$hashid,$result,600);
 5901: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5902: 	    return $tmp;
 5903: 	} elsif ($tmp =~ /^(error)/) {
 5904: 	    $result=undef;
 5905: 	    &do_cache_new('courseres',$hashid,$result,600);
 5906: 	}
 5907:     }
 5908:     return $result;
 5909: }
 5910: 
 5911: sub devalidateuserresdata {
 5912:     my ($uname,$udom)=@_;
 5913:     my $hashid="$udom:$uname";
 5914:     &devalidate_cache_new('userres',$hashid);
 5915: }
 5916: 
 5917: sub get_userresdata {
 5918:     my ($uname,$udom)=@_;
 5919:     #most student don\'t have any data set, check if there is some data
 5920:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5921: 
 5922:     my $hashid="$udom:$uname";
 5923:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5924:     if (!defined($cached)) {
 5925: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5926: 	$result=\%resourcedata;
 5927: 	&do_cache_new('userres',$hashid,$result,600);
 5928:     }
 5929:     my ($tmp)=keys(%$result);
 5930:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5931: 	return $result;
 5932:     }
 5933:     #error 2 occurs when the .db doesn't exist
 5934:     if ($tmp!~/error: 2 /) {
 5935: 	&logthis("<font color=\"blue\">WARNING:".
 5936: 		 " Trying to get resource data for ".
 5937: 		 $uname." at ".$udom.": ".
 5938: 		 $tmp."</font>");
 5939:     } elsif ($tmp=~/error: 2 /) {
 5940: 	#&EXT_cache_set($udom,$uname);
 5941: 	&do_cache_new('userres',$hashid,undef,600);
 5942: 	undef($tmp); # not really an error so don't send it back
 5943:     }
 5944:     return $tmp;
 5945: }
 5946: 
 5947: sub resdata {
 5948:     my ($name,$domain,$type,@which)=@_;
 5949:     my $result;
 5950:     if ($type eq 'course') {
 5951: 	$result=&get_courseresdata($name,$domain);
 5952:     } elsif ($type eq 'user') {
 5953: 	$result=&get_userresdata($name,$domain);
 5954:     }
 5955:     if (!ref($result)) { return $result; }    
 5956:     foreach my $item (@which) {
 5957: 	if (defined($result->{$item})) {
 5958: 	    return $result->{$item};
 5959: 	}
 5960:     }
 5961:     return undef;
 5962: }
 5963: 
 5964: #
 5965: # EXT resource caching routines
 5966: #
 5967: 
 5968: sub clear_EXT_cache_status {
 5969:     &delenv('cache.EXT.');
 5970: }
 5971: 
 5972: sub EXT_cache_status {
 5973:     my ($target_domain,$target_user) = @_;
 5974:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5975:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5976:         # We know already the user has no data
 5977:         return 1;
 5978:     } else {
 5979:         return 0;
 5980:     }
 5981: }
 5982: 
 5983: sub EXT_cache_set {
 5984:     my ($target_domain,$target_user) = @_;
 5985:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5986:     #&appenv($cachename => time);
 5987: }
 5988: 
 5989: # --------------------------------------------------------- Value of a Variable
 5990: sub EXT {
 5991: 
 5992:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5993:     unless ($varname) { return ''; }
 5994:     #get real user name/domain, courseid and symb
 5995:     my $courseid;
 5996:     my $publicuser;
 5997:     if ($symbparm) {
 5998: 	$symbparm=&get_symb_from_alias($symbparm);
 5999:     }
 6000:     if (!($uname && $udom)) {
 6001:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6002:       if (!$symbparm) {	$symbparm=$cursymb; }
 6003:     } else {
 6004: 	$courseid=$env{'request.course.id'};
 6005:     }
 6006:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6007:     my $rest;
 6008:     if (defined($therest[0])) {
 6009:        $rest=join('.',@therest);
 6010:     } else {
 6011:        $rest='';
 6012:     }
 6013: 
 6014:     my $qualifierrest=$qualifier;
 6015:     if ($rest) { $qualifierrest.='.'.$rest; }
 6016:     my $spacequalifierrest=$space;
 6017:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6018:     if ($realm eq 'user') {
 6019: # --------------------------------------------------------------- user.resource
 6020: 	if ($space eq 'resource') {
 6021: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6022: 		  || defined($Apache::lonhomework::parsing_a_task))
 6023: 		 &&
 6024: 		 ($symbparm eq &symbread()) ) {	
 6025: 		# if we are in the middle of processing the resource the
 6026: 		# get the value we are planning on committing
 6027:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6028:                     return $Apache::lonhomework::results{$qualifierrest};
 6029:                 } else {
 6030:                     return $Apache::lonhomework::history{$qualifierrest};
 6031:                 }
 6032: 	    } else {
 6033: 		my %restored;
 6034: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6035: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6036: 		} else {
 6037: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6038: 		}
 6039: 		return $restored{$qualifierrest};
 6040: 	    }
 6041: # ----------------------------------------------------------------- user.access
 6042:         } elsif ($space eq 'access') {
 6043: 	    # FIXME - not supporting calls for a specific user
 6044:             return &allowed($qualifier,$rest);
 6045: # ------------------------------------------ user.preferences, user.environment
 6046:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6047: 	    if (($uname eq $env{'user.name'}) &&
 6048: 		($udom eq $env{'user.domain'})) {
 6049: 		return $env{join('.',('environment',$qualifierrest))};
 6050: 	    } else {
 6051: 		my %returnhash;
 6052: 		if (!$publicuser) {
 6053: 		    %returnhash=&userenvironment($udom,$uname,
 6054: 						 $qualifierrest);
 6055: 		}
 6056: 		return $returnhash{$qualifierrest};
 6057: 	    }
 6058: # ----------------------------------------------------------------- user.course
 6059:         } elsif ($space eq 'course') {
 6060: 	    # FIXME - not supporting calls for a specific user
 6061:             return $env{join('.',('request.course',$qualifier))};
 6062: # ------------------------------------------------------------------- user.role
 6063:         } elsif ($space eq 'role') {
 6064: 	    # FIXME - not supporting calls for a specific user
 6065:             my ($role,$where)=split(/\./,$env{'request.role'});
 6066:             if ($qualifier eq 'value') {
 6067: 		return $role;
 6068:             } elsif ($qualifier eq 'extent') {
 6069:                 return $where;
 6070:             }
 6071: # ----------------------------------------------------------------- user.domain
 6072:         } elsif ($space eq 'domain') {
 6073:             return $udom;
 6074: # ------------------------------------------------------------------- user.name
 6075:         } elsif ($space eq 'name') {
 6076:             return $uname;
 6077: # ---------------------------------------------------- Any other user namespace
 6078:         } else {
 6079: 	    my %reply;
 6080: 	    if (!$publicuser) {
 6081: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6082: 	    }
 6083: 	    return $reply{$qualifierrest};
 6084:         }
 6085:     } elsif ($realm eq 'query') {
 6086: # ---------------------------------------------- pull stuff out of query string
 6087:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6088: 						[$spacequalifierrest]);
 6089: 	return $env{'form.'.$spacequalifierrest}; 
 6090:    } elsif ($realm eq 'request') {
 6091: # ------------------------------------------------------------- request.browser
 6092:         if ($space eq 'browser') {
 6093: 	    if ($qualifier eq 'textremote') {
 6094: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6095: 		    return 1;
 6096: 		} else {
 6097: 		    return 0;
 6098: 		}
 6099: 	    } else {
 6100: 		return $env{'browser.'.$qualifier};
 6101: 	    }
 6102: # ------------------------------------------------------------ request.filename
 6103:         } else {
 6104:             return $env{'request.'.$spacequalifierrest};
 6105:         }
 6106:     } elsif ($realm eq 'course') {
 6107: # ---------------------------------------------------------- course.description
 6108:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6109:     } elsif ($realm eq 'resource') {
 6110: 
 6111: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6112: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6113: 	}
 6114: 
 6115: 	if ($space eq 'title') {
 6116: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6117: 	    return &gettitle($symbparm);
 6118: 	}
 6119: 	
 6120: 	if ($space eq 'map') {
 6121: 	    my ($map) = &decode_symb($symbparm);
 6122: 	    return &symbread($map);
 6123: 	}
 6124: 
 6125: 	my ($section, $group, @groups);
 6126: 	my ($courselevelm,$courselevel);
 6127: 	if ($symbparm && defined($courseid) && 
 6128: 	    $courseid eq $env{'request.course.id'}) {
 6129: 
 6130: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6131: 
 6132: # ----------------------------------------------------- Cascading lookup scheme
 6133: 	    my $symbp=$symbparm;
 6134: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6135: 
 6136: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6137: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6138: 
 6139: 	    if (($env{'user.name'} eq $uname) &&
 6140: 		($env{'user.domain'} eq $udom)) {
 6141: 		$section=$env{'request.course.sec'};
 6142:                 @groups = split(/:/,$env{'request.course.groups'});  
 6143:                 @groups=&sort_course_groups($courseid,@groups); 
 6144: 	    } else {
 6145: 		if (! defined($usection)) {
 6146: 		    $section=&getsection($udom,$uname,$courseid);
 6147: 		} else {
 6148: 		    $section = $usection;
 6149: 		}
 6150:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6151: 	    }
 6152: 
 6153: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6154: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6155: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6156: 
 6157: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6158: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6159: 	    $courselevelm=$courseid.'.'.$mapparm;
 6160: 
 6161: # ----------------------------------------------------------- first, check user
 6162: 
 6163: 	    my $userreply=&resdata($uname,$udom,'user',
 6164: 				       ($courselevelr,$courselevelm,
 6165: 					$courselevel));
 6166: 	    if (defined($userreply)) { return $userreply; }
 6167: 
 6168: # ------------------------------------------------ second, check some of course
 6169:             my $coursereply;
 6170:             if (@groups > 0) {
 6171:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6172:                                        $mapparm,$spacequalifierrest);
 6173:                 if (defined($coursereply)) { return $coursereply; }
 6174:             }
 6175: 
 6176: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6177: 				     $env{'course.'.$courseid.'.domain'},
 6178: 				     'course',
 6179: 				     ($seclevelr,$seclevelm,$seclevel,
 6180: 				      $courselevelr));
 6181: 	    if (defined($coursereply)) { return $coursereply; }
 6182: 
 6183: # ------------------------------------------------------ third, check map parms
 6184: 	    my %parmhash=();
 6185: 	    my $thisparm='';
 6186: 	    if (tie(%parmhash,'GDBM_File',
 6187: 		    $env{'request.course.fn'}.'_parms.db',
 6188: 		    &GDBM_READER(),0640)) {
 6189: 		$thisparm=$parmhash{$symbparm};
 6190: 		untie(%parmhash);
 6191: 	    }
 6192: 	    if ($thisparm) { return $thisparm; }
 6193: 	}
 6194: # ------------------------------------------ fourth, look in resource metadata
 6195: 
 6196: 	$spacequalifierrest=~s/\./\_/;
 6197: 	my $filename;
 6198: 	if (!$symbparm) { $symbparm=&symbread(); }
 6199: 	if ($symbparm) {
 6200: 	    $filename=(&decode_symb($symbparm))[2];
 6201: 	} else {
 6202: 	    $filename=$env{'request.filename'};
 6203: 	}
 6204: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6205: 	if (defined($metadata)) { return $metadata; }
 6206: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6207: 	if (defined($metadata)) { return $metadata; }
 6208: 
 6209: # ---------------------------------------------- fourth, look in rest pf course
 6210: 	if ($symbparm && defined($courseid) && 
 6211: 	    $courseid eq $env{'request.course.id'}) {
 6212: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6213: 				     $env{'course.'.$courseid.'.domain'},
 6214: 				     'course',
 6215: 				     ($courselevelm,$courselevel));
 6216: 	    if (defined($coursereply)) { return $coursereply; }
 6217: 	}
 6218: # ------------------------------------------------------------------ Cascade up
 6219: 	unless ($space eq '0') {
 6220: 	    my @parts=split(/_/,$space);
 6221: 	    my $id=pop(@parts);
 6222: 	    my $part=join('_',@parts);
 6223: 	    if ($part eq '') { $part='0'; }
 6224: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6225: 				 $symbparm,$udom,$uname,$section,1);
 6226: 	    if (defined($partgeneral)) { return $partgeneral; }
 6227: 	}
 6228: 	if ($recurse) { return undef; }
 6229: 	my $pack_def=&packages_tab_default($filename,$varname);
 6230: 	if (defined($pack_def)) { return $pack_def; }
 6231: 
 6232: # ---------------------------------------------------- Any other user namespace
 6233:     } elsif ($realm eq 'environment') {
 6234: # ----------------------------------------------------------------- environment
 6235: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6236: 	    return $env{'environment.'.$spacequalifierrest};
 6237: 	} else {
 6238: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6239: 		return '';
 6240: 	    }
 6241: 	    my %returnhash=&userenvironment($udom,$uname,
 6242: 					    $spacequalifierrest);
 6243: 	    return $returnhash{$spacequalifierrest};
 6244: 	}
 6245:     } elsif ($realm eq 'system') {
 6246: # ----------------------------------------------------------------- system.time
 6247: 	if ($space eq 'time') {
 6248: 	    return time;
 6249:         }
 6250:     } elsif ($realm eq 'server') {
 6251: # ----------------------------------------------------------------- system.time
 6252: 	if ($space eq 'name') {
 6253: 	    return $ENV{'SERVER_NAME'};
 6254:         }
 6255:     }
 6256:     return '';
 6257: }
 6258: 
 6259: sub check_group_parms {
 6260:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6261:     my @groupitems = ();
 6262:     my $resultitem;
 6263:     my @levels = ($symbparm,$mapparm,$what);
 6264:     foreach my $group (@{$groups}) {
 6265:         foreach my $level (@levels) {
 6266:              my $item = $courseid.'.['.$group.'].'.$level;
 6267:              push(@groupitems,$item);
 6268:         }
 6269:     }
 6270:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6271:                             $env{'course.'.$courseid.'.domain'},
 6272:                                      'course',@groupitems);
 6273:     return $coursereply;
 6274: }
 6275: 
 6276: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6277:     my ($courseid,@groups) = @_;
 6278:     @groups = sort(@groups);
 6279:     return @groups;
 6280: }
 6281: 
 6282: sub packages_tab_default {
 6283:     my ($uri,$varname)=@_;
 6284:     my (undef,$part,$name)=split(/\./,$varname);
 6285: 
 6286:     my (@extension,@specifics,$do_default);
 6287:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6288: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6289: 	if ($pack_type eq 'default') {
 6290: 	    $do_default=1;
 6291: 	} elsif ($pack_type eq 'extension') {
 6292: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6293: 	} elsif ($pack_part eq $part) {
 6294: 	    # only look at packages defaults for packages that this id is
 6295: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6296: 	}
 6297:     }
 6298:     # first look for a package that matches the requested part id
 6299:     foreach my $package (@specifics) {
 6300: 	my (undef,$pack_type,$pack_part)=@{$package};
 6301: 	next if ($pack_part ne $part);
 6302: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6303: 	    return $packagetab{"$pack_type&$name&default"};
 6304: 	}
 6305:     }
 6306:     # look for any possible matching non extension_ package
 6307:     foreach my $package (@specifics) {
 6308: 	my (undef,$pack_type,$pack_part)=@{$package};
 6309: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6310: 	    return $packagetab{"$pack_type&$name&default"};
 6311: 	}
 6312: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6313: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6314: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6315: 	}
 6316:     }
 6317:     # look for any posible extension_ match
 6318:     foreach my $package (@extension) {
 6319: 	my ($package,$pack_type)=@{$package};
 6320: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6321: 	    return $packagetab{"$pack_type&$name&default"};
 6322: 	}
 6323: 	if (defined($packagetab{$package."&$name&default"})) {
 6324: 	    return $packagetab{$package."&$name&default"};
 6325: 	}
 6326:     }
 6327:     # look for a global default setting
 6328:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6329: 	return $packagetab{"default&$name&default"};
 6330:     }
 6331:     return undef;
 6332: }
 6333: 
 6334: sub add_prefix_and_part {
 6335:     my ($prefix,$part)=@_;
 6336:     my $keyroot;
 6337:     if (defined($prefix) && $prefix !~ /^__/) {
 6338: 	# prefix that has a part already
 6339: 	$keyroot=$prefix;
 6340:     } elsif (defined($prefix)) {
 6341: 	# prefix that is missing a part
 6342: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6343:     } else {
 6344: 	# no prefix at all
 6345: 	if (defined($part)) { $keyroot='_'.$part; }
 6346:     }
 6347:     return $keyroot;
 6348: }
 6349: 
 6350: # ---------------------------------------------------------------- Get metadata
 6351: 
 6352: my %metaentry;
 6353: sub metadata {
 6354:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6355:     $uri=&declutter($uri);
 6356:     # if it is a non metadata possible uri return quickly
 6357:     if (($uri eq '') || 
 6358: 	(($uri =~ m|^/*adm/|) && 
 6359: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6360:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6361: 	($uri =~ m|home/$match_username/public_html/|)) {
 6362: 	return undef;
 6363:     }
 6364:     my $filename=$uri;
 6365:     $uri=~s/\.meta$//;
 6366: #
 6367: # Is the metadata already cached?
 6368: # Look at timestamp of caching
 6369: # Everything is cached by the main uri, libraries are never directly cached
 6370: #
 6371:     if (!defined($liburi)) {
 6372: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6373: 	if (defined($cached)) { return $result->{':'.$what}; }
 6374:     }
 6375:     {
 6376: #
 6377: # Is this a recursive call for a library?
 6378: #
 6379: #	if (! exists($metacache{$uri})) {
 6380: #	    $metacache{$uri}={};
 6381: #	}
 6382:         if ($liburi) {
 6383: 	    $liburi=&declutter($liburi);
 6384:             $filename=$liburi;
 6385:         } else {
 6386: 	    &devalidate_cache_new('meta',$uri);
 6387: 	    undef(%metaentry);
 6388: 	}
 6389:         my %metathesekeys=();
 6390:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6391: 	my $metastring;
 6392: 	if ($uri !~ m -^(editupload)/-) {
 6393: 	    my $file=&filelocation('',&clutter($filename));
 6394: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6395: 	    $metastring=&getfile($file);
 6396: 	}
 6397:         my $parser=HTML::LCParser->new(\$metastring);
 6398:         my $token;
 6399:         undef %metathesekeys;
 6400:         while ($token=$parser->get_token) {
 6401: 	    if ($token->[0] eq 'S') {
 6402: 		if (defined($token->[2]->{'package'})) {
 6403: #
 6404: # This is a package - get package info
 6405: #
 6406: 		    my $package=$token->[2]->{'package'};
 6407: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6408: 		    if (defined($token->[2]->{'id'})) { 
 6409: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6410: 		    }
 6411: 		    if ($metaentry{':packages'}) {
 6412: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6413: 		    } else {
 6414: 			$metaentry{':packages'}=$package.$keyroot;
 6415: 		    }
 6416: 		    foreach my $pack_entry (keys(%packagetab)) {
 6417: 			my $part=$keyroot;
 6418: 			$part=~s/^\_//;
 6419: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6420: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6421: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6422: 			    # ignore package.tab specified default values
 6423:                             # here &package_tab_default() will fetch those
 6424: 			    if ($subp eq 'default') { next; }
 6425: 			    my $value=$packagetab{$pack_entry};
 6426: 			    my $unikey;
 6427: 			    if ($pack =~ /_0$/) {
 6428: 				$unikey='parameter_0_'.$name;
 6429: 				$part=0;
 6430: 			    } else {
 6431: 				$unikey='parameter'.$keyroot.'_'.$name;
 6432: 			    }
 6433: 			    if ($subp eq 'display') {
 6434: 				$value.=' [Part: '.$part.']';
 6435: 			    }
 6436: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6437: 			    $metathesekeys{$unikey}=1;
 6438: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6439: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6440: 			    }
 6441: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6442: 				$metaentry{':'.$unikey}=
 6443: 				    $metaentry{':'.$unikey.'.default'};
 6444: 			    }
 6445: 			}
 6446: 		    }
 6447: 		} else {
 6448: #
 6449: # This is not a package - some other kind of start tag
 6450: #
 6451: 		    my $entry=$token->[1];
 6452: 		    my $unikey;
 6453: 		    if ($entry eq 'import') {
 6454: 			$unikey='';
 6455: 		    } else {
 6456: 			$unikey=$entry;
 6457: 		    }
 6458: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6459: 
 6460: 		    if (defined($token->[2]->{'id'})) { 
 6461: 			$unikey.='_'.$token->[2]->{'id'}; 
 6462: 		    }
 6463: 
 6464: 		    if ($entry eq 'import') {
 6465: #
 6466: # Importing a library here
 6467: #
 6468: 			if ($depthcount<20) {
 6469: 			    my $location=$parser->get_text('/import');
 6470: 			    my $dir=$filename;
 6471: 			    $dir=~s|[^/]*$||;
 6472: 			    $location=&filelocation($dir,$location);
 6473: 			    my $metadata = 
 6474: 				&metadata($uri,'keys', $location,$unikey,
 6475: 					  $depthcount+1);
 6476: 			    foreach my $meta (split(',',$metadata)) {
 6477: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6478: 				$metathesekeys{$meta}=1;
 6479: 			    }
 6480: 			}
 6481: 		    } else { 
 6482: 			
 6483: 			if (defined($token->[2]->{'name'})) { 
 6484: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6485: 			}
 6486: 			$metathesekeys{$unikey}=1;
 6487: 			foreach my $param (@{$token->[3]}) {
 6488: 			    $metaentry{':'.$unikey.'.'.$param} =
 6489: 				$token->[2]->{$param};
 6490: 			}
 6491: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6492: 			my $default=$metaentry{':'.$unikey.'.default'};
 6493: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6494: 		 # only ws inside the tag, and not in default, so use default
 6495: 		 # as value
 6496: 			    $metaentry{':'.$unikey}=$default;
 6497: 			} else {
 6498: 		  # either something interesting inside the tag or default
 6499:                   # uninteresting
 6500: 			    $metaentry{':'.$unikey}=$internaltext;
 6501: 			}
 6502: # end of not-a-package not-a-library import
 6503: 		    }
 6504: # end of not-a-package start tag
 6505: 		}
 6506: # the next is the end of "start tag"
 6507: 	    }
 6508: 	}
 6509: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6510: 	foreach my $key (keys(%packagetab)) {
 6511: 	    #no specific packages #how's our extension
 6512: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6513: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6514: 					 \%metathesekeys);
 6515: 	}
 6516: 	if (!exists($metaentry{':packages'})) {
 6517: 	    foreach my $key (keys(%packagetab)) {
 6518: 		#no specific packages well let's get default then
 6519: 		if ($key!~/^default&/) { next; }
 6520: 		&metadata_create_package_def($uri,$key,'default',
 6521: 					     \%metathesekeys);
 6522: 	    }
 6523: 	}
 6524: # are there custom rights to evaluate
 6525: 	if ($metaentry{':copyright'} eq 'custom') {
 6526: 
 6527:     #
 6528:     # Importing a rights file here
 6529:     #
 6530: 	    unless ($depthcount) {
 6531: 		my $location=$metaentry{':customdistributionfile'};
 6532: 		my $dir=$filename;
 6533: 		$dir=~s|[^/]*$||;
 6534: 		$location=&filelocation($dir,$location);
 6535: 		my $rights_metadata =
 6536: 		    &metadata($uri,'keys',$location,'_rights',
 6537: 			      $depthcount+1);
 6538: 		foreach my $rights (split(',',$rights_metadata)) {
 6539: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6540: 		    $metathesekeys{$rights}=1;
 6541: 		}
 6542: 	    }
 6543: 	}
 6544: 	# uniqifiy package listing
 6545: 	my %seen;
 6546: 	my @uniq_packages =
 6547: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6548: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6549: 
 6550: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6551: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6552: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6553: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6554: # this is the end of "was not already recently cached
 6555:     }
 6556:     return $metaentry{':'.$what};
 6557: }
 6558: 
 6559: sub metadata_create_package_def {
 6560:     my ($uri,$key,$package,$metathesekeys)=@_;
 6561:     my ($pack,$name,$subp)=split(/\&/,$key);
 6562:     if ($subp eq 'default') { next; }
 6563:     
 6564:     if (defined($metaentry{':packages'})) {
 6565: 	$metaentry{':packages'}.=','.$package;
 6566:     } else {
 6567: 	$metaentry{':packages'}=$package;
 6568:     }
 6569:     my $value=$packagetab{$key};
 6570:     my $unikey;
 6571:     $unikey='parameter_0_'.$name;
 6572:     $metaentry{':'.$unikey.'.part'}=0;
 6573:     $$metathesekeys{$unikey}=1;
 6574:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6575: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6576:     }
 6577:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6578: 	$metaentry{':'.$unikey}=
 6579: 	    $metaentry{':'.$unikey.'.default'};
 6580:     }
 6581: }
 6582: 
 6583: sub metadata_generate_part0 {
 6584:     my ($metadata,$metacache,$uri) = @_;
 6585:     my %allnames;
 6586:     foreach my $metakey (keys(%$metadata)) {
 6587: 	if ($metakey=~/^parameter\_(.*)/) {
 6588: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6589: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6590: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6591: 	    $allnames{$name}=$part;
 6592: 	  }
 6593: 	}
 6594:     }
 6595:     foreach my $name (keys(%allnames)) {
 6596:       $$metadata{"parameter_0_$name"}=1;
 6597:       my $key=":parameter_0_$name";
 6598:       $$metacache{"$key.part"}='0';
 6599:       $$metacache{"$key.name"}=$name;
 6600:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6601: 					   $allnames{$name}.'_'.$name.
 6602: 					   '.type'};
 6603:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6604: 			     '.display'};
 6605:       my $expr='[Part: '.$allnames{$name}.']';
 6606:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6607:       $$metacache{"$key.display"}=$olddis;
 6608:     }
 6609: }
 6610: 
 6611: # ------------------------------------------------------ Devalidate title cache
 6612: 
 6613: sub devalidate_title_cache {
 6614:     my ($url)=@_;
 6615:     if (!$env{'request.course.id'}) { return; }
 6616:     my $symb=&symbread($url);
 6617:     if (!$symb) { return; }
 6618:     my $key=$env{'request.course.id'}."\0".$symb;
 6619:     &devalidate_cache_new('title',$key);
 6620: }
 6621: 
 6622: # ------------------------------------------------- Get the title of a resource
 6623: 
 6624: sub gettitle {
 6625:     my $urlsymb=shift;
 6626:     my $symb=&symbread($urlsymb);
 6627:     if ($symb) {
 6628: 	my $key=$env{'request.course.id'}."\0".$symb;
 6629: 	my ($result,$cached)=&is_cached_new('title',$key);
 6630: 	if (defined($cached)) { 
 6631: 	    return $result;
 6632: 	}
 6633: 	my ($map,$resid,$url)=&decode_symb($symb);
 6634: 	my $title='';
 6635: 	my %bighash;
 6636: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6637: 		&GDBM_READER(),0640)) {
 6638: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6639: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6640: 	    untie %bighash;
 6641: 	}
 6642: 	$title=~s/\&colon\;/\:/gs;
 6643: 	if ($title) {
 6644: 	    return &do_cache_new('title',$key,$title,600);
 6645: 	}
 6646: 	$urlsymb=$url;
 6647:     }
 6648:     my $title=&metadata($urlsymb,'title');
 6649:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6650:     return $title;
 6651: }
 6652: 
 6653: sub get_slot {
 6654:     my ($which,$cnum,$cdom)=@_;
 6655:     if (!$cnum || !$cdom) {
 6656: 	(undef,my $courseid)=&whichuser();
 6657: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6658: 	$cnum=$env{'course.'.$courseid.'.num'};
 6659:     }
 6660:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6661:     my %slotinfo;
 6662:     if (exists($remembered{$key})) {
 6663: 	$slotinfo{$which} = $remembered{$key};
 6664:     } else {
 6665: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6666: 	&Apache::lonhomework::showhash(%slotinfo);
 6667: 	my ($tmp)=keys(%slotinfo);
 6668: 	if ($tmp=~/^error:/) { return (); }
 6669: 	$remembered{$key} = $slotinfo{$which};
 6670:     }
 6671:     if (ref($slotinfo{$which}) eq 'HASH') {
 6672: 	return %{$slotinfo{$which}};
 6673:     }
 6674:     return $slotinfo{$which};
 6675: }
 6676: # ------------------------------------------------- Update symbolic store links
 6677: 
 6678: sub symblist {
 6679:     my ($mapname,%newhash)=@_;
 6680:     $mapname=&deversion(&declutter($mapname));
 6681:     my %hash;
 6682:     if (($env{'request.course.fn'}) && (%newhash)) {
 6683:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6684:                       &GDBM_WRCREAT(),0640)) {
 6685: 	    foreach my $url (keys %newhash) {
 6686: 		next if ($url eq 'last_known'
 6687: 			 && $env{'form.no_update_last_known'});
 6688: 		$hash{declutter($url)}=&encode_symb($mapname,
 6689: 						    $newhash{$url}->[1],
 6690: 						    $newhash{$url}->[0]);
 6691:             }
 6692:             if (untie(%hash)) {
 6693: 		return 'ok';
 6694:             }
 6695:         }
 6696:     }
 6697:     return 'error';
 6698: }
 6699: 
 6700: # --------------------------------------------------------------- Verify a symb
 6701: 
 6702: sub symbverify {
 6703:     my ($symb,$thisurl)=@_;
 6704:     my $thisfn=$thisurl;
 6705:     $thisfn=&declutter($thisfn);
 6706: # direct jump to resource in page or to a sequence - will construct own symbs
 6707:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6708: # check URL part
 6709:     my ($map,$resid,$url)=&decode_symb($symb);
 6710: 
 6711:     unless ($url eq $thisfn) { return 0; }
 6712: 
 6713:     $symb=&symbclean($symb);
 6714:     $thisurl=&deversion($thisurl);
 6715:     $thisfn=&deversion($thisfn);
 6716: 
 6717:     my %bighash;
 6718:     my $okay=0;
 6719: 
 6720:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6721:                             &GDBM_READER(),0640)) {
 6722:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6723:         unless ($ids) { 
 6724:            $ids=$bighash{'ids_/'.$thisurl};
 6725:         }
 6726:         if ($ids) {
 6727: # ------------------------------------------------------------------- Has ID(s)
 6728: 	    foreach my $id (split(/\,/,$ids)) {
 6729: 	       my ($mapid,$resid)=split(/\./,$id);
 6730:                if (
 6731:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6732:    eq $symb) { 
 6733: 		   if (($env{'request.role.adv'}) ||
 6734: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6735: 		       $okay=1; 
 6736: 		   }
 6737: 	       }
 6738: 	   }
 6739:         }
 6740: 	untie(%bighash);
 6741:     }
 6742:     return $okay;
 6743: }
 6744: 
 6745: # --------------------------------------------------------------- Clean-up symb
 6746: 
 6747: sub symbclean {
 6748:     my $symb=shift;
 6749:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6750: # remove version from map
 6751:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6752: 
 6753: # remove version from URL
 6754:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6755: 
 6756: # remove wrapper
 6757: 
 6758:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6759:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6760:     return $symb;
 6761: }
 6762: 
 6763: # ---------------------------------------------- Split symb to find map and url
 6764: 
 6765: sub encode_symb {
 6766:     my ($map,$resid,$url)=@_;
 6767:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6768: }
 6769: 
 6770: sub decode_symb {
 6771:     my $symb=shift;
 6772:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6773:     my ($map,$resid,$url)=split(/___/,$symb);
 6774:     return (&fixversion($map),$resid,&fixversion($url));
 6775: }
 6776: 
 6777: sub fixversion {
 6778:     my $fn=shift;
 6779:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6780:     my %bighash;
 6781:     my $uri=&clutter($fn);
 6782:     my $key=$env{'request.course.id'}.'_'.$uri;
 6783: # is this cached?
 6784:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6785:     if (defined($cached)) { return $result; }
 6786: # unfortunately not cached, or expired
 6787:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6788: 	    &GDBM_READER(),0640)) {
 6789:  	if ($bighash{'version_'.$uri}) {
 6790:  	    my $version=$bighash{'version_'.$uri};
 6791:  	    unless (($version eq 'mostrecent') || 
 6792: 		    ($version==&getversion($uri))) {
 6793:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6794:  	    }
 6795:  	}
 6796:  	untie %bighash;
 6797:     }
 6798:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6799: }
 6800: 
 6801: sub deversion {
 6802:     my $url=shift;
 6803:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6804:     return $url;
 6805: }
 6806: 
 6807: # ------------------------------------------------------ Return symb list entry
 6808: 
 6809: sub symbread {
 6810:     my ($thisfn,$donotrecurse)=@_;
 6811:     my $cache_str='request.symbread.cached.'.$thisfn;
 6812:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6813: # no filename provided? try from environment
 6814:     unless ($thisfn) {
 6815:         if ($env{'request.symb'}) {
 6816: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6817: 	}
 6818: 	$thisfn=$env{'request.filename'};
 6819:     }
 6820:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6821: # is that filename actually a symb? Verify, clean, and return
 6822:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6823: 	if (&symbverify($thisfn,$1)) {
 6824: 	    return $env{$cache_str}=&symbclean($thisfn);
 6825: 	}
 6826:     }
 6827:     $thisfn=declutter($thisfn);
 6828:     my %hash;
 6829:     my %bighash;
 6830:     my $syval='';
 6831:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6832:         my $targetfn = $thisfn;
 6833:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6834:             $targetfn = 'adm/wrapper/'.$thisfn;
 6835:         }
 6836: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6837: 	    $targetfn=$1;
 6838: 	}
 6839:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6840:                       &GDBM_READER(),0640)) {
 6841: 	    $syval=$hash{$targetfn};
 6842:             untie(%hash);
 6843:         }
 6844: # ---------------------------------------------------------- There was an entry
 6845:         if ($syval) {
 6846: 	    #unless ($syval=~/\_\d+$/) {
 6847: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6848: 		    #&appenv('request.ambiguous' => $thisfn);
 6849: 		    #return $env{$cache_str}='';
 6850: 		#}    
 6851: 		#$syval.=$1;
 6852: 	    #}
 6853:         } else {
 6854: # ------------------------------------------------------- Was not in symb table
 6855:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6856:                             &GDBM_READER(),0640)) {
 6857: # ---------------------------------------------- Get ID(s) for current resource
 6858:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6859:               unless ($ids) { 
 6860:                  $ids=$bighash{'ids_/'.$thisfn};
 6861:               }
 6862:               unless ($ids) {
 6863: # alias?
 6864: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6865:               }
 6866:               if ($ids) {
 6867: # ------------------------------------------------------------------- Has ID(s)
 6868:                  my @possibilities=split(/\,/,$ids);
 6869:                  if ($#possibilities==0) {
 6870: # ----------------------------------------------- There is only one possibility
 6871: 		     my ($mapid,$resid)=split(/\./,$ids);
 6872: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6873: 						    $resid,$thisfn);
 6874:                  } elsif (!$donotrecurse) {
 6875: # ------------------------------------------ There is more than one possibility
 6876:                      my $realpossible=0;
 6877:                      foreach my $id (@possibilities) {
 6878: 			 my $file=$bighash{'src_'.$id};
 6879:                          if (&allowed('bre',$file)) {
 6880:          		    my ($mapid,$resid)=split(/\./,$id);
 6881:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6882: 				$realpossible++;
 6883:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6884: 						    $resid,$thisfn);
 6885:                             }
 6886: 			 }
 6887:                      }
 6888: 		     if ($realpossible!=1) { $syval=''; }
 6889:                  } else {
 6890:                      $syval='';
 6891:                  }
 6892: 	      }
 6893:               untie(%bighash)
 6894:            }
 6895:         }
 6896:         if ($syval) {
 6897: 	    return $env{$cache_str}=$syval;
 6898:         }
 6899:     }
 6900:     &appenv('request.ambiguous' => $thisfn);
 6901:     return $env{$cache_str}='';
 6902: }
 6903: 
 6904: # ---------------------------------------------------------- Return random seed
 6905: 
 6906: sub numval {
 6907:     my $txt=shift;
 6908:     $txt=~tr/A-J/0-9/;
 6909:     $txt=~tr/a-j/0-9/;
 6910:     $txt=~tr/K-T/0-9/;
 6911:     $txt=~tr/k-t/0-9/;
 6912:     $txt=~tr/U-Z/0-5/;
 6913:     $txt=~tr/u-z/0-5/;
 6914:     $txt=~s/\D//g;
 6915:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6916:     return int($txt);
 6917: }
 6918: 
 6919: sub numval2 {
 6920:     my $txt=shift;
 6921:     $txt=~tr/A-J/0-9/;
 6922:     $txt=~tr/a-j/0-9/;
 6923:     $txt=~tr/K-T/0-9/;
 6924:     $txt=~tr/k-t/0-9/;
 6925:     $txt=~tr/U-Z/0-5/;
 6926:     $txt=~tr/u-z/0-5/;
 6927:     $txt=~s/\D//g;
 6928:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6929:     my $total;
 6930:     foreach my $val (@txts) { $total+=$val; }
 6931:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6932:     return int($total);
 6933: }
 6934: 
 6935: sub numval3 {
 6936:     use integer;
 6937:     my $txt=shift;
 6938:     $txt=~tr/A-J/0-9/;
 6939:     $txt=~tr/a-j/0-9/;
 6940:     $txt=~tr/K-T/0-9/;
 6941:     $txt=~tr/k-t/0-9/;
 6942:     $txt=~tr/U-Z/0-5/;
 6943:     $txt=~tr/u-z/0-5/;
 6944:     $txt=~s/\D//g;
 6945:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6946:     my $total;
 6947:     foreach my $val (@txts) { $total+=$val; }
 6948:     if ($_64bit) { $total=(($total<<32)>>32); }
 6949:     return $total;
 6950: }
 6951: 
 6952: sub digest {
 6953:     my ($data)=@_;
 6954:     my $digest=&Digest::MD5::md5($data);
 6955:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6956:     my ($e,$f);
 6957:     {
 6958:         use integer;
 6959:         $e=($a+$b);
 6960:         $f=($c+$d);
 6961:         if ($_64bit) {
 6962:             $e=(($e<<32)>>32);
 6963:             $f=(($f<<32)>>32);
 6964:         }
 6965:     }
 6966:     if (wantarray) {
 6967: 	return ($e,$f);
 6968:     } else {
 6969: 	my $g;
 6970: 	{
 6971: 	    use integer;
 6972: 	    $g=($e+$f);
 6973: 	    if ($_64bit) {
 6974: 		$g=(($g<<32)>>32);
 6975: 	    }
 6976: 	}
 6977: 	return $g;
 6978:     }
 6979: }
 6980: 
 6981: sub latest_rnd_algorithm_id {
 6982:     return '64bit5';
 6983: }
 6984: 
 6985: sub get_rand_alg {
 6986:     my ($courseid)=@_;
 6987:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6988:     if ($courseid) {
 6989: 	return $env{"course.$courseid.rndseed"};
 6990:     }
 6991:     return &latest_rnd_algorithm_id();
 6992: }
 6993: 
 6994: sub validCODE {
 6995:     my ($CODE)=@_;
 6996:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6997:     return 0;
 6998: }
 6999: 
 7000: sub getCODE {
 7001:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7002:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7003: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7004: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7005: 	return $Apache::lonhomework::history{'resource.CODE'};
 7006:     }
 7007:     return undef;
 7008: }
 7009: 
 7010: sub rndseed {
 7011:     my ($symb,$courseid,$domain,$username)=@_;
 7012:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7013:     if (!$symb) {
 7014: 	unless ($symb=$wsymb) { return time; }
 7015:     }
 7016:     if (!$courseid) { $courseid=$wcourseid; }
 7017:     if (!$domain) { $domain=$wdomain; }
 7018:     if (!$username) { $username=$wusername }
 7019:     my $which=&get_rand_alg();
 7020: 
 7021:     if (defined(&getCODE())) {
 7022: 	if ($which eq '64bit5') {
 7023: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7024: 	} elsif ($which eq '64bit4') {
 7025: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7026: 	} else {
 7027: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7028: 	}
 7029:     } elsif ($which eq '64bit5') {
 7030: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7031:     } elsif ($which eq '64bit4') {
 7032: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7033:     } elsif ($which eq '64bit3') {
 7034: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7035:     } elsif ($which eq '64bit2') {
 7036: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7037:     } elsif ($which eq '64bit') {
 7038: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7039:     }
 7040:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7041: }
 7042: 
 7043: sub rndseed_32bit {
 7044:     my ($symb,$courseid,$domain,$username)=@_;
 7045:     {
 7046: 	use integer;
 7047: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7048: 	my $symbseed=numval($symb) << 22;
 7049: 	my $namechck=unpack("%32C*",$username) << 17;
 7050: 	my $nameseed=numval($username) << 12;
 7051: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7052: 	my $courseseed=unpack("%32C*",$courseid);
 7053: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7055: 	#&logthis("rndseed :$num:$symb");
 7056: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7057: 	return $num;
 7058:     }
 7059: }
 7060: 
 7061: sub rndseed_64bit {
 7062:     my ($symb,$courseid,$domain,$username)=@_;
 7063:     {
 7064: 	use integer;
 7065: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7066: 	my $symbseed=numval($symb) << 10;
 7067: 	my $namechck=unpack("%32S*",$username);
 7068: 	
 7069: 	my $nameseed=numval($username) << 21;
 7070: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7071: 	my $courseseed=unpack("%32S*",$courseid);
 7072: 	
 7073: 	my $num1=$symbchck+$symbseed+$namechck;
 7074: 	my $num2=$nameseed+$domainseed+$courseseed;
 7075: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7076: 	#&logthis("rndseed :$num:$symb");
 7077: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7078: 	return "$num1,$num2";
 7079:     }
 7080: }
 7081: 
 7082: sub rndseed_64bit2 {
 7083:     my ($symb,$courseid,$domain,$username)=@_;
 7084:     {
 7085: 	use integer;
 7086: 	# strings need to be an even # of cahracters long, it it is odd the
 7087:         # last characters gets thrown away
 7088: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7089: 	my $symbseed=numval($symb) << 10;
 7090: 	my $namechck=unpack("%32S*",$username.' ');
 7091: 	
 7092: 	my $nameseed=numval($username) << 21;
 7093: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7094: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7095: 	
 7096: 	my $num1=$symbchck+$symbseed+$namechck;
 7097: 	my $num2=$nameseed+$domainseed+$courseseed;
 7098: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7099: 	#&logthis("rndseed :$num:$symb");
 7100: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7101: 	return "$num1,$num2";
 7102:     }
 7103: }
 7104: 
 7105: sub rndseed_64bit3 {
 7106:     my ($symb,$courseid,$domain,$username)=@_;
 7107:     {
 7108: 	use integer;
 7109: 	# strings need to be an even # of cahracters long, it it is odd the
 7110:         # last characters gets thrown away
 7111: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7112: 	my $symbseed=numval2($symb) << 10;
 7113: 	my $namechck=unpack("%32S*",$username.' ');
 7114: 	
 7115: 	my $nameseed=numval2($username) << 21;
 7116: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7117: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7118: 	
 7119: 	my $num1=$symbchck+$symbseed+$namechck;
 7120: 	my $num2=$nameseed+$domainseed+$courseseed;
 7121: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7122: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7123: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7124: 	
 7125: 	return "$num1:$num2";
 7126:     }
 7127: }
 7128: 
 7129: sub rndseed_64bit4 {
 7130:     my ($symb,$courseid,$domain,$username)=@_;
 7131:     {
 7132: 	use integer;
 7133: 	# strings need to be an even # of cahracters long, it it is odd the
 7134:         # last characters gets thrown away
 7135: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7136: 	my $symbseed=numval3($symb) << 10;
 7137: 	my $namechck=unpack("%32S*",$username.' ');
 7138: 	
 7139: 	my $nameseed=numval3($username) << 21;
 7140: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7141: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7142: 	
 7143: 	my $num1=$symbchck+$symbseed+$namechck;
 7144: 	my $num2=$nameseed+$domainseed+$courseseed;
 7145: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7146: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7147: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7148: 	
 7149: 	return "$num1:$num2";
 7150:     }
 7151: }
 7152: 
 7153: sub rndseed_64bit5 {
 7154:     my ($symb,$courseid,$domain,$username)=@_;
 7155:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7156:     return "$num1:$num2";
 7157: }
 7158: 
 7159: sub rndseed_CODE_64bit {
 7160:     my ($symb,$courseid,$domain,$username)=@_;
 7161:     {
 7162: 	use integer;
 7163: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7164: 	my $symbseed=numval2($symb);
 7165: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7166: 	my $CODEseed=numval(&getCODE());
 7167: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7168: 	my $num1=$symbseed+$CODEchck;
 7169: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7170: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7171: 	#&logthis("rndseed :$num1:$num2:$symb");
 7172: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7173: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7174: 	return "$num1:$num2";
 7175:     }
 7176: }
 7177: 
 7178: sub rndseed_CODE_64bit4 {
 7179:     my ($symb,$courseid,$domain,$username)=@_;
 7180:     {
 7181: 	use integer;
 7182: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7183: 	my $symbseed=numval3($symb);
 7184: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7185: 	my $CODEseed=numval3(&getCODE());
 7186: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7187: 	my $num1=$symbseed+$CODEchck;
 7188: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7189: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7190: 	#&logthis("rndseed :$num1:$num2:$symb");
 7191: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7192: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7193: 	return "$num1:$num2";
 7194:     }
 7195: }
 7196: 
 7197: sub rndseed_CODE_64bit5 {
 7198:     my ($symb,$courseid,$domain,$username)=@_;
 7199:     my $code = &getCODE();
 7200:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7201:     return "$num1:$num2";
 7202: }
 7203: 
 7204: sub setup_random_from_rndseed {
 7205:     my ($rndseed)=@_;
 7206:     if ($rndseed =~/([,:])/) {
 7207: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7208: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7209:     } else {
 7210: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7211:     }
 7212: }
 7213: 
 7214: sub latest_receipt_algorithm_id {
 7215:     return 'receipt3';
 7216: }
 7217: 
 7218: sub recunique {
 7219:     my $fucourseid=shift;
 7220:     my $unique;
 7221:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7222: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7223: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7224:     } else {
 7225: 	$unique=$perlvar{'lonReceipt'};
 7226:     }
 7227:     return unpack("%32C*",$unique);
 7228: }
 7229: 
 7230: sub recprefix {
 7231:     my $fucourseid=shift;
 7232:     my $prefix;
 7233:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7234: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7235: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7236:     } else {
 7237: 	$prefix=$perlvar{'lonHostID'};
 7238:     }
 7239:     return unpack("%32C*",$prefix);
 7240: }
 7241: 
 7242: sub ireceipt {
 7243:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7244: 
 7245:     my $return =&recprefix($fucourseid).'-';
 7246: 
 7247:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7248: 	$env{'request.state'} eq 'construct') {
 7249: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7250: 	return $return;
 7251:     }
 7252: 
 7253:     my $cuname=unpack("%32C*",$funame);
 7254:     my $cudom=unpack("%32C*",$fudom);
 7255:     my $cucourseid=unpack("%32C*",$fucourseid);
 7256:     my $cusymb=unpack("%32C*",$fusymb);
 7257:     my $cunique=&recunique($fucourseid);
 7258:     my $cpart=unpack("%32S*",$part);
 7259:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7260: 
 7261: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7262: 			       
 7263: 	$return.= ($cunique%$cuname+
 7264: 		   $cunique%$cudom+
 7265: 		   $cusymb%$cuname+
 7266: 		   $cusymb%$cudom+
 7267: 		   $cucourseid%$cuname+
 7268: 		   $cucourseid%$cudom+
 7269: 		   $cpart%$cuname+
 7270: 		   $cpart%$cudom);
 7271:     } else {
 7272: 	$return.= ($cunique%$cuname+
 7273: 		   $cunique%$cudom+
 7274: 		   $cusymb%$cuname+
 7275: 		   $cusymb%$cudom+
 7276: 		   $cucourseid%$cuname+
 7277: 		   $cucourseid%$cudom);
 7278:     }
 7279:     return $return;
 7280: }
 7281: 
 7282: sub receipt {
 7283:     my ($part)=@_;
 7284:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7285:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7286: }
 7287: 
 7288: sub whichuser {
 7289:     my ($passedsymb)=@_;
 7290:     my ($symb,$courseid,$domain,$name,$publicuser);
 7291:     if (defined($env{'form.grade_symb'})) {
 7292: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7293: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7294: 	if (!$allowed &&
 7295: 	    exists($env{'request.course.sec'}) &&
 7296: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7297: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7298: 			      '/'.$env{'request.course.sec'});
 7299: 	}
 7300: 	if ($allowed) {
 7301: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7302: 	    $courseid=$tmp_courseid;
 7303: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7304: 	    ($name)=&get_env_multiple('form.grade_username');
 7305: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7306: 	}
 7307:     }
 7308:     if (!$passedsymb) {
 7309: 	$symb=&symbread();
 7310:     } else {
 7311: 	$symb=$passedsymb;
 7312:     }
 7313:     $courseid=$env{'request.course.id'};
 7314:     $domain=$env{'user.domain'};
 7315:     $name=$env{'user.name'};
 7316:     if ($name eq 'public' && $domain eq 'public') {
 7317: 	if (!defined($env{'form.username'})) {
 7318: 	    $env{'form.username'}.=time.rand(10000000);
 7319: 	}
 7320: 	$name.=$env{'form.username'};
 7321:     }
 7322:     return ($symb,$courseid,$domain,$name,$publicuser);
 7323: 
 7324: }
 7325: 
 7326: # ------------------------------------------------------------ Serves up a file
 7327: # returns either the contents of the file or 
 7328: # -1 if the file doesn't exist
 7329: #
 7330: # if the target is a file that was uploaded via DOCS, 
 7331: # a check will be made to see if a current copy exists on the local server,
 7332: # if it does this will be served, otherwise a copy will be retrieved from
 7333: # the home server for the course and stored in /home/httpd/html/userfiles on
 7334: # the local server.   
 7335: 
 7336: sub getfile {
 7337:     my ($file) = @_;
 7338:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7339:     &repcopy($file);
 7340:     return &readfile($file);
 7341: }
 7342: 
 7343: sub repcopy_userfile {
 7344:     my ($file)=@_;
 7345:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7346:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7347:     my ($cdom,$cnum,$filename) = 
 7348: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7349:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7350:     if (-e "$file") {
 7351: # we already have a local copy, check it out
 7352: 	my @fileinfo = stat($file);
 7353: 	my $rtncode;
 7354: 	my $info;
 7355: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7356: 	if ($lwpresp ne 'ok') {
 7357: # there is no such file anymore, even though we had a local copy
 7358: 	    if ($rtncode eq '404') {
 7359: 		unlink($file);
 7360: 	    }
 7361: 	    return -1;
 7362: 	}
 7363: 	if ($info < $fileinfo[9]) {
 7364: # nice, the file we have is up-to-date, just say okay
 7365: 	    return 'ok';
 7366: 	} else {
 7367: # the file is outdated, get rid of it
 7368: 	    unlink($file);
 7369: 	}
 7370:     }
 7371: # one way or the other, at this point, we don't have the file
 7372: # construct the correct path for the file
 7373:     my @parts = ($cdom,$cnum); 
 7374:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7375: 	push @parts, split(/\//,$1);
 7376:     }
 7377:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7378:     foreach my $part (@parts) {
 7379: 	$path .= '/'.$part;
 7380: 	if (!-e $path) {
 7381: 	    mkdir($path,0770);
 7382: 	}
 7383:     }
 7384: # now the path exists for sure
 7385: # get a user agent
 7386:     my $ua=new LWP::UserAgent;
 7387:     my $transferfile=$file.'.in.transfer';
 7388: # FIXME: this should flock
 7389:     if (-e $transferfile) { return 'ok'; }
 7390:     my $request;
 7391:     $uri=~s/^\///;
 7392:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7393:     my $response=$ua->request($request,$transferfile);
 7394: # did it work?
 7395:     if ($response->is_error()) {
 7396: 	unlink($transferfile);
 7397: 	&logthis("Userfile repcopy failed for $uri");
 7398: 	return -1;
 7399:     }
 7400: # worked, rename the transfer file
 7401:     rename($transferfile,$file);
 7402:     return 'ok';
 7403: }
 7404: 
 7405: sub tokenwrapper {
 7406:     my $uri=shift;
 7407:     $uri=~s|^http\://([^/]+)||;
 7408:     $uri=~s|^/||;
 7409:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7410:     my $token=$1;
 7411:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7412:     if ($udom && $uname && $file) {
 7413: 	$file=~s|(\?\.*)*$||;
 7414:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7415:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7416:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7417:                                '&tokenissued='.$perlvar{'lonHostID'};
 7418:     } else {
 7419:         return '/adm/notfound.html';
 7420:     }
 7421: }
 7422: 
 7423: # call with reqtype HEAD: get last modification time
 7424: # call with reqtype GET: get the file contents
 7425: # Do not call this with reqtype GET for large files! It loads everything into memory
 7426: #
 7427: sub getuploaded {
 7428:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7429:     $uri=~s/^\///;
 7430:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7431:     my $ua=new LWP::UserAgent;
 7432:     my $request=new HTTP::Request($reqtype,$uri);
 7433:     my $response=$ua->request($request);
 7434:     $$rtncode = $response->code;
 7435:     if (! $response->is_success()) {
 7436: 	return 'failed';
 7437:     }      
 7438:     if ($reqtype eq 'HEAD') {
 7439: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7440:     } elsif ($reqtype eq 'GET') {
 7441: 	$$info = $response->content;
 7442:     }
 7443:     return 'ok';
 7444: }
 7445: 
 7446: sub readfile {
 7447:     my $file = shift;
 7448:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7449:     my $fh;
 7450:     open($fh,"<$file");
 7451:     my $a='';
 7452:     while (my $line = <$fh>) { $a .= $line; }
 7453:     return $a;
 7454: }
 7455: 
 7456: sub filelocation {
 7457:     my ($dir,$file) = @_;
 7458:     my $location;
 7459:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7460: 
 7461:     if ($file =~ m-^/adm/-) {
 7462: 	$file=~s-^/adm/wrapper/-/-;
 7463: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7464:     }
 7465:     if ($file=~m:^/~:) { # is a contruction space reference
 7466:         $location = $file;
 7467:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7468:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7469: 	# is a correct contruction space reference
 7470:         $location = $file;
 7471:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7472:         my ($udom,$uname,$filename)=
 7473:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7474:         my $home=&homeserver($uname,$udom);
 7475:         my $is_me=0;
 7476:         my @ids=&current_machine_ids();
 7477:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7478:         if ($is_me) {
 7479:   	    $location=&propath($udom,$uname).
 7480:   	      '/userfiles/'.$filename;
 7481:         } else {
 7482:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7483:   	      $udom.'/'.$uname.'/'.$filename;
 7484:         }
 7485:     } else {
 7486:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7487:         $file=~s:^/res/:/:;
 7488:         if ( !( $file =~ m:^/:) ) {
 7489:             $location = $dir. '/'.$file;
 7490:         } else {
 7491:             $location = '/home/httpd/html/res'.$file;
 7492:         }
 7493:     }
 7494:     $location=~s://+:/:g; # remove duplicate /
 7495:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7496:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7497:     return $location;
 7498: }
 7499: 
 7500: sub hreflocation {
 7501:     my ($dir,$file)=@_;
 7502:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7503: 	$file=filelocation($dir,$file);
 7504:     } elsif ($file=~m-^/adm/-) {
 7505: 	$file=~s-^/adm/wrapper/-/-;
 7506: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7507:     }
 7508:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7509: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7510:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7511: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7512:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7513: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7514: 	    -/uploaded/$1/$2/-x;
 7515:     }
 7516:     return $file;
 7517: }
 7518: 
 7519: sub current_machine_domains {
 7520:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7521: }
 7522: 
 7523: sub machine_domains {
 7524:     my ($hostname) = @_;
 7525:     my @domains;
 7526:     my %hostname = &all_hostnames();
 7527:     while( my($id, $name) = each(%hostname)) {
 7528: #	&logthis("-$id-$name-$hostname-");
 7529: 	if ($hostname eq $name) {
 7530: 	    push(@domains,&host_domain($id));
 7531: 	}
 7532:     }
 7533:     return @domains;
 7534: }
 7535: 
 7536: sub current_machine_ids {
 7537:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7538: }
 7539: 
 7540: sub machine_ids {
 7541:     my ($hostname) = @_;
 7542:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7543:     my @ids;
 7544:     my %hostname = &all_hostnames();
 7545:     while( my($id, $name) = each(%hostname)) {
 7546: #	&logthis("-$id-$name-$hostname-");
 7547: 	if ($hostname eq $name) {
 7548: 	    push(@ids,$id);
 7549: 	}
 7550:     }
 7551:     return @ids;
 7552: }
 7553: 
 7554: sub additional_machine_domains {
 7555:     my @domains;
 7556:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7557:     while( my $line = <$fh>) {
 7558:         $line =~ s/\s//g;
 7559:         push(@domains,$line);
 7560:     }
 7561:     return @domains;
 7562: }
 7563: 
 7564: sub default_login_domain {
 7565:     my $domain = $perlvar{'lonDefDomain'};
 7566:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7567:     foreach my $posdom (&current_machine_domains(),
 7568:                         &additional_machine_domains()) {
 7569:         if (lc($posdom) eq lc($testdomain)) {
 7570:             $domain=$posdom;
 7571:             last;
 7572:         }
 7573:     }
 7574:     return $domain;
 7575: }
 7576: 
 7577: # ------------------------------------------------------------- Declutters URLs
 7578: 
 7579: sub declutter {
 7580:     my $thisfn=shift;
 7581:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7582:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7583:     $thisfn=~s/^\///;
 7584:     $thisfn=~s|^adm/wrapper/||;
 7585:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7586:     $thisfn=~s/^res\///;
 7587:     $thisfn=~s/\?.+$//;
 7588:     return $thisfn;
 7589: }
 7590: 
 7591: # ------------------------------------------------------------- Clutter up URLs
 7592: 
 7593: sub clutter {
 7594:     my $thisfn='/'.&declutter(shift);
 7595:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7596:        $thisfn='/res'.$thisfn; 
 7597:     }
 7598:     if ($thisfn !~m|/adm|) {
 7599: 	if ($thisfn =~ m|/ext/|) {
 7600: 	    $thisfn='/adm/wrapper'.$thisfn;
 7601: 	} else {
 7602: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7603: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7604: 	    if ($embstyle eq 'ssi'
 7605: 		|| ($embstyle eq 'hdn')
 7606: 		|| ($embstyle eq 'rat')
 7607: 		|| ($embstyle eq 'prv')
 7608: 		|| ($embstyle eq 'ign')) {
 7609: 		#do nothing with these
 7610: 	    } elsif (($embstyle eq 'img') 
 7611: 		|| ($embstyle eq 'emb')
 7612: 		|| ($embstyle eq 'wrp')) {
 7613: 		$thisfn='/adm/wrapper'.$thisfn;
 7614: 	    } elsif ($embstyle eq 'unk'
 7615: 		     && $thisfn!~/\.(sequence|page)$/) {
 7616: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7617: 	    } else {
 7618: #		&logthis("Got a blank emb style");
 7619: 	    }
 7620: 	}
 7621:     }
 7622:     return $thisfn;
 7623: }
 7624: 
 7625: sub clutter_with_no_wrapper {
 7626:     my $uri = &clutter(shift);
 7627:     if ($uri =~ m-^/adm/-) {
 7628: 	$uri =~ s-^/adm/wrapper/-/-;
 7629: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7630:     }
 7631:     return $uri;
 7632: }
 7633: 
 7634: sub freeze_escape {
 7635:     my ($value)=@_;
 7636:     if (ref($value)) {
 7637: 	$value=&nfreeze($value);
 7638: 	return '__FROZEN__'.&escape($value);
 7639:     }
 7640:     return &escape($value);
 7641: }
 7642: 
 7643: 
 7644: sub thaw_unescape {
 7645:     my ($value)=@_;
 7646:     if ($value =~ /^__FROZEN__/) {
 7647: 	substr($value,0,10,undef);
 7648: 	$value=&unescape($value);
 7649: 	return &thaw($value);
 7650:     }
 7651:     return &unescape($value);
 7652: }
 7653: 
 7654: sub correct_line_ends {
 7655:     my ($result)=@_;
 7656:     $$result =~s/\r\n/\n/mg;
 7657:     $$result =~s/\r/\n/mg;
 7658: }
 7659: # ================================================================ Main Program
 7660: 
 7661: sub goodbye {
 7662:    &logthis("Starting Shut down");
 7663: #not converted to using infrastruture and probably shouldn't be
 7664:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7665: #converted
 7666: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7667:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7668: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7669: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7670: #1.1 only
 7671: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7672: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7673: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7674: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7675:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7676:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7677:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7678:    &flushcourselogs();
 7679:    &logthis("Shutting down");
 7680: }
 7681: 
 7682: sub get_dns {
 7683:     my ($url,$func,$ignore_cache) = @_;
 7684:     if (!$ignore_cache) {
 7685: 	my ($content,$cached)=
 7686: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7687: 	if ($cached) {
 7688: 	    &$func($content);
 7689: 	    return;
 7690: 	}
 7691:     }
 7692: 
 7693:     my %alldns;
 7694:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7695:     foreach my $dns (<$config>) {
 7696: 	next if ($dns !~ /^\^(\S*)/x);
 7697: 	$alldns{$1} = 1;
 7698:     }
 7699:     while (%alldns) {
 7700: 	my ($dns) = keys(%alldns);
 7701: 	delete($alldns{$dns});
 7702: 	my $ua=new LWP::UserAgent;
 7703: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7704: 	my $response=$ua->request($request);
 7705: 	next if ($response->is_error());
 7706: 	my @content = split("\n",$response->content);
 7707: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7708: 	&$func(\@content);
 7709: 	return;
 7710:     }
 7711:     close($config);
 7712:     &logthis("unable to contact DNS defaulting to on disk file\n");
 7713:     open($config,"<$perlvar{'lonTabDir'}/dns_hosts.tab");
 7714:     my @content = <$config>;
 7715:     &$func(\@content);
 7716:     return;
 7717: }
 7718: # ------------------------------------------------------------ Read domain file
 7719: {
 7720:     my $loaded;
 7721:     my %domain;
 7722: 
 7723:     sub parse_domain_tab {
 7724: 	my ($lines) = @_;
 7725: 	foreach my $line (@$lines) {
 7726: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7727: 
 7728: 	    chomp($line);
 7729: 	    my ($name,@elements) = split(/:/,$line,9);
 7730: 	    my %this_domain;
 7731: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7732: 			       'lang_def', 'city', 'longi', 'lati',
 7733: 			       'primary') {
 7734: 		$this_domain{$field} = shift(@elements);
 7735: 	    }
 7736: 	    $domain{$name} = \%this_domain;
 7737: 	}
 7738:     }
 7739: 
 7740:     sub reset_domain_info {
 7741: 	undef($loaded);
 7742: 	undef(%domain);
 7743:     }
 7744: 
 7745:     sub load_domain_tab {
 7746: 	my ($ignore_cache) = @_;
 7747: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7748: 	my $fh;
 7749: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7750: 	    my @lines = <$fh>;
 7751: 	    &parse_domain_tab(\@lines);
 7752: 	}
 7753: 	close($fh);
 7754: 	$loaded = 1;
 7755:     }
 7756: 
 7757:     sub domain {
 7758: 	&load_domain_tab() if (!$loaded);
 7759: 
 7760: 	my ($name,$what) = @_;
 7761: 	return if ( !exists($domain{$name}) );
 7762: 
 7763: 	if (!$what) {
 7764: 	    return $domain{$name}{'description'};
 7765: 	}
 7766: 	return $domain{$name}{$what};
 7767:     }
 7768: }
 7769: 
 7770: 
 7771: # ------------------------------------------------------------- Read hosts file
 7772: {
 7773:     my %hostname;
 7774:     my %hostdom;
 7775:     my %libserv;
 7776:     my $loaded;
 7777: 
 7778:     sub parse_hosts_tab {
 7779: 	my ($file) = @_;
 7780: 	foreach my $configline (@$file) {
 7781: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7782: 	    next if ($configline =~ /^\^/);
 7783: 	    chomp($configline);
 7784: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7785: 	    $name=~s/\s//g;
 7786: 	    if ($id && $domain && $role && $name) {
 7787: 		$hostname{$id}=$name;
 7788: 		$hostdom{$id}=$domain;
 7789: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7790: 	    }
 7791: 	}
 7792:     }
 7793:     
 7794:     sub reset_hosts_info {
 7795: 	&reset_domain_info();
 7796: 	&reset_hosts_ip_info();
 7797: 	undef(%hostname);
 7798: 	undef(%hostdom);
 7799: 	undef(%libserv);
 7800: 	undef($loaded);
 7801:     }
 7802: 
 7803:     sub load_hosts_tab {
 7804: 	my ($ignore_cache) = @_;
 7805: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 7806: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7807: 	my @config = <$config>;
 7808: 	&parse_hosts_tab(\@config);
 7809: 	close($config);
 7810: 	$loaded=1;
 7811:     }
 7812: 
 7813:     sub hostname {
 7814: 	&load_hosts_tab() if (!$loaded);
 7815: 
 7816: 	my ($lonid) = @_;
 7817: 	return $hostname{$lonid};
 7818:     }
 7819: 
 7820:     sub all_hostnames {
 7821: 	&load_hosts_tab() if (!$loaded);
 7822: 
 7823: 	return %hostname;
 7824:     }
 7825: 
 7826:     sub is_library {
 7827: 	&load_hosts_tab() if (!$loaded);
 7828: 
 7829: 	return exists($libserv{$_[0]});
 7830:     }
 7831: 
 7832:     sub all_library {
 7833: 	&load_hosts_tab() if (!$loaded);
 7834: 
 7835: 	return %libserv;
 7836:     }
 7837: 
 7838:     sub get_servers {
 7839: 	&load_hosts_tab() if (!$loaded);
 7840: 
 7841: 	my ($domain,$type) = @_;
 7842: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7843: 	                                          : %hostname;
 7844: 	my %result;
 7845: 	if (ref($domain) eq 'ARRAY') {
 7846: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7847: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7848: 		    $result{$host} = $hostname;
 7849: 		}
 7850: 	    }
 7851: 	} else {
 7852: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7853: 		if ($hostdom{$host} eq $domain) {
 7854: 		    $result{$host} = $hostname;
 7855: 		}
 7856: 	    }
 7857: 	}
 7858: 	return %result;
 7859:     }
 7860: 
 7861:     sub host_domain {
 7862: 	&load_hosts_tab() if (!$loaded);
 7863: 
 7864: 	my ($lonid) = @_;
 7865: 	return $hostdom{$lonid};
 7866:     }
 7867: 
 7868:     sub all_domains {
 7869: 	&load_hosts_tab() if (!$loaded);
 7870: 
 7871: 	my %seen;
 7872: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7873: 	return @uniq;
 7874:     }
 7875: }
 7876: 
 7877: { 
 7878:     my %iphost;
 7879:     my %name_to_ip;
 7880:     my %lonid_to_ip;
 7881: 
 7882:     my %valid_ip;
 7883:     sub valid_ip {
 7884: 	my ($ip) = @_;
 7885: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
 7886: 	    return 1;	
 7887: 	}
 7888: 	my $name = gethostbyip($ip);
 7889: 	my $lonid = &hostname($name);
 7890: 	if (defined($lonid)) {
 7891: 	    $valid_ip{$ip} = $lonid;
 7892: 	    return 1;
 7893: 	}
 7894: 	my %iphosts = &get_iphost();
 7895: 	if (ref($iphost{$ip})) {
 7896: 	    return 1;	
 7897: 	}
 7898:     }
 7899: 
 7900:     sub get_hosts_from_ip {
 7901: 	my ($ip) = @_;
 7902: 	my %iphosts = &get_iphost();
 7903: 	if (ref($iphosts{$ip})) {
 7904: 	    return @{$iphosts{$ip}};
 7905: 	}
 7906: 	return;
 7907:     }
 7908:     
 7909:     sub reset_hosts_ip_info {
 7910: 	undef(%iphost);
 7911: 	undef(%name_to_ip);
 7912: 	undef(%lonid_to_ip);
 7913:     }
 7914: 
 7915:     sub get_host_ip {
 7916: 	my ($lonid) = @_;
 7917: 	if (exists($lonid_to_ip{$lonid})) {
 7918: 	    return $lonid_to_ip{$lonid};
 7919: 	}
 7920: 	my $name=&hostname($lonid);
 7921:    	my $ip = gethostbyname($name);
 7922: 	return if (!$ip || length($ip) ne 4);
 7923: 	$ip=inet_ntoa($ip);
 7924: 	$name_to_ip{$name}   = $ip;
 7925: 	$lonid_to_ip{$lonid} = $ip;
 7926: 	return $ip;
 7927:     }
 7928:     
 7929:     sub get_iphost {
 7930: 	my ($ignore_cache) = @_;
 7931: 	if (!$ignore_cache) {
 7932: 	    if (%iphost) {
 7933: 		return %iphost;
 7934: 	    }
 7935: 	    my ($ip_info,$cached)=
 7936: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 7937: 	    if ($cached) {
 7938: 		%iphost      = %{$ip_info->[0]};
 7939: 		%name_to_ip  = %{$ip_info->[1]};
 7940: 		%lonid_to_ip = %{$ip_info->[2]};
 7941: 		return %iphost;
 7942: 	    }
 7943: 	}
 7944: 	my %hostname = &all_hostnames();
 7945: 	foreach my $id (keys(%hostname)) {
 7946: 	    my $name=&hostname($id);
 7947: 	    my $ip;
 7948: 	    if (!exists($name_to_ip{$name})) {
 7949: 		$ip = gethostbyname($name);
 7950: 		if (!$ip || length($ip) ne 4) {
 7951: 		    &logthis("Skipping host $id name $name no IP found");
 7952: 		    next;
 7953: 		}
 7954: 		$ip=inet_ntoa($ip);
 7955: 		$name_to_ip{$name} = $ip;
 7956: 	    } else {
 7957: 		$ip = $name_to_ip{$name};
 7958: 	    }
 7959: 	    $lonid_to_ip{$id} = $ip;
 7960: 	    push(@{$iphost{$ip}},$id);
 7961: 	}
 7962: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 7963: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 7964: 				      24*60*60);
 7965: 
 7966: 	return %iphost;
 7967:     }
 7968: }
 7969: 
 7970: BEGIN {
 7971: 
 7972: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7973:     unless ($readit) {
 7974: {
 7975:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7976:     %perlvar = (%perlvar,%{$configvars});
 7977: }
 7978: 
 7979: 
 7980: # ------------------------------------------------------ Read spare server file
 7981: {
 7982:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7983: 
 7984:     while (my $configline=<$config>) {
 7985:        chomp($configline);
 7986:        if ($configline) {
 7987: 	   my ($host,$type) = split(':',$configline,2);
 7988: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7989: 	   push(@{ $spareid{$type} }, $host);
 7990:        }
 7991:     }
 7992:     close($config);
 7993: }
 7994: # ------------------------------------------------------------ Read permissions
 7995: {
 7996:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7997: 
 7998:     while (my $configline=<$config>) {
 7999: 	chomp($configline);
 8000: 	if ($configline) {
 8001: 	    my ($role,$perm)=split(/ /,$configline);
 8002: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8003: 	}
 8004:     }
 8005:     close($config);
 8006: }
 8007: 
 8008: # -------------------------------------------- Read plain texts for permissions
 8009: {
 8010:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8011: 
 8012:     while (my $configline=<$config>) {
 8013: 	chomp($configline);
 8014: 	if ($configline) {
 8015: 	    my ($short,@plain)=split(/:/,$configline);
 8016:             %{$prp{$short}} = ();
 8017: 	    if (@plain > 0) {
 8018:                 $prp{$short}{'std'} = $plain[0];
 8019:                 for (my $i=1; $i<@plain; $i++) {
 8020:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8021:                 }
 8022:             }
 8023: 	}
 8024:     }
 8025:     close($config);
 8026: }
 8027: 
 8028: # ---------------------------------------------------------- Read package table
 8029: {
 8030:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8031: 
 8032:     while (my $configline=<$config>) {
 8033: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8034: 	chomp($configline);
 8035: 	my ($short,$plain)=split(/:/,$configline);
 8036: 	my ($pack,$name)=split(/\&/,$short);
 8037: 	if ($plain ne '') {
 8038: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8039: 	    $packagetab{$short}=$plain; 
 8040: 	}
 8041:     }
 8042:     close($config);
 8043: }
 8044: 
 8045: # ------------- set up temporary directory
 8046: {
 8047:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8048: 
 8049: }
 8050: 
 8051: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8052: 				'compress_threshold'=> 20_000,
 8053:  			        });
 8054: 
 8055: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8056: $dumpcount=0;
 8057: 
 8058: &logtouch();
 8059: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8060: $readit=1;
 8061:     {
 8062: 	use integer;
 8063: 	my $test=(2**32)+1;
 8064: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8065: 	&logthis(" Detected 64bit platform ($_64bit)");
 8066:     }
 8067: }
 8068: }
 8069: 
 8070: 1;
 8071: __END__
 8072: 
 8073: =pod
 8074: 
 8075: =head1 NAME
 8076: 
 8077: Apache::lonnet - Subroutines to ask questions about things in the network.
 8078: 
 8079: =head1 SYNOPSIS
 8080: 
 8081: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8082: 
 8083:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8084: 
 8085: Common parameters:
 8086: 
 8087: =over 4
 8088: 
 8089: =item *
 8090: 
 8091: $uname : an internal username (if $cname expecting a course Id specifically)
 8092: 
 8093: =item *
 8094: 
 8095: $udom : a domain (if $cdom expecting a course's domain specifically)
 8096: 
 8097: =item *
 8098: 
 8099: $symb : a resource instance identifier
 8100: 
 8101: =item *
 8102: 
 8103: $namespace : the name of a .db file that contains the data needed or
 8104: being set.
 8105: 
 8106: =back
 8107: 
 8108: =head1 OVERVIEW
 8109: 
 8110: lonnet provides subroutines which interact with the
 8111: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8112: about classes, users, and resources.
 8113: 
 8114: For many of these objects you can also use this to store data about
 8115: them or modify them in various ways.
 8116: 
 8117: =head2 Symbs
 8118: 
 8119: To identify a specific instance of a resource, LON-CAPA uses symbols
 8120: or "symbs"X<symb>. These identifiers are built from the URL of the
 8121: map, the resource number of the resource in the map, and the URL of
 8122: the resource itself. The latter is somewhat redundant, but might help
 8123: if maps change.
 8124: 
 8125: An example is
 8126: 
 8127:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8128: 
 8129: The respective map entry is
 8130: 
 8131:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8132:   title="Problem 2">
 8133:  </resource>
 8134: 
 8135: Symbs are used by the random number generator, as well as to store and
 8136: restore data specific to a certain instance of for example a problem.
 8137: 
 8138: =head2 Storing And Retrieving Data
 8139: 
 8140: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8141: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8142: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8143: is is the non-critical message twin of cstore. These functions are for
 8144: handlers to store a perl hash to a user's permanent data space in an
 8145: easy manner, and to retrieve it again on another call. It is expected
 8146: that a handler would use this once at the beginning to retrieve data,
 8147: and then again once at the end to send only the new data back.
 8148: 
 8149: The data is stored in the user's data directory on the user's
 8150: homeserver under the ID of the course.
 8151: 
 8152: The hash that is returned by restore will have all of the previous
 8153: value for all of the elements of the hash.
 8154: 
 8155: Example:
 8156: 
 8157:  #creating a hash
 8158:  my %hash;
 8159:  $hash{'foo'}='bar';
 8160: 
 8161:  #storing it
 8162:  &Apache::lonnet::cstore(\%hash);
 8163: 
 8164:  #changing a value
 8165:  $hash{'foo'}='notbar';
 8166: 
 8167:  #adding a new value
 8168:  $hash{'bar'}='foo';
 8169:  &Apache::lonnet::cstore(\%hash);
 8170: 
 8171:  #retrieving the hash
 8172:  my %history=&Apache::lonnet::restore();
 8173: 
 8174:  #print the hash
 8175:  foreach my $key (sort(keys(%history))) {
 8176:    print("\%history{$key} = $history{$key}");
 8177:  }
 8178: 
 8179: Will print out:
 8180: 
 8181:  %history{1:foo} = bar
 8182:  %history{1:keys} = foo:timestamp
 8183:  %history{1:timestamp} = 990455579
 8184:  %history{2:bar} = foo
 8185:  %history{2:foo} = notbar
 8186:  %history{2:keys} = foo:bar:timestamp
 8187:  %history{2:timestamp} = 990455580
 8188:  %history{bar} = foo
 8189:  %history{foo} = notbar
 8190:  %history{timestamp} = 990455580
 8191:  %history{version} = 2
 8192: 
 8193: Note that the special hash entries C<keys>, C<version> and
 8194: C<timestamp> were added to the hash. C<version> will be equal to the
 8195: total number of versions of the data that have been stored. The
 8196: C<timestamp> attribute will be the UNIX time the hash was
 8197: stored. C<keys> is available in every historical section to list which
 8198: keys were added or changed at a specific historical revision of a
 8199: hash.
 8200: 
 8201: B<Warning>: do not store the hash that restore returns directly. This
 8202: will cause a mess since it will restore the historical keys as if the
 8203: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8204: 
 8205: Calling convention:
 8206: 
 8207:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8208:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8209: 
 8210: For more detailed information, see lonnet specific documentation.
 8211: 
 8212: =head1 RETURN MESSAGES
 8213: 
 8214: =over 4
 8215: 
 8216: =item * B<con_lost>: unable to contact remote host
 8217: 
 8218: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8219: when the connection is brought back up
 8220: 
 8221: =item * B<con_failed>: unable to contact remote host and unable to save message
 8222: for later delivery
 8223: 
 8224: =item * B<error:>: an error a occured, a description of the error follows the :
 8225: 
 8226: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8227: that was requested
 8228: 
 8229: =back
 8230: 
 8231: =head1 PUBLIC SUBROUTINES
 8232: 
 8233: =head2 Session Environment Functions
 8234: 
 8235: =over 4
 8236: 
 8237: =item * 
 8238: X<appenv()>
 8239: B<appenv(%hash)>: the value of %hash is written to
 8240: the user envirnoment file, and will be restored for each access this
 8241: user makes during this session, also modifies the %env for the current
 8242: process
 8243: 
 8244: =item *
 8245: X<delenv()>
 8246: B<delenv($regexp)>: removes all items from the session
 8247: environment file that matches the regular expression in $regexp. The
 8248: values are also delted from the current processes %env.
 8249: 
 8250: =item * get_env_multiple($name) 
 8251: 
 8252: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8253: values may be defined and end up as an array ref.
 8254: 
 8255: returns an array of values
 8256: 
 8257: =back
 8258: 
 8259: =head2 User Information
 8260: 
 8261: =over 4
 8262: 
 8263: =item *
 8264: X<queryauthenticate()>
 8265: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8266: authentication scheme
 8267: 
 8268: =item *
 8269: X<authenticate()>
 8270: B<authenticate($uname,$upass,$udom)>: try to
 8271: authenticate user from domain's lib servers (first use the current
 8272: one). C<$upass> should be the users password.
 8273: 
 8274: =item *
 8275: X<homeserver()>
 8276: B<homeserver($uname,$udom)>: find the server which has
 8277: the user's directory and files (there must be only one), this caches
 8278: the answer, and also caches if there is a borken connection.
 8279: 
 8280: =item *
 8281: X<idget()>
 8282: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8283: (IDs are a unique resource in a domain, there must be only 1 ID per
 8284: username, and only 1 username per ID in a specific domain) (returns
 8285: hash: id=>name,id=>name)
 8286: 
 8287: =item *
 8288: X<idrget()>
 8289: B<idrget($udom,@unames)>: find the IDs behind a list of
 8290: usernames (returns hash: name=>id,name=>id)
 8291: 
 8292: =item *
 8293: X<idput()>
 8294: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8295: 
 8296: =item *
 8297: X<rolesinit()>
 8298: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8299: 
 8300: =item *
 8301: X<getsection()>
 8302: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8303: course $cname, return section name/number or '' for "not in course"
 8304: and '-1' for "no section"
 8305: 
 8306: =item *
 8307: X<userenvironment()>
 8308: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8309: passed in @what from the requested user's environment, returns a hash
 8310: 
 8311: =item * 
 8312: X<userlog_query()>
 8313: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8314: activity.log file. %filters defines filters applied when parsing the
 8315: log file. These can be start or end timestamps, or the type of action
 8316: - log to look for Login or Logout events, check for Checkin or
 8317: Checkout, role for role selection. The response is in the form
 8318: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8319: escaped strings of the action recorded in the activity.log file.
 8320: 
 8321: =back
 8322: 
 8323: =head2 User Roles
 8324: 
 8325: =over 4
 8326: 
 8327: =item *
 8328: 
 8329: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8330:  F: full access
 8331:  U,I,K: authentication modes (cxx only)
 8332:  '': forbidden
 8333:  1: user needs to choose course
 8334:  2: browse allowed
 8335:  A: passphrase authentication needed
 8336: 
 8337: =item *
 8338: 
 8339: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8340: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8341: and course level
 8342: 
 8343: =item *
 8344: 
 8345: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8346: explanation of a user role term
 8347: 
 8348: =item *
 8349: 
 8350: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8351: All arguments are optional. Returns a hash of a roles, either for
 8352: co-author/assistant author roles for a user's Construction Space
 8353: (default), or if $context is 'user', roles for the user himself,
 8354: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8355: and value is set to colon-separated start and end times for the role.
 8356: If no username and domain are specified, will default to current
 8357: user/domain. Types, roles, and roledoms are references to arrays,
 8358: of role statuses (active, future or previous), roles 
 8359: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8360: to restrict the list of roles reported. If no array ref is 
 8361: provided for types, will default to return only active roles.
 8362: 
 8363: =back
 8364: 
 8365: =head2 User Modification
 8366: 
 8367: =over 4
 8368: 
 8369: =item *
 8370: 
 8371: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8372: user for the level given by URL.  Optional start and end dates (leave empty
 8373: string or zero for "no date")
 8374: 
 8375: =item *
 8376: 
 8377: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8378: change a users, password, possible return values are: ok,
 8379: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8380: refused
 8381: 
 8382: =item *
 8383: 
 8384: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8385: 
 8386: =item *
 8387: 
 8388: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8389: modify user
 8390: 
 8391: =item *
 8392: 
 8393: modifystudent
 8394: 
 8395: modify a students enrollment and identification information.
 8396: The course id is resolved based on the current users environment.  
 8397: This means the envoking user must be a course coordinator or otherwise
 8398: associated with a course.
 8399: 
 8400: This call is essentially a wrapper for lonnet::modifyuser and
 8401: lonnet::modify_student_enrollment
 8402: 
 8403: Inputs: 
 8404: 
 8405: =over 4
 8406: 
 8407: =item B<$udom> Students loncapa domain
 8408: 
 8409: =item B<$uname> Students loncapa login name
 8410: 
 8411: =item B<$uid> Students id/student number
 8412: 
 8413: =item B<$umode> Students authentication mode
 8414: 
 8415: =item B<$upass> Students password
 8416: 
 8417: =item B<$first> Students first name
 8418: 
 8419: =item B<$middle> Students middle name
 8420: 
 8421: =item B<$last> Students last name
 8422: 
 8423: =item B<$gene> Students generation
 8424: 
 8425: =item B<$usec> Students section in course
 8426: 
 8427: =item B<$end> Unix time of the roles expiration
 8428: 
 8429: =item B<$start> Unix time of the roles start date
 8430: 
 8431: =item B<$forceid> If defined, allow $uid to be changed
 8432: 
 8433: =item B<$desiredhome> server to use as home server for student
 8434: 
 8435: =back
 8436: 
 8437: =item *
 8438: 
 8439: modify_student_enrollment
 8440: 
 8441: Change a students enrollment status in a class.  The environment variable
 8442: 'role.request.course' must be defined for this function to proceed.
 8443: 
 8444: Inputs:
 8445: 
 8446: =over 4
 8447: 
 8448: =item $udom, students domain
 8449: 
 8450: =item $uname, students name
 8451: 
 8452: =item $uid, students user id
 8453: 
 8454: =item $first, students first name
 8455: 
 8456: =item $middle
 8457: 
 8458: =item $last
 8459: 
 8460: =item $gene
 8461: 
 8462: =item $usec
 8463: 
 8464: =item $end
 8465: 
 8466: =item $start
 8467: 
 8468: =back
 8469: 
 8470: 
 8471: =item *
 8472: 
 8473: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8474: custom role; give a custom role to a user for the level given by URL.  Specify
 8475: name and domain of role author, and role name
 8476: 
 8477: =item *
 8478: 
 8479: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8480: 
 8481: =item *
 8482: 
 8483: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8484: 
 8485: =back
 8486: 
 8487: =head2 Course Infomation
 8488: 
 8489: =over 4
 8490: 
 8491: =item *
 8492: 
 8493: coursedescription($courseid) : returns a hash of information about the
 8494: specified course id, including all environment settings for the
 8495: course, the description of the course will be in the hash under the
 8496: key 'description'
 8497: 
 8498: =item *
 8499: 
 8500: resdata($name,$domain,$type,@which) : request for current parameter
 8501: setting for a specific $type, where $type is either 'course' or 'user',
 8502: @what should be a list of parameters to ask about. This routine caches
 8503: answers for 5 minutes.
 8504: 
 8505: =back
 8506: 
 8507: =head2 Course Modification
 8508: 
 8509: =over 4
 8510: 
 8511: =item *
 8512: 
 8513: writecoursepref($courseid,%prefs) : write preferences (environment
 8514: database) for a course
 8515: 
 8516: =item *
 8517: 
 8518: createcourse($udom,$description,$url) : make/modify course
 8519: 
 8520: =back
 8521: 
 8522: =head2 Resource Subroutines
 8523: 
 8524: =over 4
 8525: 
 8526: =item *
 8527: 
 8528: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8529: 
 8530: =item *
 8531: 
 8532: repcopy($filename) : subscribes to the requested file, and attempts to
 8533: replicate from the owning library server, Might return
 8534: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8535: 'bad_request', also attempts to grab the metadata for the
 8536: resource. Expects the local filesystem pathname
 8537: (/home/httpd/html/res/....)
 8538: 
 8539: =back
 8540: 
 8541: =head2 Resource Information
 8542: 
 8543: =over 4
 8544: 
 8545: =item *
 8546: 
 8547: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8548: a vairety of different possible values, $varname should be a request
 8549: string, and the other parameters can be used to specify who and what
 8550: one is asking about.
 8551: 
 8552: Possible values for $varname are environment.lastname (or other item
 8553: from the envirnment hash), user.name (or someother aspect about the
 8554: user), resource.0.maxtries (or some other part and parameter of a
 8555: resource)
 8556: 
 8557: =item *
 8558: 
 8559: directcondval($number) : get current value of a condition; reads from a state
 8560: string
 8561: 
 8562: =item *
 8563: 
 8564: condval($condidx) : value of condition index based on state
 8565: 
 8566: =item *
 8567: 
 8568: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8569: resource's metadata, $what should be either a specific key, or either
 8570: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8571: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8572: 
 8573: this function automatically caches all requests
 8574: 
 8575: =item *
 8576: 
 8577: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8578: network of library servers; returns file handle of where SQL and regex results
 8579: will be stored for query
 8580: 
 8581: =item *
 8582: 
 8583: symbread($filename) : return symbolic list entry (filename argument optional);
 8584: returns the data handle
 8585: 
 8586: =item *
 8587: 
 8588: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8589: a possible symb for the URL in $thisfn, and if is an encryypted
 8590: resource that the user accessed using /enc/ returns a 1 on success, 0
 8591: on failure, user must be in a course, as it assumes the existance of
 8592: the course initial hash, and uses $env('request.course.id'}
 8593: 
 8594: 
 8595: =item *
 8596: 
 8597: symbclean($symb) : removes versions numbers from a symb, returns the
 8598: cleaned symb
 8599: 
 8600: =item *
 8601: 
 8602: is_on_map($uri) : checks if the $uri is somewhere on the current
 8603: course map, user must be in a course for it to work.
 8604: 
 8605: =item *
 8606: 
 8607: numval($salt) : return random seed value (addend for rndseed)
 8608: 
 8609: =item *
 8610: 
 8611: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8612: a random seed, all arguments are optional, if they aren't sent it uses the
 8613: environment to derive them. Note: if symb isn't sent and it can't get one
 8614: from &symbread it will use the current time as its return value
 8615: 
 8616: =item *
 8617: 
 8618: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8619: unfakeable, receipt
 8620: 
 8621: =item *
 8622: 
 8623: receipt() : API to ireceipt working off of env values; given out to users
 8624: 
 8625: =item *
 8626: 
 8627: countacc($url) : count the number of accesses to a given URL
 8628: 
 8629: =item *
 8630: 
 8631: 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
 8632: 
 8633: =item *
 8634: 
 8635: 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)
 8636: 
 8637: =item *
 8638: 
 8639: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8640: 
 8641: =item *
 8642: 
 8643: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8644: forcing spreadsheet to reevaluate the resource scores next time.
 8645: 
 8646: =back
 8647: 
 8648: =head2 Storing/Retreiving Data
 8649: 
 8650: =over 4
 8651: 
 8652: =item *
 8653: 
 8654: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8655: for this url; hashref needs to be given and should be a \%hashname; the
 8656: remaining args aren't required and if they aren't passed or are '' they will
 8657: be derived from the env
 8658: 
 8659: =item *
 8660: 
 8661: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8662: uses critical subroutine
 8663: 
 8664: =item *
 8665: 
 8666: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8667: all args are optional
 8668: 
 8669: =item *
 8670: 
 8671: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8672: dumps the complete (or key matching regexp) namespace into a hash
 8673: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8674: normally &store()ed into
 8675: 
 8676: $range should be either an integer '100' (give me the first 100
 8677:                                            matching records)
 8678:               or be  two integers sperated by a - with no spaces
 8679:                  '30-50' (give me the 30th through the 50th matching
 8680:                           records)
 8681: 
 8682: 
 8683: =item *
 8684: 
 8685: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8686: replaces a &store() version of data with a replacement set of data
 8687: for a particular resource in a namespace passed in the $storehash hash 
 8688: reference
 8689: 
 8690: =item *
 8691: 
 8692: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8693: works very similar to store/cstore, but all data is stored in a
 8694: temporary location and can be reset using tmpreset, $storehash should
 8695: be a hash reference, returns nothing on success
 8696: 
 8697: =item *
 8698: 
 8699: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8700: similar to restore, but all data is stored in a temporary location and
 8701: can be reset using tmpreset. Returns a hash of values on success,
 8702: error string otherwise.
 8703: 
 8704: =item *
 8705: 
 8706: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8707: deltes all keys for $symb form the temporary storage hash.
 8708: 
 8709: =item *
 8710: 
 8711: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8712: reference filled in from namesp ($udom and $uname are optional)
 8713: 
 8714: =item *
 8715: 
 8716: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8717: namesp ($udom and $uname are optional)
 8718: 
 8719: =item *
 8720: 
 8721: dump($namespace,$udom,$uname,$regexp,$range) : 
 8722: dumps the complete (or key matching regexp) namespace into a hash
 8723: ($udom, $uname, $regexp, $range are optional)
 8724: 
 8725: $range should be either an integer '100' (give me the first 100
 8726:                                            matching records)
 8727:               or be  two integers sperated by a - with no spaces
 8728:                  '30-50' (give me the 30th through the 50th matching
 8729:                           records)
 8730: =item *
 8731: 
 8732: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8733: $store can be a scalar, an array reference, or if the amount to be 
 8734: incremented is > 1, a hash reference.
 8735: 
 8736: ($udom and $uname are optional)
 8737: 
 8738: =item *
 8739: 
 8740: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8741: ($udom and $uname are optional)
 8742: 
 8743: =item *
 8744: 
 8745: cput($namespace,$storehash,$udom,$uname) : critical put
 8746: ($udom and $uname are optional)
 8747: 
 8748: =item *
 8749: 
 8750: newput($namespace,$storehash,$udom,$uname) :
 8751: 
 8752: Attempts to store the items in the $storehash, but only if they don't
 8753: currently exist, if this succeeds you can be certain that you have 
 8754: successfully created a new key value pair in the $namespace db.
 8755: 
 8756: 
 8757: Args:
 8758:  $namespace: name of database to store values to
 8759:  $storehash: hashref to store to the db
 8760:  $udom: (optional) domain of user containing the db
 8761:  $uname: (optional) name of user caontaining the db
 8762: 
 8763: Returns:
 8764:  'ok' -> succeeded in storing all keys of $storehash
 8765:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8766:                         least <key> already existed in the db (other
 8767:                         requested keys may also already exist)
 8768:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8769:  'con_lost' -> unable to contact request server
 8770:  'refused' -> action was not allowed by remote machine
 8771: 
 8772: 
 8773: =item *
 8774: 
 8775: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8776: reference filled in from namesp (encrypts the return communication)
 8777: ($udom and $uname are optional)
 8778: 
 8779: =item *
 8780: 
 8781: log($udom,$name,$home,$message) : write to permanent log for user; use
 8782: critical subroutine
 8783: 
 8784: =item *
 8785: 
 8786: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8787: array reference filled in from namespace found in domain level on either
 8788: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8789: 
 8790: =item *
 8791: 
 8792: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8793: domain level either on specified domain server ($uhome) or primary domain 
 8794: server ($udom and $uhome are optional)
 8795: 
 8796: =back
 8797: 
 8798: =head2 Network Status Functions
 8799: 
 8800: =over 4
 8801: 
 8802: =item *
 8803: 
 8804: dirlist($uri) : return directory list based on URI
 8805: 
 8806: =item *
 8807: 
 8808: spareserver() : find server with least workload from spare.tab
 8809: 
 8810: =back
 8811: 
 8812: =head2 Apache Request
 8813: 
 8814: =over 4
 8815: 
 8816: =item *
 8817: 
 8818: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8819: localhost, posts hash
 8820: 
 8821: =back
 8822: 
 8823: =head2 Data to String to Data
 8824: 
 8825: =over 4
 8826: 
 8827: =item *
 8828: 
 8829: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8830: and '&' separators, supports elements that are arrayrefs and hashrefs
 8831: 
 8832: =item *
 8833: 
 8834: hashref2str($hashref) : convert a hashref into a string complete with
 8835: escaping and '=' and '&' separators, supports elements that are
 8836: arrayrefs and hashrefs
 8837: 
 8838: =item *
 8839: 
 8840: arrayref2str($arrayref) : convert an arrayref into a string complete
 8841: with escaping and '&' separators, supports elements that are arrayrefs
 8842: and hashrefs
 8843: 
 8844: =item *
 8845: 
 8846: str2hash($string) : convert string to hash using unescaping and
 8847: splitting on '=' and '&', supports elements that are arrayrefs and
 8848: hashrefs
 8849: 
 8850: =item *
 8851: 
 8852: str2array($string) : convert string to hash using unescaping and
 8853: splitting on '&', supports elements that are arrayrefs and hashrefs
 8854: 
 8855: =back
 8856: 
 8857: =head2 Logging Routines
 8858: 
 8859: =over 4
 8860: 
 8861: These routines allow one to make log messages in the lonnet.log and
 8862: lonnet.perm logfiles.
 8863: 
 8864: =item *
 8865: 
 8866: logtouch() : make sure the logfile, lonnet.log, exists
 8867: 
 8868: =item *
 8869: 
 8870: logthis() : append message to the normal lonnet.log file, it gets
 8871: preiodically rolled over and deleted.
 8872: 
 8873: =item *
 8874: 
 8875: logperm() : append a permanent message to lonnet.perm.log, this log
 8876: file never gets deleted by any automated portion of the system, only
 8877: messages of critical importance should go in here.
 8878: 
 8879: =back
 8880: 
 8881: =head2 General File Helper Routines
 8882: 
 8883: =over 4
 8884: 
 8885: =item *
 8886: 
 8887: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8888: (a) files in /uploaded
 8889:   (i) If a local copy of the file exists - 
 8890:       compares modification date of local copy with last-modified date for 
 8891:       definitive version stored on home server for course. If local copy is 
 8892:       stale, requests a new version from the home server and stores it. 
 8893:       If the original has been removed from the home server, then local copy 
 8894:       is unlinked.
 8895:   (ii) If local copy does not exist -
 8896:       requests the file from the home server and stores it. 
 8897:   
 8898:   If $caller is 'uploadrep':  
 8899:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8900:     for request for files originally uploaded via DOCS. 
 8901:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8902:   
 8903:   Otherwise:
 8904:      This indicates a call from the content generation phase of the request.
 8905:      -  returns the entire contents of the file or -1.
 8906:      
 8907: (b) files in /res
 8908:    - returns the entire contents of a file or -1; 
 8909:    it properly subscribes to and replicates the file if neccessary.
 8910: 
 8911: 
 8912: =item *
 8913: 
 8914: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8915:                   reference
 8916: 
 8917: returns either a stat() list of data about the file or an empty list
 8918: if the file doesn't exist or couldn't find out about it (connection
 8919: problems or user unknown)
 8920: 
 8921: =item *
 8922: 
 8923: filelocation($dir,$file) : returns file system location of a file
 8924: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8925: directory that relative $file lookups are to looked in ($dir of /a/dir
 8926: and a file of ../bob will become /a/bob)
 8927: 
 8928: =item *
 8929: 
 8930: hreflocation($dir,$file) : returns file system location or a URL; same as
 8931: filelocation except for hrefs
 8932: 
 8933: =item *
 8934: 
 8935: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8936: 
 8937: =back
 8938: 
 8939: =head2 Usererfile file routines (/uploaded*)
 8940: 
 8941: =over 4
 8942: 
 8943: =item *
 8944: 
 8945: userfileupload(): main rotine for putting a file in a user or course's
 8946:                   filespace, arguments are,
 8947: 
 8948:  formname - required - this is the name of the element in $env where the
 8949:            filename, and the contents of the file to create/modifed exist
 8950:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8951:            contents of the file is located in $env{'form.'.$formname}
 8952:  coursedoc - if true, store the file in the course of the active role
 8953:              of the current user
 8954:  subdir - required - subdirectory to put the file in under ../userfiles/
 8955:          if undefined, it will be placed in "unknown"
 8956: 
 8957:  (This routine calls clean_filename() to remove any dangerous
 8958:  characters from the filename, and then calls finuserfileupload() to
 8959:  complete the transaction)
 8960: 
 8961:  returns either the url of the uploaded file (/uploaded/....) if successful
 8962:  and /adm/notfound.html if unsuccessful
 8963: 
 8964: =item *
 8965: 
 8966: clean_filename(): routine for cleaing a filename up for storage in
 8967:                  userfile space, argument is:
 8968: 
 8969:  filename - proposed filename
 8970: 
 8971: returns: the new clean filename
 8972: 
 8973: =item *
 8974: 
 8975: finishuserfileupload(): routine that creaes and sends the file to
 8976: userspace, probably shouldn't be called directly
 8977: 
 8978:   docuname: username or courseid of destination for the file
 8979:   docudom: domain of user/course of destination for the file
 8980:   formname: same as for userfileupload()
 8981:   fname: filename (inculding subdirectories) for the file
 8982: 
 8983:  returns either the url of the uploaded file (/uploaded/....) if successful
 8984:  and /adm/notfound.html if unsuccessful
 8985: 
 8986: =item *
 8987: 
 8988: renameuserfile(): renames an existing userfile to a new name
 8989: 
 8990:   Args:
 8991:    docuname: username or courseid of destination for the file
 8992:    docudom: domain of user/course of destination for the file
 8993:    old: current file name (including any subdirs under userfiles)
 8994:    new: desired file name (including any subdirs under userfiles)
 8995: 
 8996: =item *
 8997: 
 8998: mkdiruserfile(): creates a directory is a userfiles dir
 8999: 
 9000:   Args:
 9001:    docuname: username or courseid of destination for the file
 9002:    docudom: domain of user/course of destination for the file
 9003:    dir: dir to create (including any subdirs under userfiles)
 9004: 
 9005: =item *
 9006: 
 9007: removeuserfile(): removes a file that exists in userfiles
 9008: 
 9009:   Args:
 9010:    docuname: username or courseid of destination for the file
 9011:    docudom: domain of user/course of destination for the file
 9012:    fname: filname to delete (including any subdirs under userfiles)
 9013: 
 9014: =item *
 9015: 
 9016: removeuploadedurl(): convience function for removeuserfile()
 9017: 
 9018:   Args:
 9019:    url:  a full /uploaded/... url to delete
 9020: 
 9021: =item * 
 9022: 
 9023: get_portfile_permissions():
 9024:   Args:
 9025:     domain: domain of user or course contain the portfolio files
 9026:     user: name of user or num of course contain the portfolio files
 9027:   Returns:
 9028:     hashref of a dump of the proper file_permissions.db
 9029:    
 9030: 
 9031: =item * 
 9032: 
 9033: get_access_controls():
 9034: 
 9035: Args:
 9036:   current_permissions: the hash ref returned from get_portfile_permissions()
 9037:   group: (optional) the group you want the files associated with
 9038:   file: (optional) the file you want access info on
 9039: 
 9040: Returns:
 9041:     a hash (keys are file names) of hashes containing
 9042:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9043:         values are XML containing access control settings (see below) 
 9044: 
 9045: Internal notes:
 9046: 
 9047:  access controls are stored in file_permissions.db as key=value pairs.
 9048:     key -> path to file/file_name\0uniqueID:scope_end_start
 9049:         where scope -> public,guest,course,group,domains or users.
 9050:               end -> UNIX time for end of access (0 -> no end date)
 9051:               start -> UNIX time for start of access
 9052: 
 9053:     value -> XML description of access control
 9054:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9055:             <start></start>
 9056:             <end></end>
 9057: 
 9058:             <password></password>  for scope type = guest
 9059: 
 9060:             <domain></domain>     for scope type = course or group
 9061:             <number></number>
 9062:             <roles id="">
 9063:              <role></role>
 9064:              <access></access>
 9065:              <section></section>
 9066:              <group></group>
 9067:             </roles>
 9068: 
 9069:             <dom></dom>         for scope type = domains
 9070: 
 9071:             <users>             for scope type = users
 9072:              <user>
 9073:               <uname></uname>
 9074:               <udom></udom>
 9075:              </user>
 9076:             </users>
 9077:            </scope> 
 9078:               
 9079:  Access data is also aggregated for each file in an additional key=value pair:
 9080:  key -> path to file/file_name\0accesscontrol 
 9081:  value -> reference to hash
 9082:           hash contains key = value pairs
 9083:           where key = uniqueID:scope_end_start
 9084:                 value = UNIX time record was last updated
 9085: 
 9086:           Used to improve speed of look-ups of access controls for each file.  
 9087:  
 9088:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9089: 
 9090: modify_access_controls():
 9091: 
 9092: Modifies access controls for a portfolio file
 9093: Args
 9094: 1. file name
 9095: 2. reference to hash of required changes,
 9096: 3. domain
 9097: 4. username
 9098:   where domain,username are the domain of the portfolio owner 
 9099:   (either a user or a course) 
 9100: 
 9101: Returns:
 9102: 1. result of additions or updates ('ok' or 'error', with error message). 
 9103: 2. result of deletions ('ok' or 'error', with error message).
 9104: 3. reference to hash of any new or updated access controls.
 9105: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9106:    key = integer (inbound ID)
 9107:    value = uniqueID  
 9108: 
 9109: =back
 9110: 
 9111: =head2 HTTP Helper Routines
 9112: 
 9113: =over 4
 9114: 
 9115: =item *
 9116: 
 9117: escape() : unpack non-word characters into CGI-compatible hex codes
 9118: 
 9119: =item *
 9120: 
 9121: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9122: 
 9123: =back
 9124: 
 9125: =head1 PRIVATE SUBROUTINES
 9126: 
 9127: =head2 Underlying communication routines (Shouldn't call)
 9128: 
 9129: =over 4
 9130: 
 9131: =item *
 9132: 
 9133: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9134: 
 9135: =item *
 9136: 
 9137: reply() : uses subreply to send a message to remote machine, logs all failures
 9138: 
 9139: =item *
 9140: 
 9141: critical() : passes a critical message to another server; if cannot
 9142: get through then place message in connection buffer directory and
 9143: returns con_delayed, if incapable of saving message, returns
 9144: con_failed
 9145: 
 9146: =item *
 9147: 
 9148: reconlonc() : tries to reconnect lonc client processes.
 9149: 
 9150: =back
 9151: 
 9152: =head2 Resource Access Logging
 9153: 
 9154: =over 4
 9155: 
 9156: =item *
 9157: 
 9158: flushcourselogs() : flush (save) buffer logs and access logs
 9159: 
 9160: =item *
 9161: 
 9162: courselog($what) : save message for course in hash
 9163: 
 9164: =item *
 9165: 
 9166: courseacclog($what) : save message for course using &courselog().  Perform
 9167: special processing for specific resource types (problems, exams, quizzes, etc).
 9168: 
 9169: =item *
 9170: 
 9171: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9172: as a PerlChildExitHandler
 9173: 
 9174: =back
 9175: 
 9176: =head2 Other
 9177: 
 9178: =over 4
 9179: 
 9180: =item *
 9181: 
 9182: symblist($mapname,%newhash) : update symbolic storage links
 9183: 
 9184: =back
 9185: 
 9186: =cut

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