File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.874: download - view: text, annotated - select for diffs
Mon May 14 08:47:54 2007 UTC (17 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- cleanup some startup warnings

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.874 2007/05/14 08:47:54 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Date;
   35: # use Date::Parse;
   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   37:             $_64bit %env);
   38: 
   39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   42:     %courseownerbuf, %coursetypebuf);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use Fcntl qw(:flock);
   48: use Storable qw(thaw nfreeze);
   49: use Time::HiRes qw( gettimeofday tv_interval );
   50: use Cache::Memcached;
   51: use Digest::MD5;
   52: use Math::Random;
   53: use LONCAPA qw(:DEFAULT :match);
   54: use LONCAPA::Configuration;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: {
   89:     my $logid;
   90:     sub instructor_log {
   91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   92: 	$logid++;
   93: 	my $id=time().'00000'.$$.'00000'.$logid;
   94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   95: 				    { $id => {
   96: 					'exe_uname' => $env{'user.name'},
   97: 					'exe_udom'  => $env{'user.domain'},
   98: 					'exe_time'  => time(),
   99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  100: 					'delflag'   => $delflag,
  101: 					'logentry'  => $storehash,
  102: 					'uname'     => $uname,
  103: 					'udom'      => $udom,
  104: 				    }
  105: 				  },
  106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  108: 				    );
  109:     }
  110: }
  111: 
  112: sub logtouch {
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     unless (-e "$execdir/logs/lonnet.log") {	
  115: 	open(my $fh,">>$execdir/logs/lonnet.log");
  116: 	close $fh;
  117:     }
  118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  120: }
  121: 
  122: sub logthis {
  123:     my $message=shift;
  124:     my $execdir=$perlvar{'lonDaemons'};
  125:     my $now=time;
  126:     my $local=localtime($now);
  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  128: 	print $fh "$local ($$): $message\n";
  129: 	close($fh);
  130:     }
  131:     return 1;
  132: }
  133: 
  134: sub logperm {
  135:     my $message=shift;
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     my $now=time;
  138:     my $local=localtime($now);
  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  140: 	print $fh "$now:$message:$local\n";
  141: 	close($fh);
  142:     }
  143:     return 1;
  144: }
  145: 
  146: sub create_connection {
  147:     my ($hostname,$lonid) = @_;
  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  149: 				     Type    => SOCK_STREAM,
  150: 				     Timeout => 10);
  151:     return 0 if (!$client);
  152:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
  153:     my $result = <$client>;
  154:     chomp($result);
  155:     return 1 if ($result eq 'done');
  156:     return 0;
  157: }
  158: 
  159: 
  160: # -------------------------------------------------- Non-critical communication
  161: sub subreply {
  162:     my ($cmd,$server)=@_;
  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  164:     #
  165:     #  With loncnew process trimming, there's a timing hole between lonc server
  166:     #  process exit and the master server picking up the listen on the AF_UNIX
  167:     #  socket.  In that time interval, a lock file will exist:
  168: 
  169:     my $lockfile=$peerfile.".lock";
  170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  171: 	sleep(1);
  172:     }
  173:     # At this point, either a loncnew parent is listening or an old lonc
  174:     # or loncnew child is listening so we can connect or everything's dead.
  175:     #
  176:     #   We'll give the connection a few tries before abandoning it.  If
  177:     #   connection is not possible, we'll con_lost back to the client.
  178:     #   
  179:     my $client;
  180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  182: 				      Type    => SOCK_STREAM,
  183: 				      Timeout => 10);
  184: 	if ($client) {
  185: 	    last;		# Connected!
  186: 	} else {
  187: 	    &create_connection(&hostname($server),$server);
  188: 	}
  189:         sleep(1);		# Try again later if failed connection.
  190:     }
  191:     my $answer;
  192:     if ($client) {
  193: 	print $client "sethost:$server:$cmd\n";
  194: 	$answer=<$client>;
  195: 	if (!$answer) { $answer="con_lost"; }
  196: 	chomp($answer);
  197:     } else {
  198: 	$answer = 'con_lost';	# Failed connection.
  199:     }
  200:     return $answer;
  201: }
  202: 
  203: sub reply {
  204:     my ($cmd,$server)=@_;
  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  206:     my $answer=subreply($cmd,$server);
  207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  208:        &logthis("<font color=\"blue\">WARNING:".
  209:                 " $cmd to $server returned $answer</font>");
  210:     }
  211:     return $answer;
  212: }
  213: 
  214: # ----------------------------------------------------------- Send USR1 to lonc
  215: 
  216: sub reconlonc {
  217:     &logthis("Trying to reconnect lonc");
  218:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  219:     if (open(my $fh,"<$loncfile")) {
  220: 	my $loncpid=<$fh>;
  221:         chomp($loncpid);
  222:         if (kill 0 => $loncpid) {
  223: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  224:             kill USR1 => $loncpid;
  225:             sleep 1;
  226:          } else {
  227: 	    &logthis(
  228:                "<font color=\"blue\">WARNING:".
  229:                " lonc at pid $loncpid not responding, giving up</font>");
  230:         }
  231:     } else {
  232: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  233:     }
  234: }
  235: 
  236: # ------------------------------------------------------ Critical communication
  237: 
  238: sub critical {
  239:     my ($cmd,$server)=@_;
  240:     unless (&hostname($server)) {
  241:         &logthis("<font color=\"blue\">WARNING:".
  242:                " Critical message to unknown server ($server)</font>");
  243:         return 'no_such_host';
  244:     }
  245:     my $answer=reply($cmd,$server);
  246:     if ($answer eq 'con_lost') {
  247: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  248: 	my $answer=reply($cmd,$server);
  249:         if ($answer eq 'con_lost') {
  250:             my $now=time;
  251:             my $middlename=$cmd;
  252:             $middlename=substr($middlename,0,16);
  253:             $middlename=~s/\W//g;
  254:             my $dfilename=
  255:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  256:             $dumpcount++;
  257:             {
  258: 		my $dfh;
  259: 		if (open($dfh,">$dfilename")) {
  260: 		    print $dfh "$cmd\n"; 
  261: 		    close($dfh);
  262: 		}
  263:             }
  264:             sleep 2;
  265:             my $wcmd='';
  266:             {
  267: 		my $dfh;
  268: 		if (open($dfh,"<$dfilename")) {
  269: 		    $wcmd=<$dfh>; 
  270: 		    close($dfh);
  271: 		}
  272:             }
  273:             chomp($wcmd);
  274:             if ($wcmd eq $cmd) {
  275: 		&logthis("<font color=\"blue\">WARNING: ".
  276:                          "Connection buffer $dfilename: $cmd</font>");
  277:                 &logperm("D:$server:$cmd");
  278: 	        return 'con_delayed';
  279:             } else {
  280:                 &logthis("<font color=\"red\">CRITICAL:"
  281:                         ." Critical connection failed: $server $cmd</font>");
  282:                 &logperm("F:$server:$cmd");
  283:                 return 'con_failed';
  284:             }
  285:         }
  286:     }
  287:     return $answer;
  288: }
  289: 
  290: # ------------------------------------------- check if return value is an error
  291: 
  292: sub error {
  293:     my ($result) = @_;
  294:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  295: 	if ($2 == 2) { return undef; }
  296: 	return $1;
  297:     }
  298:     return undef;
  299: }
  300: 
  301: sub convert_and_load_session_env {
  302:     my ($lonidsdir,$handle)=@_;
  303:     my @profile;
  304:     {
  305: 	open(my $idf,"$lonidsdir/$handle.id");
  306: 	flock($idf,LOCK_SH);
  307: 	@profile=<$idf>;
  308: 	close($idf);
  309:     }
  310:     my %temp_env;
  311:     foreach my $line (@profile) {
  312: 	if ($line !~ m/=/) {
  313: 	    return 0;
  314: 	}
  315: 	chomp($line);
  316: 	my ($envname,$envvalue)=split(/=/,$line,2);
  317: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  318:     }
  319:     unlink("$lonidsdir/$handle.id");
  320:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  321: 	    0640)) {
  322: 	%disk_env = %temp_env;
  323: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  324: 	untie(%disk_env);
  325:     }
  326:     return 1;
  327: }
  328: 
  329: # ------------------------------------------- Transfer profile into environment
  330: my $env_loaded;
  331: sub transfer_profile_to_env {
  332:     my ($lonidsdir,$handle,$force_transfer) = @_;
  333:     if (!$force_transfer && $env_loaded) { return; } 
  334: 
  335:     if (!defined($lonidsdir)) {
  336: 	$lonidsdir = $perlvar{'lonIDsDir'};
  337:     }
  338:     if (!defined($handle)) {
  339:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  340:     }
  341: 
  342:     my $convert;
  343:     {
  344:     	open(my $idf,"$lonidsdir/$handle.id");
  345: 	flock($idf,LOCK_SH);
  346: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  347: 		&GDBM_READER(),0640)) {
  348: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  349: 	    untie(%disk_env);
  350: 	} else {
  351: 	    $convert = 1;
  352: 	}
  353:     }
  354:     if ($convert) {
  355: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  356: 	    &logthis("Failed to load session, or convert session.");
  357: 	}
  358:     }
  359: 
  360:     my %remove;
  361:     while ( my $envname = each(%env) ) {
  362:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  363:             if ($time < time-300) {
  364:                 $remove{$key}++;
  365:             }
  366:         }
  367:     }
  368: 
  369:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  370:     $env_loaded=1;
  371:     foreach my $expired_key (keys(%remove)) {
  372:         &delenv($expired_key);
  373:     }
  374: }
  375: 
  376: sub timed_flock {
  377:     my ($file,$lock_type) = @_;
  378:     my $failed=0;
  379:     eval {
  380: 	local $SIG{__DIE__}='DEFAULT';
  381: 	local $SIG{ALRM}=sub {
  382: 	    $failed=1;
  383: 	    die("failed lock");
  384: 	};
  385: 	alarm(13);
  386: 	flock($file,$lock_type);
  387: 	alarm(0);
  388:     };
  389:     if ($failed) {
  390: 	return undef;
  391:     } else {
  392: 	return 1;
  393:     }
  394: }
  395: 
  396: # ---------------------------------------------------------- Append Environment
  397: 
  398: sub appenv {
  399:     my %newenv=@_;
  400:     foreach my $key (keys(%newenv)) {
  401: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  402:             &logthis("<font color=\"blue\">WARNING: ".
  403:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  404:                 .'</font>');
  405: 	    delete($newenv{$key});
  406:         } else {
  407:             $env{$key}=$newenv{$key};
  408:         }
  409:     }
  410:     open(my $env_file,$env{'user.environment'});
  411:     if (&timed_flock($env_file,LOCK_EX)
  412: 	&&
  413: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  414: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  415: 	while (my ($key,$value) = each(%newenv)) {
  416: 	    $disk_env{$key} = $value;
  417: 	}
  418: 	untie(%disk_env);
  419:     }
  420:     return 'ok';
  421: }
  422: # ----------------------------------------------------- Delete from Environment
  423: 
  424: sub delenv {
  425:     my $delthis=shift;
  426:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  427:         &logthis("<font color=\"blue\">WARNING: ".
  428:                 "Attempt to delete from environment ".$delthis);
  429:         return 'error';
  430:     }
  431:     open(my $env_file,$env{'user.environment'});
  432:     if (&timed_flock($env_file,LOCK_EX)
  433: 	&&
  434: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  435: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  436: 	foreach my $key (keys(%disk_env)) {
  437: 	    if ($key=~/^$delthis/) { 
  438:                 delete($env{$key});
  439:                 delete($disk_env{$key});
  440:             }
  441: 	}
  442: 	untie(%disk_env);
  443:     }
  444:     return 'ok';
  445: }
  446: 
  447: sub get_env_multiple {
  448:     my ($name) = @_;
  449:     my @values;
  450:     if (defined($env{$name})) {
  451:         # exists is it an array
  452:         if (ref($env{$name})) {
  453:             @values=@{ $env{$name} };
  454:         } else {
  455:             $values[0]=$env{$name};
  456:         }
  457:     }
  458:     return(@values);
  459: }
  460: 
  461: # ------------------------------------------ Find out current server userload
  462: # there is a copy in lond
  463: sub userload {
  464:     my $numusers=0;
  465:     {
  466: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  467: 	my $filename;
  468: 	my $curtime=time;
  469: 	while ($filename=readdir(LONIDS)) {
  470: 	    if ($filename eq '.' || $filename eq '..') {next;}
  471: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  472: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  473: 	}
  474: 	closedir(LONIDS);
  475:     }
  476:     my $userloadpercent=0;
  477:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  478:     if ($maxuserload) {
  479: 	$userloadpercent=100*$numusers/$maxuserload;
  480:     }
  481:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  482:     return $userloadpercent;
  483: }
  484: 
  485: # ------------------------------------------ Fight off request when overloaded
  486: 
  487: sub overloaderror {
  488:     my ($r,$checkserver)=@_;
  489:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  490:     my $loadavg;
  491:     if ($checkserver eq $perlvar{'lonHostID'}) {
  492:        open(my $loadfile,'/proc/loadavg');
  493:        $loadavg=<$loadfile>;
  494:        $loadavg =~ s/\s.*//g;
  495:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  496:        close($loadfile);
  497:     } else {
  498:        $loadavg=&reply('load',$checkserver);
  499:     }
  500:     my $overload=$loadavg-100;
  501:     if ($overload>0) {
  502: 	$r->err_headers_out->{'Retry-After'}=$overload;
  503:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  504:         return 413;
  505:     }    
  506:     return '';
  507: }
  508: 
  509: # ------------------------------ Find server with least workload from spare.tab
  510: 
  511: sub spareserver {
  512:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  513:     my $spare_server;
  514:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  515:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  516:                                                      :  $userloadpercent;
  517:     
  518:     foreach my $try_server (@{ $spareid{'primary'} }) {
  519: 	($spare_server, $lowest_load) =
  520: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  521:     }
  522: 
  523:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  524: 
  525:     if (!$found_server) {
  526: 	foreach my $try_server (@{ $spareid{'default'} }) {
  527: 	    ($spare_server, $lowest_load) =
  528: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  529: 	}
  530:     }
  531: 
  532:     if (!$want_server_name) {
  533: 	$spare_server="http://".&hostname($spare_server);
  534:     }
  535:     return $spare_server;
  536: }
  537: 
  538: sub compare_server_load {
  539:     my ($try_server, $spare_server, $lowest_load) = @_;
  540: 
  541:     my $loadans     = &reply('load',    $try_server);
  542:     my $userloadans = &reply('userload',$try_server);
  543: 
  544:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  545: 	next; #didn't get a number from the server
  546:     }
  547: 
  548:     my $load;
  549:     if ($loadans =~ /\d/) {
  550: 	if ($userloadans =~ /\d/) {
  551: 	    #both are numbers, pick the bigger one
  552: 	    $load = ($loadans > $userloadans) ? $loadans 
  553: 		                              : $userloadans;
  554: 	} else {
  555: 	    $load = $loadans;
  556: 	}
  557:     } else {
  558: 	$load = $userloadans;
  559:     }
  560: 
  561:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  562: 	$spare_server = $try_server;
  563: 	$lowest_load  = $load;
  564:     }
  565:     return ($spare_server,$lowest_load);
  566: }
  567: # --------------------------------------------- Try to change a user's password
  568: 
  569: sub changepass {
  570:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  571:     $currentpass = &escape($currentpass);
  572:     $newpass     = &escape($newpass);
  573:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  574: 		       $server);
  575:     if (! $answer) {
  576: 	&logthis("No reply on password change request to $server ".
  577: 		 "by $uname in domain $udom.");
  578:     } elsif ($answer =~ "^ok") {
  579:         &logthis("$uname in $udom successfully changed their password ".
  580: 		 "on $server.");
  581:     } elsif ($answer =~ "^pwchange_failure") {
  582: 	&logthis("$uname in $udom was unable to change their password ".
  583: 		 "on $server.  The action was blocked by either lcpasswd ".
  584: 		 "or pwchange");
  585:     } elsif ($answer =~ "^non_authorized") {
  586:         &logthis("$uname in $udom did not get their password correct when ".
  587: 		 "attempting to change it on $server.");
  588:     } elsif ($answer =~ "^auth_mode_error") {
  589:         &logthis("$uname in $udom attempted to change their password despite ".
  590: 		 "not being locally or internally authenticated on $server.");
  591:     } elsif ($answer =~ "^unknown_user") {
  592:         &logthis("$uname in $udom attempted to change their password ".
  593: 		 "on $server but were unable to because $server is not ".
  594: 		 "their home server.");
  595:     } elsif ($answer =~ "^refused") {
  596: 	&logthis("$server refused to change $uname in $udom password because ".
  597: 		 "it was sent an unencrypted request to change the password.");
  598:     }
  599:     return $answer;
  600: }
  601: 
  602: # ----------------------- Try to determine user's current authentication scheme
  603: 
  604: sub queryauthenticate {
  605:     my ($uname,$udom)=@_;
  606:     my $uhome=&homeserver($uname,$udom);
  607:     if (!$uhome) {
  608: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  609: 	return 'no_host';
  610:     }
  611:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  612:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  613: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  614:     }
  615:     return $answer;
  616: }
  617: 
  618: # --------- Try to authenticate user from domain's lib servers (first this one)
  619: 
  620: sub authenticate {
  621:     my ($uname,$upass,$udom)=@_;
  622:     $upass=&escape($upass);
  623:     $uname= &LONCAPA::clean_username($uname);
  624:     my $uhome=&homeserver($uname,$udom,1);
  625:     if ((!$uhome) || ($uhome eq 'no_host')) {
  626: # Maybe the machine was offline and only re-appeared again recently?
  627:         &reconlonc();
  628: # One more
  629: 	my $uhome=&homeserver($uname,$udom,1);
  630: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  631: 	    &logthis("User $uname at $udom is unknown in authenticate");
  632: 	}
  633: 	return 'no_host';
  634:     }
  635:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  636:     if ($answer eq 'authorized') {
  637: 	&logthis("User $uname at $udom authorized by $uhome"); 
  638: 	return $uhome; 
  639:     }
  640:     if ($answer eq 'non_authorized') {
  641: 	&logthis("User $uname at $udom rejected by $uhome");
  642: 	return 'no_host'; 
  643:     }
  644:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  645:     return 'no_host';
  646: }
  647: 
  648: # ---------------------- Find the homebase for a user from domain's lib servers
  649: 
  650: my %homecache;
  651: sub homeserver {
  652:     my ($uname,$udom,$ignoreBadCache)=@_;
  653:     my $index="$uname:$udom";
  654: 
  655:     if (exists($homecache{$index})) { return $homecache{$index}; }
  656: 
  657:     my %servers = &get_servers($udom,'library');
  658:     foreach my $tryserver (keys(%servers)) {
  659:         next if ($ignoreBadCache ne 'true' && 
  660: 		 exists($badServerCache{$tryserver}));
  661: 
  662: 	my $answer=reply("home:$udom:$uname",$tryserver);
  663: 	if ($answer eq 'found') {
  664: 	    delete($badServerCache{$tryserver}); 
  665: 	    return $homecache{$index}=$tryserver;
  666: 	} elsif ($answer eq 'no_host') {
  667: 	    $badServerCache{$tryserver}=1;
  668: 	}
  669:     }    
  670:     return 'no_host';
  671: }
  672: 
  673: # ------------------------------------- Find the usernames behind a list of IDs
  674: 
  675: sub idget {
  676:     my ($udom,@ids)=@_;
  677:     my %returnhash=();
  678:     
  679:     my %servers = &get_servers($udom,'library');
  680:     foreach my $tryserver (keys(%servers)) {
  681: 	my $idlist=join('&',@ids);
  682: 	$idlist=~tr/A-Z/a-z/; 
  683: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  684: 	my @answer=();
  685: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  686: 	    @answer=split(/\&/,$reply);
  687: 	}                    ;
  688: 	my $i;
  689: 	for ($i=0;$i<=$#ids;$i++) {
  690: 	    if ($answer[$i]) {
  691: 		$returnhash{$ids[$i]}=$answer[$i];
  692: 	    } 
  693: 	}
  694:     } 
  695:     return %returnhash;
  696: }
  697: 
  698: # ------------------------------------- Find the IDs behind a list of usernames
  699: 
  700: sub idrget {
  701:     my ($udom,@unames)=@_;
  702:     my %returnhash=();
  703:     foreach my $uname (@unames) {
  704:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  705:     }
  706:     return %returnhash;
  707: }
  708: 
  709: # ------------------------------- Store away a list of names and associated IDs
  710: 
  711: sub idput {
  712:     my ($udom,%ids)=@_;
  713:     my %servers=();
  714:     foreach my $uname (keys(%ids)) {
  715: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  716:         my $uhom=&homeserver($uname,$udom);
  717:         if ($uhom ne 'no_host') {
  718:             my $id=&escape($ids{$uname});
  719:             $id=~tr/A-Z/a-z/;
  720:             my $esc_unam=&escape($uname);
  721: 	    if ($servers{$uhom}) {
  722: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  723:             } else {
  724:                 $servers{$uhom}=$id.'='.$esc_unam;
  725:             }
  726:         }
  727:     }
  728:     foreach my $server (keys(%servers)) {
  729:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  730:     }
  731: }
  732: 
  733: # ------------------------------------------- get items from domain db files   
  734: 
  735: sub get_dom {
  736:     my ($namespace,$storearr,$udom,$uhome)=@_;
  737:     my $items='';
  738:     foreach my $item (@$storearr) {
  739:         $items.=&escape($item).'&';
  740:     }
  741:     $items=~s/\&$//;
  742:     if (!$udom) {
  743:         $udom=$env{'user.domain'};
  744:         if (defined(&domain($udom,'primary'))) {
  745:             $uhome=&domain($udom,'primary');
  746:         } else {
  747:             undef($uhome);
  748:         }
  749:     } else {
  750:         if (!$uhome) {
  751:             if (defined(&domain($udom,'primary'))) {
  752:                 $uhome=&domain($udom,'primary');
  753:             }
  754:         }
  755:     }
  756:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  757:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  758:         my %returnhash;
  759:         if ($rep =~ /^error: 2 /) {
  760:             return %returnhash;
  761:         }
  762:         my @pairs=split(/\&/,$rep);
  763:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  764:             return @pairs;
  765:         }
  766:         my $i=0;
  767:         foreach my $item (@$storearr) {
  768:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  769:             $i++;
  770:         }
  771:         return %returnhash;
  772:     } else {
  773:         &logthis("get_dom failed - no homeserver and/or domain");
  774:     }
  775: }
  776: 
  777: # -------------------------------------------- put items in domain db files 
  778: 
  779: sub put_dom {
  780:     my ($namespace,$storehash,$udom,$uhome)=@_;
  781:     if (!$udom) {
  782:         $udom=$env{'user.domain'};
  783:         if (defined(&domain($udom,'primary'))) {
  784:             $uhome=&domain($udom,'primary');
  785:         } else {
  786:             undef($uhome);
  787:         }
  788:     } else {
  789:         if (!$uhome) {
  790:             if (defined(&domain($udom,'primary'))) {
  791:                 $uhome=&domain($udom,'primary');
  792:             }
  793:         }
  794:     } 
  795:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  796:         my $items='';
  797:         foreach my $item (keys(%$storehash)) {
  798:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  799:         }
  800:         $items=~s/\&$//;
  801:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  802:     } else {
  803:         &logthis("put_dom failed - no homeserver and/or domain");
  804:     }
  805: }
  806: 
  807: sub retrieve_inst_usertypes {
  808:     my ($udom) = @_;
  809:     my (%returnhash,@order);
  810:     if (defined(&domain($udom,'primary'))) {
  811:         my $uhome=&domain($udom,'primary');
  812:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  813:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  814:         my @pairs=split(/\&/,$hashitems);
  815:         foreach my $item (@pairs) {
  816:             my ($key,$value)=split(/=/,$item,2);
  817:             $key = &unescape($key);
  818:             next if ($key =~ /^error: 2 /);
  819:             $returnhash{$key}=&thaw_unescape($value);
  820:         }
  821:         my @esc_order = split(/\&/,$orderitems);
  822:         foreach my $item (@esc_order) {
  823:             push(@order,&unescape($item));
  824:         }
  825:     } else {
  826:         &logthis("get_dom failed - no primary domain server for $udom");
  827:     }
  828:     return (\%returnhash,\@order);
  829: }
  830: 
  831: sub is_domainimage {
  832:     my ($url) = @_;
  833:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  834:         if (&domain($1) ne '') {
  835:             return '1';
  836:         }
  837:     }
  838:     return;
  839: }
  840: 
  841: # --------------------------------------------------- Assign a key to a student
  842: 
  843: sub assign_access_key {
  844: #
  845: # a valid key looks like uname:udom#comments
  846: # comments are being appended
  847: #
  848:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  849:     $kdom=
  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  851:     $knum=
  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  853:     $cdom=
  854:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  855:     $cnum=
  856:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  857:     $udom=$env{'user.name'} unless (defined($udom));
  858:     $uname=$env{'user.domain'} unless (defined($uname));
  859:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  860:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  861:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  862:                                                   # assigned to this person
  863:                                                   # - this should not happen,
  864:                                                   # unless something went wrong
  865:                                                   # the first time around
  866: # ready to assign
  867:         $logentry=$1.'; '.$logentry;
  868:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  869:                                                  $kdom,$knum) eq 'ok') {
  870: # key now belongs to user
  871: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  872:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  873:                 &appenv('environment.'.$envkey => $ckey);
  874:                 return 'ok';
  875:             } else {
  876:                 return 
  877:   'error: Count not permanently assign key, will need to be re-entered later.';
  878: 	    }
  879:         } else {
  880:             return 'error: Could not assign key, try again later.';
  881:         }
  882:     } elsif (!$existing{$ckey}) {
  883: # the key does not exist
  884: 	return 'error: The key does not exist';
  885:     } else {
  886: # the key is somebody else's
  887: 	return 'error: The key is already in use';
  888:     }
  889: }
  890: 
  891: # ------------------------------------------ put an additional comment on a key
  892: 
  893: sub comment_access_key {
  894: #
  895: # a valid key looks like uname:udom#comments
  896: # comments are being appended
  897: #
  898:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  899:     $cdom=
  900:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  901:     $cnum=
  902:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  903:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  904:     if ($existing{$ckey}) {
  905:         $existing{$ckey}.='; '.$logentry;
  906: # ready to assign
  907:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  908:                                                  $cdom,$cnum) eq 'ok') {
  909: 	    return 'ok';
  910:         } else {
  911: 	    return 'error: Count not store comment.';
  912:         }
  913:     } else {
  914: # the key does not exist
  915: 	return 'error: The key does not exist';
  916:     }
  917: }
  918: 
  919: # ------------------------------------------------------ Generate a set of keys
  920: 
  921: sub generate_access_keys {
  922:     my ($number,$cdom,$cnum,$logentry)=@_;
  923:     $cdom=
  924:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  925:     $cnum=
  926:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  927:     unless (&allowed('mky',$cdom)) { return 0; }
  928:     unless (($cdom) && ($cnum)) { return 0; }
  929:     if ($number>10000) { return 0; }
  930:     sleep(2); # make sure don't get same seed twice
  931:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  932:     my $total=0;
  933:     for (my $i=1;$i<=$number;$i++) {
  934:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  935:                   sprintf("%lx",int(100000*rand)).'-'.
  936:                   sprintf("%lx",int(100000*rand));
  937:        $newkey=~s/1/g/g; # folks mix up 1 and l
  938:        $newkey=~s/0/h/g; # and also 0 and O
  939:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  940:        if ($existing{$newkey}) {
  941:            $i--;
  942:        } else {
  943: 	  if (&put('accesskeys',
  944:               { $newkey => '# generated '.localtime().
  945:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  946:                            '; '.$logentry },
  947: 		   $cdom,$cnum) eq 'ok') {
  948:               $total++;
  949: 	  }
  950:        }
  951:     }
  952:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  953:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  954:     return $total;
  955: }
  956: 
  957: # ------------------------------------------------------- Validate an accesskey
  958: 
  959: sub validate_access_key {
  960:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  961:     $cdom=
  962:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  963:     $cnum=
  964:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  965:     $udom=$env{'user.domain'} unless (defined($udom));
  966:     $uname=$env{'user.name'} unless (defined($uname));
  967:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  968:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  969: }
  970: 
  971: # ------------------------------------- Find the section of student in a course
  972: sub devalidate_getsection_cache {
  973:     my ($udom,$unam,$courseid)=@_;
  974:     my $hashid="$udom:$unam:$courseid";
  975:     &devalidate_cache_new('getsection',$hashid);
  976: }
  977: 
  978: sub courseid_to_courseurl {
  979:     my ($courseid) = @_;
  980:     #already url style courseid
  981:     return $courseid if ($courseid =~ m{^/});
  982: 
  983:     if (exists($env{'course.'.$courseid.'.num'})) {
  984: 	my $cnum = $env{'course.'.$courseid.'.num'};
  985: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  986: 	return "/$cdom/$cnum";
  987:     }
  988: 
  989:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  990:     if (exists($courseinfo{'num'})) {
  991: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  992:     }
  993: 
  994:     return undef;
  995: }
  996: 
  997: sub getsection {
  998:     my ($udom,$unam,$courseid)=@_;
  999:     my $cachetime=1800;
 1000: 
 1001:     my $hashid="$udom:$unam:$courseid";
 1002:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1003:     if (defined($cached)) { return $result; }
 1004: 
 1005:     my %Pending; 
 1006:     my %Expired;
 1007:     #
 1008:     # Each role can either have not started yet (pending), be active, 
 1009:     #    or have expired.
 1010:     #
 1011:     # If there is an active role, we are done.
 1012:     #
 1013:     # If there is more than one role which has not started yet, 
 1014:     #     choose the one which will start sooner
 1015:     # If there is one role which has not started yet, return it.
 1016:     #
 1017:     # If there is more than one expired role, choose the one which ended last.
 1018:     # If there is a role which has expired, return it.
 1019:     #
 1020:     $courseid = &courseid_to_courseurl($courseid);
 1021:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1022:     foreach my $key (keys(%roleshash)) {
 1023:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1024:         my $section=$1;
 1025:         if ($key eq $courseid.'_st') { $section=''; }
 1026:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1027:         my $now=time;
 1028:         if (defined($end) && $end && ($now > $end)) {
 1029:             $Expired{$end}=$section;
 1030:             next;
 1031:         }
 1032:         if (defined($start) && $start && ($now < $start)) {
 1033:             $Pending{$start}=$section;
 1034:             next;
 1035:         }
 1036:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1037:     }
 1038:     #
 1039:     # Presumedly there will be few matching roles from the above
 1040:     # loop and the sorting time will be negligible.
 1041:     if (scalar(keys(%Pending))) {
 1042:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1043:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1044:     } 
 1045:     if (scalar(keys(%Expired))) {
 1046:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1047:         my $time = pop(@sorted);
 1048:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1049:     }
 1050:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1051: }
 1052: 
 1053: sub save_cache {
 1054:     &purge_remembered();
 1055:     #&Apache::loncommon::validate_page();
 1056:     undef(%env);
 1057:     undef($env_loaded);
 1058: }
 1059: 
 1060: my $to_remember=-1;
 1061: my %remembered;
 1062: my %accessed;
 1063: my $kicks=0;
 1064: my $hits=0;
 1065: sub make_key {
 1066:     my ($name,$id) = @_;
 1067:     if (length($id) > 65 
 1068: 	&& length(&escape($id)) > 200) {
 1069: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1070:     }
 1071:     return &escape($name.':'.$id);
 1072: }
 1073: 
 1074: sub devalidate_cache_new {
 1075:     my ($name,$id,$debug) = @_;
 1076:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1077:     $id=&make_key($name,$id);
 1078:     $memcache->delete($id);
 1079:     delete($remembered{$id});
 1080:     delete($accessed{$id});
 1081: }
 1082: 
 1083: sub is_cached_new {
 1084:     my ($name,$id,$debug) = @_;
 1085:     $id=&make_key($name,$id);
 1086:     if (exists($remembered{$id})) {
 1087: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1088: 	$accessed{$id}=[&gettimeofday()];
 1089: 	$hits++;
 1090: 	return ($remembered{$id},1);
 1091:     }
 1092:     my $value = $memcache->get($id);
 1093:     if (!(defined($value))) {
 1094: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1095: 	return (undef,undef);
 1096:     }
 1097:     if ($value eq '__undef__') {
 1098: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1099: 	$value=undef;
 1100:     }
 1101:     &make_room($id,$value,$debug);
 1102:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1103:     return ($value,1);
 1104: }
 1105: 
 1106: sub do_cache_new {
 1107:     my ($name,$id,$value,$time,$debug) = @_;
 1108:     $id=&make_key($name,$id);
 1109:     my $setvalue=$value;
 1110:     if (!defined($setvalue)) {
 1111: 	$setvalue='__undef__';
 1112:     }
 1113:     if (!defined($time) ) {
 1114: 	$time=600;
 1115:     }
 1116:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1117:     if (!($memcache->set($id,$setvalue,$time))) {
 1118: 	&logthis("caching of id -> $id  failed");
 1119:     }
 1120:     # need to make a copy of $value
 1121:     #&make_room($id,$value,$debug);
 1122:     return $value;
 1123: }
 1124: 
 1125: sub make_room {
 1126:     my ($id,$value,$debug)=@_;
 1127:     $remembered{$id}=$value;
 1128:     if ($to_remember<0) { return; }
 1129:     $accessed{$id}=[&gettimeofday()];
 1130:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1131:     my $to_kick;
 1132:     my $max_time=0;
 1133:     foreach my $other (keys(%accessed)) {
 1134: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1135: 	    $to_kick=$other;
 1136: 	    $max_time=&tv_interval($accessed{$other});
 1137: 	}
 1138:     }
 1139:     delete($remembered{$to_kick});
 1140:     delete($accessed{$to_kick});
 1141:     $kicks++;
 1142:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1143:     return;
 1144: }
 1145: 
 1146: sub purge_remembered {
 1147:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1148:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1149:     undef(%remembered);
 1150:     undef(%accessed);
 1151: }
 1152: # ------------------------------------- Read an entry from a user's environment
 1153: 
 1154: sub userenvironment {
 1155:     my ($udom,$unam,@what)=@_;
 1156:     my %returnhash=();
 1157:     my @answer=split(/\&/,
 1158:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1159:                       &homeserver($unam,$udom)));
 1160:     my $i;
 1161:     for ($i=0;$i<=$#what;$i++) {
 1162: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1163:     }
 1164:     return %returnhash;
 1165: }
 1166: 
 1167: # ---------------------------------------------------------- Get a studentphoto
 1168: sub studentphoto {
 1169:     my ($udom,$unam,$ext) = @_;
 1170:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1171:     if (defined($env{'request.course.id'})) {
 1172:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1173:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1174:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1175:             } else {
 1176:                 my ($result,$perm_reqd)=
 1177: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1178:                 if ($result eq 'ok') {
 1179:                     if (!($perm_reqd eq 'yes')) {
 1180:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1181:                     }
 1182:                 }
 1183:             }
 1184:         }
 1185:     } else {
 1186:         my ($result,$perm_reqd) = 
 1187: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1188:         if ($result eq 'ok') {
 1189:             if (!($perm_reqd eq 'yes')) {
 1190:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1191:             }
 1192:         }
 1193:     }
 1194:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1195: }
 1196: 
 1197: sub retrievestudentphoto {
 1198:     my ($udom,$unam,$ext,$type) = @_;
 1199:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1200:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1201:     if ($ret eq 'ok') {
 1202:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1203:         if ($type eq 'thumbnail') {
 1204:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1205:         }
 1206:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1207:         return $tokenurl;
 1208:     } else {
 1209:         if ($type eq 'thumbnail') {
 1210:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1211:         } else { 
 1212:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1213:         }
 1214:     }
 1215: }
 1216: 
 1217: # -------------------------------------------------------------------- New chat
 1218: 
 1219: sub chatsend {
 1220:     my ($newentry,$anon,$group)=@_;
 1221:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1222:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1223:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1224:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1225: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1226: 		   &escape($newentry)).':'.$group,$chome);
 1227: }
 1228: 
 1229: # ------------------------------------------ Find current version of a resource
 1230: 
 1231: sub getversion {
 1232:     my $fname=&clutter(shift);
 1233:     unless ($fname=~/^\/res\//) { return -1; }
 1234:     return &currentversion(&filelocation('',$fname));
 1235: }
 1236: 
 1237: sub currentversion {
 1238:     my $fname=shift;
 1239:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1240:     if (defined($cached)) { return $result; }
 1241:     my $author=$fname;
 1242:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1243:     my ($udom,$uname)=split(/\//,$author);
 1244:     my $home=homeserver($uname,$udom);
 1245:     if ($home eq 'no_host') { 
 1246:         return -1; 
 1247:     }
 1248:     my $answer=reply("currentversion:$fname",$home);
 1249:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1250: 	return -1;
 1251:     }
 1252:     return &do_cache_new('resversion',$fname,$answer,600);
 1253: }
 1254: 
 1255: # ----------------------------- Subscribe to a resource, return URL if possible
 1256: 
 1257: sub subscribe {
 1258:     my $fname=shift;
 1259:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1260:     $fname=~s/[\n\r]//g;
 1261:     my $author=$fname;
 1262:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1263:     my ($udom,$uname)=split(/\//,$author);
 1264:     my $home=homeserver($uname,$udom);
 1265:     if ($home eq 'no_host') {
 1266:         return 'not_found';
 1267:     }
 1268:     my $answer=reply("sub:$fname",$home);
 1269:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1270: 	$answer.=' by '.$home;
 1271:     }
 1272:     return $answer;
 1273: }
 1274:     
 1275: # -------------------------------------------------------------- Replicate file
 1276: 
 1277: sub repcopy {
 1278:     my $filename=shift;
 1279:     $filename=~s/\/+/\//g;
 1280:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1281:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1282:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1283: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1284: 	return &repcopy_userfile($filename);
 1285:     }
 1286:     $filename=~s/[\n\r]//g;
 1287:     my $transname="$filename.in.transfer";
 1288: # FIXME: this should flock
 1289:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1290:     my $remoteurl=subscribe($filename);
 1291:     if ($remoteurl =~ /^con_lost by/) {
 1292: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1293:            return 'unavailable';
 1294:     } elsif ($remoteurl eq 'not_found') {
 1295: 	   #&logthis("Subscribe returned not_found: $filename");
 1296: 	   return 'not_found';
 1297:     } elsif ($remoteurl =~ /^rejected by/) {
 1298: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1299:            return 'forbidden';
 1300:     } elsif ($remoteurl eq 'directory') {
 1301:            return 'ok';
 1302:     } else {
 1303:         my $author=$filename;
 1304:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1305:         my ($udom,$uname)=split(/\//,$author);
 1306:         my $home=homeserver($uname,$udom);
 1307:         unless ($home eq $perlvar{'lonHostID'}) {
 1308:            my @parts=split(/\//,$filename);
 1309:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1310:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1311:                &logthis("Malconfiguration for replication: $filename");
 1312: 	       return 'bad_request';
 1313:            }
 1314:            my $count;
 1315:            for ($count=5;$count<$#parts;$count++) {
 1316:                $path.="/$parts[$count]";
 1317:                if ((-e $path)!=1) {
 1318: 		   mkdir($path,0777);
 1319:                }
 1320:            }
 1321:            my $ua=new LWP::UserAgent;
 1322:            my $request=new HTTP::Request('GET',"$remoteurl");
 1323:            my $response=$ua->request($request,$transname);
 1324:            if ($response->is_error()) {
 1325: 	       unlink($transname);
 1326:                my $message=$response->status_line;
 1327:                &logthis("<font color=\"blue\">WARNING:"
 1328:                        ." LWP get: $message: $filename</font>");
 1329:                return 'unavailable';
 1330:            } else {
 1331: 	       if ($remoteurl!~/\.meta$/) {
 1332:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1333:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1334:                   if ($mresponse->is_error()) {
 1335: 		      unlink($filename.'.meta');
 1336:                       &logthis(
 1337:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1338:                   }
 1339: 	       }
 1340:                rename($transname,$filename);
 1341:                return 'ok';
 1342:            }
 1343:        }
 1344:     }
 1345: }
 1346: 
 1347: # ------------------------------------------------ Get server side include body
 1348: sub ssi_body {
 1349:     my ($filelink,%form)=@_;
 1350:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1351:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1352:     }
 1353:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1354:                                      &ssi($filelink,%form));
 1355:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1356:     $output=~s/^.*?\<body[^\>]*\>//si;
 1357:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1358:     return $output;
 1359: }
 1360: 
 1361: # --------------------------------------------------------- Server Side Include
 1362: 
 1363: sub absolute_url {
 1364:     my ($host_name) = @_;
 1365:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1366:     if ($host_name eq '') {
 1367: 	$host_name = $ENV{'SERVER_NAME'};
 1368:     }
 1369:     return $protocol.$host_name;
 1370: }
 1371: 
 1372: sub ssi {
 1373: 
 1374:     my ($fn,%form)=@_;
 1375: 
 1376:     my $ua=new LWP::UserAgent;
 1377:     
 1378:     my $request;
 1379: 
 1380:     $form{'no_update_last_known'}=1;
 1381: 
 1382:     if (%form) {
 1383:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1384:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1385:     } else {
 1386:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1387:     }
 1388: 
 1389:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1390:     my $response=$ua->request($request);
 1391: 
 1392:     return $response->content;
 1393: }
 1394: 
 1395: sub externalssi {
 1396:     my ($url)=@_;
 1397:     my $ua=new LWP::UserAgent;
 1398:     my $request=new HTTP::Request('GET',$url);
 1399:     my $response=$ua->request($request);
 1400:     return $response->content;
 1401: }
 1402: 
 1403: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1404: 
 1405: sub allowuploaded {
 1406:     my ($srcurl,$url)=@_;
 1407:     $url=&clutter(&declutter($url));
 1408:     my $dir=$url;
 1409:     $dir=~s/\/[^\/]+$//;
 1410:     my %httpref=();
 1411:     my $httpurl=&hreflocation('',$url);
 1412:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1413:     &Apache::lonnet::appenv(%httpref);
 1414: }
 1415: 
 1416: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1417: # input: action, courseID, current domain, intended
 1418: #        path to file, source of file, instruction to parse file for objects,
 1419: #        ref to hash for embedded objects,
 1420: #        ref to hash for codebase of java objects.
 1421: #
 1422: # output: url to file (if action was uploaddoc), 
 1423: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1424: #
 1425: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1426: # course.
 1427: #
 1428: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1429: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1430: #          course's home server.
 1431: #
 1432: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1433: #          be copied from $source (current location) to 
 1434: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1435: #         and will then be copied to
 1436: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1437: #         course's home server.
 1438: #
 1439: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1440: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1441: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1442: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1443: #         in course's home server.
 1444: #
 1445: 
 1446: sub process_coursefile {
 1447:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1448:     my $fetchresult;
 1449:     my $home=&homeserver($docuname,$docudom);
 1450:     if ($action eq 'propagate') {
 1451:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1452: 			     $home);
 1453:     } else {
 1454:         my $fpath = '';
 1455:         my $fname = $file;
 1456:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1457:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1458:         my $filepath = &build_filepath($fpath);
 1459:         if ($action eq 'copy') {
 1460:             if ($source eq '') {
 1461:                 $fetchresult = 'no source file';
 1462:                 return $fetchresult;
 1463:             } else {
 1464:                 my $destination = $filepath.'/'.$fname;
 1465:                 rename($source,$destination);
 1466:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1467:                                  $home);
 1468:             }
 1469:         } elsif ($action eq 'uploaddoc') {
 1470:             open(my $fh,'>'.$filepath.'/'.$fname);
 1471:             print $fh $env{'form.'.$source};
 1472:             close($fh);
 1473:             if ($parser eq 'parse') {
 1474:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1475:                 unless ($parse_result eq 'ok') {
 1476:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1477:                 }
 1478:             }
 1479:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1480:                                  $home);
 1481:             if ($fetchresult eq 'ok') {
 1482:                 return '/uploaded/'.$fpath.'/'.$fname;
 1483:             } else {
 1484:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1485:                         ' to host '.$home.': '.$fetchresult);
 1486:                 return '/adm/notfound.html';
 1487:             }
 1488:         }
 1489:     }
 1490:     unless ( $fetchresult eq 'ok') {
 1491:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1492:              ' to host '.$home.': '.$fetchresult);
 1493:     }
 1494:     return $fetchresult;
 1495: }
 1496: 
 1497: sub build_filepath {
 1498:     my ($fpath) = @_;
 1499:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1500:     unless ($fpath eq '') {
 1501:         my @parts=split('/',$fpath);
 1502:         foreach my $part (@parts) {
 1503:             $filepath.= '/'.$part;
 1504:             if ((-e $filepath)!=1) {
 1505:                 mkdir($filepath,0777);
 1506:             }
 1507:         }
 1508:     }
 1509:     return $filepath;
 1510: }
 1511: 
 1512: sub store_edited_file {
 1513:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1514:     my $file = $primary_url;
 1515:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1516:     my $fpath = '';
 1517:     my $fname = $file;
 1518:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1519:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1520:     my $filepath = &build_filepath($fpath);
 1521:     open(my $fh,'>'.$filepath.'/'.$fname);
 1522:     print $fh $content;
 1523:     close($fh);
 1524:     my $home=&homeserver($docuname,$docudom);
 1525:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1526: 			  $home);
 1527:     if ($$fetchresult eq 'ok') {
 1528:         return '/uploaded/'.$fpath.'/'.$fname;
 1529:     } else {
 1530:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1531: 		 ' to host '.$home.': '.$$fetchresult);
 1532:         return '/adm/notfound.html';
 1533:     }
 1534: }
 1535: 
 1536: sub clean_filename {
 1537:     my ($fname,$args)=@_;
 1538: # Replace Windows backslashes by forward slashes
 1539:     $fname=~s/\\/\//g;
 1540:     if (!$args->{'keep_path'}) {
 1541:         # Get rid of everything but the actual filename
 1542: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1543:     }
 1544: # Replace spaces by underscores
 1545:     $fname=~s/\s+/\_/g;
 1546: # Replace all other weird characters by nothing
 1547:     $fname=~s{[^/\w\.\-]}{}g;
 1548: # Replace all .\d. sequences with _\d. so they no longer look like version
 1549: # numbers
 1550:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1551:     return $fname;
 1552: }
 1553: 
 1554: # --------------- Take an uploaded file and put it into the userfiles directory
 1555: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1556: #                    the desired filenam is in $env{"form.$formname.filename"}
 1557: #        $coursedoc - if true up to the current course
 1558: #                     if false
 1559: #        $subdir - directory in userfile to store the file into
 1560: #        $parser - instruction to parse file for objects ($parser = parse)    
 1561: #        $allfiles - reference to hash for embedded objects
 1562: #        $codebase - reference to hash for codebase of java objects
 1563: #        $desuname - username for permanent storage of uploaded file
 1564: #        $dsetudom - domain for permanaent storage of uploaded file
 1565: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1566: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1567: # 
 1568: # output: url of file in userspace, or error: <message> 
 1569: #             or /adm/notfound.html if failure to upload occurse
 1570: 
 1571: 
 1572: sub userfileupload {
 1573:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1574:         $destudom,$thumbwidth,$thumbheight)=@_;
 1575:     if (!defined($subdir)) { $subdir='unknown'; }
 1576:     my $fname=$env{'form.'.$formname.'.filename'};
 1577:     $fname=&clean_filename($fname);
 1578: # See if there is anything left
 1579:     unless ($fname) { return 'error: no uploaded file'; }
 1580:     chop($env{'form.'.$formname});
 1581:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1582:         my $now = time;
 1583:         my $filepath = 'tmp/helprequests/'.$now;
 1584:         my @parts=split(/\//,$filepath);
 1585:         my $fullpath = $perlvar{'lonDaemons'};
 1586:         for (my $i=0;$i<@parts;$i++) {
 1587:             $fullpath .= '/'.$parts[$i];
 1588:             if ((-e $fullpath)!=1) {
 1589:                 mkdir($fullpath,0777);
 1590:             }
 1591:         }
 1592:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1593:         print $fh $env{'form.'.$formname};
 1594:         close($fh);
 1595:         return $fullpath.'/'.$fname;
 1596:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1597:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1598:                        '_'.$env{'user.domain'}.'/pending';
 1599:         my @parts=split(/\//,$filepath);
 1600:         my $fullpath = $perlvar{'lonDaemons'};
 1601:         for (my $i=0;$i<@parts;$i++) {
 1602:             $fullpath .= '/'.$parts[$i];
 1603:             if ((-e $fullpath)!=1) {
 1604:                 mkdir($fullpath,0777);
 1605:             }
 1606:         }
 1607:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1608:         print $fh $env{'form.'.$formname};
 1609:         close($fh);
 1610:         return $fullpath.'/'.$fname;
 1611:     }
 1612:     
 1613: # Create the directory if not present
 1614:     $fname="$subdir/$fname";
 1615:     if ($coursedoc) {
 1616: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1617: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1618:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1619:             return &finishuserfileupload($docuname,$docudom,
 1620: 					 $formname,$fname,$parser,$allfiles,
 1621: 					 $codebase,$thumbwidth,$thumbheight);
 1622:         } else {
 1623:             $fname=$env{'form.folder'}.'/'.$fname;
 1624:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1625: 				       $fname,$formname,$parser,
 1626: 				       $allfiles,$codebase);
 1627:         }
 1628:     } elsif (defined($destuname)) {
 1629:         my $docuname=$destuname;
 1630:         my $docudom=$destudom;
 1631: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1632: 				     $parser,$allfiles,$codebase,
 1633:                                      $thumbwidth,$thumbheight);
 1634:         
 1635:     } else {
 1636:         my $docuname=$env{'user.name'};
 1637:         my $docudom=$env{'user.domain'};
 1638:         if (exists($env{'form.group'})) {
 1639:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1640:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1641:         }
 1642: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1643: 				     $parser,$allfiles,$codebase,
 1644:                                      $thumbwidth,$thumbheight);
 1645:     }
 1646: }
 1647: 
 1648: sub finishuserfileupload {
 1649:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1650:         $thumbwidth,$thumbheight) = @_;
 1651:     my $path=$docudom.'/'.$docuname.'/';
 1652:     my $filepath=$perlvar{'lonDocRoot'};
 1653:     my ($fnamepath,$file,$fetchthumb);
 1654:     $file=$fname;
 1655:     if ($fname=~m|/|) {
 1656:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1657: 	$path.=$fnamepath.'/';
 1658:     }
 1659:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1660:     my $count;
 1661:     for ($count=4;$count<=$#parts;$count++) {
 1662:         $filepath.="/$parts[$count]";
 1663:         if ((-e $filepath)!=1) {
 1664: 	    mkdir($filepath,0777);
 1665:         }
 1666:     }
 1667: # Save the file
 1668:     {
 1669: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1670: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1671: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1672: 	    return '/adm/notfound.html';
 1673: 	}
 1674: 	if (!print FH ($env{'form.'.$formname})) {
 1675: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1676: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1677: 	    return '/adm/notfound.html';
 1678: 	}
 1679: 	close(FH);
 1680:     }
 1681:     if ($parser eq 'parse') {
 1682:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1683: 						   $codebase);
 1684:         unless ($parse_result eq 'ok') {
 1685:             &logthis('Failed to parse '.$filepath.$file.
 1686: 		     ' for embedded media: '.$parse_result); 
 1687:         }
 1688:     }
 1689:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1690:         my $input = $filepath.'/'.$file;
 1691:         my $output = $filepath.'/'.'tn-'.$file;
 1692:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1693:         system("convert -sample $thumbsize $input $output");
 1694:         if (-e $filepath.'/'.'tn-'.$file) {
 1695:             $fetchthumb  = 1; 
 1696:         }
 1697:     }
 1698:  
 1699: # Notify homeserver to grep it
 1700: #
 1701:     my $docuhome=&homeserver($docuname,$docudom);
 1702:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1703:     if ($fetchresult eq 'ok') {
 1704:         if ($fetchthumb) {
 1705:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1706:             if ($thumbresult ne 'ok') {
 1707:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1708:                          $docuhome.': '.$thumbresult);
 1709:             }
 1710:         }
 1711: #
 1712: # Return the URL to it
 1713:         return '/uploaded/'.$path.$file;
 1714:     } else {
 1715:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1716: 		 ': '.$fetchresult);
 1717:         return '/adm/notfound.html';
 1718:     }
 1719: }
 1720: 
 1721: sub extract_embedded_items {
 1722:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1723:     my @state = ();
 1724:     my %javafiles = (
 1725:                       codebase => '',
 1726:                       code => '',
 1727:                       archive => ''
 1728:                     );
 1729:     my %mediafiles = (
 1730:                       src => '',
 1731:                       movie => '',
 1732:                      );
 1733:     my $p;
 1734:     if ($content) {
 1735:         $p = HTML::LCParser->new($content);
 1736:     } else {
 1737:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1738:     }
 1739:     while (my $t=$p->get_token()) {
 1740: 	if ($t->[0] eq 'S') {
 1741: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1742: 	    push (@state, $tagname);
 1743:             if (lc($tagname) eq 'allow') {
 1744:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1745:             }
 1746: 	    if (lc($tagname) eq 'img') {
 1747: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1748: 	    }
 1749:             if (lc($tagname) eq 'script') {
 1750:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1751:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1752:                 } else {
 1753:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1754:                 }
 1755:             }
 1756:             if (lc($tagname) eq 'link') {
 1757:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1758:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1759:                 }
 1760:             }
 1761: 	    if (lc($tagname) eq 'object' ||
 1762: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1763: 		foreach my $item (keys(%javafiles)) {
 1764: 		    $javafiles{$item} = '';
 1765: 		}
 1766: 	    }
 1767: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1768: 		my $name = lc($attr->{'name'});
 1769: 		foreach my $item (keys(%javafiles)) {
 1770: 		    if ($name eq $item) {
 1771: 			$javafiles{$item} = $attr->{'value'};
 1772: 			last;
 1773: 		    }
 1774: 		}
 1775: 		foreach my $item (keys(%mediafiles)) {
 1776: 		    if ($name eq $item) {
 1777: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1778: 			last;
 1779: 		    }
 1780: 		}
 1781: 	    }
 1782: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1783: 		foreach my $item (keys(%javafiles)) {
 1784: 		    if ($attr->{$item}) {
 1785: 			$javafiles{$item} = $attr->{$item};
 1786: 			last;
 1787: 		    }
 1788: 		}
 1789: 		foreach my $item (keys(%mediafiles)) {
 1790: 		    if ($attr->{$item}) {
 1791: 			&add_filetype($allfiles,$attr->{$item},$item);
 1792: 			last;
 1793: 		    }
 1794: 		}
 1795: 	    }
 1796: 	} elsif ($t->[0] eq 'E') {
 1797: 	    my ($tagname) = ($t->[1]);
 1798: 	    if ($javafiles{'codebase'} ne '') {
 1799: 		$javafiles{'codebase'} .= '/';
 1800: 	    }  
 1801: 	    if (lc($tagname) eq 'applet' ||
 1802: 		lc($tagname) eq 'object' ||
 1803: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1804: 		) {
 1805: 		foreach my $item (keys(%javafiles)) {
 1806: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1807: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1808: 			&add_filetype($allfiles,$file,$item);
 1809: 		    }
 1810: 		}
 1811: 	    } 
 1812: 	    pop @state;
 1813: 	}
 1814:     }
 1815:     return 'ok';
 1816: }
 1817: 
 1818: sub add_filetype {
 1819:     my ($allfiles,$file,$type)=@_;
 1820:     if (exists($allfiles->{$file})) {
 1821: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1822: 	    push(@{$allfiles->{$file}}, &escape($type));
 1823: 	}
 1824:     } else {
 1825: 	@{$allfiles->{$file}} = (&escape($type));
 1826:     }
 1827: }
 1828: 
 1829: sub removeuploadedurl {
 1830:     my ($url)=@_;
 1831:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1832:     return &removeuserfile($uname,$udom,$fname);
 1833: }
 1834: 
 1835: sub removeuserfile {
 1836:     my ($docuname,$docudom,$fname)=@_;
 1837:     my $home=&homeserver($docuname,$docudom);
 1838:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1839:     if ($result eq 'ok') {
 1840:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1841:             my $metafile = $fname.'.meta';
 1842:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1843: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1844:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1845:             my $sqlresult = 
 1846:                 &update_portfolio_table($docuname,$docudom,$file,
 1847:                                         'portfolio_metadata',$group,
 1848:                                         'delete');
 1849:         }
 1850:     }
 1851:     return $result;
 1852: }
 1853: 
 1854: sub mkdiruserfile {
 1855:     my ($docuname,$docudom,$dir)=@_;
 1856:     my $home=&homeserver($docuname,$docudom);
 1857:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1858: }
 1859: 
 1860: sub renameuserfile {
 1861:     my ($docuname,$docudom,$old,$new)=@_;
 1862:     my $home=&homeserver($docuname,$docudom);
 1863:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1864:                         &escape("$old").':'.&escape("$new"),$home);
 1865:     if ($result eq 'ok') {
 1866:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1867:             my $oldmeta = $old.'.meta';
 1868:             my $newmeta = $new.'.meta';
 1869:             my $metaresult = 
 1870:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1871: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1872:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1873:             my $sqlresult = 
 1874:                 &update_portfolio_table($docuname,$docudom,$file,
 1875:                                         'portfolio_metadata',$group,
 1876:                                         'delete');
 1877:         }
 1878:     }
 1879:     return $result;
 1880: }
 1881: 
 1882: # ------------------------------------------------------------------------- Log
 1883: 
 1884: sub log {
 1885:     my ($dom,$nam,$hom,$what)=@_;
 1886:     return critical("log:$dom:$nam:$what",$hom);
 1887: }
 1888: 
 1889: # ------------------------------------------------------------------ Course Log
 1890: #
 1891: # This routine flushes several buffers of non-mission-critical nature
 1892: #
 1893: 
 1894: sub flushcourselogs {
 1895:     &logthis('Flushing log buffers');
 1896: #
 1897: # course logs
 1898: # This is a log of all transactions in a course, which can be used
 1899: # for data mining purposes
 1900: #
 1901: # It also collects the courseid database, which lists last transaction
 1902: # times and course titles for all courseids
 1903: #
 1904:     my %courseidbuffer=();
 1905:     foreach my $crsid (keys %courselogs) {
 1906:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1907: 		          &escape($courselogs{$crsid}),
 1908: 		          $coursehombuf{$crsid}) eq 'ok') {
 1909: 	    delete $courselogs{$crsid};
 1910:         } else {
 1911:             &logthis('Failed to flush log buffer for '.$crsid);
 1912:             if (length($courselogs{$crsid})>40000) {
 1913:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1914:                         " exceeded maximum size, deleting.</font>");
 1915:                delete $courselogs{$crsid};
 1916:             }
 1917:         }
 1918:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1919:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1920: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1921:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1922:         } else {
 1923:            $courseidbuffer{$coursehombuf{$crsid}}=
 1924: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1925:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1926:         }
 1927:     }
 1928: #
 1929: # Write course id database (reverse lookup) to homeserver of courses 
 1930: # Is used in pickcourse
 1931: #
 1932:     foreach my $crs_home (keys(%courseidbuffer)) {
 1933:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1934: 		     $crs_home);
 1935:     }
 1936: #
 1937: # File accesses
 1938: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1939: #
 1940:     foreach my $entry (keys(%accesshash)) {
 1941:         if ($entry =~ /___count$/) {
 1942:             my ($dom,$name);
 1943:             ($dom,$name,undef)=
 1944: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1945:             if (! defined($dom) || $dom eq '' || 
 1946:                 ! defined($name) || $name eq '') {
 1947:                 my $cid = $env{'request.course.id'};
 1948:                 $dom  = $env{'request.'.$cid.'.domain'};
 1949:                 $name = $env{'request.'.$cid.'.num'};
 1950:             }
 1951:             my $value = $accesshash{$entry};
 1952:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1953:             my %temphash=($url => $value);
 1954:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1955:             if ($result eq 'ok') {
 1956:                 delete $accesshash{$entry};
 1957:             } elsif ($result eq 'unknown_cmd') {
 1958:                 # Target server has old code running on it.
 1959:                 my %temphash=($entry => $value);
 1960:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1961:                     delete $accesshash{$entry};
 1962:                 }
 1963:             }
 1964:         } else {
 1965:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1966:             my %temphash=($entry => $accesshash{$entry});
 1967:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1968:                 delete $accesshash{$entry};
 1969:             }
 1970:         }
 1971:     }
 1972: #
 1973: # Roles
 1974: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1975: #
 1976:     foreach my $entry (keys(%userrolehash)) {
 1977:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1978: 	    split(/\:/,$entry);
 1979:         if (&Apache::lonnet::put('nohist_userroles',
 1980:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1981:                 $rudom,$runame) eq 'ok') {
 1982: 	    delete $userrolehash{$entry};
 1983:         }
 1984:     }
 1985: #
 1986: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1987: #
 1988:     my %domrolebuffer = ();
 1989:     foreach my $entry (keys %domainrolehash) {
 1990:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1991:         if ($domrolebuffer{$rudom}) {
 1992:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1993:                       '='.&escape($domainrolehash{$entry});
 1994:         } else {
 1995:             $domrolebuffer{$rudom}.=&escape($entry).
 1996:                       '='.&escape($domainrolehash{$entry});
 1997:         }
 1998:         delete $domainrolehash{$entry};
 1999:     }
 2000:     foreach my $dom (keys(%domrolebuffer)) {
 2001: 	my %servers = &get_servers($dom,'library');
 2002: 	foreach my $tryserver (keys(%servers)) {
 2003: 	    unless (&reply('domroleput:'.$dom.':'.
 2004: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2005: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2006: 	    }
 2007:         }
 2008:     }
 2009:     $dumpcount++;
 2010: }
 2011: 
 2012: sub courselog {
 2013:     my $what=shift;
 2014:     $what=time.':'.$what;
 2015:     unless ($env{'request.course.id'}) { return ''; }
 2016:     $coursedombuf{$env{'request.course.id'}}=
 2017:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2018:     $coursenumbuf{$env{'request.course.id'}}=
 2019:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2020:     $coursehombuf{$env{'request.course.id'}}=
 2021:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2022:     $coursedescrbuf{$env{'request.course.id'}}=
 2023:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2024:     $courseinstcodebuf{$env{'request.course.id'}}=
 2025:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2026:     $courseownerbuf{$env{'request.course.id'}}=
 2027:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2028:     $coursetypebuf{$env{'request.course.id'}}=
 2029:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2030:     if (defined $courselogs{$env{'request.course.id'}}) {
 2031: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2032:     } else {
 2033: 	$courselogs{$env{'request.course.id'}}.=$what;
 2034:     }
 2035:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2036: 	&flushcourselogs();
 2037:     }
 2038: }
 2039: 
 2040: sub courseacclog {
 2041:     my $fnsymb=shift;
 2042:     unless ($env{'request.course.id'}) { return ''; }
 2043:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2044:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2045:         $what.=':POST';
 2046:         # FIXME: Probably ought to escape things....
 2047: 	foreach my $key (keys(%env)) {
 2048:             if ($key=~/^form\.(.*)/) {
 2049: 		$what.=':'.$1.'='.$env{$key};
 2050:             }
 2051:         }
 2052:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2053:         # FIXME: We should not be depending on a form parameter that someone
 2054:         # editing lonsearchcat.pm might change in the future.
 2055:         if ($env{'form.phase'} eq 'course_search') {
 2056:             $what.= ':POST';
 2057:             # FIXME: Probably ought to escape things....
 2058:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2059:                                  'crsdiscuss') {
 2060:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2061:             }
 2062:         }
 2063:     }
 2064:     &courselog($what);
 2065: }
 2066: 
 2067: sub countacc {
 2068:     my $url=&declutter(shift);
 2069:     return if (! defined($url) || $url eq '');
 2070:     unless ($env{'request.course.id'}) { return ''; }
 2071:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2072:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2073:     $accesshash{$key}++;
 2074: }
 2075: 
 2076: sub linklog {
 2077:     my ($from,$to)=@_;
 2078:     $from=&declutter($from);
 2079:     $to=&declutter($to);
 2080:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2081:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2082: }
 2083:   
 2084: sub userrolelog {
 2085:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2086:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2087:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2088:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2089:         ($trole=~/^ta/)) {
 2090:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2091:        $userrolehash
 2092:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2093:                     =$tend.':'.$tstart;
 2094:     }
 2095:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2096:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2097:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2098:         ($trole=~/^sc/)) {
 2099:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2100:        $domainrolehash
 2101:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2102:                     = $tend.':'.$tstart;
 2103:     }
 2104: }
 2105: 
 2106: sub get_course_adv_roles {
 2107:     my $cid=shift;
 2108:     $cid=$env{'request.course.id'} unless (defined($cid));
 2109:     my %coursehash=&coursedescription($cid);
 2110:     my %nothide=();
 2111:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2112: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2113:     }
 2114:     my %returnhash=();
 2115:     my %dumphash=
 2116:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2117:     my $now=time;
 2118:     foreach my $entry (keys %dumphash) {
 2119: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2120:         if (($tstart) && ($tstart<0)) { next; }
 2121:         if (($tend) && ($tend<$now)) { next; }
 2122:         if (($tstart) && ($now<$tstart)) { next; }
 2123:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2124: 	if ($username eq '' || $domain eq '') { next; }
 2125: 	if ((&privileged($username,$domain)) && 
 2126: 	    (!$nothide{$username.':'.$domain})) { next; }
 2127: 	if ($role eq 'cr') { next; }
 2128:         my $key=&plaintext($role);
 2129:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2130:         if ($returnhash{$key}) {
 2131: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2132:         } else {
 2133:             $returnhash{$key}=$username.':'.$domain;
 2134:         }
 2135:      }
 2136:     return %returnhash;
 2137: }
 2138: 
 2139: sub get_my_roles {
 2140:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2141:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2142:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2143:     my %dumphash;
 2144:     if ($context eq 'userroles') { 
 2145:         %dumphash = &dump('roles',$udom,$uname);
 2146:     } else {
 2147:         %dumphash=
 2148:             &dump('nohist_userroles',$udom,$uname);
 2149:     }
 2150:     my %returnhash=();
 2151:     my $now=time;
 2152:     foreach my $entry (keys(%dumphash)) {
 2153:         my ($role,$tend,$tstart);
 2154:         if ($context eq 'userroles') {
 2155: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2156:         } else {
 2157:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2158:         }
 2159:         if (($tstart) && ($tstart<0)) { next; }
 2160:         my $status = 'active';
 2161:         if (($tend) && ($tend<$now)) {
 2162:             $status = 'previous';
 2163:         } 
 2164:         if (($tstart) && ($now<$tstart)) {
 2165:             $status = 'future';
 2166:         }
 2167:         if (ref($types) eq 'ARRAY') {
 2168:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2169:                 next;
 2170:             } 
 2171:         } else {
 2172:             if ($status ne 'active') {
 2173:                 next;
 2174:             }
 2175:         }
 2176:         my ($rolecode,$username,$domain,$section,$area);
 2177:         if ($context eq 'userroles') {
 2178:             ($area,$rolecode) = split(/_/,$entry);
 2179:             (undef,$domain,$username,$section) = split(/\//,$area);
 2180:         } else {
 2181:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2182:         }
 2183:         if (ref($roledoms) eq 'ARRAY') {
 2184:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2185:                 next;
 2186:             }
 2187:         }
 2188:         if (ref($roles) eq 'ARRAY') {
 2189:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2190:                 next;
 2191:             }
 2192:         }
 2193: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2194:     }
 2195:     return %returnhash;
 2196: }
 2197: 
 2198: # ----------------------------------------------------- Frontpage Announcements
 2199: #
 2200: #
 2201: 
 2202: sub postannounce {
 2203:     my ($server,$text)=@_;
 2204:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2205:     unless ($text=~/\w/) { $text=''; }
 2206:     return &reply('setannounce:'.&escape($text),$server);
 2207: }
 2208: 
 2209: sub getannounce {
 2210: 
 2211:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2212: 	my $announcement='';
 2213: 	while (my $line = <$fh>) { $announcement .= $line; }
 2214: 	close($fh);
 2215: 	if ($announcement=~/\w/) { 
 2216: 	    return 
 2217:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2218:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2219: 	} else {
 2220: 	    return '';
 2221: 	}
 2222:     } else {
 2223: 	return '';
 2224:     }
 2225: }
 2226: 
 2227: # ---------------------------------------------------------- Course ID routines
 2228: # Deal with domain's nohist_courseid.db files
 2229: #
 2230: 
 2231: sub courseidput {
 2232:     my ($domain,$what,$coursehome)=@_;
 2233:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2234: }
 2235: 
 2236: sub courseiddump {
 2237:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2238:     my %returnhash=();
 2239:     unless ($domfilter) { $domfilter=''; }
 2240:     my %libserv = &all_library();
 2241:     foreach my $tryserver (keys(%libserv)) {
 2242:         if ( (  $hostidflag == 1 
 2243: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2244: 	     || (!defined($hostidflag)) ) {
 2245: 
 2246: 	    if ($domfilter eq ''
 2247: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2248: 	        foreach my $line (
 2249:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2250: 			       $sincefilter.':'.&escape($descfilter).':'.
 2251:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2252:                                $tryserver))) {
 2253: 		    my ($key,$value)=split(/\=/,$line,2);
 2254:                     if (($key) && ($value)) {
 2255: 		        $returnhash{&unescape($key)}=$value;
 2256:                     }
 2257:                 }
 2258:             }
 2259:         }
 2260:     }
 2261:     return %returnhash;
 2262: }
 2263: 
 2264: # ---------------------------------------------------------- DC e-mail
 2265: 
 2266: sub dcmailput {
 2267:     my ($domain,$msgid,$message,$server)=@_;
 2268:     my $status = &Apache::lonnet::critical(
 2269:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2270:        &escape($message),$server);
 2271:     return $status;
 2272: }
 2273: 
 2274: sub dcmaildump {
 2275:     my ($dom,$startdate,$enddate,$senders) = @_;
 2276:     my %returnhash=();
 2277: 
 2278:     if (defined(&domain($dom,'primary'))) {
 2279:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2280:                                                          &escape($enddate).':';
 2281: 	my @esc_senders=map { &escape($_)} @$senders;
 2282: 	$cmd.=&escape(join('&',@esc_senders));
 2283: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2284:             my ($key,$value) = split(/\=/,$line,2);
 2285:             if (($key) && ($value)) {
 2286:                 $returnhash{&unescape($key)} = &unescape($value);
 2287:             }
 2288:         }
 2289:     }
 2290:     return %returnhash;
 2291: }
 2292: # ---------------------------------------------------------- Domain roles
 2293: 
 2294: sub get_domain_roles {
 2295:     my ($dom,$roles,$startdate,$enddate)=@_;
 2296:     if (undef($startdate) || $startdate eq '') {
 2297:         $startdate = '.';
 2298:     }
 2299:     if (undef($enddate) || $enddate eq '') {
 2300:         $enddate = '.';
 2301:     }
 2302:     my $rolelist = join(':',@{$roles});
 2303:     my %personnel = ();
 2304: 
 2305:     my %servers = &get_servers($dom,'library');
 2306:     foreach my $tryserver (keys(%servers)) {
 2307: 	%{$personnel{$tryserver}}=();
 2308: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2309: 					    &escape($startdate).':'.
 2310: 					    &escape($enddate).':'.
 2311: 					    &escape($rolelist), $tryserver))) {
 2312: 	    my ($key,$value) = split(/\=/,$line,2);
 2313: 	    if (($key) && ($value)) {
 2314: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2315: 	    }
 2316: 	}
 2317:     }
 2318:     return %personnel;
 2319: }
 2320: 
 2321: # ----------------------------------------------------------- Check out an item
 2322: 
 2323: sub get_first_access {
 2324:     my ($type,$argsymb)=@_;
 2325:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2326:     if ($argsymb) { $symb=$argsymb; }
 2327:     my ($map,$id,$res)=&decode_symb($symb);
 2328:     if ($type eq 'map') {
 2329: 	$res=&symbread($map);
 2330:     } else {
 2331: 	$res=$symb;
 2332:     }
 2333:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2334:     return $times{"$courseid\0$res"};
 2335: }
 2336: 
 2337: sub set_first_access {
 2338:     my ($type)=@_;
 2339:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2340:     my ($map,$id,$res)=&decode_symb($symb);
 2341:     if ($type eq 'map') {
 2342: 	$res=&symbread($map);
 2343:     } else {
 2344: 	$res=$symb;
 2345:     }
 2346:     my $firstaccess=&get_first_access($type,$symb);
 2347:     if (!$firstaccess) {
 2348: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2349:     }
 2350:     return 'already_set';
 2351: }
 2352: 
 2353: sub checkout {
 2354:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2355:     my $now=time;
 2356:     my $lonhost=$perlvar{'lonHostID'};
 2357:     my $infostr=&escape(
 2358:                  'CHECKOUTTOKEN&'.
 2359:                  $tuname.'&'.
 2360:                  $tudom.'&'.
 2361:                  $tcrsid.'&'.
 2362:                  $symb.'&'.
 2363: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2364:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2365:     if ($token=~/^error\:/) { 
 2366:         &logthis("<font color=\"blue\">WARNING: ".
 2367:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2368:                  "</font>");
 2369:         return ''; 
 2370:     }
 2371: 
 2372:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2373:     $token=~tr/a-z/A-Z/;
 2374: 
 2375:     my %infohash=('resource.0.outtoken' => $token,
 2376:                   'resource.0.checkouttime' => $now,
 2377:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2378: 
 2379:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2380:        return '';
 2381:     } else {
 2382:         &logthis("<font color=\"blue\">WARNING: ".
 2383:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2384:                  "</font>");
 2385:     }    
 2386: 
 2387:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2388:                          &escape('Checkout '.$infostr.' - '.
 2389:                                                  $token)) ne 'ok') {
 2390: 	return '';
 2391:     } else {
 2392:         &logthis("<font color=\"blue\">WARNING: ".
 2393:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2394:                  "</font>");
 2395:     }
 2396:     return $token;
 2397: }
 2398: 
 2399: # ------------------------------------------------------------ Check in an item
 2400: 
 2401: sub checkin {
 2402:     my $token=shift;
 2403:     my $now=time;
 2404:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2405:     $lonhost=~tr/A-Z/a-z/;
 2406:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2407:     $dtoken=~s/\W/\_/g;
 2408:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2409:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2410: 
 2411:     unless (($tuname) && ($tudom)) {
 2412:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2413:         return '';
 2414:     }
 2415:     
 2416:     unless (&allowed('mgr',$tcrsid)) {
 2417:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2418:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2419:         return '';
 2420:     }
 2421: 
 2422:     my %infohash=('resource.0.intoken' => $token,
 2423:                   'resource.0.checkintime' => $now,
 2424:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2425: 
 2426:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2427:        return '';
 2428:     }    
 2429: 
 2430:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2431:                          &escape('Checkin - '.$token)) ne 'ok') {
 2432: 	return '';
 2433:     }
 2434: 
 2435:     return ($symb,$tuname,$tudom,$tcrsid);    
 2436: }
 2437: 
 2438: # --------------------------------------------- Set Expire Date for Spreadsheet
 2439: 
 2440: sub expirespread {
 2441:     my ($uname,$udom,$stype,$usymb)=@_;
 2442:     my $cid=$env{'request.course.id'}; 
 2443:     if ($cid) {
 2444:        my $now=time;
 2445:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2446:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2447:                             $env{'course.'.$cid.'.num'}.
 2448: 	        	    ':nohist_expirationdates:'.
 2449:                             &escape($key).'='.$now,
 2450:                             $env{'course.'.$cid.'.home'})
 2451:     }
 2452:     return 'ok';
 2453: }
 2454: 
 2455: # ----------------------------------------------------- Devalidate Spreadsheets
 2456: 
 2457: sub devalidate {
 2458:     my ($symb,$uname,$udom)=@_;
 2459:     my $cid=$env{'request.course.id'}; 
 2460:     if ($cid) {
 2461:         # delete the stored spreadsheets for
 2462:         # - the student level sheet of this user in course's homespace
 2463:         # - the assessment level sheet for this resource 
 2464:         #   for this user in user's homespace
 2465: 	# - current conditional state info
 2466: 	my $key=$uname.':'.$udom.':';
 2467:         my $status=
 2468: 	    &del('nohist_calculatedsheets',
 2469: 		 [$key.'studentcalc:'],
 2470: 		 $env{'course.'.$cid.'.domain'},
 2471: 		 $env{'course.'.$cid.'.num'})
 2472: 		.' '.
 2473: 	    &del('nohist_calculatedsheets_'.$cid,
 2474: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2475:         unless ($status eq 'ok ok') {
 2476:            &logthis('Could not devalidate spreadsheet '.
 2477:                     $uname.' at '.$udom.' for '.
 2478: 		    $symb.': '.$status);
 2479:         }
 2480: 	&delenv('user.state.'.$cid);
 2481:     }
 2482: }
 2483: 
 2484: sub get_scalar {
 2485:     my ($string,$end) = @_;
 2486:     my $value;
 2487:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2488: 	$value = $1;
 2489:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2490: 	$value = $1;
 2491:     }
 2492:     return &unescape($value);
 2493: }
 2494: 
 2495: sub array2str {
 2496:   my (@array) = @_;
 2497:   my $result=&arrayref2str(\@array);
 2498:   $result=~s/^__ARRAY_REF__//;
 2499:   $result=~s/__END_ARRAY_REF__$//;
 2500:   return $result;
 2501: }
 2502: 
 2503: sub arrayref2str {
 2504:   my ($arrayref) = @_;
 2505:   my $result='__ARRAY_REF__';
 2506:   foreach my $elem (@$arrayref) {
 2507:     if(ref($elem) eq 'ARRAY') {
 2508:       $result.=&arrayref2str($elem).'&';
 2509:     } elsif(ref($elem) eq 'HASH') {
 2510:       $result.=&hashref2str($elem).'&';
 2511:     } elsif(ref($elem)) {
 2512:       #print("Got a ref of ".(ref($elem))." skipping.");
 2513:     } else {
 2514:       $result.=&escape($elem).'&';
 2515:     }
 2516:   }
 2517:   $result=~s/\&$//;
 2518:   $result .= '__END_ARRAY_REF__';
 2519:   return $result;
 2520: }
 2521: 
 2522: sub hash2str {
 2523:   my (%hash) = @_;
 2524:   my $result=&hashref2str(\%hash);
 2525:   $result=~s/^__HASH_REF__//;
 2526:   $result=~s/__END_HASH_REF__$//;
 2527:   return $result;
 2528: }
 2529: 
 2530: sub hashref2str {
 2531:   my ($hashref)=@_;
 2532:   my $result='__HASH_REF__';
 2533:   foreach my $key (sort(keys(%$hashref))) {
 2534:     if (ref($key) eq 'ARRAY') {
 2535:       $result.=&arrayref2str($key).'=';
 2536:     } elsif (ref($key) eq 'HASH') {
 2537:       $result.=&hashref2str($key).'=';
 2538:     } elsif (ref($key)) {
 2539:       $result.='=';
 2540:       #print("Got a ref of ".(ref($key))." skipping.");
 2541:     } else {
 2542: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2543:     }
 2544: 
 2545:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2546:       $result.=&arrayref2str($hashref->{$key}).'&';
 2547:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2548:       $result.=&hashref2str($hashref->{$key}).'&';
 2549:     } elsif(ref($hashref->{$key})) {
 2550:        $result.='&';
 2551:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2552:     } else {
 2553:       $result.=&escape($hashref->{$key}).'&';
 2554:     }
 2555:   }
 2556:   $result=~s/\&$//;
 2557:   $result .= '__END_HASH_REF__';
 2558:   return $result;
 2559: }
 2560: 
 2561: sub str2hash {
 2562:     my ($string)=@_;
 2563:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2564:     return %$hash;
 2565: }
 2566: 
 2567: sub str2hashref {
 2568:   my ($string) = @_;
 2569: 
 2570:   my %hash;
 2571: 
 2572:   if($string !~ /^__HASH_REF__/) {
 2573:       if (! ($string eq '' || !defined($string))) {
 2574: 	  $hash{'error'}='Not hash reference';
 2575:       }
 2576:       return (\%hash, $string);
 2577:   }
 2578: 
 2579:   $string =~ s/^__HASH_REF__//;
 2580: 
 2581:   while($string !~ /^__END_HASH_REF__/) {
 2582:       #key
 2583:       my $key='';
 2584:       if($string =~ /^__HASH_REF__/) {
 2585:           ($key, $string)=&str2hashref($string);
 2586:           if(defined($key->{'error'})) {
 2587:               $hash{'error'}='Bad data';
 2588:               return (\%hash, $string);
 2589:           }
 2590:       } elsif($string =~ /^__ARRAY_REF__/) {
 2591:           ($key, $string)=&str2arrayref($string);
 2592:           if($key->[0] eq 'Array reference error') {
 2593:               $hash{'error'}='Bad data';
 2594:               return (\%hash, $string);
 2595:           }
 2596:       } else {
 2597:           $string =~ s/^(.*?)=//;
 2598: 	  $key=&unescape($1);
 2599:       }
 2600:       $string =~ s/^=//;
 2601: 
 2602:       #value
 2603:       my $value='';
 2604:       if($string =~ /^__HASH_REF__/) {
 2605:           ($value, $string)=&str2hashref($string);
 2606:           if(defined($value->{'error'})) {
 2607:               $hash{'error'}='Bad data';
 2608:               return (\%hash, $string);
 2609:           }
 2610:       } elsif($string =~ /^__ARRAY_REF__/) {
 2611:           ($value, $string)=&str2arrayref($string);
 2612:           if($value->[0] eq 'Array reference error') {
 2613:               $hash{'error'}='Bad data';
 2614:               return (\%hash, $string);
 2615:           }
 2616:       } else {
 2617: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2618:       }
 2619:       $string =~ s/^&//;
 2620: 
 2621:       $hash{$key}=$value;
 2622:   }
 2623: 
 2624:   $string =~ s/^__END_HASH_REF__//;
 2625: 
 2626:   return (\%hash, $string);
 2627: }
 2628: 
 2629: sub str2array {
 2630:     my ($string)=@_;
 2631:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2632:     return @$array;
 2633: }
 2634: 
 2635: sub str2arrayref {
 2636:   my ($string) = @_;
 2637:   my @array;
 2638: 
 2639:   if($string !~ /^__ARRAY_REF__/) {
 2640:       if (! ($string eq '' || !defined($string))) {
 2641: 	  $array[0]='Array reference error';
 2642:       }
 2643:       return (\@array, $string);
 2644:   }
 2645: 
 2646:   $string =~ s/^__ARRAY_REF__//;
 2647: 
 2648:   while($string !~ /^__END_ARRAY_REF__/) {
 2649:       my $value='';
 2650:       if($string =~ /^__HASH_REF__/) {
 2651:           ($value, $string)=&str2hashref($string);
 2652:           if(defined($value->{'error'})) {
 2653:               $array[0] ='Array reference error';
 2654:               return (\@array, $string);
 2655:           }
 2656:       } elsif($string =~ /^__ARRAY_REF__/) {
 2657:           ($value, $string)=&str2arrayref($string);
 2658:           if($value->[0] eq 'Array reference error') {
 2659:               $array[0] ='Array reference error';
 2660:               return (\@array, $string);
 2661:           }
 2662:       } else {
 2663: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2664:       }
 2665:       $string =~ s/^&//;
 2666: 
 2667:       push(@array, $value);
 2668:   }
 2669: 
 2670:   $string =~ s/^__END_ARRAY_REF__//;
 2671: 
 2672:   return (\@array, $string);
 2673: }
 2674: 
 2675: # -------------------------------------------------------------------Temp Store
 2676: 
 2677: sub tmpreset {
 2678:   my ($symb,$namespace,$domain,$stuname) = @_;
 2679:   if (!$symb) {
 2680:     $symb=&symbread();
 2681:     if (!$symb) { $symb= $env{'request.url'}; }
 2682:   }
 2683:   $symb=escape($symb);
 2684: 
 2685:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2686:   $namespace=~s/\//\_/g;
 2687:   $namespace=~s/\W//g;
 2688: 
 2689:   if (!$domain) { $domain=$env{'user.domain'}; }
 2690:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2691:   if ($domain eq 'public' && $stuname eq 'public') {
 2692:       $stuname=$ENV{'REMOTE_ADDR'};
 2693:   }
 2694:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2695:   my %hash;
 2696:   if (tie(%hash,'GDBM_File',
 2697: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2698: 	  &GDBM_WRCREAT(),0640)) {
 2699:     foreach my $key (keys %hash) {
 2700:       if ($key=~ /:$symb/) {
 2701: 	delete($hash{$key});
 2702:       }
 2703:     }
 2704:   }
 2705: }
 2706: 
 2707: sub tmpstore {
 2708:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2709: 
 2710:   if (!$symb) {
 2711:     $symb=&symbread();
 2712:     if (!$symb) { $symb= $env{'request.url'}; }
 2713:   }
 2714:   $symb=escape($symb);
 2715: 
 2716:   if (!$namespace) {
 2717:     # I don't think we would ever want to store this for a course.
 2718:     # it seems this will only be used if we don't have a course.
 2719:     #$namespace=$env{'request.course.id'};
 2720:     #if (!$namespace) {
 2721:       $namespace=$env{'request.state'};
 2722:     #}
 2723:   }
 2724:   $namespace=~s/\//\_/g;
 2725:   $namespace=~s/\W//g;
 2726:   if (!$domain) { $domain=$env{'user.domain'}; }
 2727:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2728:   if ($domain eq 'public' && $stuname eq 'public') {
 2729:       $stuname=$ENV{'REMOTE_ADDR'};
 2730:   }
 2731:   my $now=time;
 2732:   my %hash;
 2733:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2734:   if (tie(%hash,'GDBM_File',
 2735: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2736: 	  &GDBM_WRCREAT(),0640)) {
 2737:     $hash{"version:$symb"}++;
 2738:     my $version=$hash{"version:$symb"};
 2739:     my $allkeys=''; 
 2740:     foreach my $key (keys(%$storehash)) {
 2741:       $allkeys.=$key.':';
 2742:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2743:     }
 2744:     $hash{"$version:$symb:timestamp"}=$now;
 2745:     $allkeys.='timestamp';
 2746:     $hash{"$version:keys:$symb"}=$allkeys;
 2747:     if (untie(%hash)) {
 2748:       return 'ok';
 2749:     } else {
 2750:       return "error:$!";
 2751:     }
 2752:   } else {
 2753:     return "error:$!";
 2754:   }
 2755: }
 2756: 
 2757: # -----------------------------------------------------------------Temp Restore
 2758: 
 2759: sub tmprestore {
 2760:   my ($symb,$namespace,$domain,$stuname) = @_;
 2761: 
 2762:   if (!$symb) {
 2763:     $symb=&symbread();
 2764:     if (!$symb) { $symb= $env{'request.url'}; }
 2765:   }
 2766:   $symb=escape($symb);
 2767: 
 2768:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2769: 
 2770:   if (!$domain) { $domain=$env{'user.domain'}; }
 2771:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2772:   if ($domain eq 'public' && $stuname eq 'public') {
 2773:       $stuname=$ENV{'REMOTE_ADDR'};
 2774:   }
 2775:   my %returnhash;
 2776:   $namespace=~s/\//\_/g;
 2777:   $namespace=~s/\W//g;
 2778:   my %hash;
 2779:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2780:   if (tie(%hash,'GDBM_File',
 2781: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2782: 	  &GDBM_READER(),0640)) {
 2783:     my $version=$hash{"version:$symb"};
 2784:     $returnhash{'version'}=$version;
 2785:     my $scope;
 2786:     for ($scope=1;$scope<=$version;$scope++) {
 2787:       my $vkeys=$hash{"$scope:keys:$symb"};
 2788:       my @keys=split(/:/,$vkeys);
 2789:       my $key;
 2790:       $returnhash{"$scope:keys"}=$vkeys;
 2791:       foreach $key (@keys) {
 2792: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2793: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2794:       }
 2795:     }
 2796:     if (!(untie(%hash))) {
 2797:       return "error:$!";
 2798:     }
 2799:   } else {
 2800:     return "error:$!";
 2801:   }
 2802:   return %returnhash;
 2803: }
 2804: 
 2805: # ----------------------------------------------------------------------- Store
 2806: 
 2807: sub store {
 2808:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2809:     my $home='';
 2810: 
 2811:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2812: 
 2813:     $symb=&symbclean($symb);
 2814:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2815: 
 2816:     if (!$domain) { $domain=$env{'user.domain'}; }
 2817:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2818: 
 2819:     &devalidate($symb,$stuname,$domain);
 2820: 
 2821:     $symb=escape($symb);
 2822:     if (!$namespace) { 
 2823:        unless ($namespace=$env{'request.course.id'}) { 
 2824:           return ''; 
 2825:        } 
 2826:     }
 2827:     if (!$home) { $home=$env{'user.home'}; }
 2828: 
 2829:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2830:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2831: 
 2832:     my $namevalue='';
 2833:     foreach my $key (keys(%$storehash)) {
 2834:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2835:     }
 2836:     $namevalue=~s/\&$//;
 2837:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2838:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2839: }
 2840: 
 2841: # -------------------------------------------------------------- Critical Store
 2842: 
 2843: sub cstore {
 2844:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2845:     my $home='';
 2846: 
 2847:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2848: 
 2849:     $symb=&symbclean($symb);
 2850:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2851: 
 2852:     if (!$domain) { $domain=$env{'user.domain'}; }
 2853:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2854: 
 2855:     &devalidate($symb,$stuname,$domain);
 2856: 
 2857:     $symb=escape($symb);
 2858:     if (!$namespace) { 
 2859:        unless ($namespace=$env{'request.course.id'}) { 
 2860:           return ''; 
 2861:        } 
 2862:     }
 2863:     if (!$home) { $home=$env{'user.home'}; }
 2864: 
 2865:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2866:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2867: 
 2868:     my $namevalue='';
 2869:     foreach my $key (keys(%$storehash)) {
 2870:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2871:     }
 2872:     $namevalue=~s/\&$//;
 2873:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2874:     return critical
 2875:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2876: }
 2877: 
 2878: # --------------------------------------------------------------------- Restore
 2879: 
 2880: sub restore {
 2881:     my ($symb,$namespace,$domain,$stuname) = @_;
 2882:     my $home='';
 2883: 
 2884:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2885: 
 2886:     if (!$symb) {
 2887:       unless ($symb=escape(&symbread())) { return ''; }
 2888:     } else {
 2889:       $symb=&escape(&symbclean($symb));
 2890:     }
 2891:     if (!$namespace) { 
 2892:        unless ($namespace=$env{'request.course.id'}) { 
 2893:           return ''; 
 2894:        } 
 2895:     }
 2896:     if (!$domain) { $domain=$env{'user.domain'}; }
 2897:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2898:     if (!$home) { $home=$env{'user.home'}; }
 2899:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2900: 
 2901:     my %returnhash=();
 2902:     foreach my $line (split(/\&/,$answer)) {
 2903: 	my ($name,$value)=split(/\=/,$line);
 2904:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2905:     }
 2906:     my $version;
 2907:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2908:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2909:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2910:        }
 2911:     }
 2912:     return %returnhash;
 2913: }
 2914: 
 2915: # ---------------------------------------------------------- Course Description
 2916: 
 2917: sub coursedescription {
 2918:     my ($courseid,$args)=@_;
 2919:     $courseid=~s/^\///;
 2920:     $courseid=~s/\_/\//g;
 2921:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2922:     my $chome=&homeserver($cnum,$cdomain);
 2923:     my $normalid=$cdomain.'_'.$cnum;
 2924:     # need to always cache even if we get errors otherwise we keep 
 2925:     # trying and trying and trying to get the course description.
 2926:     my %envhash=();
 2927:     my %returnhash=();
 2928:     
 2929:     my $expiretime=600;
 2930:     if ($env{'request.course.id'} eq $normalid) {
 2931: 	$expiretime=120;
 2932:     }
 2933: 
 2934:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2935:     if (!$args->{'freshen_cache'}
 2936: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2937: 	foreach my $key (keys(%env)) {
 2938: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2939: 	    my ($setting) = $1;
 2940: 	    $returnhash{$setting} = $env{$key};
 2941: 	}
 2942: 	return %returnhash;
 2943:     }
 2944: 
 2945:     # get the data agin
 2946:     if (!$args->{'one_time'}) {
 2947: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2948:     }
 2949: 
 2950:     if ($chome ne 'no_host') {
 2951:        %returnhash=&dump('environment',$cdomain,$cnum);
 2952:        if (!exists($returnhash{'con_lost'})) {
 2953:            $returnhash{'home'}= $chome;
 2954: 	   $returnhash{'domain'} = $cdomain;
 2955: 	   $returnhash{'num'} = $cnum;
 2956:            if (!defined($returnhash{'type'})) {
 2957:                $returnhash{'type'} = 'Course';
 2958:            }
 2959:            while (my ($name,$value) = each %returnhash) {
 2960:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2961:            }
 2962:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2963:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2964: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2965:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2966:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2967:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2968:        }
 2969:     }
 2970:     if (!$args->{'one_time'}) {
 2971: 	&appenv(%envhash);
 2972:     }
 2973:     return %returnhash;
 2974: }
 2975: 
 2976: # -------------------------------------------------See if a user is privileged
 2977: 
 2978: sub privileged {
 2979:     my ($username,$domain)=@_;
 2980:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2981: 			&homeserver($username,$domain));
 2982:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2983:     my $now=time;
 2984:     if ($rolesdump ne '') {
 2985:         foreach my $entry (split(/&/,$rolesdump)) {
 2986: 	    if ($entry!~/^rolesdef_/) {
 2987: 		my ($area,$role)=split(/=/,$entry);
 2988: 		$area=~s/\_\w\w$//;
 2989: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2990: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2991: 		    my $active=1;
 2992: 		    if ($tend) {
 2993: 			if ($tend<$now) { $active=0; }
 2994: 		    }
 2995: 		    if ($tstart) {
 2996: 			if ($tstart>$now) { $active=0; }
 2997: 		    }
 2998: 		    if ($active) { return 1; }
 2999: 		}
 3000: 	    }
 3001: 	}
 3002:     }
 3003:     return 0;
 3004: }
 3005: 
 3006: # -------------------------------------------------------- Get user privileges
 3007: 
 3008: sub rolesinit {
 3009:     my ($domain,$username,$authhost)=@_;
 3010:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3011:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3012:     my %allroles=();
 3013:     my %allgroups=();   
 3014:     my $now=time;
 3015:     my %userroles = ('user.login.time' => $now);
 3016:     my $group_privs;
 3017: 
 3018:     if ($rolesdump ne '') {
 3019:         foreach my $entry (split(/&/,$rolesdump)) {
 3020: 	  if ($entry!~/^rolesdef_/) {
 3021:             my ($area,$role)=split(/=/,$entry);
 3022: 	    $area=~s/\_\w\w$//;
 3023:             my ($trole,$tend,$tstart,$group_privs);
 3024: 	    if ($role=~/^cr/) { 
 3025: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3026: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3027: 		    ($tend,$tstart)=split('_',$trest);
 3028: 		} else {
 3029: 		    $trole=$role;
 3030: 		}
 3031:             } elsif ($role =~ m|^gr/|) {
 3032:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3033:                 ($trole,$group_privs) = split(/\//,$trole);
 3034:                 $group_privs = &unescape($group_privs);
 3035: 	    } else {
 3036: 		($trole,$tend,$tstart)=split(/_/,$role);
 3037: 	    }
 3038: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3039: 					 $username);
 3040: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3041:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3042:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3043:             if (($area ne '') && ($trole ne '')) {
 3044: 		my $spec=$trole.'.'.$area;
 3045: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3046: 		if ($trole =~ /^cr\//) {
 3047:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3048:                 } elsif ($trole eq 'gr') {
 3049:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3050: 		} else {
 3051:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3052: 		}
 3053:             }
 3054:           }
 3055:         }
 3056:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3057:         $userroles{'user.adv'}    = $adv;
 3058: 	$userroles{'user.author'} = $author;
 3059:         $env{'user.adv'}=$adv;
 3060:     }
 3061:     return \%userroles;  
 3062: }
 3063: 
 3064: sub set_arearole {
 3065:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3066: # log the associated role with the area
 3067:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3068:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3069: }
 3070: 
 3071: sub custom_roleprivs {
 3072:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3073:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3074:     my $homsvr=homeserver($rauthor,$rdomain);
 3075:     if (&hostname($homsvr) ne '') {
 3076:         my ($rdummy,$roledef)=
 3077:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3078:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3079:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3080:             if (defined($syspriv)) {
 3081:                 $$allroles{'cm./'}.=':'.$syspriv;
 3082:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3083:             }
 3084:             if ($tdomain ne '') {
 3085:                 if (defined($dompriv)) {
 3086:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3087:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3088:                 }
 3089:                 if (($trest ne '') && (defined($coursepriv))) {
 3090:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3091:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3092:                 }
 3093:             }
 3094:         }
 3095:     }
 3096: }
 3097: 
 3098: sub group_roleprivs {
 3099:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3100:     my $access = 1;
 3101:     my $now = time;
 3102:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3103:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3104:     if ($access) {
 3105:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3106:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3107:     }
 3108: }
 3109: 
 3110: sub standard_roleprivs {
 3111:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3112:     if (defined($pr{$trole.':s'})) {
 3113:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3114:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3115:     }
 3116:     if ($tdomain ne '') {
 3117:         if (defined($pr{$trole.':d'})) {
 3118:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3119:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3120:         }
 3121:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3122:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3123:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3124:         }
 3125:     }
 3126: }
 3127: 
 3128: sub set_userprivs {
 3129:     my ($userroles,$allroles,$allgroups) = @_; 
 3130:     my $author=0;
 3131:     my $adv=0;
 3132:     my %grouproles = ();
 3133:     if (keys(%{$allgroups}) > 0) {
 3134:         foreach my $role (keys %{$allroles}) {
 3135:             my ($trole,$area,$sec,$extendedarea);
 3136:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3137:                 $trole = $1;
 3138:                 $area = $2;
 3139:                 $sec = $3;
 3140:                 $extendedarea = $area.$sec;
 3141:                 if (exists($$allgroups{$area})) {
 3142:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3143:                         my $spec = $trole.'.'.$extendedarea;
 3144:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3145:                                                 $$allgroups{$area}{$group};
 3146:                     }
 3147:                 }
 3148:             }
 3149:         }
 3150:     }
 3151:     foreach my $group (keys(%grouproles)) {
 3152:         $$allroles{$group} = $grouproles{$group};
 3153:     }
 3154:     foreach my $role (keys(%{$allroles})) {
 3155:         my %thesepriv;
 3156:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3157:         foreach my $item (split(/:/,$$allroles{$role})) {
 3158:             if ($item ne '') {
 3159:                 my ($privilege,$restrictions)=split(/&/,$item);
 3160:                 if ($restrictions eq '') {
 3161:                     $thesepriv{$privilege}='F';
 3162:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3163:                     $thesepriv{$privilege}.=$restrictions;
 3164:                 }
 3165:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3166:             }
 3167:         }
 3168:         my $thesestr='';
 3169:         foreach my $priv (keys(%thesepriv)) {
 3170: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3171: 	}
 3172:         $userroles->{'user.priv.'.$role} = $thesestr;
 3173:     }
 3174:     return ($author,$adv);
 3175: }
 3176: 
 3177: # --------------------------------------------------------------- get interface
 3178: 
 3179: sub get {
 3180:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3181:    my $items='';
 3182:    foreach my $item (@$storearr) {
 3183:        $items.=&escape($item).'&';
 3184:    }
 3185:    $items=~s/\&$//;
 3186:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3187:    if (!$uname) { $uname=$env{'user.name'}; }
 3188:    my $uhome=&homeserver($uname,$udomain);
 3189: 
 3190:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3191:    my @pairs=split(/\&/,$rep);
 3192:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3193:      return @pairs;
 3194:    }
 3195:    my %returnhash=();
 3196:    my $i=0;
 3197:    foreach my $item (@$storearr) {
 3198:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3199:       $i++;
 3200:    }
 3201:    return %returnhash;
 3202: }
 3203: 
 3204: # --------------------------------------------------------------- del interface
 3205: 
 3206: sub del {
 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:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3218: }
 3219: 
 3220: # -------------------------------------------------------------- dump interface
 3221: 
 3222: sub dump {
 3223:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3224:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3225:     if (!$uname) { $uname=$env{'user.name'}; }
 3226:     my $uhome=&homeserver($uname,$udomain);
 3227:     if ($regexp) {
 3228: 	$regexp=&escape($regexp);
 3229:     } else {
 3230: 	$regexp='.';
 3231:     }
 3232:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3233:     my @pairs=split(/\&/,$rep);
 3234:     my %returnhash=();
 3235:     foreach my $item (@pairs) {
 3236: 	my ($key,$value)=split(/=/,$item,2);
 3237: 	$key = &unescape($key);
 3238: 	next if ($key =~ /^error: 2 /);
 3239: 	$returnhash{$key}=&thaw_unescape($value);
 3240:     }
 3241:     return %returnhash;
 3242: }
 3243: 
 3244: # --------------------------------------------------------- dumpstore interface
 3245: 
 3246: sub dumpstore {
 3247:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3248:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3249:    if (!$uname) { $uname=$env{'user.name'}; }
 3250:    my $uhome=&homeserver($uname,$udomain);
 3251:    if ($regexp) {
 3252:        $regexp=&escape($regexp);
 3253:    } else {
 3254:        $regexp='.';
 3255:    }
 3256:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3257:    my @pairs=split(/\&/,$rep);
 3258:    my %returnhash=();
 3259:    foreach my $item (@pairs) {
 3260:        my ($key,$value)=split(/=/,$item,2);
 3261:        next if ($key =~ /^error: 2 /);
 3262:        $returnhash{$key}=&thaw_unescape($value);
 3263:    }
 3264:    return %returnhash;
 3265: }
 3266: 
 3267: # -------------------------------------------------------------- keys interface
 3268: 
 3269: sub getkeys {
 3270:    my ($namespace,$udomain,$uname)=@_;
 3271:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3272:    if (!$uname) { $uname=$env{'user.name'}; }
 3273:    my $uhome=&homeserver($uname,$udomain);
 3274:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3275:    my @keyarray=();
 3276:    foreach my $key (split(/\&/,$rep)) {
 3277:       next if ($key =~ /^error: 2 /);
 3278:       push(@keyarray,&unescape($key));
 3279:    }
 3280:    return @keyarray;
 3281: }
 3282: 
 3283: # --------------------------------------------------------------- currentdump
 3284: sub currentdump {
 3285:    my ($courseid,$sdom,$sname)=@_;
 3286:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3287:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3288:    $sname    = $env{'user.name'}         if (! defined($sname));
 3289:    my $uhome = &homeserver($sname,$sdom);
 3290:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3291:    return if ($rep =~ /^(error:|no_such_host)/);
 3292:    #
 3293:    my %returnhash=();
 3294:    #
 3295:    if ($rep eq "unknown_cmd") { 
 3296:        # an old lond will not know currentdump
 3297:        # Do a dump and make it look like a currentdump
 3298:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3299:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3300:        my %hash = @tmp;
 3301:        @tmp=();
 3302:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3303:    } else {
 3304:        my @pairs=split(/\&/,$rep);
 3305:        foreach my $pair (@pairs) {
 3306:            my ($key,$value)=split(/=/,$pair,2);
 3307:            my ($symb,$param) = split(/:/,$key);
 3308:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3309:                                                         &thaw_unescape($value);
 3310:        }
 3311:    }
 3312:    return %returnhash;
 3313: }
 3314: 
 3315: sub convert_dump_to_currentdump{
 3316:     my %hash = %{shift()};
 3317:     my %returnhash;
 3318:     # Code ripped from lond, essentially.  The only difference
 3319:     # here is the unescaping done by lonnet::dump().  Conceivably
 3320:     # we might run in to problems with parameter names =~ /^v\./
 3321:     while (my ($key,$value) = each(%hash)) {
 3322:         my ($v,$symb,$param) = split(/:/,$key);
 3323: 	$symb  = &unescape($symb);
 3324: 	$param = &unescape($param);
 3325:         next if ($v eq 'version' || $symb eq 'keys');
 3326:         next if (exists($returnhash{$symb}) &&
 3327:                  exists($returnhash{$symb}->{$param}) &&
 3328:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3329:         $returnhash{$symb}->{$param}=$value;
 3330:         $returnhash{$symb}->{'v.'.$param}=$v;
 3331:     }
 3332:     #
 3333:     # Remove all of the keys in the hashes which keep track of
 3334:     # the version of the parameter.
 3335:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3336:         # use a foreach because we are going to delete from the hash.
 3337:         foreach my $key (keys(%$param_hash)) {
 3338:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3339:         }
 3340:     }
 3341:     return \%returnhash;
 3342: }
 3343: 
 3344: # ------------------------------------------------------ critical inc interface
 3345: 
 3346: sub cinc {
 3347:     return &inc(@_,'critical');
 3348: }
 3349: 
 3350: # --------------------------------------------------------------- inc interface
 3351: 
 3352: sub inc {
 3353:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3354:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3355:     if (!$uname) { $uname=$env{'user.name'}; }
 3356:     my $uhome=&homeserver($uname,$udomain);
 3357:     my $items='';
 3358:     if (! ref($store)) {
 3359:         # got a single value, so use that instead
 3360:         $items = &escape($store).'=&';
 3361:     } elsif (ref($store) eq 'SCALAR') {
 3362:         $items = &escape($$store).'=&';        
 3363:     } elsif (ref($store) eq 'ARRAY') {
 3364:         $items = join('=&',map {&escape($_);} @{$store});
 3365:     } elsif (ref($store) eq 'HASH') {
 3366:         while (my($key,$value) = each(%{$store})) {
 3367:             $items.= &escape($key).'='.&escape($value).'&';
 3368:         }
 3369:     }
 3370:     $items=~s/\&$//;
 3371:     if ($critical) {
 3372: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3373:     } else {
 3374: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3375:     }
 3376: }
 3377: 
 3378: # --------------------------------------------------------------- put interface
 3379: 
 3380: sub put {
 3381:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3382:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3383:    if (!$uname) { $uname=$env{'user.name'}; }
 3384:    my $uhome=&homeserver($uname,$udomain);
 3385:    my $items='';
 3386:    foreach my $item (keys(%$storehash)) {
 3387:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3388:    }
 3389:    $items=~s/\&$//;
 3390:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3391: }
 3392: 
 3393: # ------------------------------------------------------------ newput interface
 3394: 
 3395: sub newput {
 3396:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3397:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3398:    if (!$uname) { $uname=$env{'user.name'}; }
 3399:    my $uhome=&homeserver($uname,$udomain);
 3400:    my $items='';
 3401:    foreach my $key (keys(%$storehash)) {
 3402:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3403:    }
 3404:    $items=~s/\&$//;
 3405:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3406: }
 3407: 
 3408: # ---------------------------------------------------------  putstore interface
 3409: 
 3410: sub putstore {
 3411:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3412:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3413:    if (!$uname) { $uname=$env{'user.name'}; }
 3414:    my $uhome=&homeserver($uname,$udomain);
 3415:    my $items='';
 3416:    foreach my $key (keys(%$storehash)) {
 3417:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3418:    }
 3419:    $items=~s/\&$//;
 3420:    my $esc_symb=&escape($symb);
 3421:    my $esc_v=&escape($version);
 3422:    my $reply =
 3423:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3424: 	      $uhome);
 3425:    if ($reply eq 'unknown_cmd') {
 3426:        # gfall back to way things use to be done
 3427:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3428: 			    $uname);
 3429:    }
 3430:    return $reply;
 3431: }
 3432: 
 3433: sub old_putstore {
 3434:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3435:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3436:     if (!$uname) { $uname=$env{'user.name'}; }
 3437:     my $uhome=&homeserver($uname,$udomain);
 3438:     my %newstorehash;
 3439:     foreach my $item (keys(%$storehash)) {
 3440: 	my $key = $version.':'.&escape($symb).':'.$item;
 3441: 	$newstorehash{$key} = $storehash->{$item};
 3442:     }
 3443:     my $items='';
 3444:     my %allitems = ();
 3445:     foreach my $item (keys(%newstorehash)) {
 3446: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3447: 	    my $key = $1.':keys:'.$2;
 3448: 	    $allitems{$key} .= $3.':';
 3449: 	}
 3450: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3451:     }
 3452:     foreach my $item (keys(%allitems)) {
 3453: 	$allitems{$item} =~ s/\:$//;
 3454: 	$items.= $item.'='.$allitems{$item}.'&';
 3455:     }
 3456:     $items=~s/\&$//;
 3457:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3458: }
 3459: 
 3460: # ------------------------------------------------------ critical put interface
 3461: 
 3462: sub cput {
 3463:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3464:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3465:    if (!$uname) { $uname=$env{'user.name'}; }
 3466:    my $uhome=&homeserver($uname,$udomain);
 3467:    my $items='';
 3468:    foreach my $item (keys(%$storehash)) {
 3469:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3470:    }
 3471:    $items=~s/\&$//;
 3472:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3473: }
 3474: 
 3475: # -------------------------------------------------------------- eget interface
 3476: 
 3477: sub eget {
 3478:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3479:    my $items='';
 3480:    foreach my $item (@$storearr) {
 3481:        $items.=&escape($item).'&';
 3482:    }
 3483:    $items=~s/\&$//;
 3484:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3485:    if (!$uname) { $uname=$env{'user.name'}; }
 3486:    my $uhome=&homeserver($uname,$udomain);
 3487:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3488:    my @pairs=split(/\&/,$rep);
 3489:    my %returnhash=();
 3490:    my $i=0;
 3491:    foreach my $item (@$storearr) {
 3492:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3493:       $i++;
 3494:    }
 3495:    return %returnhash;
 3496: }
 3497: 
 3498: # ------------------------------------------------------------ tmpput interface
 3499: sub tmpput {
 3500:     my ($storehash,$server,$context)=@_;
 3501:     my $items='';
 3502:     foreach my $item (keys(%$storehash)) {
 3503: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3504:     }
 3505:     $items=~s/\&$//;
 3506:     if (defined($context)) {
 3507:         $items .= ':'.&escape($context);
 3508:     }
 3509:     return &reply("tmpput:$items",$server);
 3510: }
 3511: 
 3512: # ------------------------------------------------------------ tmpget interface
 3513: sub tmpget {
 3514:     my ($token,$server)=@_;
 3515:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3516:     my $rep=&reply("tmpget:$token",$server);
 3517:     my %returnhash;
 3518:     foreach my $item (split(/\&/,$rep)) {
 3519: 	my ($key,$value)=split(/=/,$item);
 3520: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3521:     }
 3522:     return %returnhash;
 3523: }
 3524: 
 3525: # ------------------------------------------------------------ tmpget interface
 3526: sub tmpdel {
 3527:     my ($token,$server)=@_;
 3528:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3529:     return &reply("tmpdel:$token",$server);
 3530: }
 3531: 
 3532: # -------------------------------------------------- portfolio access checking
 3533: 
 3534: sub portfolio_access {
 3535:     my ($requrl) = @_;
 3536:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3537:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3538:     if ($result) {
 3539:         my %setters;
 3540:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3541:             my ($startblock,$endblock) =
 3542:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3543:             if ($startblock && $endblock) {
 3544:                 return 'B';
 3545:             }
 3546:         } else {
 3547:             my ($startblock,$endblock) =
 3548:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3549:             if ($startblock && $endblock) {
 3550:                 return 'B';
 3551:             }
 3552:         }
 3553:     }
 3554:     if ($result eq 'ok') {
 3555:        return 'F';
 3556:     } elsif ($result =~ /^[^:]+:guest_/) {
 3557:        return 'A';
 3558:     }
 3559:     return '';
 3560: }
 3561: 
 3562: sub get_portfolio_access {
 3563:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3564: 
 3565:     if (!ref($access_hash)) {
 3566: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3567: 	my %access_controls = &get_access_controls($current_perms,$group,
 3568: 						   $file_name);
 3569: 	$access_hash = $access_controls{$file_name};
 3570:     }
 3571: 
 3572:     my ($public,$guest,@domains,@users,@courses,@groups);
 3573:     my $now = time;
 3574:     if (ref($access_hash) eq 'HASH') {
 3575:         foreach my $key (keys(%{$access_hash})) {
 3576:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3577:             if ($start > $now) {
 3578:                 next;
 3579:             }
 3580:             if ($end && $end<$now) {
 3581:                 next;
 3582:             }
 3583:             if ($scope eq 'public') {
 3584:                 $public = $key;
 3585:                 last;
 3586:             } elsif ($scope eq 'guest') {
 3587:                 $guest = $key;
 3588:             } elsif ($scope eq 'domains') {
 3589:                 push(@domains,$key);
 3590:             } elsif ($scope eq 'users') {
 3591:                 push(@users,$key);
 3592:             } elsif ($scope eq 'course') {
 3593:                 push(@courses,$key);
 3594:             } elsif ($scope eq 'group') {
 3595:                 push(@groups,$key);
 3596:             }
 3597:         }
 3598:         if ($public) {
 3599:             return 'ok';
 3600:         }
 3601:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3602:             if ($guest) {
 3603:                 return $guest;
 3604:             }
 3605:         } else {
 3606:             if (@domains > 0) {
 3607:                 foreach my $domkey (@domains) {
 3608:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3609:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3610:                             return 'ok';
 3611:                         }
 3612:                     }
 3613:                 }
 3614:             }
 3615:             if (@users > 0) {
 3616:                 foreach my $userkey (@users) {
 3617:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3618:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3619:                             if (ref($item) eq 'HASH') {
 3620:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3621:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3622:                                     return 'ok';
 3623:                                 }
 3624:                             }
 3625:                         }
 3626:                     } 
 3627:                 }
 3628:             }
 3629:             my %roleshash;
 3630:             my @courses_and_groups = @courses;
 3631:             push(@courses_and_groups,@groups); 
 3632:             if (@courses_and_groups > 0) {
 3633:                 my (%allgroups,%allroles); 
 3634:                 my ($start,$end,$role,$sec,$group);
 3635:                 foreach my $envkey (%env) {
 3636:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3637:                         my $cid = $2.'_'.$3; 
 3638:                         if ($1 eq 'gr') {
 3639:                             $group = $4;
 3640:                             $allgroups{$cid}{$group} = $env{$envkey};
 3641:                         } else {
 3642:                             if ($4 eq '') {
 3643:                                 $sec = 'none';
 3644:                             } else {
 3645:                                 $sec = $4;
 3646:                             }
 3647:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3648:                         }
 3649:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3650:                         my $cid = $2.'_'.$3;
 3651:                         if ($4 eq '') {
 3652:                             $sec = 'none';
 3653:                         } else {
 3654:                             $sec = $4;
 3655:                         }
 3656:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3657:                     }
 3658:                 }
 3659:                 if (keys(%allroles) == 0) {
 3660:                     return;
 3661:                 }
 3662:                 foreach my $key (@courses_and_groups) {
 3663:                     my %content = %{$$access_hash{$key}};
 3664:                     my $cnum = $content{'number'};
 3665:                     my $cdom = $content{'domain'};
 3666:                     my $cid = $cdom.'_'.$cnum;
 3667:                     if (!exists($allroles{$cid})) {
 3668:                         next;
 3669:                     }    
 3670:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3671:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3672:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3673:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3674:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3675:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3676:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3677:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3678:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3679:                                         if (grep/^all$/,@sections) {
 3680:                                             return 'ok';
 3681:                                         } else {
 3682:                                             if (grep/^$sec$/,@sections) {
 3683:                                                 return 'ok';
 3684:                                             }
 3685:                                         }
 3686:                                     }
 3687:                                 }
 3688:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3689:                                     if (grep/^none$/,@groups) {
 3690:                                         return 'ok';
 3691:                                     }
 3692:                                 } else {
 3693:                                     if (grep/^all$/,@groups) {
 3694:                                         return 'ok';
 3695:                                     } 
 3696:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3697:                                         if (grep/^$group$/,@groups) {
 3698:                                             return 'ok';
 3699:                                         }
 3700:                                     }
 3701:                                 } 
 3702:                             }
 3703:                         }
 3704:                     }
 3705:                 }
 3706:             }
 3707:             if ($guest) {
 3708:                 return $guest;
 3709:             }
 3710:         }
 3711:     }
 3712:     return;
 3713: }
 3714: 
 3715: sub course_group_datechecker {
 3716:     my ($dates,$now,$status) = @_;
 3717:     my ($start,$end) = split(/\./,$dates);
 3718:     if (!$start && !$end) {
 3719:         return 'ok';
 3720:     }
 3721:     if (grep/^active$/,@{$status}) {
 3722:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3723:             return 'ok';
 3724:         }
 3725:     }
 3726:     if (grep/^previous$/,@{$status}) {
 3727:         if ($end > $now ) {
 3728:             return 'ok';
 3729:         }
 3730:     }
 3731:     if (grep/^future$/,@{$status}) {
 3732:         if ($start > $now) {
 3733:             return 'ok';
 3734:         }
 3735:     }
 3736:     return; 
 3737: }
 3738: 
 3739: sub parse_portfolio_url {
 3740:     my ($url) = @_;
 3741: 
 3742:     my ($type,$udom,$unum,$group,$file_name);
 3743:     
 3744:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3745: 	$type = 1;
 3746:         $udom = $1;
 3747:         $unum = $2;
 3748:         $file_name = $3;
 3749:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3750: 	$type = 2;
 3751:         $udom = $1;
 3752:         $unum = $2;
 3753:         $group = $3;
 3754:         $file_name = $3.'/'.$4;
 3755:     }
 3756:     if (wantarray) {
 3757: 	return ($type,$udom,$unum,$file_name,$group);
 3758:     }
 3759:     return $type;
 3760: }
 3761: 
 3762: sub is_portfolio_url {
 3763:     my ($url) = @_;
 3764:     return scalar(&parse_portfolio_url($url));
 3765: }
 3766: 
 3767: sub is_portfolio_file {
 3768:     my ($file) = @_;
 3769:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3770:         return 1;
 3771:     }
 3772:     return;
 3773: }
 3774: 
 3775: 
 3776: # ---------------------------------------------- Custom access rule evaluation
 3777: 
 3778: sub customaccess {
 3779:     my ($priv,$uri)=@_;
 3780:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3781:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3782:     $udom = &LONCAPA::clean_domain($udom);
 3783:     $ucrs = &LONCAPA::clean_username($ucrs);
 3784:     my $access=0;
 3785:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3786: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3787:         if ($role) {
 3788: 	   if ($role ne $urole) { next; }
 3789:         }
 3790:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3791:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3792:             if ($tdom) {
 3793: 		if ($tdom ne $udom) { next; }
 3794:             }
 3795:             if ($tcrs) {
 3796: 		if ($tcrs ne $ucrs) { next; }
 3797:             }
 3798:             if ($tsec) {
 3799: 		if ($tsec ne $usec) { next; }
 3800:             }
 3801:             $access=($effect eq 'allow');
 3802:             last;
 3803:         }
 3804: 	if ($realm eq '' && $role eq '') {
 3805:             $access=($effect eq 'allow');
 3806: 	}
 3807:     }
 3808:     return $access;
 3809: }
 3810: 
 3811: # ------------------------------------------------- Check for a user privilege
 3812: 
 3813: sub allowed {
 3814:     my ($priv,$uri,$symb,$role)=@_;
 3815:     my $ver_orguri=$uri;
 3816:     $uri=&deversion($uri);
 3817:     my $orguri=$uri;
 3818:     $uri=&declutter($uri);
 3819: 
 3820:     if ($priv eq 'evb') {
 3821: # Evade communication block restrictions for specified role in a course
 3822:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3823:             return $1;
 3824:         } else {
 3825:             return;
 3826:         }
 3827:     }
 3828: 
 3829:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3830: # Free bre access to adm and meta resources
 3831:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3832: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3833: 	&& ($priv eq 'bre')) {
 3834: 	return 'F';
 3835:     }
 3836: 
 3837: # Free bre access to user's own portfolio contents
 3838:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3839:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3840: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3841:         my %setters;
 3842:         my ($startblock,$endblock) = 
 3843:             &Apache::loncommon::blockcheck(\%setters,'port');
 3844:         if ($startblock && $endblock) {
 3845:             return 'B';
 3846:         } else {
 3847:             return 'F';
 3848:         }
 3849:     }
 3850: 
 3851: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3852:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3853:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3854:         if (exists($env{'request.course.id'})) {
 3855:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3856:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3857:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3858:                 my $courseprivid=$env{'request.course.id'};
 3859:                 $courseprivid=~s/\_/\//;
 3860:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3861:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3862:                     return $1; 
 3863:                 } else {
 3864:                     if ($env{'request.course.sec'}) {
 3865:                         $courseprivid.='/'.$env{'request.course.sec'};
 3866:                     }
 3867:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3868:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3869:                         return $2;
 3870:                     }
 3871:                 }
 3872:             }
 3873:         }
 3874:     }
 3875: 
 3876: # Free bre to public access
 3877: 
 3878:     if ($priv eq 'bre') {
 3879:         my $copyright=&metadata($uri,'copyright');
 3880: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3881:            return 'F'; 
 3882:         }
 3883:         if ($copyright eq 'priv') {
 3884:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3885: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3886: 		return '';
 3887:             }
 3888:         }
 3889:         if ($copyright eq 'domain') {
 3890:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3891: 	    unless (($env{'user.domain'} eq $1) ||
 3892:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3893: 		return '';
 3894:             }
 3895:         }
 3896:         if ($env{'request.role'}=~ /li\.\//) {
 3897:             # Library role, so allow browsing of resources in this domain.
 3898:             return 'F';
 3899:         }
 3900:         if ($copyright eq 'custom') {
 3901: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3902:         }
 3903:     }
 3904:     # Domain coordinator is trying to create a course
 3905:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3906:         # uri is the requested domain in this case.
 3907:         # comparison to 'request.role.domain' shows if the user has selected
 3908:         # a role of dc for the domain in question.
 3909:         return 'F' if ($uri eq $env{'request.role.domain'});
 3910:     }
 3911: 
 3912:     my $thisallowed='';
 3913:     my $statecond=0;
 3914:     my $courseprivid='';
 3915: 
 3916: # Course
 3917: 
 3918:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3919:        $thisallowed.=$1;
 3920:     }
 3921: 
 3922: # Domain
 3923: 
 3924:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3925:        =~/\Q$priv\E\&([^\:]*)/) {
 3926:        $thisallowed.=$1;
 3927:     }
 3928: 
 3929: # Course: uri itself is a course
 3930:     my $courseuri=$uri;
 3931:     $courseuri=~s/\_(\d)/\/$1/;
 3932:     $courseuri=~s/^([^\/])/\/$1/;
 3933: 
 3934:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3935:        =~/\Q$priv\E\&([^\:]*)/) {
 3936:        $thisallowed.=$1;
 3937:     }
 3938: 
 3939: # URI is an uploaded document for this course, default permissions don't matter
 3940: # not allowing 'edit' access (editupload) to uploaded course docs
 3941:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3942: 	$thisallowed='';
 3943:         my ($match)=&is_on_map($uri);
 3944:         if ($match) {
 3945:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3946:                   =~/\Q$priv\E\&([^\:]*)/) {
 3947:                 $thisallowed.=$1;
 3948:             }
 3949:         } else {
 3950:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3951:             if ($refuri) {
 3952:                 if ($refuri =~ m|^/adm/|) {
 3953:                     $thisallowed='F';
 3954:                 } else {
 3955:                     $refuri=&declutter($refuri);
 3956:                     my ($match) = &is_on_map($refuri);
 3957:                     if ($match) {
 3958:                         $thisallowed='F';
 3959:                     }
 3960:                 }
 3961:             }
 3962:         }
 3963:     }
 3964: 
 3965:     if ($priv eq 'bre'
 3966: 	&& $thisallowed ne 'F' 
 3967: 	&& $thisallowed ne '2'
 3968: 	&& &is_portfolio_url($uri)) {
 3969: 	$thisallowed = &portfolio_access($uri);
 3970:     }
 3971:     
 3972: # Full access at system, domain or course-wide level? Exit.
 3973: 
 3974:     if ($thisallowed=~/F/) {
 3975: 	return 'F';
 3976:     }
 3977: 
 3978: # If this is generating or modifying users, exit with special codes
 3979: 
 3980:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3981: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3982: 	    my ($audom,$auname)=split('/',$uri);
 3983: # no author name given, so this just checks on the general right to make a co-author in this domain
 3984: 	    unless ($auname) { return $thisallowed; }
 3985: # an author name is given, so we are about to actually make a co-author for a certain account
 3986: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3987: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3988: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3989: 	}
 3990: 	return $thisallowed;
 3991:     }
 3992: #
 3993: # Gathered so far: system, domain and course wide privileges
 3994: #
 3995: # Course: See if uri or referer is an individual resource that is part of 
 3996: # the course
 3997: 
 3998:     if ($env{'request.course.id'}) {
 3999: 
 4000:        $courseprivid=$env{'request.course.id'};
 4001:        if ($env{'request.course.sec'}) {
 4002:           $courseprivid.='/'.$env{'request.course.sec'};
 4003:        }
 4004:        $courseprivid=~s/\_/\//;
 4005:        my $checkreferer=1;
 4006:        my ($match,$cond)=&is_on_map($uri);
 4007:        if ($match) {
 4008:            $statecond=$cond;
 4009:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4010:                =~/\Q$priv\E\&([^\:]*)/) {
 4011:                $thisallowed.=$1;
 4012:                $checkreferer=0;
 4013:            }
 4014:        }
 4015:        
 4016:        if ($checkreferer) {
 4017: 	  my $refuri=$env{'httpref.'.$orguri};
 4018:             unless ($refuri) {
 4019:                 foreach my $key (keys(%env)) {
 4020: 		    if ($key=~/^httpref\..*\*/) {
 4021: 			my $pattern=$key;
 4022:                         $pattern=~s/^httpref\.\/res\///;
 4023:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4024:                         $pattern=~s/\//\\\//g;
 4025:                         if ($orguri=~/$pattern/) {
 4026: 			    $refuri=$env{$key};
 4027:                         }
 4028:                     }
 4029:                 }
 4030:             }
 4031: 
 4032:          if ($refuri) { 
 4033: 	  $refuri=&declutter($refuri);
 4034:           my ($match,$cond)=&is_on_map($refuri);
 4035:             if ($match) {
 4036:               my $refstatecond=$cond;
 4037:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4038:                   =~/\Q$priv\E\&([^\:]*)/) {
 4039:                   $thisallowed.=$1;
 4040:                   $uri=$refuri;
 4041:                   $statecond=$refstatecond;
 4042:               }
 4043:           }
 4044:         }
 4045:        }
 4046:    }
 4047: 
 4048: #
 4049: # Gathered now: all privileges that could apply, and condition number
 4050: # 
 4051: #
 4052: # Full or no access?
 4053: #
 4054: 
 4055:     if ($thisallowed=~/F/) {
 4056: 	return 'F';
 4057:     }
 4058: 
 4059:     unless ($thisallowed) {
 4060:         return '';
 4061:     }
 4062: 
 4063: # Restrictions exist, deal with them
 4064: #
 4065: #   C:according to course preferences
 4066: #   R:according to resource settings
 4067: #   L:unless locked
 4068: #   X:according to user session state
 4069: #
 4070: 
 4071: # Possibly locked functionality, check all courses
 4072: # Locks might take effect only after 10 minutes cache expiration for other
 4073: # courses, and 2 minutes for current course
 4074: 
 4075:     my $envkey;
 4076:     if ($thisallowed=~/L/) {
 4077:         foreach $envkey (keys %env) {
 4078:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4079:                my $courseid=$2;
 4080:                my $roleid=$1.'.'.$2;
 4081:                $courseid=~s/^\///;
 4082:                my $expiretime=600;
 4083:                if ($env{'request.role'} eq $roleid) {
 4084: 		  $expiretime=120;
 4085:                }
 4086: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4087:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4088:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4089: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4090:                }
 4091:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4092:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4093: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4094:                        &log($env{'user.domain'},$env{'user.name'},
 4095:                             $env{'user.home'},
 4096:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4097:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4098:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4099: 		       return '';
 4100:                    }
 4101:                }
 4102:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4103:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4104: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4105:                        &log($env{'user.domain'},$env{'user.name'},
 4106:                             $env{'user.home'},
 4107:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4108:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4109:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4110: 		       return '';
 4111:                    }
 4112:                }
 4113: 	   }
 4114:        }
 4115:     }
 4116:    
 4117: #
 4118: # Rest of the restrictions depend on selected course
 4119: #
 4120: 
 4121:     unless ($env{'request.course.id'}) {
 4122: 	if ($thisallowed eq 'A') {
 4123: 	    return 'A';
 4124:         } elsif ($thisallowed eq 'B') {
 4125:             return 'B';
 4126: 	} else {
 4127: 	    return '1';
 4128: 	}
 4129:     }
 4130: 
 4131: #
 4132: # Now user is definitely in a course
 4133: #
 4134: 
 4135: 
 4136: # Course preferences
 4137: 
 4138:    if ($thisallowed=~/C/) {
 4139:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4140:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4141:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4142: 	   =~/\Q$rolecode\E/) {
 4143: 	   if ($priv ne 'pch') { 
 4144: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4145: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4146: 			$env{'request.course.id'});
 4147: 	   }
 4148:            return '';
 4149:        }
 4150: 
 4151:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4152: 	   =~/\Q$unamedom\E/) {
 4153: 	   if ($priv ne 'pch') { 
 4154: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4155: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4156: 			$env{'request.course.id'});
 4157: 	   }
 4158:            return '';
 4159:        }
 4160:    }
 4161: 
 4162: # Resource preferences
 4163: 
 4164:    if ($thisallowed=~/R/) {
 4165:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4166:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4167: 	   if ($priv ne 'pch') { 
 4168: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4169: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4170: 	   }
 4171: 	   return '';
 4172:        }
 4173:    }
 4174: 
 4175: # Restricted by state or randomout?
 4176: 
 4177:    if ($thisallowed=~/X/) {
 4178:       if ($env{'acc.randomout'}) {
 4179: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4180:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4181:             return ''; 
 4182:          }
 4183:       }
 4184:       if (&condval($statecond)) {
 4185: 	 return '2';
 4186:       } else {
 4187:          return '';
 4188:       }
 4189:    }
 4190: 
 4191:     if ($thisallowed eq 'A') {
 4192: 	return 'A';
 4193:     } elsif ($thisallowed eq 'B') {
 4194:         return 'B';
 4195:     }
 4196:    return 'F';
 4197: }
 4198: 
 4199: sub split_uri_for_cond {
 4200:     my $uri=&deversion(&declutter(shift));
 4201:     my @uriparts=split(/\//,$uri);
 4202:     my $filename=pop(@uriparts);
 4203:     my $pathname=join('/',@uriparts);
 4204:     return ($pathname,$filename);
 4205: }
 4206: # --------------------------------------------------- Is a resource on the map?
 4207: 
 4208: sub is_on_map {
 4209:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4210:     #Trying to find the conditional for the file
 4211:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4212: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4213:     if ($match) {
 4214: 	return (1,$1);
 4215:     } else {
 4216: 	return (0,0);
 4217:     }
 4218: }
 4219: 
 4220: # --------------------------------------------------------- Get symb from alias
 4221: 
 4222: sub get_symb_from_alias {
 4223:     my $symb=shift;
 4224:     my ($map,$resid,$url)=&decode_symb($symb);
 4225: # Already is a symb
 4226:     if ($url) { return $symb; }
 4227: # Must be an alias
 4228:     my $aliassymb='';
 4229:     my %bighash;
 4230:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4231:                             &GDBM_READER(),0640)) {
 4232:         my $rid=$bighash{'mapalias_'.$symb};
 4233: 	if ($rid) {
 4234: 	    my ($mapid,$resid)=split(/\./,$rid);
 4235: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4236: 				    $resid,$bighash{'src_'.$rid});
 4237: 	}
 4238:         untie %bighash;
 4239:     }
 4240:     return $aliassymb;
 4241: }
 4242: 
 4243: # ----------------------------------------------------------------- Define Role
 4244: 
 4245: sub definerole {
 4246:   if (allowed('mcr','/')) {
 4247:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4248:     foreach my $role (split(':',$sysrole)) {
 4249: 	my ($crole,$cqual)=split(/\&/,$role);
 4250:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4251:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4252: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4253:                return "refused:s:$crole&$cqual"; 
 4254:             }
 4255:         }
 4256:     }
 4257:     foreach my $role (split(':',$domrole)) {
 4258: 	my ($crole,$cqual)=split(/\&/,$role);
 4259:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4260:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4261: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4262:                return "refused:d:$crole&$cqual"; 
 4263:             }
 4264:         }
 4265:     }
 4266:     foreach my $role (split(':',$courole)) {
 4267: 	my ($crole,$cqual)=split(/\&/,$role);
 4268:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4269:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4270: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4271:                return "refused:c:$crole&$cqual"; 
 4272:             }
 4273:         }
 4274:     }
 4275:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4276:                 "$env{'user.domain'}:$env{'user.name'}:".
 4277: 	        "rolesdef_$rolename=".
 4278:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4279:     return reply($command,$env{'user.home'});
 4280:   } else {
 4281:     return 'refused';
 4282:   }
 4283: }
 4284: 
 4285: # ---------------- Make a metadata query against the network of library servers
 4286: 
 4287: sub metadata_query {
 4288:     my ($query,$custom,$customshow,$server_array)=@_;
 4289:     my %rhash;
 4290:     my %libserv = &all_library();
 4291:     my @server_list = (defined($server_array) ? @$server_array
 4292:                                               : keys(%libserv) );
 4293:     for my $server (@server_list) {
 4294: 	unless ($custom or $customshow) {
 4295: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4296: 	    $rhash{$server}=$reply;
 4297: 	}
 4298: 	else {
 4299: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4300: 			     &escape($custom).':'.&escape($customshow),
 4301: 			     $server);
 4302: 	    $rhash{$server}=$reply;
 4303: 	}
 4304:     }
 4305:     return \%rhash;
 4306: }
 4307: 
 4308: # ----------------------------------------- Send log queries and wait for reply
 4309: 
 4310: sub log_query {
 4311:     my ($uname,$udom,$query,%filters)=@_;
 4312:     my $uhome=&homeserver($uname,$udom);
 4313:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4314:     my $uhost=&hostname($uhome);
 4315:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4316:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4317:                        $uhome);
 4318:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4319:     return get_query_reply($queryid);
 4320: }
 4321: 
 4322: # -------------------------- Update MySQL table for portfolio file
 4323: 
 4324: sub update_portfolio_table {
 4325:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4326:     my $homeserver = &homeserver($uname,$udom);
 4327:     my $queryid=
 4328:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4329:                ':'.&escape($file_name).':'.$action,$homeserver);
 4330:     my $reply = &get_query_reply($queryid);
 4331:     return $reply;
 4332: }
 4333: 
 4334: # ------- Request retrieval of institutional classlists for course(s)
 4335: 
 4336: sub fetch_enrollment_query {
 4337:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4338:     my $homeserver;
 4339:     my $maxtries = 1;
 4340:     if ($context eq 'automated') {
 4341:         $homeserver = $perlvar{'lonHostID'};
 4342:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4343:     } else {
 4344:         $homeserver = &homeserver($cnum,$dom);
 4345:     }
 4346:     my $host=&hostname($homeserver);
 4347:     my $cmd = '';
 4348:     foreach my $affiliate (keys %{$affiliatesref}) {
 4349:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4350:     }
 4351:     $cmd =~ s/%%$//;
 4352:     $cmd = &escape($cmd);
 4353:     my $query = 'fetchenrollment';
 4354:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4355:     unless ($queryid=~/^\Q$host\E\_/) { 
 4356:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4357:         return 'error: '.$queryid;
 4358:     }
 4359:     my $reply = &get_query_reply($queryid);
 4360:     my $tries = 1;
 4361:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4362:         $reply = &get_query_reply($queryid);
 4363:         $tries ++;
 4364:     }
 4365:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4366:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4367:     } else {
 4368:         my @responses = split/:/,$reply;
 4369:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4370:             foreach my $line (@responses) {
 4371:                 my ($key,$value) = split(/=/,$line,2);
 4372:                 $$replyref{$key} = $value;
 4373:             }
 4374:         } else {
 4375:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4376:             foreach my $line (@responses) {
 4377:                 my ($key,$value) = split(/=/,$line);
 4378:                 $$replyref{$key} = $value;
 4379:                 if ($value > 0) {
 4380:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4381:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4382:                         my $destname = $pathname.'/'.$filename;
 4383:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4384:                         if ($xml_classlist =~ /^error/) {
 4385:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4386:                         } else {
 4387:                             if ( open(FILE,">$destname") ) {
 4388:                                 print FILE &unescape($xml_classlist);
 4389:                                 close(FILE);
 4390:                             } else {
 4391:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4392:                             }
 4393:                         }
 4394:                     }
 4395:                 }
 4396:             }
 4397:         }
 4398:         return 'ok';
 4399:     }
 4400:     return 'error';
 4401: }
 4402: 
 4403: sub get_query_reply {
 4404:     my $queryid=shift;
 4405:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4406:     my $reply='';
 4407:     for (1..100) {
 4408: 	sleep 2;
 4409:         if (-e $replyfile.'.end') {
 4410: 	    if (open(my $fh,$replyfile)) {
 4411:                $reply.=<$fh>;
 4412:                close($fh);
 4413: 	   } else { return 'error: reply_file_error'; }
 4414:            return &unescape($reply);
 4415: 	}
 4416:     }
 4417:     return 'timeout:'.$queryid;
 4418: }
 4419: 
 4420: sub courselog_query {
 4421: #
 4422: # possible filters:
 4423: # url: url or symb
 4424: # username
 4425: # domain
 4426: # action: view, submit, grade
 4427: # start: timestamp
 4428: # end: timestamp
 4429: #
 4430:     my (%filters)=@_;
 4431:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4432:     if ($filters{'url'}) {
 4433: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4434:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4435:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4436:     }
 4437:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4438:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4439:     return &log_query($cname,$cdom,'courselog',%filters);
 4440: }
 4441: 
 4442: sub userlog_query {
 4443: #
 4444: # possible filters:
 4445: # action: log check role
 4446: # start: timestamp
 4447: # end: timestamp
 4448: #
 4449:     my ($uname,$udom,%filters)=@_;
 4450:     return &log_query($uname,$udom,'userlog',%filters);
 4451: }
 4452: 
 4453: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4454: 
 4455: sub auto_run {
 4456:     my ($cnum,$cdom) = @_;
 4457:     my $homeserver = &homeserver($cnum,$cdom);
 4458:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4459:     return $response;
 4460: }
 4461: 
 4462: sub auto_get_sections {
 4463:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4464:     my $homeserver = &homeserver($cnum,$cdom);
 4465:     my @secs = ();
 4466:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4467:     unless ($response eq 'refused') {
 4468:         @secs = split/:/,$response;
 4469:     }
 4470:     return @secs;
 4471: }
 4472: 
 4473: sub auto_new_course {
 4474:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4475:     my $homeserver = &homeserver($cnum,$cdom);
 4476:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4477:     return $response;
 4478: }
 4479: 
 4480: sub auto_validate_courseID {
 4481:     my ($cnum,$cdom,$inst_course_id) = @_;
 4482:     my $homeserver = &homeserver($cnum,$cdom);
 4483:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4484:     return $response;
 4485: }
 4486: 
 4487: sub auto_create_password {
 4488:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4489:     my ($homeserver,$response);
 4490:     my $create_passwd = 0;
 4491:     my $authchk = '';
 4492:     if ($udom =~ /^$match_domain$/) {
 4493:         $homeserver = &domain($udom,'primary');
 4494:     }
 4495:     if ($homeserver eq '') {
 4496:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4497:             $homeserver = &homeserver($cnum,$cdom);
 4498:         }
 4499:     }
 4500:     if ($homeserver eq '') {
 4501:         $authchk = 'nodomain';
 4502:     } else {
 4503:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4504:         if ($response eq 'refused') {
 4505:             $authchk = 'refused';
 4506:         } else {
 4507:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4508:         }
 4509:     }
 4510:     return ($authparam,$create_passwd,$authchk);
 4511: }
 4512: 
 4513: sub auto_photo_permission {
 4514:     my ($cnum,$cdom,$students) = @_;
 4515:     my $homeserver = &homeserver($cnum,$cdom);
 4516:     my ($outcome,$perm_reqd,$conditions) = 
 4517: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4518:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4519: 	return (undef,undef);
 4520:     }
 4521:     return ($outcome,$perm_reqd,$conditions);
 4522: }
 4523: 
 4524: sub auto_checkphotos {
 4525:     my ($uname,$udom,$pid) = @_;
 4526:     my $homeserver = &homeserver($uname,$udom);
 4527:     my ($result,$resulttype);
 4528:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4529: 				   &escape($uname).':'.&escape($pid),
 4530: 				   $homeserver));
 4531:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4532: 	return (undef,undef);
 4533:     }
 4534:     if ($outcome) {
 4535:         ($result,$resulttype) = split(/:/,$outcome);
 4536:     } 
 4537:     return ($result,$resulttype);
 4538: }
 4539: 
 4540: sub auto_photochoice {
 4541:     my ($cnum,$cdom) = @_;
 4542:     my $homeserver = &homeserver($cnum,$cdom);
 4543:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4544: 						       &escape($cdom),
 4545: 						       $homeserver)));
 4546:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4547: 	return (undef,undef);
 4548:     }
 4549:     return ($update,$comment);
 4550: }
 4551: 
 4552: sub auto_photoupdate {
 4553:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4554:     my $homeserver = &homeserver($cnum,$dom);
 4555:     my $host=&hostname($homeserver);
 4556:     my $cmd = '';
 4557:     my $maxtries = 1;
 4558:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4559:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4560:     }
 4561:     $cmd =~ s/%%$//;
 4562:     $cmd = &escape($cmd);
 4563:     my $query = 'institutionalphotos';
 4564:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4565:     unless ($queryid=~/^\Q$host\E\_/) {
 4566:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4567:         return 'error: '.$queryid;
 4568:     }
 4569:     my $reply = &get_query_reply($queryid);
 4570:     my $tries = 1;
 4571:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4572:         $reply = &get_query_reply($queryid);
 4573:         $tries ++;
 4574:     }
 4575:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4576:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4577:     } else {
 4578:         my @responses = split(/:/,$reply);
 4579:         my $outcome = shift(@responses); 
 4580:         foreach my $item (@responses) {
 4581:             my ($key,$value) = split(/=/,$item);
 4582:             $$photo{$key} = $value;
 4583:         }
 4584:         return $outcome;
 4585:     }
 4586:     return 'error';
 4587: }
 4588: 
 4589: sub auto_instcode_format {
 4590:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4591: 	$cat_order) = @_;
 4592:     my $courses = '';
 4593:     my @homeservers;
 4594:     if ($caller eq 'global') {
 4595: 	my %servers = &get_servers($codedom,'library');
 4596: 	foreach my $tryserver (keys(%servers)) {
 4597: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4598: 		push(@homeservers,$tryserver);
 4599: 	    }
 4600:         }
 4601:     } else {
 4602:         push(@homeservers,&homeserver($caller,$codedom));
 4603:     }
 4604:     foreach my $code (keys(%{$instcodes})) {
 4605:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4606:     }
 4607:     chop($courses);
 4608:     my $ok_response = 0;
 4609:     my $response;
 4610:     while (@homeservers > 0 && $ok_response == 0) {
 4611:         my $server = shift(@homeservers); 
 4612:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4613:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4614:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4615: 		split/:/,$response;
 4616:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4617:             push(@{$codetitles},&str2array($codetitles_str));
 4618:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4619:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4620:             $ok_response = 1;
 4621:         }
 4622:     }
 4623:     if ($ok_response) {
 4624:         return 'ok';
 4625:     } else {
 4626:         return $response;
 4627:     }
 4628: }
 4629: 
 4630: sub auto_instcode_defaults {
 4631:     my ($domain,$returnhash,$code_order) = @_;
 4632:     my @homeservers;
 4633: 
 4634:     my %servers = &get_servers($domain,'library');
 4635:     foreach my $tryserver (keys(%servers)) {
 4636: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4637: 	    push(@homeservers,$tryserver);
 4638: 	}
 4639:     }
 4640: 
 4641:     my $response;
 4642:     foreach my $server (@homeservers) {
 4643:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4644:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4645: 	
 4646: 	foreach my $pair (split(/\&/,$response)) {
 4647: 	    my ($name,$value)=split(/\=/,$pair);
 4648: 	    if ($name eq 'code_order') {
 4649: 		@{$code_order} = split(/\&/,&unescape($value));
 4650: 	    } else {
 4651: 		$returnhash->{&unescape($name)}=&unescape($value);
 4652: 	    }
 4653: 	}
 4654: 	return 'ok';
 4655:     }
 4656: 
 4657:     return $response;
 4658: } 
 4659: 
 4660: sub auto_validate_class_sec {
 4661:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4662:     my $homeserver = &homeserver($cnum,$cdom);
 4663:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4664:                         &escape($owner).':'.$cdom,$homeserver);
 4665:     return $response;
 4666: }
 4667: 
 4668: # ------------------------------------------------------- Course Group routines
 4669: 
 4670: sub get_coursegroups {
 4671:     my ($cdom,$cnum,$group,$namespace) = @_;
 4672:     return(&dump($namespace,$cdom,$cnum,$group));
 4673: }
 4674: 
 4675: sub modify_coursegroup {
 4676:     my ($cdom,$cnum,$groupsettings) = @_;
 4677:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4678: }
 4679: 
 4680: sub toggle_coursegroup_status {
 4681:     my ($cdom,$cnum,$group,$action) = @_;
 4682:     my ($from_namespace,$to_namespace);
 4683:     if ($action eq 'delete') {
 4684:         $from_namespace = 'coursegroups';
 4685:         $to_namespace = 'deleted_groups';
 4686:     } else {
 4687:         $from_namespace = 'deleted_groups';
 4688:         $to_namespace = 'coursegroups';
 4689:     }
 4690:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4691:     if (my $tmp = &error(%curr_group)) {
 4692:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4693:         return ('read error',$tmp);
 4694:     } else {
 4695:         my %savedsettings = %curr_group; 
 4696:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4697:         my $deloutcome;
 4698:         if ($result eq 'ok') {
 4699:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4700:         } else {
 4701:             return ('write error',$result);
 4702:         }
 4703:         if ($deloutcome eq 'ok') {
 4704:             return 'ok';
 4705:         } else {
 4706:             return ('delete error',$deloutcome);
 4707:         }
 4708:     }
 4709: }
 4710: 
 4711: sub modify_group_roles {
 4712:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4713:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4714:     my $role = 'gr/'.&escape($userprivs);
 4715:     my ($uname,$udom) = split(/:/,$user);
 4716:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4717:     if ($result eq 'ok') {
 4718:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4719:     }
 4720:     return $result;
 4721: }
 4722: 
 4723: sub modify_coursegroup_membership {
 4724:     my ($cdom,$cnum,$membership) = @_;
 4725:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4726:     return $result;
 4727: }
 4728: 
 4729: sub get_active_groups {
 4730:     my ($udom,$uname,$cdom,$cnum) = @_;
 4731:     my $now = time;
 4732:     my %groups = ();
 4733:     foreach my $key (keys(%env)) {
 4734:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4735:             my ($start,$end) = split(/\./,$env{$key});
 4736:             if (($end!=0) && ($end<$now)) { next; }
 4737:             if (($start!=0) && ($start>$now)) { next; }
 4738:             if ($1 eq $cdom && $2 eq $cnum) {
 4739:                 $groups{$3} = $env{$key} ;
 4740:             }
 4741:         }
 4742:     }
 4743:     return %groups;
 4744: }
 4745: 
 4746: sub get_group_membership {
 4747:     my ($cdom,$cnum,$group) = @_;
 4748:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4749: }
 4750: 
 4751: sub get_users_groups {
 4752:     my ($udom,$uname,$courseid) = @_;
 4753:     my @usersgroups;
 4754:     my $cachetime=1800;
 4755: 
 4756:     my $hashid="$udom:$uname:$courseid";
 4757:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4758:     if (defined($cached)) {
 4759:         @usersgroups = split(/:/,$grouplist);
 4760:     } else {  
 4761:         $grouplist = '';
 4762:         my $courseurl = &courseid_to_courseurl($courseid);
 4763:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4764:         my $access_end = $env{'course.'.$courseid.
 4765:                               '.default_enrollment_end_date'};
 4766:         my $now = time;
 4767:         foreach my $key (keys(%roleshash)) {
 4768:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4769:                 my $group = $1;
 4770:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4771:                     my $start = $2;
 4772:                     my $end = $1;
 4773:                     if ($start == -1) { next; } # deleted from group
 4774:                     if (($start!=0) && ($start>$now)) { next; }
 4775:                     if (($end!=0) && ($end<$now)) {
 4776:                         if ($access_end && $access_end < $now) {
 4777:                             if ($access_end - $end < 86400) {
 4778:                                 push(@usersgroups,$group);
 4779:                             }
 4780:                         }
 4781:                         next;
 4782:                     }
 4783:                     push(@usersgroups,$group);
 4784:                 }
 4785:             }
 4786:         }
 4787:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4788:         $grouplist = join(':',@usersgroups);
 4789:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4790:     }
 4791:     return @usersgroups;
 4792: }
 4793: 
 4794: sub devalidate_getgroups_cache {
 4795:     my ($udom,$uname,$cdom,$cnum)=@_;
 4796:     my $courseid = $cdom.'_'.$cnum;
 4797: 
 4798:     my $hashid="$udom:$uname:$courseid";
 4799:     &devalidate_cache_new('getgroups',$hashid);
 4800: }
 4801: 
 4802: # ------------------------------------------------------------------ Plain Text
 4803: 
 4804: sub plaintext {
 4805:     my ($short,$type,$cid) = @_;
 4806:     if ($short =~ /^cr/) {
 4807: 	return (split('/',$short))[-1];
 4808:     }
 4809:     if (!defined($cid)) {
 4810:         $cid = $env{'request.course.id'};
 4811:     }
 4812:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4813:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4814:                                           '.plaintext'});
 4815:     }
 4816:     my %rolenames = (
 4817:                       Course => 'std',
 4818:                       Group => 'alt1',
 4819:                     );
 4820:     if (defined($type) && 
 4821:          defined($rolenames{$type}) && 
 4822:          defined($prp{$short}{$rolenames{$type}})) {
 4823:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4824:     } else {
 4825:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4826:     }
 4827: }
 4828: 
 4829: # ----------------------------------------------------------------- Assign Role
 4830: 
 4831: sub assignrole {
 4832:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4833:     my $mrole;
 4834:     if ($role =~ /^cr\//) {
 4835:         my $cwosec=$url;
 4836:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4837: 	unless (&allowed('ccr',$cwosec)) {
 4838:            &logthis('Refused custom assignrole: '.
 4839:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4840: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4841:            return 'refused'; 
 4842:         }
 4843:         $mrole='cr';
 4844:     } elsif ($role =~ /^gr\//) {
 4845:         my $cwogrp=$url;
 4846:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4847:         unless (&allowed('mdg',$cwogrp)) {
 4848:             &logthis('Refused group assignrole: '.
 4849:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4850:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4851:             return 'refused';
 4852:         }
 4853:         $mrole='gr';
 4854:     } else {
 4855:         my $cwosec=$url;
 4856:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4857:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4858:            &logthis('Refused assignrole: '.
 4859:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4860: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4861:            return 'refused'; 
 4862:         }
 4863:         $mrole=$role;
 4864:     }
 4865:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4866:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4867:     if ($end) { $command.='_'.$end; }
 4868:     if ($start) {
 4869: 	if ($end) { 
 4870:            $command.='_'.$start; 
 4871:         } else {
 4872:            $command.='_0_'.$start;
 4873:         }
 4874:     }
 4875:     my $origstart = $start;
 4876:     my $origend = $end;
 4877: # actually delete
 4878:     if ($deleteflag) {
 4879: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4880: # modify command to delete the role
 4881:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4882:                 "$udom:$uname:$url".'_'."$mrole";
 4883: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4884: # set start and finish to negative values for userrolelog
 4885:            $start=-1;
 4886:            $end=-1;
 4887:         }
 4888:     }
 4889: # send command
 4890:     my $answer=&reply($command,&homeserver($uname,$udom));
 4891: # log new user role if status is ok
 4892:     if ($answer eq 'ok') {
 4893: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4894: # for course roles, perform group memberships changes triggered by role change.
 4895:         unless ($role =~ /^gr/) {
 4896:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4897:                                              $origstart);
 4898:         }
 4899:     }
 4900:     return $answer;
 4901: }
 4902: 
 4903: # -------------------------------------------------- Modify user authentication
 4904: # Overrides without validation
 4905: 
 4906: sub modifyuserauth {
 4907:     my ($udom,$uname,$umode,$upass)=@_;
 4908:     my $uhome=&homeserver($uname,$udom);
 4909:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4910:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4911:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4912:              ' in domain '.$env{'request.role.domain'});  
 4913:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4914: 		     &escape($upass),$uhome);
 4915:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4916:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4917:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4918:     &log($udom,,$uname,$uhome,
 4919:         'Authentication changed by '.$env{'user.domain'}.', '.
 4920:                                      $env{'user.name'}.', '.$umode.
 4921:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4922:     unless ($reply eq 'ok') {
 4923:         &logthis('Authentication mode error: '.$reply);
 4924: 	return 'error: '.$reply;
 4925:     }   
 4926:     return 'ok';
 4927: }
 4928: 
 4929: # --------------------------------------------------------------- Modify a user
 4930: 
 4931: sub modifyuser {
 4932:     my ($udom,    $uname, $uid,
 4933:         $umode,   $upass, $first,
 4934:         $middle,  $last,  $gene,
 4935:         $forceid, $desiredhome, $email)=@_;
 4936:     $udom= &LONCAPA::clean_domain($udom);
 4937:     $uname=&LONCAPA::clean_username($uname);
 4938:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4939:              $umode.', '.$first.', '.$middle.', '.
 4940: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4941:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4942:                                      ' desiredhome not specified'). 
 4943:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4944:              ' in domain '.$env{'request.role.domain'});
 4945:     my $uhome=&homeserver($uname,$udom,'true');
 4946: # ----------------------------------------------------------------- Create User
 4947:     if (($uhome eq 'no_host') && 
 4948: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4949:         my $unhome='';
 4950:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4951:             $unhome = $desiredhome;
 4952: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4953: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4954:         } else { # load balancing routine for determining $unhome
 4955:             my $loadm=10000000;
 4956: 	    my %servers = &get_servers($udom,'library');
 4957: 	    foreach my $tryserver (keys(%servers)) {
 4958: 		my $answer=reply('load',$tryserver);
 4959: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4960: 		    $loadm=$answer;
 4961: 		    $unhome=$tryserver;
 4962: 		}
 4963: 	    }
 4964:         }
 4965:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4966: 	    return 'error: unable to find a home server for '.$uname.
 4967:                    ' in domain '.$udom;
 4968:         }
 4969:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4970:                          &escape($upass),$unhome);
 4971: 	unless ($reply eq 'ok') {
 4972:             return 'error: '.$reply;
 4973:         }   
 4974:         $uhome=&homeserver($uname,$udom,'true');
 4975:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4976: 	    return 'error: unable verify users home machine.';
 4977:         }
 4978:     }   # End of creation of new user
 4979: # ---------------------------------------------------------------------- Add ID
 4980:     if ($uid) {
 4981:        $uid=~tr/A-Z/a-z/;
 4982:        my %uidhash=&idrget($udom,$uname);
 4983:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4984:          && (!$forceid)) {
 4985: 	  unless ($uid eq $uidhash{$uname}) {
 4986: 	      return 'error: user id "'.$uid.'" does not match '.
 4987:                   'current user id "'.$uidhash{$uname}.'".';
 4988:           }
 4989:        } else {
 4990: 	  &idput($udom,($uname => $uid));
 4991:        }
 4992:     }
 4993: # -------------------------------------------------------------- Add names, etc
 4994:     my @tmp=&get('environment',
 4995: 		   ['firstname','middlename','lastname','generation'],
 4996: 		   $udom,$uname);
 4997:     my %names;
 4998:     if ($tmp[0] =~ m/^error:.*/) { 
 4999:         %names=(); 
 5000:     } else {
 5001:         %names = @tmp;
 5002:     }
 5003: #
 5004: # Make sure to not trash student environment if instructor does not bother
 5005: # to supply name and email information
 5006: #
 5007:     if ($first)  { $names{'firstname'}  = $first; }
 5008:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5009:     if ($last)   { $names{'lastname'}   = $last; }
 5010:     if (defined($gene))   { $names{'generation'} = $gene; }
 5011:     if ($email) {
 5012:        $email=~s/[^\w\@\.\-\,]//gs;
 5013:        if ($email=~/\@/) { $names{'notification'} = $email;
 5014: 			   $names{'critnotification'} = $email;
 5015: 			   $names{'permanentemail'} = $email; }
 5016:     }
 5017:     my $reply = &put('environment', \%names, $udom,$uname);
 5018:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5019:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5020:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5021:              $umode.', '.$first.', '.$middle.', '.
 5022: 	     $last.', '.$gene.' by '.
 5023:              $env{'user.name'}.' at '.$env{'user.domain'});
 5024:     return 'ok';
 5025: }
 5026: 
 5027: # -------------------------------------------------------------- Modify student
 5028: 
 5029: sub modifystudent {
 5030:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5031:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5032:     if (!$cid) {
 5033: 	unless ($cid=$env{'request.course.id'}) {
 5034: 	    return 'not_in_class';
 5035: 	}
 5036:     }
 5037: # --------------------------------------------------------------- Make the user
 5038:     my $reply=&modifyuser
 5039: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5040:          $desiredhome,$email);
 5041:     unless ($reply eq 'ok') { return $reply; }
 5042:     # This will cause &modify_student_enrollment to get the uid from the
 5043:     # students environment
 5044:     $uid = undef if (!$forceid);
 5045:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5046: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5047:     return $reply;
 5048: }
 5049: 
 5050: sub modify_student_enrollment {
 5051:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5052:     my ($cdom,$cnum,$chome);
 5053:     if (!$cid) {
 5054: 	unless ($cid=$env{'request.course.id'}) {
 5055: 	    return 'not_in_class';
 5056: 	}
 5057: 	$cdom=$env{'course.'.$cid.'.domain'};
 5058: 	$cnum=$env{'course.'.$cid.'.num'};
 5059:     } else {
 5060: 	($cdom,$cnum)=split(/_/,$cid);
 5061:     }
 5062:     $chome=$env{'course.'.$cid.'.home'};
 5063:     if (!$chome) {
 5064: 	$chome=&homeserver($cnum,$cdom);
 5065:     }
 5066:     if (!$chome) { return 'unknown_course'; }
 5067:     # Make sure the user exists
 5068:     my $uhome=&homeserver($uname,$udom);
 5069:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5070: 	return 'error: no such user';
 5071:     }
 5072:     # Get student data if we were not given enough information
 5073:     if (!defined($first)  || $first  eq '' || 
 5074:         !defined($last)   || $last   eq '' || 
 5075:         !defined($uid)    || $uid    eq '' || 
 5076:         !defined($middle) || $middle eq '' || 
 5077:         !defined($gene)   || $gene   eq '') {
 5078:         # They did not supply us with enough data to enroll the student, so
 5079:         # we need to pick up more information.
 5080:         my %tmp = &get('environment',
 5081:                        ['firstname','middlename','lastname', 'generation','id']
 5082:                        ,$udom,$uname);
 5083: 
 5084:         #foreach my $key (keys(%tmp)) {
 5085:         #    &logthis("key $key = ".$tmp{$key});
 5086:         #}
 5087:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5088:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5089:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5090:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5091:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5092:     }
 5093:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5094:     my $reply=cput('classlist',
 5095: 		   {"$uname:$udom" => 
 5096: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5097: 		   $cdom,$cnum);
 5098:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5099: 	return 'error: '.$reply;
 5100:     } else {
 5101: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5102:     }
 5103:     # Add student role to user
 5104:     my $uurl='/'.$cid;
 5105:     $uurl=~s/\_/\//g;
 5106:     if ($usec) {
 5107: 	$uurl.='/'.$usec;
 5108:     }
 5109:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5110: }
 5111: 
 5112: sub format_name {
 5113:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5114:     my $name;
 5115:     if ($first ne 'lastname') {
 5116: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5117:     } else {
 5118: 	if ($lastname=~/\S/) {
 5119: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5120: 	    $name=~s/\s+,/,/;
 5121: 	} else {
 5122: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5123: 	}
 5124:     }
 5125:     $name=~s/^\s+//;
 5126:     $name=~s/\s+$//;
 5127:     $name=~s/\s+/ /g;
 5128:     return $name;
 5129: }
 5130: 
 5131: # ------------------------------------------------- Write to course preferences
 5132: 
 5133: sub writecoursepref {
 5134:     my ($courseid,%prefs)=@_;
 5135:     $courseid=~s/^\///;
 5136:     $courseid=~s/\_/\//g;
 5137:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5138:     my $chome=homeserver($cnum,$cdomain);
 5139:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5140: 	return 'error: no such course';
 5141:     }
 5142:     my $cstring='';
 5143:     foreach my $pref (keys(%prefs)) {
 5144: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5145:     }
 5146:     $cstring=~s/\&$//;
 5147:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5148: }
 5149: 
 5150: # ---------------------------------------------------------- Make/modify course
 5151: 
 5152: sub createcourse {
 5153:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5154:         $course_owner,$crstype)=@_;
 5155:     $url=&declutter($url);
 5156:     my $cid='';
 5157:     unless (&allowed('ccc',$udom)) {
 5158:         return 'refused';
 5159:     }
 5160: # ------------------------------------------------------------------- Create ID
 5161:    my $uname=int(1+rand(9)).
 5162:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5163:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5164:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5165: # ----------------------------------------------- Make sure that does not exist
 5166:    my $uhome=&homeserver($uname,$udom,'true');
 5167:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5168:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5169:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5170:        $uhome=&homeserver($uname,$udom,'true');       
 5171:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5172:            return 'error: unable to generate unique course-ID';
 5173:        } 
 5174:    }
 5175: # ------------------------------------------------ Check supplied server name
 5176:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5177:     if (! &is_library($course_server)) {
 5178:         return 'error:bad server name '.$course_server;
 5179:     }
 5180: # ------------------------------------------------------------- Make the course
 5181:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5182:                       $course_server);
 5183:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5184:     $uhome=&homeserver($uname,$udom,'true');
 5185:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5186: 	return 'error: no such course';
 5187:     }
 5188: # ----------------------------------------------------------------- Course made
 5189: # log existence
 5190:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5191:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5192:                   &escape($crstype),$uhome);
 5193:     &flushcourselogs();
 5194: # set toplevel url
 5195:     my $topurl=$url;
 5196:     unless ($nonstandard) {
 5197: # ------------------------------------------ For standard courses, make top url
 5198:         my $mapurl=&clutter($url);
 5199:         if ($mapurl eq '/res/') { $mapurl=''; }
 5200:         $env{'form.initmap'}=(<<ENDINITMAP);
 5201: <map>
 5202: <resource id="1" type="start"></resource>
 5203: <resource id="2" src="$mapurl"></resource>
 5204: <resource id="3" type="finish"></resource>
 5205: <link index="1" from="1" to="2"></link>
 5206: <link index="2" from="2" to="3"></link>
 5207: </map>
 5208: ENDINITMAP
 5209:         $topurl=&declutter(
 5210:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5211:                           );
 5212:     }
 5213: # ----------------------------------------------------------- Write preferences
 5214:     &writecoursepref($udom.'_'.$uname,
 5215:                      ('description' => $description,
 5216:                       'url'         => $topurl));
 5217:     return '/'.$udom.'/'.$uname;
 5218: }
 5219: 
 5220: sub is_course {
 5221:     my ($cdom,$cnum) = @_;
 5222:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5223: 				undef,'.');
 5224:     if (exists($courses{$cdom.'_'.$cnum})) {
 5225:         return 1;
 5226:     }
 5227:     return 0;
 5228: }
 5229: 
 5230: # ---------------------------------------------------------- Assign Custom Role
 5231: 
 5232: sub assigncustomrole {
 5233:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5234:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5235:                        $end,$start,$deleteflag);
 5236: }
 5237: 
 5238: # ----------------------------------------------------------------- Revoke Role
 5239: 
 5240: sub revokerole {
 5241:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5242:     my $now=time;
 5243:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5244: }
 5245: 
 5246: # ---------------------------------------------------------- Revoke Custom Role
 5247: 
 5248: sub revokecustomrole {
 5249:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5250:     my $now=time;
 5251:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5252:            $deleteflag);
 5253: }
 5254: 
 5255: # ------------------------------------------------------------ Disk usage
 5256: sub diskusage {
 5257:     my ($udom,$uname,$directoryRoot)=@_;
 5258:     $directoryRoot =~ s/\/$//;
 5259:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5260:     return $listing;
 5261: }
 5262: 
 5263: sub is_locked {
 5264:     my ($file_name, $domain, $user) = @_;
 5265:     my @check;
 5266:     my $is_locked;
 5267:     push @check, $file_name;
 5268:     my %locked = &get('file_permissions',\@check,
 5269: 		      $env{'user.domain'},$env{'user.name'});
 5270:     my ($tmp)=keys(%locked);
 5271:     if ($tmp=~/^error:/) { undef(%locked); }
 5272:     
 5273:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5274:         $is_locked = 'false';
 5275:         foreach my $entry (@{$locked{$file_name}}) {
 5276:            if (ref($entry) eq 'ARRAY') { 
 5277:                $is_locked = 'true';
 5278:                last;
 5279:            }
 5280:        }
 5281:     } else {
 5282:         $is_locked = 'false';
 5283:     }
 5284: }
 5285: 
 5286: sub declutter_portfile {
 5287:     my ($file) = @_;
 5288:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5289:     return $file;
 5290: }
 5291: 
 5292: # ------------------------------------------------------------- Mark as Read Only
 5293: 
 5294: sub mark_as_readonly {
 5295:     my ($domain,$user,$files,$what) = @_;
 5296:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5297:     my ($tmp)=keys(%current_permissions);
 5298:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5299:     foreach my $file (@{$files}) {
 5300: 	$file = &declutter_portfile($file);
 5301:         push(@{$current_permissions{$file}},$what);
 5302:     }
 5303:     &put('file_permissions',\%current_permissions,$domain,$user);
 5304:     return;
 5305: }
 5306: 
 5307: # ------------------------------------------------------------Save Selected Files
 5308: 
 5309: sub save_selected_files {
 5310:     my ($user, $path, @files) = @_;
 5311:     my $filename = $user."savedfiles";
 5312:     my @other_files = &files_not_in_path($user, $path);
 5313:     open (OUT, '>'.$tmpdir.$filename);
 5314:     foreach my $file (@files) {
 5315:         print (OUT $env{'form.currentpath'}.$file."\n");
 5316:     }
 5317:     foreach my $file (@other_files) {
 5318:         print (OUT $file."\n");
 5319:     }
 5320:     close (OUT);
 5321:     return 'ok';
 5322: }
 5323: 
 5324: sub clear_selected_files {
 5325:     my ($user) = @_;
 5326:     my $filename = $user."savedfiles";
 5327:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5328:     print (OUT undef);
 5329:     close (OUT);
 5330:     return ("ok");    
 5331: }
 5332: 
 5333: sub files_in_path {
 5334:     my ($user, $path) = @_;
 5335:     my $filename = $user."savedfiles";
 5336:     my %return_files;
 5337:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5338:     while (my $line_in = <IN>) {
 5339:         chomp ($line_in);
 5340:         my @paths_and_file = split (m!/!, $line_in);
 5341:         my $file_part = pop (@paths_and_file);
 5342:         my $path_part = join ('/', @paths_and_file);
 5343:         $path_part.='/';
 5344:         my $path_and_file = $path_part.$file_part;
 5345:         if ($path_part eq $path) {
 5346:             $return_files{$file_part}= 'selected';
 5347:         }
 5348:     }
 5349:     close (IN);
 5350:     return (\%return_files);
 5351: }
 5352: 
 5353: # called in portfolio select mode, to show files selected NOT in current directory
 5354: sub files_not_in_path {
 5355:     my ($user, $path) = @_;
 5356:     my $filename = $user."savedfiles";
 5357:     my @return_files;
 5358:     my $path_part;
 5359:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5360:     while (my $line = <IN>) {
 5361:         #ok, I know it's clunky, but I want it to work
 5362:         my @paths_and_file = split(m|/|, $line);
 5363:         my $file_part = pop(@paths_and_file);
 5364:         chomp($file_part);
 5365:         my $path_part = join('/', @paths_and_file);
 5366:         $path_part .= '/';
 5367:         my $path_and_file = $path_part.$file_part;
 5368:         if ($path_part ne $path) {
 5369:             push(@return_files, ($path_and_file));
 5370:         }
 5371:     }
 5372:     close(OUT);
 5373:     return (@return_files);
 5374: }
 5375: 
 5376: #----------------------------------------------Get portfolio file permissions
 5377: 
 5378: sub get_portfile_permissions {
 5379:     my ($domain,$user) = @_;
 5380:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5381:     my ($tmp)=keys(%current_permissions);
 5382:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5383:     return \%current_permissions;
 5384: }
 5385: 
 5386: #---------------------------------------------Get portfolio file access controls
 5387: 
 5388: sub get_access_controls {
 5389:     my ($current_permissions,$group,$file) = @_;
 5390:     my %access;
 5391:     my $real_file = $file;
 5392:     $file =~ s/\.meta$//;
 5393:     if (defined($file)) {
 5394:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5395:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5396:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5397:             }
 5398:         }
 5399:     } else {
 5400:         foreach my $key (keys(%{$current_permissions})) {
 5401:             if ($key =~ /\0accesscontrol$/) {
 5402:                 if (defined($group)) {
 5403:                     if ($key !~ m-^\Q$group\E/-) {
 5404:                         next;
 5405:                     }
 5406:                 }
 5407:                 my ($fullpath) = split(/\0/,$key);
 5408:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5409:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5410:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5411:                     }
 5412:                 }
 5413:             }
 5414:         }
 5415:     }
 5416:     return %access;
 5417: }
 5418: 
 5419: sub modify_access_controls {
 5420:     my ($file_name,$changes,$domain,$user)=@_;
 5421:     my ($outcome,$deloutcome);
 5422:     my %store_permissions;
 5423:     my %new_values;
 5424:     my %new_control;
 5425:     my %translation;
 5426:     my @deletions = ();
 5427:     my $now = time;
 5428:     if (exists($$changes{'activate'})) {
 5429:         if (ref($$changes{'activate'}) eq 'HASH') {
 5430:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5431:             my $numnew = scalar(@newitems);
 5432:             for (my $i=0; $i<$numnew; $i++) {
 5433:                 my $newkey = $newitems[$i];
 5434:                 my $newid = &Apache::loncommon::get_cgi_id();
 5435:                 if ($newkey =~ /^\d+:/) { 
 5436:                     $newkey =~ s/^(\d+)/$newid/;
 5437:                     $translation{$1} = $newid;
 5438:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5439:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5440:                     $translation{$1} = $newid;
 5441:                 }
 5442:                 $new_values{$file_name."\0".$newkey} = 
 5443:                                           $$changes{'activate'}{$newitems[$i]};
 5444:                 $new_control{$newkey} = $now;
 5445:             }
 5446:         }
 5447:     }
 5448:     my %todelete;
 5449:     my %changed_items;
 5450:     foreach my $action ('delete','update') {
 5451:         if (exists($$changes{$action})) {
 5452:             if (ref($$changes{$action}) eq 'HASH') {
 5453:                 foreach my $key (keys(%{$$changes{$action}})) {
 5454:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5455:                     if ($action eq 'delete') { 
 5456:                         $todelete{$itemnum} = 1;
 5457:                     } else {
 5458:                         $changed_items{$itemnum} = $key;
 5459:                     }
 5460:                 }
 5461:             }
 5462:         }
 5463:     }
 5464:     # get lock on access controls for file.
 5465:     my $lockhash = {
 5466:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5467:                                                        ':'.$env{'user.domain'},
 5468:                    }; 
 5469:     my $tries = 0;
 5470:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5471:    
 5472:     while (($gotlock ne 'ok') && $tries <3) {
 5473:         $tries ++;
 5474:         sleep 1;
 5475:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5476:     }
 5477:     if ($gotlock eq 'ok') {
 5478:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5479:         my ($tmp)=keys(%curr_permissions);
 5480:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5481:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5482:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5483:             if (ref($curr_controls) eq 'HASH') {
 5484:                 foreach my $control_item (keys(%{$curr_controls})) {
 5485:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5486:                     if (defined($todelete{$itemnum})) {
 5487:                         push(@deletions,$file_name."\0".$control_item);
 5488:                     } else {
 5489:                         if (defined($changed_items{$itemnum})) {
 5490:                             $new_control{$changed_items{$itemnum}} = $now;
 5491:                             push(@deletions,$file_name."\0".$control_item);
 5492:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5493:                         } else {
 5494:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5495:                         }
 5496:                     }
 5497:                 }
 5498:             }
 5499:         }
 5500:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5501:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5502:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5503:         #  remove lock
 5504:         my @del_lock = ($file_name."\0".'locked_access_records');
 5505:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5506:         my ($file,$group);
 5507:         if (&is_course($domain,$user)) {
 5508:             ($group,$file) = split(/\//,$file_name,2);
 5509:         } else {
 5510:             $file = $file_name;
 5511:         }
 5512:         my $sqlresult =
 5513:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5514:                                     $group);
 5515:     } else {
 5516:         $outcome = "error: could not obtain lockfile\n";  
 5517:     }
 5518:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5519: }
 5520: 
 5521: sub make_public_indefinitely {
 5522:     my ($requrl) = @_;
 5523:     my $now = time;
 5524:     my $action = 'activate';
 5525:     my $aclnum = 0;
 5526:     if (&is_portfolio_url($requrl)) {
 5527:         my (undef,$udom,$unum,$file_name,$group) =
 5528:             &parse_portfolio_url($requrl);
 5529:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5530:         my %access_controls = &get_access_controls($current_perms,
 5531:                                                    $group,$file_name);
 5532:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5533:             my ($num,$scope,$end,$start) = 
 5534:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5535:             if ($scope eq 'public') {
 5536:                 if ($start <= $now && $end == 0) {
 5537:                     $action = 'none';
 5538:                 } else {
 5539:                     $action = 'update';
 5540:                     $aclnum = $num;
 5541:                 }
 5542:                 last;
 5543:             }
 5544:         }
 5545:         if ($action eq 'none') {
 5546:              return 'ok';
 5547:         } else {
 5548:             my %changes;
 5549:             my $newend = 0;
 5550:             my $newstart = $now;
 5551:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5552:             $changes{$action}{$newkey} = {
 5553:                 type => 'public',
 5554:                 time => {
 5555:                     start => $newstart,
 5556:                     end   => $newend,
 5557:                 },
 5558:             };
 5559:             my ($outcome,$deloutcome,$new_values,$translation) =
 5560:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5561:             return $outcome;
 5562:         }
 5563:     } else {
 5564:         return 'invalid';
 5565:     }
 5566: }
 5567: 
 5568: #------------------------------------------------------Get Marked as Read Only
 5569: 
 5570: sub get_marked_as_readonly {
 5571:     my ($domain,$user,$what,$group) = @_;
 5572:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5573:     my @readonly_files;
 5574:     my $cmp1=$what;
 5575:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5576:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5577:         if (defined($group)) {
 5578:             if ($file_name !~ m-^\Q$group\E/-) {
 5579:                 next;
 5580:             }
 5581:         }
 5582:         if (ref($value) eq "ARRAY"){
 5583:             foreach my $stored_what (@{$value}) {
 5584:                 my $cmp2=$stored_what;
 5585:                 if (ref($stored_what) eq 'ARRAY') {
 5586:                     $cmp2=join('',@{$stored_what});
 5587:                 }
 5588:                 if ($cmp1 eq $cmp2) {
 5589:                     push(@readonly_files, $file_name);
 5590:                     last;
 5591:                 } elsif (!defined($what)) {
 5592:                     push(@readonly_files, $file_name);
 5593:                     last;
 5594:                 }
 5595:             }
 5596:         }
 5597:     }
 5598:     return @readonly_files;
 5599: }
 5600: #-----------------------------------------------------------Get Marked as Read Only Hash
 5601: 
 5602: sub get_marked_as_readonly_hash {
 5603:     my ($current_permissions,$group,$what) = @_;
 5604:     my %readonly_files;
 5605:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5606:         if (defined($group)) {
 5607:             if ($file_name !~ m-^\Q$group\E/-) {
 5608:                 next;
 5609:             }
 5610:         }
 5611:         if (ref($value) eq "ARRAY"){
 5612:             foreach my $stored_what (@{$value}) {
 5613:                 if (ref($stored_what) eq 'ARRAY') {
 5614:                     foreach my $lock_descriptor(@{$stored_what}) {
 5615:                         if ($lock_descriptor eq 'graded') {
 5616:                             $readonly_files{$file_name} = 'graded';
 5617:                         } elsif ($lock_descriptor eq 'handback') {
 5618:                             $readonly_files{$file_name} = 'handback';
 5619:                         } else {
 5620:                             if (!exists($readonly_files{$file_name})) {
 5621:                                 $readonly_files{$file_name} = 'locked';
 5622:                             }
 5623:                         }
 5624:                     }
 5625:                 } 
 5626:             }
 5627:         } 
 5628:     }
 5629:     return %readonly_files;
 5630: }
 5631: # ------------------------------------------------------------ Unmark as Read Only
 5632: 
 5633: sub unmark_as_readonly {
 5634:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5635:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5636:     my ($domain,$user,$what,$file_name,$group) = @_;
 5637:     $file_name = &declutter_portfile($file_name);
 5638:     my $symb_crs = $what;
 5639:     if (ref($what)) { $symb_crs=join('',@$what); }
 5640:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5641:     my ($tmp)=keys(%current_permissions);
 5642:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5643:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5644:     foreach my $file (@readonly_files) {
 5645: 	my $clean_file = &declutter_portfile($file);
 5646: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5647: 	my $current_locks = $current_permissions{$file};
 5648:         my @new_locks;
 5649:         my @del_keys;
 5650:         if (ref($current_locks) eq "ARRAY"){
 5651:             foreach my $locker (@{$current_locks}) {
 5652:                 my $compare=$locker;
 5653:                 if (ref($locker) eq 'ARRAY') {
 5654:                     $compare=join('',@{$locker});
 5655:                     if ($compare ne $symb_crs) {
 5656:                         push(@new_locks, $locker);
 5657:                     }
 5658:                 }
 5659:             }
 5660:             if (scalar(@new_locks) > 0) {
 5661:                 $current_permissions{$file} = \@new_locks;
 5662:             } else {
 5663:                 push(@del_keys, $file);
 5664:                 &del('file_permissions',\@del_keys, $domain, $user);
 5665:                 delete($current_permissions{$file});
 5666:             }
 5667:         }
 5668:     }
 5669:     &put('file_permissions',\%current_permissions,$domain,$user);
 5670:     return;
 5671: }
 5672: 
 5673: # ------------------------------------------------------------ Directory lister
 5674: 
 5675: sub dirlist {
 5676:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5677: 
 5678:     $uri=~s/^\///;
 5679:     $uri=~s/\/$//;
 5680:     my ($udom, $uname);
 5681:     (undef,$udom,$uname)=split(/\//,$uri);
 5682:     if(defined($userdomain)) {
 5683:         $udom = $userdomain;
 5684:     }
 5685:     if(defined($username)) {
 5686:         $uname = $username;
 5687:     }
 5688: 
 5689:     my $dirRoot = $perlvar{'lonDocRoot'};
 5690:     if(defined($alternateDirectoryRoot)) {
 5691:         $dirRoot = $alternateDirectoryRoot;
 5692:         $dirRoot =~ s/\/$//;
 5693:     }
 5694: 
 5695:     if($udom) {
 5696:         if($uname) {
 5697:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5698: 				 &homeserver($uname,$udom));
 5699:             my @listing_results;
 5700:             if ($listing eq 'unknown_cmd') {
 5701:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5702: 				  &homeserver($uname,$udom));
 5703:                 @listing_results = split(/:/,$listing);
 5704:             } else {
 5705:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5706:             }
 5707:             return @listing_results;
 5708:         } elsif(!defined($alternateDirectoryRoot)) {
 5709:             my %allusers;
 5710: 	    my %servers = &get_servers($udom,'library');
 5711: 	    foreach my $tryserver (keys(%servers)) {
 5712: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5713: 				     $udom, $tryserver);
 5714: 		my @listing_results;
 5715: 		if ($listing eq 'unknown_cmd') {
 5716: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5717: 				      $udom, $tryserver);
 5718: 		    @listing_results = split(/:/,$listing);
 5719: 		} else {
 5720: 		    @listing_results =
 5721: 			map { &unescape($_); } split(/:/,$listing);
 5722: 		}
 5723: 		if ($listing_results[0] ne 'no_such_dir' && 
 5724: 		    $listing_results[0] ne 'empty'       &&
 5725: 		    $listing_results[0] ne 'con_lost') {
 5726: 		    foreach my $line (@listing_results) {
 5727: 			my ($entry) = split(/&/,$line,2);
 5728: 			$allusers{$entry} = 1;
 5729: 		    }
 5730: 		}
 5731:             }
 5732:             my $alluserstr='';
 5733:             foreach my $user (sort(keys(%allusers))) {
 5734:                 $alluserstr.=$user.'&user:';
 5735:             }
 5736:             $alluserstr=~s/:$//;
 5737:             return split(/:/,$alluserstr);
 5738:         } else {
 5739:             return ('missing user name');
 5740:         }
 5741:     } elsif(!defined($alternateDirectoryRoot)) {
 5742:         my @all_domains = sort(&all_domains());
 5743:          foreach my $domain (@all_domains) {
 5744:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5745:          }
 5746:          return @all_domains;
 5747:      } else {
 5748:         return ('missing domain');
 5749:     }
 5750: }
 5751: 
 5752: # --------------------------------------------- GetFileTimestamp
 5753: # This function utilizes dirlist and returns the date stamp for
 5754: # when it was last modified.  It will also return an error of -1
 5755: # if an error occurs
 5756: 
 5757: ##
 5758: ## FIXME: This subroutine assumes its caller knows something about the
 5759: ## directory structure of the home server for the student ($root).
 5760: ## Not a good assumption to make.  Since this is for looking up files
 5761: ## in user directories, the full path should be constructed by lond, not
 5762: ## whatever machine we request data from.
 5763: ##
 5764: sub GetFileTimestamp {
 5765:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5766:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5767:     $studentName   = &LONCAPA::clean_username($studentName);
 5768:     my $subdir=$studentName.'__';
 5769:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5770:     my $proname="$studentDomain/$subdir/$studentName";
 5771:     $proname .= '/'.$filename;
 5772:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5773:                                               $studentName, $root);
 5774:     my @stats = split('&', $fileStat);
 5775:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5776:         # @stats contains first the filename, then the stat output
 5777:         return $stats[10]; # so this is 10 instead of 9.
 5778:     } else {
 5779:         return -1;
 5780:     }
 5781: }
 5782: 
 5783: sub stat_file {
 5784:     my ($uri) = @_;
 5785:     $uri = &clutter_with_no_wrapper($uri);
 5786: 
 5787:     my ($udom,$uname,$file,$dir);
 5788:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5789: 	($udom,$uname,$file) =
 5790: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5791: 	$file = 'userfiles/'.$file;
 5792: 	$dir = &propath($udom,$uname);
 5793:     }
 5794:     if ($uri =~ m-^/res/-) {
 5795: 	($udom,$uname) = 
 5796: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5797: 	$file = $uri;
 5798:     }
 5799: 
 5800:     if (!$udom || !$uname || !$file) {
 5801: 	# unable to handle the uri
 5802: 	return ();
 5803:     }
 5804: 
 5805:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5806:     my @stats = split('&', $result);
 5807:     
 5808:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5809: 	shift(@stats); #filename is first
 5810: 	return @stats;
 5811:     }
 5812:     return ();
 5813: }
 5814: 
 5815: # -------------------------------------------------------- Value of a Condition
 5816: 
 5817: # gets the value of a specific preevaluated condition
 5818: #    stored in the string  $env{user.state.<cid>}
 5819: # or looks up a condition reference in the bighash and if if hasn't
 5820: # already been evaluated recurses into docondval to get the value of
 5821: # the condition, then memoizing it to 
 5822: #   $env{user.state.<cid>.<condition>}
 5823: sub directcondval {
 5824:     my $number=shift;
 5825:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5826: 	&Apache::lonuserstate::evalstate();
 5827:     }
 5828:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5829: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5830:     } elsif ($number =~ /^_/) {
 5831: 	my $sub_condition;
 5832: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5833: 		&GDBM_READER(),0640)) {
 5834: 	    $sub_condition=$bighash{'conditions'.$number};
 5835: 	    untie(%bighash);
 5836: 	}
 5837: 	my $value = &docondval($sub_condition);
 5838: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5839: 	return $value;
 5840:     }
 5841:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5842:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5843:     } else {
 5844:        return 2;
 5845:     }
 5846: }
 5847: 
 5848: # get the collection of conditions for this resource
 5849: sub condval {
 5850:     my $condidx=shift;
 5851:     my $allpathcond='';
 5852:     foreach my $cond (split(/\|/,$condidx)) {
 5853: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5854: 	    $allpathcond.=
 5855: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5856: 	}
 5857:     }
 5858:     $allpathcond=~s/\|$//;
 5859:     return &docondval($allpathcond);
 5860: }
 5861: 
 5862: #evaluates an expression of conditions
 5863: sub docondval {
 5864:     my ($allpathcond) = @_;
 5865:     my $result=0;
 5866:     if ($env{'request.course.id'}
 5867: 	&& defined($allpathcond)) {
 5868: 	my $operand='|';
 5869: 	my @stack;
 5870: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5871: 	    if ($chunk eq '(') {
 5872: 		push @stack,($operand,$result);
 5873: 	    } elsif ($chunk eq ')') {
 5874: 		my $before=pop @stack;
 5875: 		if (pop @stack eq '&') {
 5876: 		    $result=$result>$before?$before:$result;
 5877: 		} else {
 5878: 		    $result=$result>$before?$result:$before;
 5879: 		}
 5880: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5881: 		$operand=$chunk;
 5882: 	    } else {
 5883: 		my $new=directcondval($chunk);
 5884: 		if ($operand eq '&') {
 5885: 		    $result=$result>$new?$new:$result;
 5886: 		} else {
 5887: 		    $result=$result>$new?$result:$new;
 5888: 		}
 5889: 	    }
 5890: 	}
 5891:     }
 5892:     return $result;
 5893: }
 5894: 
 5895: # ---------------------------------------------------- Devalidate courseresdata
 5896: 
 5897: sub devalidatecourseresdata {
 5898:     my ($coursenum,$coursedomain)=@_;
 5899:     my $hashid=$coursenum.':'.$coursedomain;
 5900:     &devalidate_cache_new('courseres',$hashid);
 5901: }
 5902: 
 5903: 
 5904: # --------------------------------------------------- Course Resourcedata Query
 5905: 
 5906: sub get_courseresdata {
 5907:     my ($coursenum,$coursedomain)=@_;
 5908:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5909:     my $hashid=$coursenum.':'.$coursedomain;
 5910:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5911:     my %dumpreply;
 5912:     unless (defined($cached)) {
 5913: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5914: 	$result=\%dumpreply;
 5915: 	my ($tmp) = keys(%dumpreply);
 5916: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5917: 	    &do_cache_new('courseres',$hashid,$result,600);
 5918: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5919: 	    return $tmp;
 5920: 	} elsif ($tmp =~ /^(error)/) {
 5921: 	    $result=undef;
 5922: 	    &do_cache_new('courseres',$hashid,$result,600);
 5923: 	}
 5924:     }
 5925:     return $result;
 5926: }
 5927: 
 5928: sub devalidateuserresdata {
 5929:     my ($uname,$udom)=@_;
 5930:     my $hashid="$udom:$uname";
 5931:     &devalidate_cache_new('userres',$hashid);
 5932: }
 5933: 
 5934: sub get_userresdata {
 5935:     my ($uname,$udom)=@_;
 5936:     #most student don\'t have any data set, check if there is some data
 5937:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5938: 
 5939:     my $hashid="$udom:$uname";
 5940:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5941:     if (!defined($cached)) {
 5942: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5943: 	$result=\%resourcedata;
 5944: 	&do_cache_new('userres',$hashid,$result,600);
 5945:     }
 5946:     my ($tmp)=keys(%$result);
 5947:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5948: 	return $result;
 5949:     }
 5950:     #error 2 occurs when the .db doesn't exist
 5951:     if ($tmp!~/error: 2 /) {
 5952: 	&logthis("<font color=\"blue\">WARNING:".
 5953: 		 " Trying to get resource data for ".
 5954: 		 $uname." at ".$udom.": ".
 5955: 		 $tmp."</font>");
 5956:     } elsif ($tmp=~/error: 2 /) {
 5957: 	#&EXT_cache_set($udom,$uname);
 5958: 	&do_cache_new('userres',$hashid,undef,600);
 5959: 	undef($tmp); # not really an error so don't send it back
 5960:     }
 5961:     return $tmp;
 5962: }
 5963: 
 5964: sub resdata {
 5965:     my ($name,$domain,$type,@which)=@_;
 5966:     my $result;
 5967:     if ($type eq 'course') {
 5968: 	$result=&get_courseresdata($name,$domain);
 5969:     } elsif ($type eq 'user') {
 5970: 	$result=&get_userresdata($name,$domain);
 5971:     }
 5972:     if (!ref($result)) { return $result; }    
 5973:     foreach my $item (@which) {
 5974: 	if (defined($result->{$item})) {
 5975: 	    return $result->{$item};
 5976: 	}
 5977:     }
 5978:     return undef;
 5979: }
 5980: 
 5981: #
 5982: # EXT resource caching routines
 5983: #
 5984: 
 5985: sub clear_EXT_cache_status {
 5986:     &delenv('cache.EXT.');
 5987: }
 5988: 
 5989: sub EXT_cache_status {
 5990:     my ($target_domain,$target_user) = @_;
 5991:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5992:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5993:         # We know already the user has no data
 5994:         return 1;
 5995:     } else {
 5996:         return 0;
 5997:     }
 5998: }
 5999: 
 6000: sub EXT_cache_set {
 6001:     my ($target_domain,$target_user) = @_;
 6002:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6003:     #&appenv($cachename => time);
 6004: }
 6005: 
 6006: # --------------------------------------------------------- Value of a Variable
 6007: sub EXT {
 6008: 
 6009:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6010:     unless ($varname) { return ''; }
 6011:     #get real user name/domain, courseid and symb
 6012:     my $courseid;
 6013:     my $publicuser;
 6014:     if ($symbparm) {
 6015: 	$symbparm=&get_symb_from_alias($symbparm);
 6016:     }
 6017:     if (!($uname && $udom)) {
 6018:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6019:       if (!$symbparm) {	$symbparm=$cursymb; }
 6020:     } else {
 6021: 	$courseid=$env{'request.course.id'};
 6022:     }
 6023:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6024:     my $rest;
 6025:     if (defined($therest[0])) {
 6026:        $rest=join('.',@therest);
 6027:     } else {
 6028:        $rest='';
 6029:     }
 6030: 
 6031:     my $qualifierrest=$qualifier;
 6032:     if ($rest) { $qualifierrest.='.'.$rest; }
 6033:     my $spacequalifierrest=$space;
 6034:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6035:     if ($realm eq 'user') {
 6036: # --------------------------------------------------------------- user.resource
 6037: 	if ($space eq 'resource') {
 6038: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6039: 		  || defined($Apache::lonhomework::parsing_a_task))
 6040: 		 &&
 6041: 		 ($symbparm eq &symbread()) ) {	
 6042: 		# if we are in the middle of processing the resource the
 6043: 		# get the value we are planning on committing
 6044:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6045:                     return $Apache::lonhomework::results{$qualifierrest};
 6046:                 } else {
 6047:                     return $Apache::lonhomework::history{$qualifierrest};
 6048:                 }
 6049: 	    } else {
 6050: 		my %restored;
 6051: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6052: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6053: 		} else {
 6054: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6055: 		}
 6056: 		return $restored{$qualifierrest};
 6057: 	    }
 6058: # ----------------------------------------------------------------- user.access
 6059:         } elsif ($space eq 'access') {
 6060: 	    # FIXME - not supporting calls for a specific user
 6061:             return &allowed($qualifier,$rest);
 6062: # ------------------------------------------ user.preferences, user.environment
 6063:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6064: 	    if (($uname eq $env{'user.name'}) &&
 6065: 		($udom eq $env{'user.domain'})) {
 6066: 		return $env{join('.',('environment',$qualifierrest))};
 6067: 	    } else {
 6068: 		my %returnhash;
 6069: 		if (!$publicuser) {
 6070: 		    %returnhash=&userenvironment($udom,$uname,
 6071: 						 $qualifierrest);
 6072: 		}
 6073: 		return $returnhash{$qualifierrest};
 6074: 	    }
 6075: # ----------------------------------------------------------------- user.course
 6076:         } elsif ($space eq 'course') {
 6077: 	    # FIXME - not supporting calls for a specific user
 6078:             return $env{join('.',('request.course',$qualifier))};
 6079: # ------------------------------------------------------------------- user.role
 6080:         } elsif ($space eq 'role') {
 6081: 	    # FIXME - not supporting calls for a specific user
 6082:             my ($role,$where)=split(/\./,$env{'request.role'});
 6083:             if ($qualifier eq 'value') {
 6084: 		return $role;
 6085:             } elsif ($qualifier eq 'extent') {
 6086:                 return $where;
 6087:             }
 6088: # ----------------------------------------------------------------- user.domain
 6089:         } elsif ($space eq 'domain') {
 6090:             return $udom;
 6091: # ------------------------------------------------------------------- user.name
 6092:         } elsif ($space eq 'name') {
 6093:             return $uname;
 6094: # ---------------------------------------------------- Any other user namespace
 6095:         } else {
 6096: 	    my %reply;
 6097: 	    if (!$publicuser) {
 6098: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6099: 	    }
 6100: 	    return $reply{$qualifierrest};
 6101:         }
 6102:     } elsif ($realm eq 'query') {
 6103: # ---------------------------------------------- pull stuff out of query string
 6104:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6105: 						[$spacequalifierrest]);
 6106: 	return $env{'form.'.$spacequalifierrest}; 
 6107:    } elsif ($realm eq 'request') {
 6108: # ------------------------------------------------------------- request.browser
 6109:         if ($space eq 'browser') {
 6110: 	    if ($qualifier eq 'textremote') {
 6111: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6112: 		    return 1;
 6113: 		} else {
 6114: 		    return 0;
 6115: 		}
 6116: 	    } else {
 6117: 		return $env{'browser.'.$qualifier};
 6118: 	    }
 6119: # ------------------------------------------------------------ request.filename
 6120:         } else {
 6121:             return $env{'request.'.$spacequalifierrest};
 6122:         }
 6123:     } elsif ($realm eq 'course') {
 6124: # ---------------------------------------------------------- course.description
 6125:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6126:     } elsif ($realm eq 'resource') {
 6127: 
 6128: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6129: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6130: 	}
 6131: 
 6132: 	if ($space eq 'title') {
 6133: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6134: 	    return &gettitle($symbparm);
 6135: 	}
 6136: 	
 6137: 	if ($space eq 'map') {
 6138: 	    my ($map) = &decode_symb($symbparm);
 6139: 	    return &symbread($map);
 6140: 	}
 6141: 
 6142: 	my ($section, $group, @groups);
 6143: 	my ($courselevelm,$courselevel);
 6144: 	if ($symbparm && defined($courseid) && 
 6145: 	    $courseid eq $env{'request.course.id'}) {
 6146: 
 6147: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6148: 
 6149: # ----------------------------------------------------- Cascading lookup scheme
 6150: 	    my $symbp=$symbparm;
 6151: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6152: 
 6153: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6154: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6155: 
 6156: 	    if (($env{'user.name'} eq $uname) &&
 6157: 		($env{'user.domain'} eq $udom)) {
 6158: 		$section=$env{'request.course.sec'};
 6159:                 @groups = split(/:/,$env{'request.course.groups'});  
 6160:                 @groups=&sort_course_groups($courseid,@groups); 
 6161: 	    } else {
 6162: 		if (! defined($usection)) {
 6163: 		    $section=&getsection($udom,$uname,$courseid);
 6164: 		} else {
 6165: 		    $section = $usection;
 6166: 		}
 6167:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6168: 	    }
 6169: 
 6170: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6171: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6172: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6173: 
 6174: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6175: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6176: 	    $courselevelm=$courseid.'.'.$mapparm;
 6177: 
 6178: # ----------------------------------------------------------- first, check user
 6179: 
 6180: 	    my $userreply=&resdata($uname,$udom,'user',
 6181: 				       ($courselevelr,$courselevelm,
 6182: 					$courselevel));
 6183: 	    if (defined($userreply)) { return $userreply; }
 6184: 
 6185: # ------------------------------------------------ second, check some of course
 6186:             my $coursereply;
 6187:             if (@groups > 0) {
 6188:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6189:                                        $mapparm,$spacequalifierrest);
 6190:                 if (defined($coursereply)) { return $coursereply; }
 6191:             }
 6192: 
 6193: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6194: 				     $env{'course.'.$courseid.'.domain'},
 6195: 				     'course',
 6196: 				     ($seclevelr,$seclevelm,$seclevel,
 6197: 				      $courselevelr));
 6198: 	    if (defined($coursereply)) { return $coursereply; }
 6199: 
 6200: # ------------------------------------------------------ third, check map parms
 6201: 	    my %parmhash=();
 6202: 	    my $thisparm='';
 6203: 	    if (tie(%parmhash,'GDBM_File',
 6204: 		    $env{'request.course.fn'}.'_parms.db',
 6205: 		    &GDBM_READER(),0640)) {
 6206: 		$thisparm=$parmhash{$symbparm};
 6207: 		untie(%parmhash);
 6208: 	    }
 6209: 	    if ($thisparm) { return $thisparm; }
 6210: 	}
 6211: # ------------------------------------------ fourth, look in resource metadata
 6212: 
 6213: 	$spacequalifierrest=~s/\./\_/;
 6214: 	my $filename;
 6215: 	if (!$symbparm) { $symbparm=&symbread(); }
 6216: 	if ($symbparm) {
 6217: 	    $filename=(&decode_symb($symbparm))[2];
 6218: 	} else {
 6219: 	    $filename=$env{'request.filename'};
 6220: 	}
 6221: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6222: 	if (defined($metadata)) { return $metadata; }
 6223: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6224: 	if (defined($metadata)) { return $metadata; }
 6225: 
 6226: # ---------------------------------------------- fourth, look in rest pf course
 6227: 	if ($symbparm && defined($courseid) && 
 6228: 	    $courseid eq $env{'request.course.id'}) {
 6229: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6230: 				     $env{'course.'.$courseid.'.domain'},
 6231: 				     'course',
 6232: 				     ($courselevelm,$courselevel));
 6233: 	    if (defined($coursereply)) { return $coursereply; }
 6234: 	}
 6235: # ------------------------------------------------------------------ Cascade up
 6236: 	unless ($space eq '0') {
 6237: 	    my @parts=split(/_/,$space);
 6238: 	    my $id=pop(@parts);
 6239: 	    my $part=join('_',@parts);
 6240: 	    if ($part eq '') { $part='0'; }
 6241: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6242: 				 $symbparm,$udom,$uname,$section,1);
 6243: 	    if (defined($partgeneral)) { return $partgeneral; }
 6244: 	}
 6245: 	if ($recurse) { return undef; }
 6246: 	my $pack_def=&packages_tab_default($filename,$varname);
 6247: 	if (defined($pack_def)) { return $pack_def; }
 6248: 
 6249: # ---------------------------------------------------- Any other user namespace
 6250:     } elsif ($realm eq 'environment') {
 6251: # ----------------------------------------------------------------- environment
 6252: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6253: 	    return $env{'environment.'.$spacequalifierrest};
 6254: 	} else {
 6255: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6256: 		return '';
 6257: 	    }
 6258: 	    my %returnhash=&userenvironment($udom,$uname,
 6259: 					    $spacequalifierrest);
 6260: 	    return $returnhash{$spacequalifierrest};
 6261: 	}
 6262:     } elsif ($realm eq 'system') {
 6263: # ----------------------------------------------------------------- system.time
 6264: 	if ($space eq 'time') {
 6265: 	    return time;
 6266:         }
 6267:     } elsif ($realm eq 'server') {
 6268: # ----------------------------------------------------------------- system.time
 6269: 	if ($space eq 'name') {
 6270: 	    return $ENV{'SERVER_NAME'};
 6271:         }
 6272:     }
 6273:     return '';
 6274: }
 6275: 
 6276: sub check_group_parms {
 6277:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6278:     my @groupitems = ();
 6279:     my $resultitem;
 6280:     my @levels = ($symbparm,$mapparm,$what);
 6281:     foreach my $group (@{$groups}) {
 6282:         foreach my $level (@levels) {
 6283:              my $item = $courseid.'.['.$group.'].'.$level;
 6284:              push(@groupitems,$item);
 6285:         }
 6286:     }
 6287:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6288:                             $env{'course.'.$courseid.'.domain'},
 6289:                                      'course',@groupitems);
 6290:     return $coursereply;
 6291: }
 6292: 
 6293: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6294:     my ($courseid,@groups) = @_;
 6295:     @groups = sort(@groups);
 6296:     return @groups;
 6297: }
 6298: 
 6299: sub packages_tab_default {
 6300:     my ($uri,$varname)=@_;
 6301:     my (undef,$part,$name)=split(/\./,$varname);
 6302: 
 6303:     my (@extension,@specifics,$do_default);
 6304:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6305: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6306: 	if ($pack_type eq 'default') {
 6307: 	    $do_default=1;
 6308: 	} elsif ($pack_type eq 'extension') {
 6309: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6310: 	} elsif ($pack_part eq $part) {
 6311: 	    # only look at packages defaults for packages that this id is
 6312: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6313: 	}
 6314:     }
 6315:     # first look for a package that matches the requested part id
 6316:     foreach my $package (@specifics) {
 6317: 	my (undef,$pack_type,$pack_part)=@{$package};
 6318: 	next if ($pack_part ne $part);
 6319: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6320: 	    return $packagetab{"$pack_type&$name&default"};
 6321: 	}
 6322:     }
 6323:     # look for any possible matching non extension_ package
 6324:     foreach my $package (@specifics) {
 6325: 	my (undef,$pack_type,$pack_part)=@{$package};
 6326: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6327: 	    return $packagetab{"$pack_type&$name&default"};
 6328: 	}
 6329: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6330: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6331: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6332: 	}
 6333:     }
 6334:     # look for any posible extension_ match
 6335:     foreach my $package (@extension) {
 6336: 	my ($package,$pack_type)=@{$package};
 6337: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6338: 	    return $packagetab{"$pack_type&$name&default"};
 6339: 	}
 6340: 	if (defined($packagetab{$package."&$name&default"})) {
 6341: 	    return $packagetab{$package."&$name&default"};
 6342: 	}
 6343:     }
 6344:     # look for a global default setting
 6345:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6346: 	return $packagetab{"default&$name&default"};
 6347:     }
 6348:     return undef;
 6349: }
 6350: 
 6351: sub add_prefix_and_part {
 6352:     my ($prefix,$part)=@_;
 6353:     my $keyroot;
 6354:     if (defined($prefix) && $prefix !~ /^__/) {
 6355: 	# prefix that has a part already
 6356: 	$keyroot=$prefix;
 6357:     } elsif (defined($prefix)) {
 6358: 	# prefix that is missing a part
 6359: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6360:     } else {
 6361: 	# no prefix at all
 6362: 	if (defined($part)) { $keyroot='_'.$part; }
 6363:     }
 6364:     return $keyroot;
 6365: }
 6366: 
 6367: # ---------------------------------------------------------------- Get metadata
 6368: 
 6369: my %metaentry;
 6370: sub metadata {
 6371:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6372:     $uri=&declutter($uri);
 6373:     # if it is a non metadata possible uri return quickly
 6374:     if (($uri eq '') || 
 6375: 	(($uri =~ m|^/*adm/|) && 
 6376: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6377:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6378: 	($uri =~ m|home/$match_username/public_html/|)) {
 6379: 	return undef;
 6380:     }
 6381:     my $filename=$uri;
 6382:     $uri=~s/\.meta$//;
 6383: #
 6384: # Is the metadata already cached?
 6385: # Look at timestamp of caching
 6386: # Everything is cached by the main uri, libraries are never directly cached
 6387: #
 6388:     if (!defined($liburi)) {
 6389: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6390: 	if (defined($cached)) { return $result->{':'.$what}; }
 6391:     }
 6392:     {
 6393: #
 6394: # Is this a recursive call for a library?
 6395: #
 6396: #	if (! exists($metacache{$uri})) {
 6397: #	    $metacache{$uri}={};
 6398: #	}
 6399:         if ($liburi) {
 6400: 	    $liburi=&declutter($liburi);
 6401:             $filename=$liburi;
 6402:         } else {
 6403: 	    &devalidate_cache_new('meta',$uri);
 6404: 	    undef(%metaentry);
 6405: 	}
 6406:         my %metathesekeys=();
 6407:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6408: 	my $metastring;
 6409: 	if ($uri !~ m -^(editupload)/-) {
 6410: 	    my $file=&filelocation('',&clutter($filename));
 6411: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6412: 	    $metastring=&getfile($file);
 6413: 	}
 6414:         my $parser=HTML::LCParser->new(\$metastring);
 6415:         my $token;
 6416:         undef %metathesekeys;
 6417:         while ($token=$parser->get_token) {
 6418: 	    if ($token->[0] eq 'S') {
 6419: 		if (defined($token->[2]->{'package'})) {
 6420: #
 6421: # This is a package - get package info
 6422: #
 6423: 		    my $package=$token->[2]->{'package'};
 6424: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6425: 		    if (defined($token->[2]->{'id'})) { 
 6426: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6427: 		    }
 6428: 		    if ($metaentry{':packages'}) {
 6429: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6430: 		    } else {
 6431: 			$metaentry{':packages'}=$package.$keyroot;
 6432: 		    }
 6433: 		    foreach my $pack_entry (keys(%packagetab)) {
 6434: 			my $part=$keyroot;
 6435: 			$part=~s/^\_//;
 6436: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6437: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6438: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6439: 			    # ignore package.tab specified default values
 6440:                             # here &package_tab_default() will fetch those
 6441: 			    if ($subp eq 'default') { next; }
 6442: 			    my $value=$packagetab{$pack_entry};
 6443: 			    my $unikey;
 6444: 			    if ($pack =~ /_0$/) {
 6445: 				$unikey='parameter_0_'.$name;
 6446: 				$part=0;
 6447: 			    } else {
 6448: 				$unikey='parameter'.$keyroot.'_'.$name;
 6449: 			    }
 6450: 			    if ($subp eq 'display') {
 6451: 				$value.=' [Part: '.$part.']';
 6452: 			    }
 6453: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6454: 			    $metathesekeys{$unikey}=1;
 6455: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6456: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6457: 			    }
 6458: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6459: 				$metaentry{':'.$unikey}=
 6460: 				    $metaentry{':'.$unikey.'.default'};
 6461: 			    }
 6462: 			}
 6463: 		    }
 6464: 		} else {
 6465: #
 6466: # This is not a package - some other kind of start tag
 6467: #
 6468: 		    my $entry=$token->[1];
 6469: 		    my $unikey;
 6470: 		    if ($entry eq 'import') {
 6471: 			$unikey='';
 6472: 		    } else {
 6473: 			$unikey=$entry;
 6474: 		    }
 6475: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6476: 
 6477: 		    if (defined($token->[2]->{'id'})) { 
 6478: 			$unikey.='_'.$token->[2]->{'id'}; 
 6479: 		    }
 6480: 
 6481: 		    if ($entry eq 'import') {
 6482: #
 6483: # Importing a library here
 6484: #
 6485: 			if ($depthcount<20) {
 6486: 			    my $location=$parser->get_text('/import');
 6487: 			    my $dir=$filename;
 6488: 			    $dir=~s|[^/]*$||;
 6489: 			    $location=&filelocation($dir,$location);
 6490: 			    my $metadata = 
 6491: 				&metadata($uri,'keys', $location,$unikey,
 6492: 					  $depthcount+1);
 6493: 			    foreach my $meta (split(',',$metadata)) {
 6494: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6495: 				$metathesekeys{$meta}=1;
 6496: 			    }
 6497: 			}
 6498: 		    } else { 
 6499: 			
 6500: 			if (defined($token->[2]->{'name'})) { 
 6501: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6502: 			}
 6503: 			$metathesekeys{$unikey}=1;
 6504: 			foreach my $param (@{$token->[3]}) {
 6505: 			    $metaentry{':'.$unikey.'.'.$param} =
 6506: 				$token->[2]->{$param};
 6507: 			}
 6508: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6509: 			my $default=$metaentry{':'.$unikey.'.default'};
 6510: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6511: 		 # only ws inside the tag, and not in default, so use default
 6512: 		 # as value
 6513: 			    $metaentry{':'.$unikey}=$default;
 6514: 			} else {
 6515: 		  # either something interesting inside the tag or default
 6516:                   # uninteresting
 6517: 			    $metaentry{':'.$unikey}=$internaltext;
 6518: 			}
 6519: # end of not-a-package not-a-library import
 6520: 		    }
 6521: # end of not-a-package start tag
 6522: 		}
 6523: # the next is the end of "start tag"
 6524: 	    }
 6525: 	}
 6526: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6527: 	foreach my $key (keys(%packagetab)) {
 6528: 	    #no specific packages #how's our extension
 6529: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6530: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6531: 					 \%metathesekeys);
 6532: 	}
 6533: 	if (!exists($metaentry{':packages'})) {
 6534: 	    foreach my $key (keys(%packagetab)) {
 6535: 		#no specific packages well let's get default then
 6536: 		if ($key!~/^default&/) { next; }
 6537: 		&metadata_create_package_def($uri,$key,'default',
 6538: 					     \%metathesekeys);
 6539: 	    }
 6540: 	}
 6541: # are there custom rights to evaluate
 6542: 	if ($metaentry{':copyright'} eq 'custom') {
 6543: 
 6544:     #
 6545:     # Importing a rights file here
 6546:     #
 6547: 	    unless ($depthcount) {
 6548: 		my $location=$metaentry{':customdistributionfile'};
 6549: 		my $dir=$filename;
 6550: 		$dir=~s|[^/]*$||;
 6551: 		$location=&filelocation($dir,$location);
 6552: 		my $rights_metadata =
 6553: 		    &metadata($uri,'keys',$location,'_rights',
 6554: 			      $depthcount+1);
 6555: 		foreach my $rights (split(',',$rights_metadata)) {
 6556: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6557: 		    $metathesekeys{$rights}=1;
 6558: 		}
 6559: 	    }
 6560: 	}
 6561: 	# uniqifiy package listing
 6562: 	my %seen;
 6563: 	my @uniq_packages =
 6564: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6565: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6566: 
 6567: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6568: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6569: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6570: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6571: # this is the end of "was not already recently cached
 6572:     }
 6573:     return $metaentry{':'.$what};
 6574: }
 6575: 
 6576: sub metadata_create_package_def {
 6577:     my ($uri,$key,$package,$metathesekeys)=@_;
 6578:     my ($pack,$name,$subp)=split(/\&/,$key);
 6579:     if ($subp eq 'default') { next; }
 6580:     
 6581:     if (defined($metaentry{':packages'})) {
 6582: 	$metaentry{':packages'}.=','.$package;
 6583:     } else {
 6584: 	$metaentry{':packages'}=$package;
 6585:     }
 6586:     my $value=$packagetab{$key};
 6587:     my $unikey;
 6588:     $unikey='parameter_0_'.$name;
 6589:     $metaentry{':'.$unikey.'.part'}=0;
 6590:     $$metathesekeys{$unikey}=1;
 6591:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6592: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6593:     }
 6594:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6595: 	$metaentry{':'.$unikey}=
 6596: 	    $metaentry{':'.$unikey.'.default'};
 6597:     }
 6598: }
 6599: 
 6600: sub metadata_generate_part0 {
 6601:     my ($metadata,$metacache,$uri) = @_;
 6602:     my %allnames;
 6603:     foreach my $metakey (keys(%$metadata)) {
 6604: 	if ($metakey=~/^parameter\_(.*)/) {
 6605: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6606: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6607: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6608: 	    $allnames{$name}=$part;
 6609: 	  }
 6610: 	}
 6611:     }
 6612:     foreach my $name (keys(%allnames)) {
 6613:       $$metadata{"parameter_0_$name"}=1;
 6614:       my $key=":parameter_0_$name";
 6615:       $$metacache{"$key.part"}='0';
 6616:       $$metacache{"$key.name"}=$name;
 6617:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6618: 					   $allnames{$name}.'_'.$name.
 6619: 					   '.type'};
 6620:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6621: 			     '.display'};
 6622:       my $expr='[Part: '.$allnames{$name}.']';
 6623:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6624:       $$metacache{"$key.display"}=$olddis;
 6625:     }
 6626: }
 6627: 
 6628: # ------------------------------------------------------ Devalidate title cache
 6629: 
 6630: sub devalidate_title_cache {
 6631:     my ($url)=@_;
 6632:     if (!$env{'request.course.id'}) { return; }
 6633:     my $symb=&symbread($url);
 6634:     if (!$symb) { return; }
 6635:     my $key=$env{'request.course.id'}."\0".$symb;
 6636:     &devalidate_cache_new('title',$key);
 6637: }
 6638: 
 6639: # ------------------------------------------------- Get the title of a resource
 6640: 
 6641: sub gettitle {
 6642:     my $urlsymb=shift;
 6643:     my $symb=&symbread($urlsymb);
 6644:     if ($symb) {
 6645: 	my $key=$env{'request.course.id'}."\0".$symb;
 6646: 	my ($result,$cached)=&is_cached_new('title',$key);
 6647: 	if (defined($cached)) { 
 6648: 	    return $result;
 6649: 	}
 6650: 	my ($map,$resid,$url)=&decode_symb($symb);
 6651: 	my $title='';
 6652: 	my %bighash;
 6653: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6654: 		&GDBM_READER(),0640)) {
 6655: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6656: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6657: 	    untie %bighash;
 6658: 	}
 6659: 	$title=~s/\&colon\;/\:/gs;
 6660: 	if ($title) {
 6661: 	    return &do_cache_new('title',$key,$title,600);
 6662: 	}
 6663: 	$urlsymb=$url;
 6664:     }
 6665:     my $title=&metadata($urlsymb,'title');
 6666:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6667:     return $title;
 6668: }
 6669: 
 6670: sub get_slot {
 6671:     my ($which,$cnum,$cdom)=@_;
 6672:     if (!$cnum || !$cdom) {
 6673: 	(undef,my $courseid)=&whichuser();
 6674: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6675: 	$cnum=$env{'course.'.$courseid.'.num'};
 6676:     }
 6677:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6678:     my %slotinfo;
 6679:     if (exists($remembered{$key})) {
 6680: 	$slotinfo{$which} = $remembered{$key};
 6681:     } else {
 6682: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6683: 	&Apache::lonhomework::showhash(%slotinfo);
 6684: 	my ($tmp)=keys(%slotinfo);
 6685: 	if ($tmp=~/^error:/) { return (); }
 6686: 	$remembered{$key} = $slotinfo{$which};
 6687:     }
 6688:     if (ref($slotinfo{$which}) eq 'HASH') {
 6689: 	return %{$slotinfo{$which}};
 6690:     }
 6691:     return $slotinfo{$which};
 6692: }
 6693: # ------------------------------------------------- Update symbolic store links
 6694: 
 6695: sub symblist {
 6696:     my ($mapname,%newhash)=@_;
 6697:     $mapname=&deversion(&declutter($mapname));
 6698:     my %hash;
 6699:     if (($env{'request.course.fn'}) && (%newhash)) {
 6700:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6701:                       &GDBM_WRCREAT(),0640)) {
 6702: 	    foreach my $url (keys %newhash) {
 6703: 		next if ($url eq 'last_known'
 6704: 			 && $env{'form.no_update_last_known'});
 6705: 		$hash{declutter($url)}=&encode_symb($mapname,
 6706: 						    $newhash{$url}->[1],
 6707: 						    $newhash{$url}->[0]);
 6708:             }
 6709:             if (untie(%hash)) {
 6710: 		return 'ok';
 6711:             }
 6712:         }
 6713:     }
 6714:     return 'error';
 6715: }
 6716: 
 6717: # --------------------------------------------------------------- Verify a symb
 6718: 
 6719: sub symbverify {
 6720:     my ($symb,$thisurl)=@_;
 6721:     my $thisfn=$thisurl;
 6722:     $thisfn=&declutter($thisfn);
 6723: # direct jump to resource in page or to a sequence - will construct own symbs
 6724:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6725: # check URL part
 6726:     my ($map,$resid,$url)=&decode_symb($symb);
 6727: 
 6728:     unless ($url eq $thisfn) { return 0; }
 6729: 
 6730:     $symb=&symbclean($symb);
 6731:     $thisurl=&deversion($thisurl);
 6732:     $thisfn=&deversion($thisfn);
 6733: 
 6734:     my %bighash;
 6735:     my $okay=0;
 6736: 
 6737:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6738:                             &GDBM_READER(),0640)) {
 6739:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6740:         unless ($ids) { 
 6741:            $ids=$bighash{'ids_/'.$thisurl};
 6742:         }
 6743:         if ($ids) {
 6744: # ------------------------------------------------------------------- Has ID(s)
 6745: 	    foreach my $id (split(/\,/,$ids)) {
 6746: 	       my ($mapid,$resid)=split(/\./,$id);
 6747:                if (
 6748:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6749:    eq $symb) { 
 6750: 		   if (($env{'request.role.adv'}) ||
 6751: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6752: 		       $okay=1; 
 6753: 		   }
 6754: 	       }
 6755: 	   }
 6756:         }
 6757: 	untie(%bighash);
 6758:     }
 6759:     return $okay;
 6760: }
 6761: 
 6762: # --------------------------------------------------------------- Clean-up symb
 6763: 
 6764: sub symbclean {
 6765:     my $symb=shift;
 6766:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6767: # remove version from map
 6768:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6769: 
 6770: # remove version from URL
 6771:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6772: 
 6773: # remove wrapper
 6774: 
 6775:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6776:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6777:     return $symb;
 6778: }
 6779: 
 6780: # ---------------------------------------------- Split symb to find map and url
 6781: 
 6782: sub encode_symb {
 6783:     my ($map,$resid,$url)=@_;
 6784:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6785: }
 6786: 
 6787: sub decode_symb {
 6788:     my $symb=shift;
 6789:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6790:     my ($map,$resid,$url)=split(/___/,$symb);
 6791:     return (&fixversion($map),$resid,&fixversion($url));
 6792: }
 6793: 
 6794: sub fixversion {
 6795:     my $fn=shift;
 6796:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6797:     my %bighash;
 6798:     my $uri=&clutter($fn);
 6799:     my $key=$env{'request.course.id'}.'_'.$uri;
 6800: # is this cached?
 6801:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6802:     if (defined($cached)) { return $result; }
 6803: # unfortunately not cached, or expired
 6804:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6805: 	    &GDBM_READER(),0640)) {
 6806:  	if ($bighash{'version_'.$uri}) {
 6807:  	    my $version=$bighash{'version_'.$uri};
 6808:  	    unless (($version eq 'mostrecent') || 
 6809: 		    ($version==&getversion($uri))) {
 6810:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6811:  	    }
 6812:  	}
 6813:  	untie %bighash;
 6814:     }
 6815:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6816: }
 6817: 
 6818: sub deversion {
 6819:     my $url=shift;
 6820:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6821:     return $url;
 6822: }
 6823: 
 6824: # ------------------------------------------------------ Return symb list entry
 6825: 
 6826: sub symbread {
 6827:     my ($thisfn,$donotrecurse)=@_;
 6828:     my $cache_str='request.symbread.cached.'.$thisfn;
 6829:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6830: # no filename provided? try from environment
 6831:     unless ($thisfn) {
 6832:         if ($env{'request.symb'}) {
 6833: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6834: 	}
 6835: 	$thisfn=$env{'request.filename'};
 6836:     }
 6837:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6838: # is that filename actually a symb? Verify, clean, and return
 6839:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6840: 	if (&symbverify($thisfn,$1)) {
 6841: 	    return $env{$cache_str}=&symbclean($thisfn);
 6842: 	}
 6843:     }
 6844:     $thisfn=declutter($thisfn);
 6845:     my %hash;
 6846:     my %bighash;
 6847:     my $syval='';
 6848:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6849:         my $targetfn = $thisfn;
 6850:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6851:             $targetfn = 'adm/wrapper/'.$thisfn;
 6852:         }
 6853: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6854: 	    $targetfn=$1;
 6855: 	}
 6856:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6857:                       &GDBM_READER(),0640)) {
 6858: 	    $syval=$hash{$targetfn};
 6859:             untie(%hash);
 6860:         }
 6861: # ---------------------------------------------------------- There was an entry
 6862:         if ($syval) {
 6863: 	    #unless ($syval=~/\_\d+$/) {
 6864: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6865: 		    #&appenv('request.ambiguous' => $thisfn);
 6866: 		    #return $env{$cache_str}='';
 6867: 		#}    
 6868: 		#$syval.=$1;
 6869: 	    #}
 6870:         } else {
 6871: # ------------------------------------------------------- Was not in symb table
 6872:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6873:                             &GDBM_READER(),0640)) {
 6874: # ---------------------------------------------- Get ID(s) for current resource
 6875:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6876:               unless ($ids) { 
 6877:                  $ids=$bighash{'ids_/'.$thisfn};
 6878:               }
 6879:               unless ($ids) {
 6880: # alias?
 6881: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6882:               }
 6883:               if ($ids) {
 6884: # ------------------------------------------------------------------- Has ID(s)
 6885:                  my @possibilities=split(/\,/,$ids);
 6886:                  if ($#possibilities==0) {
 6887: # ----------------------------------------------- There is only one possibility
 6888: 		     my ($mapid,$resid)=split(/\./,$ids);
 6889: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6890: 						    $resid,$thisfn);
 6891:                  } elsif (!$donotrecurse) {
 6892: # ------------------------------------------ There is more than one possibility
 6893:                      my $realpossible=0;
 6894:                      foreach my $id (@possibilities) {
 6895: 			 my $file=$bighash{'src_'.$id};
 6896:                          if (&allowed('bre',$file)) {
 6897:          		    my ($mapid,$resid)=split(/\./,$id);
 6898:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6899: 				$realpossible++;
 6900:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6901: 						    $resid,$thisfn);
 6902:                             }
 6903: 			 }
 6904:                      }
 6905: 		     if ($realpossible!=1) { $syval=''; }
 6906:                  } else {
 6907:                      $syval='';
 6908:                  }
 6909: 	      }
 6910:               untie(%bighash)
 6911:            }
 6912:         }
 6913:         if ($syval) {
 6914: 	    return $env{$cache_str}=$syval;
 6915:         }
 6916:     }
 6917:     &appenv('request.ambiguous' => $thisfn);
 6918:     return $env{$cache_str}='';
 6919: }
 6920: 
 6921: # ---------------------------------------------------------- Return random seed
 6922: 
 6923: sub numval {
 6924:     my $txt=shift;
 6925:     $txt=~tr/A-J/0-9/;
 6926:     $txt=~tr/a-j/0-9/;
 6927:     $txt=~tr/K-T/0-9/;
 6928:     $txt=~tr/k-t/0-9/;
 6929:     $txt=~tr/U-Z/0-5/;
 6930:     $txt=~tr/u-z/0-5/;
 6931:     $txt=~s/\D//g;
 6932:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6933:     return int($txt);
 6934: }
 6935: 
 6936: sub numval2 {
 6937:     my $txt=shift;
 6938:     $txt=~tr/A-J/0-9/;
 6939:     $txt=~tr/a-j/0-9/;
 6940:     $txt=~tr/K-T/0-9/;
 6941:     $txt=~tr/k-t/0-9/;
 6942:     $txt=~tr/U-Z/0-5/;
 6943:     $txt=~tr/u-z/0-5/;
 6944:     $txt=~s/\D//g;
 6945:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6946:     my $total;
 6947:     foreach my $val (@txts) { $total+=$val; }
 6948:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6949:     return int($total);
 6950: }
 6951: 
 6952: sub numval3 {
 6953:     use integer;
 6954:     my $txt=shift;
 6955:     $txt=~tr/A-J/0-9/;
 6956:     $txt=~tr/a-j/0-9/;
 6957:     $txt=~tr/K-T/0-9/;
 6958:     $txt=~tr/k-t/0-9/;
 6959:     $txt=~tr/U-Z/0-5/;
 6960:     $txt=~tr/u-z/0-5/;
 6961:     $txt=~s/\D//g;
 6962:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6963:     my $total;
 6964:     foreach my $val (@txts) { $total+=$val; }
 6965:     if ($_64bit) { $total=(($total<<32)>>32); }
 6966:     return $total;
 6967: }
 6968: 
 6969: sub digest {
 6970:     my ($data)=@_;
 6971:     my $digest=&Digest::MD5::md5($data);
 6972:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6973:     my ($e,$f);
 6974:     {
 6975:         use integer;
 6976:         $e=($a+$b);
 6977:         $f=($c+$d);
 6978:         if ($_64bit) {
 6979:             $e=(($e<<32)>>32);
 6980:             $f=(($f<<32)>>32);
 6981:         }
 6982:     }
 6983:     if (wantarray) {
 6984: 	return ($e,$f);
 6985:     } else {
 6986: 	my $g;
 6987: 	{
 6988: 	    use integer;
 6989: 	    $g=($e+$f);
 6990: 	    if ($_64bit) {
 6991: 		$g=(($g<<32)>>32);
 6992: 	    }
 6993: 	}
 6994: 	return $g;
 6995:     }
 6996: }
 6997: 
 6998: sub latest_rnd_algorithm_id {
 6999:     return '64bit5';
 7000: }
 7001: 
 7002: sub get_rand_alg {
 7003:     my ($courseid)=@_;
 7004:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7005:     if ($courseid) {
 7006: 	return $env{"course.$courseid.rndseed"};
 7007:     }
 7008:     return &latest_rnd_algorithm_id();
 7009: }
 7010: 
 7011: sub validCODE {
 7012:     my ($CODE)=@_;
 7013:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7014:     return 0;
 7015: }
 7016: 
 7017: sub getCODE {
 7018:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7019:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7020: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7021: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7022: 	return $Apache::lonhomework::history{'resource.CODE'};
 7023:     }
 7024:     return undef;
 7025: }
 7026: 
 7027: sub rndseed {
 7028:     my ($symb,$courseid,$domain,$username)=@_;
 7029:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7030:     if (!$symb) {
 7031: 	unless ($symb=$wsymb) { return time; }
 7032:     }
 7033:     if (!$courseid) { $courseid=$wcourseid; }
 7034:     if (!$domain) { $domain=$wdomain; }
 7035:     if (!$username) { $username=$wusername }
 7036:     my $which=&get_rand_alg();
 7037: 
 7038:     if (defined(&getCODE())) {
 7039: 	if ($which eq '64bit5') {
 7040: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7041: 	} elsif ($which eq '64bit4') {
 7042: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7043: 	} else {
 7044: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7045: 	}
 7046:     } elsif ($which eq '64bit5') {
 7047: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7048:     } elsif ($which eq '64bit4') {
 7049: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7050:     } elsif ($which eq '64bit3') {
 7051: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7052:     } elsif ($which eq '64bit2') {
 7053: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7054:     } elsif ($which eq '64bit') {
 7055: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7056:     }
 7057:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7058: }
 7059: 
 7060: sub rndseed_32bit {
 7061:     my ($symb,$courseid,$domain,$username)=@_;
 7062:     {
 7063: 	use integer;
 7064: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7065: 	my $symbseed=numval($symb) << 22;
 7066: 	my $namechck=unpack("%32C*",$username) << 17;
 7067: 	my $nameseed=numval($username) << 12;
 7068: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7069: 	my $courseseed=unpack("%32C*",$courseid);
 7070: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7071: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7072: 	#&logthis("rndseed :$num:$symb");
 7073: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7074: 	return $num;
 7075:     }
 7076: }
 7077: 
 7078: sub rndseed_64bit {
 7079:     my ($symb,$courseid,$domain,$username)=@_;
 7080:     {
 7081: 	use integer;
 7082: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7083: 	my $symbseed=numval($symb) << 10;
 7084: 	my $namechck=unpack("%32S*",$username);
 7085: 	
 7086: 	my $nameseed=numval($username) << 21;
 7087: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7088: 	my $courseseed=unpack("%32S*",$courseid);
 7089: 	
 7090: 	my $num1=$symbchck+$symbseed+$namechck;
 7091: 	my $num2=$nameseed+$domainseed+$courseseed;
 7092: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7093: 	#&logthis("rndseed :$num:$symb");
 7094: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7095: 	return "$num1,$num2";
 7096:     }
 7097: }
 7098: 
 7099: sub rndseed_64bit2 {
 7100:     my ($symb,$courseid,$domain,$username)=@_;
 7101:     {
 7102: 	use integer;
 7103: 	# strings need to be an even # of cahracters long, it it is odd the
 7104:         # last characters gets thrown away
 7105: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7106: 	my $symbseed=numval($symb) << 10;
 7107: 	my $namechck=unpack("%32S*",$username.' ');
 7108: 	
 7109: 	my $nameseed=numval($username) << 21;
 7110: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7111: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7112: 	
 7113: 	my $num1=$symbchck+$symbseed+$namechck;
 7114: 	my $num2=$nameseed+$domainseed+$courseseed;
 7115: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7116: 	#&logthis("rndseed :$num:$symb");
 7117: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7118: 	return "$num1,$num2";
 7119:     }
 7120: }
 7121: 
 7122: sub rndseed_64bit3 {
 7123:     my ($symb,$courseid,$domain,$username)=@_;
 7124:     {
 7125: 	use integer;
 7126: 	# strings need to be an even # of cahracters long, it it is odd the
 7127:         # last characters gets thrown away
 7128: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7129: 	my $symbseed=numval2($symb) << 10;
 7130: 	my $namechck=unpack("%32S*",$username.' ');
 7131: 	
 7132: 	my $nameseed=numval2($username) << 21;
 7133: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7134: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7135: 	
 7136: 	my $num1=$symbchck+$symbseed+$namechck;
 7137: 	my $num2=$nameseed+$domainseed+$courseseed;
 7138: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7139: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7140: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7141: 	
 7142: 	return "$num1:$num2";
 7143:     }
 7144: }
 7145: 
 7146: sub rndseed_64bit4 {
 7147:     my ($symb,$courseid,$domain,$username)=@_;
 7148:     {
 7149: 	use integer;
 7150: 	# strings need to be an even # of cahracters long, it it is odd the
 7151:         # last characters gets thrown away
 7152: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7153: 	my $symbseed=numval3($symb) << 10;
 7154: 	my $namechck=unpack("%32S*",$username.' ');
 7155: 	
 7156: 	my $nameseed=numval3($username) << 21;
 7157: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7158: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7159: 	
 7160: 	my $num1=$symbchck+$symbseed+$namechck;
 7161: 	my $num2=$nameseed+$domainseed+$courseseed;
 7162: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7163: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7164: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7165: 	
 7166: 	return "$num1:$num2";
 7167:     }
 7168: }
 7169: 
 7170: sub rndseed_64bit5 {
 7171:     my ($symb,$courseid,$domain,$username)=@_;
 7172:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7173:     return "$num1:$num2";
 7174: }
 7175: 
 7176: sub rndseed_CODE_64bit {
 7177:     my ($symb,$courseid,$domain,$username)=@_;
 7178:     {
 7179: 	use integer;
 7180: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7181: 	my $symbseed=numval2($symb);
 7182: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7183: 	my $CODEseed=numval(&getCODE());
 7184: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7185: 	my $num1=$symbseed+$CODEchck;
 7186: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7187: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7188: 	#&logthis("rndseed :$num1:$num2:$symb");
 7189: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7190: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7191: 	return "$num1:$num2";
 7192:     }
 7193: }
 7194: 
 7195: sub rndseed_CODE_64bit4 {
 7196:     my ($symb,$courseid,$domain,$username)=@_;
 7197:     {
 7198: 	use integer;
 7199: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7200: 	my $symbseed=numval3($symb);
 7201: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7202: 	my $CODEseed=numval3(&getCODE());
 7203: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7204: 	my $num1=$symbseed+$CODEchck;
 7205: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7206: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7207: 	#&logthis("rndseed :$num1:$num2:$symb");
 7208: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7209: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7210: 	return "$num1:$num2";
 7211:     }
 7212: }
 7213: 
 7214: sub rndseed_CODE_64bit5 {
 7215:     my ($symb,$courseid,$domain,$username)=@_;
 7216:     my $code = &getCODE();
 7217:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7218:     return "$num1:$num2";
 7219: }
 7220: 
 7221: sub setup_random_from_rndseed {
 7222:     my ($rndseed)=@_;
 7223:     if ($rndseed =~/([,:])/) {
 7224: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7225: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7226:     } else {
 7227: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7228:     }
 7229: }
 7230: 
 7231: sub latest_receipt_algorithm_id {
 7232:     return 'receipt3';
 7233: }
 7234: 
 7235: sub recunique {
 7236:     my $fucourseid=shift;
 7237:     my $unique;
 7238:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7239: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7240: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7241:     } else {
 7242: 	$unique=$perlvar{'lonReceipt'};
 7243:     }
 7244:     return unpack("%32C*",$unique);
 7245: }
 7246: 
 7247: sub recprefix {
 7248:     my $fucourseid=shift;
 7249:     my $prefix;
 7250:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7251: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7252: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7253:     } else {
 7254: 	$prefix=$perlvar{'lonHostID'};
 7255:     }
 7256:     return unpack("%32C*",$prefix);
 7257: }
 7258: 
 7259: sub ireceipt {
 7260:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7261: 
 7262:     my $return =&recprefix($fucourseid).'-';
 7263: 
 7264:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7265: 	$env{'request.state'} eq 'construct') {
 7266: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7267: 	return $return;
 7268:     }
 7269: 
 7270:     my $cuname=unpack("%32C*",$funame);
 7271:     my $cudom=unpack("%32C*",$fudom);
 7272:     my $cucourseid=unpack("%32C*",$fucourseid);
 7273:     my $cusymb=unpack("%32C*",$fusymb);
 7274:     my $cunique=&recunique($fucourseid);
 7275:     my $cpart=unpack("%32S*",$part);
 7276:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7277: 
 7278: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7279: 			       
 7280: 	$return.= ($cunique%$cuname+
 7281: 		   $cunique%$cudom+
 7282: 		   $cusymb%$cuname+
 7283: 		   $cusymb%$cudom+
 7284: 		   $cucourseid%$cuname+
 7285: 		   $cucourseid%$cudom+
 7286: 		   $cpart%$cuname+
 7287: 		   $cpart%$cudom);
 7288:     } else {
 7289: 	$return.= ($cunique%$cuname+
 7290: 		   $cunique%$cudom+
 7291: 		   $cusymb%$cuname+
 7292: 		   $cusymb%$cudom+
 7293: 		   $cucourseid%$cuname+
 7294: 		   $cucourseid%$cudom);
 7295:     }
 7296:     return $return;
 7297: }
 7298: 
 7299: sub receipt {
 7300:     my ($part)=@_;
 7301:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7302:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7303: }
 7304: 
 7305: sub whichuser {
 7306:     my ($passedsymb)=@_;
 7307:     my ($symb,$courseid,$domain,$name,$publicuser);
 7308:     if (defined($env{'form.grade_symb'})) {
 7309: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7310: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7311: 	if (!$allowed &&
 7312: 	    exists($env{'request.course.sec'}) &&
 7313: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7314: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7315: 			      '/'.$env{'request.course.sec'});
 7316: 	}
 7317: 	if ($allowed) {
 7318: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7319: 	    $courseid=$tmp_courseid;
 7320: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7321: 	    ($name)=&get_env_multiple('form.grade_username');
 7322: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7323: 	}
 7324:     }
 7325:     if (!$passedsymb) {
 7326: 	$symb=&symbread();
 7327:     } else {
 7328: 	$symb=$passedsymb;
 7329:     }
 7330:     $courseid=$env{'request.course.id'};
 7331:     $domain=$env{'user.domain'};
 7332:     $name=$env{'user.name'};
 7333:     if ($name eq 'public' && $domain eq 'public') {
 7334: 	if (!defined($env{'form.username'})) {
 7335: 	    $env{'form.username'}.=time.rand(10000000);
 7336: 	}
 7337: 	$name.=$env{'form.username'};
 7338:     }
 7339:     return ($symb,$courseid,$domain,$name,$publicuser);
 7340: 
 7341: }
 7342: 
 7343: # ------------------------------------------------------------ Serves up a file
 7344: # returns either the contents of the file or 
 7345: # -1 if the file doesn't exist
 7346: #
 7347: # if the target is a file that was uploaded via DOCS, 
 7348: # a check will be made to see if a current copy exists on the local server,
 7349: # if it does this will be served, otherwise a copy will be retrieved from
 7350: # the home server for the course and stored in /home/httpd/html/userfiles on
 7351: # the local server.   
 7352: 
 7353: sub getfile {
 7354:     my ($file) = @_;
 7355:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7356:     &repcopy($file);
 7357:     return &readfile($file);
 7358: }
 7359: 
 7360: sub repcopy_userfile {
 7361:     my ($file)=@_;
 7362:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7363:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7364:     my ($cdom,$cnum,$filename) = 
 7365: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7366:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7367:     if (-e "$file") {
 7368: # we already have a local copy, check it out
 7369: 	my @fileinfo = stat($file);
 7370: 	my $rtncode;
 7371: 	my $info;
 7372: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7373: 	if ($lwpresp ne 'ok') {
 7374: # there is no such file anymore, even though we had a local copy
 7375: 	    if ($rtncode eq '404') {
 7376: 		unlink($file);
 7377: 	    }
 7378: 	    return -1;
 7379: 	}
 7380: 	if ($info < $fileinfo[9]) {
 7381: # nice, the file we have is up-to-date, just say okay
 7382: 	    return 'ok';
 7383: 	} else {
 7384: # the file is outdated, get rid of it
 7385: 	    unlink($file);
 7386: 	}
 7387:     }
 7388: # one way or the other, at this point, we don't have the file
 7389: # construct the correct path for the file
 7390:     my @parts = ($cdom,$cnum); 
 7391:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7392: 	push @parts, split(/\//,$1);
 7393:     }
 7394:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7395:     foreach my $part (@parts) {
 7396: 	$path .= '/'.$part;
 7397: 	if (!-e $path) {
 7398: 	    mkdir($path,0770);
 7399: 	}
 7400:     }
 7401: # now the path exists for sure
 7402: # get a user agent
 7403:     my $ua=new LWP::UserAgent;
 7404:     my $transferfile=$file.'.in.transfer';
 7405: # FIXME: this should flock
 7406:     if (-e $transferfile) { return 'ok'; }
 7407:     my $request;
 7408:     $uri=~s/^\///;
 7409:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7410:     my $response=$ua->request($request,$transferfile);
 7411: # did it work?
 7412:     if ($response->is_error()) {
 7413: 	unlink($transferfile);
 7414: 	&logthis("Userfile repcopy failed for $uri");
 7415: 	return -1;
 7416:     }
 7417: # worked, rename the transfer file
 7418:     rename($transferfile,$file);
 7419:     return 'ok';
 7420: }
 7421: 
 7422: sub tokenwrapper {
 7423:     my $uri=shift;
 7424:     $uri=~s|^http\://([^/]+)||;
 7425:     $uri=~s|^/||;
 7426:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7427:     my $token=$1;
 7428:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7429:     if ($udom && $uname && $file) {
 7430: 	$file=~s|(\?\.*)*$||;
 7431:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7432:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7433:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7434:                                '&tokenissued='.$perlvar{'lonHostID'};
 7435:     } else {
 7436:         return '/adm/notfound.html';
 7437:     }
 7438: }
 7439: 
 7440: # call with reqtype HEAD: get last modification time
 7441: # call with reqtype GET: get the file contents
 7442: # Do not call this with reqtype GET for large files! It loads everything into memory
 7443: #
 7444: sub getuploaded {
 7445:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7446:     $uri=~s/^\///;
 7447:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7448:     my $ua=new LWP::UserAgent;
 7449:     my $request=new HTTP::Request($reqtype,$uri);
 7450:     my $response=$ua->request($request);
 7451:     $$rtncode = $response->code;
 7452:     if (! $response->is_success()) {
 7453: 	return 'failed';
 7454:     }      
 7455:     if ($reqtype eq 'HEAD') {
 7456: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7457:     } elsif ($reqtype eq 'GET') {
 7458: 	$$info = $response->content;
 7459:     }
 7460:     return 'ok';
 7461: }
 7462: 
 7463: sub readfile {
 7464:     my $file = shift;
 7465:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7466:     my $fh;
 7467:     open($fh,"<$file");
 7468:     my $a='';
 7469:     while (my $line = <$fh>) { $a .= $line; }
 7470:     return $a;
 7471: }
 7472: 
 7473: sub filelocation {
 7474:     my ($dir,$file) = @_;
 7475:     my $location;
 7476:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7477: 
 7478:     if ($file =~ m-^/adm/-) {
 7479: 	$file=~s-^/adm/wrapper/-/-;
 7480: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7481:     }
 7482:     if ($file=~m:^/~:) { # is a contruction space reference
 7483:         $location = $file;
 7484:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7485:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7486: 	# is a correct contruction space reference
 7487:         $location = $file;
 7488:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7489:         my ($udom,$uname,$filename)=
 7490:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7491:         my $home=&homeserver($uname,$udom);
 7492:         my $is_me=0;
 7493:         my @ids=&current_machine_ids();
 7494:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7495:         if ($is_me) {
 7496:   	    $location=&propath($udom,$uname).
 7497:   	      '/userfiles/'.$filename;
 7498:         } else {
 7499:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7500:   	      $udom.'/'.$uname.'/'.$filename;
 7501:         }
 7502:     } else {
 7503:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7504:         $file=~s:^/res/:/:;
 7505:         if ( !( $file =~ m:^/:) ) {
 7506:             $location = $dir. '/'.$file;
 7507:         } else {
 7508:             $location = '/home/httpd/html/res'.$file;
 7509:         }
 7510:     }
 7511:     $location=~s://+:/:g; # remove duplicate /
 7512:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7513:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7514:     return $location;
 7515: }
 7516: 
 7517: sub hreflocation {
 7518:     my ($dir,$file)=@_;
 7519:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7520: 	$file=filelocation($dir,$file);
 7521:     } elsif ($file=~m-^/adm/-) {
 7522: 	$file=~s-^/adm/wrapper/-/-;
 7523: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7524:     }
 7525:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7526: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7527:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7528: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7529:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7530: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7531: 	    -/uploaded/$1/$2/-x;
 7532:     }
 7533:     return $file;
 7534: }
 7535: 
 7536: sub current_machine_domains {
 7537:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7538: }
 7539: 
 7540: sub machine_domains {
 7541:     my ($hostname) = @_;
 7542:     my @domains;
 7543:     my %hostname = &all_hostnames();
 7544:     while( my($id, $name) = each(%hostname)) {
 7545: #	&logthis("-$id-$name-$hostname-");
 7546: 	if ($hostname eq $name) {
 7547: 	    push(@domains,&host_domain($id));
 7548: 	}
 7549:     }
 7550:     return @domains;
 7551: }
 7552: 
 7553: sub current_machine_ids {
 7554:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7555: }
 7556: 
 7557: sub machine_ids {
 7558:     my ($hostname) = @_;
 7559:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7560:     my @ids;
 7561:     my %hostname = &all_hostnames();
 7562:     while( my($id, $name) = each(%hostname)) {
 7563: #	&logthis("-$id-$name-$hostname-");
 7564: 	if ($hostname eq $name) {
 7565: 	    push(@ids,$id);
 7566: 	}
 7567:     }
 7568:     return @ids;
 7569: }
 7570: 
 7571: sub additional_machine_domains {
 7572:     my @domains;
 7573:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7574:     while( my $line = <$fh>) {
 7575:         $line =~ s/\s//g;
 7576:         push(@domains,$line);
 7577:     }
 7578:     return @domains;
 7579: }
 7580: 
 7581: sub default_login_domain {
 7582:     my $domain = $perlvar{'lonDefDomain'};
 7583:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7584:     foreach my $posdom (&current_machine_domains(),
 7585:                         &additional_machine_domains()) {
 7586:         if (lc($posdom) eq lc($testdomain)) {
 7587:             $domain=$posdom;
 7588:             last;
 7589:         }
 7590:     }
 7591:     return $domain;
 7592: }
 7593: 
 7594: # ------------------------------------------------------------- Declutters URLs
 7595: 
 7596: sub declutter {
 7597:     my $thisfn=shift;
 7598:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7599:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7600:     $thisfn=~s/^\///;
 7601:     $thisfn=~s|^adm/wrapper/||;
 7602:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7603:     $thisfn=~s/^res\///;
 7604:     $thisfn=~s/\?.+$//;
 7605:     return $thisfn;
 7606: }
 7607: 
 7608: # ------------------------------------------------------------- Clutter up URLs
 7609: 
 7610: sub clutter {
 7611:     my $thisfn='/'.&declutter(shift);
 7612:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7613:        $thisfn='/res'.$thisfn; 
 7614:     }
 7615:     if ($thisfn !~m|/adm|) {
 7616: 	if ($thisfn =~ m|/ext/|) {
 7617: 	    $thisfn='/adm/wrapper'.$thisfn;
 7618: 	} else {
 7619: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7620: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7621: 	    if ($embstyle eq 'ssi'
 7622: 		|| ($embstyle eq 'hdn')
 7623: 		|| ($embstyle eq 'rat')
 7624: 		|| ($embstyle eq 'prv')
 7625: 		|| ($embstyle eq 'ign')) {
 7626: 		#do nothing with these
 7627: 	    } elsif (($embstyle eq 'img') 
 7628: 		|| ($embstyle eq 'emb')
 7629: 		|| ($embstyle eq 'wrp')) {
 7630: 		$thisfn='/adm/wrapper'.$thisfn;
 7631: 	    } elsif ($embstyle eq 'unk'
 7632: 		     && $thisfn!~/\.(sequence|page)$/) {
 7633: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7634: 	    } else {
 7635: #		&logthis("Got a blank emb style");
 7636: 	    }
 7637: 	}
 7638:     }
 7639:     return $thisfn;
 7640: }
 7641: 
 7642: sub clutter_with_no_wrapper {
 7643:     my $uri = &clutter(shift);
 7644:     if ($uri =~ m-^/adm/-) {
 7645: 	$uri =~ s-^/adm/wrapper/-/-;
 7646: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7647:     }
 7648:     return $uri;
 7649: }
 7650: 
 7651: sub freeze_escape {
 7652:     my ($value)=@_;
 7653:     if (ref($value)) {
 7654: 	$value=&nfreeze($value);
 7655: 	return '__FROZEN__'.&escape($value);
 7656:     }
 7657:     return &escape($value);
 7658: }
 7659: 
 7660: 
 7661: sub thaw_unescape {
 7662:     my ($value)=@_;
 7663:     if ($value =~ /^__FROZEN__/) {
 7664: 	substr($value,0,10,undef);
 7665: 	$value=&unescape($value);
 7666: 	return &thaw($value);
 7667:     }
 7668:     return &unescape($value);
 7669: }
 7670: 
 7671: sub correct_line_ends {
 7672:     my ($result)=@_;
 7673:     $$result =~s/\r\n/\n/mg;
 7674:     $$result =~s/\r/\n/mg;
 7675: }
 7676: # ================================================================ Main Program
 7677: 
 7678: sub goodbye {
 7679:    &logthis("Starting Shut down");
 7680: #not converted to using infrastruture and probably shouldn't be
 7681:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7682: #converted
 7683: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7684:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7685: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7686: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7687: #1.1 only
 7688: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7689: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7690: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7691: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7692:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7693:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7694:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7695:    &flushcourselogs();
 7696:    &logthis("Shutting down");
 7697: }
 7698: 
 7699: sub get_dns {
 7700:     my ($url,$func,$ignore_cache) = @_;
 7701:     if (!$ignore_cache) {
 7702: 	my ($content,$cached)=
 7703: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7704: 	if ($cached) {
 7705: 	    &$func($content);
 7706: 	    return;
 7707: 	}
 7708:     }
 7709: 
 7710:     my %alldns;
 7711:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7712:     foreach my $dns (<$config>) {
 7713: 	next if ($dns !~ /^\^(\S*)/x);
 7714: 	$alldns{$1} = 1;
 7715:     }
 7716:     while (%alldns) {
 7717: 	my ($dns) = keys(%alldns);
 7718: 	delete($alldns{$dns});
 7719: 	my $ua=new LWP::UserAgent;
 7720: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7721: 	my $response=$ua->request($request);
 7722: 	next if ($response->is_error());
 7723: 	my @content = split("\n",$response->content);
 7724: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7725: 	&$func(\@content);
 7726: 	return;
 7727:     }
 7728:     close($config);
 7729:     my $which = (split('/',$url))[3];
 7730:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 7731:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 7732:     my @content = <$config>;
 7733:     &$func(\@content);
 7734:     return;
 7735: }
 7736: # ------------------------------------------------------------ Read domain file
 7737: {
 7738:     my $loaded;
 7739:     my %domain;
 7740: 
 7741:     sub parse_domain_tab {
 7742: 	my ($lines) = @_;
 7743: 	foreach my $line (@$lines) {
 7744: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7745: 
 7746: 	    chomp($line);
 7747: 	    my ($name,@elements) = split(/:/,$line,9);
 7748: 	    my %this_domain;
 7749: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7750: 			       'lang_def', 'city', 'longi', 'lati',
 7751: 			       'primary') {
 7752: 		$this_domain{$field} = shift(@elements);
 7753: 	    }
 7754: 	    $domain{$name} = \%this_domain;
 7755: 	}
 7756:     }
 7757: 
 7758:     sub reset_domain_info {
 7759: 	undef($loaded);
 7760: 	undef(%domain);
 7761:     }
 7762: 
 7763:     sub load_domain_tab {
 7764: 	my ($ignore_cache) = @_;
 7765: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7766: 	my $fh;
 7767: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7768: 	    my @lines = <$fh>;
 7769: 	    &parse_domain_tab(\@lines);
 7770: 	}
 7771: 	close($fh);
 7772: 	$loaded = 1;
 7773:     }
 7774: 
 7775:     sub domain {
 7776: 	&load_domain_tab() if (!$loaded);
 7777: 
 7778: 	my ($name,$what) = @_;
 7779: 	return if ( !exists($domain{$name}) );
 7780: 
 7781: 	if (!$what) {
 7782: 	    return $domain{$name}{'description'};
 7783: 	}
 7784: 	return $domain{$name}{$what};
 7785:     }
 7786: }
 7787: 
 7788: 
 7789: # ------------------------------------------------------------- Read hosts file
 7790: {
 7791:     my %hostname;
 7792:     my %hostdom;
 7793:     my %libserv;
 7794:     my $loaded;
 7795: 
 7796:     sub parse_hosts_tab {
 7797: 	my ($file) = @_;
 7798: 	foreach my $configline (@$file) {
 7799: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7800: 	    next if ($configline =~ /^\^/);
 7801: 	    chomp($configline);
 7802: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7803: 	    $name=~s/\s//g;
 7804: 	    if ($id && $domain && $role && $name) {
 7805: 		$hostname{$id}=$name;
 7806: 		$hostdom{$id}=$domain;
 7807: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7808: 	    }
 7809: 	}
 7810:     }
 7811:     
 7812:     sub reset_hosts_info {
 7813: 	&reset_domain_info();
 7814: 	&reset_hosts_ip_info();
 7815: 	undef(%hostname);
 7816: 	undef(%hostdom);
 7817: 	undef(%libserv);
 7818: 	undef($loaded);
 7819:     }
 7820: 
 7821:     sub load_hosts_tab {
 7822: 	my ($ignore_cache) = @_;
 7823: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 7824: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7825: 	my @config = <$config>;
 7826: 	&parse_hosts_tab(\@config);
 7827: 	close($config);
 7828: 	$loaded=1;
 7829:     }
 7830: 
 7831:     sub hostname {
 7832: 	&load_hosts_tab() if (!$loaded);
 7833: 
 7834: 	my ($lonid) = @_;
 7835: 	return $hostname{$lonid};
 7836:     }
 7837: 
 7838:     sub all_hostnames {
 7839: 	&load_hosts_tab() if (!$loaded);
 7840: 
 7841: 	return %hostname;
 7842:     }
 7843: 
 7844:     sub is_library {
 7845: 	&load_hosts_tab() if (!$loaded);
 7846: 
 7847: 	return exists($libserv{$_[0]});
 7848:     }
 7849: 
 7850:     sub all_library {
 7851: 	&load_hosts_tab() if (!$loaded);
 7852: 
 7853: 	return %libserv;
 7854:     }
 7855: 
 7856:     sub get_servers {
 7857: 	&load_hosts_tab() if (!$loaded);
 7858: 
 7859: 	my ($domain,$type) = @_;
 7860: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7861: 	                                          : %hostname;
 7862: 	my %result;
 7863: 	if (ref($domain) eq 'ARRAY') {
 7864: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7865: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7866: 		    $result{$host} = $hostname;
 7867: 		}
 7868: 	    }
 7869: 	} else {
 7870: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7871: 		if ($hostdom{$host} eq $domain) {
 7872: 		    $result{$host} = $hostname;
 7873: 		}
 7874: 	    }
 7875: 	}
 7876: 	return %result;
 7877:     }
 7878: 
 7879:     sub host_domain {
 7880: 	&load_hosts_tab() if (!$loaded);
 7881: 
 7882: 	my ($lonid) = @_;
 7883: 	return $hostdom{$lonid};
 7884:     }
 7885: 
 7886:     sub all_domains {
 7887: 	&load_hosts_tab() if (!$loaded);
 7888: 
 7889: 	my %seen;
 7890: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7891: 	return @uniq;
 7892:     }
 7893: }
 7894: 
 7895: { 
 7896:     my %iphost;
 7897:     my %name_to_ip;
 7898:     my %lonid_to_ip;
 7899: 
 7900:     my %valid_ip;
 7901:     sub valid_ip {
 7902: 	my ($ip) = @_;
 7903: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
 7904: 	    return 1;	
 7905: 	}
 7906: 	my $name = gethostbyip($ip);
 7907: 	my $lonid = &hostname($name);
 7908: 	if (defined($lonid)) {
 7909: 	    $valid_ip{$ip} = $lonid;
 7910: 	    return 1;
 7911: 	}
 7912: 	my %iphosts = &get_iphost();
 7913: 	if (ref($iphost{$ip})) {
 7914: 	    return 1;	
 7915: 	}
 7916:     }
 7917: 
 7918:     sub get_hosts_from_ip {
 7919: 	my ($ip) = @_;
 7920: 	my %iphosts = &get_iphost();
 7921: 	if (ref($iphosts{$ip})) {
 7922: 	    return @{$iphosts{$ip}};
 7923: 	}
 7924: 	return;
 7925:     }
 7926:     
 7927:     sub reset_hosts_ip_info {
 7928: 	undef(%iphost);
 7929: 	undef(%name_to_ip);
 7930: 	undef(%lonid_to_ip);
 7931:     }
 7932: 
 7933:     sub get_host_ip {
 7934: 	my ($lonid) = @_;
 7935: 	if (exists($lonid_to_ip{$lonid})) {
 7936: 	    return $lonid_to_ip{$lonid};
 7937: 	}
 7938: 	my $name=&hostname($lonid);
 7939:    	my $ip = gethostbyname($name);
 7940: 	return if (!$ip || length($ip) ne 4);
 7941: 	$ip=inet_ntoa($ip);
 7942: 	$name_to_ip{$name}   = $ip;
 7943: 	$lonid_to_ip{$lonid} = $ip;
 7944: 	return $ip;
 7945:     }
 7946:     
 7947:     sub get_iphost {
 7948: 	my ($ignore_cache) = @_;
 7949: 	if (!$ignore_cache) {
 7950: 	    if (%iphost) {
 7951: 		return %iphost;
 7952: 	    }
 7953: 	    my ($ip_info,$cached)=
 7954: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 7955: 	    if ($cached) {
 7956: 		%iphost      = %{$ip_info->[0]};
 7957: 		%name_to_ip  = %{$ip_info->[1]};
 7958: 		%lonid_to_ip = %{$ip_info->[2]};
 7959: 		return %iphost;
 7960: 	    }
 7961: 	}
 7962: 	my %hostname = &all_hostnames();
 7963: 	foreach my $id (keys(%hostname)) {
 7964: 	    my $name=&hostname($id);
 7965: 	    my $ip;
 7966: 	    if (!exists($name_to_ip{$name})) {
 7967: 		$ip = gethostbyname($name);
 7968: 		if (!$ip || length($ip) ne 4) {
 7969: 		    &logthis("Skipping host $id name $name no IP found");
 7970: 		    next;
 7971: 		}
 7972: 		$ip=inet_ntoa($ip);
 7973: 		$name_to_ip{$name} = $ip;
 7974: 	    } else {
 7975: 		$ip = $name_to_ip{$name};
 7976: 	    }
 7977: 	    $lonid_to_ip{$id} = $ip;
 7978: 	    push(@{$iphost{$ip}},$id);
 7979: 	}
 7980: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 7981: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 7982: 				      24*60*60);
 7983: 
 7984: 	return %iphost;
 7985:     }
 7986: }
 7987: 
 7988: BEGIN {
 7989: 
 7990: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7991:     unless ($readit) {
 7992: {
 7993:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7994:     %perlvar = (%perlvar,%{$configvars});
 7995: }
 7996: 
 7997: 
 7998: # ------------------------------------------------------ Read spare server file
 7999: {
 8000:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8001: 
 8002:     while (my $configline=<$config>) {
 8003:        chomp($configline);
 8004:        if ($configline) {
 8005: 	   my ($host,$type) = split(':',$configline,2);
 8006: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8007: 	   push(@{ $spareid{$type} }, $host);
 8008:        }
 8009:     }
 8010:     close($config);
 8011: }
 8012: # ------------------------------------------------------------ Read permissions
 8013: {
 8014:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8015: 
 8016:     while (my $configline=<$config>) {
 8017: 	chomp($configline);
 8018: 	if ($configline) {
 8019: 	    my ($role,$perm)=split(/ /,$configline);
 8020: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8021: 	}
 8022:     }
 8023:     close($config);
 8024: }
 8025: 
 8026: # -------------------------------------------- Read plain texts for permissions
 8027: {
 8028:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8029: 
 8030:     while (my $configline=<$config>) {
 8031: 	chomp($configline);
 8032: 	if ($configline) {
 8033: 	    my ($short,@plain)=split(/:/,$configline);
 8034:             %{$prp{$short}} = ();
 8035: 	    if (@plain > 0) {
 8036:                 $prp{$short}{'std'} = $plain[0];
 8037:                 for (my $i=1; $i<@plain; $i++) {
 8038:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8039:                 }
 8040:             }
 8041: 	}
 8042:     }
 8043:     close($config);
 8044: }
 8045: 
 8046: # ---------------------------------------------------------- Read package table
 8047: {
 8048:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8049: 
 8050:     while (my $configline=<$config>) {
 8051: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8052: 	chomp($configline);
 8053: 	my ($short,$plain)=split(/:/,$configline);
 8054: 	my ($pack,$name)=split(/\&/,$short);
 8055: 	if ($plain ne '') {
 8056: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8057: 	    $packagetab{$short}=$plain; 
 8058: 	}
 8059:     }
 8060:     close($config);
 8061: }
 8062: 
 8063: # ------------- set up temporary directory
 8064: {
 8065:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8066: 
 8067: }
 8068: 
 8069: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8070: 				'compress_threshold'=> 20_000,
 8071:  			        });
 8072: 
 8073: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8074: $dumpcount=0;
 8075: 
 8076: &logtouch();
 8077: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8078: $readit=1;
 8079:     {
 8080: 	use integer;
 8081: 	my $test=(2**32)+1;
 8082: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8083: 	&logthis(" Detected 64bit platform ($_64bit)");
 8084:     }
 8085: }
 8086: }
 8087: 
 8088: 1;
 8089: __END__
 8090: 
 8091: =pod
 8092: 
 8093: =head1 NAME
 8094: 
 8095: Apache::lonnet - Subroutines to ask questions about things in the network.
 8096: 
 8097: =head1 SYNOPSIS
 8098: 
 8099: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8100: 
 8101:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8102: 
 8103: Common parameters:
 8104: 
 8105: =over 4
 8106: 
 8107: =item *
 8108: 
 8109: $uname : an internal username (if $cname expecting a course Id specifically)
 8110: 
 8111: =item *
 8112: 
 8113: $udom : a domain (if $cdom expecting a course's domain specifically)
 8114: 
 8115: =item *
 8116: 
 8117: $symb : a resource instance identifier
 8118: 
 8119: =item *
 8120: 
 8121: $namespace : the name of a .db file that contains the data needed or
 8122: being set.
 8123: 
 8124: =back
 8125: 
 8126: =head1 OVERVIEW
 8127: 
 8128: lonnet provides subroutines which interact with the
 8129: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8130: about classes, users, and resources.
 8131: 
 8132: For many of these objects you can also use this to store data about
 8133: them or modify them in various ways.
 8134: 
 8135: =head2 Symbs
 8136: 
 8137: To identify a specific instance of a resource, LON-CAPA uses symbols
 8138: or "symbs"X<symb>. These identifiers are built from the URL of the
 8139: map, the resource number of the resource in the map, and the URL of
 8140: the resource itself. The latter is somewhat redundant, but might help
 8141: if maps change.
 8142: 
 8143: An example is
 8144: 
 8145:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8146: 
 8147: The respective map entry is
 8148: 
 8149:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8150:   title="Problem 2">
 8151:  </resource>
 8152: 
 8153: Symbs are used by the random number generator, as well as to store and
 8154: restore data specific to a certain instance of for example a problem.
 8155: 
 8156: =head2 Storing And Retrieving Data
 8157: 
 8158: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8159: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8160: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8161: is is the non-critical message twin of cstore. These functions are for
 8162: handlers to store a perl hash to a user's permanent data space in an
 8163: easy manner, and to retrieve it again on another call. It is expected
 8164: that a handler would use this once at the beginning to retrieve data,
 8165: and then again once at the end to send only the new data back.
 8166: 
 8167: The data is stored in the user's data directory on the user's
 8168: homeserver under the ID of the course.
 8169: 
 8170: The hash that is returned by restore will have all of the previous
 8171: value for all of the elements of the hash.
 8172: 
 8173: Example:
 8174: 
 8175:  #creating a hash
 8176:  my %hash;
 8177:  $hash{'foo'}='bar';
 8178: 
 8179:  #storing it
 8180:  &Apache::lonnet::cstore(\%hash);
 8181: 
 8182:  #changing a value
 8183:  $hash{'foo'}='notbar';
 8184: 
 8185:  #adding a new value
 8186:  $hash{'bar'}='foo';
 8187:  &Apache::lonnet::cstore(\%hash);
 8188: 
 8189:  #retrieving the hash
 8190:  my %history=&Apache::lonnet::restore();
 8191: 
 8192:  #print the hash
 8193:  foreach my $key (sort(keys(%history))) {
 8194:    print("\%history{$key} = $history{$key}");
 8195:  }
 8196: 
 8197: Will print out:
 8198: 
 8199:  %history{1:foo} = bar
 8200:  %history{1:keys} = foo:timestamp
 8201:  %history{1:timestamp} = 990455579
 8202:  %history{2:bar} = foo
 8203:  %history{2:foo} = notbar
 8204:  %history{2:keys} = foo:bar:timestamp
 8205:  %history{2:timestamp} = 990455580
 8206:  %history{bar} = foo
 8207:  %history{foo} = notbar
 8208:  %history{timestamp} = 990455580
 8209:  %history{version} = 2
 8210: 
 8211: Note that the special hash entries C<keys>, C<version> and
 8212: C<timestamp> were added to the hash. C<version> will be equal to the
 8213: total number of versions of the data that have been stored. The
 8214: C<timestamp> attribute will be the UNIX time the hash was
 8215: stored. C<keys> is available in every historical section to list which
 8216: keys were added or changed at a specific historical revision of a
 8217: hash.
 8218: 
 8219: B<Warning>: do not store the hash that restore returns directly. This
 8220: will cause a mess since it will restore the historical keys as if the
 8221: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8222: 
 8223: Calling convention:
 8224: 
 8225:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8226:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8227: 
 8228: For more detailed information, see lonnet specific documentation.
 8229: 
 8230: =head1 RETURN MESSAGES
 8231: 
 8232: =over 4
 8233: 
 8234: =item * B<con_lost>: unable to contact remote host
 8235: 
 8236: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8237: when the connection is brought back up
 8238: 
 8239: =item * B<con_failed>: unable to contact remote host and unable to save message
 8240: for later delivery
 8241: 
 8242: =item * B<error:>: an error a occured, a description of the error follows the :
 8243: 
 8244: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8245: that was requested
 8246: 
 8247: =back
 8248: 
 8249: =head1 PUBLIC SUBROUTINES
 8250: 
 8251: =head2 Session Environment Functions
 8252: 
 8253: =over 4
 8254: 
 8255: =item * 
 8256: X<appenv()>
 8257: B<appenv(%hash)>: the value of %hash is written to
 8258: the user envirnoment file, and will be restored for each access this
 8259: user makes during this session, also modifies the %env for the current
 8260: process
 8261: 
 8262: =item *
 8263: X<delenv()>
 8264: B<delenv($regexp)>: removes all items from the session
 8265: environment file that matches the regular expression in $regexp. The
 8266: values are also delted from the current processes %env.
 8267: 
 8268: =item * get_env_multiple($name) 
 8269: 
 8270: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8271: values may be defined and end up as an array ref.
 8272: 
 8273: returns an array of values
 8274: 
 8275: =back
 8276: 
 8277: =head2 User Information
 8278: 
 8279: =over 4
 8280: 
 8281: =item *
 8282: X<queryauthenticate()>
 8283: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8284: authentication scheme
 8285: 
 8286: =item *
 8287: X<authenticate()>
 8288: B<authenticate($uname,$upass,$udom)>: try to
 8289: authenticate user from domain's lib servers (first use the current
 8290: one). C<$upass> should be the users password.
 8291: 
 8292: =item *
 8293: X<homeserver()>
 8294: B<homeserver($uname,$udom)>: find the server which has
 8295: the user's directory and files (there must be only one), this caches
 8296: the answer, and also caches if there is a borken connection.
 8297: 
 8298: =item *
 8299: X<idget()>
 8300: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8301: (IDs are a unique resource in a domain, there must be only 1 ID per
 8302: username, and only 1 username per ID in a specific domain) (returns
 8303: hash: id=>name,id=>name)
 8304: 
 8305: =item *
 8306: X<idrget()>
 8307: B<idrget($udom,@unames)>: find the IDs behind a list of
 8308: usernames (returns hash: name=>id,name=>id)
 8309: 
 8310: =item *
 8311: X<idput()>
 8312: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8313: 
 8314: =item *
 8315: X<rolesinit()>
 8316: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8317: 
 8318: =item *
 8319: X<getsection()>
 8320: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8321: course $cname, return section name/number or '' for "not in course"
 8322: and '-1' for "no section"
 8323: 
 8324: =item *
 8325: X<userenvironment()>
 8326: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8327: passed in @what from the requested user's environment, returns a hash
 8328: 
 8329: =item * 
 8330: X<userlog_query()>
 8331: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8332: activity.log file. %filters defines filters applied when parsing the
 8333: log file. These can be start or end timestamps, or the type of action
 8334: - log to look for Login or Logout events, check for Checkin or
 8335: Checkout, role for role selection. The response is in the form
 8336: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8337: escaped strings of the action recorded in the activity.log file.
 8338: 
 8339: =back
 8340: 
 8341: =head2 User Roles
 8342: 
 8343: =over 4
 8344: 
 8345: =item *
 8346: 
 8347: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8348:  F: full access
 8349:  U,I,K: authentication modes (cxx only)
 8350:  '': forbidden
 8351:  1: user needs to choose course
 8352:  2: browse allowed
 8353:  A: passphrase authentication needed
 8354: 
 8355: =item *
 8356: 
 8357: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8358: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8359: and course level
 8360: 
 8361: =item *
 8362: 
 8363: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8364: explanation of a user role term
 8365: 
 8366: =item *
 8367: 
 8368: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8369: All arguments are optional. Returns a hash of a roles, either for
 8370: co-author/assistant author roles for a user's Construction Space
 8371: (default), or if $context is 'user', roles for the user himself,
 8372: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8373: and value is set to colon-separated start and end times for the role.
 8374: If no username and domain are specified, will default to current
 8375: user/domain. Types, roles, and roledoms are references to arrays,
 8376: of role statuses (active, future or previous), roles 
 8377: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8378: to restrict the list of roles reported. If no array ref is 
 8379: provided for types, will default to return only active roles.
 8380: 
 8381: =back
 8382: 
 8383: =head2 User Modification
 8384: 
 8385: =over 4
 8386: 
 8387: =item *
 8388: 
 8389: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8390: user for the level given by URL.  Optional start and end dates (leave empty
 8391: string or zero for "no date")
 8392: 
 8393: =item *
 8394: 
 8395: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8396: change a users, password, possible return values are: ok,
 8397: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8398: refused
 8399: 
 8400: =item *
 8401: 
 8402: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8403: 
 8404: =item *
 8405: 
 8406: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8407: modify user
 8408: 
 8409: =item *
 8410: 
 8411: modifystudent
 8412: 
 8413: modify a students enrollment and identification information.
 8414: The course id is resolved based on the current users environment.  
 8415: This means the envoking user must be a course coordinator or otherwise
 8416: associated with a course.
 8417: 
 8418: This call is essentially a wrapper for lonnet::modifyuser and
 8419: lonnet::modify_student_enrollment
 8420: 
 8421: Inputs: 
 8422: 
 8423: =over 4
 8424: 
 8425: =item B<$udom> Students loncapa domain
 8426: 
 8427: =item B<$uname> Students loncapa login name
 8428: 
 8429: =item B<$uid> Students id/student number
 8430: 
 8431: =item B<$umode> Students authentication mode
 8432: 
 8433: =item B<$upass> Students password
 8434: 
 8435: =item B<$first> Students first name
 8436: 
 8437: =item B<$middle> Students middle name
 8438: 
 8439: =item B<$last> Students last name
 8440: 
 8441: =item B<$gene> Students generation
 8442: 
 8443: =item B<$usec> Students section in course
 8444: 
 8445: =item B<$end> Unix time of the roles expiration
 8446: 
 8447: =item B<$start> Unix time of the roles start date
 8448: 
 8449: =item B<$forceid> If defined, allow $uid to be changed
 8450: 
 8451: =item B<$desiredhome> server to use as home server for student
 8452: 
 8453: =back
 8454: 
 8455: =item *
 8456: 
 8457: modify_student_enrollment
 8458: 
 8459: Change a students enrollment status in a class.  The environment variable
 8460: 'role.request.course' must be defined for this function to proceed.
 8461: 
 8462: Inputs:
 8463: 
 8464: =over 4
 8465: 
 8466: =item $udom, students domain
 8467: 
 8468: =item $uname, students name
 8469: 
 8470: =item $uid, students user id
 8471: 
 8472: =item $first, students first name
 8473: 
 8474: =item $middle
 8475: 
 8476: =item $last
 8477: 
 8478: =item $gene
 8479: 
 8480: =item $usec
 8481: 
 8482: =item $end
 8483: 
 8484: =item $start
 8485: 
 8486: =back
 8487: 
 8488: 
 8489: =item *
 8490: 
 8491: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8492: custom role; give a custom role to a user for the level given by URL.  Specify
 8493: name and domain of role author, and role name
 8494: 
 8495: =item *
 8496: 
 8497: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8498: 
 8499: =item *
 8500: 
 8501: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8502: 
 8503: =back
 8504: 
 8505: =head2 Course Infomation
 8506: 
 8507: =over 4
 8508: 
 8509: =item *
 8510: 
 8511: coursedescription($courseid) : returns a hash of information about the
 8512: specified course id, including all environment settings for the
 8513: course, the description of the course will be in the hash under the
 8514: key 'description'
 8515: 
 8516: =item *
 8517: 
 8518: resdata($name,$domain,$type,@which) : request for current parameter
 8519: setting for a specific $type, where $type is either 'course' or 'user',
 8520: @what should be a list of parameters to ask about. This routine caches
 8521: answers for 5 minutes.
 8522: 
 8523: =back
 8524: 
 8525: =head2 Course Modification
 8526: 
 8527: =over 4
 8528: 
 8529: =item *
 8530: 
 8531: writecoursepref($courseid,%prefs) : write preferences (environment
 8532: database) for a course
 8533: 
 8534: =item *
 8535: 
 8536: createcourse($udom,$description,$url) : make/modify course
 8537: 
 8538: =back
 8539: 
 8540: =head2 Resource Subroutines
 8541: 
 8542: =over 4
 8543: 
 8544: =item *
 8545: 
 8546: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8547: 
 8548: =item *
 8549: 
 8550: repcopy($filename) : subscribes to the requested file, and attempts to
 8551: replicate from the owning library server, Might return
 8552: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8553: 'bad_request', also attempts to grab the metadata for the
 8554: resource. Expects the local filesystem pathname
 8555: (/home/httpd/html/res/....)
 8556: 
 8557: =back
 8558: 
 8559: =head2 Resource Information
 8560: 
 8561: =over 4
 8562: 
 8563: =item *
 8564: 
 8565: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8566: a vairety of different possible values, $varname should be a request
 8567: string, and the other parameters can be used to specify who and what
 8568: one is asking about.
 8569: 
 8570: Possible values for $varname are environment.lastname (or other item
 8571: from the envirnment hash), user.name (or someother aspect about the
 8572: user), resource.0.maxtries (or some other part and parameter of a
 8573: resource)
 8574: 
 8575: =item *
 8576: 
 8577: directcondval($number) : get current value of a condition; reads from a state
 8578: string
 8579: 
 8580: =item *
 8581: 
 8582: condval($condidx) : value of condition index based on state
 8583: 
 8584: =item *
 8585: 
 8586: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8587: resource's metadata, $what should be either a specific key, or either
 8588: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8589: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8590: 
 8591: this function automatically caches all requests
 8592: 
 8593: =item *
 8594: 
 8595: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8596: network of library servers; returns file handle of where SQL and regex results
 8597: will be stored for query
 8598: 
 8599: =item *
 8600: 
 8601: symbread($filename) : return symbolic list entry (filename argument optional);
 8602: returns the data handle
 8603: 
 8604: =item *
 8605: 
 8606: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8607: a possible symb for the URL in $thisfn, and if is an encryypted
 8608: resource that the user accessed using /enc/ returns a 1 on success, 0
 8609: on failure, user must be in a course, as it assumes the existance of
 8610: the course initial hash, and uses $env('request.course.id'}
 8611: 
 8612: 
 8613: =item *
 8614: 
 8615: symbclean($symb) : removes versions numbers from a symb, returns the
 8616: cleaned symb
 8617: 
 8618: =item *
 8619: 
 8620: is_on_map($uri) : checks if the $uri is somewhere on the current
 8621: course map, user must be in a course for it to work.
 8622: 
 8623: =item *
 8624: 
 8625: numval($salt) : return random seed value (addend for rndseed)
 8626: 
 8627: =item *
 8628: 
 8629: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8630: a random seed, all arguments are optional, if they aren't sent it uses the
 8631: environment to derive them. Note: if symb isn't sent and it can't get one
 8632: from &symbread it will use the current time as its return value
 8633: 
 8634: =item *
 8635: 
 8636: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8637: unfakeable, receipt
 8638: 
 8639: =item *
 8640: 
 8641: receipt() : API to ireceipt working off of env values; given out to users
 8642: 
 8643: =item *
 8644: 
 8645: countacc($url) : count the number of accesses to a given URL
 8646: 
 8647: =item *
 8648: 
 8649: 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
 8650: 
 8651: =item *
 8652: 
 8653: 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)
 8654: 
 8655: =item *
 8656: 
 8657: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8658: 
 8659: =item *
 8660: 
 8661: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8662: forcing spreadsheet to reevaluate the resource scores next time.
 8663: 
 8664: =back
 8665: 
 8666: =head2 Storing/Retreiving Data
 8667: 
 8668: =over 4
 8669: 
 8670: =item *
 8671: 
 8672: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8673: for this url; hashref needs to be given and should be a \%hashname; the
 8674: remaining args aren't required and if they aren't passed or are '' they will
 8675: be derived from the env
 8676: 
 8677: =item *
 8678: 
 8679: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8680: uses critical subroutine
 8681: 
 8682: =item *
 8683: 
 8684: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8685: all args are optional
 8686: 
 8687: =item *
 8688: 
 8689: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8690: dumps the complete (or key matching regexp) namespace into a hash
 8691: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8692: normally &store()ed into
 8693: 
 8694: $range should be either an integer '100' (give me the first 100
 8695:                                            matching records)
 8696:               or be  two integers sperated by a - with no spaces
 8697:                  '30-50' (give me the 30th through the 50th matching
 8698:                           records)
 8699: 
 8700: 
 8701: =item *
 8702: 
 8703: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8704: replaces a &store() version of data with a replacement set of data
 8705: for a particular resource in a namespace passed in the $storehash hash 
 8706: reference
 8707: 
 8708: =item *
 8709: 
 8710: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8711: works very similar to store/cstore, but all data is stored in a
 8712: temporary location and can be reset using tmpreset, $storehash should
 8713: be a hash reference, returns nothing on success
 8714: 
 8715: =item *
 8716: 
 8717: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8718: similar to restore, but all data is stored in a temporary location and
 8719: can be reset using tmpreset. Returns a hash of values on success,
 8720: error string otherwise.
 8721: 
 8722: =item *
 8723: 
 8724: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8725: deltes all keys for $symb form the temporary storage hash.
 8726: 
 8727: =item *
 8728: 
 8729: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8730: reference filled in from namesp ($udom and $uname are optional)
 8731: 
 8732: =item *
 8733: 
 8734: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8735: namesp ($udom and $uname are optional)
 8736: 
 8737: =item *
 8738: 
 8739: dump($namespace,$udom,$uname,$regexp,$range) : 
 8740: dumps the complete (or key matching regexp) namespace into a hash
 8741: ($udom, $uname, $regexp, $range are optional)
 8742: 
 8743: $range should be either an integer '100' (give me the first 100
 8744:                                            matching records)
 8745:               or be  two integers sperated by a - with no spaces
 8746:                  '30-50' (give me the 30th through the 50th matching
 8747:                           records)
 8748: =item *
 8749: 
 8750: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8751: $store can be a scalar, an array reference, or if the amount to be 
 8752: incremented is > 1, a hash reference.
 8753: 
 8754: ($udom and $uname are optional)
 8755: 
 8756: =item *
 8757: 
 8758: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8759: ($udom and $uname are optional)
 8760: 
 8761: =item *
 8762: 
 8763: cput($namespace,$storehash,$udom,$uname) : critical put
 8764: ($udom and $uname are optional)
 8765: 
 8766: =item *
 8767: 
 8768: newput($namespace,$storehash,$udom,$uname) :
 8769: 
 8770: Attempts to store the items in the $storehash, but only if they don't
 8771: currently exist, if this succeeds you can be certain that you have 
 8772: successfully created a new key value pair in the $namespace db.
 8773: 
 8774: 
 8775: Args:
 8776:  $namespace: name of database to store values to
 8777:  $storehash: hashref to store to the db
 8778:  $udom: (optional) domain of user containing the db
 8779:  $uname: (optional) name of user caontaining the db
 8780: 
 8781: Returns:
 8782:  'ok' -> succeeded in storing all keys of $storehash
 8783:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8784:                         least <key> already existed in the db (other
 8785:                         requested keys may also already exist)
 8786:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8787:  'con_lost' -> unable to contact request server
 8788:  'refused' -> action was not allowed by remote machine
 8789: 
 8790: 
 8791: =item *
 8792: 
 8793: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8794: reference filled in from namesp (encrypts the return communication)
 8795: ($udom and $uname are optional)
 8796: 
 8797: =item *
 8798: 
 8799: log($udom,$name,$home,$message) : write to permanent log for user; use
 8800: critical subroutine
 8801: 
 8802: =item *
 8803: 
 8804: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8805: array reference filled in from namespace found in domain level on either
 8806: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8807: 
 8808: =item *
 8809: 
 8810: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8811: domain level either on specified domain server ($uhome) or primary domain 
 8812: server ($udom and $uhome are optional)
 8813: 
 8814: =back
 8815: 
 8816: =head2 Network Status Functions
 8817: 
 8818: =over 4
 8819: 
 8820: =item *
 8821: 
 8822: dirlist($uri) : return directory list based on URI
 8823: 
 8824: =item *
 8825: 
 8826: spareserver() : find server with least workload from spare.tab
 8827: 
 8828: =back
 8829: 
 8830: =head2 Apache Request
 8831: 
 8832: =over 4
 8833: 
 8834: =item *
 8835: 
 8836: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8837: localhost, posts hash
 8838: 
 8839: =back
 8840: 
 8841: =head2 Data to String to Data
 8842: 
 8843: =over 4
 8844: 
 8845: =item *
 8846: 
 8847: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8848: and '&' separators, supports elements that are arrayrefs and hashrefs
 8849: 
 8850: =item *
 8851: 
 8852: hashref2str($hashref) : convert a hashref into a string complete with
 8853: escaping and '=' and '&' separators, supports elements that are
 8854: arrayrefs and hashrefs
 8855: 
 8856: =item *
 8857: 
 8858: arrayref2str($arrayref) : convert an arrayref into a string complete
 8859: with escaping and '&' separators, supports elements that are arrayrefs
 8860: and hashrefs
 8861: 
 8862: =item *
 8863: 
 8864: str2hash($string) : convert string to hash using unescaping and
 8865: splitting on '=' and '&', supports elements that are arrayrefs and
 8866: hashrefs
 8867: 
 8868: =item *
 8869: 
 8870: str2array($string) : convert string to hash using unescaping and
 8871: splitting on '&', supports elements that are arrayrefs and hashrefs
 8872: 
 8873: =back
 8874: 
 8875: =head2 Logging Routines
 8876: 
 8877: =over 4
 8878: 
 8879: These routines allow one to make log messages in the lonnet.log and
 8880: lonnet.perm logfiles.
 8881: 
 8882: =item *
 8883: 
 8884: logtouch() : make sure the logfile, lonnet.log, exists
 8885: 
 8886: =item *
 8887: 
 8888: logthis() : append message to the normal lonnet.log file, it gets
 8889: preiodically rolled over and deleted.
 8890: 
 8891: =item *
 8892: 
 8893: logperm() : append a permanent message to lonnet.perm.log, this log
 8894: file never gets deleted by any automated portion of the system, only
 8895: messages of critical importance should go in here.
 8896: 
 8897: =back
 8898: 
 8899: =head2 General File Helper Routines
 8900: 
 8901: =over 4
 8902: 
 8903: =item *
 8904: 
 8905: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8906: (a) files in /uploaded
 8907:   (i) If a local copy of the file exists - 
 8908:       compares modification date of local copy with last-modified date for 
 8909:       definitive version stored on home server for course. If local copy is 
 8910:       stale, requests a new version from the home server and stores it. 
 8911:       If the original has been removed from the home server, then local copy 
 8912:       is unlinked.
 8913:   (ii) If local copy does not exist -
 8914:       requests the file from the home server and stores it. 
 8915:   
 8916:   If $caller is 'uploadrep':  
 8917:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8918:     for request for files originally uploaded via DOCS. 
 8919:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8920:   
 8921:   Otherwise:
 8922:      This indicates a call from the content generation phase of the request.
 8923:      -  returns the entire contents of the file or -1.
 8924:      
 8925: (b) files in /res
 8926:    - returns the entire contents of a file or -1; 
 8927:    it properly subscribes to and replicates the file if neccessary.
 8928: 
 8929: 
 8930: =item *
 8931: 
 8932: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8933:                   reference
 8934: 
 8935: returns either a stat() list of data about the file or an empty list
 8936: if the file doesn't exist or couldn't find out about it (connection
 8937: problems or user unknown)
 8938: 
 8939: =item *
 8940: 
 8941: filelocation($dir,$file) : returns file system location of a file
 8942: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8943: directory that relative $file lookups are to looked in ($dir of /a/dir
 8944: and a file of ../bob will become /a/bob)
 8945: 
 8946: =item *
 8947: 
 8948: hreflocation($dir,$file) : returns file system location or a URL; same as
 8949: filelocation except for hrefs
 8950: 
 8951: =item *
 8952: 
 8953: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8954: 
 8955: =back
 8956: 
 8957: =head2 Usererfile file routines (/uploaded*)
 8958: 
 8959: =over 4
 8960: 
 8961: =item *
 8962: 
 8963: userfileupload(): main rotine for putting a file in a user or course's
 8964:                   filespace, arguments are,
 8965: 
 8966:  formname - required - this is the name of the element in $env where the
 8967:            filename, and the contents of the file to create/modifed exist
 8968:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8969:            contents of the file is located in $env{'form.'.$formname}
 8970:  coursedoc - if true, store the file in the course of the active role
 8971:              of the current user
 8972:  subdir - required - subdirectory to put the file in under ../userfiles/
 8973:          if undefined, it will be placed in "unknown"
 8974: 
 8975:  (This routine calls clean_filename() to remove any dangerous
 8976:  characters from the filename, and then calls finuserfileupload() to
 8977:  complete the transaction)
 8978: 
 8979:  returns either the url of the uploaded file (/uploaded/....) if successful
 8980:  and /adm/notfound.html if unsuccessful
 8981: 
 8982: =item *
 8983: 
 8984: clean_filename(): routine for cleaing a filename up for storage in
 8985:                  userfile space, argument is:
 8986: 
 8987:  filename - proposed filename
 8988: 
 8989: returns: the new clean filename
 8990: 
 8991: =item *
 8992: 
 8993: finishuserfileupload(): routine that creaes and sends the file to
 8994: userspace, probably shouldn't be called directly
 8995: 
 8996:   docuname: username or courseid of destination for the file
 8997:   docudom: domain of user/course of destination for the file
 8998:   formname: same as for userfileupload()
 8999:   fname: filename (inculding subdirectories) for the file
 9000: 
 9001:  returns either the url of the uploaded file (/uploaded/....) if successful
 9002:  and /adm/notfound.html if unsuccessful
 9003: 
 9004: =item *
 9005: 
 9006: renameuserfile(): renames an existing userfile to a new name
 9007: 
 9008:   Args:
 9009:    docuname: username or courseid of destination for the file
 9010:    docudom: domain of user/course of destination for the file
 9011:    old: current file name (including any subdirs under userfiles)
 9012:    new: desired file name (including any subdirs under userfiles)
 9013: 
 9014: =item *
 9015: 
 9016: mkdiruserfile(): creates a directory is a userfiles dir
 9017: 
 9018:   Args:
 9019:    docuname: username or courseid of destination for the file
 9020:    docudom: domain of user/course of destination for the file
 9021:    dir: dir to create (including any subdirs under userfiles)
 9022: 
 9023: =item *
 9024: 
 9025: removeuserfile(): removes a file that exists in userfiles
 9026: 
 9027:   Args:
 9028:    docuname: username or courseid of destination for the file
 9029:    docudom: domain of user/course of destination for the file
 9030:    fname: filname to delete (including any subdirs under userfiles)
 9031: 
 9032: =item *
 9033: 
 9034: removeuploadedurl(): convience function for removeuserfile()
 9035: 
 9036:   Args:
 9037:    url:  a full /uploaded/... url to delete
 9038: 
 9039: =item * 
 9040: 
 9041: get_portfile_permissions():
 9042:   Args:
 9043:     domain: domain of user or course contain the portfolio files
 9044:     user: name of user or num of course contain the portfolio files
 9045:   Returns:
 9046:     hashref of a dump of the proper file_permissions.db
 9047:    
 9048: 
 9049: =item * 
 9050: 
 9051: get_access_controls():
 9052: 
 9053: Args:
 9054:   current_permissions: the hash ref returned from get_portfile_permissions()
 9055:   group: (optional) the group you want the files associated with
 9056:   file: (optional) the file you want access info on
 9057: 
 9058: Returns:
 9059:     a hash (keys are file names) of hashes containing
 9060:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9061:         values are XML containing access control settings (see below) 
 9062: 
 9063: Internal notes:
 9064: 
 9065:  access controls are stored in file_permissions.db as key=value pairs.
 9066:     key -> path to file/file_name\0uniqueID:scope_end_start
 9067:         where scope -> public,guest,course,group,domains or users.
 9068:               end -> UNIX time for end of access (0 -> no end date)
 9069:               start -> UNIX time for start of access
 9070: 
 9071:     value -> XML description of access control
 9072:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9073:             <start></start>
 9074:             <end></end>
 9075: 
 9076:             <password></password>  for scope type = guest
 9077: 
 9078:             <domain></domain>     for scope type = course or group
 9079:             <number></number>
 9080:             <roles id="">
 9081:              <role></role>
 9082:              <access></access>
 9083:              <section></section>
 9084:              <group></group>
 9085:             </roles>
 9086: 
 9087:             <dom></dom>         for scope type = domains
 9088: 
 9089:             <users>             for scope type = users
 9090:              <user>
 9091:               <uname></uname>
 9092:               <udom></udom>
 9093:              </user>
 9094:             </users>
 9095:            </scope> 
 9096:               
 9097:  Access data is also aggregated for each file in an additional key=value pair:
 9098:  key -> path to file/file_name\0accesscontrol 
 9099:  value -> reference to hash
 9100:           hash contains key = value pairs
 9101:           where key = uniqueID:scope_end_start
 9102:                 value = UNIX time record was last updated
 9103: 
 9104:           Used to improve speed of look-ups of access controls for each file.  
 9105:  
 9106:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9107: 
 9108: modify_access_controls():
 9109: 
 9110: Modifies access controls for a portfolio file
 9111: Args
 9112: 1. file name
 9113: 2. reference to hash of required changes,
 9114: 3. domain
 9115: 4. username
 9116:   where domain,username are the domain of the portfolio owner 
 9117:   (either a user or a course) 
 9118: 
 9119: Returns:
 9120: 1. result of additions or updates ('ok' or 'error', with error message). 
 9121: 2. result of deletions ('ok' or 'error', with error message).
 9122: 3. reference to hash of any new or updated access controls.
 9123: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9124:    key = integer (inbound ID)
 9125:    value = uniqueID  
 9126: 
 9127: =back
 9128: 
 9129: =head2 HTTP Helper Routines
 9130: 
 9131: =over 4
 9132: 
 9133: =item *
 9134: 
 9135: escape() : unpack non-word characters into CGI-compatible hex codes
 9136: 
 9137: =item *
 9138: 
 9139: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9140: 
 9141: =back
 9142: 
 9143: =head1 PRIVATE SUBROUTINES
 9144: 
 9145: =head2 Underlying communication routines (Shouldn't call)
 9146: 
 9147: =over 4
 9148: 
 9149: =item *
 9150: 
 9151: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9152: 
 9153: =item *
 9154: 
 9155: reply() : uses subreply to send a message to remote machine, logs all failures
 9156: 
 9157: =item *
 9158: 
 9159: critical() : passes a critical message to another server; if cannot
 9160: get through then place message in connection buffer directory and
 9161: returns con_delayed, if incapable of saving message, returns
 9162: con_failed
 9163: 
 9164: =item *
 9165: 
 9166: reconlonc() : tries to reconnect lonc client processes.
 9167: 
 9168: =back
 9169: 
 9170: =head2 Resource Access Logging
 9171: 
 9172: =over 4
 9173: 
 9174: =item *
 9175: 
 9176: flushcourselogs() : flush (save) buffer logs and access logs
 9177: 
 9178: =item *
 9179: 
 9180: courselog($what) : save message for course in hash
 9181: 
 9182: =item *
 9183: 
 9184: courseacclog($what) : save message for course using &courselog().  Perform
 9185: special processing for specific resource types (problems, exams, quizzes, etc).
 9186: 
 9187: =item *
 9188: 
 9189: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9190: as a PerlChildExitHandler
 9191: 
 9192: =back
 9193: 
 9194: =head2 Other
 9195: 
 9196: =over 4
 9197: 
 9198: =item *
 9199: 
 9200: symblist($mapname,%newhash) : update symbolic storage links
 9201: 
 9202: =back
 9203: 
 9204: =cut

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