File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.862: download - view: text, annotated - select for diffs
Wed Apr 4 00:07:07 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- hosts.tab no longer read on startup so moving it out of the begin block

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.862 2007/04/04 00:07:07 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %badServerCache %spareid 
   39:    %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    $tmpdir $_64bit %env);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use HTML::Parser;
   48: use Fcntl qw(:flock);
   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   50: use Time::HiRes qw( gettimeofday tv_interval );
   51: use Cache::Memcached;
   52: use Digest::MD5;
   53: use Math::Random;
   54: use LONCAPA qw(:DEFAULT :match);
   55: use LONCAPA::Configuration;
   56: 
   57: my $readit;
   58: my $max_connection_retries = 10;     # Or some such value.
   59: 
   60: require Exporter;
   61: 
   62: our @ISA = qw (Exporter);
   63: our @EXPORT = qw(%env);
   64: 
   65: =pod
   66: 
   67: =head1 Package Variables
   68: 
   69: These are largely undocumented, so if you decipher one please note it here.
   70: 
   71: =over 4
   72: 
   73: =item $processmarker
   74: 
   75: Contains the time this process was started and this servers host id.
   76: 
   77: =item $dumpcount
   78: 
   79: Counts the number of times a message log flush has been attempted (regardless
   80: of success) by this process.  Used as part of the filename when messages are
   81: delayed.
   82: 
   83: =back
   84: 
   85: =cut
   86: 
   87: 
   88: # --------------------------------------------------------------------- Logging
   89: {
   90:     my $logid;
   91:     sub instructor_log {
   92: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   93: 	$logid++;
   94: 	my $id=time().'00000'.$$.'00000'.$logid;
   95: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   96: 				    { $id => {
   97: 					'exe_uname' => $env{'user.name'},
   98: 					'exe_udom'  => $env{'user.domain'},
   99: 					'exe_time'  => time(),
  100: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  101: 					'delflag'   => $delflag,
  102: 					'logentry'  => $storehash,
  103: 					'uname'     => $uname,
  104: 					'udom'      => $udom,
  105: 				    }
  106: 				  },
  107: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  108: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  109: 				    );
  110:     }
  111: }
  112: 
  113: sub logtouch {
  114:     my $execdir=$perlvar{'lonDaemons'};
  115:     unless (-e "$execdir/logs/lonnet.log") {	
  116: 	open(my $fh,">>$execdir/logs/lonnet.log");
  117: 	close $fh;
  118:     }
  119:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  120:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  121: }
  122: 
  123: sub logthis {
  124:     my $message=shift;
  125:     my $execdir=$perlvar{'lonDaemons'};
  126:     my $now=time;
  127:     my $local=localtime($now);
  128:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  129: 	print $fh "$local ($$): $message\n";
  130: 	close($fh);
  131:     }
  132:     return 1;
  133: }
  134: 
  135: sub logperm {
  136:     my $message=shift;
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     my $now=time;
  139:     my $local=localtime($now);
  140:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  141: 	print $fh "$now:$message:$local\n";
  142: 	close($fh);
  143:     }
  144:     return 1;
  145: }
  146: 
  147: sub create_connection {
  148:     my ($hostname,$lonid) = @_;
  149:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  150: 				     Type    => SOCK_STREAM,
  151: 				     Timeout => 10);
  152:     return 0 if (!$client);
  153:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
  154:     my $result = <$client>;
  155:     chomp($result);
  156:     return 1 if ($result eq 'done');
  157:     return 0;
  158: }
  159: 
  160: 
  161: # -------------------------------------------------- Non-critical communication
  162: sub subreply {
  163:     my ($cmd,$server)=@_;
  164:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  165:     #
  166:     #  With loncnew process trimming, there's a timing hole between lonc server
  167:     #  process exit and the master server picking up the listen on the AF_UNIX
  168:     #  socket.  In that time interval, a lock file will exist:
  169: 
  170:     my $lockfile=$peerfile.".lock";
  171:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  172: 	sleep(1);
  173:     }
  174:     # At this point, either a loncnew parent is listening or an old lonc
  175:     # or loncnew child is listening so we can connect or everything's dead.
  176:     #
  177:     #   We'll give the connection a few tries before abandoning it.  If
  178:     #   connection is not possible, we'll con_lost back to the client.
  179:     #   
  180:     my $client;
  181:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  182: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  183: 				      Type    => SOCK_STREAM,
  184: 				      Timeout => 10);
  185: 	if($client) {
  186: 	    last;		# Connected!
  187: 	} else {
  188: 	    &create_connection(&hostname($server),$server);
  189: 	}
  190:         sleep(1);		# Try again later if failed connection.
  191:     }
  192:     my $answer;
  193:     if ($client) {
  194: 	print $client "sethost:$server:$cmd\n";
  195: 	$answer=<$client>;
  196: 	if (!$answer) { $answer="con_lost"; }
  197: 	chomp($answer);
  198:     } else {
  199: 	$answer = 'con_lost';	# Failed connection.
  200:     }
  201:     return $answer;
  202: }
  203: 
  204: sub reply {
  205:     my ($cmd,$server)=@_;
  206:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  207:     my $answer=subreply($cmd,$server);
  208:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  209:        &logthis("<font color=\"blue\">WARNING:".
  210:                 " $cmd to $server returned $answer</font>");
  211:     }
  212:     return $answer;
  213: }
  214: 
  215: # ----------------------------------------------------------- Send USR1 to lonc
  216: 
  217: sub reconlonc {
  218:     &logthis("Trying to reconnect lonc");
  219:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  220:     if (open(my $fh,"<$loncfile")) {
  221: 	my $loncpid=<$fh>;
  222:         chomp($loncpid);
  223:         if (kill 0 => $loncpid) {
  224: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  225:             kill USR1 => $loncpid;
  226:             sleep 1;
  227:          } else {
  228: 	    &logthis(
  229:                "<font color=\"blue\">WARNING:".
  230:                " lonc at pid $loncpid not responding, giving up</font>");
  231:         }
  232:     } else {
  233: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  234:     }
  235: }
  236: 
  237: # ------------------------------------------------------ Critical communication
  238: 
  239: sub critical {
  240:     my ($cmd,$server)=@_;
  241:     unless (&hostname($server)) {
  242:         &logthis("<font color=\"blue\">WARNING:".
  243:                " Critical message to unknown server ($server)</font>");
  244:         return 'no_such_host';
  245:     }
  246:     my $answer=reply($cmd,$server);
  247:     if ($answer eq 'con_lost') {
  248: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  249: 	my $answer=reply($cmd,$server);
  250:         if ($answer eq 'con_lost') {
  251:             my $now=time;
  252:             my $middlename=$cmd;
  253:             $middlename=substr($middlename,0,16);
  254:             $middlename=~s/\W//g;
  255:             my $dfilename=
  256:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  257:             $dumpcount++;
  258:             {
  259: 		my $dfh;
  260: 		if (open($dfh,">$dfilename")) {
  261: 		    print $dfh "$cmd\n"; 
  262: 		    close($dfh);
  263: 		}
  264:             }
  265:             sleep 2;
  266:             my $wcmd='';
  267:             {
  268: 		my $dfh;
  269: 		if (open($dfh,"<$dfilename")) {
  270: 		    $wcmd=<$dfh>; 
  271: 		    close($dfh);
  272: 		}
  273:             }
  274:             chomp($wcmd);
  275:             if ($wcmd eq $cmd) {
  276: 		&logthis("<font color=\"blue\">WARNING: ".
  277:                          "Connection buffer $dfilename: $cmd</font>");
  278:                 &logperm("D:$server:$cmd");
  279: 	        return 'con_delayed';
  280:             } else {
  281:                 &logthis("<font color=\"red\">CRITICAL:"
  282:                         ." Critical connection failed: $server $cmd</font>");
  283:                 &logperm("F:$server:$cmd");
  284:                 return 'con_failed';
  285:             }
  286:         }
  287:     }
  288:     return $answer;
  289: }
  290: 
  291: # ------------------------------------------- check if return value is an error
  292: 
  293: sub error {
  294:     my ($result) = @_;
  295:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  296: 	if ($2 == 2) { return undef; }
  297: 	return $1;
  298:     }
  299:     return undef;
  300: }
  301: 
  302: sub convert_and_load_session_env {
  303:     my ($lonidsdir,$handle)=@_;
  304:     my @profile;
  305:     {
  306: 	open(my $idf,"$lonidsdir/$handle.id");
  307: 	flock($idf,LOCK_SH);
  308: 	@profile=<$idf>;
  309: 	close($idf);
  310:     }
  311:     my %temp_env;
  312:     foreach my $line (@profile) {
  313: 	if ($line !~ m/=/) {
  314: 	    return 0;
  315: 	}
  316: 	chomp($line);
  317: 	my ($envname,$envvalue)=split(/=/,$line,2);
  318: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  319:     }
  320:     unlink("$lonidsdir/$handle.id");
  321:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  322: 	    0640)) {
  323: 	%disk_env = %temp_env;
  324: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  325: 	untie(%disk_env);
  326:     }
  327:     return 1;
  328: }
  329: 
  330: # ------------------------------------------- Transfer profile into environment
  331: my $env_loaded;
  332: sub transfer_profile_to_env {
  333:     my ($lonidsdir,$handle,$force_transfer) = @_;
  334:     if (!$force_transfer && $env_loaded) { return; } 
  335: 
  336:     if (!defined($lonidsdir)) {
  337: 	$lonidsdir = $perlvar{'lonIDsDir'};
  338:     }
  339:     if (!defined($handle)) {
  340:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  341:     }
  342: 
  343:     my $convert;
  344:     {
  345:     	open(my $idf,"$lonidsdir/$handle.id");
  346: 	flock($idf,LOCK_SH);
  347: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  348: 		&GDBM_READER(),0640)) {
  349: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  350: 	    untie(%disk_env);
  351: 	} else {
  352: 	    $convert = 1;
  353: 	}
  354:     }
  355:     if ($convert) {
  356: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  357: 	    &logthis("Failed to load session, or convert session.");
  358: 	}
  359:     }
  360: 
  361:     my %remove;
  362:     while ( my $envname = each(%env) ) {
  363:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  364:             if ($time < time-300) {
  365:                 $remove{$key}++;
  366:             }
  367:         }
  368:     }
  369: 
  370:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  371:     $env_loaded=1;
  372:     foreach my $expired_key (keys(%remove)) {
  373:         &delenv($expired_key);
  374:     }
  375: }
  376: 
  377: sub timed_flock {
  378:     my ($file,$lock_type) = @_;
  379:     my $failed=0;
  380:     eval {
  381: 	local $SIG{__DIE__}='DEFAULT';
  382: 	local $SIG{ALRM}=sub {
  383: 	    $failed=1;
  384: 	    die("failed lock");
  385: 	};
  386: 	alarm(13);
  387: 	flock($file,$lock_type);
  388: 	alarm(0);
  389:     };
  390:     if ($failed) {
  391: 	return undef;
  392:     } else {
  393: 	return 1;
  394:     }
  395: }
  396: 
  397: # ---------------------------------------------------------- Append Environment
  398: 
  399: sub appenv {
  400:     my %newenv=@_;
  401:     foreach my $key (keys(%newenv)) {
  402: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  403:             &logthis("<font color=\"blue\">WARNING: ".
  404:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  405:                 .'</font>');
  406: 	    delete($newenv{$key});
  407:         } else {
  408:             $env{$key}=$newenv{$key};
  409:         }
  410:     }
  411:     open(my $env_file,$env{'user.environment'});
  412:     if (&timed_flock($env_file,LOCK_EX)
  413: 	&&
  414: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  415: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  416: 	while (my ($key,$value) = each(%newenv)) {
  417: 	    $disk_env{$key} = $value;
  418: 	}
  419: 	untie(%disk_env);
  420:     }
  421:     return 'ok';
  422: }
  423: # ----------------------------------------------------- Delete from Environment
  424: 
  425: sub delenv {
  426:     my $delthis=shift;
  427:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  428:         &logthis("<font color=\"blue\">WARNING: ".
  429:                 "Attempt to delete from environment ".$delthis);
  430:         return 'error';
  431:     }
  432:     open(my $env_file,$env{'user.environment'});
  433:     if (&timed_flock($env_file,LOCK_EX)
  434: 	&&
  435: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  436: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  437: 	foreach my $key (keys(%disk_env)) {
  438: 	    if ($key=~/^$delthis/) { 
  439:                 delete($env{$key});
  440:                 delete($disk_env{$key});
  441:             }
  442: 	}
  443: 	untie(%disk_env);
  444:     }
  445:     return 'ok';
  446: }
  447: 
  448: sub get_env_multiple {
  449:     my ($name) = @_;
  450:     my @values;
  451:     if (defined($env{$name})) {
  452:         # exists is it an array
  453:         if (ref($env{$name})) {
  454:             @values=@{ $env{$name} };
  455:         } else {
  456:             $values[0]=$env{$name};
  457:         }
  458:     }
  459:     return(@values);
  460: }
  461: 
  462: # ------------------------------------------ Find out current server userload
  463: # there is a copy in lond
  464: sub userload {
  465:     my $numusers=0;
  466:     {
  467: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  468: 	my $filename;
  469: 	my $curtime=time;
  470: 	while ($filename=readdir(LONIDS)) {
  471: 	    if ($filename eq '.' || $filename eq '..') {next;}
  472: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  473: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  474: 	}
  475: 	closedir(LONIDS);
  476:     }
  477:     my $userloadpercent=0;
  478:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  479:     if ($maxuserload) {
  480: 	$userloadpercent=100*$numusers/$maxuserload;
  481:     }
  482:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  483:     return $userloadpercent;
  484: }
  485: 
  486: # ------------------------------------------ Fight off request when overloaded
  487: 
  488: sub overloaderror {
  489:     my ($r,$checkserver)=@_;
  490:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  491:     my $loadavg;
  492:     if ($checkserver eq $perlvar{'lonHostID'}) {
  493:        open(my $loadfile,'/proc/loadavg');
  494:        $loadavg=<$loadfile>;
  495:        $loadavg =~ s/\s.*//g;
  496:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  497:        close($loadfile);
  498:     } else {
  499:        $loadavg=&reply('load',$checkserver);
  500:     }
  501:     my $overload=$loadavg-100;
  502:     if ($overload>0) {
  503: 	$r->err_headers_out->{'Retry-After'}=$overload;
  504:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  505:         return 413;
  506:     }    
  507:     return '';
  508: }
  509: 
  510: # ------------------------------ Find server with least workload from spare.tab
  511: 
  512: sub spareserver {
  513:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  514:     my $spare_server;
  515:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  516:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  517:                                                      :  $userloadpercent;
  518:     
  519:     foreach my $try_server (@{ $spareid{'primary'} }) {
  520: 	($spare_server, $lowest_load) =
  521: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  522:     }
  523: 
  524:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  525: 
  526:     if (!$found_server) {
  527: 	foreach my $try_server (@{ $spareid{'default'} }) {
  528: 	    ($spare_server, $lowest_load) =
  529: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  530: 	}
  531:     }
  532: 
  533:     if (!$want_server_name) {
  534: 	$spare_server="http://".&hostname($spare_server);
  535:     }
  536:     return $spare_server;
  537: }
  538: 
  539: sub compare_server_load {
  540:     my ($try_server, $spare_server, $lowest_load) = @_;
  541: 
  542:     my $loadans     = &reply('load',    $try_server);
  543:     my $userloadans = &reply('userload',$try_server);
  544: 
  545:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  546: 	next; #didn't get a number from the server
  547:     }
  548: 
  549:     my $load;
  550:     if ($loadans =~ /\d/) {
  551: 	if ($userloadans =~ /\d/) {
  552: 	    #both are numbers, pick the bigger one
  553: 	    $load = ($loadans > $userloadans) ? $loadans 
  554: 		                              : $userloadans;
  555: 	} else {
  556: 	    $load = $loadans;
  557: 	}
  558:     } else {
  559: 	$load = $userloadans;
  560:     }
  561: 
  562:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  563: 	$spare_server = $try_server;
  564: 	$lowest_load  = $load;
  565:     }
  566:     return ($spare_server,$lowest_load);
  567: }
  568: # --------------------------------------------- Try to change a user's password
  569: 
  570: sub changepass {
  571:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  572:     $currentpass = &escape($currentpass);
  573:     $newpass     = &escape($newpass);
  574:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  575: 		       $server);
  576:     if (! $answer) {
  577: 	&logthis("No reply on password change request to $server ".
  578: 		 "by $uname in domain $udom.");
  579:     } elsif ($answer =~ "^ok") {
  580:         &logthis("$uname in $udom successfully changed their password ".
  581: 		 "on $server.");
  582:     } elsif ($answer =~ "^pwchange_failure") {
  583: 	&logthis("$uname in $udom was unable to change their password ".
  584: 		 "on $server.  The action was blocked by either lcpasswd ".
  585: 		 "or pwchange");
  586:     } elsif ($answer =~ "^non_authorized") {
  587:         &logthis("$uname in $udom did not get their password correct when ".
  588: 		 "attempting to change it on $server.");
  589:     } elsif ($answer =~ "^auth_mode_error") {
  590:         &logthis("$uname in $udom attempted to change their password despite ".
  591: 		 "not being locally or internally authenticated on $server.");
  592:     } elsif ($answer =~ "^unknown_user") {
  593:         &logthis("$uname in $udom attempted to change their password ".
  594: 		 "on $server but were unable to because $server is not ".
  595: 		 "their home server.");
  596:     } elsif ($answer =~ "^refused") {
  597: 	&logthis("$server refused to change $uname in $udom password because ".
  598: 		 "it was sent an unencrypted request to change the password.");
  599:     }
  600:     return $answer;
  601: }
  602: 
  603: # ----------------------- Try to determine user's current authentication scheme
  604: 
  605: sub queryauthenticate {
  606:     my ($uname,$udom)=@_;
  607:     my $uhome=&homeserver($uname,$udom);
  608:     if (!$uhome) {
  609: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  610: 	return 'no_host';
  611:     }
  612:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  613:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  614: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  615:     }
  616:     return $answer;
  617: }
  618: 
  619: # --------- Try to authenticate user from domain's lib servers (first this one)
  620: 
  621: sub authenticate {
  622:     my ($uname,$upass,$udom)=@_;
  623:     $upass=&escape($upass);
  624:     $uname= &LONCAPA::clean_username($uname);
  625:     my $uhome=&homeserver($uname,$udom,1);
  626:     if ((!$uhome) || ($uhome eq 'no_host')) {
  627: # Maybe the machine was offline and only re-appeared again recently?
  628:         &reconlonc();
  629: # One more
  630: 	my $uhome=&homeserver($uname,$udom,1);
  631: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  632: 	    &logthis("User $uname at $udom is unknown in authenticate");
  633: 	}
  634: 	return 'no_host';
  635:     }
  636:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  637:     if ($answer eq 'authorized') {
  638: 	&logthis("User $uname at $udom authorized by $uhome"); 
  639: 	return $uhome; 
  640:     }
  641:     if ($answer eq 'non_authorized') {
  642: 	&logthis("User $uname at $udom rejected by $uhome");
  643: 	return 'no_host'; 
  644:     }
  645:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  646:     return 'no_host';
  647: }
  648: 
  649: # ---------------------- Find the homebase for a user from domain's lib servers
  650: 
  651: my %homecache;
  652: sub homeserver {
  653:     my ($uname,$udom,$ignoreBadCache)=@_;
  654:     my $index="$uname:$udom";
  655: 
  656:     if (exists($homecache{$index})) { return $homecache{$index}; }
  657: 
  658:     my %servers = &get_servers($udom,'library');
  659:     foreach my $tryserver (keys(%servers)) {
  660:         next if ($ignoreBadCache ne 'true' && 
  661: 		 exists($badServerCache{$tryserver}));
  662: 
  663: 	my $answer=reply("home:$udom:$uname",$tryserver);
  664: 	if ($answer eq 'found') {
  665: 	    delete($badServerCache{$tryserver}); 
  666: 	    return $homecache{$index}=$tryserver;
  667: 	} elsif ($answer eq 'no_host') {
  668: 	    $badServerCache{$tryserver}=1;
  669: 	}
  670:     }    
  671:     return 'no_host';
  672: }
  673: 
  674: # ---------------------- Get domain configuration for a domain
  675: sub get_domainconf {
  676:     my ($udom) = @_;
  677:     my $cachetime=1800;
  678:     my ($result,$cached)=&is_cached_new('domainconfig',$udom);
  679:     if (defined($cached)) { return %{$result}; }
  680: 
  681:     if ($udom eq '') {
  682:         $udom = &Apache::loncommon::determinedomain();
  683:     }
  684:     my %domconfig = &get_dom('configuration',['login','rolecolors'],$udom);
  685:     my %designhash;
  686:     if (keys(%domconfig) > 0) {
  687:         if (ref($domconfig{'login'}) eq 'HASH') {
  688:             foreach my $key (keys(%{$domconfig{'login'}})) {
  689:                 $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
  690:             }
  691:         }
  692:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
  693:             foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
  694:                 if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
  695:                     foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
  696:                         $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
  697:                     }
  698:                 }
  699:             }
  700:         }
  701:     } else {
  702:         my $designdir=$perlvar{'lonTabDir'}.'/lonDomColors';
  703:         my $designfile =  $designdir.'/'.$udom.'.tab';
  704:         if (-e $designfile) {
  705:             if ( open (my $fh,"<$designfile") ) {
  706:                 while (my $line = <$fh>) {
  707:                     next if ($line =~ /^\#/);
  708:                     chomp($line);
  709:                     my ($key,$val)=(split(/\=/,$line));
  710:                     if ($val) { $designhash{$udom.'.'.$key}=$val; }
  711:                 }
  712:                 close($fh);
  713:             }
  714:         }
  715:         if (-e '/home/httpd/html/adm/lonDomLogos/'.$udom.'.gif') {
  716:             $designhash{$udom.'.login.domlogo'} = 
  717:                 &lonhttpdurl("/adm/lonDomLogos/$udom.gif"); 
  718:         }
  719:     }
  720:     &do_cache_new('domainconfig',$udom,\%designhash,$cachetime);
  721:     return %designhash;
  722: }
  723: 
  724: sub devalidate_domconfig_cache {
  725:     my ($udom)=@_;
  726:     &devalidate_cache_new('domainconfig',$udom);
  727: }
  728: 
  729: # ------------------------------------- Find the usernames behind a list of IDs
  730: 
  731: sub idget {
  732:     my ($udom,@ids)=@_;
  733:     my %returnhash=();
  734:     
  735:     my %servers = &get_servers($udom,'library');
  736:     foreach my $tryserver (keys(%servers)) {
  737: 	my $idlist=join('&',@ids);
  738: 	$idlist=~tr/A-Z/a-z/; 
  739: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  740: 	my @answer=();
  741: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  742: 	    @answer=split(/\&/,$reply);
  743: 	}                    ;
  744: 	my $i;
  745: 	for ($i=0;$i<=$#ids;$i++) {
  746: 	    if ($answer[$i]) {
  747: 		$returnhash{$ids[$i]}=$answer[$i];
  748: 	    } 
  749: 	}
  750:     } 
  751:     return %returnhash;
  752: }
  753: 
  754: # ------------------------------------- Find the IDs behind a list of usernames
  755: 
  756: sub idrget {
  757:     my ($udom,@unames)=@_;
  758:     my %returnhash=();
  759:     foreach my $uname (@unames) {
  760:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  761:     }
  762:     return %returnhash;
  763: }
  764: 
  765: # ------------------------------- Store away a list of names and associated IDs
  766: 
  767: sub idput {
  768:     my ($udom,%ids)=@_;
  769:     my %servers=();
  770:     foreach my $uname (keys(%ids)) {
  771: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  772:         my $uhom=&homeserver($uname,$udom);
  773:         if ($uhom ne 'no_host') {
  774:             my $id=&escape($ids{$uname});
  775:             $id=~tr/A-Z/a-z/;
  776:             my $esc_unam=&escape($uname);
  777: 	    if ($servers{$uhom}) {
  778: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  779:             } else {
  780:                 $servers{$uhom}=$id.'='.$esc_unam;
  781:             }
  782:         }
  783:     }
  784:     foreach my $server (keys(%servers)) {
  785:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  786:     }
  787: }
  788: 
  789: # ------------------------------------------- get items from domain db files   
  790: 
  791: sub get_dom {
  792:     my ($namespace,$storearr,$udom,$uhome)=@_;
  793:     my $items='';
  794:     foreach my $item (@$storearr) {
  795:         $items.=&escape($item).'&';
  796:     }
  797:     $items=~s/\&$//;
  798:     if (!$udom) {
  799:         $udom=$env{'user.domain'};
  800:         if (defined(&domain($udom,'primary'))) {
  801:             $uhome=&domain($udom,'primary');
  802:         } else {
  803:             $uhome eq '';
  804:         }
  805:     } else {
  806:         if (!$uhome) {
  807:             if (defined(&domain($udom,'primary'))) {
  808:                 $uhome=&domain($udom,'primary');
  809:             }
  810:         }
  811:     }
  812:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  813:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  814:         my @pairs=split(/\&/,$rep);
  815:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  816:             return @pairs;
  817:         }
  818:         my %returnhash=();
  819:         my $i=0;
  820:         foreach my $item (@$storearr) {
  821:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  822:             $i++;
  823:         }
  824:         return %returnhash;
  825:     } else {
  826:         &logthis("get_dom failed - no homeserver and/or domain");
  827:     }
  828: }
  829: 
  830: # -------------------------------------------- put items in domain db files 
  831: 
  832: sub put_dom {
  833:     my ($namespace,$storehash,$udom,$uhome)=@_;
  834:     if (!$udom) {
  835:         $udom=$env{'user.domain'};
  836:         if (defined(&domain($udom,'primary'))) {
  837:             $uhome=&domain($udom,'primary');
  838:         } else {
  839:             $uhome eq '';
  840:         }
  841:     } else {
  842:         if (!$uhome) {
  843:             if (defined(&domain($udom,'primary'))) {
  844:                 $uhome=&domain($udom,'primary');
  845:             }
  846:         }
  847:     } 
  848:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  849:         my $items='';
  850:         foreach my $item (keys(%$storehash)) {
  851:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  852:         }
  853:         $items=~s/\&$//;
  854:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  855:     } else {
  856:         &logthis("put_dom failed - no homeserver and/or domain");
  857:     }
  858: }
  859: 
  860: sub retrieve_inst_usertypes {
  861:     my ($udom) = @_;
  862:     my (%returnhash,@order);
  863:     if (defined(&domain($udom,'primary'))) {
  864:         my $uhome=&domain($udom,'primary');
  865:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  866:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  867:         my @pairs=split(/\&/,$hashitems);
  868:         foreach my $item (@pairs) {
  869:             my ($key,$value)=split(/=/,$item,2);
  870:             $key = &unescape($key);
  871:             next if ($key =~ /^error: 2 /);
  872:             $returnhash{$key}=&thaw_unescape($value);
  873:         }
  874:         my @esc_order = split(/\&/,$orderitems);
  875:         foreach my $item (@esc_order) {
  876:             push(@order,&unescape($item));
  877:         }
  878:     } else {
  879:         &logthis("get_dom failed - no primary domain server for $udom");
  880:     }
  881:     return (\%returnhash,\@order);
  882: }
  883: 
  884: # --------------------------------------------------- Assign a key to a student
  885: 
  886: sub assign_access_key {
  887: #
  888: # a valid key looks like uname:udom#comments
  889: # comments are being appended
  890: #
  891:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  892:     $kdom=
  893:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  894:     $knum=
  895:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  896:     $cdom=
  897:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  898:     $cnum=
  899:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  900:     $udom=$env{'user.name'} unless (defined($udom));
  901:     $uname=$env{'user.domain'} unless (defined($uname));
  902:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  903:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  904:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  905:                                                   # assigned to this person
  906:                                                   # - this should not happen,
  907:                                                   # unless something went wrong
  908:                                                   # the first time around
  909: # ready to assign
  910:         $logentry=$1.'; '.$logentry;
  911:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  912:                                                  $kdom,$knum) eq 'ok') {
  913: # key now belongs to user
  914: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  915:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  916:                 &appenv('environment.'.$envkey => $ckey);
  917:                 return 'ok';
  918:             } else {
  919:                 return 
  920:   'error: Count not permanently assign key, will need to be re-entered later.';
  921: 	    }
  922:         } else {
  923:             return 'error: Could not assign key, try again later.';
  924:         }
  925:     } elsif (!$existing{$ckey}) {
  926: # the key does not exist
  927: 	return 'error: The key does not exist';
  928:     } else {
  929: # the key is somebody else's
  930: 	return 'error: The key is already in use';
  931:     }
  932: }
  933: 
  934: # ------------------------------------------ put an additional comment on a key
  935: 
  936: sub comment_access_key {
  937: #
  938: # a valid key looks like uname:udom#comments
  939: # comments are being appended
  940: #
  941:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  942:     $cdom=
  943:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  944:     $cnum=
  945:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  946:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  947:     if ($existing{$ckey}) {
  948:         $existing{$ckey}.='; '.$logentry;
  949: # ready to assign
  950:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  951:                                                  $cdom,$cnum) eq 'ok') {
  952: 	    return 'ok';
  953:         } else {
  954: 	    return 'error: Count not store comment.';
  955:         }
  956:     } else {
  957: # the key does not exist
  958: 	return 'error: The key does not exist';
  959:     }
  960: }
  961: 
  962: # ------------------------------------------------------ Generate a set of keys
  963: 
  964: sub generate_access_keys {
  965:     my ($number,$cdom,$cnum,$logentry)=@_;
  966:     $cdom=
  967:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  968:     $cnum=
  969:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  970:     unless (&allowed('mky',$cdom)) { return 0; }
  971:     unless (($cdom) && ($cnum)) { return 0; }
  972:     if ($number>10000) { return 0; }
  973:     sleep(2); # make sure don't get same seed twice
  974:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  975:     my $total=0;
  976:     for (my $i=1;$i<=$number;$i++) {
  977:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  978:                   sprintf("%lx",int(100000*rand)).'-'.
  979:                   sprintf("%lx",int(100000*rand));
  980:        $newkey=~s/1/g/g; # folks mix up 1 and l
  981:        $newkey=~s/0/h/g; # and also 0 and O
  982:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  983:        if ($existing{$newkey}) {
  984:            $i--;
  985:        } else {
  986: 	  if (&put('accesskeys',
  987:               { $newkey => '# generated '.localtime().
  988:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  989:                            '; '.$logentry },
  990: 		   $cdom,$cnum) eq 'ok') {
  991:               $total++;
  992: 	  }
  993:        }
  994:     }
  995:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  996:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  997:     return $total;
  998: }
  999: 
 1000: # ------------------------------------------------------- Validate an accesskey
 1001: 
 1002: sub validate_access_key {
 1003:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1004:     $cdom=
 1005:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1006:     $cnum=
 1007:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1008:     $udom=$env{'user.domain'} unless (defined($udom));
 1009:     $uname=$env{'user.name'} unless (defined($uname));
 1010:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1011:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1012: }
 1013: 
 1014: # ------------------------------------- Find the section of student in a course
 1015: sub devalidate_getsection_cache {
 1016:     my ($udom,$unam,$courseid)=@_;
 1017:     my $hashid="$udom:$unam:$courseid";
 1018:     &devalidate_cache_new('getsection',$hashid);
 1019: }
 1020: 
 1021: sub courseid_to_courseurl {
 1022:     my ($courseid) = @_;
 1023:     #already url style courseid
 1024:     return $courseid if ($courseid =~ m{^/});
 1025: 
 1026:     if (exists($env{'course.'.$courseid.'.num'})) {
 1027: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1028: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1029: 	return "/$cdom/$cnum";
 1030:     }
 1031: 
 1032:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1033:     if (exists($courseinfo{'num'})) {
 1034: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1035:     }
 1036: 
 1037:     return undef;
 1038: }
 1039: 
 1040: sub getsection {
 1041:     my ($udom,$unam,$courseid)=@_;
 1042:     my $cachetime=1800;
 1043: 
 1044:     my $hashid="$udom:$unam:$courseid";
 1045:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1046:     if (defined($cached)) { return $result; }
 1047: 
 1048:     my %Pending; 
 1049:     my %Expired;
 1050:     #
 1051:     # Each role can either have not started yet (pending), be active, 
 1052:     #    or have expired.
 1053:     #
 1054:     # If there is an active role, we are done.
 1055:     #
 1056:     # If there is more than one role which has not started yet, 
 1057:     #     choose the one which will start sooner
 1058:     # If there is one role which has not started yet, return it.
 1059:     #
 1060:     # If there is more than one expired role, choose the one which ended last.
 1061:     # If there is a role which has expired, return it.
 1062:     #
 1063:     $courseid = &courseid_to_courseurl($courseid);
 1064:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1065:     foreach my $key (keys(%roleshash)) {
 1066:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1067:         my $section=$1;
 1068:         if ($key eq $courseid.'_st') { $section=''; }
 1069:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1070:         my $now=time;
 1071:         if (defined($end) && $end && ($now > $end)) {
 1072:             $Expired{$end}=$section;
 1073:             next;
 1074:         }
 1075:         if (defined($start) && $start && ($now < $start)) {
 1076:             $Pending{$start}=$section;
 1077:             next;
 1078:         }
 1079:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1080:     }
 1081:     #
 1082:     # Presumedly there will be few matching roles from the above
 1083:     # loop and the sorting time will be negligible.
 1084:     if (scalar(keys(%Pending))) {
 1085:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1086:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1087:     } 
 1088:     if (scalar(keys(%Expired))) {
 1089:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1090:         my $time = pop(@sorted);
 1091:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1092:     }
 1093:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1094: }
 1095: 
 1096: sub save_cache {
 1097:     &purge_remembered();
 1098:     #&Apache::loncommon::validate_page();
 1099:     undef(%env);
 1100:     undef($env_loaded);
 1101: }
 1102: 
 1103: my $to_remember=-1;
 1104: my %remembered;
 1105: my %accessed;
 1106: my $kicks=0;
 1107: my $hits=0;
 1108: sub make_key {
 1109:     my ($name,$id) = @_;
 1110:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
 1111:     return &escape($name.':'.$id);
 1112: }
 1113: 
 1114: sub devalidate_cache_new {
 1115:     my ($name,$id,$debug) = @_;
 1116:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1117:     $id=&make_key($name,$id);
 1118:     $memcache->delete($id);
 1119:     delete($remembered{$id});
 1120:     delete($accessed{$id});
 1121: }
 1122: 
 1123: sub is_cached_new {
 1124:     my ($name,$id,$debug) = @_;
 1125:     $id=&make_key($name,$id);
 1126:     if (exists($remembered{$id})) {
 1127: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1128: 	$accessed{$id}=[&gettimeofday()];
 1129: 	$hits++;
 1130: 	return ($remembered{$id},1);
 1131:     }
 1132:     my $value = $memcache->get($id);
 1133:     if (!(defined($value))) {
 1134: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1135: 	return (undef,undef);
 1136:     }
 1137:     if ($value eq '__undef__') {
 1138: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1139: 	$value=undef;
 1140:     }
 1141:     &make_room($id,$value,$debug);
 1142:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1143:     return ($value,1);
 1144: }
 1145: 
 1146: sub do_cache_new {
 1147:     my ($name,$id,$value,$time,$debug) = @_;
 1148:     $id=&make_key($name,$id);
 1149:     my $setvalue=$value;
 1150:     if (!defined($setvalue)) {
 1151: 	$setvalue='__undef__';
 1152:     }
 1153:     if (!defined($time) ) {
 1154: 	$time=600;
 1155:     }
 1156:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1157:     $memcache->set($id,$setvalue,$time);
 1158:     # need to make a copy of $value
 1159:     #&make_room($id,$value,$debug);
 1160:     return $value;
 1161: }
 1162: 
 1163: sub make_room {
 1164:     my ($id,$value,$debug)=@_;
 1165:     $remembered{$id}=$value;
 1166:     if ($to_remember<0) { return; }
 1167:     $accessed{$id}=[&gettimeofday()];
 1168:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1169:     my $to_kick;
 1170:     my $max_time=0;
 1171:     foreach my $other (keys(%accessed)) {
 1172: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1173: 	    $to_kick=$other;
 1174: 	    $max_time=&tv_interval($accessed{$other});
 1175: 	}
 1176:     }
 1177:     delete($remembered{$to_kick});
 1178:     delete($accessed{$to_kick});
 1179:     $kicks++;
 1180:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1181:     return;
 1182: }
 1183: 
 1184: sub purge_remembered {
 1185:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1186:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1187:     undef(%remembered);
 1188:     undef(%accessed);
 1189: }
 1190: # ------------------------------------- Read an entry from a user's environment
 1191: 
 1192: sub userenvironment {
 1193:     my ($udom,$unam,@what)=@_;
 1194:     my %returnhash=();
 1195:     my @answer=split(/\&/,
 1196:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1197:                       &homeserver($unam,$udom)));
 1198:     my $i;
 1199:     for ($i=0;$i<=$#what;$i++) {
 1200: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1201:     }
 1202:     return %returnhash;
 1203: }
 1204: 
 1205: # ---------------------------------------------------------- Get a studentphoto
 1206: sub studentphoto {
 1207:     my ($udom,$unam,$ext) = @_;
 1208:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1209:     if (defined($env{'request.course.id'})) {
 1210:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1211:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1212:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1213:             } else {
 1214:                 my ($result,$perm_reqd)=
 1215: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1216:                 if ($result eq 'ok') {
 1217:                     if (!($perm_reqd eq 'yes')) {
 1218:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1219:                     }
 1220:                 }
 1221:             }
 1222:         }
 1223:     } else {
 1224:         my ($result,$perm_reqd) = 
 1225: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1226:         if ($result eq 'ok') {
 1227:             if (!($perm_reqd eq 'yes')) {
 1228:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1229:             }
 1230:         }
 1231:     }
 1232:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1233: }
 1234: 
 1235: sub retrievestudentphoto {
 1236:     my ($udom,$unam,$ext,$type) = @_;
 1237:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1238:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1239:     if ($ret eq 'ok') {
 1240:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1241:         if ($type eq 'thumbnail') {
 1242:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1243:         }
 1244:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1245:         return $tokenurl;
 1246:     } else {
 1247:         if ($type eq 'thumbnail') {
 1248:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1249:         } else { 
 1250:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1251:         }
 1252:     }
 1253: }
 1254: 
 1255: # -------------------------------------------------------------------- New chat
 1256: 
 1257: sub chatsend {
 1258:     my ($newentry,$anon,$group)=@_;
 1259:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1260:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1261:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1262:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1263: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1264: 		   &escape($newentry)).':'.$group,$chome);
 1265: }
 1266: 
 1267: # ------------------------------------------ Find current version of a resource
 1268: 
 1269: sub getversion {
 1270:     my $fname=&clutter(shift);
 1271:     unless ($fname=~/^\/res\//) { return -1; }
 1272:     return &currentversion(&filelocation('',$fname));
 1273: }
 1274: 
 1275: sub currentversion {
 1276:     my $fname=shift;
 1277:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1278:     if (defined($cached)) { return $result; }
 1279:     my $author=$fname;
 1280:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1281:     my ($udom,$uname)=split(/\//,$author);
 1282:     my $home=homeserver($uname,$udom);
 1283:     if ($home eq 'no_host') { 
 1284:         return -1; 
 1285:     }
 1286:     my $answer=reply("currentversion:$fname",$home);
 1287:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1288: 	return -1;
 1289:     }
 1290:     return &do_cache_new('resversion',$fname,$answer,600);
 1291: }
 1292: 
 1293: # ----------------------------- Subscribe to a resource, return URL if possible
 1294: 
 1295: sub subscribe {
 1296:     my $fname=shift;
 1297:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1298:     $fname=~s/[\n\r]//g;
 1299:     my $author=$fname;
 1300:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1301:     my ($udom,$uname)=split(/\//,$author);
 1302:     my $home=homeserver($uname,$udom);
 1303:     if ($home eq 'no_host') {
 1304:         return 'not_found';
 1305:     }
 1306:     my $answer=reply("sub:$fname",$home);
 1307:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1308: 	$answer.=' by '.$home;
 1309:     }
 1310:     return $answer;
 1311: }
 1312:     
 1313: # -------------------------------------------------------------- Replicate file
 1314: 
 1315: sub repcopy {
 1316:     my $filename=shift;
 1317:     $filename=~s/\/+/\//g;
 1318:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1319:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1320:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1321: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1322: 	return &repcopy_userfile($filename);
 1323:     }
 1324:     $filename=~s/[\n\r]//g;
 1325:     my $transname="$filename.in.transfer";
 1326: # FIXME: this should flock
 1327:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1328:     my $remoteurl=subscribe($filename);
 1329:     if ($remoteurl =~ /^con_lost by/) {
 1330: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1331:            return 'unavailable';
 1332:     } elsif ($remoteurl eq 'not_found') {
 1333: 	   #&logthis("Subscribe returned not_found: $filename");
 1334: 	   return 'not_found';
 1335:     } elsif ($remoteurl =~ /^rejected by/) {
 1336: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1337:            return 'forbidden';
 1338:     } elsif ($remoteurl eq 'directory') {
 1339:            return 'ok';
 1340:     } else {
 1341:         my $author=$filename;
 1342:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1343:         my ($udom,$uname)=split(/\//,$author);
 1344:         my $home=homeserver($uname,$udom);
 1345:         unless ($home eq $perlvar{'lonHostID'}) {
 1346:            my @parts=split(/\//,$filename);
 1347:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1348:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1349:                &logthis("Malconfiguration for replication: $filename");
 1350: 	       return 'bad_request';
 1351:            }
 1352:            my $count;
 1353:            for ($count=5;$count<$#parts;$count++) {
 1354:                $path.="/$parts[$count]";
 1355:                if ((-e $path)!=1) {
 1356: 		   mkdir($path,0777);
 1357:                }
 1358:            }
 1359:            my $ua=new LWP::UserAgent;
 1360:            my $request=new HTTP::Request('GET',"$remoteurl");
 1361:            my $response=$ua->request($request,$transname);
 1362:            if ($response->is_error()) {
 1363: 	       unlink($transname);
 1364:                my $message=$response->status_line;
 1365:                &logthis("<font color=\"blue\">WARNING:"
 1366:                        ." LWP get: $message: $filename</font>");
 1367:                return 'unavailable';
 1368:            } else {
 1369: 	       if ($remoteurl!~/\.meta$/) {
 1370:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1371:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1372:                   if ($mresponse->is_error()) {
 1373: 		      unlink($filename.'.meta');
 1374:                       &logthis(
 1375:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1376:                   }
 1377: 	       }
 1378:                rename($transname,$filename);
 1379:                return 'ok';
 1380:            }
 1381:        }
 1382:     }
 1383: }
 1384: 
 1385: # ------------------------------------------------ Get server side include body
 1386: sub ssi_body {
 1387:     my ($filelink,%form)=@_;
 1388:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1389:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1390:     }
 1391:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1392:                                      &ssi($filelink,%form));
 1393:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1394:     $output=~s/^.*?\<body[^\>]*\>//si;
 1395:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1396:     return $output;
 1397: }
 1398: 
 1399: # --------------------------------------------------------- Server Side Include
 1400: 
 1401: sub absolute_url {
 1402:     my ($host_name) = @_;
 1403:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1404:     if ($host_name eq '') {
 1405: 	$host_name = $ENV{'SERVER_NAME'};
 1406:     }
 1407:     return $protocol.$host_name;
 1408: }
 1409: 
 1410: sub ssi {
 1411: 
 1412:     my ($fn,%form)=@_;
 1413: 
 1414:     my $ua=new LWP::UserAgent;
 1415:     
 1416:     my $request;
 1417: 
 1418:     $form{'no_update_last_known'}=1;
 1419: 
 1420:     if (%form) {
 1421:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1422:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1423:     } else {
 1424:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1425:     }
 1426: 
 1427:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1428:     my $response=$ua->request($request);
 1429: 
 1430:     return $response->content;
 1431: }
 1432: 
 1433: sub externalssi {
 1434:     my ($url)=@_;
 1435:     my $ua=new LWP::UserAgent;
 1436:     my $request=new HTTP::Request('GET',$url);
 1437:     my $response=$ua->request($request);
 1438:     return $response->content;
 1439: }
 1440: 
 1441: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1442: 
 1443: sub allowuploaded {
 1444:     my ($srcurl,$url)=@_;
 1445:     $url=&clutter(&declutter($url));
 1446:     my $dir=$url;
 1447:     $dir=~s/\/[^\/]+$//;
 1448:     my %httpref=();
 1449:     my $httpurl=&hreflocation('',$url);
 1450:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1451:     &Apache::lonnet::appenv(%httpref);
 1452: }
 1453: 
 1454: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1455: # input: action, courseID, current domain, intended
 1456: #        path to file, source of file, instruction to parse file for objects,
 1457: #        ref to hash for embedded objects,
 1458: #        ref to hash for codebase of java objects.
 1459: #
 1460: # output: url to file (if action was uploaddoc), 
 1461: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1462: #
 1463: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1464: # course.
 1465: #
 1466: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1467: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1468: #          course's home server.
 1469: #
 1470: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1471: #          be copied from $source (current location) to 
 1472: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1473: #         and will then be copied to
 1474: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1475: #         course's home server.
 1476: #
 1477: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1478: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1479: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1480: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1481: #         in course's home server.
 1482: #
 1483: 
 1484: sub process_coursefile {
 1485:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1486:     my $fetchresult;
 1487:     my $home=&homeserver($docuname,$docudom);
 1488:     if ($action eq 'propagate') {
 1489:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1490: 			     $home);
 1491:     } else {
 1492:         my $fpath = '';
 1493:         my $fname = $file;
 1494:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1495:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1496:         my $filepath = &build_filepath($fpath);
 1497:         if ($action eq 'copy') {
 1498:             if ($source eq '') {
 1499:                 $fetchresult = 'no source file';
 1500:                 return $fetchresult;
 1501:             } else {
 1502:                 my $destination = $filepath.'/'.$fname;
 1503:                 rename($source,$destination);
 1504:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1505:                                  $home);
 1506:             }
 1507:         } elsif ($action eq 'uploaddoc') {
 1508:             open(my $fh,'>'.$filepath.'/'.$fname);
 1509:             print $fh $env{'form.'.$source};
 1510:             close($fh);
 1511:             if ($parser eq 'parse') {
 1512:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1513:                 unless ($parse_result eq 'ok') {
 1514:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1515:                 }
 1516:             }
 1517:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1518:                                  $home);
 1519:             if ($fetchresult eq 'ok') {
 1520:                 return '/uploaded/'.$fpath.'/'.$fname;
 1521:             } else {
 1522:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1523:                         ' to host '.$home.': '.$fetchresult);
 1524:                 return '/adm/notfound.html';
 1525:             }
 1526:         }
 1527:     }
 1528:     unless ( $fetchresult eq 'ok') {
 1529:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1530:              ' to host '.$home.': '.$fetchresult);
 1531:     }
 1532:     return $fetchresult;
 1533: }
 1534: 
 1535: sub build_filepath {
 1536:     my ($fpath) = @_;
 1537:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1538:     unless ($fpath eq '') {
 1539:         my @parts=split('/',$fpath);
 1540:         foreach my $part (@parts) {
 1541:             $filepath.= '/'.$part;
 1542:             if ((-e $filepath)!=1) {
 1543:                 mkdir($filepath,0777);
 1544:             }
 1545:         }
 1546:     }
 1547:     return $filepath;
 1548: }
 1549: 
 1550: sub store_edited_file {
 1551:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1552:     my $file = $primary_url;
 1553:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1554:     my $fpath = '';
 1555:     my $fname = $file;
 1556:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1557:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1558:     my $filepath = &build_filepath($fpath);
 1559:     open(my $fh,'>'.$filepath.'/'.$fname);
 1560:     print $fh $content;
 1561:     close($fh);
 1562:     my $home=&homeserver($docuname,$docudom);
 1563:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1564: 			  $home);
 1565:     if ($$fetchresult eq 'ok') {
 1566:         return '/uploaded/'.$fpath.'/'.$fname;
 1567:     } else {
 1568:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1569: 		 ' to host '.$home.': '.$$fetchresult);
 1570:         return '/adm/notfound.html';
 1571:     }
 1572: }
 1573: 
 1574: sub clean_filename {
 1575:     my ($fname,$args)=@_;
 1576: # Replace Windows backslashes by forward slashes
 1577:     $fname=~s/\\/\//g;
 1578:     if (!$args->{'keep_path'}) {
 1579:         # Get rid of everything but the actual filename
 1580: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1581:     }
 1582: # Replace spaces by underscores
 1583:     $fname=~s/\s+/\_/g;
 1584: # Replace all other weird characters by nothing
 1585:     $fname=~s{[^/\w\.\-]}{}g;
 1586: # Replace all .\d. sequences with _\d. so they no longer look like version
 1587: # numbers
 1588:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1589:     return $fname;
 1590: }
 1591: 
 1592: # --------------- Take an uploaded file and put it into the userfiles directory
 1593: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1594: #                    the desired filenam is in $env{"form.$formname.filename"}
 1595: #        $coursedoc - if true up to the current course
 1596: #                     if false
 1597: #        $subdir - directory in userfile to store the file into
 1598: #        $parser - instruction to parse file for objects ($parser = parse)    
 1599: #        $allfiles - reference to hash for embedded objects
 1600: #        $codebase - reference to hash for codebase of java objects
 1601: #        $desuname - username for permanent storage of uploaded file
 1602: #        $dsetudom - domain for permanaent storage of uploaded file
 1603: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1604: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1605: # 
 1606: # output: url of file in userspace, or error: <message> 
 1607: #             or /adm/notfound.html if failure to upload occurse
 1608: 
 1609: 
 1610: sub userfileupload {
 1611:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1612:         $destudom,$thumbwidth,$thumbheight)=@_;
 1613:     if (!defined($subdir)) { $subdir='unknown'; }
 1614:     my $fname=$env{'form.'.$formname.'.filename'};
 1615:     $fname=&clean_filename($fname);
 1616: # See if there is anything left
 1617:     unless ($fname) { return 'error: no uploaded file'; }
 1618:     chop($env{'form.'.$formname});
 1619:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1620:         my $now = time;
 1621:         my $filepath = 'tmp/helprequests/'.$now;
 1622:         my @parts=split(/\//,$filepath);
 1623:         my $fullpath = $perlvar{'lonDaemons'};
 1624:         for (my $i=0;$i<@parts;$i++) {
 1625:             $fullpath .= '/'.$parts[$i];
 1626:             if ((-e $fullpath)!=1) {
 1627:                 mkdir($fullpath,0777);
 1628:             }
 1629:         }
 1630:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1631:         print $fh $env{'form.'.$formname};
 1632:         close($fh);
 1633:         return $fullpath.'/'.$fname;
 1634:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1635:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1636:                        '_'.$env{'user.domain'}.'/pending';
 1637:         my @parts=split(/\//,$filepath);
 1638:         my $fullpath = $perlvar{'lonDaemons'};
 1639:         for (my $i=0;$i<@parts;$i++) {
 1640:             $fullpath .= '/'.$parts[$i];
 1641:             if ((-e $fullpath)!=1) {
 1642:                 mkdir($fullpath,0777);
 1643:             }
 1644:         }
 1645:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1646:         print $fh $env{'form.'.$formname};
 1647:         close($fh);
 1648:         return $fullpath.'/'.$fname;
 1649:     }
 1650:     
 1651: # Create the directory if not present
 1652:     $fname="$subdir/$fname";
 1653:     if ($coursedoc) {
 1654: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1655: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1656:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1657:             return &finishuserfileupload($docuname,$docudom,
 1658: 					 $formname,$fname,$parser,$allfiles,
 1659: 					 $codebase,$thumbwidth,$thumbheight);
 1660:         } else {
 1661:             $fname=$env{'form.folder'}.'/'.$fname;
 1662:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1663: 				       $fname,$formname,$parser,
 1664: 				       $allfiles,$codebase);
 1665:         }
 1666:     } elsif (defined($destuname)) {
 1667:         my $docuname=$destuname;
 1668:         my $docudom=$destudom;
 1669: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1670: 				     $parser,$allfiles,$codebase,
 1671:                                      $thumbwidth,$thumbheight);
 1672:         
 1673:     } else {
 1674:         my $docuname=$env{'user.name'};
 1675:         my $docudom=$env{'user.domain'};
 1676:         if (exists($env{'form.group'})) {
 1677:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1678:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1679:         }
 1680: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1681: 				     $parser,$allfiles,$codebase,
 1682:                                      $thumbwidth,$thumbheight);
 1683:     }
 1684: }
 1685: 
 1686: sub finishuserfileupload {
 1687:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1688:         $thumbwidth,$thumbheight) = @_;
 1689:     my $path=$docudom.'/'.$docuname.'/';
 1690:     my $filepath=$perlvar{'lonDocRoot'};
 1691:     my ($fnamepath,$file,$fetchthumb);
 1692:     $file=$fname;
 1693:     if ($fname=~m|/|) {
 1694:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1695: 	$path.=$fnamepath.'/';
 1696:     }
 1697:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1698:     my $count;
 1699:     for ($count=4;$count<=$#parts;$count++) {
 1700:         $filepath.="/$parts[$count]";
 1701:         if ((-e $filepath)!=1) {
 1702: 	    mkdir($filepath,0777);
 1703:         }
 1704:     }
 1705: # Save the file
 1706:     {
 1707: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1708: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1709: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1710: 	    return '/adm/notfound.html';
 1711: 	}
 1712: 	if (!print FH ($env{'form.'.$formname})) {
 1713: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1714: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1715: 	    return '/adm/notfound.html';
 1716: 	}
 1717: 	close(FH);
 1718:     }
 1719:     if ($parser eq 'parse') {
 1720:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1721: 						   $codebase);
 1722:         unless ($parse_result eq 'ok') {
 1723:             &logthis('Failed to parse '.$filepath.$file.
 1724: 		     ' for embedded media: '.$parse_result); 
 1725:         }
 1726:     }
 1727:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1728:         my $input = $filepath.'/'.$file;
 1729:         my $output = $filepath.'/'.'tn-'.$file;
 1730:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1731:         system("convert -sample $thumbsize $input $output");
 1732:         if (-e $filepath.'/'.'tn-'.$file) {
 1733:             $fetchthumb  = 1; 
 1734:         }
 1735:     }
 1736:  
 1737: # Notify homeserver to grep it
 1738: #
 1739:     my $docuhome=&homeserver($docuname,$docudom);
 1740:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1741:     if ($fetchresult eq 'ok') {
 1742:         if ($fetchthumb) {
 1743:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1744:             if ($thumbresult ne 'ok') {
 1745:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1746:                          $docuhome.': '.$thumbresult);
 1747:             }
 1748:         }
 1749: #
 1750: # Return the URL to it
 1751:         return '/uploaded/'.$path.$file;
 1752:     } else {
 1753:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1754: 		 ': '.$fetchresult);
 1755:         return '/adm/notfound.html';
 1756:     }
 1757: }
 1758: 
 1759: sub extract_embedded_items {
 1760:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1761:     my @state = ();
 1762:     my %javafiles = (
 1763:                       codebase => '',
 1764:                       code => '',
 1765:                       archive => ''
 1766:                     );
 1767:     my %mediafiles = (
 1768:                       src => '',
 1769:                       movie => '',
 1770:                      );
 1771:     my $p;
 1772:     if ($content) {
 1773:         $p = HTML::LCParser->new($content);
 1774:     } else {
 1775:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1776:     }
 1777:     while (my $t=$p->get_token()) {
 1778: 	if ($t->[0] eq 'S') {
 1779: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1780: 	    push (@state, $tagname);
 1781:             if (lc($tagname) eq 'allow') {
 1782:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1783:             }
 1784: 	    if (lc($tagname) eq 'img') {
 1785: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1786: 	    }
 1787:             if (lc($tagname) eq 'script') {
 1788:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1789:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1790:                 } else {
 1791:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1792:                 }
 1793:             }
 1794:             if (lc($tagname) eq 'link') {
 1795:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1796:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1797:                 }
 1798:             }
 1799: 	    if (lc($tagname) eq 'object' ||
 1800: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1801: 		foreach my $item (keys(%javafiles)) {
 1802: 		    $javafiles{$item} = '';
 1803: 		}
 1804: 	    }
 1805: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1806: 		my $name = lc($attr->{'name'});
 1807: 		foreach my $item (keys(%javafiles)) {
 1808: 		    if ($name eq $item) {
 1809: 			$javafiles{$item} = $attr->{'value'};
 1810: 			last;
 1811: 		    }
 1812: 		}
 1813: 		foreach my $item (keys(%mediafiles)) {
 1814: 		    if ($name eq $item) {
 1815: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1816: 			last;
 1817: 		    }
 1818: 		}
 1819: 	    }
 1820: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1821: 		foreach my $item (keys(%javafiles)) {
 1822: 		    if ($attr->{$item}) {
 1823: 			$javafiles{$item} = $attr->{$item};
 1824: 			last;
 1825: 		    }
 1826: 		}
 1827: 		foreach my $item (keys(%mediafiles)) {
 1828: 		    if ($attr->{$item}) {
 1829: 			&add_filetype($allfiles,$attr->{$item},$item);
 1830: 			last;
 1831: 		    }
 1832: 		}
 1833: 	    }
 1834: 	} elsif ($t->[0] eq 'E') {
 1835: 	    my ($tagname) = ($t->[1]);
 1836: 	    if ($javafiles{'codebase'} ne '') {
 1837: 		$javafiles{'codebase'} .= '/';
 1838: 	    }  
 1839: 	    if (lc($tagname) eq 'applet' ||
 1840: 		lc($tagname) eq 'object' ||
 1841: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1842: 		) {
 1843: 		foreach my $item (keys(%javafiles)) {
 1844: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1845: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1846: 			&add_filetype($allfiles,$file,$item);
 1847: 		    }
 1848: 		}
 1849: 	    } 
 1850: 	    pop @state;
 1851: 	}
 1852:     }
 1853:     return 'ok';
 1854: }
 1855: 
 1856: sub add_filetype {
 1857:     my ($allfiles,$file,$type)=@_;
 1858:     if (exists($allfiles->{$file})) {
 1859: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1860: 	    push(@{$allfiles->{$file}}, &escape($type));
 1861: 	}
 1862:     } else {
 1863: 	@{$allfiles->{$file}} = (&escape($type));
 1864:     }
 1865: }
 1866: 
 1867: sub removeuploadedurl {
 1868:     my ($url)=@_;
 1869:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1870:     return &removeuserfile($uname,$udom,$fname);
 1871: }
 1872: 
 1873: sub removeuserfile {
 1874:     my ($docuname,$docudom,$fname)=@_;
 1875:     my $home=&homeserver($docuname,$docudom);
 1876:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1877:     if ($result eq 'ok') {
 1878:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1879:             my $metafile = $fname.'.meta';
 1880:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1881: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1882:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1883:             my $sqlresult = 
 1884:                 &update_portfolio_table($docuname,$docudom,$file,
 1885:                                         'portfolio_metadata',$group,
 1886:                                         'delete');
 1887:         }
 1888:     }
 1889:     return $result;
 1890: }
 1891: 
 1892: sub mkdiruserfile {
 1893:     my ($docuname,$docudom,$dir)=@_;
 1894:     my $home=&homeserver($docuname,$docudom);
 1895:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1896: }
 1897: 
 1898: sub renameuserfile {
 1899:     my ($docuname,$docudom,$old,$new)=@_;
 1900:     my $home=&homeserver($docuname,$docudom);
 1901:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1902:                         &escape("$old").':'.&escape("$new"),$home);
 1903:     if ($result eq 'ok') {
 1904:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1905:             my $oldmeta = $old.'.meta';
 1906:             my $newmeta = $new.'.meta';
 1907:             my $metaresult = 
 1908:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1909: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1910:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1911:             my $sqlresult = 
 1912:                 &update_portfolio_table($docuname,$docudom,$file,
 1913:                                         'portfolio_metadata',$group,
 1914:                                         'delete');
 1915:         }
 1916:     }
 1917:     return $result;
 1918: }
 1919: 
 1920: # ------------------------------------------------------------------------- Log
 1921: 
 1922: sub log {
 1923:     my ($dom,$nam,$hom,$what)=@_;
 1924:     return critical("log:$dom:$nam:$what",$hom);
 1925: }
 1926: 
 1927: # ------------------------------------------------------------------ Course Log
 1928: #
 1929: # This routine flushes several buffers of non-mission-critical nature
 1930: #
 1931: 
 1932: sub flushcourselogs {
 1933:     &logthis('Flushing log buffers');
 1934: #
 1935: # course logs
 1936: # This is a log of all transactions in a course, which can be used
 1937: # for data mining purposes
 1938: #
 1939: # It also collects the courseid database, which lists last transaction
 1940: # times and course titles for all courseids
 1941: #
 1942:     my %courseidbuffer=();
 1943:     foreach my $crsid (keys %courselogs) {
 1944:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1945: 		          &escape($courselogs{$crsid}),
 1946: 		          $coursehombuf{$crsid}) eq 'ok') {
 1947: 	    delete $courselogs{$crsid};
 1948:         } else {
 1949:             &logthis('Failed to flush log buffer for '.$crsid);
 1950:             if (length($courselogs{$crsid})>40000) {
 1951:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1952:                         " exceeded maximum size, deleting.</font>");
 1953:                delete $courselogs{$crsid};
 1954:             }
 1955:         }
 1956:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1957:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1958: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1959:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1960:         } else {
 1961:            $courseidbuffer{$coursehombuf{$crsid}}=
 1962: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1963:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1964:         }
 1965:     }
 1966: #
 1967: # Write course id database (reverse lookup) to homeserver of courses 
 1968: # Is used in pickcourse
 1969: #
 1970:     foreach my $crs_home (keys(%courseidbuffer)) {
 1971:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1972: 		     $crs_home);
 1973:     }
 1974: #
 1975: # File accesses
 1976: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1977: #
 1978:     foreach my $entry (keys(%accesshash)) {
 1979:         if ($entry =~ /___count$/) {
 1980:             my ($dom,$name);
 1981:             ($dom,$name,undef)=
 1982: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1983:             if (! defined($dom) || $dom eq '' || 
 1984:                 ! defined($name) || $name eq '') {
 1985:                 my $cid = $env{'request.course.id'};
 1986:                 $dom  = $env{'request.'.$cid.'.domain'};
 1987:                 $name = $env{'request.'.$cid.'.num'};
 1988:             }
 1989:             my $value = $accesshash{$entry};
 1990:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1991:             my %temphash=($url => $value);
 1992:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1993:             if ($result eq 'ok') {
 1994:                 delete $accesshash{$entry};
 1995:             } elsif ($result eq 'unknown_cmd') {
 1996:                 # Target server has old code running on it.
 1997:                 my %temphash=($entry => $value);
 1998:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1999:                     delete $accesshash{$entry};
 2000:                 }
 2001:             }
 2002:         } else {
 2003:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2004:             my %temphash=($entry => $accesshash{$entry});
 2005:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2006:                 delete $accesshash{$entry};
 2007:             }
 2008:         }
 2009:     }
 2010: #
 2011: # Roles
 2012: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2013: #
 2014:     foreach my $entry (keys(%userrolehash)) {
 2015:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2016: 	    split(/\:/,$entry);
 2017:         if (&Apache::lonnet::put('nohist_userroles',
 2018:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2019:                 $rudom,$runame) eq 'ok') {
 2020: 	    delete $userrolehash{$entry};
 2021:         }
 2022:     }
 2023: #
 2024: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2025: #
 2026:     my %domrolebuffer = ();
 2027:     foreach my $entry (keys %domainrolehash) {
 2028:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 2029:         if ($domrolebuffer{$rudom}) {
 2030:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2031:                       '='.&escape($domainrolehash{$entry});
 2032:         } else {
 2033:             $domrolebuffer{$rudom}.=&escape($entry).
 2034:                       '='.&escape($domainrolehash{$entry});
 2035:         }
 2036:         delete $domainrolehash{$entry};
 2037:     }
 2038:     foreach my $dom (keys(%domrolebuffer)) {
 2039: 	my %servers = &get_servers($dom,'library');
 2040: 	foreach my $tryserver (keys(%servers)) {
 2041: 	    unless (&reply('domroleput:'.$dom.':'.
 2042: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2043: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2044: 	    }
 2045:         }
 2046:     }
 2047:     $dumpcount++;
 2048: }
 2049: 
 2050: sub courselog {
 2051:     my $what=shift;
 2052:     $what=time.':'.$what;
 2053:     unless ($env{'request.course.id'}) { return ''; }
 2054:     $coursedombuf{$env{'request.course.id'}}=
 2055:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2056:     $coursenumbuf{$env{'request.course.id'}}=
 2057:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2058:     $coursehombuf{$env{'request.course.id'}}=
 2059:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2060:     $coursedescrbuf{$env{'request.course.id'}}=
 2061:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2062:     $courseinstcodebuf{$env{'request.course.id'}}=
 2063:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2064:     $courseownerbuf{$env{'request.course.id'}}=
 2065:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2066:     $coursetypebuf{$env{'request.course.id'}}=
 2067:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2068:     if (defined $courselogs{$env{'request.course.id'}}) {
 2069: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2070:     } else {
 2071: 	$courselogs{$env{'request.course.id'}}.=$what;
 2072:     }
 2073:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2074: 	&flushcourselogs();
 2075:     }
 2076: }
 2077: 
 2078: sub courseacclog {
 2079:     my $fnsymb=shift;
 2080:     unless ($env{'request.course.id'}) { return ''; }
 2081:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2082:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2083:         $what.=':POST';
 2084:         # FIXME: Probably ought to escape things....
 2085: 	foreach my $key (keys(%env)) {
 2086:             if ($key=~/^form\.(.*)/) {
 2087: 		$what.=':'.$1.'='.$env{$key};
 2088:             }
 2089:         }
 2090:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2091:         # FIXME: We should not be depending on a form parameter that someone
 2092:         # editing lonsearchcat.pm might change in the future.
 2093:         if ($env{'form.phase'} eq 'course_search') {
 2094:             $what.= ':POST';
 2095:             # FIXME: Probably ought to escape things....
 2096:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2097:                                  'crsdiscuss') {
 2098:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2099:             }
 2100:         }
 2101:     }
 2102:     &courselog($what);
 2103: }
 2104: 
 2105: sub countacc {
 2106:     my $url=&declutter(shift);
 2107:     return if (! defined($url) || $url eq '');
 2108:     unless ($env{'request.course.id'}) { return ''; }
 2109:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2110:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2111:     $accesshash{$key}++;
 2112: }
 2113: 
 2114: sub linklog {
 2115:     my ($from,$to)=@_;
 2116:     $from=&declutter($from);
 2117:     $to=&declutter($to);
 2118:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2119:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2120: }
 2121:   
 2122: sub userrolelog {
 2123:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2124:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2125:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2126:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2127:         ($trole=~/^ta/)) {
 2128:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2129:        $userrolehash
 2130:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2131:                     =$tend.':'.$tstart;
 2132:     }
 2133:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2134:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2135:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2136:         ($trole=~/^sc/)) {
 2137:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2138:        $domainrolehash
 2139:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2140:                     = $tend.':'.$tstart;
 2141:     }
 2142: }
 2143: 
 2144: sub get_course_adv_roles {
 2145:     my $cid=shift;
 2146:     $cid=$env{'request.course.id'} unless (defined($cid));
 2147:     my %coursehash=&coursedescription($cid);
 2148:     my %nothide=();
 2149:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2150: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2151:     }
 2152:     my %returnhash=();
 2153:     my %dumphash=
 2154:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2155:     my $now=time;
 2156:     foreach my $entry (keys %dumphash) {
 2157: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2158:         if (($tstart) && ($tstart<0)) { next; }
 2159:         if (($tend) && ($tend<$now)) { next; }
 2160:         if (($tstart) && ($now<$tstart)) { next; }
 2161:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2162: 	if ($username eq '' || $domain eq '') { next; }
 2163: 	if ((&privileged($username,$domain)) && 
 2164: 	    (!$nothide{$username.':'.$domain})) { next; }
 2165: 	if ($role eq 'cr') { next; }
 2166:         my $key=&plaintext($role);
 2167:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2168:         if ($returnhash{$key}) {
 2169: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2170:         } else {
 2171:             $returnhash{$key}=$username.':'.$domain;
 2172:         }
 2173:      }
 2174:     return %returnhash;
 2175: }
 2176: 
 2177: sub get_my_roles {
 2178:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2179:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2180:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2181:     my %dumphash;
 2182:     if ($context eq 'userroles') { 
 2183:         %dumphash = &dump('roles',$udom,$uname);
 2184:     } else {
 2185:         %dumphash=
 2186:             &dump('nohist_userroles',$udom,$uname);
 2187:     }
 2188:     my %returnhash=();
 2189:     my $now=time;
 2190:     foreach my $entry (keys(%dumphash)) {
 2191: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2192:         if (($tstart) && ($tstart<0)) { next; }
 2193:         my $status = 'active';
 2194:         if (($tend) && ($tend<$now)) {
 2195:             $status = 'previous';
 2196:         } 
 2197:         if (($tstart) && ($now<$tstart)) {
 2198:             $status = 'future';
 2199:         }
 2200:         if (ref($types) eq 'ARRAY') {
 2201:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2202:                 next;
 2203:             } 
 2204:         } else {
 2205:             if ($status ne 'active') {
 2206:                 next;
 2207:             }
 2208:         }
 2209:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2210:         if (ref($roledoms) eq 'ARRAY') {
 2211:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2212:                 next;
 2213:             }
 2214:         }
 2215:         if (ref($roles) eq 'ARRAY') {
 2216:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2217:                 next;
 2218:             }
 2219:         } 
 2220: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2221:     }
 2222:     return %returnhash;
 2223: }
 2224: 
 2225: # ----------------------------------------------------- Frontpage Announcements
 2226: #
 2227: #
 2228: 
 2229: sub postannounce {
 2230:     my ($server,$text)=@_;
 2231:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2232:     unless ($text=~/\w/) { $text=''; }
 2233:     return &reply('setannounce:'.&escape($text),$server);
 2234: }
 2235: 
 2236: sub getannounce {
 2237: 
 2238:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2239: 	my $announcement='';
 2240: 	while (my $line = <$fh>) { $announcement .= $line; }
 2241: 	close($fh);
 2242: 	if ($announcement=~/\w/) { 
 2243: 	    return 
 2244:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2245:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2246: 	} else {
 2247: 	    return '';
 2248: 	}
 2249:     } else {
 2250: 	return '';
 2251:     }
 2252: }
 2253: 
 2254: # ---------------------------------------------------------- Course ID routines
 2255: # Deal with domain's nohist_courseid.db files
 2256: #
 2257: 
 2258: sub courseidput {
 2259:     my ($domain,$what,$coursehome)=@_;
 2260:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2261: }
 2262: 
 2263: sub courseiddump {
 2264:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2265:     my %returnhash=();
 2266:     unless ($domfilter) { $domfilter=''; }
 2267:     my %libserv = &all_library();
 2268:     foreach my $tryserver (keys(%libserv)) {
 2269:         if ( (  $hostidflag == 1 
 2270: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2271: 	     || (!defined($hostidflag)) ) {
 2272: 
 2273: 	    if ($domfilter eq ''
 2274: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2275: 	        foreach my $line (
 2276:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2277: 			       $sincefilter.':'.&escape($descfilter).':'.
 2278:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2279:                                $tryserver))) {
 2280: 		    my ($key,$value)=split(/\=/,$line,2);
 2281:                     if (($key) && ($value)) {
 2282: 		        $returnhash{&unescape($key)}=$value;
 2283:                     }
 2284:                 }
 2285:             }
 2286:         }
 2287:     }
 2288:     return %returnhash;
 2289: }
 2290: 
 2291: # ---------------------------------------------------------- DC e-mail
 2292: 
 2293: sub dcmailput {
 2294:     my ($domain,$msgid,$message,$server)=@_;
 2295:     my $status = &Apache::lonnet::critical(
 2296:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2297:        &escape($message),$server);
 2298:     return $status;
 2299: }
 2300: 
 2301: sub dcmaildump {
 2302:     my ($dom,$startdate,$enddate,$senders) = @_;
 2303:     my %returnhash=();
 2304: 
 2305:     if (defined(&domain($dom,'primary'))) {
 2306:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2307:                                                          &escape($enddate).':';
 2308: 	my @esc_senders=map { &escape($_)} @$senders;
 2309: 	$cmd.=&escape(join('&',@esc_senders));
 2310: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2311:             my ($key,$value) = split(/\=/,$line,2);
 2312:             if (($key) && ($value)) {
 2313:                 $returnhash{&unescape($key)} = &unescape($value);
 2314:             }
 2315:         }
 2316:     }
 2317:     return %returnhash;
 2318: }
 2319: # ---------------------------------------------------------- Domain roles
 2320: 
 2321: sub get_domain_roles {
 2322:     my ($dom,$roles,$startdate,$enddate)=@_;
 2323:     if (undef($startdate) || $startdate eq '') {
 2324:         $startdate = '.';
 2325:     }
 2326:     if (undef($enddate) || $enddate eq '') {
 2327:         $enddate = '.';
 2328:     }
 2329:     my $rolelist = join(':',@{$roles});
 2330:     my %personnel = ();
 2331: 
 2332:     my %servers = &get_servers($dom,'library');
 2333:     foreach my $tryserver (keys(%servers)) {
 2334: 	%{$personnel{$tryserver}}=();
 2335: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2336: 					    &escape($startdate).':'.
 2337: 					    &escape($enddate).':'.
 2338: 					    &escape($rolelist), $tryserver))) {
 2339: 	    my ($key,$value) = split(/\=/,$line,2);
 2340: 	    if (($key) && ($value)) {
 2341: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2342: 	    }
 2343: 	}
 2344:     }
 2345:     return %personnel;
 2346: }
 2347: 
 2348: # ----------------------------------------------------------- Check out an item
 2349: 
 2350: sub get_first_access {
 2351:     my ($type,$argsymb)=@_;
 2352:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2353:     if ($argsymb) { $symb=$argsymb; }
 2354:     my ($map,$id,$res)=&decode_symb($symb);
 2355:     if ($type eq 'map') {
 2356: 	$res=&symbread($map);
 2357:     } else {
 2358: 	$res=$symb;
 2359:     }
 2360:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2361:     return $times{"$courseid\0$res"};
 2362: }
 2363: 
 2364: sub set_first_access {
 2365:     my ($type)=@_;
 2366:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2367:     my ($map,$id,$res)=&decode_symb($symb);
 2368:     if ($type eq 'map') {
 2369: 	$res=&symbread($map);
 2370:     } else {
 2371: 	$res=$symb;
 2372:     }
 2373:     my $firstaccess=&get_first_access($type,$symb);
 2374:     if (!$firstaccess) {
 2375: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2376:     }
 2377:     return 'already_set';
 2378: }
 2379: 
 2380: sub checkout {
 2381:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2382:     my $now=time;
 2383:     my $lonhost=$perlvar{'lonHostID'};
 2384:     my $infostr=&escape(
 2385:                  'CHECKOUTTOKEN&'.
 2386:                  $tuname.'&'.
 2387:                  $tudom.'&'.
 2388:                  $tcrsid.'&'.
 2389:                  $symb.'&'.
 2390: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2391:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2392:     if ($token=~/^error\:/) { 
 2393:         &logthis("<font color=\"blue\">WARNING: ".
 2394:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2395:                  "</font>");
 2396:         return ''; 
 2397:     }
 2398: 
 2399:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2400:     $token=~tr/a-z/A-Z/;
 2401: 
 2402:     my %infohash=('resource.0.outtoken' => $token,
 2403:                   'resource.0.checkouttime' => $now,
 2404:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2405: 
 2406:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2407:        return '';
 2408:     } else {
 2409:         &logthis("<font color=\"blue\">WARNING: ".
 2410:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2411:                  "</font>");
 2412:     }    
 2413: 
 2414:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2415:                          &escape('Checkout '.$infostr.' - '.
 2416:                                                  $token)) ne 'ok') {
 2417: 	return '';
 2418:     } else {
 2419:         &logthis("<font color=\"blue\">WARNING: ".
 2420:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2421:                  "</font>");
 2422:     }
 2423:     return $token;
 2424: }
 2425: 
 2426: # ------------------------------------------------------------ Check in an item
 2427: 
 2428: sub checkin {
 2429:     my $token=shift;
 2430:     my $now=time;
 2431:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2432:     $lonhost=~tr/A-Z/a-z/;
 2433:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2434:     $dtoken=~s/\W/\_/g;
 2435:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2436:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2437: 
 2438:     unless (($tuname) && ($tudom)) {
 2439:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2440:         return '';
 2441:     }
 2442:     
 2443:     unless (&allowed('mgr',$tcrsid)) {
 2444:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2445:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2446:         return '';
 2447:     }
 2448: 
 2449:     my %infohash=('resource.0.intoken' => $token,
 2450:                   'resource.0.checkintime' => $now,
 2451:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2452: 
 2453:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2454:        return '';
 2455:     }    
 2456: 
 2457:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2458:                          &escape('Checkin - '.$token)) ne 'ok') {
 2459: 	return '';
 2460:     }
 2461: 
 2462:     return ($symb,$tuname,$tudom,$tcrsid);    
 2463: }
 2464: 
 2465: # --------------------------------------------- Set Expire Date for Spreadsheet
 2466: 
 2467: sub expirespread {
 2468:     my ($uname,$udom,$stype,$usymb)=@_;
 2469:     my $cid=$env{'request.course.id'}; 
 2470:     if ($cid) {
 2471:        my $now=time;
 2472:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2473:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2474:                             $env{'course.'.$cid.'.num'}.
 2475: 	        	    ':nohist_expirationdates:'.
 2476:                             &escape($key).'='.$now,
 2477:                             $env{'course.'.$cid.'.home'})
 2478:     }
 2479:     return 'ok';
 2480: }
 2481: 
 2482: # ----------------------------------------------------- Devalidate Spreadsheets
 2483: 
 2484: sub devalidate {
 2485:     my ($symb,$uname,$udom)=@_;
 2486:     my $cid=$env{'request.course.id'}; 
 2487:     if ($cid) {
 2488:         # delete the stored spreadsheets for
 2489:         # - the student level sheet of this user in course's homespace
 2490:         # - the assessment level sheet for this resource 
 2491:         #   for this user in user's homespace
 2492: 	# - current conditional state info
 2493: 	my $key=$uname.':'.$udom.':';
 2494:         my $status=
 2495: 	    &del('nohist_calculatedsheets',
 2496: 		 [$key.'studentcalc:'],
 2497: 		 $env{'course.'.$cid.'.domain'},
 2498: 		 $env{'course.'.$cid.'.num'})
 2499: 		.' '.
 2500: 	    &del('nohist_calculatedsheets_'.$cid,
 2501: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2502:         unless ($status eq 'ok ok') {
 2503:            &logthis('Could not devalidate spreadsheet '.
 2504:                     $uname.' at '.$udom.' for '.
 2505: 		    $symb.': '.$status);
 2506:         }
 2507: 	&delenv('user.state.'.$cid);
 2508:     }
 2509: }
 2510: 
 2511: sub get_scalar {
 2512:     my ($string,$end) = @_;
 2513:     my $value;
 2514:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2515: 	$value = $1;
 2516:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2517: 	$value = $1;
 2518:     }
 2519:     return &unescape($value);
 2520: }
 2521: 
 2522: sub array2str {
 2523:   my (@array) = @_;
 2524:   my $result=&arrayref2str(\@array);
 2525:   $result=~s/^__ARRAY_REF__//;
 2526:   $result=~s/__END_ARRAY_REF__$//;
 2527:   return $result;
 2528: }
 2529: 
 2530: sub arrayref2str {
 2531:   my ($arrayref) = @_;
 2532:   my $result='__ARRAY_REF__';
 2533:   foreach my $elem (@$arrayref) {
 2534:     if(ref($elem) eq 'ARRAY') {
 2535:       $result.=&arrayref2str($elem).'&';
 2536:     } elsif(ref($elem) eq 'HASH') {
 2537:       $result.=&hashref2str($elem).'&';
 2538:     } elsif(ref($elem)) {
 2539:       #print("Got a ref of ".(ref($elem))." skipping.");
 2540:     } else {
 2541:       $result.=&escape($elem).'&';
 2542:     }
 2543:   }
 2544:   $result=~s/\&$//;
 2545:   $result .= '__END_ARRAY_REF__';
 2546:   return $result;
 2547: }
 2548: 
 2549: sub hash2str {
 2550:   my (%hash) = @_;
 2551:   my $result=&hashref2str(\%hash);
 2552:   $result=~s/^__HASH_REF__//;
 2553:   $result=~s/__END_HASH_REF__$//;
 2554:   return $result;
 2555: }
 2556: 
 2557: sub hashref2str {
 2558:   my ($hashref)=@_;
 2559:   my $result='__HASH_REF__';
 2560:   foreach my $key (sort(keys(%$hashref))) {
 2561:     if (ref($key) eq 'ARRAY') {
 2562:       $result.=&arrayref2str($key).'=';
 2563:     } elsif (ref($key) eq 'HASH') {
 2564:       $result.=&hashref2str($key).'=';
 2565:     } elsif (ref($key)) {
 2566:       $result.='=';
 2567:       #print("Got a ref of ".(ref($key))." skipping.");
 2568:     } else {
 2569: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2570:     }
 2571: 
 2572:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2573:       $result.=&arrayref2str($hashref->{$key}).'&';
 2574:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2575:       $result.=&hashref2str($hashref->{$key}).'&';
 2576:     } elsif(ref($hashref->{$key})) {
 2577:        $result.='&';
 2578:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2579:     } else {
 2580:       $result.=&escape($hashref->{$key}).'&';
 2581:     }
 2582:   }
 2583:   $result=~s/\&$//;
 2584:   $result .= '__END_HASH_REF__';
 2585:   return $result;
 2586: }
 2587: 
 2588: sub str2hash {
 2589:     my ($string)=@_;
 2590:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2591:     return %$hash;
 2592: }
 2593: 
 2594: sub str2hashref {
 2595:   my ($string) = @_;
 2596: 
 2597:   my %hash;
 2598: 
 2599:   if($string !~ /^__HASH_REF__/) {
 2600:       if (! ($string eq '' || !defined($string))) {
 2601: 	  $hash{'error'}='Not hash reference';
 2602:       }
 2603:       return (\%hash, $string);
 2604:   }
 2605: 
 2606:   $string =~ s/^__HASH_REF__//;
 2607: 
 2608:   while($string !~ /^__END_HASH_REF__/) {
 2609:       #key
 2610:       my $key='';
 2611:       if($string =~ /^__HASH_REF__/) {
 2612:           ($key, $string)=&str2hashref($string);
 2613:           if(defined($key->{'error'})) {
 2614:               $hash{'error'}='Bad data';
 2615:               return (\%hash, $string);
 2616:           }
 2617:       } elsif($string =~ /^__ARRAY_REF__/) {
 2618:           ($key, $string)=&str2arrayref($string);
 2619:           if($key->[0] eq 'Array reference error') {
 2620:               $hash{'error'}='Bad data';
 2621:               return (\%hash, $string);
 2622:           }
 2623:       } else {
 2624:           $string =~ s/^(.*?)=//;
 2625: 	  $key=&unescape($1);
 2626:       }
 2627:       $string =~ s/^=//;
 2628: 
 2629:       #value
 2630:       my $value='';
 2631:       if($string =~ /^__HASH_REF__/) {
 2632:           ($value, $string)=&str2hashref($string);
 2633:           if(defined($value->{'error'})) {
 2634:               $hash{'error'}='Bad data';
 2635:               return (\%hash, $string);
 2636:           }
 2637:       } elsif($string =~ /^__ARRAY_REF__/) {
 2638:           ($value, $string)=&str2arrayref($string);
 2639:           if($value->[0] eq 'Array reference error') {
 2640:               $hash{'error'}='Bad data';
 2641:               return (\%hash, $string);
 2642:           }
 2643:       } else {
 2644: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2645:       }
 2646:       $string =~ s/^&//;
 2647: 
 2648:       $hash{$key}=$value;
 2649:   }
 2650: 
 2651:   $string =~ s/^__END_HASH_REF__//;
 2652: 
 2653:   return (\%hash, $string);
 2654: }
 2655: 
 2656: sub str2array {
 2657:     my ($string)=@_;
 2658:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2659:     return @$array;
 2660: }
 2661: 
 2662: sub str2arrayref {
 2663:   my ($string) = @_;
 2664:   my @array;
 2665: 
 2666:   if($string !~ /^__ARRAY_REF__/) {
 2667:       if (! ($string eq '' || !defined($string))) {
 2668: 	  $array[0]='Array reference error';
 2669:       }
 2670:       return (\@array, $string);
 2671:   }
 2672: 
 2673:   $string =~ s/^__ARRAY_REF__//;
 2674: 
 2675:   while($string !~ /^__END_ARRAY_REF__/) {
 2676:       my $value='';
 2677:       if($string =~ /^__HASH_REF__/) {
 2678:           ($value, $string)=&str2hashref($string);
 2679:           if(defined($value->{'error'})) {
 2680:               $array[0] ='Array reference error';
 2681:               return (\@array, $string);
 2682:           }
 2683:       } elsif($string =~ /^__ARRAY_REF__/) {
 2684:           ($value, $string)=&str2arrayref($string);
 2685:           if($value->[0] eq 'Array reference error') {
 2686:               $array[0] ='Array reference error';
 2687:               return (\@array, $string);
 2688:           }
 2689:       } else {
 2690: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2691:       }
 2692:       $string =~ s/^&//;
 2693: 
 2694:       push(@array, $value);
 2695:   }
 2696: 
 2697:   $string =~ s/^__END_ARRAY_REF__//;
 2698: 
 2699:   return (\@array, $string);
 2700: }
 2701: 
 2702: # -------------------------------------------------------------------Temp Store
 2703: 
 2704: sub tmpreset {
 2705:   my ($symb,$namespace,$domain,$stuname) = @_;
 2706:   if (!$symb) {
 2707:     $symb=&symbread();
 2708:     if (!$symb) { $symb= $env{'request.url'}; }
 2709:   }
 2710:   $symb=escape($symb);
 2711: 
 2712:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2713:   $namespace=~s/\//\_/g;
 2714:   $namespace=~s/\W//g;
 2715: 
 2716:   if (!$domain) { $domain=$env{'user.domain'}; }
 2717:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2718:   if ($domain eq 'public' && $stuname eq 'public') {
 2719:       $stuname=$ENV{'REMOTE_ADDR'};
 2720:   }
 2721:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2722:   my %hash;
 2723:   if (tie(%hash,'GDBM_File',
 2724: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2725: 	  &GDBM_WRCREAT(),0640)) {
 2726:     foreach my $key (keys %hash) {
 2727:       if ($key=~ /:$symb/) {
 2728: 	delete($hash{$key});
 2729:       }
 2730:     }
 2731:   }
 2732: }
 2733: 
 2734: sub tmpstore {
 2735:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2736: 
 2737:   if (!$symb) {
 2738:     $symb=&symbread();
 2739:     if (!$symb) { $symb= $env{'request.url'}; }
 2740:   }
 2741:   $symb=escape($symb);
 2742: 
 2743:   if (!$namespace) {
 2744:     # I don't think we would ever want to store this for a course.
 2745:     # it seems this will only be used if we don't have a course.
 2746:     #$namespace=$env{'request.course.id'};
 2747:     #if (!$namespace) {
 2748:       $namespace=$env{'request.state'};
 2749:     #}
 2750:   }
 2751:   $namespace=~s/\//\_/g;
 2752:   $namespace=~s/\W//g;
 2753:   if (!$domain) { $domain=$env{'user.domain'}; }
 2754:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2755:   if ($domain eq 'public' && $stuname eq 'public') {
 2756:       $stuname=$ENV{'REMOTE_ADDR'};
 2757:   }
 2758:   my $now=time;
 2759:   my %hash;
 2760:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2761:   if (tie(%hash,'GDBM_File',
 2762: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2763: 	  &GDBM_WRCREAT(),0640)) {
 2764:     $hash{"version:$symb"}++;
 2765:     my $version=$hash{"version:$symb"};
 2766:     my $allkeys=''; 
 2767:     foreach my $key (keys(%$storehash)) {
 2768:       $allkeys.=$key.':';
 2769:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2770:     }
 2771:     $hash{"$version:$symb:timestamp"}=$now;
 2772:     $allkeys.='timestamp';
 2773:     $hash{"$version:keys:$symb"}=$allkeys;
 2774:     if (untie(%hash)) {
 2775:       return 'ok';
 2776:     } else {
 2777:       return "error:$!";
 2778:     }
 2779:   } else {
 2780:     return "error:$!";
 2781:   }
 2782: }
 2783: 
 2784: # -----------------------------------------------------------------Temp Restore
 2785: 
 2786: sub tmprestore {
 2787:   my ($symb,$namespace,$domain,$stuname) = @_;
 2788: 
 2789:   if (!$symb) {
 2790:     $symb=&symbread();
 2791:     if (!$symb) { $symb= $env{'request.url'}; }
 2792:   }
 2793:   $symb=escape($symb);
 2794: 
 2795:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2796: 
 2797:   if (!$domain) { $domain=$env{'user.domain'}; }
 2798:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2799:   if ($domain eq 'public' && $stuname eq 'public') {
 2800:       $stuname=$ENV{'REMOTE_ADDR'};
 2801:   }
 2802:   my %returnhash;
 2803:   $namespace=~s/\//\_/g;
 2804:   $namespace=~s/\W//g;
 2805:   my %hash;
 2806:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2807:   if (tie(%hash,'GDBM_File',
 2808: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2809: 	  &GDBM_READER(),0640)) {
 2810:     my $version=$hash{"version:$symb"};
 2811:     $returnhash{'version'}=$version;
 2812:     my $scope;
 2813:     for ($scope=1;$scope<=$version;$scope++) {
 2814:       my $vkeys=$hash{"$scope:keys:$symb"};
 2815:       my @keys=split(/:/,$vkeys);
 2816:       my $key;
 2817:       $returnhash{"$scope:keys"}=$vkeys;
 2818:       foreach $key (@keys) {
 2819: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2820: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2821:       }
 2822:     }
 2823:     if (!(untie(%hash))) {
 2824:       return "error:$!";
 2825:     }
 2826:   } else {
 2827:     return "error:$!";
 2828:   }
 2829:   return %returnhash;
 2830: }
 2831: 
 2832: # ----------------------------------------------------------------------- Store
 2833: 
 2834: sub store {
 2835:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2836:     my $home='';
 2837: 
 2838:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2839: 
 2840:     $symb=&symbclean($symb);
 2841:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2842: 
 2843:     if (!$domain) { $domain=$env{'user.domain'}; }
 2844:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2845: 
 2846:     &devalidate($symb,$stuname,$domain);
 2847: 
 2848:     $symb=escape($symb);
 2849:     if (!$namespace) { 
 2850:        unless ($namespace=$env{'request.course.id'}) { 
 2851:           return ''; 
 2852:        } 
 2853:     }
 2854:     if (!$home) { $home=$env{'user.home'}; }
 2855: 
 2856:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2857:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2858: 
 2859:     my $namevalue='';
 2860:     foreach my $key (keys(%$storehash)) {
 2861:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2862:     }
 2863:     $namevalue=~s/\&$//;
 2864:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2865:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2866: }
 2867: 
 2868: # -------------------------------------------------------------- Critical Store
 2869: 
 2870: sub cstore {
 2871:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2872:     my $home='';
 2873: 
 2874:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2875: 
 2876:     $symb=&symbclean($symb);
 2877:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2878: 
 2879:     if (!$domain) { $domain=$env{'user.domain'}; }
 2880:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2881: 
 2882:     &devalidate($symb,$stuname,$domain);
 2883: 
 2884:     $symb=escape($symb);
 2885:     if (!$namespace) { 
 2886:        unless ($namespace=$env{'request.course.id'}) { 
 2887:           return ''; 
 2888:        } 
 2889:     }
 2890:     if (!$home) { $home=$env{'user.home'}; }
 2891: 
 2892:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2893:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2894: 
 2895:     my $namevalue='';
 2896:     foreach my $key (keys(%$storehash)) {
 2897:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2898:     }
 2899:     $namevalue=~s/\&$//;
 2900:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2901:     return critical
 2902:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2903: }
 2904: 
 2905: # --------------------------------------------------------------------- Restore
 2906: 
 2907: sub restore {
 2908:     my ($symb,$namespace,$domain,$stuname) = @_;
 2909:     my $home='';
 2910: 
 2911:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2912: 
 2913:     if (!$symb) {
 2914:       unless ($symb=escape(&symbread())) { return ''; }
 2915:     } else {
 2916:       $symb=&escape(&symbclean($symb));
 2917:     }
 2918:     if (!$namespace) { 
 2919:        unless ($namespace=$env{'request.course.id'}) { 
 2920:           return ''; 
 2921:        } 
 2922:     }
 2923:     if (!$domain) { $domain=$env{'user.domain'}; }
 2924:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2925:     if (!$home) { $home=$env{'user.home'}; }
 2926:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2927: 
 2928:     my %returnhash=();
 2929:     foreach my $line (split(/\&/,$answer)) {
 2930: 	my ($name,$value)=split(/\=/,$line);
 2931:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2932:     }
 2933:     my $version;
 2934:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2935:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2936:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2937:        }
 2938:     }
 2939:     return %returnhash;
 2940: }
 2941: 
 2942: # ---------------------------------------------------------- Course Description
 2943: 
 2944: sub coursedescription {
 2945:     my ($courseid,$args)=@_;
 2946:     $courseid=~s/^\///;
 2947:     $courseid=~s/\_/\//g;
 2948:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2949:     my $chome=&homeserver($cnum,$cdomain);
 2950:     my $normalid=$cdomain.'_'.$cnum;
 2951:     # need to always cache even if we get errors otherwise we keep 
 2952:     # trying and trying and trying to get the course description.
 2953:     my %envhash=();
 2954:     my %returnhash=();
 2955:     
 2956:     my $expiretime=600;
 2957:     if ($env{'request.course.id'} eq $normalid) {
 2958: 	$expiretime=120;
 2959:     }
 2960: 
 2961:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2962:     if (!$args->{'freshen_cache'}
 2963: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2964: 	foreach my $key (keys(%env)) {
 2965: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2966: 	    my ($setting) = $1;
 2967: 	    $returnhash{$setting} = $env{$key};
 2968: 	}
 2969: 	return %returnhash;
 2970:     }
 2971: 
 2972:     # get the data agin
 2973:     if (!$args->{'one_time'}) {
 2974: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2975:     }
 2976: 
 2977:     if ($chome ne 'no_host') {
 2978:        %returnhash=&dump('environment',$cdomain,$cnum);
 2979:        if (!exists($returnhash{'con_lost'})) {
 2980:            $returnhash{'home'}= $chome;
 2981: 	   $returnhash{'domain'} = $cdomain;
 2982: 	   $returnhash{'num'} = $cnum;
 2983:            if (!defined($returnhash{'type'})) {
 2984:                $returnhash{'type'} = 'Course';
 2985:            }
 2986:            while (my ($name,$value) = each %returnhash) {
 2987:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2988:            }
 2989:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2990:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2991: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2992:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2993:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2994:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2995:        }
 2996:     }
 2997:     if (!$args->{'one_time'}) {
 2998: 	&appenv(%envhash);
 2999:     }
 3000:     return %returnhash;
 3001: }
 3002: 
 3003: # -------------------------------------------------See if a user is privileged
 3004: 
 3005: sub privileged {
 3006:     my ($username,$domain)=@_;
 3007:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3008: 			&homeserver($username,$domain));
 3009:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3010:     my $now=time;
 3011:     if ($rolesdump ne '') {
 3012:         foreach my $entry (split(/&/,$rolesdump)) {
 3013: 	    if ($entry!~/^rolesdef_/) {
 3014: 		my ($area,$role)=split(/=/,$entry);
 3015: 		$area=~s/\_\w\w$//;
 3016: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3017: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3018: 		    my $active=1;
 3019: 		    if ($tend) {
 3020: 			if ($tend<$now) { $active=0; }
 3021: 		    }
 3022: 		    if ($tstart) {
 3023: 			if ($tstart>$now) { $active=0; }
 3024: 		    }
 3025: 		    if ($active) { return 1; }
 3026: 		}
 3027: 	    }
 3028: 	}
 3029:     }
 3030:     return 0;
 3031: }
 3032: 
 3033: # -------------------------------------------------------- Get user privileges
 3034: 
 3035: sub rolesinit {
 3036:     my ($domain,$username,$authhost)=@_;
 3037:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3038:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3039:     my %allroles=();
 3040:     my %allgroups=();   
 3041:     my $now=time;
 3042:     my %userroles = ('user.login.time' => $now);
 3043:     my $group_privs;
 3044: 
 3045:     if ($rolesdump ne '') {
 3046:         foreach my $entry (split(/&/,$rolesdump)) {
 3047: 	  if ($entry!~/^rolesdef_/) {
 3048:             my ($area,$role)=split(/=/,$entry);
 3049: 	    $area=~s/\_\w\w$//;
 3050:             my ($trole,$tend,$tstart,$group_privs);
 3051: 	    if ($role=~/^cr/) { 
 3052: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3053: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3054: 		    ($tend,$tstart)=split('_',$trest);
 3055: 		} else {
 3056: 		    $trole=$role;
 3057: 		}
 3058:             } elsif ($role =~ m|^gr/|) {
 3059:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3060:                 ($trole,$group_privs) = split(/\//,$trole);
 3061:                 $group_privs = &unescape($group_privs);
 3062: 	    } else {
 3063: 		($trole,$tend,$tstart)=split(/_/,$role);
 3064: 	    }
 3065: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3066: 					 $username);
 3067: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3068:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3069:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3070:             if (($area ne '') && ($trole ne '')) {
 3071: 		my $spec=$trole.'.'.$area;
 3072: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3073: 		if ($trole =~ /^cr\//) {
 3074:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3075:                 } elsif ($trole eq 'gr') {
 3076:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3077: 		} else {
 3078:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3079: 		}
 3080:             }
 3081:           }
 3082:         }
 3083:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3084:         $userroles{'user.adv'}    = $adv;
 3085: 	$userroles{'user.author'} = $author;
 3086:         $env{'user.adv'}=$adv;
 3087:     }
 3088:     return \%userroles;  
 3089: }
 3090: 
 3091: sub set_arearole {
 3092:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3093: # log the associated role with the area
 3094:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3095:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3096: }
 3097: 
 3098: sub custom_roleprivs {
 3099:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3100:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3101:     my $homsvr=homeserver($rauthor,$rdomain);
 3102:     if (&hostname($homsvr) ne '') {
 3103:         my ($rdummy,$roledef)=
 3104:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3105:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3106:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3107:             if (defined($syspriv)) {
 3108:                 $$allroles{'cm./'}.=':'.$syspriv;
 3109:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3110:             }
 3111:             if ($tdomain ne '') {
 3112:                 if (defined($dompriv)) {
 3113:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3114:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3115:                 }
 3116:                 if (($trest ne '') && (defined($coursepriv))) {
 3117:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3118:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3119:                 }
 3120:             }
 3121:         }
 3122:     }
 3123: }
 3124: 
 3125: sub group_roleprivs {
 3126:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3127:     my $access = 1;
 3128:     my $now = time;
 3129:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3130:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3131:     if ($access) {
 3132:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3133:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3134:     }
 3135: }
 3136: 
 3137: sub standard_roleprivs {
 3138:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3139:     if (defined($pr{$trole.':s'})) {
 3140:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3141:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3142:     }
 3143:     if ($tdomain ne '') {
 3144:         if (defined($pr{$trole.':d'})) {
 3145:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3146:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3147:         }
 3148:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3149:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3150:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3151:         }
 3152:     }
 3153: }
 3154: 
 3155: sub set_userprivs {
 3156:     my ($userroles,$allroles,$allgroups) = @_; 
 3157:     my $author=0;
 3158:     my $adv=0;
 3159:     my %grouproles = ();
 3160:     if (keys(%{$allgroups}) > 0) {
 3161:         foreach my $role (keys %{$allroles}) {
 3162:             my ($trole,$area,$sec,$extendedarea);
 3163:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3164:                 $trole = $1;
 3165:                 $area = $2;
 3166:                 $sec = $3;
 3167:                 $extendedarea = $area.$sec;
 3168:                 if (exists($$allgroups{$area})) {
 3169:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3170:                         my $spec = $trole.'.'.$extendedarea;
 3171:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3172:                                                 $$allgroups{$area}{$group};
 3173:                     }
 3174:                 }
 3175:             }
 3176:         }
 3177:     }
 3178:     foreach my $group (keys(%grouproles)) {
 3179:         $$allroles{$group} = $grouproles{$group};
 3180:     }
 3181:     foreach my $role (keys(%{$allroles})) {
 3182:         my %thesepriv;
 3183:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3184:         foreach my $item (split(/:/,$$allroles{$role})) {
 3185:             if ($item ne '') {
 3186:                 my ($privilege,$restrictions)=split(/&/,$item);
 3187:                 if ($restrictions eq '') {
 3188:                     $thesepriv{$privilege}='F';
 3189:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3190:                     $thesepriv{$privilege}.=$restrictions;
 3191:                 }
 3192:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3193:             }
 3194:         }
 3195:         my $thesestr='';
 3196:         foreach my $priv (keys(%thesepriv)) {
 3197: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3198: 	}
 3199:         $userroles->{'user.priv.'.$role} = $thesestr;
 3200:     }
 3201:     return ($author,$adv);
 3202: }
 3203: 
 3204: # --------------------------------------------------------------- get interface
 3205: 
 3206: sub get {
 3207:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3208:    my $items='';
 3209:    foreach my $item (@$storearr) {
 3210:        $items.=&escape($item).'&';
 3211:    }
 3212:    $items=~s/\&$//;
 3213:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3214:    if (!$uname) { $uname=$env{'user.name'}; }
 3215:    my $uhome=&homeserver($uname,$udomain);
 3216: 
 3217:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3218:    my @pairs=split(/\&/,$rep);
 3219:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3220:      return @pairs;
 3221:    }
 3222:    my %returnhash=();
 3223:    my $i=0;
 3224:    foreach my $item (@$storearr) {
 3225:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3226:       $i++;
 3227:    }
 3228:    return %returnhash;
 3229: }
 3230: 
 3231: # --------------------------------------------------------------- del interface
 3232: 
 3233: sub del {
 3234:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3235:    my $items='';
 3236:    foreach my $item (@$storearr) {
 3237:        $items.=&escape($item).'&';
 3238:    }
 3239:    $items=~s/\&$//;
 3240:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3241:    if (!$uname) { $uname=$env{'user.name'}; }
 3242:    my $uhome=&homeserver($uname,$udomain);
 3243: 
 3244:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3245: }
 3246: 
 3247: # -------------------------------------------------------------- dump interface
 3248: 
 3249: sub dump {
 3250:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3251:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3252:     if (!$uname) { $uname=$env{'user.name'}; }
 3253:     my $uhome=&homeserver($uname,$udomain);
 3254:     if ($regexp) {
 3255: 	$regexp=&escape($regexp);
 3256:     } else {
 3257: 	$regexp='.';
 3258:     }
 3259:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3260:     my @pairs=split(/\&/,$rep);
 3261:     my %returnhash=();
 3262:     foreach my $item (@pairs) {
 3263: 	my ($key,$value)=split(/=/,$item,2);
 3264: 	$key = &unescape($key);
 3265: 	next if ($key =~ /^error: 2 /);
 3266: 	$returnhash{$key}=&thaw_unescape($value);
 3267:     }
 3268:     return %returnhash;
 3269: }
 3270: 
 3271: # --------------------------------------------------------- dumpstore interface
 3272: 
 3273: sub dumpstore {
 3274:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3275:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3276:    if (!$uname) { $uname=$env{'user.name'}; }
 3277:    my $uhome=&homeserver($uname,$udomain);
 3278:    if ($regexp) {
 3279:        $regexp=&escape($regexp);
 3280:    } else {
 3281:        $regexp='.';
 3282:    }
 3283:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3284:    my @pairs=split(/\&/,$rep);
 3285:    my %returnhash=();
 3286:    foreach my $item (@pairs) {
 3287:        my ($key,$value)=split(/=/,$item,2);
 3288:        next if ($key =~ /^error: 2 /);
 3289:        $returnhash{$key}=&thaw_unescape($value);
 3290:    }
 3291:    return %returnhash;
 3292: }
 3293: 
 3294: # -------------------------------------------------------------- keys interface
 3295: 
 3296: sub getkeys {
 3297:    my ($namespace,$udomain,$uname)=@_;
 3298:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3299:    if (!$uname) { $uname=$env{'user.name'}; }
 3300:    my $uhome=&homeserver($uname,$udomain);
 3301:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3302:    my @keyarray=();
 3303:    foreach my $key (split(/\&/,$rep)) {
 3304:       next if ($key =~ /^error: 2 /);
 3305:       push(@keyarray,&unescape($key));
 3306:    }
 3307:    return @keyarray;
 3308: }
 3309: 
 3310: # --------------------------------------------------------------- currentdump
 3311: sub currentdump {
 3312:    my ($courseid,$sdom,$sname)=@_;
 3313:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3314:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3315:    $sname    = $env{'user.name'}         if (! defined($sname));
 3316:    my $uhome = &homeserver($sname,$sdom);
 3317:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3318:    return if ($rep =~ /^(error:|no_such_host)/);
 3319:    #
 3320:    my %returnhash=();
 3321:    #
 3322:    if ($rep eq "unknown_cmd") { 
 3323:        # an old lond will not know currentdump
 3324:        # Do a dump and make it look like a currentdump
 3325:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3326:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3327:        my %hash = @tmp;
 3328:        @tmp=();
 3329:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3330:    } else {
 3331:        my @pairs=split(/\&/,$rep);
 3332:        foreach my $pair (@pairs) {
 3333:            my ($key,$value)=split(/=/,$pair,2);
 3334:            my ($symb,$param) = split(/:/,$key);
 3335:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3336:                                                         &thaw_unescape($value);
 3337:        }
 3338:    }
 3339:    return %returnhash;
 3340: }
 3341: 
 3342: sub convert_dump_to_currentdump{
 3343:     my %hash = %{shift()};
 3344:     my %returnhash;
 3345:     # Code ripped from lond, essentially.  The only difference
 3346:     # here is the unescaping done by lonnet::dump().  Conceivably
 3347:     # we might run in to problems with parameter names =~ /^v\./
 3348:     while (my ($key,$value) = each(%hash)) {
 3349:         my ($v,$symb,$param) = split(/:/,$key);
 3350: 	$symb  = &unescape($symb);
 3351: 	$param = &unescape($param);
 3352:         next if ($v eq 'version' || $symb eq 'keys');
 3353:         next if (exists($returnhash{$symb}) &&
 3354:                  exists($returnhash{$symb}->{$param}) &&
 3355:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3356:         $returnhash{$symb}->{$param}=$value;
 3357:         $returnhash{$symb}->{'v.'.$param}=$v;
 3358:     }
 3359:     #
 3360:     # Remove all of the keys in the hashes which keep track of
 3361:     # the version of the parameter.
 3362:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3363:         # use a foreach because we are going to delete from the hash.
 3364:         foreach my $key (keys(%$param_hash)) {
 3365:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3366:         }
 3367:     }
 3368:     return \%returnhash;
 3369: }
 3370: 
 3371: # ------------------------------------------------------ critical inc interface
 3372: 
 3373: sub cinc {
 3374:     return &inc(@_,'critical');
 3375: }
 3376: 
 3377: # --------------------------------------------------------------- inc interface
 3378: 
 3379: sub inc {
 3380:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3381:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3382:     if (!$uname) { $uname=$env{'user.name'}; }
 3383:     my $uhome=&homeserver($uname,$udomain);
 3384:     my $items='';
 3385:     if (! ref($store)) {
 3386:         # got a single value, so use that instead
 3387:         $items = &escape($store).'=&';
 3388:     } elsif (ref($store) eq 'SCALAR') {
 3389:         $items = &escape($$store).'=&';        
 3390:     } elsif (ref($store) eq 'ARRAY') {
 3391:         $items = join('=&',map {&escape($_);} @{$store});
 3392:     } elsif (ref($store) eq 'HASH') {
 3393:         while (my($key,$value) = each(%{$store})) {
 3394:             $items.= &escape($key).'='.&escape($value).'&';
 3395:         }
 3396:     }
 3397:     $items=~s/\&$//;
 3398:     if ($critical) {
 3399: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3400:     } else {
 3401: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3402:     }
 3403: }
 3404: 
 3405: # --------------------------------------------------------------- put interface
 3406: 
 3407: sub put {
 3408:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3409:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3410:    if (!$uname) { $uname=$env{'user.name'}; }
 3411:    my $uhome=&homeserver($uname,$udomain);
 3412:    my $items='';
 3413:    foreach my $item (keys(%$storehash)) {
 3414:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3415:    }
 3416:    $items=~s/\&$//;
 3417:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3418: }
 3419: 
 3420: # ------------------------------------------------------------ newput interface
 3421: 
 3422: sub newput {
 3423:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3424:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3425:    if (!$uname) { $uname=$env{'user.name'}; }
 3426:    my $uhome=&homeserver($uname,$udomain);
 3427:    my $items='';
 3428:    foreach my $key (keys(%$storehash)) {
 3429:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3430:    }
 3431:    $items=~s/\&$//;
 3432:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3433: }
 3434: 
 3435: # ---------------------------------------------------------  putstore interface
 3436: 
 3437: sub putstore {
 3438:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3439:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3440:    if (!$uname) { $uname=$env{'user.name'}; }
 3441:    my $uhome=&homeserver($uname,$udomain);
 3442:    my $items='';
 3443:    foreach my $key (keys(%$storehash)) {
 3444:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3445:    }
 3446:    $items=~s/\&$//;
 3447:    my $esc_symb=&escape($symb);
 3448:    my $esc_v=&escape($version);
 3449:    my $reply =
 3450:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3451: 	      $uhome);
 3452:    if ($reply eq 'unknown_cmd') {
 3453:        # gfall back to way things use to be done
 3454:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3455: 			    $uname);
 3456:    }
 3457:    return $reply;
 3458: }
 3459: 
 3460: sub old_putstore {
 3461:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3462:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3463:     if (!$uname) { $uname=$env{'user.name'}; }
 3464:     my $uhome=&homeserver($uname,$udomain);
 3465:     my %newstorehash;
 3466:     foreach my $item (keys(%$storehash)) {
 3467: 	my $key = $version.':'.&escape($symb).':'.$item;
 3468: 	$newstorehash{$key} = $storehash->{$item};
 3469:     }
 3470:     my $items='';
 3471:     my %allitems = ();
 3472:     foreach my $item (keys(%newstorehash)) {
 3473: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3474: 	    my $key = $1.':keys:'.$2;
 3475: 	    $allitems{$key} .= $3.':';
 3476: 	}
 3477: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3478:     }
 3479:     foreach my $item (keys(%allitems)) {
 3480: 	$allitems{$item} =~ s/\:$//;
 3481: 	$items.= $item.'='.$allitems{$item}.'&';
 3482:     }
 3483:     $items=~s/\&$//;
 3484:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3485: }
 3486: 
 3487: # ------------------------------------------------------ critical put interface
 3488: 
 3489: sub cput {
 3490:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3491:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3492:    if (!$uname) { $uname=$env{'user.name'}; }
 3493:    my $uhome=&homeserver($uname,$udomain);
 3494:    my $items='';
 3495:    foreach my $item (keys(%$storehash)) {
 3496:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3497:    }
 3498:    $items=~s/\&$//;
 3499:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3500: }
 3501: 
 3502: # -------------------------------------------------------------- eget interface
 3503: 
 3504: sub eget {
 3505:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3506:    my $items='';
 3507:    foreach my $item (@$storearr) {
 3508:        $items.=&escape($item).'&';
 3509:    }
 3510:    $items=~s/\&$//;
 3511:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3512:    if (!$uname) { $uname=$env{'user.name'}; }
 3513:    my $uhome=&homeserver($uname,$udomain);
 3514:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3515:    my @pairs=split(/\&/,$rep);
 3516:    my %returnhash=();
 3517:    my $i=0;
 3518:    foreach my $item (@$storearr) {
 3519:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3520:       $i++;
 3521:    }
 3522:    return %returnhash;
 3523: }
 3524: 
 3525: # ------------------------------------------------------------ tmpput interface
 3526: sub tmpput {
 3527:     my ($storehash,$server,$context)=@_;
 3528:     my $items='';
 3529:     foreach my $item (keys(%$storehash)) {
 3530: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3531:     }
 3532:     $items=~s/\&$//;
 3533:     if (defined($context)) {
 3534:         $items .= ':'.&escape($context);
 3535:     }
 3536:     return &reply("tmpput:$items",$server);
 3537: }
 3538: 
 3539: # ------------------------------------------------------------ tmpget interface
 3540: sub tmpget {
 3541:     my ($token,$server)=@_;
 3542:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3543:     my $rep=&reply("tmpget:$token",$server);
 3544:     my %returnhash;
 3545:     foreach my $item (split(/\&/,$rep)) {
 3546: 	my ($key,$value)=split(/=/,$item);
 3547: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3548:     }
 3549:     return %returnhash;
 3550: }
 3551: 
 3552: # ------------------------------------------------------------ tmpget interface
 3553: sub tmpdel {
 3554:     my ($token,$server)=@_;
 3555:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3556:     return &reply("tmpdel:$token",$server);
 3557: }
 3558: 
 3559: # -------------------------------------------------- portfolio access checking
 3560: 
 3561: sub portfolio_access {
 3562:     my ($requrl) = @_;
 3563:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3564:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3565:     if ($result) {
 3566:         my %setters;
 3567:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3568:             my ($startblock,$endblock) =
 3569:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3570:             if ($startblock && $endblock) {
 3571:                 return 'B';
 3572:             }
 3573:         } else {
 3574:             my ($startblock,$endblock) =
 3575:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3576:             if ($startblock && $endblock) {
 3577:                 return 'B';
 3578:             }
 3579:         }
 3580:     }
 3581:     if ($result eq 'ok') {
 3582:        return 'F';
 3583:     } elsif ($result =~ /^[^:]+:guest_/) {
 3584:        return 'A';
 3585:     }
 3586:     return '';
 3587: }
 3588: 
 3589: sub get_portfolio_access {
 3590:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3591: 
 3592:     if (!ref($access_hash)) {
 3593: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3594: 	my %access_controls = &get_access_controls($current_perms,$group,
 3595: 						   $file_name);
 3596: 	$access_hash = $access_controls{$file_name};
 3597:     }
 3598: 
 3599:     my ($public,$guest,@domains,@users,@courses,@groups);
 3600:     my $now = time;
 3601:     if (ref($access_hash) eq 'HASH') {
 3602:         foreach my $key (keys(%{$access_hash})) {
 3603:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3604:             if ($start > $now) {
 3605:                 next;
 3606:             }
 3607:             if ($end && $end<$now) {
 3608:                 next;
 3609:             }
 3610:             if ($scope eq 'public') {
 3611:                 $public = $key;
 3612:                 last;
 3613:             } elsif ($scope eq 'guest') {
 3614:                 $guest = $key;
 3615:             } elsif ($scope eq 'domains') {
 3616:                 push(@domains,$key);
 3617:             } elsif ($scope eq 'users') {
 3618:                 push(@users,$key);
 3619:             } elsif ($scope eq 'course') {
 3620:                 push(@courses,$key);
 3621:             } elsif ($scope eq 'group') {
 3622:                 push(@groups,$key);
 3623:             }
 3624:         }
 3625:         if ($public) {
 3626:             return 'ok';
 3627:         }
 3628:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3629:             if ($guest) {
 3630:                 return $guest;
 3631:             }
 3632:         } else {
 3633:             if (@domains > 0) {
 3634:                 foreach my $domkey (@domains) {
 3635:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3636:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3637:                             return 'ok';
 3638:                         }
 3639:                     }
 3640:                 }
 3641:             }
 3642:             if (@users > 0) {
 3643:                 foreach my $userkey (@users) {
 3644:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3645:                         return 'ok';
 3646:                     }
 3647:                 }
 3648:             }
 3649:             my %roleshash;
 3650:             my @courses_and_groups = @courses;
 3651:             push(@courses_and_groups,@groups); 
 3652:             if (@courses_and_groups > 0) {
 3653:                 my (%allgroups,%allroles); 
 3654:                 my ($start,$end,$role,$sec,$group);
 3655:                 foreach my $envkey (%env) {
 3656:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3657:                         my $cid = $2.'_'.$3; 
 3658:                         if ($1 eq 'gr') {
 3659:                             $group = $4;
 3660:                             $allgroups{$cid}{$group} = $env{$envkey};
 3661:                         } else {
 3662:                             if ($4 eq '') {
 3663:                                 $sec = 'none';
 3664:                             } else {
 3665:                                 $sec = $4;
 3666:                             }
 3667:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3668:                         }
 3669:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3670:                         my $cid = $2.'_'.$3;
 3671:                         if ($4 eq '') {
 3672:                             $sec = 'none';
 3673:                         } else {
 3674:                             $sec = $4;
 3675:                         }
 3676:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3677:                     }
 3678:                 }
 3679:                 if (keys(%allroles) == 0) {
 3680:                     return;
 3681:                 }
 3682:                 foreach my $key (@courses_and_groups) {
 3683:                     my %content = %{$$access_hash{$key}};
 3684:                     my $cnum = $content{'number'};
 3685:                     my $cdom = $content{'domain'};
 3686:                     my $cid = $cdom.'_'.$cnum;
 3687:                     if (!exists($allroles{$cid})) {
 3688:                         next;
 3689:                     }    
 3690:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3691:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3692:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3693:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3694:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3695:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3696:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3697:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3698:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3699:                                         if (grep/^all$/,@sections) {
 3700:                                             return 'ok';
 3701:                                         } else {
 3702:                                             if (grep/^$sec$/,@sections) {
 3703:                                                 return 'ok';
 3704:                                             }
 3705:                                         }
 3706:                                     }
 3707:                                 }
 3708:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3709:                                     if (grep/^none$/,@groups) {
 3710:                                         return 'ok';
 3711:                                     }
 3712:                                 } else {
 3713:                                     if (grep/^all$/,@groups) {
 3714:                                         return 'ok';
 3715:                                     } 
 3716:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3717:                                         if (grep/^$group$/,@groups) {
 3718:                                             return 'ok';
 3719:                                         }
 3720:                                     }
 3721:                                 } 
 3722:                             }
 3723:                         }
 3724:                     }
 3725:                 }
 3726:             }
 3727:             if ($guest) {
 3728:                 return $guest;
 3729:             }
 3730:         }
 3731:     }
 3732:     return;
 3733: }
 3734: 
 3735: sub course_group_datechecker {
 3736:     my ($dates,$now,$status) = @_;
 3737:     my ($start,$end) = split(/\./,$dates);
 3738:     if (!$start && !$end) {
 3739:         return 'ok';
 3740:     }
 3741:     if (grep/^active$/,@{$status}) {
 3742:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3743:             return 'ok';
 3744:         }
 3745:     }
 3746:     if (grep/^previous$/,@{$status}) {
 3747:         if ($end > $now ) {
 3748:             return 'ok';
 3749:         }
 3750:     }
 3751:     if (grep/^future$/,@{$status}) {
 3752:         if ($start > $now) {
 3753:             return 'ok';
 3754:         }
 3755:     }
 3756:     return; 
 3757: }
 3758: 
 3759: sub parse_portfolio_url {
 3760:     my ($url) = @_;
 3761: 
 3762:     my ($type,$udom,$unum,$group,$file_name);
 3763:     
 3764:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3765: 	$type = 1;
 3766:         $udom = $1;
 3767:         $unum = $2;
 3768:         $file_name = $3;
 3769:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3770: 	$type = 2;
 3771:         $udom = $1;
 3772:         $unum = $2;
 3773:         $group = $3;
 3774:         $file_name = $3.'/'.$4;
 3775:     }
 3776:     if (wantarray) {
 3777: 	return ($type,$udom,$unum,$file_name,$group);
 3778:     }
 3779:     return $type;
 3780: }
 3781: 
 3782: sub is_portfolio_url {
 3783:     my ($url) = @_;
 3784:     return scalar(&parse_portfolio_url($url));
 3785: }
 3786: 
 3787: sub is_portfolio_file {
 3788:     my ($file) = @_;
 3789:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3790:         return 1;
 3791:     }
 3792:     return;
 3793: }
 3794: 
 3795: 
 3796: # ---------------------------------------------- Custom access rule evaluation
 3797: 
 3798: sub customaccess {
 3799:     my ($priv,$uri)=@_;
 3800:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3801:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3802:     $udom = &LONCAPA::clean_domain($udom);
 3803:     $ucrs = &LONCAPA::clean_username($ucrs);
 3804:     my $access=0;
 3805:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3806: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3807:         if ($role) {
 3808: 	   if ($role ne $urole) { next; }
 3809:         }
 3810:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3811:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3812:             if ($tdom) {
 3813: 		if ($tdom ne $udom) { next; }
 3814:             }
 3815:             if ($tcrs) {
 3816: 		if ($tcrs ne $ucrs) { next; }
 3817:             }
 3818:             if ($tsec) {
 3819: 		if ($tsec ne $usec) { next; }
 3820:             }
 3821:             $access=($effect eq 'allow');
 3822:             last;
 3823:         }
 3824: 	if ($realm eq '' && $role eq '') {
 3825:             $access=($effect eq 'allow');
 3826: 	}
 3827:     }
 3828:     return $access;
 3829: }
 3830: 
 3831: # ------------------------------------------------- Check for a user privilege
 3832: 
 3833: sub allowed {
 3834:     my ($priv,$uri,$symb,$role)=@_;
 3835:     my $ver_orguri=$uri;
 3836:     $uri=&deversion($uri);
 3837:     my $orguri=$uri;
 3838:     $uri=&declutter($uri);
 3839: 
 3840:     if ($priv eq 'evb') {
 3841: # Evade communication block restrictions for specified role in a course
 3842:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3843:             return $1;
 3844:         } else {
 3845:             return;
 3846:         }
 3847:     }
 3848: 
 3849:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3850: # Free bre access to adm and meta resources
 3851:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3852: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3853: 	&& ($priv eq 'bre')) {
 3854: 	return 'F';
 3855:     }
 3856: 
 3857: # Free bre access to user's own portfolio contents
 3858:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3859:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3860: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3861:         my %setters;
 3862:         my ($startblock,$endblock) = 
 3863:             &Apache::loncommon::blockcheck(\%setters,'port');
 3864:         if ($startblock && $endblock) {
 3865:             return 'B';
 3866:         } else {
 3867:             return 'F';
 3868:         }
 3869:     }
 3870: 
 3871: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3872:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3873:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3874:         if (exists($env{'request.course.id'})) {
 3875:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3876:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3877:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3878:                 my $courseprivid=$env{'request.course.id'};
 3879:                 $courseprivid=~s/\_/\//;
 3880:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3881:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3882:                     return $1; 
 3883:                 } else {
 3884:                     if ($env{'request.course.sec'}) {
 3885:                         $courseprivid.='/'.$env{'request.course.sec'};
 3886:                     }
 3887:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3888:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3889:                         return $2;
 3890:                     }
 3891:                 }
 3892:             }
 3893:         }
 3894:     }
 3895: 
 3896: # Free bre to public access
 3897: 
 3898:     if ($priv eq 'bre') {
 3899:         my $copyright=&metadata($uri,'copyright');
 3900: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3901:            return 'F'; 
 3902:         }
 3903:         if ($copyright eq 'priv') {
 3904:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3905: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3906: 		return '';
 3907:             }
 3908:         }
 3909:         if ($copyright eq 'domain') {
 3910:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3911: 	    unless (($env{'user.domain'} eq $1) ||
 3912:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3913: 		return '';
 3914:             }
 3915:         }
 3916:         if ($env{'request.role'}=~ /li\.\//) {
 3917:             # Library role, so allow browsing of resources in this domain.
 3918:             return 'F';
 3919:         }
 3920:         if ($copyright eq 'custom') {
 3921: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3922:         }
 3923:     }
 3924:     # Domain coordinator is trying to create a course
 3925:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3926:         # uri is the requested domain in this case.
 3927:         # comparison to 'request.role.domain' shows if the user has selected
 3928:         # a role of dc for the domain in question.
 3929:         return 'F' if ($uri eq $env{'request.role.domain'});
 3930:     }
 3931: 
 3932:     my $thisallowed='';
 3933:     my $statecond=0;
 3934:     my $courseprivid='';
 3935: 
 3936: # Course
 3937: 
 3938:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3939:        $thisallowed.=$1;
 3940:     }
 3941: 
 3942: # Domain
 3943: 
 3944:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3945:        =~/\Q$priv\E\&([^\:]*)/) {
 3946:        $thisallowed.=$1;
 3947:     }
 3948: 
 3949: # Course: uri itself is a course
 3950:     my $courseuri=$uri;
 3951:     $courseuri=~s/\_(\d)/\/$1/;
 3952:     $courseuri=~s/^([^\/])/\/$1/;
 3953: 
 3954:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3955:        =~/\Q$priv\E\&([^\:]*)/) {
 3956:        $thisallowed.=$1;
 3957:     }
 3958: 
 3959: # URI is an uploaded document for this course, default permissions don't matter
 3960: # not allowing 'edit' access (editupload) to uploaded course docs
 3961:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3962: 	$thisallowed='';
 3963:         my ($match)=&is_on_map($uri);
 3964:         if ($match) {
 3965:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3966:                   =~/\Q$priv\E\&([^\:]*)/) {
 3967:                 $thisallowed.=$1;
 3968:             }
 3969:         } else {
 3970:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3971:             if ($refuri) {
 3972:                 if ($refuri =~ m|^/adm/|) {
 3973:                     $thisallowed='F';
 3974:                 } else {
 3975:                     $refuri=&declutter($refuri);
 3976:                     my ($match) = &is_on_map($refuri);
 3977:                     if ($match) {
 3978:                         $thisallowed='F';
 3979:                     }
 3980:                 }
 3981:             }
 3982:         }
 3983:     }
 3984: 
 3985:     if ($priv eq 'bre'
 3986: 	&& $thisallowed ne 'F' 
 3987: 	&& $thisallowed ne '2'
 3988: 	&& &is_portfolio_url($uri)) {
 3989: 	$thisallowed = &portfolio_access($uri);
 3990:     }
 3991:     
 3992: # Full access at system, domain or course-wide level? Exit.
 3993: 
 3994:     if ($thisallowed=~/F/) {
 3995: 	return 'F';
 3996:     }
 3997: 
 3998: # If this is generating or modifying users, exit with special codes
 3999: 
 4000:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4001: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4002: 	    my ($audom,$auname)=split('/',$uri);
 4003: # no author name given, so this just checks on the general right to make a co-author in this domain
 4004: 	    unless ($auname) { return $thisallowed; }
 4005: # an author name is given, so we are about to actually make a co-author for a certain account
 4006: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4007: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4008: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4009: 	}
 4010: 	return $thisallowed;
 4011:     }
 4012: #
 4013: # Gathered so far: system, domain and course wide privileges
 4014: #
 4015: # Course: See if uri or referer is an individual resource that is part of 
 4016: # the course
 4017: 
 4018:     if ($env{'request.course.id'}) {
 4019: 
 4020:        $courseprivid=$env{'request.course.id'};
 4021:        if ($env{'request.course.sec'}) {
 4022:           $courseprivid.='/'.$env{'request.course.sec'};
 4023:        }
 4024:        $courseprivid=~s/\_/\//;
 4025:        my $checkreferer=1;
 4026:        my ($match,$cond)=&is_on_map($uri);
 4027:        if ($match) {
 4028:            $statecond=$cond;
 4029:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4030:                =~/\Q$priv\E\&([^\:]*)/) {
 4031:                $thisallowed.=$1;
 4032:                $checkreferer=0;
 4033:            }
 4034:        }
 4035:        
 4036:        if ($checkreferer) {
 4037: 	  my $refuri=$env{'httpref.'.$orguri};
 4038:             unless ($refuri) {
 4039:                 foreach my $key (keys(%env)) {
 4040: 		    if ($key=~/^httpref\..*\*/) {
 4041: 			my $pattern=$key;
 4042:                         $pattern=~s/^httpref\.\/res\///;
 4043:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4044:                         $pattern=~s/\//\\\//g;
 4045:                         if ($orguri=~/$pattern/) {
 4046: 			    $refuri=$env{$key};
 4047:                         }
 4048:                     }
 4049:                 }
 4050:             }
 4051: 
 4052:          if ($refuri) { 
 4053: 	  $refuri=&declutter($refuri);
 4054:           my ($match,$cond)=&is_on_map($refuri);
 4055:             if ($match) {
 4056:               my $refstatecond=$cond;
 4057:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4058:                   =~/\Q$priv\E\&([^\:]*)/) {
 4059:                   $thisallowed.=$1;
 4060:                   $uri=$refuri;
 4061:                   $statecond=$refstatecond;
 4062:               }
 4063:           }
 4064:         }
 4065:        }
 4066:    }
 4067: 
 4068: #
 4069: # Gathered now: all privileges that could apply, and condition number
 4070: # 
 4071: #
 4072: # Full or no access?
 4073: #
 4074: 
 4075:     if ($thisallowed=~/F/) {
 4076: 	return 'F';
 4077:     }
 4078: 
 4079:     unless ($thisallowed) {
 4080:         return '';
 4081:     }
 4082: 
 4083: # Restrictions exist, deal with them
 4084: #
 4085: #   C:according to course preferences
 4086: #   R:according to resource settings
 4087: #   L:unless locked
 4088: #   X:according to user session state
 4089: #
 4090: 
 4091: # Possibly locked functionality, check all courses
 4092: # Locks might take effect only after 10 minutes cache expiration for other
 4093: # courses, and 2 minutes for current course
 4094: 
 4095:     my $envkey;
 4096:     if ($thisallowed=~/L/) {
 4097:         foreach $envkey (keys %env) {
 4098:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4099:                my $courseid=$2;
 4100:                my $roleid=$1.'.'.$2;
 4101:                $courseid=~s/^\///;
 4102:                my $expiretime=600;
 4103:                if ($env{'request.role'} eq $roleid) {
 4104: 		  $expiretime=120;
 4105:                }
 4106: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4107:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4108:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4109: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4110:                }
 4111:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4112:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4113: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4114:                        &log($env{'user.domain'},$env{'user.name'},
 4115:                             $env{'user.home'},
 4116:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4117:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4118:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4119: 		       return '';
 4120:                    }
 4121:                }
 4122:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4123:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4124: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4125:                        &log($env{'user.domain'},$env{'user.name'},
 4126:                             $env{'user.home'},
 4127:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4128:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4129:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4130: 		       return '';
 4131:                    }
 4132:                }
 4133: 	   }
 4134:        }
 4135:     }
 4136:    
 4137: #
 4138: # Rest of the restrictions depend on selected course
 4139: #
 4140: 
 4141:     unless ($env{'request.course.id'}) {
 4142: 	if ($thisallowed eq 'A') {
 4143: 	    return 'A';
 4144:         } elsif ($thisallowed eq 'B') {
 4145:             return 'B';
 4146: 	} else {
 4147: 	    return '1';
 4148: 	}
 4149:     }
 4150: 
 4151: #
 4152: # Now user is definitely in a course
 4153: #
 4154: 
 4155: 
 4156: # Course preferences
 4157: 
 4158:    if ($thisallowed=~/C/) {
 4159:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4160:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4161:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4162: 	   =~/\Q$rolecode\E/) {
 4163: 	   if ($priv ne 'pch') { 
 4164: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4165: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4166: 			$env{'request.course.id'});
 4167: 	   }
 4168:            return '';
 4169:        }
 4170: 
 4171:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4172: 	   =~/\Q$unamedom\E/) {
 4173: 	   if ($priv ne 'pch') { 
 4174: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4175: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4176: 			$env{'request.course.id'});
 4177: 	   }
 4178:            return '';
 4179:        }
 4180:    }
 4181: 
 4182: # Resource preferences
 4183: 
 4184:    if ($thisallowed=~/R/) {
 4185:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4186:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4187: 	   if ($priv ne 'pch') { 
 4188: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4189: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4190: 	   }
 4191: 	   return '';
 4192:        }
 4193:    }
 4194: 
 4195: # Restricted by state or randomout?
 4196: 
 4197:    if ($thisallowed=~/X/) {
 4198:       if ($env{'acc.randomout'}) {
 4199: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4200:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4201:             return ''; 
 4202:          }
 4203:       }
 4204:       if (&condval($statecond)) {
 4205: 	 return '2';
 4206:       } else {
 4207:          return '';
 4208:       }
 4209:    }
 4210: 
 4211:     if ($thisallowed eq 'A') {
 4212: 	return 'A';
 4213:     } elsif ($thisallowed eq 'B') {
 4214:         return 'B';
 4215:     }
 4216:    return 'F';
 4217: }
 4218: 
 4219: sub split_uri_for_cond {
 4220:     my $uri=&deversion(&declutter(shift));
 4221:     my @uriparts=split(/\//,$uri);
 4222:     my $filename=pop(@uriparts);
 4223:     my $pathname=join('/',@uriparts);
 4224:     return ($pathname,$filename);
 4225: }
 4226: # --------------------------------------------------- Is a resource on the map?
 4227: 
 4228: sub is_on_map {
 4229:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4230:     #Trying to find the conditional for the file
 4231:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4232: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4233:     if ($match) {
 4234: 	return (1,$1);
 4235:     } else {
 4236: 	return (0,0);
 4237:     }
 4238: }
 4239: 
 4240: # --------------------------------------------------------- Get symb from alias
 4241: 
 4242: sub get_symb_from_alias {
 4243:     my $symb=shift;
 4244:     my ($map,$resid,$url)=&decode_symb($symb);
 4245: # Already is a symb
 4246:     if ($url) { return $symb; }
 4247: # Must be an alias
 4248:     my $aliassymb='';
 4249:     my %bighash;
 4250:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4251:                             &GDBM_READER(),0640)) {
 4252:         my $rid=$bighash{'mapalias_'.$symb};
 4253: 	if ($rid) {
 4254: 	    my ($mapid,$resid)=split(/\./,$rid);
 4255: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4256: 				    $resid,$bighash{'src_'.$rid});
 4257: 	}
 4258:         untie %bighash;
 4259:     }
 4260:     return $aliassymb;
 4261: }
 4262: 
 4263: # ----------------------------------------------------------------- Define Role
 4264: 
 4265: sub definerole {
 4266:   if (allowed('mcr','/')) {
 4267:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4268:     foreach my $role (split(':',$sysrole)) {
 4269: 	my ($crole,$cqual)=split(/\&/,$role);
 4270:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4271:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4272: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4273:                return "refused:s:$crole&$cqual"; 
 4274:             }
 4275:         }
 4276:     }
 4277:     foreach my $role (split(':',$domrole)) {
 4278: 	my ($crole,$cqual)=split(/\&/,$role);
 4279:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4280:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4281: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4282:                return "refused:d:$crole&$cqual"; 
 4283:             }
 4284:         }
 4285:     }
 4286:     foreach my $role (split(':',$courole)) {
 4287: 	my ($crole,$cqual)=split(/\&/,$role);
 4288:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4289:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4290: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4291:                return "refused:c:$crole&$cqual"; 
 4292:             }
 4293:         }
 4294:     }
 4295:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4296:                 "$env{'user.domain'}:$env{'user.name'}:".
 4297: 	        "rolesdef_$rolename=".
 4298:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4299:     return reply($command,$env{'user.home'});
 4300:   } else {
 4301:     return 'refused';
 4302:   }
 4303: }
 4304: 
 4305: # ---------------- Make a metadata query against the network of library servers
 4306: 
 4307: sub metadata_query {
 4308:     my ($query,$custom,$customshow,$server_array)=@_;
 4309:     my %rhash;
 4310:     my %libserv = &all_library();
 4311:     my @server_list = (defined($server_array) ? @$server_array
 4312:                                               : keys(%libserv) );
 4313:     for my $server (@server_list) {
 4314: 	unless ($custom or $customshow) {
 4315: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4316: 	    $rhash{$server}=$reply;
 4317: 	}
 4318: 	else {
 4319: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4320: 			     &escape($custom).':'.&escape($customshow),
 4321: 			     $server);
 4322: 	    $rhash{$server}=$reply;
 4323: 	}
 4324:     }
 4325:     return \%rhash;
 4326: }
 4327: 
 4328: # ----------------------------------------- Send log queries and wait for reply
 4329: 
 4330: sub log_query {
 4331:     my ($uname,$udom,$query,%filters)=@_;
 4332:     my $uhome=&homeserver($uname,$udom);
 4333:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4334:     my $uhost=&hostname($uhome);
 4335:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4336:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4337:                        $uhome);
 4338:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4339:     return get_query_reply($queryid);
 4340: }
 4341: 
 4342: # -------------------------- Update MySQL table for portfolio file
 4343: 
 4344: sub update_portfolio_table {
 4345:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4346:     my $homeserver = &homeserver($uname,$udom);
 4347:     my $queryid=
 4348:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4349:                ':'.&escape($file_name).':'.$action,$homeserver);
 4350:     my $reply = &get_query_reply($queryid);
 4351:     return $reply;
 4352: }
 4353: 
 4354: # ------- Request retrieval of institutional classlists for course(s)
 4355: 
 4356: sub fetch_enrollment_query {
 4357:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4358:     my $homeserver;
 4359:     my $maxtries = 1;
 4360:     if ($context eq 'automated') {
 4361:         $homeserver = $perlvar{'lonHostID'};
 4362:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4363:     } else {
 4364:         $homeserver = &homeserver($cnum,$dom);
 4365:     }
 4366:     my $host=&hostname($homeserver);
 4367:     my $cmd = '';
 4368:     foreach my $affiliate (keys %{$affiliatesref}) {
 4369:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4370:     }
 4371:     $cmd =~ s/%%$//;
 4372:     $cmd = &escape($cmd);
 4373:     my $query = 'fetchenrollment';
 4374:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4375:     unless ($queryid=~/^\Q$host\E\_/) { 
 4376:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4377:         return 'error: '.$queryid;
 4378:     }
 4379:     my $reply = &get_query_reply($queryid);
 4380:     my $tries = 1;
 4381:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4382:         $reply = &get_query_reply($queryid);
 4383:         $tries ++;
 4384:     }
 4385:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4386:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4387:     } else {
 4388:         my @responses = split/:/,$reply;
 4389:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4390:             foreach my $line (@responses) {
 4391:                 my ($key,$value) = split(/=/,$line,2);
 4392:                 $$replyref{$key} = $value;
 4393:             }
 4394:         } else {
 4395:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4396:             foreach my $line (@responses) {
 4397:                 my ($key,$value) = split(/=/,$line);
 4398:                 $$replyref{$key} = $value;
 4399:                 if ($value > 0) {
 4400:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4401:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4402:                         my $destname = $pathname.'/'.$filename;
 4403:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4404:                         if ($xml_classlist =~ /^error/) {
 4405:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4406:                         } else {
 4407:                             if ( open(FILE,">$destname") ) {
 4408:                                 print FILE &unescape($xml_classlist);
 4409:                                 close(FILE);
 4410:                             } else {
 4411:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4412:                             }
 4413:                         }
 4414:                     }
 4415:                 }
 4416:             }
 4417:         }
 4418:         return 'ok';
 4419:     }
 4420:     return 'error';
 4421: }
 4422: 
 4423: sub get_query_reply {
 4424:     my $queryid=shift;
 4425:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4426:     my $reply='';
 4427:     for (1..100) {
 4428: 	sleep 2;
 4429:         if (-e $replyfile.'.end') {
 4430: 	    if (open(my $fh,$replyfile)) {
 4431:                $reply.=<$fh>;
 4432:                close($fh);
 4433: 	   } else { return 'error: reply_file_error'; }
 4434:            return &unescape($reply);
 4435: 	}
 4436:     }
 4437:     return 'timeout:'.$queryid;
 4438: }
 4439: 
 4440: sub courselog_query {
 4441: #
 4442: # possible filters:
 4443: # url: url or symb
 4444: # username
 4445: # domain
 4446: # action: view, submit, grade
 4447: # start: timestamp
 4448: # end: timestamp
 4449: #
 4450:     my (%filters)=@_;
 4451:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4452:     if ($filters{'url'}) {
 4453: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4454:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4455:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4456:     }
 4457:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4458:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4459:     return &log_query($cname,$cdom,'courselog',%filters);
 4460: }
 4461: 
 4462: sub userlog_query {
 4463: #
 4464: # possible filters:
 4465: # action: log check role
 4466: # start: timestamp
 4467: # end: timestamp
 4468: #
 4469:     my ($uname,$udom,%filters)=@_;
 4470:     return &log_query($uname,$udom,'userlog',%filters);
 4471: }
 4472: 
 4473: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4474: 
 4475: sub auto_run {
 4476:     my ($cnum,$cdom) = @_;
 4477:     my $homeserver = &homeserver($cnum,$cdom);
 4478:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4479:     return $response;
 4480: }
 4481: 
 4482: sub auto_get_sections {
 4483:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4484:     my $homeserver = &homeserver($cnum,$cdom);
 4485:     my @secs = ();
 4486:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4487:     unless ($response eq 'refused') {
 4488:         @secs = split/:/,$response;
 4489:     }
 4490:     return @secs;
 4491: }
 4492: 
 4493: sub auto_new_course {
 4494:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4495:     my $homeserver = &homeserver($cnum,$cdom);
 4496:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4497:     return $response;
 4498: }
 4499: 
 4500: sub auto_validate_courseID {
 4501:     my ($cnum,$cdom,$inst_course_id) = @_;
 4502:     my $homeserver = &homeserver($cnum,$cdom);
 4503:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4504:     return $response;
 4505: }
 4506: 
 4507: sub auto_create_password {
 4508:     my ($cnum,$cdom,$authparam) = @_;
 4509:     my $homeserver = &homeserver($cnum,$cdom); 
 4510:     my $create_passwd = 0;
 4511:     my $authchk = '';
 4512:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4513:     if ($response eq 'refused') {
 4514:         $authchk = 'refused';
 4515:     } else {
 4516:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4517:     }
 4518:     return ($authparam,$create_passwd,$authchk);
 4519: }
 4520: 
 4521: sub auto_photo_permission {
 4522:     my ($cnum,$cdom,$students) = @_;
 4523:     my $homeserver = &homeserver($cnum,$cdom);
 4524:     my ($outcome,$perm_reqd,$conditions) = 
 4525: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4526:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4527: 	return (undef,undef);
 4528:     }
 4529:     return ($outcome,$perm_reqd,$conditions);
 4530: }
 4531: 
 4532: sub auto_checkphotos {
 4533:     my ($uname,$udom,$pid) = @_;
 4534:     my $homeserver = &homeserver($uname,$udom);
 4535:     my ($result,$resulttype);
 4536:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4537: 				   &escape($uname).':'.&escape($pid),
 4538: 				   $homeserver));
 4539:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4540: 	return (undef,undef);
 4541:     }
 4542:     if ($outcome) {
 4543:         ($result,$resulttype) = split(/:/,$outcome);
 4544:     } 
 4545:     return ($result,$resulttype);
 4546: }
 4547: 
 4548: sub auto_photochoice {
 4549:     my ($cnum,$cdom) = @_;
 4550:     my $homeserver = &homeserver($cnum,$cdom);
 4551:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4552: 						       &escape($cdom),
 4553: 						       $homeserver)));
 4554:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4555: 	return (undef,undef);
 4556:     }
 4557:     return ($update,$comment);
 4558: }
 4559: 
 4560: sub auto_photoupdate {
 4561:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4562:     my $homeserver = &homeserver($cnum,$dom);
 4563:     my $host=&hostname($homeserver);
 4564:     my $cmd = '';
 4565:     my $maxtries = 1;
 4566:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4567:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4568:     }
 4569:     $cmd =~ s/%%$//;
 4570:     $cmd = &escape($cmd);
 4571:     my $query = 'institutionalphotos';
 4572:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4573:     unless ($queryid=~/^\Q$host\E\_/) {
 4574:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4575:         return 'error: '.$queryid;
 4576:     }
 4577:     my $reply = &get_query_reply($queryid);
 4578:     my $tries = 1;
 4579:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4580:         $reply = &get_query_reply($queryid);
 4581:         $tries ++;
 4582:     }
 4583:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4584:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4585:     } else {
 4586:         my @responses = split(/:/,$reply);
 4587:         my $outcome = shift(@responses); 
 4588:         foreach my $item (@responses) {
 4589:             my ($key,$value) = split(/=/,$item);
 4590:             $$photo{$key} = $value;
 4591:         }
 4592:         return $outcome;
 4593:     }
 4594:     return 'error';
 4595: }
 4596: 
 4597: sub auto_instcode_format {
 4598:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4599: 	$cat_order) = @_;
 4600:     my $courses = '';
 4601:     my @homeservers;
 4602:     if ($caller eq 'global') {
 4603: 	my %servers = &get_servers($codedom,'library');
 4604: 	foreach my $tryserver (keys(%servers)) {
 4605: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4606: 		push(@homeservers,$tryserver);
 4607: 	    }
 4608:         }
 4609:     } else {
 4610:         push(@homeservers,&homeserver($caller,$codedom));
 4611:     }
 4612:     foreach my $code (keys(%{$instcodes})) {
 4613:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4614:     }
 4615:     chop($courses);
 4616:     my $ok_response = 0;
 4617:     my $response;
 4618:     while (@homeservers > 0 && $ok_response == 0) {
 4619:         my $server = shift(@homeservers); 
 4620:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4621:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4622:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4623: 		split/:/,$response;
 4624:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4625:             push(@{$codetitles},&str2array($codetitles_str));
 4626:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4627:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4628:             $ok_response = 1;
 4629:         }
 4630:     }
 4631:     if ($ok_response) {
 4632:         return 'ok';
 4633:     } else {
 4634:         return $response;
 4635:     }
 4636: }
 4637: 
 4638: sub auto_instcode_defaults {
 4639:     my ($domain,$returnhash,$code_order) = @_;
 4640:     my @homeservers;
 4641: 
 4642:     my %servers = &get_servers($domain,'library');
 4643:     foreach my $tryserver (keys(%servers)) {
 4644: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4645: 	    push(@homeservers,$tryserver);
 4646: 	}
 4647:     }
 4648: 
 4649:     my $response;
 4650:     foreach my $server (@homeservers) {
 4651:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4652:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4653: 	
 4654: 	foreach my $pair (split(/\&/,$response)) {
 4655: 	    my ($name,$value)=split(/\=/,$pair);
 4656: 	    if ($name eq 'code_order') {
 4657: 		@{$code_order} = split(/\&/,&unescape($value));
 4658: 	    } else {
 4659: 		$returnhash->{&unescape($name)}=&unescape($value);
 4660: 	    }
 4661: 	}
 4662: 	return 'ok';
 4663:     }
 4664: 
 4665:     return $response;
 4666: } 
 4667: 
 4668: sub auto_validate_class_sec {
 4669:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4670:     my $homeserver = &homeserver($cnum,$cdom);
 4671:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4672:                         &escape($owner).':'.$cdom,$homeserver);
 4673:     return $response;
 4674: }
 4675: 
 4676: # ------------------------------------------------------- Course Group routines
 4677: 
 4678: sub get_coursegroups {
 4679:     my ($cdom,$cnum,$group,$namespace) = @_;
 4680:     return(&dump($namespace,$cdom,$cnum,$group));
 4681: }
 4682: 
 4683: sub modify_coursegroup {
 4684:     my ($cdom,$cnum,$groupsettings) = @_;
 4685:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4686: }
 4687: 
 4688: sub toggle_coursegroup_status {
 4689:     my ($cdom,$cnum,$group,$action) = @_;
 4690:     my ($from_namespace,$to_namespace);
 4691:     if ($action eq 'delete') {
 4692:         $from_namespace = 'coursegroups';
 4693:         $to_namespace = 'deleted_groups';
 4694:     } else {
 4695:         $from_namespace = 'deleted_groups';
 4696:         $to_namespace = 'coursegroups';
 4697:     }
 4698:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4699:     if (my $tmp = &error(%curr_group)) {
 4700:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4701:         return ('read error',$tmp);
 4702:     } else {
 4703:         my %savedsettings = %curr_group; 
 4704:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4705:         my $deloutcome;
 4706:         if ($result eq 'ok') {
 4707:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4708:         } else {
 4709:             return ('write error',$result);
 4710:         }
 4711:         if ($deloutcome eq 'ok') {
 4712:             return 'ok';
 4713:         } else {
 4714:             return ('delete error',$deloutcome);
 4715:         }
 4716:     }
 4717: }
 4718: 
 4719: sub modify_group_roles {
 4720:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4721:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4722:     my $role = 'gr/'.&escape($userprivs);
 4723:     my ($uname,$udom) = split(/:/,$user);
 4724:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4725:     if ($result eq 'ok') {
 4726:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4727:     }
 4728:     return $result;
 4729: }
 4730: 
 4731: sub modify_coursegroup_membership {
 4732:     my ($cdom,$cnum,$membership) = @_;
 4733:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4734:     return $result;
 4735: }
 4736: 
 4737: sub get_active_groups {
 4738:     my ($udom,$uname,$cdom,$cnum) = @_;
 4739:     my $now = time;
 4740:     my %groups = ();
 4741:     foreach my $key (keys(%env)) {
 4742:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4743:             my ($start,$end) = split(/\./,$env{$key});
 4744:             if (($end!=0) && ($end<$now)) { next; }
 4745:             if (($start!=0) && ($start>$now)) { next; }
 4746:             if ($1 eq $cdom && $2 eq $cnum) {
 4747:                 $groups{$3} = $env{$key} ;
 4748:             }
 4749:         }
 4750:     }
 4751:     return %groups;
 4752: }
 4753: 
 4754: sub get_group_membership {
 4755:     my ($cdom,$cnum,$group) = @_;
 4756:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4757: }
 4758: 
 4759: sub get_users_groups {
 4760:     my ($udom,$uname,$courseid) = @_;
 4761:     my @usersgroups;
 4762:     my $cachetime=1800;
 4763: 
 4764:     my $hashid="$udom:$uname:$courseid";
 4765:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4766:     if (defined($cached)) {
 4767:         @usersgroups = split(/:/,$grouplist);
 4768:     } else {  
 4769:         $grouplist = '';
 4770:         my $courseurl = &courseid_to_courseurl($courseid);
 4771:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4772:         my $access_end = $env{'course.'.$courseid.
 4773:                               '.default_enrollment_end_date'};
 4774:         my $now = time;
 4775:         foreach my $key (keys(%roleshash)) {
 4776:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4777:                 my $group = $1;
 4778:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4779:                     my $start = $2;
 4780:                     my $end = $1;
 4781:                     if ($start == -1) { next; } # deleted from group
 4782:                     if (($start!=0) && ($start>$now)) { next; }
 4783:                     if (($end!=0) && ($end<$now)) {
 4784:                         if ($access_end && $access_end < $now) {
 4785:                             if ($access_end - $end < 86400) {
 4786:                                 push(@usersgroups,$group);
 4787:                             }
 4788:                         }
 4789:                         next;
 4790:                     }
 4791:                     push(@usersgroups,$group);
 4792:                 }
 4793:             }
 4794:         }
 4795:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4796:         $grouplist = join(':',@usersgroups);
 4797:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4798:     }
 4799:     return @usersgroups;
 4800: }
 4801: 
 4802: sub devalidate_getgroups_cache {
 4803:     my ($udom,$uname,$cdom,$cnum)=@_;
 4804:     my $courseid = $cdom.'_'.$cnum;
 4805: 
 4806:     my $hashid="$udom:$uname:$courseid";
 4807:     &devalidate_cache_new('getgroups',$hashid);
 4808: }
 4809: 
 4810: # ------------------------------------------------------------------ Plain Text
 4811: 
 4812: sub plaintext {
 4813:     my ($short,$type,$cid) = @_;
 4814:     if ($short =~ /^cr/) {
 4815: 	return (split('/',$short))[-1];
 4816:     }
 4817:     if (!defined($cid)) {
 4818:         $cid = $env{'request.course.id'};
 4819:     }
 4820:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4821:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4822:                                           '.plaintext'});
 4823:     }
 4824:     my %rolenames = (
 4825:                       Course => 'std',
 4826:                       Group => 'alt1',
 4827:                     );
 4828:     if (defined($type) && 
 4829:          defined($rolenames{$type}) && 
 4830:          defined($prp{$short}{$rolenames{$type}})) {
 4831:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4832:     } else {
 4833:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4834:     }
 4835: }
 4836: 
 4837: # ----------------------------------------------------------------- Assign Role
 4838: 
 4839: sub assignrole {
 4840:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4841:     my $mrole;
 4842:     if ($role =~ /^cr\//) {
 4843:         my $cwosec=$url;
 4844:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4845: 	unless (&allowed('ccr',$cwosec)) {
 4846:            &logthis('Refused custom assignrole: '.
 4847:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4848: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4849:            return 'refused'; 
 4850:         }
 4851:         $mrole='cr';
 4852:     } elsif ($role =~ /^gr\//) {
 4853:         my $cwogrp=$url;
 4854:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4855:         unless (&allowed('mdg',$cwogrp)) {
 4856:             &logthis('Refused group assignrole: '.
 4857:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4858:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4859:             return 'refused';
 4860:         }
 4861:         $mrole='gr';
 4862:     } else {
 4863:         my $cwosec=$url;
 4864:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4865:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4866:            &logthis('Refused assignrole: '.
 4867:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4868: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4869:            return 'refused'; 
 4870:         }
 4871:         $mrole=$role;
 4872:     }
 4873:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4874:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4875:     if ($end) { $command.='_'.$end; }
 4876:     if ($start) {
 4877: 	if ($end) { 
 4878:            $command.='_'.$start; 
 4879:         } else {
 4880:            $command.='_0_'.$start;
 4881:         }
 4882:     }
 4883:     my $origstart = $start;
 4884:     my $origend = $end;
 4885: # actually delete
 4886:     if ($deleteflag) {
 4887: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4888: # modify command to delete the role
 4889:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4890:                 "$udom:$uname:$url".'_'."$mrole";
 4891: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4892: # set start and finish to negative values for userrolelog
 4893:            $start=-1;
 4894:            $end=-1;
 4895:         }
 4896:     }
 4897: # send command
 4898:     my $answer=&reply($command,&homeserver($uname,$udom));
 4899: # log new user role if status is ok
 4900:     if ($answer eq 'ok') {
 4901: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4902: # for course roles, perform group memberships changes triggered by role change.
 4903:         unless ($role =~ /^gr/) {
 4904:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4905:                                              $origstart);
 4906:         }
 4907:     }
 4908:     return $answer;
 4909: }
 4910: 
 4911: # -------------------------------------------------- Modify user authentication
 4912: # Overrides without validation
 4913: 
 4914: sub modifyuserauth {
 4915:     my ($udom,$uname,$umode,$upass)=@_;
 4916:     my $uhome=&homeserver($uname,$udom);
 4917:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4918:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4919:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4920:              ' in domain '.$env{'request.role.domain'});  
 4921:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4922: 		     &escape($upass),$uhome);
 4923:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4924:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4925:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4926:     &log($udom,,$uname,$uhome,
 4927:         'Authentication changed by '.$env{'user.domain'}.', '.
 4928:                                      $env{'user.name'}.', '.$umode.
 4929:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4930:     unless ($reply eq 'ok') {
 4931:         &logthis('Authentication mode error: '.$reply);
 4932: 	return 'error: '.$reply;
 4933:     }   
 4934:     return 'ok';
 4935: }
 4936: 
 4937: # --------------------------------------------------------------- Modify a user
 4938: 
 4939: sub modifyuser {
 4940:     my ($udom,    $uname, $uid,
 4941:         $umode,   $upass, $first,
 4942:         $middle,  $last,  $gene,
 4943:         $forceid, $desiredhome, $email)=@_;
 4944:     $udom= &LONCAPA::clean_domain($udom);
 4945:     $uname=&LONCAPA::clean_username($uname);
 4946:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4947:              $umode.', '.$first.', '.$middle.', '.
 4948: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4949:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4950:                                      ' desiredhome not specified'). 
 4951:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4952:              ' in domain '.$env{'request.role.domain'});
 4953:     my $uhome=&homeserver($uname,$udom,'true');
 4954: # ----------------------------------------------------------------- Create User
 4955:     if (($uhome eq 'no_host') && 
 4956: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4957:         my $unhome='';
 4958:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4959:             $unhome = $desiredhome;
 4960: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4961: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4962:         } else { # load balancing routine for determining $unhome
 4963:             my $loadm=10000000;
 4964: 	    my %servers = &get_servers($udom,'library');
 4965: 	    foreach my $tryserver (keys(%servers)) {
 4966: 		my $answer=reply('load',$tryserver);
 4967: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4968: 		    $loadm=$answer;
 4969: 		    $unhome=$tryserver;
 4970: 		}
 4971: 	    }
 4972:         }
 4973:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4974: 	    return 'error: unable to find a home server for '.$uname.
 4975:                    ' in domain '.$udom;
 4976:         }
 4977:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4978:                          &escape($upass),$unhome);
 4979: 	unless ($reply eq 'ok') {
 4980:             return 'error: '.$reply;
 4981:         }   
 4982:         $uhome=&homeserver($uname,$udom,'true');
 4983:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4984: 	    return 'error: unable verify users home machine.';
 4985:         }
 4986:     }   # End of creation of new user
 4987: # ---------------------------------------------------------------------- Add ID
 4988:     if ($uid) {
 4989:        $uid=~tr/A-Z/a-z/;
 4990:        my %uidhash=&idrget($udom,$uname);
 4991:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4992:          && (!$forceid)) {
 4993: 	  unless ($uid eq $uidhash{$uname}) {
 4994: 	      return 'error: user id "'.$uid.'" does not match '.
 4995:                   'current user id "'.$uidhash{$uname}.'".';
 4996:           }
 4997:        } else {
 4998: 	  &idput($udom,($uname => $uid));
 4999:        }
 5000:     }
 5001: # -------------------------------------------------------------- Add names, etc
 5002:     my @tmp=&get('environment',
 5003: 		   ['firstname','middlename','lastname','generation'],
 5004: 		   $udom,$uname);
 5005:     my %names;
 5006:     if ($tmp[0] =~ m/^error:.*/) { 
 5007:         %names=(); 
 5008:     } else {
 5009:         %names = @tmp;
 5010:     }
 5011: #
 5012: # Make sure to not trash student environment if instructor does not bother
 5013: # to supply name and email information
 5014: #
 5015:     if ($first)  { $names{'firstname'}  = $first; }
 5016:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5017:     if ($last)   { $names{'lastname'}   = $last; }
 5018:     if (defined($gene))   { $names{'generation'} = $gene; }
 5019:     if ($email) {
 5020:        $email=~s/[^\w\@\.\-\,]//gs;
 5021:        if ($email=~/\@/) { $names{'notification'} = $email;
 5022: 			   $names{'critnotification'} = $email;
 5023: 			   $names{'permanentemail'} = $email; }
 5024:     }
 5025:     my $reply = &put('environment', \%names, $udom,$uname);
 5026:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5027:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5028:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5029:              $umode.', '.$first.', '.$middle.', '.
 5030: 	     $last.', '.$gene.' by '.
 5031:              $env{'user.name'}.' at '.$env{'user.domain'});
 5032:     return 'ok';
 5033: }
 5034: 
 5035: # -------------------------------------------------------------- Modify student
 5036: 
 5037: sub modifystudent {
 5038:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5039:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5040:     if (!$cid) {
 5041: 	unless ($cid=$env{'request.course.id'}) {
 5042: 	    return 'not_in_class';
 5043: 	}
 5044:     }
 5045: # --------------------------------------------------------------- Make the user
 5046:     my $reply=&modifyuser
 5047: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5048:          $desiredhome,$email);
 5049:     unless ($reply eq 'ok') { return $reply; }
 5050:     # This will cause &modify_student_enrollment to get the uid from the
 5051:     # students environment
 5052:     $uid = undef if (!$forceid);
 5053:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5054: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5055:     return $reply;
 5056: }
 5057: 
 5058: sub modify_student_enrollment {
 5059:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5060:     my ($cdom,$cnum,$chome);
 5061:     if (!$cid) {
 5062: 	unless ($cid=$env{'request.course.id'}) {
 5063: 	    return 'not_in_class';
 5064: 	}
 5065: 	$cdom=$env{'course.'.$cid.'.domain'};
 5066: 	$cnum=$env{'course.'.$cid.'.num'};
 5067:     } else {
 5068: 	($cdom,$cnum)=split(/_/,$cid);
 5069:     }
 5070:     $chome=$env{'course.'.$cid.'.home'};
 5071:     if (!$chome) {
 5072: 	$chome=&homeserver($cnum,$cdom);
 5073:     }
 5074:     if (!$chome) { return 'unknown_course'; }
 5075:     # Make sure the user exists
 5076:     my $uhome=&homeserver($uname,$udom);
 5077:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5078: 	return 'error: no such user';
 5079:     }
 5080:     # Get student data if we were not given enough information
 5081:     if (!defined($first)  || $first  eq '' || 
 5082:         !defined($last)   || $last   eq '' || 
 5083:         !defined($uid)    || $uid    eq '' || 
 5084:         !defined($middle) || $middle eq '' || 
 5085:         !defined($gene)   || $gene   eq '') {
 5086:         # They did not supply us with enough data to enroll the student, so
 5087:         # we need to pick up more information.
 5088:         my %tmp = &get('environment',
 5089:                        ['firstname','middlename','lastname', 'generation','id']
 5090:                        ,$udom,$uname);
 5091: 
 5092:         #foreach my $key (keys(%tmp)) {
 5093:         #    &logthis("key $key = ".$tmp{$key});
 5094:         #}
 5095:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5096:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5097:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5098:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5099:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5100:     }
 5101:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5102:     my $reply=cput('classlist',
 5103: 		   {"$uname:$udom" => 
 5104: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5105: 		   $cdom,$cnum);
 5106:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5107: 	return 'error: '.$reply;
 5108:     } else {
 5109: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5110:     }
 5111:     # Add student role to user
 5112:     my $uurl='/'.$cid;
 5113:     $uurl=~s/\_/\//g;
 5114:     if ($usec) {
 5115: 	$uurl.='/'.$usec;
 5116:     }
 5117:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5118: }
 5119: 
 5120: sub format_name {
 5121:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5122:     my $name;
 5123:     if ($first ne 'lastname') {
 5124: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5125:     } else {
 5126: 	if ($lastname=~/\S/) {
 5127: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5128: 	    $name=~s/\s+,/,/;
 5129: 	} else {
 5130: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5131: 	}
 5132:     }
 5133:     $name=~s/^\s+//;
 5134:     $name=~s/\s+$//;
 5135:     $name=~s/\s+/ /g;
 5136:     return $name;
 5137: }
 5138: 
 5139: # ------------------------------------------------- Write to course preferences
 5140: 
 5141: sub writecoursepref {
 5142:     my ($courseid,%prefs)=@_;
 5143:     $courseid=~s/^\///;
 5144:     $courseid=~s/\_/\//g;
 5145:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5146:     my $chome=homeserver($cnum,$cdomain);
 5147:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5148: 	return 'error: no such course';
 5149:     }
 5150:     my $cstring='';
 5151:     foreach my $pref (keys(%prefs)) {
 5152: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5153:     }
 5154:     $cstring=~s/\&$//;
 5155:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5156: }
 5157: 
 5158: # ---------------------------------------------------------- Make/modify course
 5159: 
 5160: sub createcourse {
 5161:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5162:         $course_owner,$crstype)=@_;
 5163:     $url=&declutter($url);
 5164:     my $cid='';
 5165:     unless (&allowed('ccc',$udom)) {
 5166:         return 'refused';
 5167:     }
 5168: # ------------------------------------------------------------------- Create ID
 5169:    my $uname=int(1+rand(9)).
 5170:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5171:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5172:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5173: # ----------------------------------------------- Make sure that does not exist
 5174:    my $uhome=&homeserver($uname,$udom,'true');
 5175:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5176:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5177:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5178:        $uhome=&homeserver($uname,$udom,'true');       
 5179:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5180:            return 'error: unable to generate unique course-ID';
 5181:        } 
 5182:    }
 5183: # ------------------------------------------------ Check supplied server name
 5184:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5185:     if (! &is_library($course_server)) {
 5186:         return 'error:bad server name '.$course_server;
 5187:     }
 5188: # ------------------------------------------------------------- Make the course
 5189:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5190:                       $course_server);
 5191:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5192:     $uhome=&homeserver($uname,$udom,'true');
 5193:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5194: 	return 'error: no such course';
 5195:     }
 5196: # ----------------------------------------------------------------- Course made
 5197: # log existence
 5198:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5199:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5200:                   &escape($crstype),$uhome);
 5201:     &flushcourselogs();
 5202: # set toplevel url
 5203:     my $topurl=$url;
 5204:     unless ($nonstandard) {
 5205: # ------------------------------------------ For standard courses, make top url
 5206:         my $mapurl=&clutter($url);
 5207:         if ($mapurl eq '/res/') { $mapurl=''; }
 5208:         $env{'form.initmap'}=(<<ENDINITMAP);
 5209: <map>
 5210: <resource id="1" type="start"></resource>
 5211: <resource id="2" src="$mapurl"></resource>
 5212: <resource id="3" type="finish"></resource>
 5213: <link index="1" from="1" to="2"></link>
 5214: <link index="2" from="2" to="3"></link>
 5215: </map>
 5216: ENDINITMAP
 5217:         $topurl=&declutter(
 5218:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5219:                           );
 5220:     }
 5221: # ----------------------------------------------------------- Write preferences
 5222:     &writecoursepref($udom.'_'.$uname,
 5223:                      ('description' => $description,
 5224:                       'url'         => $topurl));
 5225:     return '/'.$udom.'/'.$uname;
 5226: }
 5227: 
 5228: sub is_course {
 5229:     my ($cdom,$cnum) = @_;
 5230:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5231: 				undef,'.');
 5232:     if (exists($courses{$cdom.'_'.$cnum})) {
 5233:         return 1;
 5234:     }
 5235:     return 0;
 5236: }
 5237: 
 5238: # ---------------------------------------------------------- Assign Custom Role
 5239: 
 5240: sub assigncustomrole {
 5241:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5242:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5243:                        $end,$start,$deleteflag);
 5244: }
 5245: 
 5246: # ----------------------------------------------------------------- Revoke Role
 5247: 
 5248: sub revokerole {
 5249:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5250:     my $now=time;
 5251:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5252: }
 5253: 
 5254: # ---------------------------------------------------------- Revoke Custom Role
 5255: 
 5256: sub revokecustomrole {
 5257:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5258:     my $now=time;
 5259:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5260:            $deleteflag);
 5261: }
 5262: 
 5263: # ------------------------------------------------------------ Disk usage
 5264: sub diskusage {
 5265:     my ($udom,$uname,$directoryRoot)=@_;
 5266:     $directoryRoot =~ s/\/$//;
 5267:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5268:     return $listing;
 5269: }
 5270: 
 5271: sub is_locked {
 5272:     my ($file_name, $domain, $user) = @_;
 5273:     my @check;
 5274:     my $is_locked;
 5275:     push @check, $file_name;
 5276:     my %locked = &get('file_permissions',\@check,
 5277: 		      $env{'user.domain'},$env{'user.name'});
 5278:     my ($tmp)=keys(%locked);
 5279:     if ($tmp=~/^error:/) { undef(%locked); }
 5280:     
 5281:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5282:         $is_locked = 'false';
 5283:         foreach my $entry (@{$locked{$file_name}}) {
 5284:            if (ref($entry) eq 'ARRAY') { 
 5285:                $is_locked = 'true';
 5286:                last;
 5287:            }
 5288:        }
 5289:     } else {
 5290:         $is_locked = 'false';
 5291:     }
 5292: }
 5293: 
 5294: sub declutter_portfile {
 5295:     my ($file) = @_;
 5296:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5297:     return $file;
 5298: }
 5299: 
 5300: # ------------------------------------------------------------- Mark as Read Only
 5301: 
 5302: sub mark_as_readonly {
 5303:     my ($domain,$user,$files,$what) = @_;
 5304:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5305:     my ($tmp)=keys(%current_permissions);
 5306:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5307:     foreach my $file (@{$files}) {
 5308: 	$file = &declutter_portfile($file);
 5309:         push(@{$current_permissions{$file}},$what);
 5310:     }
 5311:     &put('file_permissions',\%current_permissions,$domain,$user);
 5312:     return;
 5313: }
 5314: 
 5315: # ------------------------------------------------------------Save Selected Files
 5316: 
 5317: sub save_selected_files {
 5318:     my ($user, $path, @files) = @_;
 5319:     my $filename = $user."savedfiles";
 5320:     my @other_files = &files_not_in_path($user, $path);
 5321:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5322:     foreach my $file (@files) {
 5323:         print (OUT $env{'form.currentpath'}.$file."\n");
 5324:     }
 5325:     foreach my $file (@other_files) {
 5326:         print (OUT $file."\n");
 5327:     }
 5328:     close (OUT);
 5329:     return 'ok';
 5330: }
 5331: 
 5332: sub clear_selected_files {
 5333:     my ($user) = @_;
 5334:     my $filename = $user."savedfiles";
 5335:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5336:     print (OUT undef);
 5337:     close (OUT);
 5338:     return ("ok");    
 5339: }
 5340: 
 5341: sub files_in_path {
 5342:     my ($user, $path) = @_;
 5343:     my $filename = $user."savedfiles";
 5344:     my %return_files;
 5345:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5346:     while (my $line_in = <IN>) {
 5347:         chomp ($line_in);
 5348:         my @paths_and_file = split (m!/!, $line_in);
 5349:         my $file_part = pop (@paths_and_file);
 5350:         my $path_part = join ('/', @paths_and_file);
 5351:         $path_part.='/';
 5352:         my $path_and_file = $path_part.$file_part;
 5353:         if ($path_part eq $path) {
 5354:             $return_files{$file_part}= 'selected';
 5355:         }
 5356:     }
 5357:     close (IN);
 5358:     return (\%return_files);
 5359: }
 5360: 
 5361: # called in portfolio select mode, to show files selected NOT in current directory
 5362: sub files_not_in_path {
 5363:     my ($user, $path) = @_;
 5364:     my $filename = $user."savedfiles";
 5365:     my @return_files;
 5366:     my $path_part;
 5367:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5368:     while (my $line = <IN>) {
 5369:         #ok, I know it's clunky, but I want it to work
 5370:         my @paths_and_file = split(m|/|, $line);
 5371:         my $file_part = pop(@paths_and_file);
 5372:         chomp($file_part);
 5373:         my $path_part = join('/', @paths_and_file);
 5374:         $path_part .= '/';
 5375:         my $path_and_file = $path_part.$file_part;
 5376:         if ($path_part ne $path) {
 5377:             push(@return_files, ($path_and_file));
 5378:         }
 5379:     }
 5380:     close(OUT);
 5381:     return (@return_files);
 5382: }
 5383: 
 5384: #----------------------------------------------Get portfolio file permissions
 5385: 
 5386: sub get_portfile_permissions {
 5387:     my ($domain,$user) = @_;
 5388:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5389:     my ($tmp)=keys(%current_permissions);
 5390:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5391:     return \%current_permissions;
 5392: }
 5393: 
 5394: #---------------------------------------------Get portfolio file access controls
 5395: 
 5396: sub get_access_controls {
 5397:     my ($current_permissions,$group,$file) = @_;
 5398:     my %access;
 5399:     my $real_file = $file;
 5400:     $file =~ s/\.meta$//;
 5401:     if (defined($file)) {
 5402:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5403:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5404:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5405:             }
 5406:         }
 5407:     } else {
 5408:         foreach my $key (keys(%{$current_permissions})) {
 5409:             if ($key =~ /\0accesscontrol$/) {
 5410:                 if (defined($group)) {
 5411:                     if ($key !~ m-^\Q$group\E/-) {
 5412:                         next;
 5413:                     }
 5414:                 }
 5415:                 my ($fullpath) = split(/\0/,$key);
 5416:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5417:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5418:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5419:                     }
 5420:                 }
 5421:             }
 5422:         }
 5423:     }
 5424:     return %access;
 5425: }
 5426: 
 5427: sub modify_access_controls {
 5428:     my ($file_name,$changes,$domain,$user)=@_;
 5429:     my ($outcome,$deloutcome);
 5430:     my %store_permissions;
 5431:     my %new_values;
 5432:     my %new_control;
 5433:     my %translation;
 5434:     my @deletions = ();
 5435:     my $now = time;
 5436:     if (exists($$changes{'activate'})) {
 5437:         if (ref($$changes{'activate'}) eq 'HASH') {
 5438:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5439:             my $numnew = scalar(@newitems);
 5440:             for (my $i=0; $i<$numnew; $i++) {
 5441:                 my $newkey = $newitems[$i];
 5442:                 my $newid = &Apache::loncommon::get_cgi_id();
 5443:                 if ($newkey =~ /^\d+:/) { 
 5444:                     $newkey =~ s/^(\d+)/$newid/;
 5445:                     $translation{$1} = $newid;
 5446:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5447:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5448:                     $translation{$1} = $newid;
 5449:                 }
 5450:                 $new_values{$file_name."\0".$newkey} = 
 5451:                                           $$changes{'activate'}{$newitems[$i]};
 5452:                 $new_control{$newkey} = $now;
 5453:             }
 5454:         }
 5455:     }
 5456:     my %todelete;
 5457:     my %changed_items;
 5458:     foreach my $action ('delete','update') {
 5459:         if (exists($$changes{$action})) {
 5460:             if (ref($$changes{$action}) eq 'HASH') {
 5461:                 foreach my $key (keys(%{$$changes{$action}})) {
 5462:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5463:                     if ($action eq 'delete') { 
 5464:                         $todelete{$itemnum} = 1;
 5465:                     } else {
 5466:                         $changed_items{$itemnum} = $key;
 5467:                     }
 5468:                 }
 5469:             }
 5470:         }
 5471:     }
 5472:     # get lock on access controls for file.
 5473:     my $lockhash = {
 5474:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5475:                                                        ':'.$env{'user.domain'},
 5476:                    }; 
 5477:     my $tries = 0;
 5478:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5479:    
 5480:     while (($gotlock ne 'ok') && $tries <3) {
 5481:         $tries ++;
 5482:         sleep 1;
 5483:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5484:     }
 5485:     if ($gotlock eq 'ok') {
 5486:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5487:         my ($tmp)=keys(%curr_permissions);
 5488:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5489:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5490:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5491:             if (ref($curr_controls) eq 'HASH') {
 5492:                 foreach my $control_item (keys(%{$curr_controls})) {
 5493:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5494:                     if (defined($todelete{$itemnum})) {
 5495:                         push(@deletions,$file_name."\0".$control_item);
 5496:                     } else {
 5497:                         if (defined($changed_items{$itemnum})) {
 5498:                             $new_control{$changed_items{$itemnum}} = $now;
 5499:                             push(@deletions,$file_name."\0".$control_item);
 5500:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5501:                         } else {
 5502:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5503:                         }
 5504:                     }
 5505:                 }
 5506:             }
 5507:         }
 5508:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5509:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5510:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5511:         #  remove lock
 5512:         my @del_lock = ($file_name."\0".'locked_access_records');
 5513:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5514:         my ($file,$group);
 5515:         if (&is_course($domain,$user)) {
 5516:             ($group,$file) = split(/\//,$file_name,2);
 5517:         } else {
 5518:             $file = $file_name;
 5519:         }
 5520:         my $sqlresult =
 5521:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5522:                                     $group);
 5523:     } else {
 5524:         $outcome = "error: could not obtain lockfile\n";  
 5525:     }
 5526:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5527: }
 5528: 
 5529: sub make_public_indefinitely {
 5530:     my ($requrl) = @_;
 5531:     my $now = time;
 5532:     my $action = 'activate';
 5533:     my $aclnum = 0;
 5534:     if (&is_portfolio_url($requrl)) {
 5535:         my (undef,$udom,$unum,$file_name,$group) =
 5536:             &parse_portfolio_url($requrl);
 5537:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5538:         my %access_controls = &get_access_controls($current_perms,
 5539:                                                    $group,$file_name);
 5540:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5541:             my ($num,$scope,$end,$start) = 
 5542:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5543:             if ($scope eq 'public') {
 5544:                 if ($start <= $now && $end == 0) {
 5545:                     $action = 'none';
 5546:                 } else {
 5547:                     $action = 'update';
 5548:                     $aclnum = $num;
 5549:                 }
 5550:                 last;
 5551:             }
 5552:         }
 5553:         if ($action eq 'none') {
 5554:              return 'ok';
 5555:         } else {
 5556:             my %changes;
 5557:             my $newend = 0;
 5558:             my $newstart = $now;
 5559:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5560:             $changes{$action}{$newkey} = {
 5561:                 type => 'public',
 5562:                 time => {
 5563:                     start => $newstart,
 5564:                     end   => $newend,
 5565:                 },
 5566:             };
 5567:             my ($outcome,$deloutcome,$new_values,$translation) =
 5568:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5569:             return $outcome;
 5570:         }
 5571:     } else {
 5572:         return 'invalid';
 5573:     }
 5574: }
 5575: 
 5576: #------------------------------------------------------Get Marked as Read Only
 5577: 
 5578: sub get_marked_as_readonly {
 5579:     my ($domain,$user,$what,$group) = @_;
 5580:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5581:     my @readonly_files;
 5582:     my $cmp1=$what;
 5583:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5584:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5585:         if (defined($group)) {
 5586:             if ($file_name !~ m-^\Q$group\E/-) {
 5587:                 next;
 5588:             }
 5589:         }
 5590:         if (ref($value) eq "ARRAY"){
 5591:             foreach my $stored_what (@{$value}) {
 5592:                 my $cmp2=$stored_what;
 5593:                 if (ref($stored_what) eq 'ARRAY') {
 5594:                     $cmp2=join('',@{$stored_what});
 5595:                 }
 5596:                 if ($cmp1 eq $cmp2) {
 5597:                     push(@readonly_files, $file_name);
 5598:                     last;
 5599:                 } elsif (!defined($what)) {
 5600:                     push(@readonly_files, $file_name);
 5601:                     last;
 5602:                 }
 5603:             }
 5604:         }
 5605:     }
 5606:     return @readonly_files;
 5607: }
 5608: #-----------------------------------------------------------Get Marked as Read Only Hash
 5609: 
 5610: sub get_marked_as_readonly_hash {
 5611:     my ($current_permissions,$group,$what) = @_;
 5612:     my %readonly_files;
 5613:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5614:         if (defined($group)) {
 5615:             if ($file_name !~ m-^\Q$group\E/-) {
 5616:                 next;
 5617:             }
 5618:         }
 5619:         if (ref($value) eq "ARRAY"){
 5620:             foreach my $stored_what (@{$value}) {
 5621:                 if (ref($stored_what) eq 'ARRAY') {
 5622:                     foreach my $lock_descriptor(@{$stored_what}) {
 5623:                         if ($lock_descriptor eq 'graded') {
 5624:                             $readonly_files{$file_name} = 'graded';
 5625:                         } elsif ($lock_descriptor eq 'handback') {
 5626:                             $readonly_files{$file_name} = 'handback';
 5627:                         } else {
 5628:                             if (!exists($readonly_files{$file_name})) {
 5629:                                 $readonly_files{$file_name} = 'locked';
 5630:                             }
 5631:                         }
 5632:                     }
 5633:                 } 
 5634:             }
 5635:         } 
 5636:     }
 5637:     return %readonly_files;
 5638: }
 5639: # ------------------------------------------------------------ Unmark as Read Only
 5640: 
 5641: sub unmark_as_readonly {
 5642:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5643:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5644:     my ($domain,$user,$what,$file_name,$group) = @_;
 5645:     $file_name = &declutter_portfile($file_name);
 5646:     my $symb_crs = $what;
 5647:     if (ref($what)) { $symb_crs=join('',@$what); }
 5648:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5649:     my ($tmp)=keys(%current_permissions);
 5650:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5651:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5652:     foreach my $file (@readonly_files) {
 5653: 	my $clean_file = &declutter_portfile($file);
 5654: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5655: 	my $current_locks = $current_permissions{$file};
 5656:         my @new_locks;
 5657:         my @del_keys;
 5658:         if (ref($current_locks) eq "ARRAY"){
 5659:             foreach my $locker (@{$current_locks}) {
 5660:                 my $compare=$locker;
 5661:                 if (ref($locker) eq 'ARRAY') {
 5662:                     $compare=join('',@{$locker});
 5663:                     if ($compare ne $symb_crs) {
 5664:                         push(@new_locks, $locker);
 5665:                     }
 5666:                 }
 5667:             }
 5668:             if (scalar(@new_locks) > 0) {
 5669:                 $current_permissions{$file} = \@new_locks;
 5670:             } else {
 5671:                 push(@del_keys, $file);
 5672:                 &del('file_permissions',\@del_keys, $domain, $user);
 5673:                 delete($current_permissions{$file});
 5674:             }
 5675:         }
 5676:     }
 5677:     &put('file_permissions',\%current_permissions,$domain,$user);
 5678:     return;
 5679: }
 5680: 
 5681: # ------------------------------------------------------------ Directory lister
 5682: 
 5683: sub dirlist {
 5684:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5685: 
 5686:     $uri=~s/^\///;
 5687:     $uri=~s/\/$//;
 5688:     my ($udom, $uname);
 5689:     (undef,$udom,$uname)=split(/\//,$uri);
 5690:     if(defined($userdomain)) {
 5691:         $udom = $userdomain;
 5692:     }
 5693:     if(defined($username)) {
 5694:         $uname = $username;
 5695:     }
 5696: 
 5697:     my $dirRoot = $perlvar{'lonDocRoot'};
 5698:     if(defined($alternateDirectoryRoot)) {
 5699:         $dirRoot = $alternateDirectoryRoot;
 5700:         $dirRoot =~ s/\/$//;
 5701:     }
 5702: 
 5703:     if($udom) {
 5704:         if($uname) {
 5705:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5706: 				 &homeserver($uname,$udom));
 5707:             my @listing_results;
 5708:             if ($listing eq 'unknown_cmd') {
 5709:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5710: 				  &homeserver($uname,$udom));
 5711:                 @listing_results = split(/:/,$listing);
 5712:             } else {
 5713:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5714:             }
 5715:             return @listing_results;
 5716:         } elsif(!defined($alternateDirectoryRoot)) {
 5717:             my %allusers;
 5718: 	    my %servers = &get_servers($udom,'library');
 5719: 	    foreach my $tryserver (keys(%servers)) {
 5720: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5721: 				     $udom, $tryserver);
 5722: 		my @listing_results;
 5723: 		if ($listing eq 'unknown_cmd') {
 5724: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5725: 				      $udom, $tryserver);
 5726: 		    @listing_results = split(/:/,$listing);
 5727: 		} else {
 5728: 		    @listing_results =
 5729: 			map { &unescape($_); } split(/:/,$listing);
 5730: 		}
 5731: 		if ($listing_results[0] ne 'no_such_dir' && 
 5732: 		    $listing_results[0] ne 'empty'       &&
 5733: 		    $listing_results[0] ne 'con_lost') {
 5734: 		    foreach my $line (@listing_results) {
 5735: 			my ($entry) = split(/&/,$line,2);
 5736: 			$allusers{$entry} = 1;
 5737: 		    }
 5738: 		}
 5739:             }
 5740:             my $alluserstr='';
 5741:             foreach my $user (sort(keys(%allusers))) {
 5742:                 $alluserstr.=$user.'&user:';
 5743:             }
 5744:             $alluserstr=~s/:$//;
 5745:             return split(/:/,$alluserstr);
 5746:         } else {
 5747:             return ('missing user name');
 5748:         }
 5749:     } elsif(!defined($alternateDirectoryRoot)) {
 5750:         my @all_domains = sort(&all_domains());
 5751:          foreach my $domain (@all_domains) {
 5752:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5753:          }
 5754:          return @all_domains;
 5755:      } else {
 5756:         return ('missing domain');
 5757:     }
 5758: }
 5759: 
 5760: # --------------------------------------------- GetFileTimestamp
 5761: # This function utilizes dirlist and returns the date stamp for
 5762: # when it was last modified.  It will also return an error of -1
 5763: # if an error occurs
 5764: 
 5765: ##
 5766: ## FIXME: This subroutine assumes its caller knows something about the
 5767: ## directory structure of the home server for the student ($root).
 5768: ## Not a good assumption to make.  Since this is for looking up files
 5769: ## in user directories, the full path should be constructed by lond, not
 5770: ## whatever machine we request data from.
 5771: ##
 5772: sub GetFileTimestamp {
 5773:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5774:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5775:     $studentName   = &LONCAPA::clean_username($studentName);
 5776:     my $subdir=$studentName.'__';
 5777:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5778:     my $proname="$studentDomain/$subdir/$studentName";
 5779:     $proname .= '/'.$filename;
 5780:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5781:                                               $studentName, $root);
 5782:     my @stats = split('&', $fileStat);
 5783:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5784:         # @stats contains first the filename, then the stat output
 5785:         return $stats[10]; # so this is 10 instead of 9.
 5786:     } else {
 5787:         return -1;
 5788:     }
 5789: }
 5790: 
 5791: sub stat_file {
 5792:     my ($uri) = @_;
 5793:     $uri = &clutter_with_no_wrapper($uri);
 5794: 
 5795:     my ($udom,$uname,$file,$dir);
 5796:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5797: 	($udom,$uname,$file) =
 5798: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5799: 	$file = 'userfiles/'.$file;
 5800: 	$dir = &propath($udom,$uname);
 5801:     }
 5802:     if ($uri =~ m-^/res/-) {
 5803: 	($udom,$uname) = 
 5804: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5805: 	$file = $uri;
 5806:     }
 5807: 
 5808:     if (!$udom || !$uname || !$file) {
 5809: 	# unable to handle the uri
 5810: 	return ();
 5811:     }
 5812: 
 5813:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5814:     my @stats = split('&', $result);
 5815:     
 5816:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5817: 	shift(@stats); #filename is first
 5818: 	return @stats;
 5819:     }
 5820:     return ();
 5821: }
 5822: 
 5823: # -------------------------------------------------------- Value of a Condition
 5824: 
 5825: # gets the value of a specific preevaluated condition
 5826: #    stored in the string  $env{user.state.<cid>}
 5827: # or looks up a condition reference in the bighash and if if hasn't
 5828: # already been evaluated recurses into docondval to get the value of
 5829: # the condition, then memoizing it to 
 5830: #   $env{user.state.<cid>.<condition>}
 5831: sub directcondval {
 5832:     my $number=shift;
 5833:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5834: 	&Apache::lonuserstate::evalstate();
 5835:     }
 5836:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5837: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5838:     } elsif ($number =~ /^_/) {
 5839: 	my $sub_condition;
 5840: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5841: 		&GDBM_READER(),0640)) {
 5842: 	    $sub_condition=$bighash{'conditions'.$number};
 5843: 	    untie(%bighash);
 5844: 	}
 5845: 	my $value = &docondval($sub_condition);
 5846: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5847: 	return $value;
 5848:     }
 5849:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5850:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5851:     } else {
 5852:        return 2;
 5853:     }
 5854: }
 5855: 
 5856: # get the collection of conditions for this resource
 5857: sub condval {
 5858:     my $condidx=shift;
 5859:     my $allpathcond='';
 5860:     foreach my $cond (split(/\|/,$condidx)) {
 5861: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5862: 	    $allpathcond.=
 5863: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5864: 	}
 5865:     }
 5866:     $allpathcond=~s/\|$//;
 5867:     return &docondval($allpathcond);
 5868: }
 5869: 
 5870: #evaluates an expression of conditions
 5871: sub docondval {
 5872:     my ($allpathcond) = @_;
 5873:     my $result=0;
 5874:     if ($env{'request.course.id'}
 5875: 	&& defined($allpathcond)) {
 5876: 	my $operand='|';
 5877: 	my @stack;
 5878: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5879: 	    if ($chunk eq '(') {
 5880: 		push @stack,($operand,$result);
 5881: 	    } elsif ($chunk eq ')') {
 5882: 		my $before=pop @stack;
 5883: 		if (pop @stack eq '&') {
 5884: 		    $result=$result>$before?$before:$result;
 5885: 		} else {
 5886: 		    $result=$result>$before?$result:$before;
 5887: 		}
 5888: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5889: 		$operand=$chunk;
 5890: 	    } else {
 5891: 		my $new=directcondval($chunk);
 5892: 		if ($operand eq '&') {
 5893: 		    $result=$result>$new?$new:$result;
 5894: 		} else {
 5895: 		    $result=$result>$new?$result:$new;
 5896: 		}
 5897: 	    }
 5898: 	}
 5899:     }
 5900:     return $result;
 5901: }
 5902: 
 5903: # ---------------------------------------------------- Devalidate courseresdata
 5904: 
 5905: sub devalidatecourseresdata {
 5906:     my ($coursenum,$coursedomain)=@_;
 5907:     my $hashid=$coursenum.':'.$coursedomain;
 5908:     &devalidate_cache_new('courseres',$hashid);
 5909: }
 5910: 
 5911: 
 5912: # --------------------------------------------------- Course Resourcedata Query
 5913: 
 5914: sub get_courseresdata {
 5915:     my ($coursenum,$coursedomain)=@_;
 5916:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5917:     my $hashid=$coursenum.':'.$coursedomain;
 5918:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5919:     my %dumpreply;
 5920:     unless (defined($cached)) {
 5921: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5922: 	$result=\%dumpreply;
 5923: 	my ($tmp) = keys(%dumpreply);
 5924: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5925: 	    &do_cache_new('courseres',$hashid,$result,600);
 5926: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5927: 	    return $tmp;
 5928: 	} elsif ($tmp =~ /^(error)/) {
 5929: 	    $result=undef;
 5930: 	    &do_cache_new('courseres',$hashid,$result,600);
 5931: 	}
 5932:     }
 5933:     return $result;
 5934: }
 5935: 
 5936: sub devalidateuserresdata {
 5937:     my ($uname,$udom)=@_;
 5938:     my $hashid="$udom:$uname";
 5939:     &devalidate_cache_new('userres',$hashid);
 5940: }
 5941: 
 5942: sub get_userresdata {
 5943:     my ($uname,$udom)=@_;
 5944:     #most student don\'t have any data set, check if there is some data
 5945:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5946: 
 5947:     my $hashid="$udom:$uname";
 5948:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5949:     if (!defined($cached)) {
 5950: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5951: 	$result=\%resourcedata;
 5952: 	&do_cache_new('userres',$hashid,$result,600);
 5953:     }
 5954:     my ($tmp)=keys(%$result);
 5955:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5956: 	return $result;
 5957:     }
 5958:     #error 2 occurs when the .db doesn't exist
 5959:     if ($tmp!~/error: 2 /) {
 5960: 	&logthis("<font color=\"blue\">WARNING:".
 5961: 		 " Trying to get resource data for ".
 5962: 		 $uname." at ".$udom.": ".
 5963: 		 $tmp."</font>");
 5964:     } elsif ($tmp=~/error: 2 /) {
 5965: 	#&EXT_cache_set($udom,$uname);
 5966: 	&do_cache_new('userres',$hashid,undef,600);
 5967: 	undef($tmp); # not really an error so don't send it back
 5968:     }
 5969:     return $tmp;
 5970: }
 5971: 
 5972: sub resdata {
 5973:     my ($name,$domain,$type,@which)=@_;
 5974:     my $result;
 5975:     if ($type eq 'course') {
 5976: 	$result=&get_courseresdata($name,$domain);
 5977:     } elsif ($type eq 'user') {
 5978: 	$result=&get_userresdata($name,$domain);
 5979:     }
 5980:     if (!ref($result)) { return $result; }    
 5981:     foreach my $item (@which) {
 5982: 	if (defined($result->{$item})) {
 5983: 	    return $result->{$item};
 5984: 	}
 5985:     }
 5986:     return undef;
 5987: }
 5988: 
 5989: #
 5990: # EXT resource caching routines
 5991: #
 5992: 
 5993: sub clear_EXT_cache_status {
 5994:     &delenv('cache.EXT.');
 5995: }
 5996: 
 5997: sub EXT_cache_status {
 5998:     my ($target_domain,$target_user) = @_;
 5999:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6000:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6001:         # We know already the user has no data
 6002:         return 1;
 6003:     } else {
 6004:         return 0;
 6005:     }
 6006: }
 6007: 
 6008: sub EXT_cache_set {
 6009:     my ($target_domain,$target_user) = @_;
 6010:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6011:     #&appenv($cachename => time);
 6012: }
 6013: 
 6014: # --------------------------------------------------------- Value of a Variable
 6015: sub EXT {
 6016: 
 6017:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6018:     unless ($varname) { return ''; }
 6019:     #get real user name/domain, courseid and symb
 6020:     my $courseid;
 6021:     my $publicuser;
 6022:     if ($symbparm) {
 6023: 	$symbparm=&get_symb_from_alias($symbparm);
 6024:     }
 6025:     if (!($uname && $udom)) {
 6026:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6027:       if (!$symbparm) {	$symbparm=$cursymb; }
 6028:     } else {
 6029: 	$courseid=$env{'request.course.id'};
 6030:     }
 6031:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6032:     my $rest;
 6033:     if (defined($therest[0])) {
 6034:        $rest=join('.',@therest);
 6035:     } else {
 6036:        $rest='';
 6037:     }
 6038: 
 6039:     my $qualifierrest=$qualifier;
 6040:     if ($rest) { $qualifierrest.='.'.$rest; }
 6041:     my $spacequalifierrest=$space;
 6042:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6043:     if ($realm eq 'user') {
 6044: # --------------------------------------------------------------- user.resource
 6045: 	if ($space eq 'resource') {
 6046: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6047: 		  || defined($Apache::lonhomework::parsing_a_task))
 6048: 		 &&
 6049: 		 ($symbparm eq &symbread()) ) {	
 6050: 		# if we are in the middle of processing the resource the
 6051: 		# get the value we are planning on committing
 6052:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6053:                     return $Apache::lonhomework::results{$qualifierrest};
 6054:                 } else {
 6055:                     return $Apache::lonhomework::history{$qualifierrest};
 6056:                 }
 6057: 	    } else {
 6058: 		my %restored;
 6059: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6060: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6061: 		} else {
 6062: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6063: 		}
 6064: 		return $restored{$qualifierrest};
 6065: 	    }
 6066: # ----------------------------------------------------------------- user.access
 6067:         } elsif ($space eq 'access') {
 6068: 	    # FIXME - not supporting calls for a specific user
 6069:             return &allowed($qualifier,$rest);
 6070: # ------------------------------------------ user.preferences, user.environment
 6071:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6072: 	    if (($uname eq $env{'user.name'}) &&
 6073: 		($udom eq $env{'user.domain'})) {
 6074: 		return $env{join('.',('environment',$qualifierrest))};
 6075: 	    } else {
 6076: 		my %returnhash;
 6077: 		if (!$publicuser) {
 6078: 		    %returnhash=&userenvironment($udom,$uname,
 6079: 						 $qualifierrest);
 6080: 		}
 6081: 		return $returnhash{$qualifierrest};
 6082: 	    }
 6083: # ----------------------------------------------------------------- user.course
 6084:         } elsif ($space eq 'course') {
 6085: 	    # FIXME - not supporting calls for a specific user
 6086:             return $env{join('.',('request.course',$qualifier))};
 6087: # ------------------------------------------------------------------- user.role
 6088:         } elsif ($space eq 'role') {
 6089: 	    # FIXME - not supporting calls for a specific user
 6090:             my ($role,$where)=split(/\./,$env{'request.role'});
 6091:             if ($qualifier eq 'value') {
 6092: 		return $role;
 6093:             } elsif ($qualifier eq 'extent') {
 6094:                 return $where;
 6095:             }
 6096: # ----------------------------------------------------------------- user.domain
 6097:         } elsif ($space eq 'domain') {
 6098:             return $udom;
 6099: # ------------------------------------------------------------------- user.name
 6100:         } elsif ($space eq 'name') {
 6101:             return $uname;
 6102: # ---------------------------------------------------- Any other user namespace
 6103:         } else {
 6104: 	    my %reply;
 6105: 	    if (!$publicuser) {
 6106: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6107: 	    }
 6108: 	    return $reply{$qualifierrest};
 6109:         }
 6110:     } elsif ($realm eq 'query') {
 6111: # ---------------------------------------------- pull stuff out of query string
 6112:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6113: 						[$spacequalifierrest]);
 6114: 	return $env{'form.'.$spacequalifierrest}; 
 6115:    } elsif ($realm eq 'request') {
 6116: # ------------------------------------------------------------- request.browser
 6117:         if ($space eq 'browser') {
 6118: 	    if ($qualifier eq 'textremote') {
 6119: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6120: 		    return 1;
 6121: 		} else {
 6122: 		    return 0;
 6123: 		}
 6124: 	    } else {
 6125: 		return $env{'browser.'.$qualifier};
 6126: 	    }
 6127: # ------------------------------------------------------------ request.filename
 6128:         } else {
 6129:             return $env{'request.'.$spacequalifierrest};
 6130:         }
 6131:     } elsif ($realm eq 'course') {
 6132: # ---------------------------------------------------------- course.description
 6133:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6134:     } elsif ($realm eq 'resource') {
 6135: 
 6136: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6137: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6138: 	}
 6139: 
 6140: 	if ($space eq 'title') {
 6141: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6142: 	    return &gettitle($symbparm);
 6143: 	}
 6144: 	
 6145: 	if ($space eq 'map') {
 6146: 	    my ($map) = &decode_symb($symbparm);
 6147: 	    return &symbread($map);
 6148: 	}
 6149: 
 6150: 	my ($section, $group, @groups);
 6151: 	my ($courselevelm,$courselevel);
 6152: 	if ($symbparm && defined($courseid) && 
 6153: 	    $courseid eq $env{'request.course.id'}) {
 6154: 
 6155: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6156: 
 6157: # ----------------------------------------------------- Cascading lookup scheme
 6158: 	    my $symbp=$symbparm;
 6159: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6160: 
 6161: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6162: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6163: 
 6164: 	    if (($env{'user.name'} eq $uname) &&
 6165: 		($env{'user.domain'} eq $udom)) {
 6166: 		$section=$env{'request.course.sec'};
 6167:                 @groups = split(/:/,$env{'request.course.groups'});  
 6168:                 @groups=&sort_course_groups($courseid,@groups); 
 6169: 	    } else {
 6170: 		if (! defined($usection)) {
 6171: 		    $section=&getsection($udom,$uname,$courseid);
 6172: 		} else {
 6173: 		    $section = $usection;
 6174: 		}
 6175:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6176: 	    }
 6177: 
 6178: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6179: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6180: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6181: 
 6182: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6183: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6184: 	    $courselevelm=$courseid.'.'.$mapparm;
 6185: 
 6186: # ----------------------------------------------------------- first, check user
 6187: 
 6188: 	    my $userreply=&resdata($uname,$udom,'user',
 6189: 				       ($courselevelr,$courselevelm,
 6190: 					$courselevel));
 6191: 	    if (defined($userreply)) { return $userreply; }
 6192: 
 6193: # ------------------------------------------------ second, check some of course
 6194:             my $coursereply;
 6195:             if (@groups > 0) {
 6196:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6197:                                        $mapparm,$spacequalifierrest);
 6198:                 if (defined($coursereply)) { return $coursereply; }
 6199:             }
 6200: 
 6201: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6202: 				     $env{'course.'.$courseid.'.domain'},
 6203: 				     'course',
 6204: 				     ($seclevelr,$seclevelm,$seclevel,
 6205: 				      $courselevelr));
 6206: 	    if (defined($coursereply)) { return $coursereply; }
 6207: 
 6208: # ------------------------------------------------------ third, check map parms
 6209: 	    my %parmhash=();
 6210: 	    my $thisparm='';
 6211: 	    if (tie(%parmhash,'GDBM_File',
 6212: 		    $env{'request.course.fn'}.'_parms.db',
 6213: 		    &GDBM_READER(),0640)) {
 6214: 		$thisparm=$parmhash{$symbparm};
 6215: 		untie(%parmhash);
 6216: 	    }
 6217: 	    if ($thisparm) { return $thisparm; }
 6218: 	}
 6219: # ------------------------------------------ fourth, look in resource metadata
 6220: 
 6221: 	$spacequalifierrest=~s/\./\_/;
 6222: 	my $filename;
 6223: 	if (!$symbparm) { $symbparm=&symbread(); }
 6224: 	if ($symbparm) {
 6225: 	    $filename=(&decode_symb($symbparm))[2];
 6226: 	} else {
 6227: 	    $filename=$env{'request.filename'};
 6228: 	}
 6229: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6230: 	if (defined($metadata)) { return $metadata; }
 6231: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6232: 	if (defined($metadata)) { return $metadata; }
 6233: 
 6234: # ---------------------------------------------- fourth, look in rest pf course
 6235: 	if ($symbparm && defined($courseid) && 
 6236: 	    $courseid eq $env{'request.course.id'}) {
 6237: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6238: 				     $env{'course.'.$courseid.'.domain'},
 6239: 				     'course',
 6240: 				     ($courselevelm,$courselevel));
 6241: 	    if (defined($coursereply)) { return $coursereply; }
 6242: 	}
 6243: # ------------------------------------------------------------------ Cascade up
 6244: 	unless ($space eq '0') {
 6245: 	    my @parts=split(/_/,$space);
 6246: 	    my $id=pop(@parts);
 6247: 	    my $part=join('_',@parts);
 6248: 	    if ($part eq '') { $part='0'; }
 6249: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6250: 				 $symbparm,$udom,$uname,$section,1);
 6251: 	    if (defined($partgeneral)) { return $partgeneral; }
 6252: 	}
 6253: 	if ($recurse) { return undef; }
 6254: 	my $pack_def=&packages_tab_default($filename,$varname);
 6255: 	if (defined($pack_def)) { return $pack_def; }
 6256: 
 6257: # ---------------------------------------------------- Any other user namespace
 6258:     } elsif ($realm eq 'environment') {
 6259: # ----------------------------------------------------------------- environment
 6260: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6261: 	    return $env{'environment.'.$spacequalifierrest};
 6262: 	} else {
 6263: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6264: 		return '';
 6265: 	    }
 6266: 	    my %returnhash=&userenvironment($udom,$uname,
 6267: 					    $spacequalifierrest);
 6268: 	    return $returnhash{$spacequalifierrest};
 6269: 	}
 6270:     } elsif ($realm eq 'system') {
 6271: # ----------------------------------------------------------------- system.time
 6272: 	if ($space eq 'time') {
 6273: 	    return time;
 6274:         }
 6275:     } elsif ($realm eq 'server') {
 6276: # ----------------------------------------------------------------- system.time
 6277: 	if ($space eq 'name') {
 6278: 	    return $ENV{'SERVER_NAME'};
 6279:         }
 6280:     }
 6281:     return '';
 6282: }
 6283: 
 6284: sub check_group_parms {
 6285:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6286:     my @groupitems = ();
 6287:     my $resultitem;
 6288:     my @levels = ($symbparm,$mapparm,$what);
 6289:     foreach my $group (@{$groups}) {
 6290:         foreach my $level (@levels) {
 6291:              my $item = $courseid.'.['.$group.'].'.$level;
 6292:              push(@groupitems,$item);
 6293:         }
 6294:     }
 6295:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6296:                             $env{'course.'.$courseid.'.domain'},
 6297:                                      'course',@groupitems);
 6298:     return $coursereply;
 6299: }
 6300: 
 6301: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6302:     my ($courseid,@groups) = @_;
 6303:     @groups = sort(@groups);
 6304:     return @groups;
 6305: }
 6306: 
 6307: sub packages_tab_default {
 6308:     my ($uri,$varname)=@_;
 6309:     my (undef,$part,$name)=split(/\./,$varname);
 6310: 
 6311:     my (@extension,@specifics,$do_default);
 6312:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6313: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6314: 	if ($pack_type eq 'default') {
 6315: 	    $do_default=1;
 6316: 	} elsif ($pack_type eq 'extension') {
 6317: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6318: 	} elsif ($pack_part eq $part) {
 6319: 	    # only look at packages defaults for packages that this id is
 6320: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6321: 	}
 6322:     }
 6323:     # first look for a package that matches the requested part id
 6324:     foreach my $package (@specifics) {
 6325: 	my (undef,$pack_type,$pack_part)=@{$package};
 6326: 	next if ($pack_part ne $part);
 6327: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6328: 	    return $packagetab{"$pack_type&$name&default"};
 6329: 	}
 6330:     }
 6331:     # look for any possible matching non extension_ package
 6332:     foreach my $package (@specifics) {
 6333: 	my (undef,$pack_type,$pack_part)=@{$package};
 6334: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6335: 	    return $packagetab{"$pack_type&$name&default"};
 6336: 	}
 6337: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6338: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6339: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6340: 	}
 6341:     }
 6342:     # look for any posible extension_ match
 6343:     foreach my $package (@extension) {
 6344: 	my ($package,$pack_type)=@{$package};
 6345: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6346: 	    return $packagetab{"$pack_type&$name&default"};
 6347: 	}
 6348: 	if (defined($packagetab{$package."&$name&default"})) {
 6349: 	    return $packagetab{$package."&$name&default"};
 6350: 	}
 6351:     }
 6352:     # look for a global default setting
 6353:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6354: 	return $packagetab{"default&$name&default"};
 6355:     }
 6356:     return undef;
 6357: }
 6358: 
 6359: sub add_prefix_and_part {
 6360:     my ($prefix,$part)=@_;
 6361:     my $keyroot;
 6362:     if (defined($prefix) && $prefix !~ /^__/) {
 6363: 	# prefix that has a part already
 6364: 	$keyroot=$prefix;
 6365:     } elsif (defined($prefix)) {
 6366: 	# prefix that is missing a part
 6367: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6368:     } else {
 6369: 	# no prefix at all
 6370: 	if (defined($part)) { $keyroot='_'.$part; }
 6371:     }
 6372:     return $keyroot;
 6373: }
 6374: 
 6375: # ---------------------------------------------------------------- Get metadata
 6376: 
 6377: my %metaentry;
 6378: sub metadata {
 6379:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6380:     $uri=&declutter($uri);
 6381:     # if it is a non metadata possible uri return quickly
 6382:     if (($uri eq '') || 
 6383: 	(($uri =~ m|^/*adm/|) && 
 6384: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6385:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6386: 	($uri =~ m|home/$match_username/public_html/|)) {
 6387: 	return undef;
 6388:     }
 6389:     my $filename=$uri;
 6390:     $uri=~s/\.meta$//;
 6391: #
 6392: # Is the metadata already cached?
 6393: # Look at timestamp of caching
 6394: # Everything is cached by the main uri, libraries are never directly cached
 6395: #
 6396:     if (!defined($liburi)) {
 6397: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6398: 	if (defined($cached)) { return $result->{':'.$what}; }
 6399:     }
 6400:     {
 6401: #
 6402: # Is this a recursive call for a library?
 6403: #
 6404: #	if (! exists($metacache{$uri})) {
 6405: #	    $metacache{$uri}={};
 6406: #	}
 6407:         if ($liburi) {
 6408: 	    $liburi=&declutter($liburi);
 6409:             $filename=$liburi;
 6410:         } else {
 6411: 	    &devalidate_cache_new('meta',$uri);
 6412: 	    undef(%metaentry);
 6413: 	}
 6414:         my %metathesekeys=();
 6415:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6416: 	my $metastring;
 6417: 	if ($uri !~ m -^(editupload)/-) {
 6418: 	    my $file=&filelocation('',&clutter($filename));
 6419: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6420: 	    $metastring=&getfile($file);
 6421: 	}
 6422:         my $parser=HTML::LCParser->new(\$metastring);
 6423:         my $token;
 6424:         undef %metathesekeys;
 6425:         while ($token=$parser->get_token) {
 6426: 	    if ($token->[0] eq 'S') {
 6427: 		if (defined($token->[2]->{'package'})) {
 6428: #
 6429: # This is a package - get package info
 6430: #
 6431: 		    my $package=$token->[2]->{'package'};
 6432: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6433: 		    if (defined($token->[2]->{'id'})) { 
 6434: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6435: 		    }
 6436: 		    if ($metaentry{':packages'}) {
 6437: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6438: 		    } else {
 6439: 			$metaentry{':packages'}=$package.$keyroot;
 6440: 		    }
 6441: 		    foreach my $pack_entry (keys(%packagetab)) {
 6442: 			my $part=$keyroot;
 6443: 			$part=~s/^\_//;
 6444: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6445: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6446: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6447: 			    # ignore package.tab specified default values
 6448:                             # here &package_tab_default() will fetch those
 6449: 			    if ($subp eq 'default') { next; }
 6450: 			    my $value=$packagetab{$pack_entry};
 6451: 			    my $unikey;
 6452: 			    if ($pack =~ /_0$/) {
 6453: 				$unikey='parameter_0_'.$name;
 6454: 				$part=0;
 6455: 			    } else {
 6456: 				$unikey='parameter'.$keyroot.'_'.$name;
 6457: 			    }
 6458: 			    if ($subp eq 'display') {
 6459: 				$value.=' [Part: '.$part.']';
 6460: 			    }
 6461: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6462: 			    $metathesekeys{$unikey}=1;
 6463: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6464: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6465: 			    }
 6466: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6467: 				$metaentry{':'.$unikey}=
 6468: 				    $metaentry{':'.$unikey.'.default'};
 6469: 			    }
 6470: 			}
 6471: 		    }
 6472: 		} else {
 6473: #
 6474: # This is not a package - some other kind of start tag
 6475: #
 6476: 		    my $entry=$token->[1];
 6477: 		    my $unikey;
 6478: 		    if ($entry eq 'import') {
 6479: 			$unikey='';
 6480: 		    } else {
 6481: 			$unikey=$entry;
 6482: 		    }
 6483: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6484: 
 6485: 		    if (defined($token->[2]->{'id'})) { 
 6486: 			$unikey.='_'.$token->[2]->{'id'}; 
 6487: 		    }
 6488: 
 6489: 		    if ($entry eq 'import') {
 6490: #
 6491: # Importing a library here
 6492: #
 6493: 			if ($depthcount<20) {
 6494: 			    my $location=$parser->get_text('/import');
 6495: 			    my $dir=$filename;
 6496: 			    $dir=~s|[^/]*$||;
 6497: 			    $location=&filelocation($dir,$location);
 6498: 			    my $metadata = 
 6499: 				&metadata($uri,'keys', $location,$unikey,
 6500: 					  $depthcount+1);
 6501: 			    foreach my $meta (split(',',$metadata)) {
 6502: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6503: 				$metathesekeys{$meta}=1;
 6504: 			    }
 6505: 			}
 6506: 		    } else { 
 6507: 			
 6508: 			if (defined($token->[2]->{'name'})) { 
 6509: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6510: 			}
 6511: 			$metathesekeys{$unikey}=1;
 6512: 			foreach my $param (@{$token->[3]}) {
 6513: 			    $metaentry{':'.$unikey.'.'.$param} =
 6514: 				$token->[2]->{$param};
 6515: 			}
 6516: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6517: 			my $default=$metaentry{':'.$unikey.'.default'};
 6518: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6519: 		 # only ws inside the tag, and not in default, so use default
 6520: 		 # as value
 6521: 			    $metaentry{':'.$unikey}=$default;
 6522: 			} else {
 6523: 		  # either something interesting inside the tag or default
 6524:                   # uninteresting
 6525: 			    $metaentry{':'.$unikey}=$internaltext;
 6526: 			}
 6527: # end of not-a-package not-a-library import
 6528: 		    }
 6529: # end of not-a-package start tag
 6530: 		}
 6531: # the next is the end of "start tag"
 6532: 	    }
 6533: 	}
 6534: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6535: 	foreach my $key (keys(%packagetab)) {
 6536: 	    #no specific packages #how's our extension
 6537: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6538: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6539: 					 \%metathesekeys);
 6540: 	}
 6541: 	if (!exists($metaentry{':packages'})) {
 6542: 	    foreach my $key (keys(%packagetab)) {
 6543: 		#no specific packages well let's get default then
 6544: 		if ($key!~/^default&/) { next; }
 6545: 		&metadata_create_package_def($uri,$key,'default',
 6546: 					     \%metathesekeys);
 6547: 	    }
 6548: 	}
 6549: # are there custom rights to evaluate
 6550: 	if ($metaentry{':copyright'} eq 'custom') {
 6551: 
 6552:     #
 6553:     # Importing a rights file here
 6554:     #
 6555: 	    unless ($depthcount) {
 6556: 		my $location=$metaentry{':customdistributionfile'};
 6557: 		my $dir=$filename;
 6558: 		$dir=~s|[^/]*$||;
 6559: 		$location=&filelocation($dir,$location);
 6560: 		my $rights_metadata =
 6561: 		    &metadata($uri,'keys',$location,'_rights',
 6562: 			      $depthcount+1);
 6563: 		foreach my $rights (split(',',$rights_metadata)) {
 6564: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6565: 		    $metathesekeys{$rights}=1;
 6566: 		}
 6567: 	    }
 6568: 	}
 6569: 	# uniqifiy package listing
 6570: 	my %seen;
 6571: 	my @uniq_packages =
 6572: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6573: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6574: 
 6575: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6576: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6577: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6578: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6579: # this is the end of "was not already recently cached
 6580:     }
 6581:     return $metaentry{':'.$what};
 6582: }
 6583: 
 6584: sub metadata_create_package_def {
 6585:     my ($uri,$key,$package,$metathesekeys)=@_;
 6586:     my ($pack,$name,$subp)=split(/\&/,$key);
 6587:     if ($subp eq 'default') { next; }
 6588:     
 6589:     if (defined($metaentry{':packages'})) {
 6590: 	$metaentry{':packages'}.=','.$package;
 6591:     } else {
 6592: 	$metaentry{':packages'}=$package;
 6593:     }
 6594:     my $value=$packagetab{$key};
 6595:     my $unikey;
 6596:     $unikey='parameter_0_'.$name;
 6597:     $metaentry{':'.$unikey.'.part'}=0;
 6598:     $$metathesekeys{$unikey}=1;
 6599:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6600: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6601:     }
 6602:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6603: 	$metaentry{':'.$unikey}=
 6604: 	    $metaentry{':'.$unikey.'.default'};
 6605:     }
 6606: }
 6607: 
 6608: sub metadata_generate_part0 {
 6609:     my ($metadata,$metacache,$uri) = @_;
 6610:     my %allnames;
 6611:     foreach my $metakey (keys(%$metadata)) {
 6612: 	if ($metakey=~/^parameter\_(.*)/) {
 6613: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6614: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6615: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6616: 	    $allnames{$name}=$part;
 6617: 	  }
 6618: 	}
 6619:     }
 6620:     foreach my $name (keys(%allnames)) {
 6621:       $$metadata{"parameter_0_$name"}=1;
 6622:       my $key=":parameter_0_$name";
 6623:       $$metacache{"$key.part"}='0';
 6624:       $$metacache{"$key.name"}=$name;
 6625:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6626: 					   $allnames{$name}.'_'.$name.
 6627: 					   '.type'};
 6628:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6629: 			     '.display'};
 6630:       my $expr='[Part: '.$allnames{$name}.']';
 6631:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6632:       $$metacache{"$key.display"}=$olddis;
 6633:     }
 6634: }
 6635: 
 6636: # ------------------------------------------------------ Devalidate title cache
 6637: 
 6638: sub devalidate_title_cache {
 6639:     my ($url)=@_;
 6640:     if (!$env{'request.course.id'}) { return; }
 6641:     my $symb=&symbread($url);
 6642:     if (!$symb) { return; }
 6643:     my $key=$env{'request.course.id'}."\0".$symb;
 6644:     &devalidate_cache_new('title',$key);
 6645: }
 6646: 
 6647: # ------------------------------------------------- Get the title of a resource
 6648: 
 6649: sub gettitle {
 6650:     my $urlsymb=shift;
 6651:     my $symb=&symbread($urlsymb);
 6652:     if ($symb) {
 6653: 	my $key=$env{'request.course.id'}."\0".$symb;
 6654: 	my ($result,$cached)=&is_cached_new('title',$key);
 6655: 	if (defined($cached)) { 
 6656: 	    return $result;
 6657: 	}
 6658: 	my ($map,$resid,$url)=&decode_symb($symb);
 6659: 	my $title='';
 6660: 	my %bighash;
 6661: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6662: 		&GDBM_READER(),0640)) {
 6663: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6664: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6665: 	    untie %bighash;
 6666: 	}
 6667: 	$title=~s/\&colon\;/\:/gs;
 6668: 	if ($title) {
 6669: 	    return &do_cache_new('title',$key,$title,600);
 6670: 	}
 6671: 	$urlsymb=$url;
 6672:     }
 6673:     my $title=&metadata($urlsymb,'title');
 6674:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6675:     return $title;
 6676: }
 6677: 
 6678: sub get_slot {
 6679:     my ($which,$cnum,$cdom)=@_;
 6680:     if (!$cnum || !$cdom) {
 6681: 	(undef,my $courseid)=&whichuser();
 6682: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6683: 	$cnum=$env{'course.'.$courseid.'.num'};
 6684:     }
 6685:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6686:     my %slotinfo;
 6687:     if (exists($remembered{$key})) {
 6688: 	$slotinfo{$which} = $remembered{$key};
 6689:     } else {
 6690: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6691: 	&Apache::lonhomework::showhash(%slotinfo);
 6692: 	my ($tmp)=keys(%slotinfo);
 6693: 	if ($tmp=~/^error:/) { return (); }
 6694: 	$remembered{$key} = $slotinfo{$which};
 6695:     }
 6696:     if (ref($slotinfo{$which}) eq 'HASH') {
 6697: 	return %{$slotinfo{$which}};
 6698:     }
 6699:     return $slotinfo{$which};
 6700: }
 6701: # ------------------------------------------------- Update symbolic store links
 6702: 
 6703: sub symblist {
 6704:     my ($mapname,%newhash)=@_;
 6705:     $mapname=&deversion(&declutter($mapname));
 6706:     my %hash;
 6707:     if (($env{'request.course.fn'}) && (%newhash)) {
 6708:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6709:                       &GDBM_WRCREAT(),0640)) {
 6710: 	    foreach my $url (keys %newhash) {
 6711: 		next if ($url eq 'last_known'
 6712: 			 && $env{'form.no_update_last_known'});
 6713: 		$hash{declutter($url)}=&encode_symb($mapname,
 6714: 						    $newhash{$url}->[1],
 6715: 						    $newhash{$url}->[0]);
 6716:             }
 6717:             if (untie(%hash)) {
 6718: 		return 'ok';
 6719:             }
 6720:         }
 6721:     }
 6722:     return 'error';
 6723: }
 6724: 
 6725: # --------------------------------------------------------------- Verify a symb
 6726: 
 6727: sub symbverify {
 6728:     my ($symb,$thisurl)=@_;
 6729:     my $thisfn=$thisurl;
 6730:     $thisfn=&declutter($thisfn);
 6731: # direct jump to resource in page or to a sequence - will construct own symbs
 6732:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6733: # check URL part
 6734:     my ($map,$resid,$url)=&decode_symb($symb);
 6735: 
 6736:     unless ($url eq $thisfn) { return 0; }
 6737: 
 6738:     $symb=&symbclean($symb);
 6739:     $thisurl=&deversion($thisurl);
 6740:     $thisfn=&deversion($thisfn);
 6741: 
 6742:     my %bighash;
 6743:     my $okay=0;
 6744: 
 6745:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6746:                             &GDBM_READER(),0640)) {
 6747:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6748:         unless ($ids) { 
 6749:            $ids=$bighash{'ids_/'.$thisurl};
 6750:         }
 6751:         if ($ids) {
 6752: # ------------------------------------------------------------------- Has ID(s)
 6753: 	    foreach my $id (split(/\,/,$ids)) {
 6754: 	       my ($mapid,$resid)=split(/\./,$id);
 6755:                if (
 6756:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6757:    eq $symb) { 
 6758: 		   if (($env{'request.role.adv'}) ||
 6759: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6760: 		       $okay=1; 
 6761: 		   }
 6762: 	       }
 6763: 	   }
 6764:         }
 6765: 	untie(%bighash);
 6766:     }
 6767:     return $okay;
 6768: }
 6769: 
 6770: # --------------------------------------------------------------- Clean-up symb
 6771: 
 6772: sub symbclean {
 6773:     my $symb=shift;
 6774:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6775: # remove version from map
 6776:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6777: 
 6778: # remove version from URL
 6779:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6780: 
 6781: # remove wrapper
 6782: 
 6783:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6784:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6785:     return $symb;
 6786: }
 6787: 
 6788: # ---------------------------------------------- Split symb to find map and url
 6789: 
 6790: sub encode_symb {
 6791:     my ($map,$resid,$url)=@_;
 6792:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6793: }
 6794: 
 6795: sub decode_symb {
 6796:     my $symb=shift;
 6797:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6798:     my ($map,$resid,$url)=split(/___/,$symb);
 6799:     return (&fixversion($map),$resid,&fixversion($url));
 6800: }
 6801: 
 6802: sub fixversion {
 6803:     my $fn=shift;
 6804:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6805:     my %bighash;
 6806:     my $uri=&clutter($fn);
 6807:     my $key=$env{'request.course.id'}.'_'.$uri;
 6808: # is this cached?
 6809:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6810:     if (defined($cached)) { return $result; }
 6811: # unfortunately not cached, or expired
 6812:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6813: 	    &GDBM_READER(),0640)) {
 6814:  	if ($bighash{'version_'.$uri}) {
 6815:  	    my $version=$bighash{'version_'.$uri};
 6816:  	    unless (($version eq 'mostrecent') || 
 6817: 		    ($version==&getversion($uri))) {
 6818:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6819:  	    }
 6820:  	}
 6821:  	untie %bighash;
 6822:     }
 6823:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6824: }
 6825: 
 6826: sub deversion {
 6827:     my $url=shift;
 6828:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6829:     return $url;
 6830: }
 6831: 
 6832: # ------------------------------------------------------ Return symb list entry
 6833: 
 6834: sub symbread {
 6835:     my ($thisfn,$donotrecurse)=@_;
 6836:     my $cache_str='request.symbread.cached.'.$thisfn;
 6837:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6838: # no filename provided? try from environment
 6839:     unless ($thisfn) {
 6840:         if ($env{'request.symb'}) {
 6841: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6842: 	}
 6843: 	$thisfn=$env{'request.filename'};
 6844:     }
 6845:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6846: # is that filename actually a symb? Verify, clean, and return
 6847:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6848: 	if (&symbverify($thisfn,$1)) {
 6849: 	    return $env{$cache_str}=&symbclean($thisfn);
 6850: 	}
 6851:     }
 6852:     $thisfn=declutter($thisfn);
 6853:     my %hash;
 6854:     my %bighash;
 6855:     my $syval='';
 6856:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6857:         my $targetfn = $thisfn;
 6858:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6859:             $targetfn = 'adm/wrapper/'.$thisfn;
 6860:         }
 6861: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6862: 	    $targetfn=$1;
 6863: 	}
 6864:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6865:                       &GDBM_READER(),0640)) {
 6866: 	    $syval=$hash{$targetfn};
 6867:             untie(%hash);
 6868:         }
 6869: # ---------------------------------------------------------- There was an entry
 6870:         if ($syval) {
 6871: 	    #unless ($syval=~/\_\d+$/) {
 6872: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6873: 		    #&appenv('request.ambiguous' => $thisfn);
 6874: 		    #return $env{$cache_str}='';
 6875: 		#}    
 6876: 		#$syval.=$1;
 6877: 	    #}
 6878:         } else {
 6879: # ------------------------------------------------------- Was not in symb table
 6880:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6881:                             &GDBM_READER(),0640)) {
 6882: # ---------------------------------------------- Get ID(s) for current resource
 6883:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6884:               unless ($ids) { 
 6885:                  $ids=$bighash{'ids_/'.$thisfn};
 6886:               }
 6887:               unless ($ids) {
 6888: # alias?
 6889: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6890:               }
 6891:               if ($ids) {
 6892: # ------------------------------------------------------------------- Has ID(s)
 6893:                  my @possibilities=split(/\,/,$ids);
 6894:                  if ($#possibilities==0) {
 6895: # ----------------------------------------------- There is only one possibility
 6896: 		     my ($mapid,$resid)=split(/\./,$ids);
 6897: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6898: 						    $resid,$thisfn);
 6899:                  } elsif (!$donotrecurse) {
 6900: # ------------------------------------------ There is more than one possibility
 6901:                      my $realpossible=0;
 6902:                      foreach my $id (@possibilities) {
 6903: 			 my $file=$bighash{'src_'.$id};
 6904:                          if (&allowed('bre',$file)) {
 6905:          		    my ($mapid,$resid)=split(/\./,$id);
 6906:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6907: 				$realpossible++;
 6908:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6909: 						    $resid,$thisfn);
 6910:                             }
 6911: 			 }
 6912:                      }
 6913: 		     if ($realpossible!=1) { $syval=''; }
 6914:                  } else {
 6915:                      $syval='';
 6916:                  }
 6917: 	      }
 6918:               untie(%bighash)
 6919:            }
 6920:         }
 6921:         if ($syval) {
 6922: 	    return $env{$cache_str}=$syval;
 6923:         }
 6924:     }
 6925:     &appenv('request.ambiguous' => $thisfn);
 6926:     return $env{$cache_str}='';
 6927: }
 6928: 
 6929: # ---------------------------------------------------------- Return random seed
 6930: 
 6931: sub numval {
 6932:     my $txt=shift;
 6933:     $txt=~tr/A-J/0-9/;
 6934:     $txt=~tr/a-j/0-9/;
 6935:     $txt=~tr/K-T/0-9/;
 6936:     $txt=~tr/k-t/0-9/;
 6937:     $txt=~tr/U-Z/0-5/;
 6938:     $txt=~tr/u-z/0-5/;
 6939:     $txt=~s/\D//g;
 6940:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6941:     return int($txt);
 6942: }
 6943: 
 6944: sub numval2 {
 6945:     my $txt=shift;
 6946:     $txt=~tr/A-J/0-9/;
 6947:     $txt=~tr/a-j/0-9/;
 6948:     $txt=~tr/K-T/0-9/;
 6949:     $txt=~tr/k-t/0-9/;
 6950:     $txt=~tr/U-Z/0-5/;
 6951:     $txt=~tr/u-z/0-5/;
 6952:     $txt=~s/\D//g;
 6953:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6954:     my $total;
 6955:     foreach my $val (@txts) { $total+=$val; }
 6956:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6957:     return int($total);
 6958: }
 6959: 
 6960: sub numval3 {
 6961:     use integer;
 6962:     my $txt=shift;
 6963:     $txt=~tr/A-J/0-9/;
 6964:     $txt=~tr/a-j/0-9/;
 6965:     $txt=~tr/K-T/0-9/;
 6966:     $txt=~tr/k-t/0-9/;
 6967:     $txt=~tr/U-Z/0-5/;
 6968:     $txt=~tr/u-z/0-5/;
 6969:     $txt=~s/\D//g;
 6970:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6971:     my $total;
 6972:     foreach my $val (@txts) { $total+=$val; }
 6973:     if ($_64bit) { $total=(($total<<32)>>32); }
 6974:     return $total;
 6975: }
 6976: 
 6977: sub digest {
 6978:     my ($data)=@_;
 6979:     my $digest=&Digest::MD5::md5($data);
 6980:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6981:     my ($e,$f);
 6982:     {
 6983:         use integer;
 6984:         $e=($a+$b);
 6985:         $f=($c+$d);
 6986:         if ($_64bit) {
 6987:             $e=(($e<<32)>>32);
 6988:             $f=(($f<<32)>>32);
 6989:         }
 6990:     }
 6991:     if (wantarray) {
 6992: 	return ($e,$f);
 6993:     } else {
 6994: 	my $g;
 6995: 	{
 6996: 	    use integer;
 6997: 	    $g=($e+$f);
 6998: 	    if ($_64bit) {
 6999: 		$g=(($g<<32)>>32);
 7000: 	    }
 7001: 	}
 7002: 	return $g;
 7003:     }
 7004: }
 7005: 
 7006: sub latest_rnd_algorithm_id {
 7007:     return '64bit5';
 7008: }
 7009: 
 7010: sub get_rand_alg {
 7011:     my ($courseid)=@_;
 7012:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7013:     if ($courseid) {
 7014: 	return $env{"course.$courseid.rndseed"};
 7015:     }
 7016:     return &latest_rnd_algorithm_id();
 7017: }
 7018: 
 7019: sub validCODE {
 7020:     my ($CODE)=@_;
 7021:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7022:     return 0;
 7023: }
 7024: 
 7025: sub getCODE {
 7026:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7027:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7028: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7029: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7030: 	return $Apache::lonhomework::history{'resource.CODE'};
 7031:     }
 7032:     return undef;
 7033: }
 7034: 
 7035: sub rndseed {
 7036:     my ($symb,$courseid,$domain,$username)=@_;
 7037:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7038:     if (!$symb) {
 7039: 	unless ($symb=$wsymb) { return time; }
 7040:     }
 7041:     if (!$courseid) { $courseid=$wcourseid; }
 7042:     if (!$domain) { $domain=$wdomain; }
 7043:     if (!$username) { $username=$wusername }
 7044:     my $which=&get_rand_alg();
 7045: 
 7046:     if (defined(&getCODE())) {
 7047: 	if ($which eq '64bit5') {
 7048: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7049: 	} elsif ($which eq '64bit4') {
 7050: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7051: 	} else {
 7052: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7053: 	}
 7054:     } elsif ($which eq '64bit5') {
 7055: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7056:     } elsif ($which eq '64bit4') {
 7057: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7058:     } elsif ($which eq '64bit3') {
 7059: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7060:     } elsif ($which eq '64bit2') {
 7061: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7062:     } elsif ($which eq '64bit') {
 7063: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7064:     }
 7065:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7066: }
 7067: 
 7068: sub rndseed_32bit {
 7069:     my ($symb,$courseid,$domain,$username)=@_;
 7070:     {
 7071: 	use integer;
 7072: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7073: 	my $symbseed=numval($symb) << 22;
 7074: 	my $namechck=unpack("%32C*",$username) << 17;
 7075: 	my $nameseed=numval($username) << 12;
 7076: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7077: 	my $courseseed=unpack("%32C*",$courseid);
 7078: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7079: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7080: 	#&logthis("rndseed :$num:$symb");
 7081: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7082: 	return $num;
 7083:     }
 7084: }
 7085: 
 7086: sub rndseed_64bit {
 7087:     my ($symb,$courseid,$domain,$username)=@_;
 7088:     {
 7089: 	use integer;
 7090: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7091: 	my $symbseed=numval($symb) << 10;
 7092: 	my $namechck=unpack("%32S*",$username);
 7093: 	
 7094: 	my $nameseed=numval($username) << 21;
 7095: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7096: 	my $courseseed=unpack("%32S*",$courseid);
 7097: 	
 7098: 	my $num1=$symbchck+$symbseed+$namechck;
 7099: 	my $num2=$nameseed+$domainseed+$courseseed;
 7100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7101: 	#&logthis("rndseed :$num:$symb");
 7102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7103: 	return "$num1,$num2";
 7104:     }
 7105: }
 7106: 
 7107: sub rndseed_64bit2 {
 7108:     my ($symb,$courseid,$domain,$username)=@_;
 7109:     {
 7110: 	use integer;
 7111: 	# strings need to be an even # of cahracters long, it it is odd the
 7112:         # last characters gets thrown away
 7113: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7114: 	my $symbseed=numval($symb) << 10;
 7115: 	my $namechck=unpack("%32S*",$username.' ');
 7116: 	
 7117: 	my $nameseed=numval($username) << 21;
 7118: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7119: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7120: 	
 7121: 	my $num1=$symbchck+$symbseed+$namechck;
 7122: 	my $num2=$nameseed+$domainseed+$courseseed;
 7123: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7124: 	#&logthis("rndseed :$num:$symb");
 7125: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7126: 	return "$num1,$num2";
 7127:     }
 7128: }
 7129: 
 7130: sub rndseed_64bit3 {
 7131:     my ($symb,$courseid,$domain,$username)=@_;
 7132:     {
 7133: 	use integer;
 7134: 	# strings need to be an even # of cahracters long, it it is odd the
 7135:         # last characters gets thrown away
 7136: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7137: 	my $symbseed=numval2($symb) << 10;
 7138: 	my $namechck=unpack("%32S*",$username.' ');
 7139: 	
 7140: 	my $nameseed=numval2($username) << 21;
 7141: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7142: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7143: 	
 7144: 	my $num1=$symbchck+$symbseed+$namechck;
 7145: 	my $num2=$nameseed+$domainseed+$courseseed;
 7146: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7147: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7148: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7149: 	
 7150: 	return "$num1:$num2";
 7151:     }
 7152: }
 7153: 
 7154: sub rndseed_64bit4 {
 7155:     my ($symb,$courseid,$domain,$username)=@_;
 7156:     {
 7157: 	use integer;
 7158: 	# strings need to be an even # of cahracters long, it it is odd the
 7159:         # last characters gets thrown away
 7160: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7161: 	my $symbseed=numval3($symb) << 10;
 7162: 	my $namechck=unpack("%32S*",$username.' ');
 7163: 	
 7164: 	my $nameseed=numval3($username) << 21;
 7165: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7166: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7167: 	
 7168: 	my $num1=$symbchck+$symbseed+$namechck;
 7169: 	my $num2=$nameseed+$domainseed+$courseseed;
 7170: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7171: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7172: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7173: 	
 7174: 	return "$num1:$num2";
 7175:     }
 7176: }
 7177: 
 7178: sub rndseed_64bit5 {
 7179:     my ($symb,$courseid,$domain,$username)=@_;
 7180:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7181:     return "$num1:$num2";
 7182: }
 7183: 
 7184: sub rndseed_CODE_64bit {
 7185:     my ($symb,$courseid,$domain,$username)=@_;
 7186:     {
 7187: 	use integer;
 7188: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7189: 	my $symbseed=numval2($symb);
 7190: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7191: 	my $CODEseed=numval(&getCODE());
 7192: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7193: 	my $num1=$symbseed+$CODEchck;
 7194: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7195: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7196: 	#&logthis("rndseed :$num1:$num2:$symb");
 7197: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7198: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7199: 	return "$num1:$num2";
 7200:     }
 7201: }
 7202: 
 7203: sub rndseed_CODE_64bit4 {
 7204:     my ($symb,$courseid,$domain,$username)=@_;
 7205:     {
 7206: 	use integer;
 7207: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7208: 	my $symbseed=numval3($symb);
 7209: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7210: 	my $CODEseed=numval3(&getCODE());
 7211: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7212: 	my $num1=$symbseed+$CODEchck;
 7213: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7214: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7215: 	#&logthis("rndseed :$num1:$num2:$symb");
 7216: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7217: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7218: 	return "$num1:$num2";
 7219:     }
 7220: }
 7221: 
 7222: sub rndseed_CODE_64bit5 {
 7223:     my ($symb,$courseid,$domain,$username)=@_;
 7224:     my $code = &getCODE();
 7225:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7226:     return "$num1:$num2";
 7227: }
 7228: 
 7229: sub setup_random_from_rndseed {
 7230:     my ($rndseed)=@_;
 7231:     if ($rndseed =~/([,:])/) {
 7232: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7233: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7234:     } else {
 7235: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7236:     }
 7237: }
 7238: 
 7239: sub latest_receipt_algorithm_id {
 7240:     return 'receipt3';
 7241: }
 7242: 
 7243: sub recunique {
 7244:     my $fucourseid=shift;
 7245:     my $unique;
 7246:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7247: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7248: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7249:     } else {
 7250: 	$unique=$perlvar{'lonReceipt'};
 7251:     }
 7252:     return unpack("%32C*",$unique);
 7253: }
 7254: 
 7255: sub recprefix {
 7256:     my $fucourseid=shift;
 7257:     my $prefix;
 7258:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7259: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7260: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7261:     } else {
 7262: 	$prefix=$perlvar{'lonHostID'};
 7263:     }
 7264:     return unpack("%32C*",$prefix);
 7265: }
 7266: 
 7267: sub ireceipt {
 7268:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7269: 
 7270:     my $return =&recprefix($fucourseid).'-';
 7271: 
 7272:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7273: 	$env{'request.state'} eq 'construct') {
 7274: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7275: 	return $return;
 7276:     }
 7277: 
 7278:     my $cuname=unpack("%32C*",$funame);
 7279:     my $cudom=unpack("%32C*",$fudom);
 7280:     my $cucourseid=unpack("%32C*",$fucourseid);
 7281:     my $cusymb=unpack("%32C*",$fusymb);
 7282:     my $cunique=&recunique($fucourseid);
 7283:     my $cpart=unpack("%32S*",$part);
 7284:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7285: 
 7286: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7287: 			       
 7288: 	$return.= ($cunique%$cuname+
 7289: 		   $cunique%$cudom+
 7290: 		   $cusymb%$cuname+
 7291: 		   $cusymb%$cudom+
 7292: 		   $cucourseid%$cuname+
 7293: 		   $cucourseid%$cudom+
 7294: 		   $cpart%$cuname+
 7295: 		   $cpart%$cudom);
 7296:     } else {
 7297: 	$return.= ($cunique%$cuname+
 7298: 		   $cunique%$cudom+
 7299: 		   $cusymb%$cuname+
 7300: 		   $cusymb%$cudom+
 7301: 		   $cucourseid%$cuname+
 7302: 		   $cucourseid%$cudom);
 7303:     }
 7304:     return $return;
 7305: }
 7306: 
 7307: sub receipt {
 7308:     my ($part)=@_;
 7309:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7310:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7311: }
 7312: 
 7313: sub whichuser {
 7314:     my ($passedsymb)=@_;
 7315:     my ($symb,$courseid,$domain,$name,$publicuser);
 7316:     if (defined($env{'form.grade_symb'})) {
 7317: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7318: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7319: 	if (!$allowed &&
 7320: 	    exists($env{'request.course.sec'}) &&
 7321: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7322: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7323: 			      '/'.$env{'request.course.sec'});
 7324: 	}
 7325: 	if ($allowed) {
 7326: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7327: 	    $courseid=$tmp_courseid;
 7328: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7329: 	    ($name)=&get_env_multiple('form.grade_username');
 7330: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7331: 	}
 7332:     }
 7333:     if (!$passedsymb) {
 7334: 	$symb=&symbread();
 7335:     } else {
 7336: 	$symb=$passedsymb;
 7337:     }
 7338:     $courseid=$env{'request.course.id'};
 7339:     $domain=$env{'user.domain'};
 7340:     $name=$env{'user.name'};
 7341:     if ($name eq 'public' && $domain eq 'public') {
 7342: 	if (!defined($env{'form.username'})) {
 7343: 	    $env{'form.username'}.=time.rand(10000000);
 7344: 	}
 7345: 	$name.=$env{'form.username'};
 7346:     }
 7347:     return ($symb,$courseid,$domain,$name,$publicuser);
 7348: 
 7349: }
 7350: 
 7351: # ------------------------------------------------------------ Serves up a file
 7352: # returns either the contents of the file or 
 7353: # -1 if the file doesn't exist
 7354: #
 7355: # if the target is a file that was uploaded via DOCS, 
 7356: # a check will be made to see if a current copy exists on the local server,
 7357: # if it does this will be served, otherwise a copy will be retrieved from
 7358: # the home server for the course and stored in /home/httpd/html/userfiles on
 7359: # the local server.   
 7360: 
 7361: sub getfile {
 7362:     my ($file) = @_;
 7363:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7364:     &repcopy($file);
 7365:     return &readfile($file);
 7366: }
 7367: 
 7368: sub repcopy_userfile {
 7369:     my ($file)=@_;
 7370:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7371:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7372:     my ($cdom,$cnum,$filename) = 
 7373: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7374:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7375:     if (-e "$file") {
 7376: # we already have a local copy, check it out
 7377: 	my @fileinfo = stat($file);
 7378: 	my $rtncode;
 7379: 	my $info;
 7380: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7381: 	if ($lwpresp ne 'ok') {
 7382: # there is no such file anymore, even though we had a local copy
 7383: 	    if ($rtncode eq '404') {
 7384: 		unlink($file);
 7385: 	    }
 7386: 	    return -1;
 7387: 	}
 7388: 	if ($info < $fileinfo[9]) {
 7389: # nice, the file we have is up-to-date, just say okay
 7390: 	    return 'ok';
 7391: 	} else {
 7392: # the file is outdated, get rid of it
 7393: 	    unlink($file);
 7394: 	}
 7395:     }
 7396: # one way or the other, at this point, we don't have the file
 7397: # construct the correct path for the file
 7398:     my @parts = ($cdom,$cnum); 
 7399:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7400: 	push @parts, split(/\//,$1);
 7401:     }
 7402:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7403:     foreach my $part (@parts) {
 7404: 	$path .= '/'.$part;
 7405: 	if (!-e $path) {
 7406: 	    mkdir($path,0770);
 7407: 	}
 7408:     }
 7409: # now the path exists for sure
 7410: # get a user agent
 7411:     my $ua=new LWP::UserAgent;
 7412:     my $transferfile=$file.'.in.transfer';
 7413: # FIXME: this should flock
 7414:     if (-e $transferfile) { return 'ok'; }
 7415:     my $request;
 7416:     $uri=~s/^\///;
 7417:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7418:     my $response=$ua->request($request,$transferfile);
 7419: # did it work?
 7420:     if ($response->is_error()) {
 7421: 	unlink($transferfile);
 7422: 	&logthis("Userfile repcopy failed for $uri");
 7423: 	return -1;
 7424:     }
 7425: # worked, rename the transfer file
 7426:     rename($transferfile,$file);
 7427:     return 'ok';
 7428: }
 7429: 
 7430: sub tokenwrapper {
 7431:     my $uri=shift;
 7432:     $uri=~s|^http\://([^/]+)||;
 7433:     $uri=~s|^/||;
 7434:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7435:     my $token=$1;
 7436:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7437:     if ($udom && $uname && $file) {
 7438: 	$file=~s|(\?\.*)*$||;
 7439:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7440:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7441:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7442:                                '&tokenissued='.$perlvar{'lonHostID'};
 7443:     } else {
 7444:         return '/adm/notfound.html';
 7445:     }
 7446: }
 7447: 
 7448: # call with reqtype HEAD: get last modification time
 7449: # call with reqtype GET: get the file contents
 7450: # Do not call this with reqtype GET for large files! It loads everything into memory
 7451: #
 7452: sub getuploaded {
 7453:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7454:     $uri=~s/^\///;
 7455:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7456:     my $ua=new LWP::UserAgent;
 7457:     my $request=new HTTP::Request($reqtype,$uri);
 7458:     my $response=$ua->request($request);
 7459:     $$rtncode = $response->code;
 7460:     if (! $response->is_success()) {
 7461: 	return 'failed';
 7462:     }      
 7463:     if ($reqtype eq 'HEAD') {
 7464: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7465:     } elsif ($reqtype eq 'GET') {
 7466: 	$$info = $response->content;
 7467:     }
 7468:     return 'ok';
 7469: }
 7470: 
 7471: sub readfile {
 7472:     my $file = shift;
 7473:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7474:     my $fh;
 7475:     open($fh,"<$file");
 7476:     my $a='';
 7477:     while (my $line = <$fh>) { $a .= $line; }
 7478:     return $a;
 7479: }
 7480: 
 7481: sub filelocation {
 7482:     my ($dir,$file) = @_;
 7483:     my $location;
 7484:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7485: 
 7486:     if ($file =~ m-^/adm/-) {
 7487: 	$file=~s-^/adm/wrapper/-/-;
 7488: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7489:     }
 7490:     if ($file=~m:^/~:) { # is a contruction space reference
 7491:         $location = $file;
 7492:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7493:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7494: 	# is a correct contruction space reference
 7495:         $location = $file;
 7496:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7497:         my ($udom,$uname,$filename)=
 7498:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7499:         my $home=&homeserver($uname,$udom);
 7500:         my $is_me=0;
 7501:         my @ids=&current_machine_ids();
 7502:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7503:         if ($is_me) {
 7504:   	    $location=&propath($udom,$uname).
 7505:   	      '/userfiles/'.$filename;
 7506:         } else {
 7507:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7508:   	      $udom.'/'.$uname.'/'.$filename;
 7509:         }
 7510:     } else {
 7511:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7512:         $file=~s:^/res/:/:;
 7513:         if ( !( $file =~ m:^/:) ) {
 7514:             $location = $dir. '/'.$file;
 7515:         } else {
 7516:             $location = '/home/httpd/html/res'.$file;
 7517:         }
 7518:     }
 7519:     $location=~s://+:/:g; # remove duplicate /
 7520:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7521:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7522:     return $location;
 7523: }
 7524: 
 7525: sub hreflocation {
 7526:     my ($dir,$file)=@_;
 7527:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7528: 	$file=filelocation($dir,$file);
 7529:     } elsif ($file=~m-^/adm/-) {
 7530: 	$file=~s-^/adm/wrapper/-/-;
 7531: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7532:     }
 7533:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7534: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7535:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7536: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7537:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7538: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7539: 	    -/uploaded/$1/$2/-x;
 7540:     }
 7541:     return $file;
 7542: }
 7543: 
 7544: sub current_machine_domains {
 7545:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7546: }
 7547: 
 7548: sub machine_domains {
 7549:     my ($hostname) = @_;
 7550:     my @domains;
 7551:     my %hostname = &all_hostnames();
 7552:     while( my($id, $name) = each(%hostname)) {
 7553: #	&logthis("-$id-$name-$hostname-");
 7554: 	if ($hostname eq $name) {
 7555: 	    push(@domains,&host_domain($id));
 7556: 	}
 7557:     }
 7558:     return @domains;
 7559: }
 7560: 
 7561: sub current_machine_ids {
 7562:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7563: }
 7564: 
 7565: sub machine_ids {
 7566:     my ($hostname) = @_;
 7567:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7568:     my @ids;
 7569:     my %hostname = &all_hostnames();
 7570:     while( my($id, $name) = each(%hostname)) {
 7571: #	&logthis("-$id-$name-$hostname-");
 7572: 	if ($hostname eq $name) {
 7573: 	    push(@ids,$id);
 7574: 	}
 7575:     }
 7576:     return @ids;
 7577: }
 7578: 
 7579: sub additional_machine_domains {
 7580:     my @domains;
 7581:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7582:     while( my $line = <$fh>) {
 7583:         $line =~ s/\s//g;
 7584:         push(@domains,$line);
 7585:     }
 7586:     return @domains;
 7587: }
 7588: 
 7589: sub default_login_domain {
 7590:     my $domain = $perlvar{'lonDefDomain'};
 7591:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7592:     foreach my $posdom (&current_machine_domains(),
 7593:                         &additional_machine_domains()) {
 7594:         if (lc($posdom) eq lc($testdomain)) {
 7595:             $domain=$posdom;
 7596:             last;
 7597:         }
 7598:     }
 7599:     return $domain;
 7600: }
 7601: 
 7602: # ------------------------------------------------------------- Declutters URLs
 7603: 
 7604: sub declutter {
 7605:     my $thisfn=shift;
 7606:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7607:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7608:     $thisfn=~s/^\///;
 7609:     $thisfn=~s|^adm/wrapper/||;
 7610:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7611:     $thisfn=~s/^res\///;
 7612:     $thisfn=~s/\?.+$//;
 7613:     return $thisfn;
 7614: }
 7615: 
 7616: # ------------------------------------------------------------- Clutter up URLs
 7617: 
 7618: sub clutter {
 7619:     my $thisfn='/'.&declutter(shift);
 7620:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7621:        $thisfn='/res'.$thisfn; 
 7622:     }
 7623:     if ($thisfn !~m|/adm|) {
 7624: 	if ($thisfn =~ m|/ext/|) {
 7625: 	    $thisfn='/adm/wrapper'.$thisfn;
 7626: 	} else {
 7627: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7628: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7629: 	    if ($embstyle eq 'ssi'
 7630: 		|| ($embstyle eq 'hdn')
 7631: 		|| ($embstyle eq 'rat')
 7632: 		|| ($embstyle eq 'prv')
 7633: 		|| ($embstyle eq 'ign')) {
 7634: 		#do nothing with these
 7635: 	    } elsif (($embstyle eq 'img') 
 7636: 		|| ($embstyle eq 'emb')
 7637: 		|| ($embstyle eq 'wrp')) {
 7638: 		$thisfn='/adm/wrapper'.$thisfn;
 7639: 	    } elsif ($embstyle eq 'unk'
 7640: 		     && $thisfn!~/\.(sequence|page)$/) {
 7641: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7642: 	    } else {
 7643: #		&logthis("Got a blank emb style");
 7644: 	    }
 7645: 	}
 7646:     }
 7647:     return $thisfn;
 7648: }
 7649: 
 7650: sub clutter_with_no_wrapper {
 7651:     my $uri = &clutter(shift);
 7652:     if ($uri =~ m-^/adm/-) {
 7653: 	$uri =~ s-^/adm/wrapper/-/-;
 7654: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7655:     }
 7656:     return $uri;
 7657: }
 7658: 
 7659: sub freeze_escape {
 7660:     my ($value)=@_;
 7661:     if (ref($value)) {
 7662: 	$value=&nfreeze($value);
 7663: 	return '__FROZEN__'.&escape($value);
 7664:     }
 7665:     return &escape($value);
 7666: }
 7667: 
 7668: 
 7669: sub thaw_unescape {
 7670:     my ($value)=@_;
 7671:     if ($value =~ /^__FROZEN__/) {
 7672: 	substr($value,0,10,undef);
 7673: 	$value=&unescape($value);
 7674: 	return &thaw($value);
 7675:     }
 7676:     return &unescape($value);
 7677: }
 7678: 
 7679: sub correct_line_ends {
 7680:     my ($result)=@_;
 7681:     $$result =~s/\r\n/\n/mg;
 7682:     $$result =~s/\r/\n/mg;
 7683: }
 7684: # ================================================================ Main Program
 7685: 
 7686: sub goodbye {
 7687:    &logthis("Starting Shut down");
 7688: #not converted to using infrastruture and probably shouldn't be
 7689:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7690: #converted
 7691: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7692:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7693: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7694: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7695: #1.1 only
 7696: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7697: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7698: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7699: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7700:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7701:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7702:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7703:    &flushcourselogs();
 7704:    &logthis("Shutting down");
 7705: }
 7706: 
 7707: sub get_dns {
 7708:     my ($url,$func) = @_;
 7709:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7710:     foreach my $dns (<$config>) {
 7711: 	next if ($dns !~ /^\^(\S*)/x);
 7712: 	$dns = $1;
 7713: 	my $ua=new LWP::UserAgent;
 7714: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7715: 	my $response=$ua->request($request);
 7716: 	next if ($response->is_error());
 7717: 	my @content = split("\n",$response->content);
 7718: 	&$func(\@content);
 7719:     }
 7720:     close($config);
 7721: }
 7722: # ------------------------------------------------------------ Read domain file
 7723: {
 7724:     my $loaded;
 7725:     my %domain;
 7726: 
 7727:     sub parse_domain_tab {
 7728: 	my ($lines) = @_;
 7729: 	foreach my $line (@$lines) {
 7730: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7731: 
 7732: 	    chomp($line);
 7733: 	    my ($name,@elements) = split(/:/,$line,9);
 7734: 	    my %this_domain;
 7735: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7736: 			       'lang_def', 'city', 'longi', 'lati',
 7737: 			       'primary') {
 7738: 		$this_domain{$field} = shift(@elements);
 7739: 	    }
 7740: 	    $domain{$name} = \%this_domain;
 7741: 	}
 7742:     }
 7743:     
 7744:     sub load_domain_tab {
 7745: 	&get_dns('/adm/dns/domain',\&parse_domain_tab);
 7746: 	my $fh;
 7747: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7748: 	    my @lines = <$fh>;
 7749: 	    &parse_domain_tab(\@lines);
 7750: 	}
 7751: 	close($fh);
 7752: 	$loaded = 1;
 7753:     }
 7754: 
 7755:     sub domain {
 7756: 	&load_domain_tab() if (!$loaded);
 7757: 
 7758: 	my ($name,$what) = @_;
 7759: 	return if ( !exists($domain{$name}) );
 7760: 
 7761: 	if (!$what) {
 7762: 	    return $domain{$name}{'description'};
 7763: 	}
 7764: 	return $domain{$name}{$what};
 7765:     }
 7766: }
 7767: 
 7768: 
 7769: # ------------------------------------------------------------- Read hosts file
 7770: {
 7771:     my %hostname;
 7772:     my %hostdom;
 7773:     my %libserv;
 7774:     my $loaded;
 7775: 
 7776:     sub parse_hosts_tab {
 7777: 	my ($file) = @_;
 7778: 	foreach my $configline (@$file) {
 7779: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7780: 	    next if ($configline =~ /^\^/);
 7781: 	    chomp($configline);
 7782: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7783: 	    $name=~s/\s//g;
 7784: 	    if ($id && $domain && $role && $name) {
 7785: 		$hostname{$id}=$name;
 7786: 		$hostdom{$id}=$domain;
 7787: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7788: 	    }
 7789: 	}
 7790:     }
 7791: 
 7792:     sub load_hosts_tab {
 7793: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab);
 7794: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7795: 	my @config = <$config>;
 7796: 	&parse_hosts_tab(\@config);
 7797: 	close($config);
 7798: 	$loaded=1;
 7799:     }
 7800: 
 7801:     sub hostname {
 7802: 	&load_hosts_tab() if (!$loaded);
 7803: 
 7804: 	my ($lonid) = @_;
 7805: 	return $hostname{$lonid};
 7806:     }
 7807: 
 7808:     sub all_hostnames {
 7809: 	&load_hosts_tab() if (!$loaded);
 7810: 
 7811: 	return %hostname;
 7812:     }
 7813: 
 7814:     sub is_library {
 7815: 	&load_hosts_tab() if (!$loaded);
 7816: 
 7817: 	return exists($libserv{$_[0]});
 7818:     }
 7819: 
 7820:     sub all_library {
 7821: 	&load_hosts_tab() if (!$loaded);
 7822: 
 7823: 	return %libserv;
 7824:     }
 7825: 
 7826:     sub get_servers {
 7827: 	&load_hosts_tab() if (!$loaded);
 7828: 
 7829: 	my ($domain,$type) = @_;
 7830: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7831: 	                                          : %hostname;
 7832: 	my %result;
 7833: 	if (ref($domain) eq 'ARRAY') {
 7834: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7835: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7836: 		    $result{$host} = $hostname;
 7837: 		}
 7838: 	    }
 7839: 	} else {
 7840: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7841: 		if ($hostdom{$host} eq $domain) {
 7842: 		    $result{$host} = $hostname;
 7843: 		}
 7844: 	    }
 7845: 	}
 7846: 	return %result;
 7847:     }
 7848: 
 7849:     sub host_domain {
 7850: 	&load_hosts_tab() if (!$loaded);
 7851: 
 7852: 	my ($lonid) = @_;
 7853: 	return $hostdom{$lonid};
 7854:     }
 7855: 
 7856:     sub all_domains {
 7857: 	&load_hosts_tab() if (!$loaded);
 7858: 
 7859: 	my %seen;
 7860: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7861: 	return @uniq;
 7862:     }
 7863: }
 7864: 
 7865: { 
 7866:     my %iphost;
 7867:     my %name_to_ip;
 7868:     my %lonid_to_ip;
 7869:     sub get_hosts_from_ip {
 7870: 	my ($ip) = @_;
 7871: 	my %iphosts = &get_iphost();
 7872: 	if (ref($iphosts{$ip})) {
 7873: 	    return @{$iphosts{$ip}};
 7874: 	}
 7875: 	return;
 7876:     }
 7877: 
 7878:     sub get_host_ip {
 7879: 	my ($lonid) = @_;
 7880: 	if (exists($lonid_to_ip{$lonid})) {
 7881: 	    return $lonid_to_ip{$lonid};
 7882: 	}
 7883: 	my $name=&hostname($lonid);
 7884:    	my $ip = gethostbyname($name);
 7885: 	return if (!$ip || length($ip) ne 4);
 7886: 	$ip=inet_ntoa($ip);
 7887: 	$name_to_ip{$name}   = $ip;
 7888: 	$lonid_to_ip{$lonid} = $ip;
 7889: 	return $ip;
 7890:     }
 7891:     
 7892:     sub get_iphost {
 7893: 	if (%iphost) { return %iphost; }
 7894: 	my %hostname = &all_hostnames();
 7895: 	foreach my $id (keys(%hostname)) {
 7896: 	    my $name=$hostname{$id};
 7897: 	    my $ip;
 7898: 	    if (!exists($name_to_ip{$name})) {
 7899: 		$ip = gethostbyname($name);
 7900: 		if (!$ip || length($ip) ne 4) {
 7901: 		    &logthis("Skipping host $id name $name no IP found");
 7902: 		    next;
 7903: 		}
 7904: 		$ip=inet_ntoa($ip);
 7905: 		$name_to_ip{$name} = $ip;
 7906: 	    } else {
 7907: 		$ip = $name_to_ip{$name};
 7908: 	    }
 7909: 	    $lonid_to_ip{$id} = $ip;
 7910: 	    push(@{$iphost{$ip}},$id);
 7911: 	}
 7912: 	return %iphost;
 7913:     }
 7914: }
 7915: 
 7916: BEGIN {
 7917: 
 7918: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7919:     unless ($readit) {
 7920: {
 7921:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7922:     %perlvar = (%perlvar,%{$configvars});
 7923: }
 7924: 
 7925: 
 7926: # ------------------------------------------------------ Read spare server file
 7927: {
 7928:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7929: 
 7930:     while (my $configline=<$config>) {
 7931:        chomp($configline);
 7932:        if ($configline) {
 7933: 	   my ($host,$type) = split(':',$configline,2);
 7934: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7935: 	   push(@{ $spareid{$type} }, $host);
 7936:        }
 7937:     }
 7938:     close($config);
 7939: }
 7940: # ------------------------------------------------------------ Read permissions
 7941: {
 7942:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7943: 
 7944:     while (my $configline=<$config>) {
 7945: 	chomp($configline);
 7946: 	if ($configline) {
 7947: 	    my ($role,$perm)=split(/ /,$configline);
 7948: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7949: 	}
 7950:     }
 7951:     close($config);
 7952: }
 7953: 
 7954: # -------------------------------------------- Read plain texts for permissions
 7955: {
 7956:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7957: 
 7958:     while (my $configline=<$config>) {
 7959: 	chomp($configline);
 7960: 	if ($configline) {
 7961: 	    my ($short,@plain)=split(/:/,$configline);
 7962:             %{$prp{$short}} = ();
 7963: 	    if (@plain > 0) {
 7964:                 $prp{$short}{'std'} = $plain[0];
 7965:                 for (my $i=1; $i<@plain; $i++) {
 7966:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7967:                 }
 7968:             }
 7969: 	}
 7970:     }
 7971:     close($config);
 7972: }
 7973: 
 7974: # ---------------------------------------------------------- Read package table
 7975: {
 7976:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7977: 
 7978:     while (my $configline=<$config>) {
 7979: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7980: 	chomp($configline);
 7981: 	my ($short,$plain)=split(/:/,$configline);
 7982: 	my ($pack,$name)=split(/\&/,$short);
 7983: 	if ($plain ne '') {
 7984: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7985: 	    $packagetab{$short}=$plain; 
 7986: 	}
 7987:     }
 7988:     close($config);
 7989: }
 7990: 
 7991: # ------------- set up temporary directory
 7992: {
 7993:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7994: 
 7995: }
 7996: 
 7997: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7998: 				'compress_threshold'=> 20_000,
 7999:  			        });
 8000: 
 8001: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8002: $dumpcount=0;
 8003: 
 8004: &logtouch();
 8005: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8006: $readit=1;
 8007:     {
 8008: 	use integer;
 8009: 	my $test=(2**32)+1;
 8010: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8011: 	&logthis(" Detected 64bit platform ($_64bit)");
 8012:     }
 8013: }
 8014: }
 8015: 
 8016: 1;
 8017: __END__
 8018: 
 8019: =pod
 8020: 
 8021: =head1 NAME
 8022: 
 8023: Apache::lonnet - Subroutines to ask questions about things in the network.
 8024: 
 8025: =head1 SYNOPSIS
 8026: 
 8027: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8028: 
 8029:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8030: 
 8031: Common parameters:
 8032: 
 8033: =over 4
 8034: 
 8035: =item *
 8036: 
 8037: $uname : an internal username (if $cname expecting a course Id specifically)
 8038: 
 8039: =item *
 8040: 
 8041: $udom : a domain (if $cdom expecting a course's domain specifically)
 8042: 
 8043: =item *
 8044: 
 8045: $symb : a resource instance identifier
 8046: 
 8047: =item *
 8048: 
 8049: $namespace : the name of a .db file that contains the data needed or
 8050: being set.
 8051: 
 8052: =back
 8053: 
 8054: =head1 OVERVIEW
 8055: 
 8056: lonnet provides subroutines which interact with the
 8057: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8058: about classes, users, and resources.
 8059: 
 8060: For many of these objects you can also use this to store data about
 8061: them or modify them in various ways.
 8062: 
 8063: =head2 Symbs
 8064: 
 8065: To identify a specific instance of a resource, LON-CAPA uses symbols
 8066: or "symbs"X<symb>. These identifiers are built from the URL of the
 8067: map, the resource number of the resource in the map, and the URL of
 8068: the resource itself. The latter is somewhat redundant, but might help
 8069: if maps change.
 8070: 
 8071: An example is
 8072: 
 8073:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8074: 
 8075: The respective map entry is
 8076: 
 8077:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8078:   title="Problem 2">
 8079:  </resource>
 8080: 
 8081: Symbs are used by the random number generator, as well as to store and
 8082: restore data specific to a certain instance of for example a problem.
 8083: 
 8084: =head2 Storing And Retrieving Data
 8085: 
 8086: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8087: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8088: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8089: is is the non-critical message twin of cstore. These functions are for
 8090: handlers to store a perl hash to a user's permanent data space in an
 8091: easy manner, and to retrieve it again on another call. It is expected
 8092: that a handler would use this once at the beginning to retrieve data,
 8093: and then again once at the end to send only the new data back.
 8094: 
 8095: The data is stored in the user's data directory on the user's
 8096: homeserver under the ID of the course.
 8097: 
 8098: The hash that is returned by restore will have all of the previous
 8099: value for all of the elements of the hash.
 8100: 
 8101: Example:
 8102: 
 8103:  #creating a hash
 8104:  my %hash;
 8105:  $hash{'foo'}='bar';
 8106: 
 8107:  #storing it
 8108:  &Apache::lonnet::cstore(\%hash);
 8109: 
 8110:  #changing a value
 8111:  $hash{'foo'}='notbar';
 8112: 
 8113:  #adding a new value
 8114:  $hash{'bar'}='foo';
 8115:  &Apache::lonnet::cstore(\%hash);
 8116: 
 8117:  #retrieving the hash
 8118:  my %history=&Apache::lonnet::restore();
 8119: 
 8120:  #print the hash
 8121:  foreach my $key (sort(keys(%history))) {
 8122:    print("\%history{$key} = $history{$key}");
 8123:  }
 8124: 
 8125: Will print out:
 8126: 
 8127:  %history{1:foo} = bar
 8128:  %history{1:keys} = foo:timestamp
 8129:  %history{1:timestamp} = 990455579
 8130:  %history{2:bar} = foo
 8131:  %history{2:foo} = notbar
 8132:  %history{2:keys} = foo:bar:timestamp
 8133:  %history{2:timestamp} = 990455580
 8134:  %history{bar} = foo
 8135:  %history{foo} = notbar
 8136:  %history{timestamp} = 990455580
 8137:  %history{version} = 2
 8138: 
 8139: Note that the special hash entries C<keys>, C<version> and
 8140: C<timestamp> were added to the hash. C<version> will be equal to the
 8141: total number of versions of the data that have been stored. The
 8142: C<timestamp> attribute will be the UNIX time the hash was
 8143: stored. C<keys> is available in every historical section to list which
 8144: keys were added or changed at a specific historical revision of a
 8145: hash.
 8146: 
 8147: B<Warning>: do not store the hash that restore returns directly. This
 8148: will cause a mess since it will restore the historical keys as if the
 8149: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8150: 
 8151: Calling convention:
 8152: 
 8153:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8154:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8155: 
 8156: For more detailed information, see lonnet specific documentation.
 8157: 
 8158: =head1 RETURN MESSAGES
 8159: 
 8160: =over 4
 8161: 
 8162: =item * B<con_lost>: unable to contact remote host
 8163: 
 8164: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8165: when the connection is brought back up
 8166: 
 8167: =item * B<con_failed>: unable to contact remote host and unable to save message
 8168: for later delivery
 8169: 
 8170: =item * B<error:>: an error a occured, a description of the error follows the :
 8171: 
 8172: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8173: that was requested
 8174: 
 8175: =back
 8176: 
 8177: =head1 PUBLIC SUBROUTINES
 8178: 
 8179: =head2 Session Environment Functions
 8180: 
 8181: =over 4
 8182: 
 8183: =item * 
 8184: X<appenv()>
 8185: B<appenv(%hash)>: the value of %hash is written to
 8186: the user envirnoment file, and will be restored for each access this
 8187: user makes during this session, also modifies the %env for the current
 8188: process
 8189: 
 8190: =item *
 8191: X<delenv()>
 8192: B<delenv($regexp)>: removes all items from the session
 8193: environment file that matches the regular expression in $regexp. The
 8194: values are also delted from the current processes %env.
 8195: 
 8196: =item * get_env_multiple($name) 
 8197: 
 8198: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8199: values may be defined and end up as an array ref.
 8200: 
 8201: returns an array of values
 8202: 
 8203: =back
 8204: 
 8205: =head2 User Information
 8206: 
 8207: =over 4
 8208: 
 8209: =item *
 8210: X<queryauthenticate()>
 8211: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8212: authentication scheme
 8213: 
 8214: =item *
 8215: X<authenticate()>
 8216: B<authenticate($uname,$upass,$udom)>: try to
 8217: authenticate user from domain's lib servers (first use the current
 8218: one). C<$upass> should be the users password.
 8219: 
 8220: =item *
 8221: X<homeserver()>
 8222: B<homeserver($uname,$udom)>: find the server which has
 8223: the user's directory and files (there must be only one), this caches
 8224: the answer, and also caches if there is a borken connection.
 8225: 
 8226: =item *
 8227: X<idget()>
 8228: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8229: (IDs are a unique resource in a domain, there must be only 1 ID per
 8230: username, and only 1 username per ID in a specific domain) (returns
 8231: hash: id=>name,id=>name)
 8232: 
 8233: =item *
 8234: X<idrget()>
 8235: B<idrget($udom,@unames)>: find the IDs behind a list of
 8236: usernames (returns hash: name=>id,name=>id)
 8237: 
 8238: =item *
 8239: X<idput()>
 8240: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8241: 
 8242: =item *
 8243: X<rolesinit()>
 8244: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8245: 
 8246: =item *
 8247: X<getsection()>
 8248: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8249: course $cname, return section name/number or '' for "not in course"
 8250: and '-1' for "no section"
 8251: 
 8252: =item *
 8253: X<userenvironment()>
 8254: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8255: passed in @what from the requested user's environment, returns a hash
 8256: 
 8257: =item * 
 8258: X<userlog_query()>
 8259: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8260: activity.log file. %filters defines filters applied when parsing the
 8261: log file. These can be start or end timestamps, or the type of action
 8262: - log to look for Login or Logout events, check for Checkin or
 8263: Checkout, role for role selection. The response is in the form
 8264: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8265: escaped strings of the action recorded in the activity.log file.
 8266: 
 8267: =back
 8268: 
 8269: =head2 User Roles
 8270: 
 8271: =over 4
 8272: 
 8273: =item *
 8274: 
 8275: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8276:  F: full access
 8277:  U,I,K: authentication modes (cxx only)
 8278:  '': forbidden
 8279:  1: user needs to choose course
 8280:  2: browse allowed
 8281:  A: passphrase authentication needed
 8282: 
 8283: =item *
 8284: 
 8285: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8286: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8287: and course level
 8288: 
 8289: =item *
 8290: 
 8291: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8292: explanation of a user role term
 8293: 
 8294: =item *
 8295: 
 8296: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8297: All arguments are optional. Returns a hash of a roles, either for
 8298: co-author/assistant author roles for a user's Construction Space
 8299: (default), or if $context is 'user', roles for the user himself,
 8300: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8301: and value is set to colon-separated start and end times for the role.
 8302: If no username and domain are specified, will default to current
 8303: user/domain. Types, roles, and roledoms are references to arrays,
 8304: of role statuses (active, future or previous), roles 
 8305: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8306: to restrict the list of roles reported. If no array ref is 
 8307: provided for types, will default to return only active roles.
 8308: 
 8309: =back
 8310: 
 8311: =head2 User Modification
 8312: 
 8313: =over 4
 8314: 
 8315: =item *
 8316: 
 8317: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8318: user for the level given by URL.  Optional start and end dates (leave empty
 8319: string or zero for "no date")
 8320: 
 8321: =item *
 8322: 
 8323: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8324: change a users, password, possible return values are: ok,
 8325: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8326: refused
 8327: 
 8328: =item *
 8329: 
 8330: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8331: 
 8332: =item *
 8333: 
 8334: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8335: modify user
 8336: 
 8337: =item *
 8338: 
 8339: modifystudent
 8340: 
 8341: modify a students enrollment and identification information.
 8342: The course id is resolved based on the current users environment.  
 8343: This means the envoking user must be a course coordinator or otherwise
 8344: associated with a course.
 8345: 
 8346: This call is essentially a wrapper for lonnet::modifyuser and
 8347: lonnet::modify_student_enrollment
 8348: 
 8349: Inputs: 
 8350: 
 8351: =over 4
 8352: 
 8353: =item B<$udom> Students loncapa domain
 8354: 
 8355: =item B<$uname> Students loncapa login name
 8356: 
 8357: =item B<$uid> Students id/student number
 8358: 
 8359: =item B<$umode> Students authentication mode
 8360: 
 8361: =item B<$upass> Students password
 8362: 
 8363: =item B<$first> Students first name
 8364: 
 8365: =item B<$middle> Students middle name
 8366: 
 8367: =item B<$last> Students last name
 8368: 
 8369: =item B<$gene> Students generation
 8370: 
 8371: =item B<$usec> Students section in course
 8372: 
 8373: =item B<$end> Unix time of the roles expiration
 8374: 
 8375: =item B<$start> Unix time of the roles start date
 8376: 
 8377: =item B<$forceid> If defined, allow $uid to be changed
 8378: 
 8379: =item B<$desiredhome> server to use as home server for student
 8380: 
 8381: =back
 8382: 
 8383: =item *
 8384: 
 8385: modify_student_enrollment
 8386: 
 8387: Change a students enrollment status in a class.  The environment variable
 8388: 'role.request.course' must be defined for this function to proceed.
 8389: 
 8390: Inputs:
 8391: 
 8392: =over 4
 8393: 
 8394: =item $udom, students domain
 8395: 
 8396: =item $uname, students name
 8397: 
 8398: =item $uid, students user id
 8399: 
 8400: =item $first, students first name
 8401: 
 8402: =item $middle
 8403: 
 8404: =item $last
 8405: 
 8406: =item $gene
 8407: 
 8408: =item $usec
 8409: 
 8410: =item $end
 8411: 
 8412: =item $start
 8413: 
 8414: =back
 8415: 
 8416: 
 8417: =item *
 8418: 
 8419: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8420: custom role; give a custom role to a user for the level given by URL.  Specify
 8421: name and domain of role author, and role name
 8422: 
 8423: =item *
 8424: 
 8425: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8426: 
 8427: =item *
 8428: 
 8429: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8430: 
 8431: =back
 8432: 
 8433: =head2 Course Infomation
 8434: 
 8435: =over 4
 8436: 
 8437: =item *
 8438: 
 8439: coursedescription($courseid) : returns a hash of information about the
 8440: specified course id, including all environment settings for the
 8441: course, the description of the course will be in the hash under the
 8442: key 'description'
 8443: 
 8444: =item *
 8445: 
 8446: resdata($name,$domain,$type,@which) : request for current parameter
 8447: setting for a specific $type, where $type is either 'course' or 'user',
 8448: @what should be a list of parameters to ask about. This routine caches
 8449: answers for 5 minutes.
 8450: 
 8451: =back
 8452: 
 8453: =head2 Course Modification
 8454: 
 8455: =over 4
 8456: 
 8457: =item *
 8458: 
 8459: writecoursepref($courseid,%prefs) : write preferences (environment
 8460: database) for a course
 8461: 
 8462: =item *
 8463: 
 8464: createcourse($udom,$description,$url) : make/modify course
 8465: 
 8466: =back
 8467: 
 8468: =head2 Resource Subroutines
 8469: 
 8470: =over 4
 8471: 
 8472: =item *
 8473: 
 8474: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8475: 
 8476: =item *
 8477: 
 8478: repcopy($filename) : subscribes to the requested file, and attempts to
 8479: replicate from the owning library server, Might return
 8480: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8481: 'bad_request', also attempts to grab the metadata for the
 8482: resource. Expects the local filesystem pathname
 8483: (/home/httpd/html/res/....)
 8484: 
 8485: =back
 8486: 
 8487: =head2 Resource Information
 8488: 
 8489: =over 4
 8490: 
 8491: =item *
 8492: 
 8493: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8494: a vairety of different possible values, $varname should be a request
 8495: string, and the other parameters can be used to specify who and what
 8496: one is asking about.
 8497: 
 8498: Possible values for $varname are environment.lastname (or other item
 8499: from the envirnment hash), user.name (or someother aspect about the
 8500: user), resource.0.maxtries (or some other part and parameter of a
 8501: resource)
 8502: 
 8503: =item *
 8504: 
 8505: directcondval($number) : get current value of a condition; reads from a state
 8506: string
 8507: 
 8508: =item *
 8509: 
 8510: condval($condidx) : value of condition index based on state
 8511: 
 8512: =item *
 8513: 
 8514: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8515: resource's metadata, $what should be either a specific key, or either
 8516: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8517: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8518: 
 8519: this function automatically caches all requests
 8520: 
 8521: =item *
 8522: 
 8523: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8524: network of library servers; returns file handle of where SQL and regex results
 8525: will be stored for query
 8526: 
 8527: =item *
 8528: 
 8529: symbread($filename) : return symbolic list entry (filename argument optional);
 8530: returns the data handle
 8531: 
 8532: =item *
 8533: 
 8534: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8535: a possible symb for the URL in $thisfn, and if is an encryypted
 8536: resource that the user accessed using /enc/ returns a 1 on success, 0
 8537: on failure, user must be in a course, as it assumes the existance of
 8538: the course initial hash, and uses $env('request.course.id'}
 8539: 
 8540: 
 8541: =item *
 8542: 
 8543: symbclean($symb) : removes versions numbers from a symb, returns the
 8544: cleaned symb
 8545: 
 8546: =item *
 8547: 
 8548: is_on_map($uri) : checks if the $uri is somewhere on the current
 8549: course map, user must be in a course for it to work.
 8550: 
 8551: =item *
 8552: 
 8553: numval($salt) : return random seed value (addend for rndseed)
 8554: 
 8555: =item *
 8556: 
 8557: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8558: a random seed, all arguments are optional, if they aren't sent it uses the
 8559: environment to derive them. Note: if symb isn't sent and it can't get one
 8560: from &symbread it will use the current time as its return value
 8561: 
 8562: =item *
 8563: 
 8564: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8565: unfakeable, receipt
 8566: 
 8567: =item *
 8568: 
 8569: receipt() : API to ireceipt working off of env values; given out to users
 8570: 
 8571: =item *
 8572: 
 8573: countacc($url) : count the number of accesses to a given URL
 8574: 
 8575: =item *
 8576: 
 8577: 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
 8578: 
 8579: =item *
 8580: 
 8581: 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)
 8582: 
 8583: =item *
 8584: 
 8585: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8586: 
 8587: =item *
 8588: 
 8589: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8590: forcing spreadsheet to reevaluate the resource scores next time.
 8591: 
 8592: =back
 8593: 
 8594: =head2 Storing/Retreiving Data
 8595: 
 8596: =over 4
 8597: 
 8598: =item *
 8599: 
 8600: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8601: for this url; hashref needs to be given and should be a \%hashname; the
 8602: remaining args aren't required and if they aren't passed or are '' they will
 8603: be derived from the env
 8604: 
 8605: =item *
 8606: 
 8607: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8608: uses critical subroutine
 8609: 
 8610: =item *
 8611: 
 8612: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8613: all args are optional
 8614: 
 8615: =item *
 8616: 
 8617: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8618: dumps the complete (or key matching regexp) namespace into a hash
 8619: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8620: normally &store()ed into
 8621: 
 8622: $range should be either an integer '100' (give me the first 100
 8623:                                            matching records)
 8624:               or be  two integers sperated by a - with no spaces
 8625:                  '30-50' (give me the 30th through the 50th matching
 8626:                           records)
 8627: 
 8628: 
 8629: =item *
 8630: 
 8631: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8632: replaces a &store() version of data with a replacement set of data
 8633: for a particular resource in a namespace passed in the $storehash hash 
 8634: reference
 8635: 
 8636: =item *
 8637: 
 8638: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8639: works very similar to store/cstore, but all data is stored in a
 8640: temporary location and can be reset using tmpreset, $storehash should
 8641: be a hash reference, returns nothing on success
 8642: 
 8643: =item *
 8644: 
 8645: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8646: similar to restore, but all data is stored in a temporary location and
 8647: can be reset using tmpreset. Returns a hash of values on success,
 8648: error string otherwise.
 8649: 
 8650: =item *
 8651: 
 8652: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8653: deltes all keys for $symb form the temporary storage hash.
 8654: 
 8655: =item *
 8656: 
 8657: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8658: reference filled in from namesp ($udom and $uname are optional)
 8659: 
 8660: =item *
 8661: 
 8662: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8663: namesp ($udom and $uname are optional)
 8664: 
 8665: =item *
 8666: 
 8667: dump($namespace,$udom,$uname,$regexp,$range) : 
 8668: dumps the complete (or key matching regexp) namespace into a hash
 8669: ($udom, $uname, $regexp, $range are optional)
 8670: 
 8671: $range should be either an integer '100' (give me the first 100
 8672:                                            matching records)
 8673:               or be  two integers sperated by a - with no spaces
 8674:                  '30-50' (give me the 30th through the 50th matching
 8675:                           records)
 8676: =item *
 8677: 
 8678: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8679: $store can be a scalar, an array reference, or if the amount to be 
 8680: incremented is > 1, a hash reference.
 8681: 
 8682: ($udom and $uname are optional)
 8683: 
 8684: =item *
 8685: 
 8686: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8687: ($udom and $uname are optional)
 8688: 
 8689: =item *
 8690: 
 8691: cput($namespace,$storehash,$udom,$uname) : critical put
 8692: ($udom and $uname are optional)
 8693: 
 8694: =item *
 8695: 
 8696: newput($namespace,$storehash,$udom,$uname) :
 8697: 
 8698: Attempts to store the items in the $storehash, but only if they don't
 8699: currently exist, if this succeeds you can be certain that you have 
 8700: successfully created a new key value pair in the $namespace db.
 8701: 
 8702: 
 8703: Args:
 8704:  $namespace: name of database to store values to
 8705:  $storehash: hashref to store to the db
 8706:  $udom: (optional) domain of user containing the db
 8707:  $uname: (optional) name of user caontaining the db
 8708: 
 8709: Returns:
 8710:  'ok' -> succeeded in storing all keys of $storehash
 8711:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8712:                         least <key> already existed in the db (other
 8713:                         requested keys may also already exist)
 8714:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8715:  'con_lost' -> unable to contact request server
 8716:  'refused' -> action was not allowed by remote machine
 8717: 
 8718: 
 8719: =item *
 8720: 
 8721: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8722: reference filled in from namesp (encrypts the return communication)
 8723: ($udom and $uname are optional)
 8724: 
 8725: =item *
 8726: 
 8727: log($udom,$name,$home,$message) : write to permanent log for user; use
 8728: critical subroutine
 8729: 
 8730: =item *
 8731: 
 8732: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8733: array reference filled in from namespace found in domain level on either
 8734: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8735: 
 8736: =item *
 8737: 
 8738: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8739: domain level either on specified domain server ($uhome) or primary domain 
 8740: server ($udom and $uhome are optional)
 8741: 
 8742: =back
 8743: 
 8744: =head2 Network Status Functions
 8745: 
 8746: =over 4
 8747: 
 8748: =item *
 8749: 
 8750: dirlist($uri) : return directory list based on URI
 8751: 
 8752: =item *
 8753: 
 8754: spareserver() : find server with least workload from spare.tab
 8755: 
 8756: =back
 8757: 
 8758: =head2 Apache Request
 8759: 
 8760: =over 4
 8761: 
 8762: =item *
 8763: 
 8764: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8765: localhost, posts hash
 8766: 
 8767: =back
 8768: 
 8769: =head2 Data to String to Data
 8770: 
 8771: =over 4
 8772: 
 8773: =item *
 8774: 
 8775: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8776: and '&' separators, supports elements that are arrayrefs and hashrefs
 8777: 
 8778: =item *
 8779: 
 8780: hashref2str($hashref) : convert a hashref into a string complete with
 8781: escaping and '=' and '&' separators, supports elements that are
 8782: arrayrefs and hashrefs
 8783: 
 8784: =item *
 8785: 
 8786: arrayref2str($arrayref) : convert an arrayref into a string complete
 8787: with escaping and '&' separators, supports elements that are arrayrefs
 8788: and hashrefs
 8789: 
 8790: =item *
 8791: 
 8792: str2hash($string) : convert string to hash using unescaping and
 8793: splitting on '=' and '&', supports elements that are arrayrefs and
 8794: hashrefs
 8795: 
 8796: =item *
 8797: 
 8798: str2array($string) : convert string to hash using unescaping and
 8799: splitting on '&', supports elements that are arrayrefs and hashrefs
 8800: 
 8801: =back
 8802: 
 8803: =head2 Logging Routines
 8804: 
 8805: =over 4
 8806: 
 8807: These routines allow one to make log messages in the lonnet.log and
 8808: lonnet.perm logfiles.
 8809: 
 8810: =item *
 8811: 
 8812: logtouch() : make sure the logfile, lonnet.log, exists
 8813: 
 8814: =item *
 8815: 
 8816: logthis() : append message to the normal lonnet.log file, it gets
 8817: preiodically rolled over and deleted.
 8818: 
 8819: =item *
 8820: 
 8821: logperm() : append a permanent message to lonnet.perm.log, this log
 8822: file never gets deleted by any automated portion of the system, only
 8823: messages of critical importance should go in here.
 8824: 
 8825: =back
 8826: 
 8827: =head2 General File Helper Routines
 8828: 
 8829: =over 4
 8830: 
 8831: =item *
 8832: 
 8833: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8834: (a) files in /uploaded
 8835:   (i) If a local copy of the file exists - 
 8836:       compares modification date of local copy with last-modified date for 
 8837:       definitive version stored on home server for course. If local copy is 
 8838:       stale, requests a new version from the home server and stores it. 
 8839:       If the original has been removed from the home server, then local copy 
 8840:       is unlinked.
 8841:   (ii) If local copy does not exist -
 8842:       requests the file from the home server and stores it. 
 8843:   
 8844:   If $caller is 'uploadrep':  
 8845:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8846:     for request for files originally uploaded via DOCS. 
 8847:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8848:   
 8849:   Otherwise:
 8850:      This indicates a call from the content generation phase of the request.
 8851:      -  returns the entire contents of the file or -1.
 8852:      
 8853: (b) files in /res
 8854:    - returns the entire contents of a file or -1; 
 8855:    it properly subscribes to and replicates the file if neccessary.
 8856: 
 8857: 
 8858: =item *
 8859: 
 8860: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8861:                   reference
 8862: 
 8863: returns either a stat() list of data about the file or an empty list
 8864: if the file doesn't exist or couldn't find out about it (connection
 8865: problems or user unknown)
 8866: 
 8867: =item *
 8868: 
 8869: filelocation($dir,$file) : returns file system location of a file
 8870: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8871: directory that relative $file lookups are to looked in ($dir of /a/dir
 8872: and a file of ../bob will become /a/bob)
 8873: 
 8874: =item *
 8875: 
 8876: hreflocation($dir,$file) : returns file system location or a URL; same as
 8877: filelocation except for hrefs
 8878: 
 8879: =item *
 8880: 
 8881: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8882: 
 8883: =back
 8884: 
 8885: =head2 Usererfile file routines (/uploaded*)
 8886: 
 8887: =over 4
 8888: 
 8889: =item *
 8890: 
 8891: userfileupload(): main rotine for putting a file in a user or course's
 8892:                   filespace, arguments are,
 8893: 
 8894:  formname - required - this is the name of the element in $env where the
 8895:            filename, and the contents of the file to create/modifed exist
 8896:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8897:            contents of the file is located in $env{'form.'.$formname}
 8898:  coursedoc - if true, store the file in the course of the active role
 8899:              of the current user
 8900:  subdir - required - subdirectory to put the file in under ../userfiles/
 8901:          if undefined, it will be placed in "unknown"
 8902: 
 8903:  (This routine calls clean_filename() to remove any dangerous
 8904:  characters from the filename, and then calls finuserfileupload() to
 8905:  complete the transaction)
 8906: 
 8907:  returns either the url of the uploaded file (/uploaded/....) if successful
 8908:  and /adm/notfound.html if unsuccessful
 8909: 
 8910: =item *
 8911: 
 8912: clean_filename(): routine for cleaing a filename up for storage in
 8913:                  userfile space, argument is:
 8914: 
 8915:  filename - proposed filename
 8916: 
 8917: returns: the new clean filename
 8918: 
 8919: =item *
 8920: 
 8921: finishuserfileupload(): routine that creaes and sends the file to
 8922: userspace, probably shouldn't be called directly
 8923: 
 8924:   docuname: username or courseid of destination for the file
 8925:   docudom: domain of user/course of destination for the file
 8926:   formname: same as for userfileupload()
 8927:   fname: filename (inculding subdirectories) for the file
 8928: 
 8929:  returns either the url of the uploaded file (/uploaded/....) if successful
 8930:  and /adm/notfound.html if unsuccessful
 8931: 
 8932: =item *
 8933: 
 8934: renameuserfile(): renames an existing userfile to a new name
 8935: 
 8936:   Args:
 8937:    docuname: username or courseid of destination for the file
 8938:    docudom: domain of user/course of destination for the file
 8939:    old: current file name (including any subdirs under userfiles)
 8940:    new: desired file name (including any subdirs under userfiles)
 8941: 
 8942: =item *
 8943: 
 8944: mkdiruserfile(): creates a directory is a userfiles dir
 8945: 
 8946:   Args:
 8947:    docuname: username or courseid of destination for the file
 8948:    docudom: domain of user/course of destination for the file
 8949:    dir: dir to create (including any subdirs under userfiles)
 8950: 
 8951: =item *
 8952: 
 8953: removeuserfile(): removes a file that exists in userfiles
 8954: 
 8955:   Args:
 8956:    docuname: username or courseid of destination for the file
 8957:    docudom: domain of user/course of destination for the file
 8958:    fname: filname to delete (including any subdirs under userfiles)
 8959: 
 8960: =item *
 8961: 
 8962: removeuploadedurl(): convience function for removeuserfile()
 8963: 
 8964:   Args:
 8965:    url:  a full /uploaded/... url to delete
 8966: 
 8967: =item * 
 8968: 
 8969: get_portfile_permissions():
 8970:   Args:
 8971:     domain: domain of user or course contain the portfolio files
 8972:     user: name of user or num of course contain the portfolio files
 8973:   Returns:
 8974:     hashref of a dump of the proper file_permissions.db
 8975:    
 8976: 
 8977: =item * 
 8978: 
 8979: get_access_controls():
 8980: 
 8981: Args:
 8982:   current_permissions: the hash ref returned from get_portfile_permissions()
 8983:   group: (optional) the group you want the files associated with
 8984:   file: (optional) the file you want access info on
 8985: 
 8986: Returns:
 8987:     a hash (keys are file names) of hashes containing
 8988:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8989:         values are XML containing access control settings (see below) 
 8990: 
 8991: Internal notes:
 8992: 
 8993:  access controls are stored in file_permissions.db as key=value pairs.
 8994:     key -> path to file/file_name\0uniqueID:scope_end_start
 8995:         where scope -> public,guest,course,group,domains or users.
 8996:               end -> UNIX time for end of access (0 -> no end date)
 8997:               start -> UNIX time for start of access
 8998: 
 8999:     value -> XML description of access control
 9000:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9001:             <start></start>
 9002:             <end></end>
 9003: 
 9004:             <password></password>  for scope type = guest
 9005: 
 9006:             <domain></domain>     for scope type = course or group
 9007:             <number></number>
 9008:             <roles id="">
 9009:              <role></role>
 9010:              <access></access>
 9011:              <section></section>
 9012:              <group></group>
 9013:             </roles>
 9014: 
 9015:             <dom></dom>         for scope type = domains
 9016: 
 9017:             <users>             for scope type = users
 9018:              <user>
 9019:               <uname></uname>
 9020:               <udom></udom>
 9021:              </user>
 9022:             </users>
 9023:            </scope> 
 9024:               
 9025:  Access data is also aggregated for each file in an additional key=value pair:
 9026:  key -> path to file/file_name\0accesscontrol 
 9027:  value -> reference to hash
 9028:           hash contains key = value pairs
 9029:           where key = uniqueID:scope_end_start
 9030:                 value = UNIX time record was last updated
 9031: 
 9032:           Used to improve speed of look-ups of access controls for each file.  
 9033:  
 9034:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9035: 
 9036: modify_access_controls():
 9037: 
 9038: Modifies access controls for a portfolio file
 9039: Args
 9040: 1. file name
 9041: 2. reference to hash of required changes,
 9042: 3. domain
 9043: 4. username
 9044:   where domain,username are the domain of the portfolio owner 
 9045:   (either a user or a course) 
 9046: 
 9047: Returns:
 9048: 1. result of additions or updates ('ok' or 'error', with error message). 
 9049: 2. result of deletions ('ok' or 'error', with error message).
 9050: 3. reference to hash of any new or updated access controls.
 9051: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9052:    key = integer (inbound ID)
 9053:    value = uniqueID  
 9054: 
 9055: =back
 9056: 
 9057: =head2 HTTP Helper Routines
 9058: 
 9059: =over 4
 9060: 
 9061: =item *
 9062: 
 9063: escape() : unpack non-word characters into CGI-compatible hex codes
 9064: 
 9065: =item *
 9066: 
 9067: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9068: 
 9069: =back
 9070: 
 9071: =head1 PRIVATE SUBROUTINES
 9072: 
 9073: =head2 Underlying communication routines (Shouldn't call)
 9074: 
 9075: =over 4
 9076: 
 9077: =item *
 9078: 
 9079: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9080: 
 9081: =item *
 9082: 
 9083: reply() : uses subreply to send a message to remote machine, logs all failures
 9084: 
 9085: =item *
 9086: 
 9087: critical() : passes a critical message to another server; if cannot
 9088: get through then place message in connection buffer directory and
 9089: returns con_delayed, if incapable of saving message, returns
 9090: con_failed
 9091: 
 9092: =item *
 9093: 
 9094: reconlonc() : tries to reconnect lonc client processes.
 9095: 
 9096: =back
 9097: 
 9098: =head2 Resource Access Logging
 9099: 
 9100: =over 4
 9101: 
 9102: =item *
 9103: 
 9104: flushcourselogs() : flush (save) buffer logs and access logs
 9105: 
 9106: =item *
 9107: 
 9108: courselog($what) : save message for course in hash
 9109: 
 9110: =item *
 9111: 
 9112: courseacclog($what) : save message for course using &courselog().  Perform
 9113: special processing for specific resource types (problems, exams, quizzes, etc).
 9114: 
 9115: =item *
 9116: 
 9117: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9118: as a PerlChildExitHandler
 9119: 
 9120: =back
 9121: 
 9122: =head2 Other
 9123: 
 9124: =over 4
 9125: 
 9126: =item *
 9127: 
 9128: symblist($mapname,%newhash) : update symbolic storage links
 9129: 
 9130: =back
 9131: 
 9132: =cut

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