File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.871: download - view: text, annotated - select for diffs
Fri Apr 20 21:48:09 2007 UTC (17 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- switch to only making available as globals that which needs to be
- dns default was incorrectly defaulting to hosts.tab in both cases

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.871 2007/04/20 21:48:09 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:             $uhome eq '';
  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 %returnhash=();
  767:         my $i=0;
  768:         foreach my $item (@$storearr) {
  769:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  770:             $i++;
  771:         }
  772:         return %returnhash;
  773:     } else {
  774:         &logthis("get_dom failed - no homeserver and/or domain");
  775:     }
  776: }
  777: 
  778: # -------------------------------------------- put items in domain db files 
  779: 
  780: sub put_dom {
  781:     my ($namespace,$storehash,$udom,$uhome)=@_;
  782:     if (!$udom) {
  783:         $udom=$env{'user.domain'};
  784:         if (defined(&domain($udom,'primary'))) {
  785:             $uhome=&domain($udom,'primary');
  786:         } else {
  787:             $uhome eq '';
  788:         }
  789:     } else {
  790:         if (!$uhome) {
  791:             if (defined(&domain($udom,'primary'))) {
  792:                 $uhome=&domain($udom,'primary');
  793:             }
  794:         }
  795:     } 
  796:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  797:         my $items='';
  798:         foreach my $item (keys(%$storehash)) {
  799:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  800:         }
  801:         $items=~s/\&$//;
  802:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  803:     } else {
  804:         &logthis("put_dom failed - no homeserver and/or domain");
  805:     }
  806: }
  807: 
  808: sub retrieve_inst_usertypes {
  809:     my ($udom) = @_;
  810:     my (%returnhash,@order);
  811:     if (defined(&domain($udom,'primary'))) {
  812:         my $uhome=&domain($udom,'primary');
  813:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  814:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  815:         my @pairs=split(/\&/,$hashitems);
  816:         foreach my $item (@pairs) {
  817:             my ($key,$value)=split(/=/,$item,2);
  818:             $key = &unescape($key);
  819:             next if ($key =~ /^error: 2 /);
  820:             $returnhash{$key}=&thaw_unescape($value);
  821:         }
  822:         my @esc_order = split(/\&/,$orderitems);
  823:         foreach my $item (@esc_order) {
  824:             push(@order,&unescape($item));
  825:         }
  826:     } else {
  827:         &logthis("get_dom failed - no primary domain server for $udom");
  828:     }
  829:     return (\%returnhash,\@order);
  830: }
  831: 
  832: sub is_domainimage {
  833:     my ($url) = @_;
  834:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  835:         if (&domain($1) ne '') {
  836:             return '1';
  837:         }
  838:     }
  839:     return;
  840: }
  841: 
  842: # --------------------------------------------------- Assign a key to a student
  843: 
  844: sub assign_access_key {
  845: #
  846: # a valid key looks like uname:udom#comments
  847: # comments are being appended
  848: #
  849:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  850:     $kdom=
  851:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  852:     $knum=
  853:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  854:     $cdom=
  855:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  856:     $cnum=
  857:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  858:     $udom=$env{'user.name'} unless (defined($udom));
  859:     $uname=$env{'user.domain'} unless (defined($uname));
  860:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  861:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  862:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  863:                                                   # assigned to this person
  864:                                                   # - this should not happen,
  865:                                                   # unless something went wrong
  866:                                                   # the first time around
  867: # ready to assign
  868:         $logentry=$1.'; '.$logentry;
  869:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  870:                                                  $kdom,$knum) eq 'ok') {
  871: # key now belongs to user
  872: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  873:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  874:                 &appenv('environment.'.$envkey => $ckey);
  875:                 return 'ok';
  876:             } else {
  877:                 return 
  878:   'error: Count not permanently assign key, will need to be re-entered later.';
  879: 	    }
  880:         } else {
  881:             return 'error: Could not assign key, try again later.';
  882:         }
  883:     } elsif (!$existing{$ckey}) {
  884: # the key does not exist
  885: 	return 'error: The key does not exist';
  886:     } else {
  887: # the key is somebody else's
  888: 	return 'error: The key is already in use';
  889:     }
  890: }
  891: 
  892: # ------------------------------------------ put an additional comment on a key
  893: 
  894: sub comment_access_key {
  895: #
  896: # a valid key looks like uname:udom#comments
  897: # comments are being appended
  898: #
  899:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  900:     $cdom=
  901:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  902:     $cnum=
  903:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  904:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  905:     if ($existing{$ckey}) {
  906:         $existing{$ckey}.='; '.$logentry;
  907: # ready to assign
  908:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  909:                                                  $cdom,$cnum) eq 'ok') {
  910: 	    return 'ok';
  911:         } else {
  912: 	    return 'error: Count not store comment.';
  913:         }
  914:     } else {
  915: # the key does not exist
  916: 	return 'error: The key does not exist';
  917:     }
  918: }
  919: 
  920: # ------------------------------------------------------ Generate a set of keys
  921: 
  922: sub generate_access_keys {
  923:     my ($number,$cdom,$cnum,$logentry)=@_;
  924:     $cdom=
  925:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  926:     $cnum=
  927:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  928:     unless (&allowed('mky',$cdom)) { return 0; }
  929:     unless (($cdom) && ($cnum)) { return 0; }
  930:     if ($number>10000) { return 0; }
  931:     sleep(2); # make sure don't get same seed twice
  932:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  933:     my $total=0;
  934:     for (my $i=1;$i<=$number;$i++) {
  935:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  936:                   sprintf("%lx",int(100000*rand)).'-'.
  937:                   sprintf("%lx",int(100000*rand));
  938:        $newkey=~s/1/g/g; # folks mix up 1 and l
  939:        $newkey=~s/0/h/g; # and also 0 and O
  940:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  941:        if ($existing{$newkey}) {
  942:            $i--;
  943:        } else {
  944: 	  if (&put('accesskeys',
  945:               { $newkey => '# generated '.localtime().
  946:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  947:                            '; '.$logentry },
  948: 		   $cdom,$cnum) eq 'ok') {
  949:               $total++;
  950: 	  }
  951:        }
  952:     }
  953:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  954:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  955:     return $total;
  956: }
  957: 
  958: # ------------------------------------------------------- Validate an accesskey
  959: 
  960: sub validate_access_key {
  961:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  962:     $cdom=
  963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  964:     $cnum=
  965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  966:     $udom=$env{'user.domain'} unless (defined($udom));
  967:     $uname=$env{'user.name'} unless (defined($uname));
  968:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  969:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  970: }
  971: 
  972: # ------------------------------------- Find the section of student in a course
  973: sub devalidate_getsection_cache {
  974:     my ($udom,$unam,$courseid)=@_;
  975:     my $hashid="$udom:$unam:$courseid";
  976:     &devalidate_cache_new('getsection',$hashid);
  977: }
  978: 
  979: sub courseid_to_courseurl {
  980:     my ($courseid) = @_;
  981:     #already url style courseid
  982:     return $courseid if ($courseid =~ m{^/});
  983: 
  984:     if (exists($env{'course.'.$courseid.'.num'})) {
  985: 	my $cnum = $env{'course.'.$courseid.'.num'};
  986: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  987: 	return "/$cdom/$cnum";
  988:     }
  989: 
  990:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  991:     if (exists($courseinfo{'num'})) {
  992: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  993:     }
  994: 
  995:     return undef;
  996: }
  997: 
  998: sub getsection {
  999:     my ($udom,$unam,$courseid)=@_;
 1000:     my $cachetime=1800;
 1001: 
 1002:     my $hashid="$udom:$unam:$courseid";
 1003:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1004:     if (defined($cached)) { return $result; }
 1005: 
 1006:     my %Pending; 
 1007:     my %Expired;
 1008:     #
 1009:     # Each role can either have not started yet (pending), be active, 
 1010:     #    or have expired.
 1011:     #
 1012:     # If there is an active role, we are done.
 1013:     #
 1014:     # If there is more than one role which has not started yet, 
 1015:     #     choose the one which will start sooner
 1016:     # If there is one role which has not started yet, return it.
 1017:     #
 1018:     # If there is more than one expired role, choose the one which ended last.
 1019:     # If there is a role which has expired, return it.
 1020:     #
 1021:     $courseid = &courseid_to_courseurl($courseid);
 1022:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1023:     foreach my $key (keys(%roleshash)) {
 1024:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1025:         my $section=$1;
 1026:         if ($key eq $courseid.'_st') { $section=''; }
 1027:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1028:         my $now=time;
 1029:         if (defined($end) && $end && ($now > $end)) {
 1030:             $Expired{$end}=$section;
 1031:             next;
 1032:         }
 1033:         if (defined($start) && $start && ($now < $start)) {
 1034:             $Pending{$start}=$section;
 1035:             next;
 1036:         }
 1037:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1038:     }
 1039:     #
 1040:     # Presumedly there will be few matching roles from the above
 1041:     # loop and the sorting time will be negligible.
 1042:     if (scalar(keys(%Pending))) {
 1043:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1044:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1045:     } 
 1046:     if (scalar(keys(%Expired))) {
 1047:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1048:         my $time = pop(@sorted);
 1049:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1050:     }
 1051:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1052: }
 1053: 
 1054: sub save_cache {
 1055:     &purge_remembered();
 1056:     #&Apache::loncommon::validate_page();
 1057:     undef(%env);
 1058:     undef($env_loaded);
 1059: }
 1060: 
 1061: my $to_remember=-1;
 1062: my %remembered;
 1063: my %accessed;
 1064: my $kicks=0;
 1065: my $hits=0;
 1066: sub make_key {
 1067:     my ($name,$id) = @_;
 1068:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
 1069:     return &escape($name.':'.$id);
 1070: }
 1071: 
 1072: sub devalidate_cache_new {
 1073:     my ($name,$id,$debug) = @_;
 1074:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1075:     $id=&make_key($name,$id);
 1076:     $memcache->delete($id);
 1077:     delete($remembered{$id});
 1078:     delete($accessed{$id});
 1079: }
 1080: 
 1081: sub is_cached_new {
 1082:     my ($name,$id,$debug) = @_;
 1083:     $id=&make_key($name,$id);
 1084:     if (exists($remembered{$id})) {
 1085: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1086: 	$accessed{$id}=[&gettimeofday()];
 1087: 	$hits++;
 1088: 	return ($remembered{$id},1);
 1089:     }
 1090:     my $value = $memcache->get($id);
 1091:     if (!(defined($value))) {
 1092: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1093: 	return (undef,undef);
 1094:     }
 1095:     if ($value eq '__undef__') {
 1096: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1097: 	$value=undef;
 1098:     }
 1099:     &make_room($id,$value,$debug);
 1100:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1101:     return ($value,1);
 1102: }
 1103: 
 1104: sub do_cache_new {
 1105:     my ($name,$id,$value,$time,$debug) = @_;
 1106:     $id=&make_key($name,$id);
 1107:     my $setvalue=$value;
 1108:     if (!defined($setvalue)) {
 1109: 	$setvalue='__undef__';
 1110:     }
 1111:     if (!defined($time) ) {
 1112: 	$time=600;
 1113:     }
 1114:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1115:     $memcache->set($id,$setvalue,$time);
 1116:     # need to make a copy of $value
 1117:     #&make_room($id,$value,$debug);
 1118:     return $value;
 1119: }
 1120: 
 1121: sub make_room {
 1122:     my ($id,$value,$debug)=@_;
 1123:     $remembered{$id}=$value;
 1124:     if ($to_remember<0) { return; }
 1125:     $accessed{$id}=[&gettimeofday()];
 1126:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1127:     my $to_kick;
 1128:     my $max_time=0;
 1129:     foreach my $other (keys(%accessed)) {
 1130: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1131: 	    $to_kick=$other;
 1132: 	    $max_time=&tv_interval($accessed{$other});
 1133: 	}
 1134:     }
 1135:     delete($remembered{$to_kick});
 1136:     delete($accessed{$to_kick});
 1137:     $kicks++;
 1138:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1139:     return;
 1140: }
 1141: 
 1142: sub purge_remembered {
 1143:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1144:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1145:     undef(%remembered);
 1146:     undef(%accessed);
 1147: }
 1148: # ------------------------------------- Read an entry from a user's environment
 1149: 
 1150: sub userenvironment {
 1151:     my ($udom,$unam,@what)=@_;
 1152:     my %returnhash=();
 1153:     my @answer=split(/\&/,
 1154:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1155:                       &homeserver($unam,$udom)));
 1156:     my $i;
 1157:     for ($i=0;$i<=$#what;$i++) {
 1158: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1159:     }
 1160:     return %returnhash;
 1161: }
 1162: 
 1163: # ---------------------------------------------------------- Get a studentphoto
 1164: sub studentphoto {
 1165:     my ($udom,$unam,$ext) = @_;
 1166:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1167:     if (defined($env{'request.course.id'})) {
 1168:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1169:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1170:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1171:             } else {
 1172:                 my ($result,$perm_reqd)=
 1173: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1174:                 if ($result eq 'ok') {
 1175:                     if (!($perm_reqd eq 'yes')) {
 1176:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1177:                     }
 1178:                 }
 1179:             }
 1180:         }
 1181:     } else {
 1182:         my ($result,$perm_reqd) = 
 1183: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1184:         if ($result eq 'ok') {
 1185:             if (!($perm_reqd eq 'yes')) {
 1186:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1187:             }
 1188:         }
 1189:     }
 1190:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1191: }
 1192: 
 1193: sub retrievestudentphoto {
 1194:     my ($udom,$unam,$ext,$type) = @_;
 1195:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1196:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1197:     if ($ret eq 'ok') {
 1198:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1199:         if ($type eq 'thumbnail') {
 1200:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1201:         }
 1202:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1203:         return $tokenurl;
 1204:     } else {
 1205:         if ($type eq 'thumbnail') {
 1206:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1207:         } else { 
 1208:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1209:         }
 1210:     }
 1211: }
 1212: 
 1213: # -------------------------------------------------------------------- New chat
 1214: 
 1215: sub chatsend {
 1216:     my ($newentry,$anon,$group)=@_;
 1217:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1218:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1219:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1220:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1221: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1222: 		   &escape($newentry)).':'.$group,$chome);
 1223: }
 1224: 
 1225: # ------------------------------------------ Find current version of a resource
 1226: 
 1227: sub getversion {
 1228:     my $fname=&clutter(shift);
 1229:     unless ($fname=~/^\/res\//) { return -1; }
 1230:     return &currentversion(&filelocation('',$fname));
 1231: }
 1232: 
 1233: sub currentversion {
 1234:     my $fname=shift;
 1235:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1236:     if (defined($cached)) { return $result; }
 1237:     my $author=$fname;
 1238:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1239:     my ($udom,$uname)=split(/\//,$author);
 1240:     my $home=homeserver($uname,$udom);
 1241:     if ($home eq 'no_host') { 
 1242:         return -1; 
 1243:     }
 1244:     my $answer=reply("currentversion:$fname",$home);
 1245:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1246: 	return -1;
 1247:     }
 1248:     return &do_cache_new('resversion',$fname,$answer,600);
 1249: }
 1250: 
 1251: # ----------------------------- Subscribe to a resource, return URL if possible
 1252: 
 1253: sub subscribe {
 1254:     my $fname=shift;
 1255:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1256:     $fname=~s/[\n\r]//g;
 1257:     my $author=$fname;
 1258:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1259:     my ($udom,$uname)=split(/\//,$author);
 1260:     my $home=homeserver($uname,$udom);
 1261:     if ($home eq 'no_host') {
 1262:         return 'not_found';
 1263:     }
 1264:     my $answer=reply("sub:$fname",$home);
 1265:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1266: 	$answer.=' by '.$home;
 1267:     }
 1268:     return $answer;
 1269: }
 1270:     
 1271: # -------------------------------------------------------------- Replicate file
 1272: 
 1273: sub repcopy {
 1274:     my $filename=shift;
 1275:     $filename=~s/\/+/\//g;
 1276:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1277:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1278:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1279: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1280: 	return &repcopy_userfile($filename);
 1281:     }
 1282:     $filename=~s/[\n\r]//g;
 1283:     my $transname="$filename.in.transfer";
 1284: # FIXME: this should flock
 1285:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1286:     my $remoteurl=subscribe($filename);
 1287:     if ($remoteurl =~ /^con_lost by/) {
 1288: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1289:            return 'unavailable';
 1290:     } elsif ($remoteurl eq 'not_found') {
 1291: 	   #&logthis("Subscribe returned not_found: $filename");
 1292: 	   return 'not_found';
 1293:     } elsif ($remoteurl =~ /^rejected by/) {
 1294: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1295:            return 'forbidden';
 1296:     } elsif ($remoteurl eq 'directory') {
 1297:            return 'ok';
 1298:     } else {
 1299:         my $author=$filename;
 1300:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1301:         my ($udom,$uname)=split(/\//,$author);
 1302:         my $home=homeserver($uname,$udom);
 1303:         unless ($home eq $perlvar{'lonHostID'}) {
 1304:            my @parts=split(/\//,$filename);
 1305:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1306:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1307:                &logthis("Malconfiguration for replication: $filename");
 1308: 	       return 'bad_request';
 1309:            }
 1310:            my $count;
 1311:            for ($count=5;$count<$#parts;$count++) {
 1312:                $path.="/$parts[$count]";
 1313:                if ((-e $path)!=1) {
 1314: 		   mkdir($path,0777);
 1315:                }
 1316:            }
 1317:            my $ua=new LWP::UserAgent;
 1318:            my $request=new HTTP::Request('GET',"$remoteurl");
 1319:            my $response=$ua->request($request,$transname);
 1320:            if ($response->is_error()) {
 1321: 	       unlink($transname);
 1322:                my $message=$response->status_line;
 1323:                &logthis("<font color=\"blue\">WARNING:"
 1324:                        ." LWP get: $message: $filename</font>");
 1325:                return 'unavailable';
 1326:            } else {
 1327: 	       if ($remoteurl!~/\.meta$/) {
 1328:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1329:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1330:                   if ($mresponse->is_error()) {
 1331: 		      unlink($filename.'.meta');
 1332:                       &logthis(
 1333:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1334:                   }
 1335: 	       }
 1336:                rename($transname,$filename);
 1337:                return 'ok';
 1338:            }
 1339:        }
 1340:     }
 1341: }
 1342: 
 1343: # ------------------------------------------------ Get server side include body
 1344: sub ssi_body {
 1345:     my ($filelink,%form)=@_;
 1346:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1347:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1348:     }
 1349:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1350:                                      &ssi($filelink,%form));
 1351:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1352:     $output=~s/^.*?\<body[^\>]*\>//si;
 1353:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1354:     return $output;
 1355: }
 1356: 
 1357: # --------------------------------------------------------- Server Side Include
 1358: 
 1359: sub absolute_url {
 1360:     my ($host_name) = @_;
 1361:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1362:     if ($host_name eq '') {
 1363: 	$host_name = $ENV{'SERVER_NAME'};
 1364:     }
 1365:     return $protocol.$host_name;
 1366: }
 1367: 
 1368: sub ssi {
 1369: 
 1370:     my ($fn,%form)=@_;
 1371: 
 1372:     my $ua=new LWP::UserAgent;
 1373:     
 1374:     my $request;
 1375: 
 1376:     $form{'no_update_last_known'}=1;
 1377: 
 1378:     if (%form) {
 1379:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1380:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1381:     } else {
 1382:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1383:     }
 1384: 
 1385:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1386:     my $response=$ua->request($request);
 1387: 
 1388:     return $response->content;
 1389: }
 1390: 
 1391: sub externalssi {
 1392:     my ($url)=@_;
 1393:     my $ua=new LWP::UserAgent;
 1394:     my $request=new HTTP::Request('GET',$url);
 1395:     my $response=$ua->request($request);
 1396:     return $response->content;
 1397: }
 1398: 
 1399: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1400: 
 1401: sub allowuploaded {
 1402:     my ($srcurl,$url)=@_;
 1403:     $url=&clutter(&declutter($url));
 1404:     my $dir=$url;
 1405:     $dir=~s/\/[^\/]+$//;
 1406:     my %httpref=();
 1407:     my $httpurl=&hreflocation('',$url);
 1408:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1409:     &Apache::lonnet::appenv(%httpref);
 1410: }
 1411: 
 1412: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1413: # input: action, courseID, current domain, intended
 1414: #        path to file, source of file, instruction to parse file for objects,
 1415: #        ref to hash for embedded objects,
 1416: #        ref to hash for codebase of java objects.
 1417: #
 1418: # output: url to file (if action was uploaddoc), 
 1419: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1420: #
 1421: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1422: # course.
 1423: #
 1424: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1425: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1426: #          course's home server.
 1427: #
 1428: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1429: #          be copied from $source (current location) to 
 1430: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1431: #         and will then be copied to
 1432: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1433: #         course's home server.
 1434: #
 1435: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1436: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1437: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1438: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1439: #         in course's home server.
 1440: #
 1441: 
 1442: sub process_coursefile {
 1443:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1444:     my $fetchresult;
 1445:     my $home=&homeserver($docuname,$docudom);
 1446:     if ($action eq 'propagate') {
 1447:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1448: 			     $home);
 1449:     } else {
 1450:         my $fpath = '';
 1451:         my $fname = $file;
 1452:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1453:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1454:         my $filepath = &build_filepath($fpath);
 1455:         if ($action eq 'copy') {
 1456:             if ($source eq '') {
 1457:                 $fetchresult = 'no source file';
 1458:                 return $fetchresult;
 1459:             } else {
 1460:                 my $destination = $filepath.'/'.$fname;
 1461:                 rename($source,$destination);
 1462:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1463:                                  $home);
 1464:             }
 1465:         } elsif ($action eq 'uploaddoc') {
 1466:             open(my $fh,'>'.$filepath.'/'.$fname);
 1467:             print $fh $env{'form.'.$source};
 1468:             close($fh);
 1469:             if ($parser eq 'parse') {
 1470:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1471:                 unless ($parse_result eq 'ok') {
 1472:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1473:                 }
 1474:             }
 1475:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1476:                                  $home);
 1477:             if ($fetchresult eq 'ok') {
 1478:                 return '/uploaded/'.$fpath.'/'.$fname;
 1479:             } else {
 1480:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1481:                         ' to host '.$home.': '.$fetchresult);
 1482:                 return '/adm/notfound.html';
 1483:             }
 1484:         }
 1485:     }
 1486:     unless ( $fetchresult eq 'ok') {
 1487:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1488:              ' to host '.$home.': '.$fetchresult);
 1489:     }
 1490:     return $fetchresult;
 1491: }
 1492: 
 1493: sub build_filepath {
 1494:     my ($fpath) = @_;
 1495:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1496:     unless ($fpath eq '') {
 1497:         my @parts=split('/',$fpath);
 1498:         foreach my $part (@parts) {
 1499:             $filepath.= '/'.$part;
 1500:             if ((-e $filepath)!=1) {
 1501:                 mkdir($filepath,0777);
 1502:             }
 1503:         }
 1504:     }
 1505:     return $filepath;
 1506: }
 1507: 
 1508: sub store_edited_file {
 1509:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1510:     my $file = $primary_url;
 1511:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1512:     my $fpath = '';
 1513:     my $fname = $file;
 1514:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1515:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1516:     my $filepath = &build_filepath($fpath);
 1517:     open(my $fh,'>'.$filepath.'/'.$fname);
 1518:     print $fh $content;
 1519:     close($fh);
 1520:     my $home=&homeserver($docuname,$docudom);
 1521:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1522: 			  $home);
 1523:     if ($$fetchresult eq 'ok') {
 1524:         return '/uploaded/'.$fpath.'/'.$fname;
 1525:     } else {
 1526:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1527: 		 ' to host '.$home.': '.$$fetchresult);
 1528:         return '/adm/notfound.html';
 1529:     }
 1530: }
 1531: 
 1532: sub clean_filename {
 1533:     my ($fname,$args)=@_;
 1534: # Replace Windows backslashes by forward slashes
 1535:     $fname=~s/\\/\//g;
 1536:     if (!$args->{'keep_path'}) {
 1537:         # Get rid of everything but the actual filename
 1538: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1539:     }
 1540: # Replace spaces by underscores
 1541:     $fname=~s/\s+/\_/g;
 1542: # Replace all other weird characters by nothing
 1543:     $fname=~s{[^/\w\.\-]}{}g;
 1544: # Replace all .\d. sequences with _\d. so they no longer look like version
 1545: # numbers
 1546:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1547:     return $fname;
 1548: }
 1549: 
 1550: # --------------- Take an uploaded file and put it into the userfiles directory
 1551: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1552: #                    the desired filenam is in $env{"form.$formname.filename"}
 1553: #        $coursedoc - if true up to the current course
 1554: #                     if false
 1555: #        $subdir - directory in userfile to store the file into
 1556: #        $parser - instruction to parse file for objects ($parser = parse)    
 1557: #        $allfiles - reference to hash for embedded objects
 1558: #        $codebase - reference to hash for codebase of java objects
 1559: #        $desuname - username for permanent storage of uploaded file
 1560: #        $dsetudom - domain for permanaent storage of uploaded file
 1561: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1562: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1563: # 
 1564: # output: url of file in userspace, or error: <message> 
 1565: #             or /adm/notfound.html if failure to upload occurse
 1566: 
 1567: 
 1568: sub userfileupload {
 1569:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1570:         $destudom,$thumbwidth,$thumbheight)=@_;
 1571:     if (!defined($subdir)) { $subdir='unknown'; }
 1572:     my $fname=$env{'form.'.$formname.'.filename'};
 1573:     $fname=&clean_filename($fname);
 1574: # See if there is anything left
 1575:     unless ($fname) { return 'error: no uploaded file'; }
 1576:     chop($env{'form.'.$formname});
 1577:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1578:         my $now = time;
 1579:         my $filepath = 'tmp/helprequests/'.$now;
 1580:         my @parts=split(/\//,$filepath);
 1581:         my $fullpath = $perlvar{'lonDaemons'};
 1582:         for (my $i=0;$i<@parts;$i++) {
 1583:             $fullpath .= '/'.$parts[$i];
 1584:             if ((-e $fullpath)!=1) {
 1585:                 mkdir($fullpath,0777);
 1586:             }
 1587:         }
 1588:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1589:         print $fh $env{'form.'.$formname};
 1590:         close($fh);
 1591:         return $fullpath.'/'.$fname;
 1592:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1593:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1594:                        '_'.$env{'user.domain'}.'/pending';
 1595:         my @parts=split(/\//,$filepath);
 1596:         my $fullpath = $perlvar{'lonDaemons'};
 1597:         for (my $i=0;$i<@parts;$i++) {
 1598:             $fullpath .= '/'.$parts[$i];
 1599:             if ((-e $fullpath)!=1) {
 1600:                 mkdir($fullpath,0777);
 1601:             }
 1602:         }
 1603:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1604:         print $fh $env{'form.'.$formname};
 1605:         close($fh);
 1606:         return $fullpath.'/'.$fname;
 1607:     }
 1608:     
 1609: # Create the directory if not present
 1610:     $fname="$subdir/$fname";
 1611:     if ($coursedoc) {
 1612: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1613: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1614:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1615:             return &finishuserfileupload($docuname,$docudom,
 1616: 					 $formname,$fname,$parser,$allfiles,
 1617: 					 $codebase,$thumbwidth,$thumbheight);
 1618:         } else {
 1619:             $fname=$env{'form.folder'}.'/'.$fname;
 1620:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1621: 				       $fname,$formname,$parser,
 1622: 				       $allfiles,$codebase);
 1623:         }
 1624:     } elsif (defined($destuname)) {
 1625:         my $docuname=$destuname;
 1626:         my $docudom=$destudom;
 1627: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1628: 				     $parser,$allfiles,$codebase,
 1629:                                      $thumbwidth,$thumbheight);
 1630:         
 1631:     } else {
 1632:         my $docuname=$env{'user.name'};
 1633:         my $docudom=$env{'user.domain'};
 1634:         if (exists($env{'form.group'})) {
 1635:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1636:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1637:         }
 1638: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1639: 				     $parser,$allfiles,$codebase,
 1640:                                      $thumbwidth,$thumbheight);
 1641:     }
 1642: }
 1643: 
 1644: sub finishuserfileupload {
 1645:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1646:         $thumbwidth,$thumbheight) = @_;
 1647:     my $path=$docudom.'/'.$docuname.'/';
 1648:     my $filepath=$perlvar{'lonDocRoot'};
 1649:     my ($fnamepath,$file,$fetchthumb);
 1650:     $file=$fname;
 1651:     if ($fname=~m|/|) {
 1652:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1653: 	$path.=$fnamepath.'/';
 1654:     }
 1655:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1656:     my $count;
 1657:     for ($count=4;$count<=$#parts;$count++) {
 1658:         $filepath.="/$parts[$count]";
 1659:         if ((-e $filepath)!=1) {
 1660: 	    mkdir($filepath,0777);
 1661:         }
 1662:     }
 1663: # Save the file
 1664:     {
 1665: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1666: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1667: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1668: 	    return '/adm/notfound.html';
 1669: 	}
 1670: 	if (!print FH ($env{'form.'.$formname})) {
 1671: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1672: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1673: 	    return '/adm/notfound.html';
 1674: 	}
 1675: 	close(FH);
 1676:     }
 1677:     if ($parser eq 'parse') {
 1678:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1679: 						   $codebase);
 1680:         unless ($parse_result eq 'ok') {
 1681:             &logthis('Failed to parse '.$filepath.$file.
 1682: 		     ' for embedded media: '.$parse_result); 
 1683:         }
 1684:     }
 1685:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1686:         my $input = $filepath.'/'.$file;
 1687:         my $output = $filepath.'/'.'tn-'.$file;
 1688:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1689:         system("convert -sample $thumbsize $input $output");
 1690:         if (-e $filepath.'/'.'tn-'.$file) {
 1691:             $fetchthumb  = 1; 
 1692:         }
 1693:     }
 1694:  
 1695: # Notify homeserver to grep it
 1696: #
 1697:     my $docuhome=&homeserver($docuname,$docudom);
 1698:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1699:     if ($fetchresult eq 'ok') {
 1700:         if ($fetchthumb) {
 1701:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1702:             if ($thumbresult ne 'ok') {
 1703:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1704:                          $docuhome.': '.$thumbresult);
 1705:             }
 1706:         }
 1707: #
 1708: # Return the URL to it
 1709:         return '/uploaded/'.$path.$file;
 1710:     } else {
 1711:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1712: 		 ': '.$fetchresult);
 1713:         return '/adm/notfound.html';
 1714:     }
 1715: }
 1716: 
 1717: sub extract_embedded_items {
 1718:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1719:     my @state = ();
 1720:     my %javafiles = (
 1721:                       codebase => '',
 1722:                       code => '',
 1723:                       archive => ''
 1724:                     );
 1725:     my %mediafiles = (
 1726:                       src => '',
 1727:                       movie => '',
 1728:                      );
 1729:     my $p;
 1730:     if ($content) {
 1731:         $p = HTML::LCParser->new($content);
 1732:     } else {
 1733:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1734:     }
 1735:     while (my $t=$p->get_token()) {
 1736: 	if ($t->[0] eq 'S') {
 1737: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1738: 	    push (@state, $tagname);
 1739:             if (lc($tagname) eq 'allow') {
 1740:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1741:             }
 1742: 	    if (lc($tagname) eq 'img') {
 1743: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1744: 	    }
 1745:             if (lc($tagname) eq 'script') {
 1746:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1747:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1748:                 } else {
 1749:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1750:                 }
 1751:             }
 1752:             if (lc($tagname) eq 'link') {
 1753:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1754:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1755:                 }
 1756:             }
 1757: 	    if (lc($tagname) eq 'object' ||
 1758: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1759: 		foreach my $item (keys(%javafiles)) {
 1760: 		    $javafiles{$item} = '';
 1761: 		}
 1762: 	    }
 1763: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1764: 		my $name = lc($attr->{'name'});
 1765: 		foreach my $item (keys(%javafiles)) {
 1766: 		    if ($name eq $item) {
 1767: 			$javafiles{$item} = $attr->{'value'};
 1768: 			last;
 1769: 		    }
 1770: 		}
 1771: 		foreach my $item (keys(%mediafiles)) {
 1772: 		    if ($name eq $item) {
 1773: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1774: 			last;
 1775: 		    }
 1776: 		}
 1777: 	    }
 1778: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1779: 		foreach my $item (keys(%javafiles)) {
 1780: 		    if ($attr->{$item}) {
 1781: 			$javafiles{$item} = $attr->{$item};
 1782: 			last;
 1783: 		    }
 1784: 		}
 1785: 		foreach my $item (keys(%mediafiles)) {
 1786: 		    if ($attr->{$item}) {
 1787: 			&add_filetype($allfiles,$attr->{$item},$item);
 1788: 			last;
 1789: 		    }
 1790: 		}
 1791: 	    }
 1792: 	} elsif ($t->[0] eq 'E') {
 1793: 	    my ($tagname) = ($t->[1]);
 1794: 	    if ($javafiles{'codebase'} ne '') {
 1795: 		$javafiles{'codebase'} .= '/';
 1796: 	    }  
 1797: 	    if (lc($tagname) eq 'applet' ||
 1798: 		lc($tagname) eq 'object' ||
 1799: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1800: 		) {
 1801: 		foreach my $item (keys(%javafiles)) {
 1802: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1803: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1804: 			&add_filetype($allfiles,$file,$item);
 1805: 		    }
 1806: 		}
 1807: 	    } 
 1808: 	    pop @state;
 1809: 	}
 1810:     }
 1811:     return 'ok';
 1812: }
 1813: 
 1814: sub add_filetype {
 1815:     my ($allfiles,$file,$type)=@_;
 1816:     if (exists($allfiles->{$file})) {
 1817: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1818: 	    push(@{$allfiles->{$file}}, &escape($type));
 1819: 	}
 1820:     } else {
 1821: 	@{$allfiles->{$file}} = (&escape($type));
 1822:     }
 1823: }
 1824: 
 1825: sub removeuploadedurl {
 1826:     my ($url)=@_;
 1827:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1828:     return &removeuserfile($uname,$udom,$fname);
 1829: }
 1830: 
 1831: sub removeuserfile {
 1832:     my ($docuname,$docudom,$fname)=@_;
 1833:     my $home=&homeserver($docuname,$docudom);
 1834:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1835:     if ($result eq 'ok') {
 1836:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1837:             my $metafile = $fname.'.meta';
 1838:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1839: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1840:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1841:             my $sqlresult = 
 1842:                 &update_portfolio_table($docuname,$docudom,$file,
 1843:                                         'portfolio_metadata',$group,
 1844:                                         'delete');
 1845:         }
 1846:     }
 1847:     return $result;
 1848: }
 1849: 
 1850: sub mkdiruserfile {
 1851:     my ($docuname,$docudom,$dir)=@_;
 1852:     my $home=&homeserver($docuname,$docudom);
 1853:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1854: }
 1855: 
 1856: sub renameuserfile {
 1857:     my ($docuname,$docudom,$old,$new)=@_;
 1858:     my $home=&homeserver($docuname,$docudom);
 1859:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1860:                         &escape("$old").':'.&escape("$new"),$home);
 1861:     if ($result eq 'ok') {
 1862:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1863:             my $oldmeta = $old.'.meta';
 1864:             my $newmeta = $new.'.meta';
 1865:             my $metaresult = 
 1866:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1867: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1868:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1869:             my $sqlresult = 
 1870:                 &update_portfolio_table($docuname,$docudom,$file,
 1871:                                         'portfolio_metadata',$group,
 1872:                                         'delete');
 1873:         }
 1874:     }
 1875:     return $result;
 1876: }
 1877: 
 1878: # ------------------------------------------------------------------------- Log
 1879: 
 1880: sub log {
 1881:     my ($dom,$nam,$hom,$what)=@_;
 1882:     return critical("log:$dom:$nam:$what",$hom);
 1883: }
 1884: 
 1885: # ------------------------------------------------------------------ Course Log
 1886: #
 1887: # This routine flushes several buffers of non-mission-critical nature
 1888: #
 1889: 
 1890: sub flushcourselogs {
 1891:     &logthis('Flushing log buffers');
 1892: #
 1893: # course logs
 1894: # This is a log of all transactions in a course, which can be used
 1895: # for data mining purposes
 1896: #
 1897: # It also collects the courseid database, which lists last transaction
 1898: # times and course titles for all courseids
 1899: #
 1900:     my %courseidbuffer=();
 1901:     foreach my $crsid (keys %courselogs) {
 1902:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1903: 		          &escape($courselogs{$crsid}),
 1904: 		          $coursehombuf{$crsid}) eq 'ok') {
 1905: 	    delete $courselogs{$crsid};
 1906:         } else {
 1907:             &logthis('Failed to flush log buffer for '.$crsid);
 1908:             if (length($courselogs{$crsid})>40000) {
 1909:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1910:                         " exceeded maximum size, deleting.</font>");
 1911:                delete $courselogs{$crsid};
 1912:             }
 1913:         }
 1914:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1915:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1916: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1917:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1918:         } else {
 1919:            $courseidbuffer{$coursehombuf{$crsid}}=
 1920: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1921:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1922:         }
 1923:     }
 1924: #
 1925: # Write course id database (reverse lookup) to homeserver of courses 
 1926: # Is used in pickcourse
 1927: #
 1928:     foreach my $crs_home (keys(%courseidbuffer)) {
 1929:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1930: 		     $crs_home);
 1931:     }
 1932: #
 1933: # File accesses
 1934: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1935: #
 1936:     foreach my $entry (keys(%accesshash)) {
 1937:         if ($entry =~ /___count$/) {
 1938:             my ($dom,$name);
 1939:             ($dom,$name,undef)=
 1940: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1941:             if (! defined($dom) || $dom eq '' || 
 1942:                 ! defined($name) || $name eq '') {
 1943:                 my $cid = $env{'request.course.id'};
 1944:                 $dom  = $env{'request.'.$cid.'.domain'};
 1945:                 $name = $env{'request.'.$cid.'.num'};
 1946:             }
 1947:             my $value = $accesshash{$entry};
 1948:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1949:             my %temphash=($url => $value);
 1950:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1951:             if ($result eq 'ok') {
 1952:                 delete $accesshash{$entry};
 1953:             } elsif ($result eq 'unknown_cmd') {
 1954:                 # Target server has old code running on it.
 1955:                 my %temphash=($entry => $value);
 1956:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1957:                     delete $accesshash{$entry};
 1958:                 }
 1959:             }
 1960:         } else {
 1961:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1962:             my %temphash=($entry => $accesshash{$entry});
 1963:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1964:                 delete $accesshash{$entry};
 1965:             }
 1966:         }
 1967:     }
 1968: #
 1969: # Roles
 1970: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1971: #
 1972:     foreach my $entry (keys(%userrolehash)) {
 1973:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1974: 	    split(/\:/,$entry);
 1975:         if (&Apache::lonnet::put('nohist_userroles',
 1976:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1977:                 $rudom,$runame) eq 'ok') {
 1978: 	    delete $userrolehash{$entry};
 1979:         }
 1980:     }
 1981: #
 1982: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1983: #
 1984:     my %domrolebuffer = ();
 1985:     foreach my $entry (keys %domainrolehash) {
 1986:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1987:         if ($domrolebuffer{$rudom}) {
 1988:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1989:                       '='.&escape($domainrolehash{$entry});
 1990:         } else {
 1991:             $domrolebuffer{$rudom}.=&escape($entry).
 1992:                       '='.&escape($domainrolehash{$entry});
 1993:         }
 1994:         delete $domainrolehash{$entry};
 1995:     }
 1996:     foreach my $dom (keys(%domrolebuffer)) {
 1997: 	my %servers = &get_servers($dom,'library');
 1998: 	foreach my $tryserver (keys(%servers)) {
 1999: 	    unless (&reply('domroleput:'.$dom.':'.
 2000: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2001: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2002: 	    }
 2003:         }
 2004:     }
 2005:     $dumpcount++;
 2006: }
 2007: 
 2008: sub courselog {
 2009:     my $what=shift;
 2010:     $what=time.':'.$what;
 2011:     unless ($env{'request.course.id'}) { return ''; }
 2012:     $coursedombuf{$env{'request.course.id'}}=
 2013:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2014:     $coursenumbuf{$env{'request.course.id'}}=
 2015:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2016:     $coursehombuf{$env{'request.course.id'}}=
 2017:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2018:     $coursedescrbuf{$env{'request.course.id'}}=
 2019:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2020:     $courseinstcodebuf{$env{'request.course.id'}}=
 2021:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2022:     $courseownerbuf{$env{'request.course.id'}}=
 2023:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2024:     $coursetypebuf{$env{'request.course.id'}}=
 2025:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2026:     if (defined $courselogs{$env{'request.course.id'}}) {
 2027: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2028:     } else {
 2029: 	$courselogs{$env{'request.course.id'}}.=$what;
 2030:     }
 2031:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2032: 	&flushcourselogs();
 2033:     }
 2034: }
 2035: 
 2036: sub courseacclog {
 2037:     my $fnsymb=shift;
 2038:     unless ($env{'request.course.id'}) { return ''; }
 2039:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2040:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2041:         $what.=':POST';
 2042:         # FIXME: Probably ought to escape things....
 2043: 	foreach my $key (keys(%env)) {
 2044:             if ($key=~/^form\.(.*)/) {
 2045: 		$what.=':'.$1.'='.$env{$key};
 2046:             }
 2047:         }
 2048:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2049:         # FIXME: We should not be depending on a form parameter that someone
 2050:         # editing lonsearchcat.pm might change in the future.
 2051:         if ($env{'form.phase'} eq 'course_search') {
 2052:             $what.= ':POST';
 2053:             # FIXME: Probably ought to escape things....
 2054:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2055:                                  'crsdiscuss') {
 2056:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2057:             }
 2058:         }
 2059:     }
 2060:     &courselog($what);
 2061: }
 2062: 
 2063: sub countacc {
 2064:     my $url=&declutter(shift);
 2065:     return if (! defined($url) || $url eq '');
 2066:     unless ($env{'request.course.id'}) { return ''; }
 2067:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2068:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2069:     $accesshash{$key}++;
 2070: }
 2071: 
 2072: sub linklog {
 2073:     my ($from,$to)=@_;
 2074:     $from=&declutter($from);
 2075:     $to=&declutter($to);
 2076:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2077:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2078: }
 2079:   
 2080: sub userrolelog {
 2081:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2082:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2083:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2084:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2085:         ($trole=~/^ta/)) {
 2086:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2087:        $userrolehash
 2088:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2089:                     =$tend.':'.$tstart;
 2090:     }
 2091:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2092:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2093:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2094:         ($trole=~/^sc/)) {
 2095:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2096:        $domainrolehash
 2097:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2098:                     = $tend.':'.$tstart;
 2099:     }
 2100: }
 2101: 
 2102: sub get_course_adv_roles {
 2103:     my $cid=shift;
 2104:     $cid=$env{'request.course.id'} unless (defined($cid));
 2105:     my %coursehash=&coursedescription($cid);
 2106:     my %nothide=();
 2107:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2108: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2109:     }
 2110:     my %returnhash=();
 2111:     my %dumphash=
 2112:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2113:     my $now=time;
 2114:     foreach my $entry (keys %dumphash) {
 2115: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2116:         if (($tstart) && ($tstart<0)) { next; }
 2117:         if (($tend) && ($tend<$now)) { next; }
 2118:         if (($tstart) && ($now<$tstart)) { next; }
 2119:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2120: 	if ($username eq '' || $domain eq '') { next; }
 2121: 	if ((&privileged($username,$domain)) && 
 2122: 	    (!$nothide{$username.':'.$domain})) { next; }
 2123: 	if ($role eq 'cr') { next; }
 2124:         my $key=&plaintext($role);
 2125:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2126:         if ($returnhash{$key}) {
 2127: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2128:         } else {
 2129:             $returnhash{$key}=$username.':'.$domain;
 2130:         }
 2131:      }
 2132:     return %returnhash;
 2133: }
 2134: 
 2135: sub get_my_roles {
 2136:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2137:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2138:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2139:     my %dumphash;
 2140:     if ($context eq 'userroles') { 
 2141:         %dumphash = &dump('roles',$udom,$uname);
 2142:     } else {
 2143:         %dumphash=
 2144:             &dump('nohist_userroles',$udom,$uname);
 2145:     }
 2146:     my %returnhash=();
 2147:     my $now=time;
 2148:     foreach my $entry (keys(%dumphash)) {
 2149:         my ($role,$tend,$tstart);
 2150:         if ($context eq 'userroles') {
 2151: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2152:         } else {
 2153:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2154:         }
 2155:         if (($tstart) && ($tstart<0)) { next; }
 2156:         my $status = 'active';
 2157:         if (($tend) && ($tend<$now)) {
 2158:             $status = 'previous';
 2159:         } 
 2160:         if (($tstart) && ($now<$tstart)) {
 2161:             $status = 'future';
 2162:         }
 2163:         if (ref($types) eq 'ARRAY') {
 2164:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2165:                 next;
 2166:             } 
 2167:         } else {
 2168:             if ($status ne 'active') {
 2169:                 next;
 2170:             }
 2171:         }
 2172:         my ($rolecode,$username,$domain,$section,$area);
 2173:         if ($context eq 'userroles') {
 2174:             ($area,$rolecode) = split(/_/,$entry);
 2175:             (undef,$domain,$username,$section) = split(/\//,$area);
 2176:         } else {
 2177:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2178:         }
 2179:         if (ref($roledoms) eq 'ARRAY') {
 2180:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2181:                 next;
 2182:             }
 2183:         }
 2184:         if (ref($roles) eq 'ARRAY') {
 2185:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2186:                 next;
 2187:             }
 2188:         }
 2189: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2190:     }
 2191:     return %returnhash;
 2192: }
 2193: 
 2194: # ----------------------------------------------------- Frontpage Announcements
 2195: #
 2196: #
 2197: 
 2198: sub postannounce {
 2199:     my ($server,$text)=@_;
 2200:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2201:     unless ($text=~/\w/) { $text=''; }
 2202:     return &reply('setannounce:'.&escape($text),$server);
 2203: }
 2204: 
 2205: sub getannounce {
 2206: 
 2207:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2208: 	my $announcement='';
 2209: 	while (my $line = <$fh>) { $announcement .= $line; }
 2210: 	close($fh);
 2211: 	if ($announcement=~/\w/) { 
 2212: 	    return 
 2213:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2214:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2215: 	} else {
 2216: 	    return '';
 2217: 	}
 2218:     } else {
 2219: 	return '';
 2220:     }
 2221: }
 2222: 
 2223: # ---------------------------------------------------------- Course ID routines
 2224: # Deal with domain's nohist_courseid.db files
 2225: #
 2226: 
 2227: sub courseidput {
 2228:     my ($domain,$what,$coursehome)=@_;
 2229:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2230: }
 2231: 
 2232: sub courseiddump {
 2233:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2234:     my %returnhash=();
 2235:     unless ($domfilter) { $domfilter=''; }
 2236:     my %libserv = &all_library();
 2237:     foreach my $tryserver (keys(%libserv)) {
 2238:         if ( (  $hostidflag == 1 
 2239: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2240: 	     || (!defined($hostidflag)) ) {
 2241: 
 2242: 	    if ($domfilter eq ''
 2243: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2244: 	        foreach my $line (
 2245:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2246: 			       $sincefilter.':'.&escape($descfilter).':'.
 2247:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2248:                                $tryserver))) {
 2249: 		    my ($key,$value)=split(/\=/,$line,2);
 2250:                     if (($key) && ($value)) {
 2251: 		        $returnhash{&unescape($key)}=$value;
 2252:                     }
 2253:                 }
 2254:             }
 2255:         }
 2256:     }
 2257:     return %returnhash;
 2258: }
 2259: 
 2260: # ---------------------------------------------------------- DC e-mail
 2261: 
 2262: sub dcmailput {
 2263:     my ($domain,$msgid,$message,$server)=@_;
 2264:     my $status = &Apache::lonnet::critical(
 2265:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2266:        &escape($message),$server);
 2267:     return $status;
 2268: }
 2269: 
 2270: sub dcmaildump {
 2271:     my ($dom,$startdate,$enddate,$senders) = @_;
 2272:     my %returnhash=();
 2273: 
 2274:     if (defined(&domain($dom,'primary'))) {
 2275:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2276:                                                          &escape($enddate).':';
 2277: 	my @esc_senders=map { &escape($_)} @$senders;
 2278: 	$cmd.=&escape(join('&',@esc_senders));
 2279: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2280:             my ($key,$value) = split(/\=/,$line,2);
 2281:             if (($key) && ($value)) {
 2282:                 $returnhash{&unescape($key)} = &unescape($value);
 2283:             }
 2284:         }
 2285:     }
 2286:     return %returnhash;
 2287: }
 2288: # ---------------------------------------------------------- Domain roles
 2289: 
 2290: sub get_domain_roles {
 2291:     my ($dom,$roles,$startdate,$enddate)=@_;
 2292:     if (undef($startdate) || $startdate eq '') {
 2293:         $startdate = '.';
 2294:     }
 2295:     if (undef($enddate) || $enddate eq '') {
 2296:         $enddate = '.';
 2297:     }
 2298:     my $rolelist = join(':',@{$roles});
 2299:     my %personnel = ();
 2300: 
 2301:     my %servers = &get_servers($dom,'library');
 2302:     foreach my $tryserver (keys(%servers)) {
 2303: 	%{$personnel{$tryserver}}=();
 2304: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2305: 					    &escape($startdate).':'.
 2306: 					    &escape($enddate).':'.
 2307: 					    &escape($rolelist), $tryserver))) {
 2308: 	    my ($key,$value) = split(/\=/,$line,2);
 2309: 	    if (($key) && ($value)) {
 2310: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2311: 	    }
 2312: 	}
 2313:     }
 2314:     return %personnel;
 2315: }
 2316: 
 2317: # ----------------------------------------------------------- Check out an item
 2318: 
 2319: sub get_first_access {
 2320:     my ($type,$argsymb)=@_;
 2321:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2322:     if ($argsymb) { $symb=$argsymb; }
 2323:     my ($map,$id,$res)=&decode_symb($symb);
 2324:     if ($type eq 'map') {
 2325: 	$res=&symbread($map);
 2326:     } else {
 2327: 	$res=$symb;
 2328:     }
 2329:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2330:     return $times{"$courseid\0$res"};
 2331: }
 2332: 
 2333: sub set_first_access {
 2334:     my ($type)=@_;
 2335:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2336:     my ($map,$id,$res)=&decode_symb($symb);
 2337:     if ($type eq 'map') {
 2338: 	$res=&symbread($map);
 2339:     } else {
 2340: 	$res=$symb;
 2341:     }
 2342:     my $firstaccess=&get_first_access($type,$symb);
 2343:     if (!$firstaccess) {
 2344: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2345:     }
 2346:     return 'already_set';
 2347: }
 2348: 
 2349: sub checkout {
 2350:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2351:     my $now=time;
 2352:     my $lonhost=$perlvar{'lonHostID'};
 2353:     my $infostr=&escape(
 2354:                  'CHECKOUTTOKEN&'.
 2355:                  $tuname.'&'.
 2356:                  $tudom.'&'.
 2357:                  $tcrsid.'&'.
 2358:                  $symb.'&'.
 2359: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2360:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2361:     if ($token=~/^error\:/) { 
 2362:         &logthis("<font color=\"blue\">WARNING: ".
 2363:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2364:                  "</font>");
 2365:         return ''; 
 2366:     }
 2367: 
 2368:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2369:     $token=~tr/a-z/A-Z/;
 2370: 
 2371:     my %infohash=('resource.0.outtoken' => $token,
 2372:                   'resource.0.checkouttime' => $now,
 2373:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2374: 
 2375:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2376:        return '';
 2377:     } else {
 2378:         &logthis("<font color=\"blue\">WARNING: ".
 2379:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2380:                  "</font>");
 2381:     }    
 2382: 
 2383:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2384:                          &escape('Checkout '.$infostr.' - '.
 2385:                                                  $token)) ne 'ok') {
 2386: 	return '';
 2387:     } else {
 2388:         &logthis("<font color=\"blue\">WARNING: ".
 2389:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2390:                  "</font>");
 2391:     }
 2392:     return $token;
 2393: }
 2394: 
 2395: # ------------------------------------------------------------ Check in an item
 2396: 
 2397: sub checkin {
 2398:     my $token=shift;
 2399:     my $now=time;
 2400:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2401:     $lonhost=~tr/A-Z/a-z/;
 2402:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2403:     $dtoken=~s/\W/\_/g;
 2404:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2405:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2406: 
 2407:     unless (($tuname) && ($tudom)) {
 2408:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2409:         return '';
 2410:     }
 2411:     
 2412:     unless (&allowed('mgr',$tcrsid)) {
 2413:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2414:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2415:         return '';
 2416:     }
 2417: 
 2418:     my %infohash=('resource.0.intoken' => $token,
 2419:                   'resource.0.checkintime' => $now,
 2420:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2421: 
 2422:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2423:        return '';
 2424:     }    
 2425: 
 2426:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2427:                          &escape('Checkin - '.$token)) ne 'ok') {
 2428: 	return '';
 2429:     }
 2430: 
 2431:     return ($symb,$tuname,$tudom,$tcrsid);    
 2432: }
 2433: 
 2434: # --------------------------------------------- Set Expire Date for Spreadsheet
 2435: 
 2436: sub expirespread {
 2437:     my ($uname,$udom,$stype,$usymb)=@_;
 2438:     my $cid=$env{'request.course.id'}; 
 2439:     if ($cid) {
 2440:        my $now=time;
 2441:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2442:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2443:                             $env{'course.'.$cid.'.num'}.
 2444: 	        	    ':nohist_expirationdates:'.
 2445:                             &escape($key).'='.$now,
 2446:                             $env{'course.'.$cid.'.home'})
 2447:     }
 2448:     return 'ok';
 2449: }
 2450: 
 2451: # ----------------------------------------------------- Devalidate Spreadsheets
 2452: 
 2453: sub devalidate {
 2454:     my ($symb,$uname,$udom)=@_;
 2455:     my $cid=$env{'request.course.id'}; 
 2456:     if ($cid) {
 2457:         # delete the stored spreadsheets for
 2458:         # - the student level sheet of this user in course's homespace
 2459:         # - the assessment level sheet for this resource 
 2460:         #   for this user in user's homespace
 2461: 	# - current conditional state info
 2462: 	my $key=$uname.':'.$udom.':';
 2463:         my $status=
 2464: 	    &del('nohist_calculatedsheets',
 2465: 		 [$key.'studentcalc:'],
 2466: 		 $env{'course.'.$cid.'.domain'},
 2467: 		 $env{'course.'.$cid.'.num'})
 2468: 		.' '.
 2469: 	    &del('nohist_calculatedsheets_'.$cid,
 2470: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2471:         unless ($status eq 'ok ok') {
 2472:            &logthis('Could not devalidate spreadsheet '.
 2473:                     $uname.' at '.$udom.' for '.
 2474: 		    $symb.': '.$status);
 2475:         }
 2476: 	&delenv('user.state.'.$cid);
 2477:     }
 2478: }
 2479: 
 2480: sub get_scalar {
 2481:     my ($string,$end) = @_;
 2482:     my $value;
 2483:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2484: 	$value = $1;
 2485:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2486: 	$value = $1;
 2487:     }
 2488:     return &unescape($value);
 2489: }
 2490: 
 2491: sub array2str {
 2492:   my (@array) = @_;
 2493:   my $result=&arrayref2str(\@array);
 2494:   $result=~s/^__ARRAY_REF__//;
 2495:   $result=~s/__END_ARRAY_REF__$//;
 2496:   return $result;
 2497: }
 2498: 
 2499: sub arrayref2str {
 2500:   my ($arrayref) = @_;
 2501:   my $result='__ARRAY_REF__';
 2502:   foreach my $elem (@$arrayref) {
 2503:     if(ref($elem) eq 'ARRAY') {
 2504:       $result.=&arrayref2str($elem).'&';
 2505:     } elsif(ref($elem) eq 'HASH') {
 2506:       $result.=&hashref2str($elem).'&';
 2507:     } elsif(ref($elem)) {
 2508:       #print("Got a ref of ".(ref($elem))." skipping.");
 2509:     } else {
 2510:       $result.=&escape($elem).'&';
 2511:     }
 2512:   }
 2513:   $result=~s/\&$//;
 2514:   $result .= '__END_ARRAY_REF__';
 2515:   return $result;
 2516: }
 2517: 
 2518: sub hash2str {
 2519:   my (%hash) = @_;
 2520:   my $result=&hashref2str(\%hash);
 2521:   $result=~s/^__HASH_REF__//;
 2522:   $result=~s/__END_HASH_REF__$//;
 2523:   return $result;
 2524: }
 2525: 
 2526: sub hashref2str {
 2527:   my ($hashref)=@_;
 2528:   my $result='__HASH_REF__';
 2529:   foreach my $key (sort(keys(%$hashref))) {
 2530:     if (ref($key) eq 'ARRAY') {
 2531:       $result.=&arrayref2str($key).'=';
 2532:     } elsif (ref($key) eq 'HASH') {
 2533:       $result.=&hashref2str($key).'=';
 2534:     } elsif (ref($key)) {
 2535:       $result.='=';
 2536:       #print("Got a ref of ".(ref($key))." skipping.");
 2537:     } else {
 2538: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2539:     }
 2540: 
 2541:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2542:       $result.=&arrayref2str($hashref->{$key}).'&';
 2543:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2544:       $result.=&hashref2str($hashref->{$key}).'&';
 2545:     } elsif(ref($hashref->{$key})) {
 2546:        $result.='&';
 2547:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2548:     } else {
 2549:       $result.=&escape($hashref->{$key}).'&';
 2550:     }
 2551:   }
 2552:   $result=~s/\&$//;
 2553:   $result .= '__END_HASH_REF__';
 2554:   return $result;
 2555: }
 2556: 
 2557: sub str2hash {
 2558:     my ($string)=@_;
 2559:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2560:     return %$hash;
 2561: }
 2562: 
 2563: sub str2hashref {
 2564:   my ($string) = @_;
 2565: 
 2566:   my %hash;
 2567: 
 2568:   if($string !~ /^__HASH_REF__/) {
 2569:       if (! ($string eq '' || !defined($string))) {
 2570: 	  $hash{'error'}='Not hash reference';
 2571:       }
 2572:       return (\%hash, $string);
 2573:   }
 2574: 
 2575:   $string =~ s/^__HASH_REF__//;
 2576: 
 2577:   while($string !~ /^__END_HASH_REF__/) {
 2578:       #key
 2579:       my $key='';
 2580:       if($string =~ /^__HASH_REF__/) {
 2581:           ($key, $string)=&str2hashref($string);
 2582:           if(defined($key->{'error'})) {
 2583:               $hash{'error'}='Bad data';
 2584:               return (\%hash, $string);
 2585:           }
 2586:       } elsif($string =~ /^__ARRAY_REF__/) {
 2587:           ($key, $string)=&str2arrayref($string);
 2588:           if($key->[0] eq 'Array reference error') {
 2589:               $hash{'error'}='Bad data';
 2590:               return (\%hash, $string);
 2591:           }
 2592:       } else {
 2593:           $string =~ s/^(.*?)=//;
 2594: 	  $key=&unescape($1);
 2595:       }
 2596:       $string =~ s/^=//;
 2597: 
 2598:       #value
 2599:       my $value='';
 2600:       if($string =~ /^__HASH_REF__/) {
 2601:           ($value, $string)=&str2hashref($string);
 2602:           if(defined($value->{'error'})) {
 2603:               $hash{'error'}='Bad data';
 2604:               return (\%hash, $string);
 2605:           }
 2606:       } elsif($string =~ /^__ARRAY_REF__/) {
 2607:           ($value, $string)=&str2arrayref($string);
 2608:           if($value->[0] eq 'Array reference error') {
 2609:               $hash{'error'}='Bad data';
 2610:               return (\%hash, $string);
 2611:           }
 2612:       } else {
 2613: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2614:       }
 2615:       $string =~ s/^&//;
 2616: 
 2617:       $hash{$key}=$value;
 2618:   }
 2619: 
 2620:   $string =~ s/^__END_HASH_REF__//;
 2621: 
 2622:   return (\%hash, $string);
 2623: }
 2624: 
 2625: sub str2array {
 2626:     my ($string)=@_;
 2627:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2628:     return @$array;
 2629: }
 2630: 
 2631: sub str2arrayref {
 2632:   my ($string) = @_;
 2633:   my @array;
 2634: 
 2635:   if($string !~ /^__ARRAY_REF__/) {
 2636:       if (! ($string eq '' || !defined($string))) {
 2637: 	  $array[0]='Array reference error';
 2638:       }
 2639:       return (\@array, $string);
 2640:   }
 2641: 
 2642:   $string =~ s/^__ARRAY_REF__//;
 2643: 
 2644:   while($string !~ /^__END_ARRAY_REF__/) {
 2645:       my $value='';
 2646:       if($string =~ /^__HASH_REF__/) {
 2647:           ($value, $string)=&str2hashref($string);
 2648:           if(defined($value->{'error'})) {
 2649:               $array[0] ='Array reference error';
 2650:               return (\@array, $string);
 2651:           }
 2652:       } elsif($string =~ /^__ARRAY_REF__/) {
 2653:           ($value, $string)=&str2arrayref($string);
 2654:           if($value->[0] eq 'Array reference error') {
 2655:               $array[0] ='Array reference error';
 2656:               return (\@array, $string);
 2657:           }
 2658:       } else {
 2659: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2660:       }
 2661:       $string =~ s/^&//;
 2662: 
 2663:       push(@array, $value);
 2664:   }
 2665: 
 2666:   $string =~ s/^__END_ARRAY_REF__//;
 2667: 
 2668:   return (\@array, $string);
 2669: }
 2670: 
 2671: # -------------------------------------------------------------------Temp Store
 2672: 
 2673: sub tmpreset {
 2674:   my ($symb,$namespace,$domain,$stuname) = @_;
 2675:   if (!$symb) {
 2676:     $symb=&symbread();
 2677:     if (!$symb) { $symb= $env{'request.url'}; }
 2678:   }
 2679:   $symb=escape($symb);
 2680: 
 2681:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2682:   $namespace=~s/\//\_/g;
 2683:   $namespace=~s/\W//g;
 2684: 
 2685:   if (!$domain) { $domain=$env{'user.domain'}; }
 2686:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2687:   if ($domain eq 'public' && $stuname eq 'public') {
 2688:       $stuname=$ENV{'REMOTE_ADDR'};
 2689:   }
 2690:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2691:   my %hash;
 2692:   if (tie(%hash,'GDBM_File',
 2693: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2694: 	  &GDBM_WRCREAT(),0640)) {
 2695:     foreach my $key (keys %hash) {
 2696:       if ($key=~ /:$symb/) {
 2697: 	delete($hash{$key});
 2698:       }
 2699:     }
 2700:   }
 2701: }
 2702: 
 2703: sub tmpstore {
 2704:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2705: 
 2706:   if (!$symb) {
 2707:     $symb=&symbread();
 2708:     if (!$symb) { $symb= $env{'request.url'}; }
 2709:   }
 2710:   $symb=escape($symb);
 2711: 
 2712:   if (!$namespace) {
 2713:     # I don't think we would ever want to store this for a course.
 2714:     # it seems this will only be used if we don't have a course.
 2715:     #$namespace=$env{'request.course.id'};
 2716:     #if (!$namespace) {
 2717:       $namespace=$env{'request.state'};
 2718:     #}
 2719:   }
 2720:   $namespace=~s/\//\_/g;
 2721:   $namespace=~s/\W//g;
 2722:   if (!$domain) { $domain=$env{'user.domain'}; }
 2723:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2724:   if ($domain eq 'public' && $stuname eq 'public') {
 2725:       $stuname=$ENV{'REMOTE_ADDR'};
 2726:   }
 2727:   my $now=time;
 2728:   my %hash;
 2729:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2730:   if (tie(%hash,'GDBM_File',
 2731: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2732: 	  &GDBM_WRCREAT(),0640)) {
 2733:     $hash{"version:$symb"}++;
 2734:     my $version=$hash{"version:$symb"};
 2735:     my $allkeys=''; 
 2736:     foreach my $key (keys(%$storehash)) {
 2737:       $allkeys.=$key.':';
 2738:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2739:     }
 2740:     $hash{"$version:$symb:timestamp"}=$now;
 2741:     $allkeys.='timestamp';
 2742:     $hash{"$version:keys:$symb"}=$allkeys;
 2743:     if (untie(%hash)) {
 2744:       return 'ok';
 2745:     } else {
 2746:       return "error:$!";
 2747:     }
 2748:   } else {
 2749:     return "error:$!";
 2750:   }
 2751: }
 2752: 
 2753: # -----------------------------------------------------------------Temp Restore
 2754: 
 2755: sub tmprestore {
 2756:   my ($symb,$namespace,$domain,$stuname) = @_;
 2757: 
 2758:   if (!$symb) {
 2759:     $symb=&symbread();
 2760:     if (!$symb) { $symb= $env{'request.url'}; }
 2761:   }
 2762:   $symb=escape($symb);
 2763: 
 2764:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2765: 
 2766:   if (!$domain) { $domain=$env{'user.domain'}; }
 2767:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2768:   if ($domain eq 'public' && $stuname eq 'public') {
 2769:       $stuname=$ENV{'REMOTE_ADDR'};
 2770:   }
 2771:   my %returnhash;
 2772:   $namespace=~s/\//\_/g;
 2773:   $namespace=~s/\W//g;
 2774:   my %hash;
 2775:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2776:   if (tie(%hash,'GDBM_File',
 2777: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2778: 	  &GDBM_READER(),0640)) {
 2779:     my $version=$hash{"version:$symb"};
 2780:     $returnhash{'version'}=$version;
 2781:     my $scope;
 2782:     for ($scope=1;$scope<=$version;$scope++) {
 2783:       my $vkeys=$hash{"$scope:keys:$symb"};
 2784:       my @keys=split(/:/,$vkeys);
 2785:       my $key;
 2786:       $returnhash{"$scope:keys"}=$vkeys;
 2787:       foreach $key (@keys) {
 2788: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2789: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2790:       }
 2791:     }
 2792:     if (!(untie(%hash))) {
 2793:       return "error:$!";
 2794:     }
 2795:   } else {
 2796:     return "error:$!";
 2797:   }
 2798:   return %returnhash;
 2799: }
 2800: 
 2801: # ----------------------------------------------------------------------- Store
 2802: 
 2803: sub store {
 2804:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2805:     my $home='';
 2806: 
 2807:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2808: 
 2809:     $symb=&symbclean($symb);
 2810:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2811: 
 2812:     if (!$domain) { $domain=$env{'user.domain'}; }
 2813:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2814: 
 2815:     &devalidate($symb,$stuname,$domain);
 2816: 
 2817:     $symb=escape($symb);
 2818:     if (!$namespace) { 
 2819:        unless ($namespace=$env{'request.course.id'}) { 
 2820:           return ''; 
 2821:        } 
 2822:     }
 2823:     if (!$home) { $home=$env{'user.home'}; }
 2824: 
 2825:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2826:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2827: 
 2828:     my $namevalue='';
 2829:     foreach my $key (keys(%$storehash)) {
 2830:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2831:     }
 2832:     $namevalue=~s/\&$//;
 2833:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2834:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2835: }
 2836: 
 2837: # -------------------------------------------------------------- Critical Store
 2838: 
 2839: sub cstore {
 2840:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2841:     my $home='';
 2842: 
 2843:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2844: 
 2845:     $symb=&symbclean($symb);
 2846:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2847: 
 2848:     if (!$domain) { $domain=$env{'user.domain'}; }
 2849:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2850: 
 2851:     &devalidate($symb,$stuname,$domain);
 2852: 
 2853:     $symb=escape($symb);
 2854:     if (!$namespace) { 
 2855:        unless ($namespace=$env{'request.course.id'}) { 
 2856:           return ''; 
 2857:        } 
 2858:     }
 2859:     if (!$home) { $home=$env{'user.home'}; }
 2860: 
 2861:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2862:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2863: 
 2864:     my $namevalue='';
 2865:     foreach my $key (keys(%$storehash)) {
 2866:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2867:     }
 2868:     $namevalue=~s/\&$//;
 2869:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2870:     return critical
 2871:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2872: }
 2873: 
 2874: # --------------------------------------------------------------------- Restore
 2875: 
 2876: sub restore {
 2877:     my ($symb,$namespace,$domain,$stuname) = @_;
 2878:     my $home='';
 2879: 
 2880:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2881: 
 2882:     if (!$symb) {
 2883:       unless ($symb=escape(&symbread())) { return ''; }
 2884:     } else {
 2885:       $symb=&escape(&symbclean($symb));
 2886:     }
 2887:     if (!$namespace) { 
 2888:        unless ($namespace=$env{'request.course.id'}) { 
 2889:           return ''; 
 2890:        } 
 2891:     }
 2892:     if (!$domain) { $domain=$env{'user.domain'}; }
 2893:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2894:     if (!$home) { $home=$env{'user.home'}; }
 2895:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2896: 
 2897:     my %returnhash=();
 2898:     foreach my $line (split(/\&/,$answer)) {
 2899: 	my ($name,$value)=split(/\=/,$line);
 2900:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2901:     }
 2902:     my $version;
 2903:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2904:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2905:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2906:        }
 2907:     }
 2908:     return %returnhash;
 2909: }
 2910: 
 2911: # ---------------------------------------------------------- Course Description
 2912: 
 2913: sub coursedescription {
 2914:     my ($courseid,$args)=@_;
 2915:     $courseid=~s/^\///;
 2916:     $courseid=~s/\_/\//g;
 2917:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2918:     my $chome=&homeserver($cnum,$cdomain);
 2919:     my $normalid=$cdomain.'_'.$cnum;
 2920:     # need to always cache even if we get errors otherwise we keep 
 2921:     # trying and trying and trying to get the course description.
 2922:     my %envhash=();
 2923:     my %returnhash=();
 2924:     
 2925:     my $expiretime=600;
 2926:     if ($env{'request.course.id'} eq $normalid) {
 2927: 	$expiretime=120;
 2928:     }
 2929: 
 2930:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2931:     if (!$args->{'freshen_cache'}
 2932: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2933: 	foreach my $key (keys(%env)) {
 2934: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2935: 	    my ($setting) = $1;
 2936: 	    $returnhash{$setting} = $env{$key};
 2937: 	}
 2938: 	return %returnhash;
 2939:     }
 2940: 
 2941:     # get the data agin
 2942:     if (!$args->{'one_time'}) {
 2943: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2944:     }
 2945: 
 2946:     if ($chome ne 'no_host') {
 2947:        %returnhash=&dump('environment',$cdomain,$cnum);
 2948:        if (!exists($returnhash{'con_lost'})) {
 2949:            $returnhash{'home'}= $chome;
 2950: 	   $returnhash{'domain'} = $cdomain;
 2951: 	   $returnhash{'num'} = $cnum;
 2952:            if (!defined($returnhash{'type'})) {
 2953:                $returnhash{'type'} = 'Course';
 2954:            }
 2955:            while (my ($name,$value) = each %returnhash) {
 2956:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2957:            }
 2958:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2959:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2960: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2961:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2962:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2963:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2964:        }
 2965:     }
 2966:     if (!$args->{'one_time'}) {
 2967: 	&appenv(%envhash);
 2968:     }
 2969:     return %returnhash;
 2970: }
 2971: 
 2972: # -------------------------------------------------See if a user is privileged
 2973: 
 2974: sub privileged {
 2975:     my ($username,$domain)=@_;
 2976:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2977: 			&homeserver($username,$domain));
 2978:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2979:     my $now=time;
 2980:     if ($rolesdump ne '') {
 2981:         foreach my $entry (split(/&/,$rolesdump)) {
 2982: 	    if ($entry!~/^rolesdef_/) {
 2983: 		my ($area,$role)=split(/=/,$entry);
 2984: 		$area=~s/\_\w\w$//;
 2985: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2986: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2987: 		    my $active=1;
 2988: 		    if ($tend) {
 2989: 			if ($tend<$now) { $active=0; }
 2990: 		    }
 2991: 		    if ($tstart) {
 2992: 			if ($tstart>$now) { $active=0; }
 2993: 		    }
 2994: 		    if ($active) { return 1; }
 2995: 		}
 2996: 	    }
 2997: 	}
 2998:     }
 2999:     return 0;
 3000: }
 3001: 
 3002: # -------------------------------------------------------- Get user privileges
 3003: 
 3004: sub rolesinit {
 3005:     my ($domain,$username,$authhost)=@_;
 3006:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3007:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3008:     my %allroles=();
 3009:     my %allgroups=();   
 3010:     my $now=time;
 3011:     my %userroles = ('user.login.time' => $now);
 3012:     my $group_privs;
 3013: 
 3014:     if ($rolesdump ne '') {
 3015:         foreach my $entry (split(/&/,$rolesdump)) {
 3016: 	  if ($entry!~/^rolesdef_/) {
 3017:             my ($area,$role)=split(/=/,$entry);
 3018: 	    $area=~s/\_\w\w$//;
 3019:             my ($trole,$tend,$tstart,$group_privs);
 3020: 	    if ($role=~/^cr/) { 
 3021: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3022: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3023: 		    ($tend,$tstart)=split('_',$trest);
 3024: 		} else {
 3025: 		    $trole=$role;
 3026: 		}
 3027:             } elsif ($role =~ m|^gr/|) {
 3028:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3029:                 ($trole,$group_privs) = split(/\//,$trole);
 3030:                 $group_privs = &unescape($group_privs);
 3031: 	    } else {
 3032: 		($trole,$tend,$tstart)=split(/_/,$role);
 3033: 	    }
 3034: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3035: 					 $username);
 3036: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3037:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3038:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3039:             if (($area ne '') && ($trole ne '')) {
 3040: 		my $spec=$trole.'.'.$area;
 3041: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3042: 		if ($trole =~ /^cr\//) {
 3043:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3044:                 } elsif ($trole eq 'gr') {
 3045:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3046: 		} else {
 3047:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3048: 		}
 3049:             }
 3050:           }
 3051:         }
 3052:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3053:         $userroles{'user.adv'}    = $adv;
 3054: 	$userroles{'user.author'} = $author;
 3055:         $env{'user.adv'}=$adv;
 3056:     }
 3057:     return \%userroles;  
 3058: }
 3059: 
 3060: sub set_arearole {
 3061:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3062: # log the associated role with the area
 3063:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3064:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3065: }
 3066: 
 3067: sub custom_roleprivs {
 3068:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3069:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3070:     my $homsvr=homeserver($rauthor,$rdomain);
 3071:     if (&hostname($homsvr) ne '') {
 3072:         my ($rdummy,$roledef)=
 3073:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3074:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3075:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3076:             if (defined($syspriv)) {
 3077:                 $$allroles{'cm./'}.=':'.$syspriv;
 3078:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3079:             }
 3080:             if ($tdomain ne '') {
 3081:                 if (defined($dompriv)) {
 3082:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3083:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3084:                 }
 3085:                 if (($trest ne '') && (defined($coursepriv))) {
 3086:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3087:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3088:                 }
 3089:             }
 3090:         }
 3091:     }
 3092: }
 3093: 
 3094: sub group_roleprivs {
 3095:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3096:     my $access = 1;
 3097:     my $now = time;
 3098:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3099:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3100:     if ($access) {
 3101:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3102:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3103:     }
 3104: }
 3105: 
 3106: sub standard_roleprivs {
 3107:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3108:     if (defined($pr{$trole.':s'})) {
 3109:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3110:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3111:     }
 3112:     if ($tdomain ne '') {
 3113:         if (defined($pr{$trole.':d'})) {
 3114:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3115:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3116:         }
 3117:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3118:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3119:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3120:         }
 3121:     }
 3122: }
 3123: 
 3124: sub set_userprivs {
 3125:     my ($userroles,$allroles,$allgroups) = @_; 
 3126:     my $author=0;
 3127:     my $adv=0;
 3128:     my %grouproles = ();
 3129:     if (keys(%{$allgroups}) > 0) {
 3130:         foreach my $role (keys %{$allroles}) {
 3131:             my ($trole,$area,$sec,$extendedarea);
 3132:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3133:                 $trole = $1;
 3134:                 $area = $2;
 3135:                 $sec = $3;
 3136:                 $extendedarea = $area.$sec;
 3137:                 if (exists($$allgroups{$area})) {
 3138:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3139:                         my $spec = $trole.'.'.$extendedarea;
 3140:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3141:                                                 $$allgroups{$area}{$group};
 3142:                     }
 3143:                 }
 3144:             }
 3145:         }
 3146:     }
 3147:     foreach my $group (keys(%grouproles)) {
 3148:         $$allroles{$group} = $grouproles{$group};
 3149:     }
 3150:     foreach my $role (keys(%{$allroles})) {
 3151:         my %thesepriv;
 3152:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3153:         foreach my $item (split(/:/,$$allroles{$role})) {
 3154:             if ($item ne '') {
 3155:                 my ($privilege,$restrictions)=split(/&/,$item);
 3156:                 if ($restrictions eq '') {
 3157:                     $thesepriv{$privilege}='F';
 3158:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3159:                     $thesepriv{$privilege}.=$restrictions;
 3160:                 }
 3161:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3162:             }
 3163:         }
 3164:         my $thesestr='';
 3165:         foreach my $priv (keys(%thesepriv)) {
 3166: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3167: 	}
 3168:         $userroles->{'user.priv.'.$role} = $thesestr;
 3169:     }
 3170:     return ($author,$adv);
 3171: }
 3172: 
 3173: # --------------------------------------------------------------- get interface
 3174: 
 3175: sub get {
 3176:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3177:    my $items='';
 3178:    foreach my $item (@$storearr) {
 3179:        $items.=&escape($item).'&';
 3180:    }
 3181:    $items=~s/\&$//;
 3182:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3183:    if (!$uname) { $uname=$env{'user.name'}; }
 3184:    my $uhome=&homeserver($uname,$udomain);
 3185: 
 3186:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3187:    my @pairs=split(/\&/,$rep);
 3188:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3189:      return @pairs;
 3190:    }
 3191:    my %returnhash=();
 3192:    my $i=0;
 3193:    foreach my $item (@$storearr) {
 3194:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3195:       $i++;
 3196:    }
 3197:    return %returnhash;
 3198: }
 3199: 
 3200: # --------------------------------------------------------------- del interface
 3201: 
 3202: sub del {
 3203:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3204:    my $items='';
 3205:    foreach my $item (@$storearr) {
 3206:        $items.=&escape($item).'&';
 3207:    }
 3208:    $items=~s/\&$//;
 3209:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3210:    if (!$uname) { $uname=$env{'user.name'}; }
 3211:    my $uhome=&homeserver($uname,$udomain);
 3212: 
 3213:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3214: }
 3215: 
 3216: # -------------------------------------------------------------- dump interface
 3217: 
 3218: sub dump {
 3219:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3220:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3221:     if (!$uname) { $uname=$env{'user.name'}; }
 3222:     my $uhome=&homeserver($uname,$udomain);
 3223:     if ($regexp) {
 3224: 	$regexp=&escape($regexp);
 3225:     } else {
 3226: 	$regexp='.';
 3227:     }
 3228:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3229:     my @pairs=split(/\&/,$rep);
 3230:     my %returnhash=();
 3231:     foreach my $item (@pairs) {
 3232: 	my ($key,$value)=split(/=/,$item,2);
 3233: 	$key = &unescape($key);
 3234: 	next if ($key =~ /^error: 2 /);
 3235: 	$returnhash{$key}=&thaw_unescape($value);
 3236:     }
 3237:     return %returnhash;
 3238: }
 3239: 
 3240: # --------------------------------------------------------- dumpstore interface
 3241: 
 3242: sub dumpstore {
 3243:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3244:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3245:    if (!$uname) { $uname=$env{'user.name'}; }
 3246:    my $uhome=&homeserver($uname,$udomain);
 3247:    if ($regexp) {
 3248:        $regexp=&escape($regexp);
 3249:    } else {
 3250:        $regexp='.';
 3251:    }
 3252:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3253:    my @pairs=split(/\&/,$rep);
 3254:    my %returnhash=();
 3255:    foreach my $item (@pairs) {
 3256:        my ($key,$value)=split(/=/,$item,2);
 3257:        next if ($key =~ /^error: 2 /);
 3258:        $returnhash{$key}=&thaw_unescape($value);
 3259:    }
 3260:    return %returnhash;
 3261: }
 3262: 
 3263: # -------------------------------------------------------------- keys interface
 3264: 
 3265: sub getkeys {
 3266:    my ($namespace,$udomain,$uname)=@_;
 3267:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3268:    if (!$uname) { $uname=$env{'user.name'}; }
 3269:    my $uhome=&homeserver($uname,$udomain);
 3270:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3271:    my @keyarray=();
 3272:    foreach my $key (split(/\&/,$rep)) {
 3273:       next if ($key =~ /^error: 2 /);
 3274:       push(@keyarray,&unescape($key));
 3275:    }
 3276:    return @keyarray;
 3277: }
 3278: 
 3279: # --------------------------------------------------------------- currentdump
 3280: sub currentdump {
 3281:    my ($courseid,$sdom,$sname)=@_;
 3282:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3283:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3284:    $sname    = $env{'user.name'}         if (! defined($sname));
 3285:    my $uhome = &homeserver($sname,$sdom);
 3286:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3287:    return if ($rep =~ /^(error:|no_such_host)/);
 3288:    #
 3289:    my %returnhash=();
 3290:    #
 3291:    if ($rep eq "unknown_cmd") { 
 3292:        # an old lond will not know currentdump
 3293:        # Do a dump and make it look like a currentdump
 3294:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3295:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3296:        my %hash = @tmp;
 3297:        @tmp=();
 3298:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3299:    } else {
 3300:        my @pairs=split(/\&/,$rep);
 3301:        foreach my $pair (@pairs) {
 3302:            my ($key,$value)=split(/=/,$pair,2);
 3303:            my ($symb,$param) = split(/:/,$key);
 3304:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3305:                                                         &thaw_unescape($value);
 3306:        }
 3307:    }
 3308:    return %returnhash;
 3309: }
 3310: 
 3311: sub convert_dump_to_currentdump{
 3312:     my %hash = %{shift()};
 3313:     my %returnhash;
 3314:     # Code ripped from lond, essentially.  The only difference
 3315:     # here is the unescaping done by lonnet::dump().  Conceivably
 3316:     # we might run in to problems with parameter names =~ /^v\./
 3317:     while (my ($key,$value) = each(%hash)) {
 3318:         my ($v,$symb,$param) = split(/:/,$key);
 3319: 	$symb  = &unescape($symb);
 3320: 	$param = &unescape($param);
 3321:         next if ($v eq 'version' || $symb eq 'keys');
 3322:         next if (exists($returnhash{$symb}) &&
 3323:                  exists($returnhash{$symb}->{$param}) &&
 3324:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3325:         $returnhash{$symb}->{$param}=$value;
 3326:         $returnhash{$symb}->{'v.'.$param}=$v;
 3327:     }
 3328:     #
 3329:     # Remove all of the keys in the hashes which keep track of
 3330:     # the version of the parameter.
 3331:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3332:         # use a foreach because we are going to delete from the hash.
 3333:         foreach my $key (keys(%$param_hash)) {
 3334:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3335:         }
 3336:     }
 3337:     return \%returnhash;
 3338: }
 3339: 
 3340: # ------------------------------------------------------ critical inc interface
 3341: 
 3342: sub cinc {
 3343:     return &inc(@_,'critical');
 3344: }
 3345: 
 3346: # --------------------------------------------------------------- inc interface
 3347: 
 3348: sub inc {
 3349:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3350:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3351:     if (!$uname) { $uname=$env{'user.name'}; }
 3352:     my $uhome=&homeserver($uname,$udomain);
 3353:     my $items='';
 3354:     if (! ref($store)) {
 3355:         # got a single value, so use that instead
 3356:         $items = &escape($store).'=&';
 3357:     } elsif (ref($store) eq 'SCALAR') {
 3358:         $items = &escape($$store).'=&';        
 3359:     } elsif (ref($store) eq 'ARRAY') {
 3360:         $items = join('=&',map {&escape($_);} @{$store});
 3361:     } elsif (ref($store) eq 'HASH') {
 3362:         while (my($key,$value) = each(%{$store})) {
 3363:             $items.= &escape($key).'='.&escape($value).'&';
 3364:         }
 3365:     }
 3366:     $items=~s/\&$//;
 3367:     if ($critical) {
 3368: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3369:     } else {
 3370: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3371:     }
 3372: }
 3373: 
 3374: # --------------------------------------------------------------- put interface
 3375: 
 3376: sub put {
 3377:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3378:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3379:    if (!$uname) { $uname=$env{'user.name'}; }
 3380:    my $uhome=&homeserver($uname,$udomain);
 3381:    my $items='';
 3382:    foreach my $item (keys(%$storehash)) {
 3383:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3384:    }
 3385:    $items=~s/\&$//;
 3386:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3387: }
 3388: 
 3389: # ------------------------------------------------------------ newput interface
 3390: 
 3391: sub newput {
 3392:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3393:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3394:    if (!$uname) { $uname=$env{'user.name'}; }
 3395:    my $uhome=&homeserver($uname,$udomain);
 3396:    my $items='';
 3397:    foreach my $key (keys(%$storehash)) {
 3398:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3399:    }
 3400:    $items=~s/\&$//;
 3401:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3402: }
 3403: 
 3404: # ---------------------------------------------------------  putstore interface
 3405: 
 3406: sub putstore {
 3407:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3408:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3409:    if (!$uname) { $uname=$env{'user.name'}; }
 3410:    my $uhome=&homeserver($uname,$udomain);
 3411:    my $items='';
 3412:    foreach my $key (keys(%$storehash)) {
 3413:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3414:    }
 3415:    $items=~s/\&$//;
 3416:    my $esc_symb=&escape($symb);
 3417:    my $esc_v=&escape($version);
 3418:    my $reply =
 3419:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3420: 	      $uhome);
 3421:    if ($reply eq 'unknown_cmd') {
 3422:        # gfall back to way things use to be done
 3423:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3424: 			    $uname);
 3425:    }
 3426:    return $reply;
 3427: }
 3428: 
 3429: sub old_putstore {
 3430:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3431:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3432:     if (!$uname) { $uname=$env{'user.name'}; }
 3433:     my $uhome=&homeserver($uname,$udomain);
 3434:     my %newstorehash;
 3435:     foreach my $item (keys(%$storehash)) {
 3436: 	my $key = $version.':'.&escape($symb).':'.$item;
 3437: 	$newstorehash{$key} = $storehash->{$item};
 3438:     }
 3439:     my $items='';
 3440:     my %allitems = ();
 3441:     foreach my $item (keys(%newstorehash)) {
 3442: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3443: 	    my $key = $1.':keys:'.$2;
 3444: 	    $allitems{$key} .= $3.':';
 3445: 	}
 3446: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3447:     }
 3448:     foreach my $item (keys(%allitems)) {
 3449: 	$allitems{$item} =~ s/\:$//;
 3450: 	$items.= $item.'='.$allitems{$item}.'&';
 3451:     }
 3452:     $items=~s/\&$//;
 3453:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3454: }
 3455: 
 3456: # ------------------------------------------------------ critical put interface
 3457: 
 3458: sub cput {
 3459:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3460:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3461:    if (!$uname) { $uname=$env{'user.name'}; }
 3462:    my $uhome=&homeserver($uname,$udomain);
 3463:    my $items='';
 3464:    foreach my $item (keys(%$storehash)) {
 3465:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3466:    }
 3467:    $items=~s/\&$//;
 3468:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3469: }
 3470: 
 3471: # -------------------------------------------------------------- eget interface
 3472: 
 3473: sub eget {
 3474:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3475:    my $items='';
 3476:    foreach my $item (@$storearr) {
 3477:        $items.=&escape($item).'&';
 3478:    }
 3479:    $items=~s/\&$//;
 3480:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3481:    if (!$uname) { $uname=$env{'user.name'}; }
 3482:    my $uhome=&homeserver($uname,$udomain);
 3483:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3484:    my @pairs=split(/\&/,$rep);
 3485:    my %returnhash=();
 3486:    my $i=0;
 3487:    foreach my $item (@$storearr) {
 3488:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3489:       $i++;
 3490:    }
 3491:    return %returnhash;
 3492: }
 3493: 
 3494: # ------------------------------------------------------------ tmpput interface
 3495: sub tmpput {
 3496:     my ($storehash,$server,$context)=@_;
 3497:     my $items='';
 3498:     foreach my $item (keys(%$storehash)) {
 3499: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3500:     }
 3501:     $items=~s/\&$//;
 3502:     if (defined($context)) {
 3503:         $items .= ':'.&escape($context);
 3504:     }
 3505:     return &reply("tmpput:$items",$server);
 3506: }
 3507: 
 3508: # ------------------------------------------------------------ tmpget interface
 3509: sub tmpget {
 3510:     my ($token,$server)=@_;
 3511:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3512:     my $rep=&reply("tmpget:$token",$server);
 3513:     my %returnhash;
 3514:     foreach my $item (split(/\&/,$rep)) {
 3515: 	my ($key,$value)=split(/=/,$item);
 3516: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3517:     }
 3518:     return %returnhash;
 3519: }
 3520: 
 3521: # ------------------------------------------------------------ tmpget interface
 3522: sub tmpdel {
 3523:     my ($token,$server)=@_;
 3524:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3525:     return &reply("tmpdel:$token",$server);
 3526: }
 3527: 
 3528: # -------------------------------------------------- portfolio access checking
 3529: 
 3530: sub portfolio_access {
 3531:     my ($requrl) = @_;
 3532:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3533:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3534:     if ($result) {
 3535:         my %setters;
 3536:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3537:             my ($startblock,$endblock) =
 3538:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3539:             if ($startblock && $endblock) {
 3540:                 return 'B';
 3541:             }
 3542:         } else {
 3543:             my ($startblock,$endblock) =
 3544:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3545:             if ($startblock && $endblock) {
 3546:                 return 'B';
 3547:             }
 3548:         }
 3549:     }
 3550:     if ($result eq 'ok') {
 3551:        return 'F';
 3552:     } elsif ($result =~ /^[^:]+:guest_/) {
 3553:        return 'A';
 3554:     }
 3555:     return '';
 3556: }
 3557: 
 3558: sub get_portfolio_access {
 3559:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3560: 
 3561:     if (!ref($access_hash)) {
 3562: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3563: 	my %access_controls = &get_access_controls($current_perms,$group,
 3564: 						   $file_name);
 3565: 	$access_hash = $access_controls{$file_name};
 3566:     }
 3567: 
 3568:     my ($public,$guest,@domains,@users,@courses,@groups);
 3569:     my $now = time;
 3570:     if (ref($access_hash) eq 'HASH') {
 3571:         foreach my $key (keys(%{$access_hash})) {
 3572:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3573:             if ($start > $now) {
 3574:                 next;
 3575:             }
 3576:             if ($end && $end<$now) {
 3577:                 next;
 3578:             }
 3579:             if ($scope eq 'public') {
 3580:                 $public = $key;
 3581:                 last;
 3582:             } elsif ($scope eq 'guest') {
 3583:                 $guest = $key;
 3584:             } elsif ($scope eq 'domains') {
 3585:                 push(@domains,$key);
 3586:             } elsif ($scope eq 'users') {
 3587:                 push(@users,$key);
 3588:             } elsif ($scope eq 'course') {
 3589:                 push(@courses,$key);
 3590:             } elsif ($scope eq 'group') {
 3591:                 push(@groups,$key);
 3592:             }
 3593:         }
 3594:         if ($public) {
 3595:             return 'ok';
 3596:         }
 3597:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3598:             if ($guest) {
 3599:                 return $guest;
 3600:             }
 3601:         } else {
 3602:             if (@domains > 0) {
 3603:                 foreach my $domkey (@domains) {
 3604:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3605:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3606:                             return 'ok';
 3607:                         }
 3608:                     }
 3609:                 }
 3610:             }
 3611:             if (@users > 0) {
 3612:                 foreach my $userkey (@users) {
 3613:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3614:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3615:                             if (ref($item) eq 'HASH') {
 3616:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3617:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3618:                                     return 'ok';
 3619:                                 }
 3620:                             }
 3621:                         }
 3622:                     } 
 3623:                 }
 3624:             }
 3625:             my %roleshash;
 3626:             my @courses_and_groups = @courses;
 3627:             push(@courses_and_groups,@groups); 
 3628:             if (@courses_and_groups > 0) {
 3629:                 my (%allgroups,%allroles); 
 3630:                 my ($start,$end,$role,$sec,$group);
 3631:                 foreach my $envkey (%env) {
 3632:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3633:                         my $cid = $2.'_'.$3; 
 3634:                         if ($1 eq 'gr') {
 3635:                             $group = $4;
 3636:                             $allgroups{$cid}{$group} = $env{$envkey};
 3637:                         } else {
 3638:                             if ($4 eq '') {
 3639:                                 $sec = 'none';
 3640:                             } else {
 3641:                                 $sec = $4;
 3642:                             }
 3643:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3644:                         }
 3645:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3646:                         my $cid = $2.'_'.$3;
 3647:                         if ($4 eq '') {
 3648:                             $sec = 'none';
 3649:                         } else {
 3650:                             $sec = $4;
 3651:                         }
 3652:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3653:                     }
 3654:                 }
 3655:                 if (keys(%allroles) == 0) {
 3656:                     return;
 3657:                 }
 3658:                 foreach my $key (@courses_and_groups) {
 3659:                     my %content = %{$$access_hash{$key}};
 3660:                     my $cnum = $content{'number'};
 3661:                     my $cdom = $content{'domain'};
 3662:                     my $cid = $cdom.'_'.$cnum;
 3663:                     if (!exists($allroles{$cid})) {
 3664:                         next;
 3665:                     }    
 3666:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3667:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3668:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3669:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3670:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3671:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3672:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3673:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3674:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3675:                                         if (grep/^all$/,@sections) {
 3676:                                             return 'ok';
 3677:                                         } else {
 3678:                                             if (grep/^$sec$/,@sections) {
 3679:                                                 return 'ok';
 3680:                                             }
 3681:                                         }
 3682:                                     }
 3683:                                 }
 3684:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3685:                                     if (grep/^none$/,@groups) {
 3686:                                         return 'ok';
 3687:                                     }
 3688:                                 } else {
 3689:                                     if (grep/^all$/,@groups) {
 3690:                                         return 'ok';
 3691:                                     } 
 3692:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3693:                                         if (grep/^$group$/,@groups) {
 3694:                                             return 'ok';
 3695:                                         }
 3696:                                     }
 3697:                                 } 
 3698:                             }
 3699:                         }
 3700:                     }
 3701:                 }
 3702:             }
 3703:             if ($guest) {
 3704:                 return $guest;
 3705:             }
 3706:         }
 3707:     }
 3708:     return;
 3709: }
 3710: 
 3711: sub course_group_datechecker {
 3712:     my ($dates,$now,$status) = @_;
 3713:     my ($start,$end) = split(/\./,$dates);
 3714:     if (!$start && !$end) {
 3715:         return 'ok';
 3716:     }
 3717:     if (grep/^active$/,@{$status}) {
 3718:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3719:             return 'ok';
 3720:         }
 3721:     }
 3722:     if (grep/^previous$/,@{$status}) {
 3723:         if ($end > $now ) {
 3724:             return 'ok';
 3725:         }
 3726:     }
 3727:     if (grep/^future$/,@{$status}) {
 3728:         if ($start > $now) {
 3729:             return 'ok';
 3730:         }
 3731:     }
 3732:     return; 
 3733: }
 3734: 
 3735: sub parse_portfolio_url {
 3736:     my ($url) = @_;
 3737: 
 3738:     my ($type,$udom,$unum,$group,$file_name);
 3739:     
 3740:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3741: 	$type = 1;
 3742:         $udom = $1;
 3743:         $unum = $2;
 3744:         $file_name = $3;
 3745:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3746: 	$type = 2;
 3747:         $udom = $1;
 3748:         $unum = $2;
 3749:         $group = $3;
 3750:         $file_name = $3.'/'.$4;
 3751:     }
 3752:     if (wantarray) {
 3753: 	return ($type,$udom,$unum,$file_name,$group);
 3754:     }
 3755:     return $type;
 3756: }
 3757: 
 3758: sub is_portfolio_url {
 3759:     my ($url) = @_;
 3760:     return scalar(&parse_portfolio_url($url));
 3761: }
 3762: 
 3763: sub is_portfolio_file {
 3764:     my ($file) = @_;
 3765:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3766:         return 1;
 3767:     }
 3768:     return;
 3769: }
 3770: 
 3771: 
 3772: # ---------------------------------------------- Custom access rule evaluation
 3773: 
 3774: sub customaccess {
 3775:     my ($priv,$uri)=@_;
 3776:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3777:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3778:     $udom = &LONCAPA::clean_domain($udom);
 3779:     $ucrs = &LONCAPA::clean_username($ucrs);
 3780:     my $access=0;
 3781:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3782: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3783:         if ($role) {
 3784: 	   if ($role ne $urole) { next; }
 3785:         }
 3786:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3787:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3788:             if ($tdom) {
 3789: 		if ($tdom ne $udom) { next; }
 3790:             }
 3791:             if ($tcrs) {
 3792: 		if ($tcrs ne $ucrs) { next; }
 3793:             }
 3794:             if ($tsec) {
 3795: 		if ($tsec ne $usec) { next; }
 3796:             }
 3797:             $access=($effect eq 'allow');
 3798:             last;
 3799:         }
 3800: 	if ($realm eq '' && $role eq '') {
 3801:             $access=($effect eq 'allow');
 3802: 	}
 3803:     }
 3804:     return $access;
 3805: }
 3806: 
 3807: # ------------------------------------------------- Check for a user privilege
 3808: 
 3809: sub allowed {
 3810:     my ($priv,$uri,$symb,$role)=@_;
 3811:     my $ver_orguri=$uri;
 3812:     $uri=&deversion($uri);
 3813:     my $orguri=$uri;
 3814:     $uri=&declutter($uri);
 3815: 
 3816:     if ($priv eq 'evb') {
 3817: # Evade communication block restrictions for specified role in a course
 3818:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3819:             return $1;
 3820:         } else {
 3821:             return;
 3822:         }
 3823:     }
 3824: 
 3825:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3826: # Free bre access to adm and meta resources
 3827:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3828: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3829: 	&& ($priv eq 'bre')) {
 3830: 	return 'F';
 3831:     }
 3832: 
 3833: # Free bre access to user's own portfolio contents
 3834:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3835:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3836: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3837:         my %setters;
 3838:         my ($startblock,$endblock) = 
 3839:             &Apache::loncommon::blockcheck(\%setters,'port');
 3840:         if ($startblock && $endblock) {
 3841:             return 'B';
 3842:         } else {
 3843:             return 'F';
 3844:         }
 3845:     }
 3846: 
 3847: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3848:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3849:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3850:         if (exists($env{'request.course.id'})) {
 3851:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3852:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3853:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3854:                 my $courseprivid=$env{'request.course.id'};
 3855:                 $courseprivid=~s/\_/\//;
 3856:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3857:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3858:                     return $1; 
 3859:                 } else {
 3860:                     if ($env{'request.course.sec'}) {
 3861:                         $courseprivid.='/'.$env{'request.course.sec'};
 3862:                     }
 3863:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3864:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3865:                         return $2;
 3866:                     }
 3867:                 }
 3868:             }
 3869:         }
 3870:     }
 3871: 
 3872: # Free bre to public access
 3873: 
 3874:     if ($priv eq 'bre') {
 3875:         my $copyright=&metadata($uri,'copyright');
 3876: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3877:            return 'F'; 
 3878:         }
 3879:         if ($copyright eq 'priv') {
 3880:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3881: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3882: 		return '';
 3883:             }
 3884:         }
 3885:         if ($copyright eq 'domain') {
 3886:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3887: 	    unless (($env{'user.domain'} eq $1) ||
 3888:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3889: 		return '';
 3890:             }
 3891:         }
 3892:         if ($env{'request.role'}=~ /li\.\//) {
 3893:             # Library role, so allow browsing of resources in this domain.
 3894:             return 'F';
 3895:         }
 3896:         if ($copyright eq 'custom') {
 3897: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3898:         }
 3899:     }
 3900:     # Domain coordinator is trying to create a course
 3901:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3902:         # uri is the requested domain in this case.
 3903:         # comparison to 'request.role.domain' shows if the user has selected
 3904:         # a role of dc for the domain in question.
 3905:         return 'F' if ($uri eq $env{'request.role.domain'});
 3906:     }
 3907: 
 3908:     my $thisallowed='';
 3909:     my $statecond=0;
 3910:     my $courseprivid='';
 3911: 
 3912: # Course
 3913: 
 3914:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3915:        $thisallowed.=$1;
 3916:     }
 3917: 
 3918: # Domain
 3919: 
 3920:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3921:        =~/\Q$priv\E\&([^\:]*)/) {
 3922:        $thisallowed.=$1;
 3923:     }
 3924: 
 3925: # Course: uri itself is a course
 3926:     my $courseuri=$uri;
 3927:     $courseuri=~s/\_(\d)/\/$1/;
 3928:     $courseuri=~s/^([^\/])/\/$1/;
 3929: 
 3930:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3931:        =~/\Q$priv\E\&([^\:]*)/) {
 3932:        $thisallowed.=$1;
 3933:     }
 3934: 
 3935: # URI is an uploaded document for this course, default permissions don't matter
 3936: # not allowing 'edit' access (editupload) to uploaded course docs
 3937:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3938: 	$thisallowed='';
 3939:         my ($match)=&is_on_map($uri);
 3940:         if ($match) {
 3941:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3942:                   =~/\Q$priv\E\&([^\:]*)/) {
 3943:                 $thisallowed.=$1;
 3944:             }
 3945:         } else {
 3946:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3947:             if ($refuri) {
 3948:                 if ($refuri =~ m|^/adm/|) {
 3949:                     $thisallowed='F';
 3950:                 } else {
 3951:                     $refuri=&declutter($refuri);
 3952:                     my ($match) = &is_on_map($refuri);
 3953:                     if ($match) {
 3954:                         $thisallowed='F';
 3955:                     }
 3956:                 }
 3957:             }
 3958:         }
 3959:     }
 3960: 
 3961:     if ($priv eq 'bre'
 3962: 	&& $thisallowed ne 'F' 
 3963: 	&& $thisallowed ne '2'
 3964: 	&& &is_portfolio_url($uri)) {
 3965: 	$thisallowed = &portfolio_access($uri);
 3966:     }
 3967:     
 3968: # Full access at system, domain or course-wide level? Exit.
 3969: 
 3970:     if ($thisallowed=~/F/) {
 3971: 	return 'F';
 3972:     }
 3973: 
 3974: # If this is generating or modifying users, exit with special codes
 3975: 
 3976:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3977: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3978: 	    my ($audom,$auname)=split('/',$uri);
 3979: # no author name given, so this just checks on the general right to make a co-author in this domain
 3980: 	    unless ($auname) { return $thisallowed; }
 3981: # an author name is given, so we are about to actually make a co-author for a certain account
 3982: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3983: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3984: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3985: 	}
 3986: 	return $thisallowed;
 3987:     }
 3988: #
 3989: # Gathered so far: system, domain and course wide privileges
 3990: #
 3991: # Course: See if uri or referer is an individual resource that is part of 
 3992: # the course
 3993: 
 3994:     if ($env{'request.course.id'}) {
 3995: 
 3996:        $courseprivid=$env{'request.course.id'};
 3997:        if ($env{'request.course.sec'}) {
 3998:           $courseprivid.='/'.$env{'request.course.sec'};
 3999:        }
 4000:        $courseprivid=~s/\_/\//;
 4001:        my $checkreferer=1;
 4002:        my ($match,$cond)=&is_on_map($uri);
 4003:        if ($match) {
 4004:            $statecond=$cond;
 4005:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4006:                =~/\Q$priv\E\&([^\:]*)/) {
 4007:                $thisallowed.=$1;
 4008:                $checkreferer=0;
 4009:            }
 4010:        }
 4011:        
 4012:        if ($checkreferer) {
 4013: 	  my $refuri=$env{'httpref.'.$orguri};
 4014:             unless ($refuri) {
 4015:                 foreach my $key (keys(%env)) {
 4016: 		    if ($key=~/^httpref\..*\*/) {
 4017: 			my $pattern=$key;
 4018:                         $pattern=~s/^httpref\.\/res\///;
 4019:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4020:                         $pattern=~s/\//\\\//g;
 4021:                         if ($orguri=~/$pattern/) {
 4022: 			    $refuri=$env{$key};
 4023:                         }
 4024:                     }
 4025:                 }
 4026:             }
 4027: 
 4028:          if ($refuri) { 
 4029: 	  $refuri=&declutter($refuri);
 4030:           my ($match,$cond)=&is_on_map($refuri);
 4031:             if ($match) {
 4032:               my $refstatecond=$cond;
 4033:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4034:                   =~/\Q$priv\E\&([^\:]*)/) {
 4035:                   $thisallowed.=$1;
 4036:                   $uri=$refuri;
 4037:                   $statecond=$refstatecond;
 4038:               }
 4039:           }
 4040:         }
 4041:        }
 4042:    }
 4043: 
 4044: #
 4045: # Gathered now: all privileges that could apply, and condition number
 4046: # 
 4047: #
 4048: # Full or no access?
 4049: #
 4050: 
 4051:     if ($thisallowed=~/F/) {
 4052: 	return 'F';
 4053:     }
 4054: 
 4055:     unless ($thisallowed) {
 4056:         return '';
 4057:     }
 4058: 
 4059: # Restrictions exist, deal with them
 4060: #
 4061: #   C:according to course preferences
 4062: #   R:according to resource settings
 4063: #   L:unless locked
 4064: #   X:according to user session state
 4065: #
 4066: 
 4067: # Possibly locked functionality, check all courses
 4068: # Locks might take effect only after 10 minutes cache expiration for other
 4069: # courses, and 2 minutes for current course
 4070: 
 4071:     my $envkey;
 4072:     if ($thisallowed=~/L/) {
 4073:         foreach $envkey (keys %env) {
 4074:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4075:                my $courseid=$2;
 4076:                my $roleid=$1.'.'.$2;
 4077:                $courseid=~s/^\///;
 4078:                my $expiretime=600;
 4079:                if ($env{'request.role'} eq $roleid) {
 4080: 		  $expiretime=120;
 4081:                }
 4082: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4083:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4084:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4085: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4086:                }
 4087:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4088:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4089: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4090:                        &log($env{'user.domain'},$env{'user.name'},
 4091:                             $env{'user.home'},
 4092:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4093:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4094:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4095: 		       return '';
 4096:                    }
 4097:                }
 4098:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4099:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4100: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4101:                        &log($env{'user.domain'},$env{'user.name'},
 4102:                             $env{'user.home'},
 4103:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4104:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4105:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4106: 		       return '';
 4107:                    }
 4108:                }
 4109: 	   }
 4110:        }
 4111:     }
 4112:    
 4113: #
 4114: # Rest of the restrictions depend on selected course
 4115: #
 4116: 
 4117:     unless ($env{'request.course.id'}) {
 4118: 	if ($thisallowed eq 'A') {
 4119: 	    return 'A';
 4120:         } elsif ($thisallowed eq 'B') {
 4121:             return 'B';
 4122: 	} else {
 4123: 	    return '1';
 4124: 	}
 4125:     }
 4126: 
 4127: #
 4128: # Now user is definitely in a course
 4129: #
 4130: 
 4131: 
 4132: # Course preferences
 4133: 
 4134:    if ($thisallowed=~/C/) {
 4135:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4136:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4137:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4138: 	   =~/\Q$rolecode\E/) {
 4139: 	   if ($priv ne 'pch') { 
 4140: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4141: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4142: 			$env{'request.course.id'});
 4143: 	   }
 4144:            return '';
 4145:        }
 4146: 
 4147:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4148: 	   =~/\Q$unamedom\E/) {
 4149: 	   if ($priv ne 'pch') { 
 4150: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4151: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4152: 			$env{'request.course.id'});
 4153: 	   }
 4154:            return '';
 4155:        }
 4156:    }
 4157: 
 4158: # Resource preferences
 4159: 
 4160:    if ($thisallowed=~/R/) {
 4161:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4162:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4163: 	   if ($priv ne 'pch') { 
 4164: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4165: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4166: 	   }
 4167: 	   return '';
 4168:        }
 4169:    }
 4170: 
 4171: # Restricted by state or randomout?
 4172: 
 4173:    if ($thisallowed=~/X/) {
 4174:       if ($env{'acc.randomout'}) {
 4175: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4176:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4177:             return ''; 
 4178:          }
 4179:       }
 4180:       if (&condval($statecond)) {
 4181: 	 return '2';
 4182:       } else {
 4183:          return '';
 4184:       }
 4185:    }
 4186: 
 4187:     if ($thisallowed eq 'A') {
 4188: 	return 'A';
 4189:     } elsif ($thisallowed eq 'B') {
 4190:         return 'B';
 4191:     }
 4192:    return 'F';
 4193: }
 4194: 
 4195: sub split_uri_for_cond {
 4196:     my $uri=&deversion(&declutter(shift));
 4197:     my @uriparts=split(/\//,$uri);
 4198:     my $filename=pop(@uriparts);
 4199:     my $pathname=join('/',@uriparts);
 4200:     return ($pathname,$filename);
 4201: }
 4202: # --------------------------------------------------- Is a resource on the map?
 4203: 
 4204: sub is_on_map {
 4205:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4206:     #Trying to find the conditional for the file
 4207:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4208: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4209:     if ($match) {
 4210: 	return (1,$1);
 4211:     } else {
 4212: 	return (0,0);
 4213:     }
 4214: }
 4215: 
 4216: # --------------------------------------------------------- Get symb from alias
 4217: 
 4218: sub get_symb_from_alias {
 4219:     my $symb=shift;
 4220:     my ($map,$resid,$url)=&decode_symb($symb);
 4221: # Already is a symb
 4222:     if ($url) { return $symb; }
 4223: # Must be an alias
 4224:     my $aliassymb='';
 4225:     my %bighash;
 4226:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4227:                             &GDBM_READER(),0640)) {
 4228:         my $rid=$bighash{'mapalias_'.$symb};
 4229: 	if ($rid) {
 4230: 	    my ($mapid,$resid)=split(/\./,$rid);
 4231: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4232: 				    $resid,$bighash{'src_'.$rid});
 4233: 	}
 4234:         untie %bighash;
 4235:     }
 4236:     return $aliassymb;
 4237: }
 4238: 
 4239: # ----------------------------------------------------------------- Define Role
 4240: 
 4241: sub definerole {
 4242:   if (allowed('mcr','/')) {
 4243:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4244:     foreach my $role (split(':',$sysrole)) {
 4245: 	my ($crole,$cqual)=split(/\&/,$role);
 4246:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4247:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4248: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4249:                return "refused:s:$crole&$cqual"; 
 4250:             }
 4251:         }
 4252:     }
 4253:     foreach my $role (split(':',$domrole)) {
 4254: 	my ($crole,$cqual)=split(/\&/,$role);
 4255:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4256:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4257: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4258:                return "refused:d:$crole&$cqual"; 
 4259:             }
 4260:         }
 4261:     }
 4262:     foreach my $role (split(':',$courole)) {
 4263: 	my ($crole,$cqual)=split(/\&/,$role);
 4264:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4265:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4266: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4267:                return "refused:c:$crole&$cqual"; 
 4268:             }
 4269:         }
 4270:     }
 4271:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4272:                 "$env{'user.domain'}:$env{'user.name'}:".
 4273: 	        "rolesdef_$rolename=".
 4274:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4275:     return reply($command,$env{'user.home'});
 4276:   } else {
 4277:     return 'refused';
 4278:   }
 4279: }
 4280: 
 4281: # ---------------- Make a metadata query against the network of library servers
 4282: 
 4283: sub metadata_query {
 4284:     my ($query,$custom,$customshow,$server_array)=@_;
 4285:     my %rhash;
 4286:     my %libserv = &all_library();
 4287:     my @server_list = (defined($server_array) ? @$server_array
 4288:                                               : keys(%libserv) );
 4289:     for my $server (@server_list) {
 4290: 	unless ($custom or $customshow) {
 4291: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4292: 	    $rhash{$server}=$reply;
 4293: 	}
 4294: 	else {
 4295: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4296: 			     &escape($custom).':'.&escape($customshow),
 4297: 			     $server);
 4298: 	    $rhash{$server}=$reply;
 4299: 	}
 4300:     }
 4301:     return \%rhash;
 4302: }
 4303: 
 4304: # ----------------------------------------- Send log queries and wait for reply
 4305: 
 4306: sub log_query {
 4307:     my ($uname,$udom,$query,%filters)=@_;
 4308:     my $uhome=&homeserver($uname,$udom);
 4309:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4310:     my $uhost=&hostname($uhome);
 4311:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4312:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4313:                        $uhome);
 4314:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4315:     return get_query_reply($queryid);
 4316: }
 4317: 
 4318: # -------------------------- Update MySQL table for portfolio file
 4319: 
 4320: sub update_portfolio_table {
 4321:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4322:     my $homeserver = &homeserver($uname,$udom);
 4323:     my $queryid=
 4324:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4325:                ':'.&escape($file_name).':'.$action,$homeserver);
 4326:     my $reply = &get_query_reply($queryid);
 4327:     return $reply;
 4328: }
 4329: 
 4330: # ------- Request retrieval of institutional classlists for course(s)
 4331: 
 4332: sub fetch_enrollment_query {
 4333:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4334:     my $homeserver;
 4335:     my $maxtries = 1;
 4336:     if ($context eq 'automated') {
 4337:         $homeserver = $perlvar{'lonHostID'};
 4338:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4339:     } else {
 4340:         $homeserver = &homeserver($cnum,$dom);
 4341:     }
 4342:     my $host=&hostname($homeserver);
 4343:     my $cmd = '';
 4344:     foreach my $affiliate (keys %{$affiliatesref}) {
 4345:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4346:     }
 4347:     $cmd =~ s/%%$//;
 4348:     $cmd = &escape($cmd);
 4349:     my $query = 'fetchenrollment';
 4350:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4351:     unless ($queryid=~/^\Q$host\E\_/) { 
 4352:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4353:         return 'error: '.$queryid;
 4354:     }
 4355:     my $reply = &get_query_reply($queryid);
 4356:     my $tries = 1;
 4357:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4358:         $reply = &get_query_reply($queryid);
 4359:         $tries ++;
 4360:     }
 4361:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4362:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4363:     } else {
 4364:         my @responses = split/:/,$reply;
 4365:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4366:             foreach my $line (@responses) {
 4367:                 my ($key,$value) = split(/=/,$line,2);
 4368:                 $$replyref{$key} = $value;
 4369:             }
 4370:         } else {
 4371:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4372:             foreach my $line (@responses) {
 4373:                 my ($key,$value) = split(/=/,$line);
 4374:                 $$replyref{$key} = $value;
 4375:                 if ($value > 0) {
 4376:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4377:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4378:                         my $destname = $pathname.'/'.$filename;
 4379:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4380:                         if ($xml_classlist =~ /^error/) {
 4381:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4382:                         } else {
 4383:                             if ( open(FILE,">$destname") ) {
 4384:                                 print FILE &unescape($xml_classlist);
 4385:                                 close(FILE);
 4386:                             } else {
 4387:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4388:                             }
 4389:                         }
 4390:                     }
 4391:                 }
 4392:             }
 4393:         }
 4394:         return 'ok';
 4395:     }
 4396:     return 'error';
 4397: }
 4398: 
 4399: sub get_query_reply {
 4400:     my $queryid=shift;
 4401:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4402:     my $reply='';
 4403:     for (1..100) {
 4404: 	sleep 2;
 4405:         if (-e $replyfile.'.end') {
 4406: 	    if (open(my $fh,$replyfile)) {
 4407:                $reply.=<$fh>;
 4408:                close($fh);
 4409: 	   } else { return 'error: reply_file_error'; }
 4410:            return &unescape($reply);
 4411: 	}
 4412:     }
 4413:     return 'timeout:'.$queryid;
 4414: }
 4415: 
 4416: sub courselog_query {
 4417: #
 4418: # possible filters:
 4419: # url: url or symb
 4420: # username
 4421: # domain
 4422: # action: view, submit, grade
 4423: # start: timestamp
 4424: # end: timestamp
 4425: #
 4426:     my (%filters)=@_;
 4427:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4428:     if ($filters{'url'}) {
 4429: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4430:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4431:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4432:     }
 4433:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4434:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4435:     return &log_query($cname,$cdom,'courselog',%filters);
 4436: }
 4437: 
 4438: sub userlog_query {
 4439: #
 4440: # possible filters:
 4441: # action: log check role
 4442: # start: timestamp
 4443: # end: timestamp
 4444: #
 4445:     my ($uname,$udom,%filters)=@_;
 4446:     return &log_query($uname,$udom,'userlog',%filters);
 4447: }
 4448: 
 4449: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4450: 
 4451: sub auto_run {
 4452:     my ($cnum,$cdom) = @_;
 4453:     my $homeserver = &homeserver($cnum,$cdom);
 4454:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4455:     return $response;
 4456: }
 4457: 
 4458: sub auto_get_sections {
 4459:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4460:     my $homeserver = &homeserver($cnum,$cdom);
 4461:     my @secs = ();
 4462:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4463:     unless ($response eq 'refused') {
 4464:         @secs = split/:/,$response;
 4465:     }
 4466:     return @secs;
 4467: }
 4468: 
 4469: sub auto_new_course {
 4470:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4471:     my $homeserver = &homeserver($cnum,$cdom);
 4472:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4473:     return $response;
 4474: }
 4475: 
 4476: sub auto_validate_courseID {
 4477:     my ($cnum,$cdom,$inst_course_id) = @_;
 4478:     my $homeserver = &homeserver($cnum,$cdom);
 4479:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4480:     return $response;
 4481: }
 4482: 
 4483: sub auto_create_password {
 4484:     my ($cnum,$cdom,$authparam) = @_;
 4485:     my $homeserver = &homeserver($cnum,$cdom); 
 4486:     my $create_passwd = 0;
 4487:     my $authchk = '';
 4488:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4489:     if ($response eq 'refused') {
 4490:         $authchk = 'refused';
 4491:     } else {
 4492:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4493:     }
 4494:     return ($authparam,$create_passwd,$authchk);
 4495: }
 4496: 
 4497: sub auto_photo_permission {
 4498:     my ($cnum,$cdom,$students) = @_;
 4499:     my $homeserver = &homeserver($cnum,$cdom);
 4500:     my ($outcome,$perm_reqd,$conditions) = 
 4501: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4502:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4503: 	return (undef,undef);
 4504:     }
 4505:     return ($outcome,$perm_reqd,$conditions);
 4506: }
 4507: 
 4508: sub auto_checkphotos {
 4509:     my ($uname,$udom,$pid) = @_;
 4510:     my $homeserver = &homeserver($uname,$udom);
 4511:     my ($result,$resulttype);
 4512:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4513: 				   &escape($uname).':'.&escape($pid),
 4514: 				   $homeserver));
 4515:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4516: 	return (undef,undef);
 4517:     }
 4518:     if ($outcome) {
 4519:         ($result,$resulttype) = split(/:/,$outcome);
 4520:     } 
 4521:     return ($result,$resulttype);
 4522: }
 4523: 
 4524: sub auto_photochoice {
 4525:     my ($cnum,$cdom) = @_;
 4526:     my $homeserver = &homeserver($cnum,$cdom);
 4527:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4528: 						       &escape($cdom),
 4529: 						       $homeserver)));
 4530:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4531: 	return (undef,undef);
 4532:     }
 4533:     return ($update,$comment);
 4534: }
 4535: 
 4536: sub auto_photoupdate {
 4537:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4538:     my $homeserver = &homeserver($cnum,$dom);
 4539:     my $host=&hostname($homeserver);
 4540:     my $cmd = '';
 4541:     my $maxtries = 1;
 4542:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4543:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4544:     }
 4545:     $cmd =~ s/%%$//;
 4546:     $cmd = &escape($cmd);
 4547:     my $query = 'institutionalphotos';
 4548:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4549:     unless ($queryid=~/^\Q$host\E\_/) {
 4550:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4551:         return 'error: '.$queryid;
 4552:     }
 4553:     my $reply = &get_query_reply($queryid);
 4554:     my $tries = 1;
 4555:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4556:         $reply = &get_query_reply($queryid);
 4557:         $tries ++;
 4558:     }
 4559:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4560:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4561:     } else {
 4562:         my @responses = split(/:/,$reply);
 4563:         my $outcome = shift(@responses); 
 4564:         foreach my $item (@responses) {
 4565:             my ($key,$value) = split(/=/,$item);
 4566:             $$photo{$key} = $value;
 4567:         }
 4568:         return $outcome;
 4569:     }
 4570:     return 'error';
 4571: }
 4572: 
 4573: sub auto_instcode_format {
 4574:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4575: 	$cat_order) = @_;
 4576:     my $courses = '';
 4577:     my @homeservers;
 4578:     if ($caller eq 'global') {
 4579: 	my %servers = &get_servers($codedom,'library');
 4580: 	foreach my $tryserver (keys(%servers)) {
 4581: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4582: 		push(@homeservers,$tryserver);
 4583: 	    }
 4584:         }
 4585:     } else {
 4586:         push(@homeservers,&homeserver($caller,$codedom));
 4587:     }
 4588:     foreach my $code (keys(%{$instcodes})) {
 4589:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4590:     }
 4591:     chop($courses);
 4592:     my $ok_response = 0;
 4593:     my $response;
 4594:     while (@homeservers > 0 && $ok_response == 0) {
 4595:         my $server = shift(@homeservers); 
 4596:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4597:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4598:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4599: 		split/:/,$response;
 4600:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4601:             push(@{$codetitles},&str2array($codetitles_str));
 4602:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4603:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4604:             $ok_response = 1;
 4605:         }
 4606:     }
 4607:     if ($ok_response) {
 4608:         return 'ok';
 4609:     } else {
 4610:         return $response;
 4611:     }
 4612: }
 4613: 
 4614: sub auto_instcode_defaults {
 4615:     my ($domain,$returnhash,$code_order) = @_;
 4616:     my @homeservers;
 4617: 
 4618:     my %servers = &get_servers($domain,'library');
 4619:     foreach my $tryserver (keys(%servers)) {
 4620: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4621: 	    push(@homeservers,$tryserver);
 4622: 	}
 4623:     }
 4624: 
 4625:     my $response;
 4626:     foreach my $server (@homeservers) {
 4627:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4628:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4629: 	
 4630: 	foreach my $pair (split(/\&/,$response)) {
 4631: 	    my ($name,$value)=split(/\=/,$pair);
 4632: 	    if ($name eq 'code_order') {
 4633: 		@{$code_order} = split(/\&/,&unescape($value));
 4634: 	    } else {
 4635: 		$returnhash->{&unescape($name)}=&unescape($value);
 4636: 	    }
 4637: 	}
 4638: 	return 'ok';
 4639:     }
 4640: 
 4641:     return $response;
 4642: } 
 4643: 
 4644: sub auto_validate_class_sec {
 4645:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4646:     my $homeserver = &homeserver($cnum,$cdom);
 4647:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4648:                         &escape($owner).':'.$cdom,$homeserver);
 4649:     return $response;
 4650: }
 4651: 
 4652: # ------------------------------------------------------- Course Group routines
 4653: 
 4654: sub get_coursegroups {
 4655:     my ($cdom,$cnum,$group,$namespace) = @_;
 4656:     return(&dump($namespace,$cdom,$cnum,$group));
 4657: }
 4658: 
 4659: sub modify_coursegroup {
 4660:     my ($cdom,$cnum,$groupsettings) = @_;
 4661:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4662: }
 4663: 
 4664: sub toggle_coursegroup_status {
 4665:     my ($cdom,$cnum,$group,$action) = @_;
 4666:     my ($from_namespace,$to_namespace);
 4667:     if ($action eq 'delete') {
 4668:         $from_namespace = 'coursegroups';
 4669:         $to_namespace = 'deleted_groups';
 4670:     } else {
 4671:         $from_namespace = 'deleted_groups';
 4672:         $to_namespace = 'coursegroups';
 4673:     }
 4674:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4675:     if (my $tmp = &error(%curr_group)) {
 4676:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4677:         return ('read error',$tmp);
 4678:     } else {
 4679:         my %savedsettings = %curr_group; 
 4680:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4681:         my $deloutcome;
 4682:         if ($result eq 'ok') {
 4683:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4684:         } else {
 4685:             return ('write error',$result);
 4686:         }
 4687:         if ($deloutcome eq 'ok') {
 4688:             return 'ok';
 4689:         } else {
 4690:             return ('delete error',$deloutcome);
 4691:         }
 4692:     }
 4693: }
 4694: 
 4695: sub modify_group_roles {
 4696:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4697:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4698:     my $role = 'gr/'.&escape($userprivs);
 4699:     my ($uname,$udom) = split(/:/,$user);
 4700:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4701:     if ($result eq 'ok') {
 4702:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4703:     }
 4704:     return $result;
 4705: }
 4706: 
 4707: sub modify_coursegroup_membership {
 4708:     my ($cdom,$cnum,$membership) = @_;
 4709:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4710:     return $result;
 4711: }
 4712: 
 4713: sub get_active_groups {
 4714:     my ($udom,$uname,$cdom,$cnum) = @_;
 4715:     my $now = time;
 4716:     my %groups = ();
 4717:     foreach my $key (keys(%env)) {
 4718:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4719:             my ($start,$end) = split(/\./,$env{$key});
 4720:             if (($end!=0) && ($end<$now)) { next; }
 4721:             if (($start!=0) && ($start>$now)) { next; }
 4722:             if ($1 eq $cdom && $2 eq $cnum) {
 4723:                 $groups{$3} = $env{$key} ;
 4724:             }
 4725:         }
 4726:     }
 4727:     return %groups;
 4728: }
 4729: 
 4730: sub get_group_membership {
 4731:     my ($cdom,$cnum,$group) = @_;
 4732:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4733: }
 4734: 
 4735: sub get_users_groups {
 4736:     my ($udom,$uname,$courseid) = @_;
 4737:     my @usersgroups;
 4738:     my $cachetime=1800;
 4739: 
 4740:     my $hashid="$udom:$uname:$courseid";
 4741:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4742:     if (defined($cached)) {
 4743:         @usersgroups = split(/:/,$grouplist);
 4744:     } else {  
 4745:         $grouplist = '';
 4746:         my $courseurl = &courseid_to_courseurl($courseid);
 4747:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4748:         my $access_end = $env{'course.'.$courseid.
 4749:                               '.default_enrollment_end_date'};
 4750:         my $now = time;
 4751:         foreach my $key (keys(%roleshash)) {
 4752:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4753:                 my $group = $1;
 4754:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4755:                     my $start = $2;
 4756:                     my $end = $1;
 4757:                     if ($start == -1) { next; } # deleted from group
 4758:                     if (($start!=0) && ($start>$now)) { next; }
 4759:                     if (($end!=0) && ($end<$now)) {
 4760:                         if ($access_end && $access_end < $now) {
 4761:                             if ($access_end - $end < 86400) {
 4762:                                 push(@usersgroups,$group);
 4763:                             }
 4764:                         }
 4765:                         next;
 4766:                     }
 4767:                     push(@usersgroups,$group);
 4768:                 }
 4769:             }
 4770:         }
 4771:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4772:         $grouplist = join(':',@usersgroups);
 4773:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4774:     }
 4775:     return @usersgroups;
 4776: }
 4777: 
 4778: sub devalidate_getgroups_cache {
 4779:     my ($udom,$uname,$cdom,$cnum)=@_;
 4780:     my $courseid = $cdom.'_'.$cnum;
 4781: 
 4782:     my $hashid="$udom:$uname:$courseid";
 4783:     &devalidate_cache_new('getgroups',$hashid);
 4784: }
 4785: 
 4786: # ------------------------------------------------------------------ Plain Text
 4787: 
 4788: sub plaintext {
 4789:     my ($short,$type,$cid) = @_;
 4790:     if ($short =~ /^cr/) {
 4791: 	return (split('/',$short))[-1];
 4792:     }
 4793:     if (!defined($cid)) {
 4794:         $cid = $env{'request.course.id'};
 4795:     }
 4796:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4797:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4798:                                           '.plaintext'});
 4799:     }
 4800:     my %rolenames = (
 4801:                       Course => 'std',
 4802:                       Group => 'alt1',
 4803:                     );
 4804:     if (defined($type) && 
 4805:          defined($rolenames{$type}) && 
 4806:          defined($prp{$short}{$rolenames{$type}})) {
 4807:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4808:     } else {
 4809:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4810:     }
 4811: }
 4812: 
 4813: # ----------------------------------------------------------------- Assign Role
 4814: 
 4815: sub assignrole {
 4816:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4817:     my $mrole;
 4818:     if ($role =~ /^cr\//) {
 4819:         my $cwosec=$url;
 4820:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4821: 	unless (&allowed('ccr',$cwosec)) {
 4822:            &logthis('Refused custom assignrole: '.
 4823:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4824: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4825:            return 'refused'; 
 4826:         }
 4827:         $mrole='cr';
 4828:     } elsif ($role =~ /^gr\//) {
 4829:         my $cwogrp=$url;
 4830:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4831:         unless (&allowed('mdg',$cwogrp)) {
 4832:             &logthis('Refused group assignrole: '.
 4833:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4834:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4835:             return 'refused';
 4836:         }
 4837:         $mrole='gr';
 4838:     } else {
 4839:         my $cwosec=$url;
 4840:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4841:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4842:            &logthis('Refused assignrole: '.
 4843:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4844: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4845:            return 'refused'; 
 4846:         }
 4847:         $mrole=$role;
 4848:     }
 4849:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4850:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4851:     if ($end) { $command.='_'.$end; }
 4852:     if ($start) {
 4853: 	if ($end) { 
 4854:            $command.='_'.$start; 
 4855:         } else {
 4856:            $command.='_0_'.$start;
 4857:         }
 4858:     }
 4859:     my $origstart = $start;
 4860:     my $origend = $end;
 4861: # actually delete
 4862:     if ($deleteflag) {
 4863: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4864: # modify command to delete the role
 4865:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4866:                 "$udom:$uname:$url".'_'."$mrole";
 4867: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4868: # set start and finish to negative values for userrolelog
 4869:            $start=-1;
 4870:            $end=-1;
 4871:         }
 4872:     }
 4873: # send command
 4874:     my $answer=&reply($command,&homeserver($uname,$udom));
 4875: # log new user role if status is ok
 4876:     if ($answer eq 'ok') {
 4877: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4878: # for course roles, perform group memberships changes triggered by role change.
 4879:         unless ($role =~ /^gr/) {
 4880:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4881:                                              $origstart);
 4882:         }
 4883:     }
 4884:     return $answer;
 4885: }
 4886: 
 4887: # -------------------------------------------------- Modify user authentication
 4888: # Overrides without validation
 4889: 
 4890: sub modifyuserauth {
 4891:     my ($udom,$uname,$umode,$upass)=@_;
 4892:     my $uhome=&homeserver($uname,$udom);
 4893:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4894:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4895:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4896:              ' in domain '.$env{'request.role.domain'});  
 4897:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4898: 		     &escape($upass),$uhome);
 4899:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4900:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4901:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4902:     &log($udom,,$uname,$uhome,
 4903:         'Authentication changed by '.$env{'user.domain'}.', '.
 4904:                                      $env{'user.name'}.', '.$umode.
 4905:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4906:     unless ($reply eq 'ok') {
 4907:         &logthis('Authentication mode error: '.$reply);
 4908: 	return 'error: '.$reply;
 4909:     }   
 4910:     return 'ok';
 4911: }
 4912: 
 4913: # --------------------------------------------------------------- Modify a user
 4914: 
 4915: sub modifyuser {
 4916:     my ($udom,    $uname, $uid,
 4917:         $umode,   $upass, $first,
 4918:         $middle,  $last,  $gene,
 4919:         $forceid, $desiredhome, $email)=@_;
 4920:     $udom= &LONCAPA::clean_domain($udom);
 4921:     $uname=&LONCAPA::clean_username($uname);
 4922:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4923:              $umode.', '.$first.', '.$middle.', '.
 4924: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4925:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4926:                                      ' desiredhome not specified'). 
 4927:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4928:              ' in domain '.$env{'request.role.domain'});
 4929:     my $uhome=&homeserver($uname,$udom,'true');
 4930: # ----------------------------------------------------------------- Create User
 4931:     if (($uhome eq 'no_host') && 
 4932: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4933:         my $unhome='';
 4934:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4935:             $unhome = $desiredhome;
 4936: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4937: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4938:         } else { # load balancing routine for determining $unhome
 4939:             my $loadm=10000000;
 4940: 	    my %servers = &get_servers($udom,'library');
 4941: 	    foreach my $tryserver (keys(%servers)) {
 4942: 		my $answer=reply('load',$tryserver);
 4943: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4944: 		    $loadm=$answer;
 4945: 		    $unhome=$tryserver;
 4946: 		}
 4947: 	    }
 4948:         }
 4949:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4950: 	    return 'error: unable to find a home server for '.$uname.
 4951:                    ' in domain '.$udom;
 4952:         }
 4953:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4954:                          &escape($upass),$unhome);
 4955: 	unless ($reply eq 'ok') {
 4956:             return 'error: '.$reply;
 4957:         }   
 4958:         $uhome=&homeserver($uname,$udom,'true');
 4959:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4960: 	    return 'error: unable verify users home machine.';
 4961:         }
 4962:     }   # End of creation of new user
 4963: # ---------------------------------------------------------------------- Add ID
 4964:     if ($uid) {
 4965:        $uid=~tr/A-Z/a-z/;
 4966:        my %uidhash=&idrget($udom,$uname);
 4967:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4968:          && (!$forceid)) {
 4969: 	  unless ($uid eq $uidhash{$uname}) {
 4970: 	      return 'error: user id "'.$uid.'" does not match '.
 4971:                   'current user id "'.$uidhash{$uname}.'".';
 4972:           }
 4973:        } else {
 4974: 	  &idput($udom,($uname => $uid));
 4975:        }
 4976:     }
 4977: # -------------------------------------------------------------- Add names, etc
 4978:     my @tmp=&get('environment',
 4979: 		   ['firstname','middlename','lastname','generation'],
 4980: 		   $udom,$uname);
 4981:     my %names;
 4982:     if ($tmp[0] =~ m/^error:.*/) { 
 4983:         %names=(); 
 4984:     } else {
 4985:         %names = @tmp;
 4986:     }
 4987: #
 4988: # Make sure to not trash student environment if instructor does not bother
 4989: # to supply name and email information
 4990: #
 4991:     if ($first)  { $names{'firstname'}  = $first; }
 4992:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4993:     if ($last)   { $names{'lastname'}   = $last; }
 4994:     if (defined($gene))   { $names{'generation'} = $gene; }
 4995:     if ($email) {
 4996:        $email=~s/[^\w\@\.\-\,]//gs;
 4997:        if ($email=~/\@/) { $names{'notification'} = $email;
 4998: 			   $names{'critnotification'} = $email;
 4999: 			   $names{'permanentemail'} = $email; }
 5000:     }
 5001:     my $reply = &put('environment', \%names, $udom,$uname);
 5002:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5003:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5004:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5005:              $umode.', '.$first.', '.$middle.', '.
 5006: 	     $last.', '.$gene.' by '.
 5007:              $env{'user.name'}.' at '.$env{'user.domain'});
 5008:     return 'ok';
 5009: }
 5010: 
 5011: # -------------------------------------------------------------- Modify student
 5012: 
 5013: sub modifystudent {
 5014:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5015:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5016:     if (!$cid) {
 5017: 	unless ($cid=$env{'request.course.id'}) {
 5018: 	    return 'not_in_class';
 5019: 	}
 5020:     }
 5021: # --------------------------------------------------------------- Make the user
 5022:     my $reply=&modifyuser
 5023: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5024:          $desiredhome,$email);
 5025:     unless ($reply eq 'ok') { return $reply; }
 5026:     # This will cause &modify_student_enrollment to get the uid from the
 5027:     # students environment
 5028:     $uid = undef if (!$forceid);
 5029:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5030: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5031:     return $reply;
 5032: }
 5033: 
 5034: sub modify_student_enrollment {
 5035:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5036:     my ($cdom,$cnum,$chome);
 5037:     if (!$cid) {
 5038: 	unless ($cid=$env{'request.course.id'}) {
 5039: 	    return 'not_in_class';
 5040: 	}
 5041: 	$cdom=$env{'course.'.$cid.'.domain'};
 5042: 	$cnum=$env{'course.'.$cid.'.num'};
 5043:     } else {
 5044: 	($cdom,$cnum)=split(/_/,$cid);
 5045:     }
 5046:     $chome=$env{'course.'.$cid.'.home'};
 5047:     if (!$chome) {
 5048: 	$chome=&homeserver($cnum,$cdom);
 5049:     }
 5050:     if (!$chome) { return 'unknown_course'; }
 5051:     # Make sure the user exists
 5052:     my $uhome=&homeserver($uname,$udom);
 5053:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5054: 	return 'error: no such user';
 5055:     }
 5056:     # Get student data if we were not given enough information
 5057:     if (!defined($first)  || $first  eq '' || 
 5058:         !defined($last)   || $last   eq '' || 
 5059:         !defined($uid)    || $uid    eq '' || 
 5060:         !defined($middle) || $middle eq '' || 
 5061:         !defined($gene)   || $gene   eq '') {
 5062:         # They did not supply us with enough data to enroll the student, so
 5063:         # we need to pick up more information.
 5064:         my %tmp = &get('environment',
 5065:                        ['firstname','middlename','lastname', 'generation','id']
 5066:                        ,$udom,$uname);
 5067: 
 5068:         #foreach my $key (keys(%tmp)) {
 5069:         #    &logthis("key $key = ".$tmp{$key});
 5070:         #}
 5071:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5072:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5073:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5074:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5075:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5076:     }
 5077:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5078:     my $reply=cput('classlist',
 5079: 		   {"$uname:$udom" => 
 5080: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5081: 		   $cdom,$cnum);
 5082:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5083: 	return 'error: '.$reply;
 5084:     } else {
 5085: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5086:     }
 5087:     # Add student role to user
 5088:     my $uurl='/'.$cid;
 5089:     $uurl=~s/\_/\//g;
 5090:     if ($usec) {
 5091: 	$uurl.='/'.$usec;
 5092:     }
 5093:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5094: }
 5095: 
 5096: sub format_name {
 5097:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5098:     my $name;
 5099:     if ($first ne 'lastname') {
 5100: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5101:     } else {
 5102: 	if ($lastname=~/\S/) {
 5103: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5104: 	    $name=~s/\s+,/,/;
 5105: 	} else {
 5106: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5107: 	}
 5108:     }
 5109:     $name=~s/^\s+//;
 5110:     $name=~s/\s+$//;
 5111:     $name=~s/\s+/ /g;
 5112:     return $name;
 5113: }
 5114: 
 5115: # ------------------------------------------------- Write to course preferences
 5116: 
 5117: sub writecoursepref {
 5118:     my ($courseid,%prefs)=@_;
 5119:     $courseid=~s/^\///;
 5120:     $courseid=~s/\_/\//g;
 5121:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5122:     my $chome=homeserver($cnum,$cdomain);
 5123:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5124: 	return 'error: no such course';
 5125:     }
 5126:     my $cstring='';
 5127:     foreach my $pref (keys(%prefs)) {
 5128: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5129:     }
 5130:     $cstring=~s/\&$//;
 5131:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5132: }
 5133: 
 5134: # ---------------------------------------------------------- Make/modify course
 5135: 
 5136: sub createcourse {
 5137:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5138:         $course_owner,$crstype)=@_;
 5139:     $url=&declutter($url);
 5140:     my $cid='';
 5141:     unless (&allowed('ccc',$udom)) {
 5142:         return 'refused';
 5143:     }
 5144: # ------------------------------------------------------------------- Create ID
 5145:    my $uname=int(1+rand(9)).
 5146:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5147:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5148:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5149: # ----------------------------------------------- Make sure that does not exist
 5150:    my $uhome=&homeserver($uname,$udom,'true');
 5151:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5152:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5153:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5154:        $uhome=&homeserver($uname,$udom,'true');       
 5155:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5156:            return 'error: unable to generate unique course-ID';
 5157:        } 
 5158:    }
 5159: # ------------------------------------------------ Check supplied server name
 5160:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5161:     if (! &is_library($course_server)) {
 5162:         return 'error:bad server name '.$course_server;
 5163:     }
 5164: # ------------------------------------------------------------- Make the course
 5165:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5166:                       $course_server);
 5167:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5168:     $uhome=&homeserver($uname,$udom,'true');
 5169:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5170: 	return 'error: no such course';
 5171:     }
 5172: # ----------------------------------------------------------------- Course made
 5173: # log existence
 5174:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5175:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5176:                   &escape($crstype),$uhome);
 5177:     &flushcourselogs();
 5178: # set toplevel url
 5179:     my $topurl=$url;
 5180:     unless ($nonstandard) {
 5181: # ------------------------------------------ For standard courses, make top url
 5182:         my $mapurl=&clutter($url);
 5183:         if ($mapurl eq '/res/') { $mapurl=''; }
 5184:         $env{'form.initmap'}=(<<ENDINITMAP);
 5185: <map>
 5186: <resource id="1" type="start"></resource>
 5187: <resource id="2" src="$mapurl"></resource>
 5188: <resource id="3" type="finish"></resource>
 5189: <link index="1" from="1" to="2"></link>
 5190: <link index="2" from="2" to="3"></link>
 5191: </map>
 5192: ENDINITMAP
 5193:         $topurl=&declutter(
 5194:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5195:                           );
 5196:     }
 5197: # ----------------------------------------------------------- Write preferences
 5198:     &writecoursepref($udom.'_'.$uname,
 5199:                      ('description' => $description,
 5200:                       'url'         => $topurl));
 5201:     return '/'.$udom.'/'.$uname;
 5202: }
 5203: 
 5204: sub is_course {
 5205:     my ($cdom,$cnum) = @_;
 5206:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5207: 				undef,'.');
 5208:     if (exists($courses{$cdom.'_'.$cnum})) {
 5209:         return 1;
 5210:     }
 5211:     return 0;
 5212: }
 5213: 
 5214: # ---------------------------------------------------------- Assign Custom Role
 5215: 
 5216: sub assigncustomrole {
 5217:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5218:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5219:                        $end,$start,$deleteflag);
 5220: }
 5221: 
 5222: # ----------------------------------------------------------------- Revoke Role
 5223: 
 5224: sub revokerole {
 5225:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5226:     my $now=time;
 5227:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5228: }
 5229: 
 5230: # ---------------------------------------------------------- Revoke Custom Role
 5231: 
 5232: sub revokecustomrole {
 5233:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5234:     my $now=time;
 5235:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5236:            $deleteflag);
 5237: }
 5238: 
 5239: # ------------------------------------------------------------ Disk usage
 5240: sub diskusage {
 5241:     my ($udom,$uname,$directoryRoot)=@_;
 5242:     $directoryRoot =~ s/\/$//;
 5243:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5244:     return $listing;
 5245: }
 5246: 
 5247: sub is_locked {
 5248:     my ($file_name, $domain, $user) = @_;
 5249:     my @check;
 5250:     my $is_locked;
 5251:     push @check, $file_name;
 5252:     my %locked = &get('file_permissions',\@check,
 5253: 		      $env{'user.domain'},$env{'user.name'});
 5254:     my ($tmp)=keys(%locked);
 5255:     if ($tmp=~/^error:/) { undef(%locked); }
 5256:     
 5257:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5258:         $is_locked = 'false';
 5259:         foreach my $entry (@{$locked{$file_name}}) {
 5260:            if (ref($entry) eq 'ARRAY') { 
 5261:                $is_locked = 'true';
 5262:                last;
 5263:            }
 5264:        }
 5265:     } else {
 5266:         $is_locked = 'false';
 5267:     }
 5268: }
 5269: 
 5270: sub declutter_portfile {
 5271:     my ($file) = @_;
 5272:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5273:     return $file;
 5274: }
 5275: 
 5276: # ------------------------------------------------------------- Mark as Read Only
 5277: 
 5278: sub mark_as_readonly {
 5279:     my ($domain,$user,$files,$what) = @_;
 5280:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5281:     my ($tmp)=keys(%current_permissions);
 5282:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5283:     foreach my $file (@{$files}) {
 5284: 	$file = &declutter_portfile($file);
 5285:         push(@{$current_permissions{$file}},$what);
 5286:     }
 5287:     &put('file_permissions',\%current_permissions,$domain,$user);
 5288:     return;
 5289: }
 5290: 
 5291: # ------------------------------------------------------------Save Selected Files
 5292: 
 5293: sub save_selected_files {
 5294:     my ($user, $path, @files) = @_;
 5295:     my $filename = $user."savedfiles";
 5296:     my @other_files = &files_not_in_path($user, $path);
 5297:     open (OUT, '>'.$tmpdir.$filename);
 5298:     foreach my $file (@files) {
 5299:         print (OUT $env{'form.currentpath'}.$file."\n");
 5300:     }
 5301:     foreach my $file (@other_files) {
 5302:         print (OUT $file."\n");
 5303:     }
 5304:     close (OUT);
 5305:     return 'ok';
 5306: }
 5307: 
 5308: sub clear_selected_files {
 5309:     my ($user) = @_;
 5310:     my $filename = $user."savedfiles";
 5311:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5312:     print (OUT undef);
 5313:     close (OUT);
 5314:     return ("ok");    
 5315: }
 5316: 
 5317: sub files_in_path {
 5318:     my ($user, $path) = @_;
 5319:     my $filename = $user."savedfiles";
 5320:     my %return_files;
 5321:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5322:     while (my $line_in = <IN>) {
 5323:         chomp ($line_in);
 5324:         my @paths_and_file = split (m!/!, $line_in);
 5325:         my $file_part = pop (@paths_and_file);
 5326:         my $path_part = join ('/', @paths_and_file);
 5327:         $path_part.='/';
 5328:         my $path_and_file = $path_part.$file_part;
 5329:         if ($path_part eq $path) {
 5330:             $return_files{$file_part}= 'selected';
 5331:         }
 5332:     }
 5333:     close (IN);
 5334:     return (\%return_files);
 5335: }
 5336: 
 5337: # called in portfolio select mode, to show files selected NOT in current directory
 5338: sub files_not_in_path {
 5339:     my ($user, $path) = @_;
 5340:     my $filename = $user."savedfiles";
 5341:     my @return_files;
 5342:     my $path_part;
 5343:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5344:     while (my $line = <IN>) {
 5345:         #ok, I know it's clunky, but I want it to work
 5346:         my @paths_and_file = split(m|/|, $line);
 5347:         my $file_part = pop(@paths_and_file);
 5348:         chomp($file_part);
 5349:         my $path_part = join('/', @paths_and_file);
 5350:         $path_part .= '/';
 5351:         my $path_and_file = $path_part.$file_part;
 5352:         if ($path_part ne $path) {
 5353:             push(@return_files, ($path_and_file));
 5354:         }
 5355:     }
 5356:     close(OUT);
 5357:     return (@return_files);
 5358: }
 5359: 
 5360: #----------------------------------------------Get portfolio file permissions
 5361: 
 5362: sub get_portfile_permissions {
 5363:     my ($domain,$user) = @_;
 5364:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5365:     my ($tmp)=keys(%current_permissions);
 5366:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5367:     return \%current_permissions;
 5368: }
 5369: 
 5370: #---------------------------------------------Get portfolio file access controls
 5371: 
 5372: sub get_access_controls {
 5373:     my ($current_permissions,$group,$file) = @_;
 5374:     my %access;
 5375:     my $real_file = $file;
 5376:     $file =~ s/\.meta$//;
 5377:     if (defined($file)) {
 5378:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5379:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5380:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5381:             }
 5382:         }
 5383:     } else {
 5384:         foreach my $key (keys(%{$current_permissions})) {
 5385:             if ($key =~ /\0accesscontrol$/) {
 5386:                 if (defined($group)) {
 5387:                     if ($key !~ m-^\Q$group\E/-) {
 5388:                         next;
 5389:                     }
 5390:                 }
 5391:                 my ($fullpath) = split(/\0/,$key);
 5392:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5393:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5394:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5395:                     }
 5396:                 }
 5397:             }
 5398:         }
 5399:     }
 5400:     return %access;
 5401: }
 5402: 
 5403: sub modify_access_controls {
 5404:     my ($file_name,$changes,$domain,$user)=@_;
 5405:     my ($outcome,$deloutcome);
 5406:     my %store_permissions;
 5407:     my %new_values;
 5408:     my %new_control;
 5409:     my %translation;
 5410:     my @deletions = ();
 5411:     my $now = time;
 5412:     if (exists($$changes{'activate'})) {
 5413:         if (ref($$changes{'activate'}) eq 'HASH') {
 5414:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5415:             my $numnew = scalar(@newitems);
 5416:             for (my $i=0; $i<$numnew; $i++) {
 5417:                 my $newkey = $newitems[$i];
 5418:                 my $newid = &Apache::loncommon::get_cgi_id();
 5419:                 if ($newkey =~ /^\d+:/) { 
 5420:                     $newkey =~ s/^(\d+)/$newid/;
 5421:                     $translation{$1} = $newid;
 5422:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5423:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5424:                     $translation{$1} = $newid;
 5425:                 }
 5426:                 $new_values{$file_name."\0".$newkey} = 
 5427:                                           $$changes{'activate'}{$newitems[$i]};
 5428:                 $new_control{$newkey} = $now;
 5429:             }
 5430:         }
 5431:     }
 5432:     my %todelete;
 5433:     my %changed_items;
 5434:     foreach my $action ('delete','update') {
 5435:         if (exists($$changes{$action})) {
 5436:             if (ref($$changes{$action}) eq 'HASH') {
 5437:                 foreach my $key (keys(%{$$changes{$action}})) {
 5438:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5439:                     if ($action eq 'delete') { 
 5440:                         $todelete{$itemnum} = 1;
 5441:                     } else {
 5442:                         $changed_items{$itemnum} = $key;
 5443:                     }
 5444:                 }
 5445:             }
 5446:         }
 5447:     }
 5448:     # get lock on access controls for file.
 5449:     my $lockhash = {
 5450:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5451:                                                        ':'.$env{'user.domain'},
 5452:                    }; 
 5453:     my $tries = 0;
 5454:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5455:    
 5456:     while (($gotlock ne 'ok') && $tries <3) {
 5457:         $tries ++;
 5458:         sleep 1;
 5459:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5460:     }
 5461:     if ($gotlock eq 'ok') {
 5462:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5463:         my ($tmp)=keys(%curr_permissions);
 5464:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5465:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5466:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5467:             if (ref($curr_controls) eq 'HASH') {
 5468:                 foreach my $control_item (keys(%{$curr_controls})) {
 5469:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5470:                     if (defined($todelete{$itemnum})) {
 5471:                         push(@deletions,$file_name."\0".$control_item);
 5472:                     } else {
 5473:                         if (defined($changed_items{$itemnum})) {
 5474:                             $new_control{$changed_items{$itemnum}} = $now;
 5475:                             push(@deletions,$file_name."\0".$control_item);
 5476:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5477:                         } else {
 5478:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5479:                         }
 5480:                     }
 5481:                 }
 5482:             }
 5483:         }
 5484:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5485:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5486:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5487:         #  remove lock
 5488:         my @del_lock = ($file_name."\0".'locked_access_records');
 5489:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5490:         my ($file,$group);
 5491:         if (&is_course($domain,$user)) {
 5492:             ($group,$file) = split(/\//,$file_name,2);
 5493:         } else {
 5494:             $file = $file_name;
 5495:         }
 5496:         my $sqlresult =
 5497:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5498:                                     $group);
 5499:     } else {
 5500:         $outcome = "error: could not obtain lockfile\n";  
 5501:     }
 5502:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5503: }
 5504: 
 5505: sub make_public_indefinitely {
 5506:     my ($requrl) = @_;
 5507:     my $now = time;
 5508:     my $action = 'activate';
 5509:     my $aclnum = 0;
 5510:     if (&is_portfolio_url($requrl)) {
 5511:         my (undef,$udom,$unum,$file_name,$group) =
 5512:             &parse_portfolio_url($requrl);
 5513:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5514:         my %access_controls = &get_access_controls($current_perms,
 5515:                                                    $group,$file_name);
 5516:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5517:             my ($num,$scope,$end,$start) = 
 5518:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5519:             if ($scope eq 'public') {
 5520:                 if ($start <= $now && $end == 0) {
 5521:                     $action = 'none';
 5522:                 } else {
 5523:                     $action = 'update';
 5524:                     $aclnum = $num;
 5525:                 }
 5526:                 last;
 5527:             }
 5528:         }
 5529:         if ($action eq 'none') {
 5530:              return 'ok';
 5531:         } else {
 5532:             my %changes;
 5533:             my $newend = 0;
 5534:             my $newstart = $now;
 5535:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5536:             $changes{$action}{$newkey} = {
 5537:                 type => 'public',
 5538:                 time => {
 5539:                     start => $newstart,
 5540:                     end   => $newend,
 5541:                 },
 5542:             };
 5543:             my ($outcome,$deloutcome,$new_values,$translation) =
 5544:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5545:             return $outcome;
 5546:         }
 5547:     } else {
 5548:         return 'invalid';
 5549:     }
 5550: }
 5551: 
 5552: #------------------------------------------------------Get Marked as Read Only
 5553: 
 5554: sub get_marked_as_readonly {
 5555:     my ($domain,$user,$what,$group) = @_;
 5556:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5557:     my @readonly_files;
 5558:     my $cmp1=$what;
 5559:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5560:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5561:         if (defined($group)) {
 5562:             if ($file_name !~ m-^\Q$group\E/-) {
 5563:                 next;
 5564:             }
 5565:         }
 5566:         if (ref($value) eq "ARRAY"){
 5567:             foreach my $stored_what (@{$value}) {
 5568:                 my $cmp2=$stored_what;
 5569:                 if (ref($stored_what) eq 'ARRAY') {
 5570:                     $cmp2=join('',@{$stored_what});
 5571:                 }
 5572:                 if ($cmp1 eq $cmp2) {
 5573:                     push(@readonly_files, $file_name);
 5574:                     last;
 5575:                 } elsif (!defined($what)) {
 5576:                     push(@readonly_files, $file_name);
 5577:                     last;
 5578:                 }
 5579:             }
 5580:         }
 5581:     }
 5582:     return @readonly_files;
 5583: }
 5584: #-----------------------------------------------------------Get Marked as Read Only Hash
 5585: 
 5586: sub get_marked_as_readonly_hash {
 5587:     my ($current_permissions,$group,$what) = @_;
 5588:     my %readonly_files;
 5589:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5590:         if (defined($group)) {
 5591:             if ($file_name !~ m-^\Q$group\E/-) {
 5592:                 next;
 5593:             }
 5594:         }
 5595:         if (ref($value) eq "ARRAY"){
 5596:             foreach my $stored_what (@{$value}) {
 5597:                 if (ref($stored_what) eq 'ARRAY') {
 5598:                     foreach my $lock_descriptor(@{$stored_what}) {
 5599:                         if ($lock_descriptor eq 'graded') {
 5600:                             $readonly_files{$file_name} = 'graded';
 5601:                         } elsif ($lock_descriptor eq 'handback') {
 5602:                             $readonly_files{$file_name} = 'handback';
 5603:                         } else {
 5604:                             if (!exists($readonly_files{$file_name})) {
 5605:                                 $readonly_files{$file_name} = 'locked';
 5606:                             }
 5607:                         }
 5608:                     }
 5609:                 } 
 5610:             }
 5611:         } 
 5612:     }
 5613:     return %readonly_files;
 5614: }
 5615: # ------------------------------------------------------------ Unmark as Read Only
 5616: 
 5617: sub unmark_as_readonly {
 5618:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5619:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5620:     my ($domain,$user,$what,$file_name,$group) = @_;
 5621:     $file_name = &declutter_portfile($file_name);
 5622:     my $symb_crs = $what;
 5623:     if (ref($what)) { $symb_crs=join('',@$what); }
 5624:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5625:     my ($tmp)=keys(%current_permissions);
 5626:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5627:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5628:     foreach my $file (@readonly_files) {
 5629: 	my $clean_file = &declutter_portfile($file);
 5630: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5631: 	my $current_locks = $current_permissions{$file};
 5632:         my @new_locks;
 5633:         my @del_keys;
 5634:         if (ref($current_locks) eq "ARRAY"){
 5635:             foreach my $locker (@{$current_locks}) {
 5636:                 my $compare=$locker;
 5637:                 if (ref($locker) eq 'ARRAY') {
 5638:                     $compare=join('',@{$locker});
 5639:                     if ($compare ne $symb_crs) {
 5640:                         push(@new_locks, $locker);
 5641:                     }
 5642:                 }
 5643:             }
 5644:             if (scalar(@new_locks) > 0) {
 5645:                 $current_permissions{$file} = \@new_locks;
 5646:             } else {
 5647:                 push(@del_keys, $file);
 5648:                 &del('file_permissions',\@del_keys, $domain, $user);
 5649:                 delete($current_permissions{$file});
 5650:             }
 5651:         }
 5652:     }
 5653:     &put('file_permissions',\%current_permissions,$domain,$user);
 5654:     return;
 5655: }
 5656: 
 5657: # ------------------------------------------------------------ Directory lister
 5658: 
 5659: sub dirlist {
 5660:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5661: 
 5662:     $uri=~s/^\///;
 5663:     $uri=~s/\/$//;
 5664:     my ($udom, $uname);
 5665:     (undef,$udom,$uname)=split(/\//,$uri);
 5666:     if(defined($userdomain)) {
 5667:         $udom = $userdomain;
 5668:     }
 5669:     if(defined($username)) {
 5670:         $uname = $username;
 5671:     }
 5672: 
 5673:     my $dirRoot = $perlvar{'lonDocRoot'};
 5674:     if(defined($alternateDirectoryRoot)) {
 5675:         $dirRoot = $alternateDirectoryRoot;
 5676:         $dirRoot =~ s/\/$//;
 5677:     }
 5678: 
 5679:     if($udom) {
 5680:         if($uname) {
 5681:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5682: 				 &homeserver($uname,$udom));
 5683:             my @listing_results;
 5684:             if ($listing eq 'unknown_cmd') {
 5685:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5686: 				  &homeserver($uname,$udom));
 5687:                 @listing_results = split(/:/,$listing);
 5688:             } else {
 5689:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5690:             }
 5691:             return @listing_results;
 5692:         } elsif(!defined($alternateDirectoryRoot)) {
 5693:             my %allusers;
 5694: 	    my %servers = &get_servers($udom,'library');
 5695: 	    foreach my $tryserver (keys(%servers)) {
 5696: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5697: 				     $udom, $tryserver);
 5698: 		my @listing_results;
 5699: 		if ($listing eq 'unknown_cmd') {
 5700: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5701: 				      $udom, $tryserver);
 5702: 		    @listing_results = split(/:/,$listing);
 5703: 		} else {
 5704: 		    @listing_results =
 5705: 			map { &unescape($_); } split(/:/,$listing);
 5706: 		}
 5707: 		if ($listing_results[0] ne 'no_such_dir' && 
 5708: 		    $listing_results[0] ne 'empty'       &&
 5709: 		    $listing_results[0] ne 'con_lost') {
 5710: 		    foreach my $line (@listing_results) {
 5711: 			my ($entry) = split(/&/,$line,2);
 5712: 			$allusers{$entry} = 1;
 5713: 		    }
 5714: 		}
 5715:             }
 5716:             my $alluserstr='';
 5717:             foreach my $user (sort(keys(%allusers))) {
 5718:                 $alluserstr.=$user.'&user:';
 5719:             }
 5720:             $alluserstr=~s/:$//;
 5721:             return split(/:/,$alluserstr);
 5722:         } else {
 5723:             return ('missing user name');
 5724:         }
 5725:     } elsif(!defined($alternateDirectoryRoot)) {
 5726:         my @all_domains = sort(&all_domains());
 5727:          foreach my $domain (@all_domains) {
 5728:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5729:          }
 5730:          return @all_domains;
 5731:      } else {
 5732:         return ('missing domain');
 5733:     }
 5734: }
 5735: 
 5736: # --------------------------------------------- GetFileTimestamp
 5737: # This function utilizes dirlist and returns the date stamp for
 5738: # when it was last modified.  It will also return an error of -1
 5739: # if an error occurs
 5740: 
 5741: ##
 5742: ## FIXME: This subroutine assumes its caller knows something about the
 5743: ## directory structure of the home server for the student ($root).
 5744: ## Not a good assumption to make.  Since this is for looking up files
 5745: ## in user directories, the full path should be constructed by lond, not
 5746: ## whatever machine we request data from.
 5747: ##
 5748: sub GetFileTimestamp {
 5749:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5750:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5751:     $studentName   = &LONCAPA::clean_username($studentName);
 5752:     my $subdir=$studentName.'__';
 5753:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5754:     my $proname="$studentDomain/$subdir/$studentName";
 5755:     $proname .= '/'.$filename;
 5756:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5757:                                               $studentName, $root);
 5758:     my @stats = split('&', $fileStat);
 5759:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5760:         # @stats contains first the filename, then the stat output
 5761:         return $stats[10]; # so this is 10 instead of 9.
 5762:     } else {
 5763:         return -1;
 5764:     }
 5765: }
 5766: 
 5767: sub stat_file {
 5768:     my ($uri) = @_;
 5769:     $uri = &clutter_with_no_wrapper($uri);
 5770: 
 5771:     my ($udom,$uname,$file,$dir);
 5772:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5773: 	($udom,$uname,$file) =
 5774: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5775: 	$file = 'userfiles/'.$file;
 5776: 	$dir = &propath($udom,$uname);
 5777:     }
 5778:     if ($uri =~ m-^/res/-) {
 5779: 	($udom,$uname) = 
 5780: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5781: 	$file = $uri;
 5782:     }
 5783: 
 5784:     if (!$udom || !$uname || !$file) {
 5785: 	# unable to handle the uri
 5786: 	return ();
 5787:     }
 5788: 
 5789:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5790:     my @stats = split('&', $result);
 5791:     
 5792:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5793: 	shift(@stats); #filename is first
 5794: 	return @stats;
 5795:     }
 5796:     return ();
 5797: }
 5798: 
 5799: # -------------------------------------------------------- Value of a Condition
 5800: 
 5801: # gets the value of a specific preevaluated condition
 5802: #    stored in the string  $env{user.state.<cid>}
 5803: # or looks up a condition reference in the bighash and if if hasn't
 5804: # already been evaluated recurses into docondval to get the value of
 5805: # the condition, then memoizing it to 
 5806: #   $env{user.state.<cid>.<condition>}
 5807: sub directcondval {
 5808:     my $number=shift;
 5809:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5810: 	&Apache::lonuserstate::evalstate();
 5811:     }
 5812:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5813: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5814:     } elsif ($number =~ /^_/) {
 5815: 	my $sub_condition;
 5816: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5817: 		&GDBM_READER(),0640)) {
 5818: 	    $sub_condition=$bighash{'conditions'.$number};
 5819: 	    untie(%bighash);
 5820: 	}
 5821: 	my $value = &docondval($sub_condition);
 5822: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5823: 	return $value;
 5824:     }
 5825:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5826:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5827:     } else {
 5828:        return 2;
 5829:     }
 5830: }
 5831: 
 5832: # get the collection of conditions for this resource
 5833: sub condval {
 5834:     my $condidx=shift;
 5835:     my $allpathcond='';
 5836:     foreach my $cond (split(/\|/,$condidx)) {
 5837: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5838: 	    $allpathcond.=
 5839: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5840: 	}
 5841:     }
 5842:     $allpathcond=~s/\|$//;
 5843:     return &docondval($allpathcond);
 5844: }
 5845: 
 5846: #evaluates an expression of conditions
 5847: sub docondval {
 5848:     my ($allpathcond) = @_;
 5849:     my $result=0;
 5850:     if ($env{'request.course.id'}
 5851: 	&& defined($allpathcond)) {
 5852: 	my $operand='|';
 5853: 	my @stack;
 5854: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5855: 	    if ($chunk eq '(') {
 5856: 		push @stack,($operand,$result);
 5857: 	    } elsif ($chunk eq ')') {
 5858: 		my $before=pop @stack;
 5859: 		if (pop @stack eq '&') {
 5860: 		    $result=$result>$before?$before:$result;
 5861: 		} else {
 5862: 		    $result=$result>$before?$result:$before;
 5863: 		}
 5864: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5865: 		$operand=$chunk;
 5866: 	    } else {
 5867: 		my $new=directcondval($chunk);
 5868: 		if ($operand eq '&') {
 5869: 		    $result=$result>$new?$new:$result;
 5870: 		} else {
 5871: 		    $result=$result>$new?$result:$new;
 5872: 		}
 5873: 	    }
 5874: 	}
 5875:     }
 5876:     return $result;
 5877: }
 5878: 
 5879: # ---------------------------------------------------- Devalidate courseresdata
 5880: 
 5881: sub devalidatecourseresdata {
 5882:     my ($coursenum,$coursedomain)=@_;
 5883:     my $hashid=$coursenum.':'.$coursedomain;
 5884:     &devalidate_cache_new('courseres',$hashid);
 5885: }
 5886: 
 5887: 
 5888: # --------------------------------------------------- Course Resourcedata Query
 5889: 
 5890: sub get_courseresdata {
 5891:     my ($coursenum,$coursedomain)=@_;
 5892:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5893:     my $hashid=$coursenum.':'.$coursedomain;
 5894:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5895:     my %dumpreply;
 5896:     unless (defined($cached)) {
 5897: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5898: 	$result=\%dumpreply;
 5899: 	my ($tmp) = keys(%dumpreply);
 5900: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5901: 	    &do_cache_new('courseres',$hashid,$result,600);
 5902: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5903: 	    return $tmp;
 5904: 	} elsif ($tmp =~ /^(error)/) {
 5905: 	    $result=undef;
 5906: 	    &do_cache_new('courseres',$hashid,$result,600);
 5907: 	}
 5908:     }
 5909:     return $result;
 5910: }
 5911: 
 5912: sub devalidateuserresdata {
 5913:     my ($uname,$udom)=@_;
 5914:     my $hashid="$udom:$uname";
 5915:     &devalidate_cache_new('userres',$hashid);
 5916: }
 5917: 
 5918: sub get_userresdata {
 5919:     my ($uname,$udom)=@_;
 5920:     #most student don\'t have any data set, check if there is some data
 5921:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5922: 
 5923:     my $hashid="$udom:$uname";
 5924:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5925:     if (!defined($cached)) {
 5926: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5927: 	$result=\%resourcedata;
 5928: 	&do_cache_new('userres',$hashid,$result,600);
 5929:     }
 5930:     my ($tmp)=keys(%$result);
 5931:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5932: 	return $result;
 5933:     }
 5934:     #error 2 occurs when the .db doesn't exist
 5935:     if ($tmp!~/error: 2 /) {
 5936: 	&logthis("<font color=\"blue\">WARNING:".
 5937: 		 " Trying to get resource data for ".
 5938: 		 $uname." at ".$udom.": ".
 5939: 		 $tmp."</font>");
 5940:     } elsif ($tmp=~/error: 2 /) {
 5941: 	#&EXT_cache_set($udom,$uname);
 5942: 	&do_cache_new('userres',$hashid,undef,600);
 5943: 	undef($tmp); # not really an error so don't send it back
 5944:     }
 5945:     return $tmp;
 5946: }
 5947: 
 5948: sub resdata {
 5949:     my ($name,$domain,$type,@which)=@_;
 5950:     my $result;
 5951:     if ($type eq 'course') {
 5952: 	$result=&get_courseresdata($name,$domain);
 5953:     } elsif ($type eq 'user') {
 5954: 	$result=&get_userresdata($name,$domain);
 5955:     }
 5956:     if (!ref($result)) { return $result; }    
 5957:     foreach my $item (@which) {
 5958: 	if (defined($result->{$item})) {
 5959: 	    return $result->{$item};
 5960: 	}
 5961:     }
 5962:     return undef;
 5963: }
 5964: 
 5965: #
 5966: # EXT resource caching routines
 5967: #
 5968: 
 5969: sub clear_EXT_cache_status {
 5970:     &delenv('cache.EXT.');
 5971: }
 5972: 
 5973: sub EXT_cache_status {
 5974:     my ($target_domain,$target_user) = @_;
 5975:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5976:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5977:         # We know already the user has no data
 5978:         return 1;
 5979:     } else {
 5980:         return 0;
 5981:     }
 5982: }
 5983: 
 5984: sub EXT_cache_set {
 5985:     my ($target_domain,$target_user) = @_;
 5986:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5987:     #&appenv($cachename => time);
 5988: }
 5989: 
 5990: # --------------------------------------------------------- Value of a Variable
 5991: sub EXT {
 5992: 
 5993:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5994:     unless ($varname) { return ''; }
 5995:     #get real user name/domain, courseid and symb
 5996:     my $courseid;
 5997:     my $publicuser;
 5998:     if ($symbparm) {
 5999: 	$symbparm=&get_symb_from_alias($symbparm);
 6000:     }
 6001:     if (!($uname && $udom)) {
 6002:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6003:       if (!$symbparm) {	$symbparm=$cursymb; }
 6004:     } else {
 6005: 	$courseid=$env{'request.course.id'};
 6006:     }
 6007:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6008:     my $rest;
 6009:     if (defined($therest[0])) {
 6010:        $rest=join('.',@therest);
 6011:     } else {
 6012:        $rest='';
 6013:     }
 6014: 
 6015:     my $qualifierrest=$qualifier;
 6016:     if ($rest) { $qualifierrest.='.'.$rest; }
 6017:     my $spacequalifierrest=$space;
 6018:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6019:     if ($realm eq 'user') {
 6020: # --------------------------------------------------------------- user.resource
 6021: 	if ($space eq 'resource') {
 6022: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6023: 		  || defined($Apache::lonhomework::parsing_a_task))
 6024: 		 &&
 6025: 		 ($symbparm eq &symbread()) ) {	
 6026: 		# if we are in the middle of processing the resource the
 6027: 		# get the value we are planning on committing
 6028:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6029:                     return $Apache::lonhomework::results{$qualifierrest};
 6030:                 } else {
 6031:                     return $Apache::lonhomework::history{$qualifierrest};
 6032:                 }
 6033: 	    } else {
 6034: 		my %restored;
 6035: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6036: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6037: 		} else {
 6038: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6039: 		}
 6040: 		return $restored{$qualifierrest};
 6041: 	    }
 6042: # ----------------------------------------------------------------- user.access
 6043:         } elsif ($space eq 'access') {
 6044: 	    # FIXME - not supporting calls for a specific user
 6045:             return &allowed($qualifier,$rest);
 6046: # ------------------------------------------ user.preferences, user.environment
 6047:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6048: 	    if (($uname eq $env{'user.name'}) &&
 6049: 		($udom eq $env{'user.domain'})) {
 6050: 		return $env{join('.',('environment',$qualifierrest))};
 6051: 	    } else {
 6052: 		my %returnhash;
 6053: 		if (!$publicuser) {
 6054: 		    %returnhash=&userenvironment($udom,$uname,
 6055: 						 $qualifierrest);
 6056: 		}
 6057: 		return $returnhash{$qualifierrest};
 6058: 	    }
 6059: # ----------------------------------------------------------------- user.course
 6060:         } elsif ($space eq 'course') {
 6061: 	    # FIXME - not supporting calls for a specific user
 6062:             return $env{join('.',('request.course',$qualifier))};
 6063: # ------------------------------------------------------------------- user.role
 6064:         } elsif ($space eq 'role') {
 6065: 	    # FIXME - not supporting calls for a specific user
 6066:             my ($role,$where)=split(/\./,$env{'request.role'});
 6067:             if ($qualifier eq 'value') {
 6068: 		return $role;
 6069:             } elsif ($qualifier eq 'extent') {
 6070:                 return $where;
 6071:             }
 6072: # ----------------------------------------------------------------- user.domain
 6073:         } elsif ($space eq 'domain') {
 6074:             return $udom;
 6075: # ------------------------------------------------------------------- user.name
 6076:         } elsif ($space eq 'name') {
 6077:             return $uname;
 6078: # ---------------------------------------------------- Any other user namespace
 6079:         } else {
 6080: 	    my %reply;
 6081: 	    if (!$publicuser) {
 6082: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6083: 	    }
 6084: 	    return $reply{$qualifierrest};
 6085:         }
 6086:     } elsif ($realm eq 'query') {
 6087: # ---------------------------------------------- pull stuff out of query string
 6088:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6089: 						[$spacequalifierrest]);
 6090: 	return $env{'form.'.$spacequalifierrest}; 
 6091:    } elsif ($realm eq 'request') {
 6092: # ------------------------------------------------------------- request.browser
 6093:         if ($space eq 'browser') {
 6094: 	    if ($qualifier eq 'textremote') {
 6095: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6096: 		    return 1;
 6097: 		} else {
 6098: 		    return 0;
 6099: 		}
 6100: 	    } else {
 6101: 		return $env{'browser.'.$qualifier};
 6102: 	    }
 6103: # ------------------------------------------------------------ request.filename
 6104:         } else {
 6105:             return $env{'request.'.$spacequalifierrest};
 6106:         }
 6107:     } elsif ($realm eq 'course') {
 6108: # ---------------------------------------------------------- course.description
 6109:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6110:     } elsif ($realm eq 'resource') {
 6111: 
 6112: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6113: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6114: 	}
 6115: 
 6116: 	if ($space eq 'title') {
 6117: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6118: 	    return &gettitle($symbparm);
 6119: 	}
 6120: 	
 6121: 	if ($space eq 'map') {
 6122: 	    my ($map) = &decode_symb($symbparm);
 6123: 	    return &symbread($map);
 6124: 	}
 6125: 
 6126: 	my ($section, $group, @groups);
 6127: 	my ($courselevelm,$courselevel);
 6128: 	if ($symbparm && defined($courseid) && 
 6129: 	    $courseid eq $env{'request.course.id'}) {
 6130: 
 6131: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6132: 
 6133: # ----------------------------------------------------- Cascading lookup scheme
 6134: 	    my $symbp=$symbparm;
 6135: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6136: 
 6137: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6138: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6139: 
 6140: 	    if (($env{'user.name'} eq $uname) &&
 6141: 		($env{'user.domain'} eq $udom)) {
 6142: 		$section=$env{'request.course.sec'};
 6143:                 @groups = split(/:/,$env{'request.course.groups'});  
 6144:                 @groups=&sort_course_groups($courseid,@groups); 
 6145: 	    } else {
 6146: 		if (! defined($usection)) {
 6147: 		    $section=&getsection($udom,$uname,$courseid);
 6148: 		} else {
 6149: 		    $section = $usection;
 6150: 		}
 6151:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6152: 	    }
 6153: 
 6154: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6155: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6156: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6157: 
 6158: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6159: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6160: 	    $courselevelm=$courseid.'.'.$mapparm;
 6161: 
 6162: # ----------------------------------------------------------- first, check user
 6163: 
 6164: 	    my $userreply=&resdata($uname,$udom,'user',
 6165: 				       ($courselevelr,$courselevelm,
 6166: 					$courselevel));
 6167: 	    if (defined($userreply)) { return $userreply; }
 6168: 
 6169: # ------------------------------------------------ second, check some of course
 6170:             my $coursereply;
 6171:             if (@groups > 0) {
 6172:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6173:                                        $mapparm,$spacequalifierrest);
 6174:                 if (defined($coursereply)) { return $coursereply; }
 6175:             }
 6176: 
 6177: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6178: 				     $env{'course.'.$courseid.'.domain'},
 6179: 				     'course',
 6180: 				     ($seclevelr,$seclevelm,$seclevel,
 6181: 				      $courselevelr));
 6182: 	    if (defined($coursereply)) { return $coursereply; }
 6183: 
 6184: # ------------------------------------------------------ third, check map parms
 6185: 	    my %parmhash=();
 6186: 	    my $thisparm='';
 6187: 	    if (tie(%parmhash,'GDBM_File',
 6188: 		    $env{'request.course.fn'}.'_parms.db',
 6189: 		    &GDBM_READER(),0640)) {
 6190: 		$thisparm=$parmhash{$symbparm};
 6191: 		untie(%parmhash);
 6192: 	    }
 6193: 	    if ($thisparm) { return $thisparm; }
 6194: 	}
 6195: # ------------------------------------------ fourth, look in resource metadata
 6196: 
 6197: 	$spacequalifierrest=~s/\./\_/;
 6198: 	my $filename;
 6199: 	if (!$symbparm) { $symbparm=&symbread(); }
 6200: 	if ($symbparm) {
 6201: 	    $filename=(&decode_symb($symbparm))[2];
 6202: 	} else {
 6203: 	    $filename=$env{'request.filename'};
 6204: 	}
 6205: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6206: 	if (defined($metadata)) { return $metadata; }
 6207: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6208: 	if (defined($metadata)) { return $metadata; }
 6209: 
 6210: # ---------------------------------------------- fourth, look in rest pf course
 6211: 	if ($symbparm && defined($courseid) && 
 6212: 	    $courseid eq $env{'request.course.id'}) {
 6213: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6214: 				     $env{'course.'.$courseid.'.domain'},
 6215: 				     'course',
 6216: 				     ($courselevelm,$courselevel));
 6217: 	    if (defined($coursereply)) { return $coursereply; }
 6218: 	}
 6219: # ------------------------------------------------------------------ Cascade up
 6220: 	unless ($space eq '0') {
 6221: 	    my @parts=split(/_/,$space);
 6222: 	    my $id=pop(@parts);
 6223: 	    my $part=join('_',@parts);
 6224: 	    if ($part eq '') { $part='0'; }
 6225: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6226: 				 $symbparm,$udom,$uname,$section,1);
 6227: 	    if (defined($partgeneral)) { return $partgeneral; }
 6228: 	}
 6229: 	if ($recurse) { return undef; }
 6230: 	my $pack_def=&packages_tab_default($filename,$varname);
 6231: 	if (defined($pack_def)) { return $pack_def; }
 6232: 
 6233: # ---------------------------------------------------- Any other user namespace
 6234:     } elsif ($realm eq 'environment') {
 6235: # ----------------------------------------------------------------- environment
 6236: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6237: 	    return $env{'environment.'.$spacequalifierrest};
 6238: 	} else {
 6239: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6240: 		return '';
 6241: 	    }
 6242: 	    my %returnhash=&userenvironment($udom,$uname,
 6243: 					    $spacequalifierrest);
 6244: 	    return $returnhash{$spacequalifierrest};
 6245: 	}
 6246:     } elsif ($realm eq 'system') {
 6247: # ----------------------------------------------------------------- system.time
 6248: 	if ($space eq 'time') {
 6249: 	    return time;
 6250:         }
 6251:     } elsif ($realm eq 'server') {
 6252: # ----------------------------------------------------------------- system.time
 6253: 	if ($space eq 'name') {
 6254: 	    return $ENV{'SERVER_NAME'};
 6255:         }
 6256:     }
 6257:     return '';
 6258: }
 6259: 
 6260: sub check_group_parms {
 6261:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6262:     my @groupitems = ();
 6263:     my $resultitem;
 6264:     my @levels = ($symbparm,$mapparm,$what);
 6265:     foreach my $group (@{$groups}) {
 6266:         foreach my $level (@levels) {
 6267:              my $item = $courseid.'.['.$group.'].'.$level;
 6268:              push(@groupitems,$item);
 6269:         }
 6270:     }
 6271:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6272:                             $env{'course.'.$courseid.'.domain'},
 6273:                                      'course',@groupitems);
 6274:     return $coursereply;
 6275: }
 6276: 
 6277: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6278:     my ($courseid,@groups) = @_;
 6279:     @groups = sort(@groups);
 6280:     return @groups;
 6281: }
 6282: 
 6283: sub packages_tab_default {
 6284:     my ($uri,$varname)=@_;
 6285:     my (undef,$part,$name)=split(/\./,$varname);
 6286: 
 6287:     my (@extension,@specifics,$do_default);
 6288:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6289: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6290: 	if ($pack_type eq 'default') {
 6291: 	    $do_default=1;
 6292: 	} elsif ($pack_type eq 'extension') {
 6293: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6294: 	} elsif ($pack_part eq $part) {
 6295: 	    # only look at packages defaults for packages that this id is
 6296: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6297: 	}
 6298:     }
 6299:     # first look for a package that matches the requested part id
 6300:     foreach my $package (@specifics) {
 6301: 	my (undef,$pack_type,$pack_part)=@{$package};
 6302: 	next if ($pack_part ne $part);
 6303: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6304: 	    return $packagetab{"$pack_type&$name&default"};
 6305: 	}
 6306:     }
 6307:     # look for any possible matching non extension_ package
 6308:     foreach my $package (@specifics) {
 6309: 	my (undef,$pack_type,$pack_part)=@{$package};
 6310: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6311: 	    return $packagetab{"$pack_type&$name&default"};
 6312: 	}
 6313: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6314: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6315: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6316: 	}
 6317:     }
 6318:     # look for any posible extension_ match
 6319:     foreach my $package (@extension) {
 6320: 	my ($package,$pack_type)=@{$package};
 6321: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6322: 	    return $packagetab{"$pack_type&$name&default"};
 6323: 	}
 6324: 	if (defined($packagetab{$package."&$name&default"})) {
 6325: 	    return $packagetab{$package."&$name&default"};
 6326: 	}
 6327:     }
 6328:     # look for a global default setting
 6329:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6330: 	return $packagetab{"default&$name&default"};
 6331:     }
 6332:     return undef;
 6333: }
 6334: 
 6335: sub add_prefix_and_part {
 6336:     my ($prefix,$part)=@_;
 6337:     my $keyroot;
 6338:     if (defined($prefix) && $prefix !~ /^__/) {
 6339: 	# prefix that has a part already
 6340: 	$keyroot=$prefix;
 6341:     } elsif (defined($prefix)) {
 6342: 	# prefix that is missing a part
 6343: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6344:     } else {
 6345: 	# no prefix at all
 6346: 	if (defined($part)) { $keyroot='_'.$part; }
 6347:     }
 6348:     return $keyroot;
 6349: }
 6350: 
 6351: # ---------------------------------------------------------------- Get metadata
 6352: 
 6353: my %metaentry;
 6354: sub metadata {
 6355:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6356:     $uri=&declutter($uri);
 6357:     # if it is a non metadata possible uri return quickly
 6358:     if (($uri eq '') || 
 6359: 	(($uri =~ m|^/*adm/|) && 
 6360: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6361:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6362: 	($uri =~ m|home/$match_username/public_html/|)) {
 6363: 	return undef;
 6364:     }
 6365:     my $filename=$uri;
 6366:     $uri=~s/\.meta$//;
 6367: #
 6368: # Is the metadata already cached?
 6369: # Look at timestamp of caching
 6370: # Everything is cached by the main uri, libraries are never directly cached
 6371: #
 6372:     if (!defined($liburi)) {
 6373: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6374: 	if (defined($cached)) { return $result->{':'.$what}; }
 6375:     }
 6376:     {
 6377: #
 6378: # Is this a recursive call for a library?
 6379: #
 6380: #	if (! exists($metacache{$uri})) {
 6381: #	    $metacache{$uri}={};
 6382: #	}
 6383:         if ($liburi) {
 6384: 	    $liburi=&declutter($liburi);
 6385:             $filename=$liburi;
 6386:         } else {
 6387: 	    &devalidate_cache_new('meta',$uri);
 6388: 	    undef(%metaentry);
 6389: 	}
 6390:         my %metathesekeys=();
 6391:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6392: 	my $metastring;
 6393: 	if ($uri !~ m -^(editupload)/-) {
 6394: 	    my $file=&filelocation('',&clutter($filename));
 6395: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6396: 	    $metastring=&getfile($file);
 6397: 	}
 6398:         my $parser=HTML::LCParser->new(\$metastring);
 6399:         my $token;
 6400:         undef %metathesekeys;
 6401:         while ($token=$parser->get_token) {
 6402: 	    if ($token->[0] eq 'S') {
 6403: 		if (defined($token->[2]->{'package'})) {
 6404: #
 6405: # This is a package - get package info
 6406: #
 6407: 		    my $package=$token->[2]->{'package'};
 6408: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6409: 		    if (defined($token->[2]->{'id'})) { 
 6410: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6411: 		    }
 6412: 		    if ($metaentry{':packages'}) {
 6413: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6414: 		    } else {
 6415: 			$metaentry{':packages'}=$package.$keyroot;
 6416: 		    }
 6417: 		    foreach my $pack_entry (keys(%packagetab)) {
 6418: 			my $part=$keyroot;
 6419: 			$part=~s/^\_//;
 6420: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6421: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6422: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6423: 			    # ignore package.tab specified default values
 6424:                             # here &package_tab_default() will fetch those
 6425: 			    if ($subp eq 'default') { next; }
 6426: 			    my $value=$packagetab{$pack_entry};
 6427: 			    my $unikey;
 6428: 			    if ($pack =~ /_0$/) {
 6429: 				$unikey='parameter_0_'.$name;
 6430: 				$part=0;
 6431: 			    } else {
 6432: 				$unikey='parameter'.$keyroot.'_'.$name;
 6433: 			    }
 6434: 			    if ($subp eq 'display') {
 6435: 				$value.=' [Part: '.$part.']';
 6436: 			    }
 6437: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6438: 			    $metathesekeys{$unikey}=1;
 6439: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6440: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6441: 			    }
 6442: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6443: 				$metaentry{':'.$unikey}=
 6444: 				    $metaentry{':'.$unikey.'.default'};
 6445: 			    }
 6446: 			}
 6447: 		    }
 6448: 		} else {
 6449: #
 6450: # This is not a package - some other kind of start tag
 6451: #
 6452: 		    my $entry=$token->[1];
 6453: 		    my $unikey;
 6454: 		    if ($entry eq 'import') {
 6455: 			$unikey='';
 6456: 		    } else {
 6457: 			$unikey=$entry;
 6458: 		    }
 6459: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6460: 
 6461: 		    if (defined($token->[2]->{'id'})) { 
 6462: 			$unikey.='_'.$token->[2]->{'id'}; 
 6463: 		    }
 6464: 
 6465: 		    if ($entry eq 'import') {
 6466: #
 6467: # Importing a library here
 6468: #
 6469: 			if ($depthcount<20) {
 6470: 			    my $location=$parser->get_text('/import');
 6471: 			    my $dir=$filename;
 6472: 			    $dir=~s|[^/]*$||;
 6473: 			    $location=&filelocation($dir,$location);
 6474: 			    my $metadata = 
 6475: 				&metadata($uri,'keys', $location,$unikey,
 6476: 					  $depthcount+1);
 6477: 			    foreach my $meta (split(',',$metadata)) {
 6478: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6479: 				$metathesekeys{$meta}=1;
 6480: 			    }
 6481: 			}
 6482: 		    } else { 
 6483: 			
 6484: 			if (defined($token->[2]->{'name'})) { 
 6485: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6486: 			}
 6487: 			$metathesekeys{$unikey}=1;
 6488: 			foreach my $param (@{$token->[3]}) {
 6489: 			    $metaentry{':'.$unikey.'.'.$param} =
 6490: 				$token->[2]->{$param};
 6491: 			}
 6492: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6493: 			my $default=$metaentry{':'.$unikey.'.default'};
 6494: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6495: 		 # only ws inside the tag, and not in default, so use default
 6496: 		 # as value
 6497: 			    $metaentry{':'.$unikey}=$default;
 6498: 			} else {
 6499: 		  # either something interesting inside the tag or default
 6500:                   # uninteresting
 6501: 			    $metaentry{':'.$unikey}=$internaltext;
 6502: 			}
 6503: # end of not-a-package not-a-library import
 6504: 		    }
 6505: # end of not-a-package start tag
 6506: 		}
 6507: # the next is the end of "start tag"
 6508: 	    }
 6509: 	}
 6510: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6511: 	foreach my $key (keys(%packagetab)) {
 6512: 	    #no specific packages #how's our extension
 6513: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6514: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6515: 					 \%metathesekeys);
 6516: 	}
 6517: 	if (!exists($metaentry{':packages'})) {
 6518: 	    foreach my $key (keys(%packagetab)) {
 6519: 		#no specific packages well let's get default then
 6520: 		if ($key!~/^default&/) { next; }
 6521: 		&metadata_create_package_def($uri,$key,'default',
 6522: 					     \%metathesekeys);
 6523: 	    }
 6524: 	}
 6525: # are there custom rights to evaluate
 6526: 	if ($metaentry{':copyright'} eq 'custom') {
 6527: 
 6528:     #
 6529:     # Importing a rights file here
 6530:     #
 6531: 	    unless ($depthcount) {
 6532: 		my $location=$metaentry{':customdistributionfile'};
 6533: 		my $dir=$filename;
 6534: 		$dir=~s|[^/]*$||;
 6535: 		$location=&filelocation($dir,$location);
 6536: 		my $rights_metadata =
 6537: 		    &metadata($uri,'keys',$location,'_rights',
 6538: 			      $depthcount+1);
 6539: 		foreach my $rights (split(',',$rights_metadata)) {
 6540: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6541: 		    $metathesekeys{$rights}=1;
 6542: 		}
 6543: 	    }
 6544: 	}
 6545: 	# uniqifiy package listing
 6546: 	my %seen;
 6547: 	my @uniq_packages =
 6548: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6549: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6550: 
 6551: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6552: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6553: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6554: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6555: # this is the end of "was not already recently cached
 6556:     }
 6557:     return $metaentry{':'.$what};
 6558: }
 6559: 
 6560: sub metadata_create_package_def {
 6561:     my ($uri,$key,$package,$metathesekeys)=@_;
 6562:     my ($pack,$name,$subp)=split(/\&/,$key);
 6563:     if ($subp eq 'default') { next; }
 6564:     
 6565:     if (defined($metaentry{':packages'})) {
 6566: 	$metaentry{':packages'}.=','.$package;
 6567:     } else {
 6568: 	$metaentry{':packages'}=$package;
 6569:     }
 6570:     my $value=$packagetab{$key};
 6571:     my $unikey;
 6572:     $unikey='parameter_0_'.$name;
 6573:     $metaentry{':'.$unikey.'.part'}=0;
 6574:     $$metathesekeys{$unikey}=1;
 6575:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6576: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6577:     }
 6578:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6579: 	$metaentry{':'.$unikey}=
 6580: 	    $metaentry{':'.$unikey.'.default'};
 6581:     }
 6582: }
 6583: 
 6584: sub metadata_generate_part0 {
 6585:     my ($metadata,$metacache,$uri) = @_;
 6586:     my %allnames;
 6587:     foreach my $metakey (keys(%$metadata)) {
 6588: 	if ($metakey=~/^parameter\_(.*)/) {
 6589: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6590: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6591: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6592: 	    $allnames{$name}=$part;
 6593: 	  }
 6594: 	}
 6595:     }
 6596:     foreach my $name (keys(%allnames)) {
 6597:       $$metadata{"parameter_0_$name"}=1;
 6598:       my $key=":parameter_0_$name";
 6599:       $$metacache{"$key.part"}='0';
 6600:       $$metacache{"$key.name"}=$name;
 6601:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6602: 					   $allnames{$name}.'_'.$name.
 6603: 					   '.type'};
 6604:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6605: 			     '.display'};
 6606:       my $expr='[Part: '.$allnames{$name}.']';
 6607:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6608:       $$metacache{"$key.display"}=$olddis;
 6609:     }
 6610: }
 6611: 
 6612: # ------------------------------------------------------ Devalidate title cache
 6613: 
 6614: sub devalidate_title_cache {
 6615:     my ($url)=@_;
 6616:     if (!$env{'request.course.id'}) { return; }
 6617:     my $symb=&symbread($url);
 6618:     if (!$symb) { return; }
 6619:     my $key=$env{'request.course.id'}."\0".$symb;
 6620:     &devalidate_cache_new('title',$key);
 6621: }
 6622: 
 6623: # ------------------------------------------------- Get the title of a resource
 6624: 
 6625: sub gettitle {
 6626:     my $urlsymb=shift;
 6627:     my $symb=&symbread($urlsymb);
 6628:     if ($symb) {
 6629: 	my $key=$env{'request.course.id'}."\0".$symb;
 6630: 	my ($result,$cached)=&is_cached_new('title',$key);
 6631: 	if (defined($cached)) { 
 6632: 	    return $result;
 6633: 	}
 6634: 	my ($map,$resid,$url)=&decode_symb($symb);
 6635: 	my $title='';
 6636: 	my %bighash;
 6637: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6638: 		&GDBM_READER(),0640)) {
 6639: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6640: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6641: 	    untie %bighash;
 6642: 	}
 6643: 	$title=~s/\&colon\;/\:/gs;
 6644: 	if ($title) {
 6645: 	    return &do_cache_new('title',$key,$title,600);
 6646: 	}
 6647: 	$urlsymb=$url;
 6648:     }
 6649:     my $title=&metadata($urlsymb,'title');
 6650:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6651:     return $title;
 6652: }
 6653: 
 6654: sub get_slot {
 6655:     my ($which,$cnum,$cdom)=@_;
 6656:     if (!$cnum || !$cdom) {
 6657: 	(undef,my $courseid)=&whichuser();
 6658: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6659: 	$cnum=$env{'course.'.$courseid.'.num'};
 6660:     }
 6661:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6662:     my %slotinfo;
 6663:     if (exists($remembered{$key})) {
 6664: 	$slotinfo{$which} = $remembered{$key};
 6665:     } else {
 6666: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6667: 	&Apache::lonhomework::showhash(%slotinfo);
 6668: 	my ($tmp)=keys(%slotinfo);
 6669: 	if ($tmp=~/^error:/) { return (); }
 6670: 	$remembered{$key} = $slotinfo{$which};
 6671:     }
 6672:     if (ref($slotinfo{$which}) eq 'HASH') {
 6673: 	return %{$slotinfo{$which}};
 6674:     }
 6675:     return $slotinfo{$which};
 6676: }
 6677: # ------------------------------------------------- Update symbolic store links
 6678: 
 6679: sub symblist {
 6680:     my ($mapname,%newhash)=@_;
 6681:     $mapname=&deversion(&declutter($mapname));
 6682:     my %hash;
 6683:     if (($env{'request.course.fn'}) && (%newhash)) {
 6684:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6685:                       &GDBM_WRCREAT(),0640)) {
 6686: 	    foreach my $url (keys %newhash) {
 6687: 		next if ($url eq 'last_known'
 6688: 			 && $env{'form.no_update_last_known'});
 6689: 		$hash{declutter($url)}=&encode_symb($mapname,
 6690: 						    $newhash{$url}->[1],
 6691: 						    $newhash{$url}->[0]);
 6692:             }
 6693:             if (untie(%hash)) {
 6694: 		return 'ok';
 6695:             }
 6696:         }
 6697:     }
 6698:     return 'error';
 6699: }
 6700: 
 6701: # --------------------------------------------------------------- Verify a symb
 6702: 
 6703: sub symbverify {
 6704:     my ($symb,$thisurl)=@_;
 6705:     my $thisfn=$thisurl;
 6706:     $thisfn=&declutter($thisfn);
 6707: # direct jump to resource in page or to a sequence - will construct own symbs
 6708:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6709: # check URL part
 6710:     my ($map,$resid,$url)=&decode_symb($symb);
 6711: 
 6712:     unless ($url eq $thisfn) { return 0; }
 6713: 
 6714:     $symb=&symbclean($symb);
 6715:     $thisurl=&deversion($thisurl);
 6716:     $thisfn=&deversion($thisfn);
 6717: 
 6718:     my %bighash;
 6719:     my $okay=0;
 6720: 
 6721:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6722:                             &GDBM_READER(),0640)) {
 6723:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6724:         unless ($ids) { 
 6725:            $ids=$bighash{'ids_/'.$thisurl};
 6726:         }
 6727:         if ($ids) {
 6728: # ------------------------------------------------------------------- Has ID(s)
 6729: 	    foreach my $id (split(/\,/,$ids)) {
 6730: 	       my ($mapid,$resid)=split(/\./,$id);
 6731:                if (
 6732:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6733:    eq $symb) { 
 6734: 		   if (($env{'request.role.adv'}) ||
 6735: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6736: 		       $okay=1; 
 6737: 		   }
 6738: 	       }
 6739: 	   }
 6740:         }
 6741: 	untie(%bighash);
 6742:     }
 6743:     return $okay;
 6744: }
 6745: 
 6746: # --------------------------------------------------------------- Clean-up symb
 6747: 
 6748: sub symbclean {
 6749:     my $symb=shift;
 6750:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6751: # remove version from map
 6752:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6753: 
 6754: # remove version from URL
 6755:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6756: 
 6757: # remove wrapper
 6758: 
 6759:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6760:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6761:     return $symb;
 6762: }
 6763: 
 6764: # ---------------------------------------------- Split symb to find map and url
 6765: 
 6766: sub encode_symb {
 6767:     my ($map,$resid,$url)=@_;
 6768:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6769: }
 6770: 
 6771: sub decode_symb {
 6772:     my $symb=shift;
 6773:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6774:     my ($map,$resid,$url)=split(/___/,$symb);
 6775:     return (&fixversion($map),$resid,&fixversion($url));
 6776: }
 6777: 
 6778: sub fixversion {
 6779:     my $fn=shift;
 6780:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6781:     my %bighash;
 6782:     my $uri=&clutter($fn);
 6783:     my $key=$env{'request.course.id'}.'_'.$uri;
 6784: # is this cached?
 6785:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6786:     if (defined($cached)) { return $result; }
 6787: # unfortunately not cached, or expired
 6788:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6789: 	    &GDBM_READER(),0640)) {
 6790:  	if ($bighash{'version_'.$uri}) {
 6791:  	    my $version=$bighash{'version_'.$uri};
 6792:  	    unless (($version eq 'mostrecent') || 
 6793: 		    ($version==&getversion($uri))) {
 6794:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6795:  	    }
 6796:  	}
 6797:  	untie %bighash;
 6798:     }
 6799:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6800: }
 6801: 
 6802: sub deversion {
 6803:     my $url=shift;
 6804:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6805:     return $url;
 6806: }
 6807: 
 6808: # ------------------------------------------------------ Return symb list entry
 6809: 
 6810: sub symbread {
 6811:     my ($thisfn,$donotrecurse)=@_;
 6812:     my $cache_str='request.symbread.cached.'.$thisfn;
 6813:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6814: # no filename provided? try from environment
 6815:     unless ($thisfn) {
 6816:         if ($env{'request.symb'}) {
 6817: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6818: 	}
 6819: 	$thisfn=$env{'request.filename'};
 6820:     }
 6821:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6822: # is that filename actually a symb? Verify, clean, and return
 6823:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6824: 	if (&symbverify($thisfn,$1)) {
 6825: 	    return $env{$cache_str}=&symbclean($thisfn);
 6826: 	}
 6827:     }
 6828:     $thisfn=declutter($thisfn);
 6829:     my %hash;
 6830:     my %bighash;
 6831:     my $syval='';
 6832:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6833:         my $targetfn = $thisfn;
 6834:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6835:             $targetfn = 'adm/wrapper/'.$thisfn;
 6836:         }
 6837: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6838: 	    $targetfn=$1;
 6839: 	}
 6840:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6841:                       &GDBM_READER(),0640)) {
 6842: 	    $syval=$hash{$targetfn};
 6843:             untie(%hash);
 6844:         }
 6845: # ---------------------------------------------------------- There was an entry
 6846:         if ($syval) {
 6847: 	    #unless ($syval=~/\_\d+$/) {
 6848: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6849: 		    #&appenv('request.ambiguous' => $thisfn);
 6850: 		    #return $env{$cache_str}='';
 6851: 		#}    
 6852: 		#$syval.=$1;
 6853: 	    #}
 6854:         } else {
 6855: # ------------------------------------------------------- Was not in symb table
 6856:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6857:                             &GDBM_READER(),0640)) {
 6858: # ---------------------------------------------- Get ID(s) for current resource
 6859:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6860:               unless ($ids) { 
 6861:                  $ids=$bighash{'ids_/'.$thisfn};
 6862:               }
 6863:               unless ($ids) {
 6864: # alias?
 6865: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6866:               }
 6867:               if ($ids) {
 6868: # ------------------------------------------------------------------- Has ID(s)
 6869:                  my @possibilities=split(/\,/,$ids);
 6870:                  if ($#possibilities==0) {
 6871: # ----------------------------------------------- There is only one possibility
 6872: 		     my ($mapid,$resid)=split(/\./,$ids);
 6873: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6874: 						    $resid,$thisfn);
 6875:                  } elsif (!$donotrecurse) {
 6876: # ------------------------------------------ There is more than one possibility
 6877:                      my $realpossible=0;
 6878:                      foreach my $id (@possibilities) {
 6879: 			 my $file=$bighash{'src_'.$id};
 6880:                          if (&allowed('bre',$file)) {
 6881:          		    my ($mapid,$resid)=split(/\./,$id);
 6882:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6883: 				$realpossible++;
 6884:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6885: 						    $resid,$thisfn);
 6886:                             }
 6887: 			 }
 6888:                      }
 6889: 		     if ($realpossible!=1) { $syval=''; }
 6890:                  } else {
 6891:                      $syval='';
 6892:                  }
 6893: 	      }
 6894:               untie(%bighash)
 6895:            }
 6896:         }
 6897:         if ($syval) {
 6898: 	    return $env{$cache_str}=$syval;
 6899:         }
 6900:     }
 6901:     &appenv('request.ambiguous' => $thisfn);
 6902:     return $env{$cache_str}='';
 6903: }
 6904: 
 6905: # ---------------------------------------------------------- Return random seed
 6906: 
 6907: sub numval {
 6908:     my $txt=shift;
 6909:     $txt=~tr/A-J/0-9/;
 6910:     $txt=~tr/a-j/0-9/;
 6911:     $txt=~tr/K-T/0-9/;
 6912:     $txt=~tr/k-t/0-9/;
 6913:     $txt=~tr/U-Z/0-5/;
 6914:     $txt=~tr/u-z/0-5/;
 6915:     $txt=~s/\D//g;
 6916:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6917:     return int($txt);
 6918: }
 6919: 
 6920: sub numval2 {
 6921:     my $txt=shift;
 6922:     $txt=~tr/A-J/0-9/;
 6923:     $txt=~tr/a-j/0-9/;
 6924:     $txt=~tr/K-T/0-9/;
 6925:     $txt=~tr/k-t/0-9/;
 6926:     $txt=~tr/U-Z/0-5/;
 6927:     $txt=~tr/u-z/0-5/;
 6928:     $txt=~s/\D//g;
 6929:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6930:     my $total;
 6931:     foreach my $val (@txts) { $total+=$val; }
 6932:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6933:     return int($total);
 6934: }
 6935: 
 6936: sub numval3 {
 6937:     use integer;
 6938:     my $txt=shift;
 6939:     $txt=~tr/A-J/0-9/;
 6940:     $txt=~tr/a-j/0-9/;
 6941:     $txt=~tr/K-T/0-9/;
 6942:     $txt=~tr/k-t/0-9/;
 6943:     $txt=~tr/U-Z/0-5/;
 6944:     $txt=~tr/u-z/0-5/;
 6945:     $txt=~s/\D//g;
 6946:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6947:     my $total;
 6948:     foreach my $val (@txts) { $total+=$val; }
 6949:     if ($_64bit) { $total=(($total<<32)>>32); }
 6950:     return $total;
 6951: }
 6952: 
 6953: sub digest {
 6954:     my ($data)=@_;
 6955:     my $digest=&Digest::MD5::md5($data);
 6956:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6957:     my ($e,$f);
 6958:     {
 6959:         use integer;
 6960:         $e=($a+$b);
 6961:         $f=($c+$d);
 6962:         if ($_64bit) {
 6963:             $e=(($e<<32)>>32);
 6964:             $f=(($f<<32)>>32);
 6965:         }
 6966:     }
 6967:     if (wantarray) {
 6968: 	return ($e,$f);
 6969:     } else {
 6970: 	my $g;
 6971: 	{
 6972: 	    use integer;
 6973: 	    $g=($e+$f);
 6974: 	    if ($_64bit) {
 6975: 		$g=(($g<<32)>>32);
 6976: 	    }
 6977: 	}
 6978: 	return $g;
 6979:     }
 6980: }
 6981: 
 6982: sub latest_rnd_algorithm_id {
 6983:     return '64bit5';
 6984: }
 6985: 
 6986: sub get_rand_alg {
 6987:     my ($courseid)=@_;
 6988:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6989:     if ($courseid) {
 6990: 	return $env{"course.$courseid.rndseed"};
 6991:     }
 6992:     return &latest_rnd_algorithm_id();
 6993: }
 6994: 
 6995: sub validCODE {
 6996:     my ($CODE)=@_;
 6997:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6998:     return 0;
 6999: }
 7000: 
 7001: sub getCODE {
 7002:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7003:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7004: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7005: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7006: 	return $Apache::lonhomework::history{'resource.CODE'};
 7007:     }
 7008:     return undef;
 7009: }
 7010: 
 7011: sub rndseed {
 7012:     my ($symb,$courseid,$domain,$username)=@_;
 7013:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7014:     if (!$symb) {
 7015: 	unless ($symb=$wsymb) { return time; }
 7016:     }
 7017:     if (!$courseid) { $courseid=$wcourseid; }
 7018:     if (!$domain) { $domain=$wdomain; }
 7019:     if (!$username) { $username=$wusername }
 7020:     my $which=&get_rand_alg();
 7021: 
 7022:     if (defined(&getCODE())) {
 7023: 	if ($which eq '64bit5') {
 7024: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7025: 	} elsif ($which eq '64bit4') {
 7026: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7027: 	} else {
 7028: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7029: 	}
 7030:     } elsif ($which eq '64bit5') {
 7031: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7032:     } elsif ($which eq '64bit4') {
 7033: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7034:     } elsif ($which eq '64bit3') {
 7035: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7036:     } elsif ($which eq '64bit2') {
 7037: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7038:     } elsif ($which eq '64bit') {
 7039: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7040:     }
 7041:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7042: }
 7043: 
 7044: sub rndseed_32bit {
 7045:     my ($symb,$courseid,$domain,$username)=@_;
 7046:     {
 7047: 	use integer;
 7048: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7049: 	my $symbseed=numval($symb) << 22;
 7050: 	my $namechck=unpack("%32C*",$username) << 17;
 7051: 	my $nameseed=numval($username) << 12;
 7052: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7053: 	my $courseseed=unpack("%32C*",$courseid);
 7054: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7055: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7056: 	#&logthis("rndseed :$num:$symb");
 7057: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7058: 	return $num;
 7059:     }
 7060: }
 7061: 
 7062: sub rndseed_64bit {
 7063:     my ($symb,$courseid,$domain,$username)=@_;
 7064:     {
 7065: 	use integer;
 7066: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7067: 	my $symbseed=numval($symb) << 10;
 7068: 	my $namechck=unpack("%32S*",$username);
 7069: 	
 7070: 	my $nameseed=numval($username) << 21;
 7071: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7072: 	my $courseseed=unpack("%32S*",$courseid);
 7073: 	
 7074: 	my $num1=$symbchck+$symbseed+$namechck;
 7075: 	my $num2=$nameseed+$domainseed+$courseseed;
 7076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7077: 	#&logthis("rndseed :$num:$symb");
 7078: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7079: 	return "$num1,$num2";
 7080:     }
 7081: }
 7082: 
 7083: sub rndseed_64bit2 {
 7084:     my ($symb,$courseid,$domain,$username)=@_;
 7085:     {
 7086: 	use integer;
 7087: 	# strings need to be an even # of cahracters long, it it is odd the
 7088:         # last characters gets thrown away
 7089: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7090: 	my $symbseed=numval($symb) << 10;
 7091: 	my $namechck=unpack("%32S*",$username.' ');
 7092: 	
 7093: 	my $nameseed=numval($username) << 21;
 7094: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7095: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7096: 	
 7097: 	my $num1=$symbchck+$symbseed+$namechck;
 7098: 	my $num2=$nameseed+$domainseed+$courseseed;
 7099: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7100: 	#&logthis("rndseed :$num:$symb");
 7101: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7102: 	return "$num1,$num2";
 7103:     }
 7104: }
 7105: 
 7106: sub rndseed_64bit3 {
 7107:     my ($symb,$courseid,$domain,$username)=@_;
 7108:     {
 7109: 	use integer;
 7110: 	# strings need to be an even # of cahracters long, it it is odd the
 7111:         # last characters gets thrown away
 7112: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7113: 	my $symbseed=numval2($symb) << 10;
 7114: 	my $namechck=unpack("%32S*",$username.' ');
 7115: 	
 7116: 	my $nameseed=numval2($username) << 21;
 7117: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7118: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7119: 	
 7120: 	my $num1=$symbchck+$symbseed+$namechck;
 7121: 	my $num2=$nameseed+$domainseed+$courseseed;
 7122: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7123: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7124: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7125: 	
 7126: 	return "$num1:$num2";
 7127:     }
 7128: }
 7129: 
 7130: sub rndseed_64bit4 {
 7131:     my ($symb,$courseid,$domain,$username)=@_;
 7132:     {
 7133: 	use integer;
 7134: 	# strings need to be an even # of cahracters long, it it is odd the
 7135:         # last characters gets thrown away
 7136: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7137: 	my $symbseed=numval3($symb) << 10;
 7138: 	my $namechck=unpack("%32S*",$username.' ');
 7139: 	
 7140: 	my $nameseed=numval3($username) << 21;
 7141: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7142: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7143: 	
 7144: 	my $num1=$symbchck+$symbseed+$namechck;
 7145: 	my $num2=$nameseed+$domainseed+$courseseed;
 7146: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7147: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7148: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7149: 	
 7150: 	return "$num1:$num2";
 7151:     }
 7152: }
 7153: 
 7154: sub rndseed_64bit5 {
 7155:     my ($symb,$courseid,$domain,$username)=@_;
 7156:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7157:     return "$num1:$num2";
 7158: }
 7159: 
 7160: sub rndseed_CODE_64bit {
 7161:     my ($symb,$courseid,$domain,$username)=@_;
 7162:     {
 7163: 	use integer;
 7164: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7165: 	my $symbseed=numval2($symb);
 7166: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7167: 	my $CODEseed=numval(&getCODE());
 7168: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7169: 	my $num1=$symbseed+$CODEchck;
 7170: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7171: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7172: 	#&logthis("rndseed :$num1:$num2:$symb");
 7173: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7174: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7175: 	return "$num1:$num2";
 7176:     }
 7177: }
 7178: 
 7179: sub rndseed_CODE_64bit4 {
 7180:     my ($symb,$courseid,$domain,$username)=@_;
 7181:     {
 7182: 	use integer;
 7183: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7184: 	my $symbseed=numval3($symb);
 7185: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7186: 	my $CODEseed=numval3(&getCODE());
 7187: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7188: 	my $num1=$symbseed+$CODEchck;
 7189: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7190: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7191: 	#&logthis("rndseed :$num1:$num2:$symb");
 7192: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7193: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7194: 	return "$num1:$num2";
 7195:     }
 7196: }
 7197: 
 7198: sub rndseed_CODE_64bit5 {
 7199:     my ($symb,$courseid,$domain,$username)=@_;
 7200:     my $code = &getCODE();
 7201:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7202:     return "$num1:$num2";
 7203: }
 7204: 
 7205: sub setup_random_from_rndseed {
 7206:     my ($rndseed)=@_;
 7207:     if ($rndseed =~/([,:])/) {
 7208: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7209: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7210:     } else {
 7211: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7212:     }
 7213: }
 7214: 
 7215: sub latest_receipt_algorithm_id {
 7216:     return 'receipt3';
 7217: }
 7218: 
 7219: sub recunique {
 7220:     my $fucourseid=shift;
 7221:     my $unique;
 7222:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7223: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7224: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7225:     } else {
 7226: 	$unique=$perlvar{'lonReceipt'};
 7227:     }
 7228:     return unpack("%32C*",$unique);
 7229: }
 7230: 
 7231: sub recprefix {
 7232:     my $fucourseid=shift;
 7233:     my $prefix;
 7234:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7235: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7236: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7237:     } else {
 7238: 	$prefix=$perlvar{'lonHostID'};
 7239:     }
 7240:     return unpack("%32C*",$prefix);
 7241: }
 7242: 
 7243: sub ireceipt {
 7244:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7245: 
 7246:     my $return =&recprefix($fucourseid).'-';
 7247: 
 7248:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7249: 	$env{'request.state'} eq 'construct') {
 7250: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7251: 	return $return;
 7252:     }
 7253: 
 7254:     my $cuname=unpack("%32C*",$funame);
 7255:     my $cudom=unpack("%32C*",$fudom);
 7256:     my $cucourseid=unpack("%32C*",$fucourseid);
 7257:     my $cusymb=unpack("%32C*",$fusymb);
 7258:     my $cunique=&recunique($fucourseid);
 7259:     my $cpart=unpack("%32S*",$part);
 7260:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7261: 
 7262: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7263: 			       
 7264: 	$return.= ($cunique%$cuname+
 7265: 		   $cunique%$cudom+
 7266: 		   $cusymb%$cuname+
 7267: 		   $cusymb%$cudom+
 7268: 		   $cucourseid%$cuname+
 7269: 		   $cucourseid%$cudom+
 7270: 		   $cpart%$cuname+
 7271: 		   $cpart%$cudom);
 7272:     } else {
 7273: 	$return.= ($cunique%$cuname+
 7274: 		   $cunique%$cudom+
 7275: 		   $cusymb%$cuname+
 7276: 		   $cusymb%$cudom+
 7277: 		   $cucourseid%$cuname+
 7278: 		   $cucourseid%$cudom);
 7279:     }
 7280:     return $return;
 7281: }
 7282: 
 7283: sub receipt {
 7284:     my ($part)=@_;
 7285:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7286:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7287: }
 7288: 
 7289: sub whichuser {
 7290:     my ($passedsymb)=@_;
 7291:     my ($symb,$courseid,$domain,$name,$publicuser);
 7292:     if (defined($env{'form.grade_symb'})) {
 7293: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7294: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7295: 	if (!$allowed &&
 7296: 	    exists($env{'request.course.sec'}) &&
 7297: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7298: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7299: 			      '/'.$env{'request.course.sec'});
 7300: 	}
 7301: 	if ($allowed) {
 7302: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7303: 	    $courseid=$tmp_courseid;
 7304: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7305: 	    ($name)=&get_env_multiple('form.grade_username');
 7306: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7307: 	}
 7308:     }
 7309:     if (!$passedsymb) {
 7310: 	$symb=&symbread();
 7311:     } else {
 7312: 	$symb=$passedsymb;
 7313:     }
 7314:     $courseid=$env{'request.course.id'};
 7315:     $domain=$env{'user.domain'};
 7316:     $name=$env{'user.name'};
 7317:     if ($name eq 'public' && $domain eq 'public') {
 7318: 	if (!defined($env{'form.username'})) {
 7319: 	    $env{'form.username'}.=time.rand(10000000);
 7320: 	}
 7321: 	$name.=$env{'form.username'};
 7322:     }
 7323:     return ($symb,$courseid,$domain,$name,$publicuser);
 7324: 
 7325: }
 7326: 
 7327: # ------------------------------------------------------------ Serves up a file
 7328: # returns either the contents of the file or 
 7329: # -1 if the file doesn't exist
 7330: #
 7331: # if the target is a file that was uploaded via DOCS, 
 7332: # a check will be made to see if a current copy exists on the local server,
 7333: # if it does this will be served, otherwise a copy will be retrieved from
 7334: # the home server for the course and stored in /home/httpd/html/userfiles on
 7335: # the local server.   
 7336: 
 7337: sub getfile {
 7338:     my ($file) = @_;
 7339:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7340:     &repcopy($file);
 7341:     return &readfile($file);
 7342: }
 7343: 
 7344: sub repcopy_userfile {
 7345:     my ($file)=@_;
 7346:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7347:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7348:     my ($cdom,$cnum,$filename) = 
 7349: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7350:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7351:     if (-e "$file") {
 7352: # we already have a local copy, check it out
 7353: 	my @fileinfo = stat($file);
 7354: 	my $rtncode;
 7355: 	my $info;
 7356: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7357: 	if ($lwpresp ne 'ok') {
 7358: # there is no such file anymore, even though we had a local copy
 7359: 	    if ($rtncode eq '404') {
 7360: 		unlink($file);
 7361: 	    }
 7362: 	    return -1;
 7363: 	}
 7364: 	if ($info < $fileinfo[9]) {
 7365: # nice, the file we have is up-to-date, just say okay
 7366: 	    return 'ok';
 7367: 	} else {
 7368: # the file is outdated, get rid of it
 7369: 	    unlink($file);
 7370: 	}
 7371:     }
 7372: # one way or the other, at this point, we don't have the file
 7373: # construct the correct path for the file
 7374:     my @parts = ($cdom,$cnum); 
 7375:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7376: 	push @parts, split(/\//,$1);
 7377:     }
 7378:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7379:     foreach my $part (@parts) {
 7380: 	$path .= '/'.$part;
 7381: 	if (!-e $path) {
 7382: 	    mkdir($path,0770);
 7383: 	}
 7384:     }
 7385: # now the path exists for sure
 7386: # get a user agent
 7387:     my $ua=new LWP::UserAgent;
 7388:     my $transferfile=$file.'.in.transfer';
 7389: # FIXME: this should flock
 7390:     if (-e $transferfile) { return 'ok'; }
 7391:     my $request;
 7392:     $uri=~s/^\///;
 7393:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7394:     my $response=$ua->request($request,$transferfile);
 7395: # did it work?
 7396:     if ($response->is_error()) {
 7397: 	unlink($transferfile);
 7398: 	&logthis("Userfile repcopy failed for $uri");
 7399: 	return -1;
 7400:     }
 7401: # worked, rename the transfer file
 7402:     rename($transferfile,$file);
 7403:     return 'ok';
 7404: }
 7405: 
 7406: sub tokenwrapper {
 7407:     my $uri=shift;
 7408:     $uri=~s|^http\://([^/]+)||;
 7409:     $uri=~s|^/||;
 7410:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7411:     my $token=$1;
 7412:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7413:     if ($udom && $uname && $file) {
 7414: 	$file=~s|(\?\.*)*$||;
 7415:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7416:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7417:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7418:                                '&tokenissued='.$perlvar{'lonHostID'};
 7419:     } else {
 7420:         return '/adm/notfound.html';
 7421:     }
 7422: }
 7423: 
 7424: # call with reqtype HEAD: get last modification time
 7425: # call with reqtype GET: get the file contents
 7426: # Do not call this with reqtype GET for large files! It loads everything into memory
 7427: #
 7428: sub getuploaded {
 7429:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7430:     $uri=~s/^\///;
 7431:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7432:     my $ua=new LWP::UserAgent;
 7433:     my $request=new HTTP::Request($reqtype,$uri);
 7434:     my $response=$ua->request($request);
 7435:     $$rtncode = $response->code;
 7436:     if (! $response->is_success()) {
 7437: 	return 'failed';
 7438:     }      
 7439:     if ($reqtype eq 'HEAD') {
 7440: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7441:     } elsif ($reqtype eq 'GET') {
 7442: 	$$info = $response->content;
 7443:     }
 7444:     return 'ok';
 7445: }
 7446: 
 7447: sub readfile {
 7448:     my $file = shift;
 7449:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7450:     my $fh;
 7451:     open($fh,"<$file");
 7452:     my $a='';
 7453:     while (my $line = <$fh>) { $a .= $line; }
 7454:     return $a;
 7455: }
 7456: 
 7457: sub filelocation {
 7458:     my ($dir,$file) = @_;
 7459:     my $location;
 7460:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7461: 
 7462:     if ($file =~ m-^/adm/-) {
 7463: 	$file=~s-^/adm/wrapper/-/-;
 7464: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7465:     }
 7466:     if ($file=~m:^/~:) { # is a contruction space reference
 7467:         $location = $file;
 7468:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7469:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7470: 	# is a correct contruction space reference
 7471:         $location = $file;
 7472:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7473:         my ($udom,$uname,$filename)=
 7474:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7475:         my $home=&homeserver($uname,$udom);
 7476:         my $is_me=0;
 7477:         my @ids=&current_machine_ids();
 7478:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7479:         if ($is_me) {
 7480:   	    $location=&propath($udom,$uname).
 7481:   	      '/userfiles/'.$filename;
 7482:         } else {
 7483:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7484:   	      $udom.'/'.$uname.'/'.$filename;
 7485:         }
 7486:     } else {
 7487:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7488:         $file=~s:^/res/:/:;
 7489:         if ( !( $file =~ m:^/:) ) {
 7490:             $location = $dir. '/'.$file;
 7491:         } else {
 7492:             $location = '/home/httpd/html/res'.$file;
 7493:         }
 7494:     }
 7495:     $location=~s://+:/:g; # remove duplicate /
 7496:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7497:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7498:     return $location;
 7499: }
 7500: 
 7501: sub hreflocation {
 7502:     my ($dir,$file)=@_;
 7503:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7504: 	$file=filelocation($dir,$file);
 7505:     } elsif ($file=~m-^/adm/-) {
 7506: 	$file=~s-^/adm/wrapper/-/-;
 7507: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7508:     }
 7509:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7510: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7511:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7512: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7513:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7514: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7515: 	    -/uploaded/$1/$2/-x;
 7516:     }
 7517:     return $file;
 7518: }
 7519: 
 7520: sub current_machine_domains {
 7521:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7522: }
 7523: 
 7524: sub machine_domains {
 7525:     my ($hostname) = @_;
 7526:     my @domains;
 7527:     my %hostname = &all_hostnames();
 7528:     while( my($id, $name) = each(%hostname)) {
 7529: #	&logthis("-$id-$name-$hostname-");
 7530: 	if ($hostname eq $name) {
 7531: 	    push(@domains,&host_domain($id));
 7532: 	}
 7533:     }
 7534:     return @domains;
 7535: }
 7536: 
 7537: sub current_machine_ids {
 7538:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7539: }
 7540: 
 7541: sub machine_ids {
 7542:     my ($hostname) = @_;
 7543:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7544:     my @ids;
 7545:     my %hostname = &all_hostnames();
 7546:     while( my($id, $name) = each(%hostname)) {
 7547: #	&logthis("-$id-$name-$hostname-");
 7548: 	if ($hostname eq $name) {
 7549: 	    push(@ids,$id);
 7550: 	}
 7551:     }
 7552:     return @ids;
 7553: }
 7554: 
 7555: sub additional_machine_domains {
 7556:     my @domains;
 7557:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7558:     while( my $line = <$fh>) {
 7559:         $line =~ s/\s//g;
 7560:         push(@domains,$line);
 7561:     }
 7562:     return @domains;
 7563: }
 7564: 
 7565: sub default_login_domain {
 7566:     my $domain = $perlvar{'lonDefDomain'};
 7567:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7568:     foreach my $posdom (&current_machine_domains(),
 7569:                         &additional_machine_domains()) {
 7570:         if (lc($posdom) eq lc($testdomain)) {
 7571:             $domain=$posdom;
 7572:             last;
 7573:         }
 7574:     }
 7575:     return $domain;
 7576: }
 7577: 
 7578: # ------------------------------------------------------------- Declutters URLs
 7579: 
 7580: sub declutter {
 7581:     my $thisfn=shift;
 7582:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7583:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7584:     $thisfn=~s/^\///;
 7585:     $thisfn=~s|^adm/wrapper/||;
 7586:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7587:     $thisfn=~s/^res\///;
 7588:     $thisfn=~s/\?.+$//;
 7589:     return $thisfn;
 7590: }
 7591: 
 7592: # ------------------------------------------------------------- Clutter up URLs
 7593: 
 7594: sub clutter {
 7595:     my $thisfn='/'.&declutter(shift);
 7596:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7597:        $thisfn='/res'.$thisfn; 
 7598:     }
 7599:     if ($thisfn !~m|/adm|) {
 7600: 	if ($thisfn =~ m|/ext/|) {
 7601: 	    $thisfn='/adm/wrapper'.$thisfn;
 7602: 	} else {
 7603: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7604: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7605: 	    if ($embstyle eq 'ssi'
 7606: 		|| ($embstyle eq 'hdn')
 7607: 		|| ($embstyle eq 'rat')
 7608: 		|| ($embstyle eq 'prv')
 7609: 		|| ($embstyle eq 'ign')) {
 7610: 		#do nothing with these
 7611: 	    } elsif (($embstyle eq 'img') 
 7612: 		|| ($embstyle eq 'emb')
 7613: 		|| ($embstyle eq 'wrp')) {
 7614: 		$thisfn='/adm/wrapper'.$thisfn;
 7615: 	    } elsif ($embstyle eq 'unk'
 7616: 		     && $thisfn!~/\.(sequence|page)$/) {
 7617: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7618: 	    } else {
 7619: #		&logthis("Got a blank emb style");
 7620: 	    }
 7621: 	}
 7622:     }
 7623:     return $thisfn;
 7624: }
 7625: 
 7626: sub clutter_with_no_wrapper {
 7627:     my $uri = &clutter(shift);
 7628:     if ($uri =~ m-^/adm/-) {
 7629: 	$uri =~ s-^/adm/wrapper/-/-;
 7630: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7631:     }
 7632:     return $uri;
 7633: }
 7634: 
 7635: sub freeze_escape {
 7636:     my ($value)=@_;
 7637:     if (ref($value)) {
 7638: 	$value=&nfreeze($value);
 7639: 	return '__FROZEN__'.&escape($value);
 7640:     }
 7641:     return &escape($value);
 7642: }
 7643: 
 7644: 
 7645: sub thaw_unescape {
 7646:     my ($value)=@_;
 7647:     if ($value =~ /^__FROZEN__/) {
 7648: 	substr($value,0,10,undef);
 7649: 	$value=&unescape($value);
 7650: 	return &thaw($value);
 7651:     }
 7652:     return &unescape($value);
 7653: }
 7654: 
 7655: sub correct_line_ends {
 7656:     my ($result)=@_;
 7657:     $$result =~s/\r\n/\n/mg;
 7658:     $$result =~s/\r/\n/mg;
 7659: }
 7660: # ================================================================ Main Program
 7661: 
 7662: sub goodbye {
 7663:    &logthis("Starting Shut down");
 7664: #not converted to using infrastruture and probably shouldn't be
 7665:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7666: #converted
 7667: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7668:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7669: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7670: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7671: #1.1 only
 7672: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7673: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7674: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7675: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7676:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7677:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7678:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7679:    &flushcourselogs();
 7680:    &logthis("Shutting down");
 7681: }
 7682: 
 7683: sub get_dns {
 7684:     my ($url,$func,$ignore_cache) = @_;
 7685:     if (!$ignore_cache) {
 7686: 	my ($content,$cached)=
 7687: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7688: 	if ($cached) {
 7689: 	    &$func($content);
 7690: 	    return;
 7691: 	}
 7692:     }
 7693: 
 7694:     my %alldns;
 7695:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7696:     foreach my $dns (<$config>) {
 7697: 	next if ($dns !~ /^\^(\S*)/x);
 7698: 	$alldns{$1} = 1;
 7699:     }
 7700:     while (%alldns) {
 7701: 	my ($dns) = keys(%alldns);
 7702: 	delete($alldns{$dns});
 7703: 	my $ua=new LWP::UserAgent;
 7704: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7705: 	my $response=$ua->request($request);
 7706: 	next if ($response->is_error());
 7707: 	my @content = split("\n",$response->content);
 7708: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7709: 	&$func(\@content);
 7710: 	return;
 7711:     }
 7712:     close($config);
 7713:     my $which = (split('/',$url))[3];
 7714:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 7715:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 7716:     my @content = <$config>;
 7717:     &$func(\@content);
 7718:     return;
 7719: }
 7720: # ------------------------------------------------------------ Read domain file
 7721: {
 7722:     my $loaded;
 7723:     my %domain;
 7724: 
 7725:     sub parse_domain_tab {
 7726: 	my ($lines) = @_;
 7727: 	foreach my $line (@$lines) {
 7728: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7729: 
 7730: 	    chomp($line);
 7731: 	    my ($name,@elements) = split(/:/,$line,9);
 7732: 	    my %this_domain;
 7733: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7734: 			       'lang_def', 'city', 'longi', 'lati',
 7735: 			       'primary') {
 7736: 		$this_domain{$field} = shift(@elements);
 7737: 	    }
 7738: 	    $domain{$name} = \%this_domain;
 7739: 	}
 7740:     }
 7741: 
 7742:     sub reset_domain_info {
 7743: 	undef($loaded);
 7744: 	undef(%domain);
 7745:     }
 7746: 
 7747:     sub load_domain_tab {
 7748: 	my ($ignore_cache) = @_;
 7749: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7750: 	my $fh;
 7751: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7752: 	    my @lines = <$fh>;
 7753: 	    &parse_domain_tab(\@lines);
 7754: 	}
 7755: 	close($fh);
 7756: 	$loaded = 1;
 7757:     }
 7758: 
 7759:     sub domain {
 7760: 	&load_domain_tab() if (!$loaded);
 7761: 
 7762: 	my ($name,$what) = @_;
 7763: 	return if ( !exists($domain{$name}) );
 7764: 
 7765: 	if (!$what) {
 7766: 	    return $domain{$name}{'description'};
 7767: 	}
 7768: 	return $domain{$name}{$what};
 7769:     }
 7770: }
 7771: 
 7772: 
 7773: # ------------------------------------------------------------- Read hosts file
 7774: {
 7775:     my %hostname;
 7776:     my %hostdom;
 7777:     my %libserv;
 7778:     my $loaded;
 7779: 
 7780:     sub parse_hosts_tab {
 7781: 	my ($file) = @_;
 7782: 	foreach my $configline (@$file) {
 7783: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7784: 	    next if ($configline =~ /^\^/);
 7785: 	    chomp($configline);
 7786: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7787: 	    $name=~s/\s//g;
 7788: 	    if ($id && $domain && $role && $name) {
 7789: 		$hostname{$id}=$name;
 7790: 		$hostdom{$id}=$domain;
 7791: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7792: 	    }
 7793: 	}
 7794:     }
 7795:     
 7796:     sub reset_hosts_info {
 7797: 	&reset_domain_info();
 7798: 	&reset_hosts_ip_info();
 7799: 	undef(%hostname);
 7800: 	undef(%hostdom);
 7801: 	undef(%libserv);
 7802: 	undef($loaded);
 7803:     }
 7804: 
 7805:     sub load_hosts_tab {
 7806: 	my ($ignore_cache) = @_;
 7807: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 7808: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7809: 	my @config = <$config>;
 7810: 	&parse_hosts_tab(\@config);
 7811: 	close($config);
 7812: 	$loaded=1;
 7813:     }
 7814: 
 7815:     sub hostname {
 7816: 	&load_hosts_tab() if (!$loaded);
 7817: 
 7818: 	my ($lonid) = @_;
 7819: 	return $hostname{$lonid};
 7820:     }
 7821: 
 7822:     sub all_hostnames {
 7823: 	&load_hosts_tab() if (!$loaded);
 7824: 
 7825: 	return %hostname;
 7826:     }
 7827: 
 7828:     sub is_library {
 7829: 	&load_hosts_tab() if (!$loaded);
 7830: 
 7831: 	return exists($libserv{$_[0]});
 7832:     }
 7833: 
 7834:     sub all_library {
 7835: 	&load_hosts_tab() if (!$loaded);
 7836: 
 7837: 	return %libserv;
 7838:     }
 7839: 
 7840:     sub get_servers {
 7841: 	&load_hosts_tab() if (!$loaded);
 7842: 
 7843: 	my ($domain,$type) = @_;
 7844: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7845: 	                                          : %hostname;
 7846: 	my %result;
 7847: 	if (ref($domain) eq 'ARRAY') {
 7848: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7849: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7850: 		    $result{$host} = $hostname;
 7851: 		}
 7852: 	    }
 7853: 	} else {
 7854: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7855: 		if ($hostdom{$host} eq $domain) {
 7856: 		    $result{$host} = $hostname;
 7857: 		}
 7858: 	    }
 7859: 	}
 7860: 	return %result;
 7861:     }
 7862: 
 7863:     sub host_domain {
 7864: 	&load_hosts_tab() if (!$loaded);
 7865: 
 7866: 	my ($lonid) = @_;
 7867: 	return $hostdom{$lonid};
 7868:     }
 7869: 
 7870:     sub all_domains {
 7871: 	&load_hosts_tab() if (!$loaded);
 7872: 
 7873: 	my %seen;
 7874: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7875: 	return @uniq;
 7876:     }
 7877: }
 7878: 
 7879: { 
 7880:     my %iphost;
 7881:     my %name_to_ip;
 7882:     my %lonid_to_ip;
 7883: 
 7884:     my %valid_ip;
 7885:     sub valid_ip {
 7886: 	my ($ip) = @_;
 7887: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
 7888: 	    return 1;	
 7889: 	}
 7890: 	my $name = gethostbyip($ip);
 7891: 	my $lonid = &hostname($name);
 7892: 	if (defined($lonid)) {
 7893: 	    $valid_ip{$ip} = $lonid;
 7894: 	    return 1;
 7895: 	}
 7896: 	my %iphosts = &get_iphost();
 7897: 	if (ref($iphost{$ip})) {
 7898: 	    return 1;	
 7899: 	}
 7900:     }
 7901: 
 7902:     sub get_hosts_from_ip {
 7903: 	my ($ip) = @_;
 7904: 	my %iphosts = &get_iphost();
 7905: 	if (ref($iphosts{$ip})) {
 7906: 	    return @{$iphosts{$ip}};
 7907: 	}
 7908: 	return;
 7909:     }
 7910:     
 7911:     sub reset_hosts_ip_info {
 7912: 	undef(%iphost);
 7913: 	undef(%name_to_ip);
 7914: 	undef(%lonid_to_ip);
 7915:     }
 7916: 
 7917:     sub get_host_ip {
 7918: 	my ($lonid) = @_;
 7919: 	if (exists($lonid_to_ip{$lonid})) {
 7920: 	    return $lonid_to_ip{$lonid};
 7921: 	}
 7922: 	my $name=&hostname($lonid);
 7923:    	my $ip = gethostbyname($name);
 7924: 	return if (!$ip || length($ip) ne 4);
 7925: 	$ip=inet_ntoa($ip);
 7926: 	$name_to_ip{$name}   = $ip;
 7927: 	$lonid_to_ip{$lonid} = $ip;
 7928: 	return $ip;
 7929:     }
 7930:     
 7931:     sub get_iphost {
 7932: 	my ($ignore_cache) = @_;
 7933: 	if (!$ignore_cache) {
 7934: 	    if (%iphost) {
 7935: 		return %iphost;
 7936: 	    }
 7937: 	    my ($ip_info,$cached)=
 7938: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 7939: 	    if ($cached) {
 7940: 		%iphost      = %{$ip_info->[0]};
 7941: 		%name_to_ip  = %{$ip_info->[1]};
 7942: 		%lonid_to_ip = %{$ip_info->[2]};
 7943: 		return %iphost;
 7944: 	    }
 7945: 	}
 7946: 	my %hostname = &all_hostnames();
 7947: 	foreach my $id (keys(%hostname)) {
 7948: 	    my $name=&hostname($id);
 7949: 	    my $ip;
 7950: 	    if (!exists($name_to_ip{$name})) {
 7951: 		$ip = gethostbyname($name);
 7952: 		if (!$ip || length($ip) ne 4) {
 7953: 		    &logthis("Skipping host $id name $name no IP found");
 7954: 		    next;
 7955: 		}
 7956: 		$ip=inet_ntoa($ip);
 7957: 		$name_to_ip{$name} = $ip;
 7958: 	    } else {
 7959: 		$ip = $name_to_ip{$name};
 7960: 	    }
 7961: 	    $lonid_to_ip{$id} = $ip;
 7962: 	    push(@{$iphost{$ip}},$id);
 7963: 	}
 7964: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 7965: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 7966: 				      24*60*60);
 7967: 
 7968: 	return %iphost;
 7969:     }
 7970: }
 7971: 
 7972: BEGIN {
 7973: 
 7974: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7975:     unless ($readit) {
 7976: {
 7977:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7978:     %perlvar = (%perlvar,%{$configvars});
 7979: }
 7980: 
 7981: 
 7982: # ------------------------------------------------------ Read spare server file
 7983: {
 7984:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7985: 
 7986:     while (my $configline=<$config>) {
 7987:        chomp($configline);
 7988:        if ($configline) {
 7989: 	   my ($host,$type) = split(':',$configline,2);
 7990: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7991: 	   push(@{ $spareid{$type} }, $host);
 7992:        }
 7993:     }
 7994:     close($config);
 7995: }
 7996: # ------------------------------------------------------------ Read permissions
 7997: {
 7998:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7999: 
 8000:     while (my $configline=<$config>) {
 8001: 	chomp($configline);
 8002: 	if ($configline) {
 8003: 	    my ($role,$perm)=split(/ /,$configline);
 8004: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8005: 	}
 8006:     }
 8007:     close($config);
 8008: }
 8009: 
 8010: # -------------------------------------------- Read plain texts for permissions
 8011: {
 8012:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8013: 
 8014:     while (my $configline=<$config>) {
 8015: 	chomp($configline);
 8016: 	if ($configline) {
 8017: 	    my ($short,@plain)=split(/:/,$configline);
 8018:             %{$prp{$short}} = ();
 8019: 	    if (@plain > 0) {
 8020:                 $prp{$short}{'std'} = $plain[0];
 8021:                 for (my $i=1; $i<@plain; $i++) {
 8022:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8023:                 }
 8024:             }
 8025: 	}
 8026:     }
 8027:     close($config);
 8028: }
 8029: 
 8030: # ---------------------------------------------------------- Read package table
 8031: {
 8032:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8033: 
 8034:     while (my $configline=<$config>) {
 8035: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8036: 	chomp($configline);
 8037: 	my ($short,$plain)=split(/:/,$configline);
 8038: 	my ($pack,$name)=split(/\&/,$short);
 8039: 	if ($plain ne '') {
 8040: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8041: 	    $packagetab{$short}=$plain; 
 8042: 	}
 8043:     }
 8044:     close($config);
 8045: }
 8046: 
 8047: # ------------- set up temporary directory
 8048: {
 8049:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8050: 
 8051: }
 8052: 
 8053: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8054: 				'compress_threshold'=> 20_000,
 8055:  			        });
 8056: 
 8057: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8058: $dumpcount=0;
 8059: 
 8060: &logtouch();
 8061: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8062: $readit=1;
 8063:     {
 8064: 	use integer;
 8065: 	my $test=(2**32)+1;
 8066: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8067: 	&logthis(" Detected 64bit platform ($_64bit)");
 8068:     }
 8069: }
 8070: }
 8071: 
 8072: 1;
 8073: __END__
 8074: 
 8075: =pod
 8076: 
 8077: =head1 NAME
 8078: 
 8079: Apache::lonnet - Subroutines to ask questions about things in the network.
 8080: 
 8081: =head1 SYNOPSIS
 8082: 
 8083: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8084: 
 8085:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8086: 
 8087: Common parameters:
 8088: 
 8089: =over 4
 8090: 
 8091: =item *
 8092: 
 8093: $uname : an internal username (if $cname expecting a course Id specifically)
 8094: 
 8095: =item *
 8096: 
 8097: $udom : a domain (if $cdom expecting a course's domain specifically)
 8098: 
 8099: =item *
 8100: 
 8101: $symb : a resource instance identifier
 8102: 
 8103: =item *
 8104: 
 8105: $namespace : the name of a .db file that contains the data needed or
 8106: being set.
 8107: 
 8108: =back
 8109: 
 8110: =head1 OVERVIEW
 8111: 
 8112: lonnet provides subroutines which interact with the
 8113: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8114: about classes, users, and resources.
 8115: 
 8116: For many of these objects you can also use this to store data about
 8117: them or modify them in various ways.
 8118: 
 8119: =head2 Symbs
 8120: 
 8121: To identify a specific instance of a resource, LON-CAPA uses symbols
 8122: or "symbs"X<symb>. These identifiers are built from the URL of the
 8123: map, the resource number of the resource in the map, and the URL of
 8124: the resource itself. The latter is somewhat redundant, but might help
 8125: if maps change.
 8126: 
 8127: An example is
 8128: 
 8129:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8130: 
 8131: The respective map entry is
 8132: 
 8133:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8134:   title="Problem 2">
 8135:  </resource>
 8136: 
 8137: Symbs are used by the random number generator, as well as to store and
 8138: restore data specific to a certain instance of for example a problem.
 8139: 
 8140: =head2 Storing And Retrieving Data
 8141: 
 8142: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8143: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8144: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8145: is is the non-critical message twin of cstore. These functions are for
 8146: handlers to store a perl hash to a user's permanent data space in an
 8147: easy manner, and to retrieve it again on another call. It is expected
 8148: that a handler would use this once at the beginning to retrieve data,
 8149: and then again once at the end to send only the new data back.
 8150: 
 8151: The data is stored in the user's data directory on the user's
 8152: homeserver under the ID of the course.
 8153: 
 8154: The hash that is returned by restore will have all of the previous
 8155: value for all of the elements of the hash.
 8156: 
 8157: Example:
 8158: 
 8159:  #creating a hash
 8160:  my %hash;
 8161:  $hash{'foo'}='bar';
 8162: 
 8163:  #storing it
 8164:  &Apache::lonnet::cstore(\%hash);
 8165: 
 8166:  #changing a value
 8167:  $hash{'foo'}='notbar';
 8168: 
 8169:  #adding a new value
 8170:  $hash{'bar'}='foo';
 8171:  &Apache::lonnet::cstore(\%hash);
 8172: 
 8173:  #retrieving the hash
 8174:  my %history=&Apache::lonnet::restore();
 8175: 
 8176:  #print the hash
 8177:  foreach my $key (sort(keys(%history))) {
 8178:    print("\%history{$key} = $history{$key}");
 8179:  }
 8180: 
 8181: Will print out:
 8182: 
 8183:  %history{1:foo} = bar
 8184:  %history{1:keys} = foo:timestamp
 8185:  %history{1:timestamp} = 990455579
 8186:  %history{2:bar} = foo
 8187:  %history{2:foo} = notbar
 8188:  %history{2:keys} = foo:bar:timestamp
 8189:  %history{2:timestamp} = 990455580
 8190:  %history{bar} = foo
 8191:  %history{foo} = notbar
 8192:  %history{timestamp} = 990455580
 8193:  %history{version} = 2
 8194: 
 8195: Note that the special hash entries C<keys>, C<version> and
 8196: C<timestamp> were added to the hash. C<version> will be equal to the
 8197: total number of versions of the data that have been stored. The
 8198: C<timestamp> attribute will be the UNIX time the hash was
 8199: stored. C<keys> is available in every historical section to list which
 8200: keys were added or changed at a specific historical revision of a
 8201: hash.
 8202: 
 8203: B<Warning>: do not store the hash that restore returns directly. This
 8204: will cause a mess since it will restore the historical keys as if the
 8205: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8206: 
 8207: Calling convention:
 8208: 
 8209:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8210:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8211: 
 8212: For more detailed information, see lonnet specific documentation.
 8213: 
 8214: =head1 RETURN MESSAGES
 8215: 
 8216: =over 4
 8217: 
 8218: =item * B<con_lost>: unable to contact remote host
 8219: 
 8220: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8221: when the connection is brought back up
 8222: 
 8223: =item * B<con_failed>: unable to contact remote host and unable to save message
 8224: for later delivery
 8225: 
 8226: =item * B<error:>: an error a occured, a description of the error follows the :
 8227: 
 8228: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8229: that was requested
 8230: 
 8231: =back
 8232: 
 8233: =head1 PUBLIC SUBROUTINES
 8234: 
 8235: =head2 Session Environment Functions
 8236: 
 8237: =over 4
 8238: 
 8239: =item * 
 8240: X<appenv()>
 8241: B<appenv(%hash)>: the value of %hash is written to
 8242: the user envirnoment file, and will be restored for each access this
 8243: user makes during this session, also modifies the %env for the current
 8244: process
 8245: 
 8246: =item *
 8247: X<delenv()>
 8248: B<delenv($regexp)>: removes all items from the session
 8249: environment file that matches the regular expression in $regexp. The
 8250: values are also delted from the current processes %env.
 8251: 
 8252: =item * get_env_multiple($name) 
 8253: 
 8254: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8255: values may be defined and end up as an array ref.
 8256: 
 8257: returns an array of values
 8258: 
 8259: =back
 8260: 
 8261: =head2 User Information
 8262: 
 8263: =over 4
 8264: 
 8265: =item *
 8266: X<queryauthenticate()>
 8267: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8268: authentication scheme
 8269: 
 8270: =item *
 8271: X<authenticate()>
 8272: B<authenticate($uname,$upass,$udom)>: try to
 8273: authenticate user from domain's lib servers (first use the current
 8274: one). C<$upass> should be the users password.
 8275: 
 8276: =item *
 8277: X<homeserver()>
 8278: B<homeserver($uname,$udom)>: find the server which has
 8279: the user's directory and files (there must be only one), this caches
 8280: the answer, and also caches if there is a borken connection.
 8281: 
 8282: =item *
 8283: X<idget()>
 8284: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8285: (IDs are a unique resource in a domain, there must be only 1 ID per
 8286: username, and only 1 username per ID in a specific domain) (returns
 8287: hash: id=>name,id=>name)
 8288: 
 8289: =item *
 8290: X<idrget()>
 8291: B<idrget($udom,@unames)>: find the IDs behind a list of
 8292: usernames (returns hash: name=>id,name=>id)
 8293: 
 8294: =item *
 8295: X<idput()>
 8296: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8297: 
 8298: =item *
 8299: X<rolesinit()>
 8300: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8301: 
 8302: =item *
 8303: X<getsection()>
 8304: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8305: course $cname, return section name/number or '' for "not in course"
 8306: and '-1' for "no section"
 8307: 
 8308: =item *
 8309: X<userenvironment()>
 8310: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8311: passed in @what from the requested user's environment, returns a hash
 8312: 
 8313: =item * 
 8314: X<userlog_query()>
 8315: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8316: activity.log file. %filters defines filters applied when parsing the
 8317: log file. These can be start or end timestamps, or the type of action
 8318: - log to look for Login or Logout events, check for Checkin or
 8319: Checkout, role for role selection. The response is in the form
 8320: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8321: escaped strings of the action recorded in the activity.log file.
 8322: 
 8323: =back
 8324: 
 8325: =head2 User Roles
 8326: 
 8327: =over 4
 8328: 
 8329: =item *
 8330: 
 8331: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8332:  F: full access
 8333:  U,I,K: authentication modes (cxx only)
 8334:  '': forbidden
 8335:  1: user needs to choose course
 8336:  2: browse allowed
 8337:  A: passphrase authentication needed
 8338: 
 8339: =item *
 8340: 
 8341: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8342: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8343: and course level
 8344: 
 8345: =item *
 8346: 
 8347: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8348: explanation of a user role term
 8349: 
 8350: =item *
 8351: 
 8352: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8353: All arguments are optional. Returns a hash of a roles, either for
 8354: co-author/assistant author roles for a user's Construction Space
 8355: (default), or if $context is 'user', roles for the user himself,
 8356: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8357: and value is set to colon-separated start and end times for the role.
 8358: If no username and domain are specified, will default to current
 8359: user/domain. Types, roles, and roledoms are references to arrays,
 8360: of role statuses (active, future or previous), roles 
 8361: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8362: to restrict the list of roles reported. If no array ref is 
 8363: provided for types, will default to return only active roles.
 8364: 
 8365: =back
 8366: 
 8367: =head2 User Modification
 8368: 
 8369: =over 4
 8370: 
 8371: =item *
 8372: 
 8373: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8374: user for the level given by URL.  Optional start and end dates (leave empty
 8375: string or zero for "no date")
 8376: 
 8377: =item *
 8378: 
 8379: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8380: change a users, password, possible return values are: ok,
 8381: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8382: refused
 8383: 
 8384: =item *
 8385: 
 8386: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8387: 
 8388: =item *
 8389: 
 8390: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8391: modify user
 8392: 
 8393: =item *
 8394: 
 8395: modifystudent
 8396: 
 8397: modify a students enrollment and identification information.
 8398: The course id is resolved based on the current users environment.  
 8399: This means the envoking user must be a course coordinator or otherwise
 8400: associated with a course.
 8401: 
 8402: This call is essentially a wrapper for lonnet::modifyuser and
 8403: lonnet::modify_student_enrollment
 8404: 
 8405: Inputs: 
 8406: 
 8407: =over 4
 8408: 
 8409: =item B<$udom> Students loncapa domain
 8410: 
 8411: =item B<$uname> Students loncapa login name
 8412: 
 8413: =item B<$uid> Students id/student number
 8414: 
 8415: =item B<$umode> Students authentication mode
 8416: 
 8417: =item B<$upass> Students password
 8418: 
 8419: =item B<$first> Students first name
 8420: 
 8421: =item B<$middle> Students middle name
 8422: 
 8423: =item B<$last> Students last name
 8424: 
 8425: =item B<$gene> Students generation
 8426: 
 8427: =item B<$usec> Students section in course
 8428: 
 8429: =item B<$end> Unix time of the roles expiration
 8430: 
 8431: =item B<$start> Unix time of the roles start date
 8432: 
 8433: =item B<$forceid> If defined, allow $uid to be changed
 8434: 
 8435: =item B<$desiredhome> server to use as home server for student
 8436: 
 8437: =back
 8438: 
 8439: =item *
 8440: 
 8441: modify_student_enrollment
 8442: 
 8443: Change a students enrollment status in a class.  The environment variable
 8444: 'role.request.course' must be defined for this function to proceed.
 8445: 
 8446: Inputs:
 8447: 
 8448: =over 4
 8449: 
 8450: =item $udom, students domain
 8451: 
 8452: =item $uname, students name
 8453: 
 8454: =item $uid, students user id
 8455: 
 8456: =item $first, students first name
 8457: 
 8458: =item $middle
 8459: 
 8460: =item $last
 8461: 
 8462: =item $gene
 8463: 
 8464: =item $usec
 8465: 
 8466: =item $end
 8467: 
 8468: =item $start
 8469: 
 8470: =back
 8471: 
 8472: 
 8473: =item *
 8474: 
 8475: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8476: custom role; give a custom role to a user for the level given by URL.  Specify
 8477: name and domain of role author, and role name
 8478: 
 8479: =item *
 8480: 
 8481: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8482: 
 8483: =item *
 8484: 
 8485: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8486: 
 8487: =back
 8488: 
 8489: =head2 Course Infomation
 8490: 
 8491: =over 4
 8492: 
 8493: =item *
 8494: 
 8495: coursedescription($courseid) : returns a hash of information about the
 8496: specified course id, including all environment settings for the
 8497: course, the description of the course will be in the hash under the
 8498: key 'description'
 8499: 
 8500: =item *
 8501: 
 8502: resdata($name,$domain,$type,@which) : request for current parameter
 8503: setting for a specific $type, where $type is either 'course' or 'user',
 8504: @what should be a list of parameters to ask about. This routine caches
 8505: answers for 5 minutes.
 8506: 
 8507: =back
 8508: 
 8509: =head2 Course Modification
 8510: 
 8511: =over 4
 8512: 
 8513: =item *
 8514: 
 8515: writecoursepref($courseid,%prefs) : write preferences (environment
 8516: database) for a course
 8517: 
 8518: =item *
 8519: 
 8520: createcourse($udom,$description,$url) : make/modify course
 8521: 
 8522: =back
 8523: 
 8524: =head2 Resource Subroutines
 8525: 
 8526: =over 4
 8527: 
 8528: =item *
 8529: 
 8530: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8531: 
 8532: =item *
 8533: 
 8534: repcopy($filename) : subscribes to the requested file, and attempts to
 8535: replicate from the owning library server, Might return
 8536: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8537: 'bad_request', also attempts to grab the metadata for the
 8538: resource. Expects the local filesystem pathname
 8539: (/home/httpd/html/res/....)
 8540: 
 8541: =back
 8542: 
 8543: =head2 Resource Information
 8544: 
 8545: =over 4
 8546: 
 8547: =item *
 8548: 
 8549: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8550: a vairety of different possible values, $varname should be a request
 8551: string, and the other parameters can be used to specify who and what
 8552: one is asking about.
 8553: 
 8554: Possible values for $varname are environment.lastname (or other item
 8555: from the envirnment hash), user.name (or someother aspect about the
 8556: user), resource.0.maxtries (or some other part and parameter of a
 8557: resource)
 8558: 
 8559: =item *
 8560: 
 8561: directcondval($number) : get current value of a condition; reads from a state
 8562: string
 8563: 
 8564: =item *
 8565: 
 8566: condval($condidx) : value of condition index based on state
 8567: 
 8568: =item *
 8569: 
 8570: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8571: resource's metadata, $what should be either a specific key, or either
 8572: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8573: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8574: 
 8575: this function automatically caches all requests
 8576: 
 8577: =item *
 8578: 
 8579: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8580: network of library servers; returns file handle of where SQL and regex results
 8581: will be stored for query
 8582: 
 8583: =item *
 8584: 
 8585: symbread($filename) : return symbolic list entry (filename argument optional);
 8586: returns the data handle
 8587: 
 8588: =item *
 8589: 
 8590: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8591: a possible symb for the URL in $thisfn, and if is an encryypted
 8592: resource that the user accessed using /enc/ returns a 1 on success, 0
 8593: on failure, user must be in a course, as it assumes the existance of
 8594: the course initial hash, and uses $env('request.course.id'}
 8595: 
 8596: 
 8597: =item *
 8598: 
 8599: symbclean($symb) : removes versions numbers from a symb, returns the
 8600: cleaned symb
 8601: 
 8602: =item *
 8603: 
 8604: is_on_map($uri) : checks if the $uri is somewhere on the current
 8605: course map, user must be in a course for it to work.
 8606: 
 8607: =item *
 8608: 
 8609: numval($salt) : return random seed value (addend for rndseed)
 8610: 
 8611: =item *
 8612: 
 8613: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8614: a random seed, all arguments are optional, if they aren't sent it uses the
 8615: environment to derive them. Note: if symb isn't sent and it can't get one
 8616: from &symbread it will use the current time as its return value
 8617: 
 8618: =item *
 8619: 
 8620: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8621: unfakeable, receipt
 8622: 
 8623: =item *
 8624: 
 8625: receipt() : API to ireceipt working off of env values; given out to users
 8626: 
 8627: =item *
 8628: 
 8629: countacc($url) : count the number of accesses to a given URL
 8630: 
 8631: =item *
 8632: 
 8633: 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
 8634: 
 8635: =item *
 8636: 
 8637: 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)
 8638: 
 8639: =item *
 8640: 
 8641: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8642: 
 8643: =item *
 8644: 
 8645: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8646: forcing spreadsheet to reevaluate the resource scores next time.
 8647: 
 8648: =back
 8649: 
 8650: =head2 Storing/Retreiving Data
 8651: 
 8652: =over 4
 8653: 
 8654: =item *
 8655: 
 8656: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8657: for this url; hashref needs to be given and should be a \%hashname; the
 8658: remaining args aren't required and if they aren't passed or are '' they will
 8659: be derived from the env
 8660: 
 8661: =item *
 8662: 
 8663: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8664: uses critical subroutine
 8665: 
 8666: =item *
 8667: 
 8668: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8669: all args are optional
 8670: 
 8671: =item *
 8672: 
 8673: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8674: dumps the complete (or key matching regexp) namespace into a hash
 8675: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8676: normally &store()ed into
 8677: 
 8678: $range should be either an integer '100' (give me the first 100
 8679:                                            matching records)
 8680:               or be  two integers sperated by a - with no spaces
 8681:                  '30-50' (give me the 30th through the 50th matching
 8682:                           records)
 8683: 
 8684: 
 8685: =item *
 8686: 
 8687: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8688: replaces a &store() version of data with a replacement set of data
 8689: for a particular resource in a namespace passed in the $storehash hash 
 8690: reference
 8691: 
 8692: =item *
 8693: 
 8694: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8695: works very similar to store/cstore, but all data is stored in a
 8696: temporary location and can be reset using tmpreset, $storehash should
 8697: be a hash reference, returns nothing on success
 8698: 
 8699: =item *
 8700: 
 8701: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8702: similar to restore, but all data is stored in a temporary location and
 8703: can be reset using tmpreset. Returns a hash of values on success,
 8704: error string otherwise.
 8705: 
 8706: =item *
 8707: 
 8708: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8709: deltes all keys for $symb form the temporary storage hash.
 8710: 
 8711: =item *
 8712: 
 8713: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8714: reference filled in from namesp ($udom and $uname are optional)
 8715: 
 8716: =item *
 8717: 
 8718: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8719: namesp ($udom and $uname are optional)
 8720: 
 8721: =item *
 8722: 
 8723: dump($namespace,$udom,$uname,$regexp,$range) : 
 8724: dumps the complete (or key matching regexp) namespace into a hash
 8725: ($udom, $uname, $regexp, $range are optional)
 8726: 
 8727: $range should be either an integer '100' (give me the first 100
 8728:                                            matching records)
 8729:               or be  two integers sperated by a - with no spaces
 8730:                  '30-50' (give me the 30th through the 50th matching
 8731:                           records)
 8732: =item *
 8733: 
 8734: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8735: $store can be a scalar, an array reference, or if the amount to be 
 8736: incremented is > 1, a hash reference.
 8737: 
 8738: ($udom and $uname are optional)
 8739: 
 8740: =item *
 8741: 
 8742: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8743: ($udom and $uname are optional)
 8744: 
 8745: =item *
 8746: 
 8747: cput($namespace,$storehash,$udom,$uname) : critical put
 8748: ($udom and $uname are optional)
 8749: 
 8750: =item *
 8751: 
 8752: newput($namespace,$storehash,$udom,$uname) :
 8753: 
 8754: Attempts to store the items in the $storehash, but only if they don't
 8755: currently exist, if this succeeds you can be certain that you have 
 8756: successfully created a new key value pair in the $namespace db.
 8757: 
 8758: 
 8759: Args:
 8760:  $namespace: name of database to store values to
 8761:  $storehash: hashref to store to the db
 8762:  $udom: (optional) domain of user containing the db
 8763:  $uname: (optional) name of user caontaining the db
 8764: 
 8765: Returns:
 8766:  'ok' -> succeeded in storing all keys of $storehash
 8767:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8768:                         least <key> already existed in the db (other
 8769:                         requested keys may also already exist)
 8770:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8771:  'con_lost' -> unable to contact request server
 8772:  'refused' -> action was not allowed by remote machine
 8773: 
 8774: 
 8775: =item *
 8776: 
 8777: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8778: reference filled in from namesp (encrypts the return communication)
 8779: ($udom and $uname are optional)
 8780: 
 8781: =item *
 8782: 
 8783: log($udom,$name,$home,$message) : write to permanent log for user; use
 8784: critical subroutine
 8785: 
 8786: =item *
 8787: 
 8788: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8789: array reference filled in from namespace found in domain level on either
 8790: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8791: 
 8792: =item *
 8793: 
 8794: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8795: domain level either on specified domain server ($uhome) or primary domain 
 8796: server ($udom and $uhome are optional)
 8797: 
 8798: =back
 8799: 
 8800: =head2 Network Status Functions
 8801: 
 8802: =over 4
 8803: 
 8804: =item *
 8805: 
 8806: dirlist($uri) : return directory list based on URI
 8807: 
 8808: =item *
 8809: 
 8810: spareserver() : find server with least workload from spare.tab
 8811: 
 8812: =back
 8813: 
 8814: =head2 Apache Request
 8815: 
 8816: =over 4
 8817: 
 8818: =item *
 8819: 
 8820: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8821: localhost, posts hash
 8822: 
 8823: =back
 8824: 
 8825: =head2 Data to String to Data
 8826: 
 8827: =over 4
 8828: 
 8829: =item *
 8830: 
 8831: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8832: and '&' separators, supports elements that are arrayrefs and hashrefs
 8833: 
 8834: =item *
 8835: 
 8836: hashref2str($hashref) : convert a hashref into a string complete with
 8837: escaping and '=' and '&' separators, supports elements that are
 8838: arrayrefs and hashrefs
 8839: 
 8840: =item *
 8841: 
 8842: arrayref2str($arrayref) : convert an arrayref into a string complete
 8843: with escaping and '&' separators, supports elements that are arrayrefs
 8844: and hashrefs
 8845: 
 8846: =item *
 8847: 
 8848: str2hash($string) : convert string to hash using unescaping and
 8849: splitting on '=' and '&', supports elements that are arrayrefs and
 8850: hashrefs
 8851: 
 8852: =item *
 8853: 
 8854: str2array($string) : convert string to hash using unescaping and
 8855: splitting on '&', supports elements that are arrayrefs and hashrefs
 8856: 
 8857: =back
 8858: 
 8859: =head2 Logging Routines
 8860: 
 8861: =over 4
 8862: 
 8863: These routines allow one to make log messages in the lonnet.log and
 8864: lonnet.perm logfiles.
 8865: 
 8866: =item *
 8867: 
 8868: logtouch() : make sure the logfile, lonnet.log, exists
 8869: 
 8870: =item *
 8871: 
 8872: logthis() : append message to the normal lonnet.log file, it gets
 8873: preiodically rolled over and deleted.
 8874: 
 8875: =item *
 8876: 
 8877: logperm() : append a permanent message to lonnet.perm.log, this log
 8878: file never gets deleted by any automated portion of the system, only
 8879: messages of critical importance should go in here.
 8880: 
 8881: =back
 8882: 
 8883: =head2 General File Helper Routines
 8884: 
 8885: =over 4
 8886: 
 8887: =item *
 8888: 
 8889: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8890: (a) files in /uploaded
 8891:   (i) If a local copy of the file exists - 
 8892:       compares modification date of local copy with last-modified date for 
 8893:       definitive version stored on home server for course. If local copy is 
 8894:       stale, requests a new version from the home server and stores it. 
 8895:       If the original has been removed from the home server, then local copy 
 8896:       is unlinked.
 8897:   (ii) If local copy does not exist -
 8898:       requests the file from the home server and stores it. 
 8899:   
 8900:   If $caller is 'uploadrep':  
 8901:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8902:     for request for files originally uploaded via DOCS. 
 8903:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8904:   
 8905:   Otherwise:
 8906:      This indicates a call from the content generation phase of the request.
 8907:      -  returns the entire contents of the file or -1.
 8908:      
 8909: (b) files in /res
 8910:    - returns the entire contents of a file or -1; 
 8911:    it properly subscribes to and replicates the file if neccessary.
 8912: 
 8913: 
 8914: =item *
 8915: 
 8916: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8917:                   reference
 8918: 
 8919: returns either a stat() list of data about the file or an empty list
 8920: if the file doesn't exist or couldn't find out about it (connection
 8921: problems or user unknown)
 8922: 
 8923: =item *
 8924: 
 8925: filelocation($dir,$file) : returns file system location of a file
 8926: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8927: directory that relative $file lookups are to looked in ($dir of /a/dir
 8928: and a file of ../bob will become /a/bob)
 8929: 
 8930: =item *
 8931: 
 8932: hreflocation($dir,$file) : returns file system location or a URL; same as
 8933: filelocation except for hrefs
 8934: 
 8935: =item *
 8936: 
 8937: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8938: 
 8939: =back
 8940: 
 8941: =head2 Usererfile file routines (/uploaded*)
 8942: 
 8943: =over 4
 8944: 
 8945: =item *
 8946: 
 8947: userfileupload(): main rotine for putting a file in a user or course's
 8948:                   filespace, arguments are,
 8949: 
 8950:  formname - required - this is the name of the element in $env where the
 8951:            filename, and the contents of the file to create/modifed exist
 8952:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8953:            contents of the file is located in $env{'form.'.$formname}
 8954:  coursedoc - if true, store the file in the course of the active role
 8955:              of the current user
 8956:  subdir - required - subdirectory to put the file in under ../userfiles/
 8957:          if undefined, it will be placed in "unknown"
 8958: 
 8959:  (This routine calls clean_filename() to remove any dangerous
 8960:  characters from the filename, and then calls finuserfileupload() to
 8961:  complete the transaction)
 8962: 
 8963:  returns either the url of the uploaded file (/uploaded/....) if successful
 8964:  and /adm/notfound.html if unsuccessful
 8965: 
 8966: =item *
 8967: 
 8968: clean_filename(): routine for cleaing a filename up for storage in
 8969:                  userfile space, argument is:
 8970: 
 8971:  filename - proposed filename
 8972: 
 8973: returns: the new clean filename
 8974: 
 8975: =item *
 8976: 
 8977: finishuserfileupload(): routine that creaes and sends the file to
 8978: userspace, probably shouldn't be called directly
 8979: 
 8980:   docuname: username or courseid of destination for the file
 8981:   docudom: domain of user/course of destination for the file
 8982:   formname: same as for userfileupload()
 8983:   fname: filename (inculding subdirectories) for the file
 8984: 
 8985:  returns either the url of the uploaded file (/uploaded/....) if successful
 8986:  and /adm/notfound.html if unsuccessful
 8987: 
 8988: =item *
 8989: 
 8990: renameuserfile(): renames an existing userfile to a new name
 8991: 
 8992:   Args:
 8993:    docuname: username or courseid of destination for the file
 8994:    docudom: domain of user/course of destination for the file
 8995:    old: current file name (including any subdirs under userfiles)
 8996:    new: desired file name (including any subdirs under userfiles)
 8997: 
 8998: =item *
 8999: 
 9000: mkdiruserfile(): creates a directory is a userfiles dir
 9001: 
 9002:   Args:
 9003:    docuname: username or courseid of destination for the file
 9004:    docudom: domain of user/course of destination for the file
 9005:    dir: dir to create (including any subdirs under userfiles)
 9006: 
 9007: =item *
 9008: 
 9009: removeuserfile(): removes a file that exists in userfiles
 9010: 
 9011:   Args:
 9012:    docuname: username or courseid of destination for the file
 9013:    docudom: domain of user/course of destination for the file
 9014:    fname: filname to delete (including any subdirs under userfiles)
 9015: 
 9016: =item *
 9017: 
 9018: removeuploadedurl(): convience function for removeuserfile()
 9019: 
 9020:   Args:
 9021:    url:  a full /uploaded/... url to delete
 9022: 
 9023: =item * 
 9024: 
 9025: get_portfile_permissions():
 9026:   Args:
 9027:     domain: domain of user or course contain the portfolio files
 9028:     user: name of user or num of course contain the portfolio files
 9029:   Returns:
 9030:     hashref of a dump of the proper file_permissions.db
 9031:    
 9032: 
 9033: =item * 
 9034: 
 9035: get_access_controls():
 9036: 
 9037: Args:
 9038:   current_permissions: the hash ref returned from get_portfile_permissions()
 9039:   group: (optional) the group you want the files associated with
 9040:   file: (optional) the file you want access info on
 9041: 
 9042: Returns:
 9043:     a hash (keys are file names) of hashes containing
 9044:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9045:         values are XML containing access control settings (see below) 
 9046: 
 9047: Internal notes:
 9048: 
 9049:  access controls are stored in file_permissions.db as key=value pairs.
 9050:     key -> path to file/file_name\0uniqueID:scope_end_start
 9051:         where scope -> public,guest,course,group,domains or users.
 9052:               end -> UNIX time for end of access (0 -> no end date)
 9053:               start -> UNIX time for start of access
 9054: 
 9055:     value -> XML description of access control
 9056:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9057:             <start></start>
 9058:             <end></end>
 9059: 
 9060:             <password></password>  for scope type = guest
 9061: 
 9062:             <domain></domain>     for scope type = course or group
 9063:             <number></number>
 9064:             <roles id="">
 9065:              <role></role>
 9066:              <access></access>
 9067:              <section></section>
 9068:              <group></group>
 9069:             </roles>
 9070: 
 9071:             <dom></dom>         for scope type = domains
 9072: 
 9073:             <users>             for scope type = users
 9074:              <user>
 9075:               <uname></uname>
 9076:               <udom></udom>
 9077:              </user>
 9078:             </users>
 9079:            </scope> 
 9080:               
 9081:  Access data is also aggregated for each file in an additional key=value pair:
 9082:  key -> path to file/file_name\0accesscontrol 
 9083:  value -> reference to hash
 9084:           hash contains key = value pairs
 9085:           where key = uniqueID:scope_end_start
 9086:                 value = UNIX time record was last updated
 9087: 
 9088:           Used to improve speed of look-ups of access controls for each file.  
 9089:  
 9090:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9091: 
 9092: modify_access_controls():
 9093: 
 9094: Modifies access controls for a portfolio file
 9095: Args
 9096: 1. file name
 9097: 2. reference to hash of required changes,
 9098: 3. domain
 9099: 4. username
 9100:   where domain,username are the domain of the portfolio owner 
 9101:   (either a user or a course) 
 9102: 
 9103: Returns:
 9104: 1. result of additions or updates ('ok' or 'error', with error message). 
 9105: 2. result of deletions ('ok' or 'error', with error message).
 9106: 3. reference to hash of any new or updated access controls.
 9107: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9108:    key = integer (inbound ID)
 9109:    value = uniqueID  
 9110: 
 9111: =back
 9112: 
 9113: =head2 HTTP Helper Routines
 9114: 
 9115: =over 4
 9116: 
 9117: =item *
 9118: 
 9119: escape() : unpack non-word characters into CGI-compatible hex codes
 9120: 
 9121: =item *
 9122: 
 9123: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9124: 
 9125: =back
 9126: 
 9127: =head1 PRIVATE SUBROUTINES
 9128: 
 9129: =head2 Underlying communication routines (Shouldn't call)
 9130: 
 9131: =over 4
 9132: 
 9133: =item *
 9134: 
 9135: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9136: 
 9137: =item *
 9138: 
 9139: reply() : uses subreply to send a message to remote machine, logs all failures
 9140: 
 9141: =item *
 9142: 
 9143: critical() : passes a critical message to another server; if cannot
 9144: get through then place message in connection buffer directory and
 9145: returns con_delayed, if incapable of saving message, returns
 9146: con_failed
 9147: 
 9148: =item *
 9149: 
 9150: reconlonc() : tries to reconnect lonc client processes.
 9151: 
 9152: =back
 9153: 
 9154: =head2 Resource Access Logging
 9155: 
 9156: =over 4
 9157: 
 9158: =item *
 9159: 
 9160: flushcourselogs() : flush (save) buffer logs and access logs
 9161: 
 9162: =item *
 9163: 
 9164: courselog($what) : save message for course in hash
 9165: 
 9166: =item *
 9167: 
 9168: courseacclog($what) : save message for course using &courselog().  Perform
 9169: special processing for specific resource types (problems, exams, quizzes, etc).
 9170: 
 9171: =item *
 9172: 
 9173: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9174: as a PerlChildExitHandler
 9175: 
 9176: =back
 9177: 
 9178: =head2 Other
 9179: 
 9180: =over 4
 9181: 
 9182: =item *
 9183: 
 9184: symblist($mapname,%newhash) : update symbolic storage links
 9185: 
 9186: =back
 9187: 
 9188: =cut

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