File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.843: download - view: text, annotated - select for diffs
Sat Mar 3 02:10:59 2007 UTC (17 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- need to make it an exact match

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.843 2007/03/03 02:10:59 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: use Math::Random;
   56: use LONCAPA qw(:DEFAULT :match);
   57: use LONCAPA::Configuration;
   58: 
   59: my $readit;
   60: my $max_connection_retries = 10;     # Or some such value.
   61: 
   62: require Exporter;
   63: 
   64: our @ISA = qw (Exporter);
   65: our @EXPORT = qw(%env);
   66: 
   67: =pod
   68: 
   69: =head1 Package Variables
   70: 
   71: These are largely undocumented, so if you decipher one please note it here.
   72: 
   73: =over 4
   74: 
   75: =item $processmarker
   76: 
   77: Contains the time this process was started and this servers host id.
   78: 
   79: =item $dumpcount
   80: 
   81: Counts the number of times a message log flush has been attempted (regardless
   82: of success) by this process.  Used as part of the filename when messages are
   83: delayed.
   84: 
   85: =back
   86: 
   87: =cut
   88: 
   89: 
   90: # --------------------------------------------------------------------- Logging
   91: {
   92:     my $logid;
   93:     sub instructor_log {
   94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   95: 	$logid++;
   96: 	my $id=time().'00000'.$$.'00000'.$logid;
   97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   98: 				    { $id => {
   99: 					'exe_uname' => $env{'user.name'},
  100: 					'exe_udom'  => $env{'user.domain'},
  101: 					'exe_time'  => time(),
  102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  103: 					'delflag'   => $delflag,
  104: 					'logentry'  => $storehash,
  105: 					'uname'     => $uname,
  106: 					'udom'      => $udom,
  107: 				    }
  108: 				  },
  109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  111: 				    );
  112:     }
  113: }
  114: 
  115: sub logtouch {
  116:     my $execdir=$perlvar{'lonDaemons'};
  117:     unless (-e "$execdir/logs/lonnet.log") {	
  118: 	open(my $fh,">>$execdir/logs/lonnet.log");
  119: 	close $fh;
  120:     }
  121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  123: }
  124: 
  125: sub logthis {
  126:     my $message=shift;
  127:     my $execdir=$perlvar{'lonDaemons'};
  128:     my $now=time;
  129:     my $local=localtime($now);
  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  131: 	print $fh "$local ($$): $message\n";
  132: 	close($fh);
  133:     }
  134:     return 1;
  135: }
  136: 
  137: sub logperm {
  138:     my $message=shift;
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     my $now=time;
  141:     my $local=localtime($now);
  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  143: 	print $fh "$now:$message:$local\n";
  144: 	close($fh);
  145:     }
  146:     return 1;
  147: }
  148: 
  149: # -------------------------------------------------- Non-critical communication
  150: sub subreply {
  151:     my ($cmd,$server)=@_;
  152:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  153:     #
  154:     #  With loncnew process trimming, there's a timing hole between lonc server
  155:     #  process exit and the master server picking up the listen on the AF_UNIX
  156:     #  socket.  In that time interval, a lock file will exist:
  157: 
  158:     my $lockfile=$peerfile.".lock";
  159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  160: 	sleep(1);
  161:     }
  162:     # At this point, either a loncnew parent is listening or an old lonc
  163:     # or loncnew child is listening so we can connect or everything's dead.
  164:     #
  165:     #   We'll give the connection a few tries before abandoning it.  If
  166:     #   connection is not possible, we'll con_lost back to the client.
  167:     #   
  168:     my $client;
  169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  171: 				      Type    => SOCK_STREAM,
  172: 				      Timeout => 10);
  173: 	if($client) {
  174: 	    last;		# Connected!
  175: 	}
  176: 	sleep(1);		# Try again later if failed connection.
  177:     }
  178:     my $answer;
  179:     if ($client) {
  180: 	print $client "sethost:$server:$cmd\n";
  181: 	$answer=<$client>;
  182: 	if (!$answer) { $answer="con_lost"; }
  183: 	chomp($answer);
  184:     } else {
  185: 	$answer = 'con_lost';	# Failed connection.
  186:     }
  187:     return $answer;
  188: }
  189: 
  190: sub reply {
  191:     my ($cmd,$server)=@_;
  192:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  193:     my $answer=subreply($cmd,$server);
  194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  195:        &logthis("<font color=\"blue\">WARNING:".
  196:                 " $cmd to $server returned $answer</font>");
  197:     }
  198:     return $answer;
  199: }
  200: 
  201: # ----------------------------------------------------------- Send USR1 to lonc
  202: 
  203: sub reconlonc {
  204:     &logthis("Trying to reconnect lonc");
  205:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  206:     if (open(my $fh,"<$loncfile")) {
  207: 	my $loncpid=<$fh>;
  208:         chomp($loncpid);
  209:         if (kill 0 => $loncpid) {
  210: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  211:             kill USR1 => $loncpid;
  212:             sleep 1;
  213:          } else {
  214: 	    &logthis(
  215:                "<font color=\"blue\">WARNING:".
  216:                " lonc at pid $loncpid not responding, giving up</font>");
  217:         }
  218:     } else {
  219: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  220:     }
  221: }
  222: 
  223: # ------------------------------------------------------ Critical communication
  224: 
  225: sub critical {
  226:     my ($cmd,$server)=@_;
  227:     unless (&hostname($server)) {
  228:         &logthis("<font color=\"blue\">WARNING:".
  229:                " Critical message to unknown server ($server)</font>");
  230:         return 'no_such_host';
  231:     }
  232:     my $answer=reply($cmd,$server);
  233:     if ($answer eq 'con_lost') {
  234: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  235: 	my $answer=reply($cmd,$server);
  236:         if ($answer eq 'con_lost') {
  237:             my $now=time;
  238:             my $middlename=$cmd;
  239:             $middlename=substr($middlename,0,16);
  240:             $middlename=~s/\W//g;
  241:             my $dfilename=
  242:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  243:             $dumpcount++;
  244:             {
  245: 		my $dfh;
  246: 		if (open($dfh,">$dfilename")) {
  247: 		    print $dfh "$cmd\n"; 
  248: 		    close($dfh);
  249: 		}
  250:             }
  251:             sleep 2;
  252:             my $wcmd='';
  253:             {
  254: 		my $dfh;
  255: 		if (open($dfh,"<$dfilename")) {
  256: 		    $wcmd=<$dfh>; 
  257: 		    close($dfh);
  258: 		}
  259:             }
  260:             chomp($wcmd);
  261:             if ($wcmd eq $cmd) {
  262: 		&logthis("<font color=\"blue\">WARNING: ".
  263:                          "Connection buffer $dfilename: $cmd</font>");
  264:                 &logperm("D:$server:$cmd");
  265: 	        return 'con_delayed';
  266:             } else {
  267:                 &logthis("<font color=\"red\">CRITICAL:"
  268:                         ." Critical connection failed: $server $cmd</font>");
  269:                 &logperm("F:$server:$cmd");
  270:                 return 'con_failed';
  271:             }
  272:         }
  273:     }
  274:     return $answer;
  275: }
  276: 
  277: # ------------------------------------------- check if return value is an error
  278: 
  279: sub error {
  280:     my ($result) = @_;
  281:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  282: 	if ($2 == 2) { return undef; }
  283: 	return $1;
  284:     }
  285:     return undef;
  286: }
  287: 
  288: sub convert_and_load_session_env {
  289:     my ($lonidsdir,$handle)=@_;
  290:     my @profile;
  291:     {
  292: 	open(my $idf,"$lonidsdir/$handle.id");
  293: 	flock($idf,LOCK_SH);
  294: 	@profile=<$idf>;
  295: 	close($idf);
  296:     }
  297:     my %temp_env;
  298:     foreach my $line (@profile) {
  299: 	if ($line !~ m/=/) {
  300: 	    return 0;
  301: 	}
  302: 	chomp($line);
  303: 	my ($envname,$envvalue)=split(/=/,$line,2);
  304: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  305:     }
  306:     unlink("$lonidsdir/$handle.id");
  307:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  308: 	    0640)) {
  309: 	%disk_env = %temp_env;
  310: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  311: 	untie(%disk_env);
  312:     }
  313:     return 1;
  314: }
  315: 
  316: # ------------------------------------------- Transfer profile into environment
  317: my $env_loaded;
  318: sub transfer_profile_to_env {
  319:     my ($lonidsdir,$handle,$force_transfer) = @_;
  320:     if (!$force_transfer && $env_loaded) { return; } 
  321: 
  322:     if (!defined($lonidsdir)) {
  323: 	$lonidsdir = $perlvar{'lonIDsDir'};
  324:     }
  325:     if (!defined($handle)) {
  326:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  327:     }
  328: 
  329:     my $convert;
  330:     {
  331:     	open(my $idf,"$lonidsdir/$handle.id");
  332: 	flock($idf,LOCK_SH);
  333: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  334: 		&GDBM_READER(),0640)) {
  335: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  336: 	    untie(%disk_env);
  337: 	} else {
  338: 	    $convert = 1;
  339: 	}
  340:     }
  341:     if ($convert) {
  342: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  343: 	    &logthis("Failed to load session, or convert session.");
  344: 	}
  345:     }
  346: 
  347:     my %remove;
  348:     while ( my $envname = each(%env) ) {
  349:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  350:             if ($time < time-300) {
  351:                 $remove{$key}++;
  352:             }
  353:         }
  354:     }
  355: 
  356:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  357:     $env_loaded=1;
  358:     foreach my $expired_key (keys(%remove)) {
  359:         &delenv($expired_key);
  360:     }
  361: }
  362: 
  363: sub timed_flock {
  364:     my ($file,$lock_type) = @_;
  365:     my $failed=0;
  366:     eval {
  367: 	local $SIG{__DIE__}='DEFAULT';
  368: 	local $SIG{ALRM}=sub {
  369: 	    $failed=1;
  370: 	    die("failed lock");
  371: 	};
  372: 	alarm(13);
  373: 	flock($file,$lock_type);
  374: 	alarm(0);
  375:     };
  376:     if ($failed) {
  377: 	return undef;
  378:     } else {
  379: 	return 1;
  380:     }
  381: }
  382: 
  383: # ---------------------------------------------------------- Append Environment
  384: 
  385: sub appenv {
  386:     my %newenv=@_;
  387:     foreach my $key (keys(%newenv)) {
  388: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  389:             &logthis("<font color=\"blue\">WARNING: ".
  390:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  391:                 .'</font>');
  392: 	    delete($newenv{$key});
  393:         } else {
  394:             $env{$key}=$newenv{$key};
  395:         }
  396:     }
  397:     open(my $env_file,$env{'user.environment'});
  398:     if (&timed_flock($env_file,LOCK_EX)
  399: 	&&
  400: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  401: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  402: 	while (my ($key,$value) = each(%newenv)) {
  403: 	    $disk_env{$key} = $value;
  404: 	}
  405: 	untie(%disk_env);
  406:     }
  407:     return 'ok';
  408: }
  409: # ----------------------------------------------------- Delete from Environment
  410: 
  411: sub delenv {
  412:     my $delthis=shift;
  413:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  414:         &logthis("<font color=\"blue\">WARNING: ".
  415:                 "Attempt to delete from environment ".$delthis);
  416:         return 'error';
  417:     }
  418:     open(my $env_file,$env{'user.environment'});
  419:     if (&timed_flock($env_file,LOCK_EX)
  420: 	&&
  421: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  422: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  423: 	foreach my $key (keys(%disk_env)) {
  424: 	    if ($key=~/^$delthis/) { 
  425:                 delete($env{$key});
  426:                 delete($disk_env{$key});
  427:             }
  428: 	}
  429: 	untie(%disk_env);
  430:     }
  431:     return 'ok';
  432: }
  433: 
  434: sub get_env_multiple {
  435:     my ($name) = @_;
  436:     my @values;
  437:     if (defined($env{$name})) {
  438:         # exists is it an array
  439:         if (ref($env{$name})) {
  440:             @values=@{ $env{$name} };
  441:         } else {
  442:             $values[0]=$env{$name};
  443:         }
  444:     }
  445:     return(@values);
  446: }
  447: 
  448: # ------------------------------------------ Find out current server userload
  449: # there is a copy in lond
  450: sub userload {
  451:     my $numusers=0;
  452:     {
  453: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  454: 	my $filename;
  455: 	my $curtime=time;
  456: 	while ($filename=readdir(LONIDS)) {
  457: 	    if ($filename eq '.' || $filename eq '..') {next;}
  458: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  459: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  460: 	}
  461: 	closedir(LONIDS);
  462:     }
  463:     my $userloadpercent=0;
  464:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  465:     if ($maxuserload) {
  466: 	$userloadpercent=100*$numusers/$maxuserload;
  467:     }
  468:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  469:     return $userloadpercent;
  470: }
  471: 
  472: # ------------------------------------------ Fight off request when overloaded
  473: 
  474: sub overloaderror {
  475:     my ($r,$checkserver)=@_;
  476:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  477:     my $loadavg;
  478:     if ($checkserver eq $perlvar{'lonHostID'}) {
  479:        open(my $loadfile,'/proc/loadavg');
  480:        $loadavg=<$loadfile>;
  481:        $loadavg =~ s/\s.*//g;
  482:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  483:        close($loadfile);
  484:     } else {
  485:        $loadavg=&reply('load',$checkserver);
  486:     }
  487:     my $overload=$loadavg-100;
  488:     if ($overload>0) {
  489: 	$r->err_headers_out->{'Retry-After'}=$overload;
  490:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  491:         return 413;
  492:     }    
  493:     return '';
  494: }
  495: 
  496: # ------------------------------ Find server with least workload from spare.tab
  497: 
  498: sub spareserver {
  499:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  500:     my $spare_server;
  501:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  502:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  503:                                                      :  $userloadpercent;
  504:     
  505:     foreach my $try_server (@{ $spareid{'primary'} }) {
  506: 	($spare_server, $lowest_load) =
  507: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  508:     }
  509: 
  510:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  511: 
  512:     if (!$found_server) {
  513: 	foreach my $try_server (@{ $spareid{'default'} }) {
  514: 	    ($spare_server, $lowest_load) =
  515: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  516: 	}
  517:     }
  518: 
  519:     if (!$want_server_name) {
  520: 	$spare_server="http://".&hostname($spare_server);
  521:     }
  522:     return $spare_server;
  523: }
  524: 
  525: sub compare_server_load {
  526:     my ($try_server, $spare_server, $lowest_load) = @_;
  527: 
  528:     my $loadans     = &reply('load',    $try_server);
  529:     my $userloadans = &reply('userload',$try_server);
  530: 
  531:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  532: 	next; #didn't get a number from the server
  533:     }
  534: 
  535:     my $load;
  536:     if ($loadans =~ /\d/) {
  537: 	if ($userloadans =~ /\d/) {
  538: 	    #both are numbers, pick the bigger one
  539: 	    $load = ($loadans > $userloadans) ? $loadans 
  540: 		                              : $userloadans;
  541: 	} else {
  542: 	    $load = $loadans;
  543: 	}
  544:     } else {
  545: 	$load = $userloadans;
  546:     }
  547: 
  548:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  549: 	$spare_server = $try_server;
  550: 	$lowest_load  = $load;
  551:     }
  552:     return ($spare_server,$lowest_load);
  553: }
  554: # --------------------------------------------- Try to change a user's password
  555: 
  556: sub changepass {
  557:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  558:     $currentpass = &escape($currentpass);
  559:     $newpass     = &escape($newpass);
  560:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  561: 		       $server);
  562:     if (! $answer) {
  563: 	&logthis("No reply on password change request to $server ".
  564: 		 "by $uname in domain $udom.");
  565:     } elsif ($answer =~ "^ok") {
  566:         &logthis("$uname in $udom successfully changed their password ".
  567: 		 "on $server.");
  568:     } elsif ($answer =~ "^pwchange_failure") {
  569: 	&logthis("$uname in $udom was unable to change their password ".
  570: 		 "on $server.  The action was blocked by either lcpasswd ".
  571: 		 "or pwchange");
  572:     } elsif ($answer =~ "^non_authorized") {
  573:         &logthis("$uname in $udom did not get their password correct when ".
  574: 		 "attempting to change it on $server.");
  575:     } elsif ($answer =~ "^auth_mode_error") {
  576:         &logthis("$uname in $udom attempted to change their password despite ".
  577: 		 "not being locally or internally authenticated on $server.");
  578:     } elsif ($answer =~ "^unknown_user") {
  579:         &logthis("$uname in $udom attempted to change their password ".
  580: 		 "on $server but were unable to because $server is not ".
  581: 		 "their home server.");
  582:     } elsif ($answer =~ "^refused") {
  583: 	&logthis("$server refused to change $uname in $udom password because ".
  584: 		 "it was sent an unencrypted request to change the password.");
  585:     }
  586:     return $answer;
  587: }
  588: 
  589: # ----------------------- Try to determine user's current authentication scheme
  590: 
  591: sub queryauthenticate {
  592:     my ($uname,$udom)=@_;
  593:     my $uhome=&homeserver($uname,$udom);
  594:     if (!$uhome) {
  595: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  596: 	return 'no_host';
  597:     }
  598:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  599:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  600: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  601:     }
  602:     return $answer;
  603: }
  604: 
  605: # --------- Try to authenticate user from domain's lib servers (first this one)
  606: 
  607: sub authenticate {
  608:     my ($uname,$upass,$udom)=@_;
  609:     $upass=&escape($upass);
  610:     $uname= &LONCAPA::clean_username($uname);
  611:     my $uhome=&homeserver($uname,$udom,1);
  612:     if ((!$uhome) || ($uhome eq 'no_host')) {
  613: # Maybe the machine was offline and only re-appeared again recently?
  614:         &reconlonc();
  615: # One more
  616: 	my $uhome=&homeserver($uname,$udom,1);
  617: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  618: 	    &logthis("User $uname at $udom is unknown in authenticate");
  619: 	}
  620: 	return 'no_host';
  621:     }
  622:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  623:     if ($answer eq 'authorized') {
  624: 	&logthis("User $uname at $udom authorized by $uhome"); 
  625: 	return $uhome; 
  626:     }
  627:     if ($answer eq 'non_authorized') {
  628: 	&logthis("User $uname at $udom rejected by $uhome");
  629: 	return 'no_host'; 
  630:     }
  631:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  632:     return 'no_host';
  633: }
  634: 
  635: # ---------------------- Find the homebase for a user from domain's lib servers
  636: 
  637: my %homecache;
  638: sub homeserver {
  639:     my ($uname,$udom,$ignoreBadCache)=@_;
  640:     my $index="$uname:$udom";
  641: 
  642:     if (exists($homecache{$index})) { return $homecache{$index}; }
  643: 
  644:     my %servers = &get_servers($udom,'library');
  645:     foreach my $tryserver (keys(%servers)) {
  646:         next if ($ignoreBadCache ne 'true' && 
  647: 		 exists($badServerCache{$tryserver}));
  648: 
  649: 	my $answer=reply("home:$udom:$uname",$tryserver);
  650: 	if ($answer eq 'found') {
  651: 	    delete($badServerCache{$tryserver}); 
  652: 	    return $homecache{$index}=$tryserver;
  653: 	} elsif ($answer eq 'no_host') {
  654: 	    $badServerCache{$tryserver}=1;
  655: 	}
  656:     }    
  657:     return 'no_host';
  658: }
  659: 
  660: # ------------------------------------- Find the usernames behind a list of IDs
  661: 
  662: sub idget {
  663:     my ($udom,@ids)=@_;
  664:     my %returnhash=();
  665:     
  666:     my %servers = &get_servers($udom,'library');
  667:     foreach my $tryserver (keys(%servers)) {
  668: 	my $idlist=join('&',@ids);
  669: 	$idlist=~tr/A-Z/a-z/; 
  670: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  671: 	my @answer=();
  672: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  673: 	    @answer=split(/\&/,$reply);
  674: 	}                    ;
  675: 	my $i;
  676: 	for ($i=0;$i<=$#ids;$i++) {
  677: 	    if ($answer[$i]) {
  678: 		$returnhash{$ids[$i]}=$answer[$i];
  679: 	    } 
  680: 	}
  681:     } 
  682:     return %returnhash;
  683: }
  684: 
  685: # ------------------------------------- Find the IDs behind a list of usernames
  686: 
  687: sub idrget {
  688:     my ($udom,@unames)=@_;
  689:     my %returnhash=();
  690:     foreach my $uname (@unames) {
  691:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  692:     }
  693:     return %returnhash;
  694: }
  695: 
  696: # ------------------------------- Store away a list of names and associated IDs
  697: 
  698: sub idput {
  699:     my ($udom,%ids)=@_;
  700:     my %servers=();
  701:     foreach my $uname (keys(%ids)) {
  702: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  703:         my $uhom=&homeserver($uname,$udom);
  704:         if ($uhom ne 'no_host') {
  705:             my $id=&escape($ids{$uname});
  706:             $id=~tr/A-Z/a-z/;
  707:             my $esc_unam=&escape($uname);
  708: 	    if ($servers{$uhom}) {
  709: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  710:             } else {
  711:                 $servers{$uhom}=$id.'='.$esc_unam;
  712:             }
  713:         }
  714:     }
  715:     foreach my $server (keys(%servers)) {
  716:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  717:     }
  718: }
  719: 
  720: # ------------------------------------------- get items from domain db files   
  721: 
  722: sub get_dom {
  723:     my ($namespace,$storearr,$udom)=@_;
  724:     my $items='';
  725:     foreach my $item (@$storearr) {
  726:         $items.=&escape($item).'&';
  727:     }
  728:     $items=~s/\&$//;
  729:     if (!$udom) { $udom=$env{'user.domain'}; }
  730:     if (exists($domain_primary{$udom})) {
  731:         my $uhome=$domain_primary{$udom};
  732:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  733:         my @pairs=split(/\&/,$rep);
  734:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  735:             return @pairs;
  736:         }
  737:         my %returnhash=();
  738:         my $i=0;
  739:         foreach my $item (@$storearr) {
  740:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  741:             $i++;
  742:         }
  743:         return %returnhash;
  744:     } else {
  745:         &logthis("get_dom failed - no primary domain server for $udom");
  746:     }
  747: }
  748: 
  749: # -------------------------------------------- put items in domain db files 
  750: 
  751: sub put_dom {
  752:     my ($namespace,$storehash,$udom)=@_;
  753:     if (!$udom) { $udom=$env{'user.domain'}; }
  754:     if (exists($domain_primary{$udom})) {
  755:         my $uhome=$domain_primary{$udom};
  756:         my $items='';
  757:         foreach my $item (keys(%$storehash)) {
  758:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  759:         }
  760:         $items=~s/\&$//;
  761:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  762:     } else {
  763:         &logthis("put_dom failed - no primary domain server for $udom");
  764:     }
  765: }
  766: 
  767: sub retrieve_inst_usertypes {
  768:     my ($udom) = @_;
  769:     my (%returnhash,@order);
  770:     if (exists($domain_primary{$udom})) {
  771:         my $uhome=$domain_primary{$udom};
  772:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  773:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  774:         my @pairs=split(/\&/,$hashitems);
  775:         foreach my $item (@pairs) {
  776:             my ($key,$value)=split(/=/,$item,2);
  777:             $key = &unescape($key);
  778:             next if ($key =~ /^error: 2 /);
  779:             $returnhash{$key}=&thaw_unescape($value);
  780:         }
  781:         my @esc_order = split(/\&/,$orderitems);
  782:         foreach my $item (@esc_order) {
  783:             push(@order,&unescape($item));
  784:         }
  785:     } else {
  786:         &logthis("get_dom failed - no primary domain server for $udom");
  787:     }
  788:     return (\%returnhash,\@order);
  789: }
  790: 
  791: # --------------------------------------------------- Assign a key to a student
  792: 
  793: sub assign_access_key {
  794: #
  795: # a valid key looks like uname:udom#comments
  796: # comments are being appended
  797: #
  798:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  799:     $kdom=
  800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  801:     $knum=
  802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  803:     $cdom=
  804:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  805:     $cnum=
  806:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  807:     $udom=$env{'user.name'} unless (defined($udom));
  808:     $uname=$env{'user.domain'} unless (defined($uname));
  809:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  810:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  811:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  812:                                                   # assigned to this person
  813:                                                   # - this should not happen,
  814:                                                   # unless something went wrong
  815:                                                   # the first time around
  816: # ready to assign
  817:         $logentry=$1.'; '.$logentry;
  818:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  819:                                                  $kdom,$knum) eq 'ok') {
  820: # key now belongs to user
  821: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  822:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  823:                 &appenv('environment.'.$envkey => $ckey);
  824:                 return 'ok';
  825:             } else {
  826:                 return 
  827:   'error: Count not permanently assign key, will need to be re-entered later.';
  828: 	    }
  829:         } else {
  830:             return 'error: Could not assign key, try again later.';
  831:         }
  832:     } elsif (!$existing{$ckey}) {
  833: # the key does not exist
  834: 	return 'error: The key does not exist';
  835:     } else {
  836: # the key is somebody else's
  837: 	return 'error: The key is already in use';
  838:     }
  839: }
  840: 
  841: # ------------------------------------------ put an additional comment on a key
  842: 
  843: sub comment_access_key {
  844: #
  845: # a valid key looks like uname:udom#comments
  846: # comments are being appended
  847: #
  848:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  849:     $cdom=
  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  851:     $cnum=
  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  853:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  854:     if ($existing{$ckey}) {
  855:         $existing{$ckey}.='; '.$logentry;
  856: # ready to assign
  857:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  858:                                                  $cdom,$cnum) eq 'ok') {
  859: 	    return 'ok';
  860:         } else {
  861: 	    return 'error: Count not store comment.';
  862:         }
  863:     } else {
  864: # the key does not exist
  865: 	return 'error: The key does not exist';
  866:     }
  867: }
  868: 
  869: # ------------------------------------------------------ Generate a set of keys
  870: 
  871: sub generate_access_keys {
  872:     my ($number,$cdom,$cnum,$logentry)=@_;
  873:     $cdom=
  874:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  875:     $cnum=
  876:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  877:     unless (&allowed('mky',$cdom)) { return 0; }
  878:     unless (($cdom) && ($cnum)) { return 0; }
  879:     if ($number>10000) { return 0; }
  880:     sleep(2); # make sure don't get same seed twice
  881:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  882:     my $total=0;
  883:     for (my $i=1;$i<=$number;$i++) {
  884:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  885:                   sprintf("%lx",int(100000*rand)).'-'.
  886:                   sprintf("%lx",int(100000*rand));
  887:        $newkey=~s/1/g/g; # folks mix up 1 and l
  888:        $newkey=~s/0/h/g; # and also 0 and O
  889:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  890:        if ($existing{$newkey}) {
  891:            $i--;
  892:        } else {
  893: 	  if (&put('accesskeys',
  894:               { $newkey => '# generated '.localtime().
  895:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  896:                            '; '.$logentry },
  897: 		   $cdom,$cnum) eq 'ok') {
  898:               $total++;
  899: 	  }
  900:        }
  901:     }
  902:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  903:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  904:     return $total;
  905: }
  906: 
  907: # ------------------------------------------------------- Validate an accesskey
  908: 
  909: sub validate_access_key {
  910:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  911:     $cdom=
  912:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  913:     $cnum=
  914:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  915:     $udom=$env{'user.domain'} unless (defined($udom));
  916:     $uname=$env{'user.name'} unless (defined($uname));
  917:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  918:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  919: }
  920: 
  921: # ------------------------------------- Find the section of student in a course
  922: sub devalidate_getsection_cache {
  923:     my ($udom,$unam,$courseid)=@_;
  924:     my $hashid="$udom:$unam:$courseid";
  925:     &devalidate_cache_new('getsection',$hashid);
  926: }
  927: 
  928: sub courseid_to_courseurl {
  929:     my ($courseid) = @_;
  930:     #already url style courseid
  931:     return $courseid if ($courseid =~ m{^/});
  932: 
  933:     if (exists($env{'course.'.$courseid.'.num'})) {
  934: 	my $cnum = $env{'course.'.$courseid.'.num'};
  935: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  936: 	return "/$cdom/$cnum";
  937:     }
  938: 
  939:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  940:     if (exists($courseinfo{'num'})) {
  941: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  942:     }
  943: 
  944:     return undef;
  945: }
  946: 
  947: sub getsection {
  948:     my ($udom,$unam,$courseid)=@_;
  949:     my $cachetime=1800;
  950: 
  951:     my $hashid="$udom:$unam:$courseid";
  952:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  953:     if (defined($cached)) { return $result; }
  954: 
  955:     my %Pending; 
  956:     my %Expired;
  957:     #
  958:     # Each role can either have not started yet (pending), be active, 
  959:     #    or have expired.
  960:     #
  961:     # If there is an active role, we are done.
  962:     #
  963:     # If there is more than one role which has not started yet, 
  964:     #     choose the one which will start sooner
  965:     # If there is one role which has not started yet, return it.
  966:     #
  967:     # If there is more than one expired role, choose the one which ended last.
  968:     # If there is a role which has expired, return it.
  969:     #
  970:     $courseid = &courseid_to_courseurl($courseid);
  971:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
  972:     foreach my $key (keys(%roleshash)) {
  973:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  974:         my $section=$1;
  975:         if ($key eq $courseid.'_st') { $section=''; }
  976:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
  977:         my $now=time;
  978:         if (defined($end) && $end && ($now > $end)) {
  979:             $Expired{$end}=$section;
  980:             next;
  981:         }
  982:         if (defined($start) && $start && ($now < $start)) {
  983:             $Pending{$start}=$section;
  984:             next;
  985:         }
  986:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  987:     }
  988:     #
  989:     # Presumedly there will be few matching roles from the above
  990:     # loop and the sorting time will be negligible.
  991:     if (scalar(keys(%Pending))) {
  992:         my ($time) = sort {$a <=> $b} keys(%Pending);
  993:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  994:     } 
  995:     if (scalar(keys(%Expired))) {
  996:         my @sorted = sort {$a <=> $b} keys(%Expired);
  997:         my $time = pop(@sorted);
  998:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  999:     }
 1000:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1001: }
 1002: 
 1003: sub save_cache {
 1004:     &purge_remembered();
 1005:     #&Apache::loncommon::validate_page();
 1006:     undef(%env);
 1007:     undef($env_loaded);
 1008: }
 1009: 
 1010: my $to_remember=-1;
 1011: my %remembered;
 1012: my %accessed;
 1013: my $kicks=0;
 1014: my $hits=0;
 1015: sub devalidate_cache_new {
 1016:     my ($name,$id,$debug) = @_;
 1017:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1018:     $id=&escape($name.':'.$id);
 1019:     $memcache->delete($id);
 1020:     delete($remembered{$id});
 1021:     delete($accessed{$id});
 1022: }
 1023: 
 1024: sub is_cached_new {
 1025:     my ($name,$id,$debug) = @_;
 1026:     $id=&escape($name.':'.$id);
 1027:     if (exists($remembered{$id})) {
 1028: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1029: 	$accessed{$id}=[&gettimeofday()];
 1030: 	$hits++;
 1031: 	return ($remembered{$id},1);
 1032:     }
 1033:     my $value = $memcache->get($id);
 1034:     if (!(defined($value))) {
 1035: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1036: 	return (undef,undef);
 1037:     }
 1038:     if ($value eq '__undef__') {
 1039: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1040: 	$value=undef;
 1041:     }
 1042:     &make_room($id,$value,$debug);
 1043:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1044:     return ($value,1);
 1045: }
 1046: 
 1047: sub do_cache_new {
 1048:     my ($name,$id,$value,$time,$debug) = @_;
 1049:     $id=&escape($name.':'.$id);
 1050:     my $setvalue=$value;
 1051:     if (!defined($setvalue)) {
 1052: 	$setvalue='__undef__';
 1053:     }
 1054:     if (!defined($time) ) {
 1055: 	$time=600;
 1056:     }
 1057:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1058:     $memcache->set($id,$setvalue,$time);
 1059:     # need to make a copy of $value
 1060:     #&make_room($id,$value,$debug);
 1061:     return $value;
 1062: }
 1063: 
 1064: sub make_room {
 1065:     my ($id,$value,$debug)=@_;
 1066:     $remembered{$id}=$value;
 1067:     if ($to_remember<0) { return; }
 1068:     $accessed{$id}=[&gettimeofday()];
 1069:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1070:     my $to_kick;
 1071:     my $max_time=0;
 1072:     foreach my $other (keys(%accessed)) {
 1073: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1074: 	    $to_kick=$other;
 1075: 	    $max_time=&tv_interval($accessed{$other});
 1076: 	}
 1077:     }
 1078:     delete($remembered{$to_kick});
 1079:     delete($accessed{$to_kick});
 1080:     $kicks++;
 1081:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1082:     return;
 1083: }
 1084: 
 1085: sub purge_remembered {
 1086:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1087:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1088:     undef(%remembered);
 1089:     undef(%accessed);
 1090: }
 1091: # ------------------------------------- Read an entry from a user's environment
 1092: 
 1093: sub userenvironment {
 1094:     my ($udom,$unam,@what)=@_;
 1095:     my %returnhash=();
 1096:     my @answer=split(/\&/,
 1097:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1098:                       &homeserver($unam,$udom)));
 1099:     my $i;
 1100:     for ($i=0;$i<=$#what;$i++) {
 1101: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1102:     }
 1103:     return %returnhash;
 1104: }
 1105: 
 1106: # ---------------------------------------------------------- Get a studentphoto
 1107: sub studentphoto {
 1108:     my ($udom,$unam,$ext) = @_;
 1109:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1110:     if (defined($env{'request.course.id'})) {
 1111:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1112:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1113:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1114:             } else {
 1115:                 my ($result,$perm_reqd)=
 1116: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1117:                 if ($result eq 'ok') {
 1118:                     if (!($perm_reqd eq 'yes')) {
 1119:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1120:                     }
 1121:                 }
 1122:             }
 1123:         }
 1124:     } else {
 1125:         my ($result,$perm_reqd) = 
 1126: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1127:         if ($result eq 'ok') {
 1128:             if (!($perm_reqd eq 'yes')) {
 1129:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1130:             }
 1131:         }
 1132:     }
 1133:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1134: }
 1135: 
 1136: sub retrievestudentphoto {
 1137:     my ($udom,$unam,$ext,$type) = @_;
 1138:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1139:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1140:     if ($ret eq 'ok') {
 1141:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1142:         if ($type eq 'thumbnail') {
 1143:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1144:         }
 1145:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1146:         return $tokenurl;
 1147:     } else {
 1148:         if ($type eq 'thumbnail') {
 1149:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1150:         } else { 
 1151:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1152:         }
 1153:     }
 1154: }
 1155: 
 1156: # -------------------------------------------------------------------- New chat
 1157: 
 1158: sub chatsend {
 1159:     my ($newentry,$anon,$group)=@_;
 1160:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1161:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1162:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1163:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1164: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1165: 		   &escape($newentry)).':'.$group,$chome);
 1166: }
 1167: 
 1168: # ------------------------------------------ Find current version of a resource
 1169: 
 1170: sub getversion {
 1171:     my $fname=&clutter(shift);
 1172:     unless ($fname=~/^\/res\//) { return -1; }
 1173:     return &currentversion(&filelocation('',$fname));
 1174: }
 1175: 
 1176: sub currentversion {
 1177:     my $fname=shift;
 1178:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1179:     if (defined($cached)) { return $result; }
 1180:     my $author=$fname;
 1181:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1182:     my ($udom,$uname)=split(/\//,$author);
 1183:     my $home=homeserver($uname,$udom);
 1184:     if ($home eq 'no_host') { 
 1185:         return -1; 
 1186:     }
 1187:     my $answer=reply("currentversion:$fname",$home);
 1188:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1189: 	return -1;
 1190:     }
 1191:     return &do_cache_new('resversion',$fname,$answer,600);
 1192: }
 1193: 
 1194: # ----------------------------- Subscribe to a resource, return URL if possible
 1195: 
 1196: sub subscribe {
 1197:     my $fname=shift;
 1198:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1199:     $fname=~s/[\n\r]//g;
 1200:     my $author=$fname;
 1201:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1202:     my ($udom,$uname)=split(/\//,$author);
 1203:     my $home=homeserver($uname,$udom);
 1204:     if ($home eq 'no_host') {
 1205:         return 'not_found';
 1206:     }
 1207:     my $answer=reply("sub:$fname",$home);
 1208:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1209: 	$answer.=' by '.$home;
 1210:     }
 1211:     return $answer;
 1212: }
 1213:     
 1214: # -------------------------------------------------------------- Replicate file
 1215: 
 1216: sub repcopy {
 1217:     my $filename=shift;
 1218:     $filename=~s/\/+/\//g;
 1219:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1220:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1221:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1222: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1223: 	return &repcopy_userfile($filename);
 1224:     }
 1225:     $filename=~s/[\n\r]//g;
 1226:     my $transname="$filename.in.transfer";
 1227: # FIXME: this should flock
 1228:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1229:     my $remoteurl=subscribe($filename);
 1230:     if ($remoteurl =~ /^con_lost by/) {
 1231: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1232:            return 'unavailable';
 1233:     } elsif ($remoteurl eq 'not_found') {
 1234: 	   #&logthis("Subscribe returned not_found: $filename");
 1235: 	   return 'not_found';
 1236:     } elsif ($remoteurl =~ /^rejected by/) {
 1237: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1238:            return 'forbidden';
 1239:     } elsif ($remoteurl eq 'directory') {
 1240:            return 'ok';
 1241:     } else {
 1242:         my $author=$filename;
 1243:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1244:         my ($udom,$uname)=split(/\//,$author);
 1245:         my $home=homeserver($uname,$udom);
 1246:         unless ($home eq $perlvar{'lonHostID'}) {
 1247:            my @parts=split(/\//,$filename);
 1248:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1249:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1250:                &logthis("Malconfiguration for replication: $filename");
 1251: 	       return 'bad_request';
 1252:            }
 1253:            my $count;
 1254:            for ($count=5;$count<$#parts;$count++) {
 1255:                $path.="/$parts[$count]";
 1256:                if ((-e $path)!=1) {
 1257: 		   mkdir($path,0777);
 1258:                }
 1259:            }
 1260:            my $ua=new LWP::UserAgent;
 1261:            my $request=new HTTP::Request('GET',"$remoteurl");
 1262:            my $response=$ua->request($request,$transname);
 1263:            if ($response->is_error()) {
 1264: 	       unlink($transname);
 1265:                my $message=$response->status_line;
 1266:                &logthis("<font color=\"blue\">WARNING:"
 1267:                        ." LWP get: $message: $filename</font>");
 1268:                return 'unavailable';
 1269:            } else {
 1270: 	       if ($remoteurl!~/\.meta$/) {
 1271:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1272:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1273:                   if ($mresponse->is_error()) {
 1274: 		      unlink($filename.'.meta');
 1275:                       &logthis(
 1276:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1277:                   }
 1278: 	       }
 1279:                rename($transname,$filename);
 1280:                return 'ok';
 1281:            }
 1282:        }
 1283:     }
 1284: }
 1285: 
 1286: # ------------------------------------------------ Get server side include body
 1287: sub ssi_body {
 1288:     my ($filelink,%form)=@_;
 1289:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1290:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1291:     }
 1292:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1293:                                      &ssi($filelink,%form));
 1294:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1295:     $output=~s/^.*?\<body[^\>]*\>//si;
 1296:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1297:     return $output;
 1298: }
 1299: 
 1300: # --------------------------------------------------------- Server Side Include
 1301: 
 1302: sub absolute_url {
 1303:     my ($host_name) = @_;
 1304:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1305:     if ($host_name eq '') {
 1306: 	$host_name = $ENV{'SERVER_NAME'};
 1307:     }
 1308:     return $protocol.$host_name;
 1309: }
 1310: 
 1311: sub ssi {
 1312: 
 1313:     my ($fn,%form)=@_;
 1314: 
 1315:     my $ua=new LWP::UserAgent;
 1316:     
 1317:     my $request;
 1318: 
 1319:     $form{'no_update_last_known'}=1;
 1320: 
 1321:     if (%form) {
 1322:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1323:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1324:     } else {
 1325:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1326:     }
 1327: 
 1328:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1329:     my $response=$ua->request($request);
 1330: 
 1331:     return $response->content;
 1332: }
 1333: 
 1334: sub externalssi {
 1335:     my ($url)=@_;
 1336:     my $ua=new LWP::UserAgent;
 1337:     my $request=new HTTP::Request('GET',$url);
 1338:     my $response=$ua->request($request);
 1339:     return $response->content;
 1340: }
 1341: 
 1342: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1343: 
 1344: sub allowuploaded {
 1345:     my ($srcurl,$url)=@_;
 1346:     $url=&clutter(&declutter($url));
 1347:     my $dir=$url;
 1348:     $dir=~s/\/[^\/]+$//;
 1349:     my %httpref=();
 1350:     my $httpurl=&hreflocation('',$url);
 1351:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1352:     &Apache::lonnet::appenv(%httpref);
 1353: }
 1354: 
 1355: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1356: # input: action, courseID, current domain, intended
 1357: #        path to file, source of file, instruction to parse file for objects,
 1358: #        ref to hash for embedded objects,
 1359: #        ref to hash for codebase of java objects.
 1360: #
 1361: # output: url to file (if action was uploaddoc), 
 1362: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1363: #
 1364: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1365: # course.
 1366: #
 1367: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1368: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1369: #          course's home server.
 1370: #
 1371: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1372: #          be copied from $source (current location) to 
 1373: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1374: #         and will then be copied to
 1375: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1376: #         course's home server.
 1377: #
 1378: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1379: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1380: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1381: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1382: #         in course's home server.
 1383: #
 1384: 
 1385: sub process_coursefile {
 1386:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1387:     my $fetchresult;
 1388:     my $home=&homeserver($docuname,$docudom);
 1389:     if ($action eq 'propagate') {
 1390:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1391: 			     $home);
 1392:     } else {
 1393:         my $fpath = '';
 1394:         my $fname = $file;
 1395:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1396:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1397:         my $filepath = &build_filepath($fpath);
 1398:         if ($action eq 'copy') {
 1399:             if ($source eq '') {
 1400:                 $fetchresult = 'no source file';
 1401:                 return $fetchresult;
 1402:             } else {
 1403:                 my $destination = $filepath.'/'.$fname;
 1404:                 rename($source,$destination);
 1405:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1406:                                  $home);
 1407:             }
 1408:         } elsif ($action eq 'uploaddoc') {
 1409:             open(my $fh,'>'.$filepath.'/'.$fname);
 1410:             print $fh $env{'form.'.$source};
 1411:             close($fh);
 1412:             if ($parser eq 'parse') {
 1413:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1414:                 unless ($parse_result eq 'ok') {
 1415:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1416:                 }
 1417:             }
 1418:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1419:                                  $home);
 1420:             if ($fetchresult eq 'ok') {
 1421:                 return '/uploaded/'.$fpath.'/'.$fname;
 1422:             } else {
 1423:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1424:                         ' to host '.$home.': '.$fetchresult);
 1425:                 return '/adm/notfound.html';
 1426:             }
 1427:         }
 1428:     }
 1429:     unless ( $fetchresult eq 'ok') {
 1430:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1431:              ' to host '.$home.': '.$fetchresult);
 1432:     }
 1433:     return $fetchresult;
 1434: }
 1435: 
 1436: sub build_filepath {
 1437:     my ($fpath) = @_;
 1438:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1439:     unless ($fpath eq '') {
 1440:         my @parts=split('/',$fpath);
 1441:         foreach my $part (@parts) {
 1442:             $filepath.= '/'.$part;
 1443:             if ((-e $filepath)!=1) {
 1444:                 mkdir($filepath,0777);
 1445:             }
 1446:         }
 1447:     }
 1448:     return $filepath;
 1449: }
 1450: 
 1451: sub store_edited_file {
 1452:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1453:     my $file = $primary_url;
 1454:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1455:     my $fpath = '';
 1456:     my $fname = $file;
 1457:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1458:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1459:     my $filepath = &build_filepath($fpath);
 1460:     open(my $fh,'>'.$filepath.'/'.$fname);
 1461:     print $fh $content;
 1462:     close($fh);
 1463:     my $home=&homeserver($docuname,$docudom);
 1464:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1465: 			  $home);
 1466:     if ($$fetchresult eq 'ok') {
 1467:         return '/uploaded/'.$fpath.'/'.$fname;
 1468:     } else {
 1469:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1470: 		 ' to host '.$home.': '.$$fetchresult);
 1471:         return '/adm/notfound.html';
 1472:     }
 1473: }
 1474: 
 1475: sub clean_filename {
 1476:     my ($fname,$args)=@_;
 1477: # Replace Windows backslashes by forward slashes
 1478:     $fname=~s/\\/\//g;
 1479:     if (!$args->{'keep_path'}) {
 1480:         # Get rid of everything but the actual filename
 1481: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1482:     }
 1483: # Replace spaces by underscores
 1484:     $fname=~s/\s+/\_/g;
 1485: # Replace all other weird characters by nothing
 1486:     $fname=~s{[^/\w\.\-]}{}g;
 1487: # Replace all .\d. sequences with _\d. so they no longer look like version
 1488: # numbers
 1489:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1490:     return $fname;
 1491: }
 1492: 
 1493: # --------------- Take an uploaded file and put it into the userfiles directory
 1494: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1495: #                    the desired filenam is in $env{"form.$formname.filename"}
 1496: #        $coursedoc - if true up to the current course
 1497: #                     if false
 1498: #        $subdir - directory in userfile to store the file into
 1499: #        $parser, $allfiles, $codebase - unknown
 1500: #
 1501: # output: url of file in userspace, or error: <message> 
 1502: #             or /adm/notfound.html if failure to upload occurse
 1503: 
 1504: 
 1505: sub userfileupload {
 1506:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1507:     if (!defined($subdir)) { $subdir='unknown'; }
 1508:     my $fname=$env{'form.'.$formname.'.filename'};
 1509:     $fname=&clean_filename($fname);
 1510: # See if there is anything left
 1511:     unless ($fname) { return 'error: no uploaded file'; }
 1512:     chop($env{'form.'.$formname});
 1513:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1514:         my $now = time;
 1515:         my $filepath = 'tmp/helprequests/'.$now;
 1516:         my @parts=split(/\//,$filepath);
 1517:         my $fullpath = $perlvar{'lonDaemons'};
 1518:         for (my $i=0;$i<@parts;$i++) {
 1519:             $fullpath .= '/'.$parts[$i];
 1520:             if ((-e $fullpath)!=1) {
 1521:                 mkdir($fullpath,0777);
 1522:             }
 1523:         }
 1524:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1525:         print $fh $env{'form.'.$formname};
 1526:         close($fh);
 1527:         return $fullpath.'/'.$fname;
 1528:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1529:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1530:                        '_'.$env{'user.domain'}.'/pending';
 1531:         my @parts=split(/\//,$filepath);
 1532:         my $fullpath = $perlvar{'lonDaemons'};
 1533:         for (my $i=0;$i<@parts;$i++) {
 1534:             $fullpath .= '/'.$parts[$i];
 1535:             if ((-e $fullpath)!=1) {
 1536:                 mkdir($fullpath,0777);
 1537:             }
 1538:         }
 1539:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1540:         print $fh $env{'form.'.$formname};
 1541:         close($fh);
 1542:         return $fullpath.'/'.$fname;
 1543:     }
 1544:     
 1545: # Create the directory if not present
 1546:     $fname="$subdir/$fname";
 1547:     if ($coursedoc) {
 1548: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1549: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1550:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1551:             return &finishuserfileupload($docuname,$docudom,
 1552: 					 $formname,$fname,$parser,$allfiles,
 1553: 					 $codebase);
 1554:         } else {
 1555:             $fname=$env{'form.folder'}.'/'.$fname;
 1556:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1557: 				       $fname,$formname,$parser,
 1558: 				       $allfiles,$codebase);
 1559:         }
 1560:     } elsif (defined($destuname)) {
 1561:         my $docuname=$destuname;
 1562:         my $docudom=$destudom;
 1563: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1564: 				     $fname,$parser,$allfiles,$codebase);
 1565:         
 1566:     } else {
 1567:         my $docuname=$env{'user.name'};
 1568:         my $docudom=$env{'user.domain'};
 1569:         if (exists($env{'form.group'})) {
 1570:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1571:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1572:         }
 1573: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1574: 				     $fname,$parser,$allfiles,$codebase);
 1575:     }
 1576: }
 1577: 
 1578: sub finishuserfileupload {
 1579:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1580:     my $path=$docudom.'/'.$docuname.'/';
 1581:     my $filepath=$perlvar{'lonDocRoot'};
 1582:     my ($fnamepath,$file);
 1583:     $file=$fname;
 1584:     if ($fname=~m|/|) {
 1585:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1586: 	$path.=$fnamepath.'/';
 1587:     }
 1588:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1589:     my $count;
 1590:     for ($count=4;$count<=$#parts;$count++) {
 1591:         $filepath.="/$parts[$count]";
 1592:         if ((-e $filepath)!=1) {
 1593: 	    mkdir($filepath,0777);
 1594:         }
 1595:     }
 1596: # Save the file
 1597:     {
 1598: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1599: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1600: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1601: 	    return '/adm/notfound.html';
 1602: 	}
 1603: 	if (!print FH ($env{'form.'.$formname})) {
 1604: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1605: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1606: 	    return '/adm/notfound.html';
 1607: 	}
 1608: 	close(FH);
 1609:     }
 1610:     if ($parser eq 'parse') {
 1611:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1612: 						   $codebase);
 1613:         unless ($parse_result eq 'ok') {
 1614:             &logthis('Failed to parse '.$filepath.$file.
 1615: 		     ' for embedded media: '.$parse_result); 
 1616:         }
 1617:     }
 1618: # Notify homeserver to grep it
 1619: #
 1620:     my $docuhome=&homeserver($docuname,$docudom);
 1621:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1622:     if ($fetchresult eq 'ok') {
 1623: #
 1624: # Return the URL to it
 1625:         return '/uploaded/'.$path.$file;
 1626:     } else {
 1627:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1628: 		 ': '.$fetchresult);
 1629:         return '/adm/notfound.html';
 1630:     }    
 1631: }
 1632: 
 1633: sub extract_embedded_items {
 1634:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1635:     my @state = ();
 1636:     my %javafiles = (
 1637:                       codebase => '',
 1638:                       code => '',
 1639:                       archive => ''
 1640:                     );
 1641:     my %mediafiles = (
 1642:                       src => '',
 1643:                       movie => '',
 1644:                      );
 1645:     my $p;
 1646:     if ($content) {
 1647:         $p = HTML::LCParser->new($content);
 1648:     } else {
 1649:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1650:     }
 1651:     while (my $t=$p->get_token()) {
 1652: 	if ($t->[0] eq 'S') {
 1653: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1654: 	    push (@state, $tagname);
 1655:             if (lc($tagname) eq 'allow') {
 1656:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1657:             }
 1658: 	    if (lc($tagname) eq 'img') {
 1659: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1660: 	    }
 1661:             if (lc($tagname) eq 'script') {
 1662:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1663:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1664:                 } else {
 1665:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1666:                 }
 1667:             }
 1668:             if (lc($tagname) eq 'link') {
 1669:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1670:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1671:                 }
 1672:             }
 1673: 	    if (lc($tagname) eq 'object' ||
 1674: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1675: 		foreach my $item (keys(%javafiles)) {
 1676: 		    $javafiles{$item} = '';
 1677: 		}
 1678: 	    }
 1679: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1680: 		my $name = lc($attr->{'name'});
 1681: 		foreach my $item (keys(%javafiles)) {
 1682: 		    if ($name eq $item) {
 1683: 			$javafiles{$item} = $attr->{'value'};
 1684: 			last;
 1685: 		    }
 1686: 		}
 1687: 		foreach my $item (keys(%mediafiles)) {
 1688: 		    if ($name eq $item) {
 1689: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1690: 			last;
 1691: 		    }
 1692: 		}
 1693: 	    }
 1694: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1695: 		foreach my $item (keys(%javafiles)) {
 1696: 		    if ($attr->{$item}) {
 1697: 			$javafiles{$item} = $attr->{$item};
 1698: 			last;
 1699: 		    }
 1700: 		}
 1701: 		foreach my $item (keys(%mediafiles)) {
 1702: 		    if ($attr->{$item}) {
 1703: 			&add_filetype($allfiles,$attr->{$item},$item);
 1704: 			last;
 1705: 		    }
 1706: 		}
 1707: 	    }
 1708: 	} elsif ($t->[0] eq 'E') {
 1709: 	    my ($tagname) = ($t->[1]);
 1710: 	    if ($javafiles{'codebase'} ne '') {
 1711: 		$javafiles{'codebase'} .= '/';
 1712: 	    }  
 1713: 	    if (lc($tagname) eq 'applet' ||
 1714: 		lc($tagname) eq 'object' ||
 1715: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1716: 		) {
 1717: 		foreach my $item (keys(%javafiles)) {
 1718: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1719: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1720: 			&add_filetype($allfiles,$file,$item);
 1721: 		    }
 1722: 		}
 1723: 	    } 
 1724: 	    pop @state;
 1725: 	}
 1726:     }
 1727:     return 'ok';
 1728: }
 1729: 
 1730: sub add_filetype {
 1731:     my ($allfiles,$file,$type)=@_;
 1732:     if (exists($allfiles->{$file})) {
 1733: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1734: 	    push(@{$allfiles->{$file}}, &escape($type));
 1735: 	}
 1736:     } else {
 1737: 	@{$allfiles->{$file}} = (&escape($type));
 1738:     }
 1739: }
 1740: 
 1741: sub removeuploadedurl {
 1742:     my ($url)=@_;
 1743:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1744:     return &removeuserfile($uname,$udom,$fname);
 1745: }
 1746: 
 1747: sub removeuserfile {
 1748:     my ($docuname,$docudom,$fname)=@_;
 1749:     my $home=&homeserver($docuname,$docudom);
 1750:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1751:     if ($result eq 'ok') {
 1752:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1753:             my $metafile = $fname.'.meta';
 1754:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1755: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1756:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1757:             my $sqlresult = 
 1758:                 &update_portfolio_table($docuname,$docudom,$file,
 1759:                                         'portfolio_metadata',$group,
 1760:                                         'delete');
 1761:         }
 1762:     }
 1763:     return $result;
 1764: }
 1765: 
 1766: sub mkdiruserfile {
 1767:     my ($docuname,$docudom,$dir)=@_;
 1768:     my $home=&homeserver($docuname,$docudom);
 1769:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1770: }
 1771: 
 1772: sub renameuserfile {
 1773:     my ($docuname,$docudom,$old,$new)=@_;
 1774:     my $home=&homeserver($docuname,$docudom);
 1775:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1776:                         &escape("$old").':'.&escape("$new"),$home);
 1777:     if ($result eq 'ok') {
 1778:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1779:             my $oldmeta = $old.'.meta';
 1780:             my $newmeta = $new.'.meta';
 1781:             my $metaresult = 
 1782:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1783: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1784:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1785:             my $sqlresult = 
 1786:                 &update_portfolio_table($docuname,$docudom,$file,
 1787:                                         'portfolio_metadata',$group,
 1788:                                         'delete');
 1789:         }
 1790:     }
 1791:     return $result;
 1792: }
 1793: 
 1794: # ------------------------------------------------------------------------- Log
 1795: 
 1796: sub log {
 1797:     my ($dom,$nam,$hom,$what)=@_;
 1798:     return critical("log:$dom:$nam:$what",$hom);
 1799: }
 1800: 
 1801: # ------------------------------------------------------------------ Course Log
 1802: #
 1803: # This routine flushes several buffers of non-mission-critical nature
 1804: #
 1805: 
 1806: sub flushcourselogs {
 1807:     &logthis('Flushing log buffers');
 1808: #
 1809: # course logs
 1810: # This is a log of all transactions in a course, which can be used
 1811: # for data mining purposes
 1812: #
 1813: # It also collects the courseid database, which lists last transaction
 1814: # times and course titles for all courseids
 1815: #
 1816:     my %courseidbuffer=();
 1817:     foreach my $crsid (keys %courselogs) {
 1818:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1819: 		          &escape($courselogs{$crsid}),
 1820: 		          $coursehombuf{$crsid}) eq 'ok') {
 1821: 	    delete $courselogs{$crsid};
 1822:         } else {
 1823:             &logthis('Failed to flush log buffer for '.$crsid);
 1824:             if (length($courselogs{$crsid})>40000) {
 1825:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1826:                         " exceeded maximum size, deleting.</font>");
 1827:                delete $courselogs{$crsid};
 1828:             }
 1829:         }
 1830:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1831:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1832: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1833:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1834:         } else {
 1835:            $courseidbuffer{$coursehombuf{$crsid}}=
 1836: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1837:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1838:         }
 1839:     }
 1840: #
 1841: # Write course id database (reverse lookup) to homeserver of courses 
 1842: # Is used in pickcourse
 1843: #
 1844:     foreach my $crs_home (keys(%courseidbuffer)) {
 1845:         &courseidput($hostdom{$crs_home},$courseidbuffer{$crs_home},
 1846: 		     $crs_home);
 1847:     }
 1848: #
 1849: # File accesses
 1850: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1851: #
 1852:     foreach my $entry (keys(%accesshash)) {
 1853:         if ($entry =~ /___count$/) {
 1854:             my ($dom,$name);
 1855:             ($dom,$name,undef)=
 1856: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1857:             if (! defined($dom) || $dom eq '' || 
 1858:                 ! defined($name) || $name eq '') {
 1859:                 my $cid = $env{'request.course.id'};
 1860:                 $dom  = $env{'request.'.$cid.'.domain'};
 1861:                 $name = $env{'request.'.$cid.'.num'};
 1862:             }
 1863:             my $value = $accesshash{$entry};
 1864:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1865:             my %temphash=($url => $value);
 1866:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1867:             if ($result eq 'ok') {
 1868:                 delete $accesshash{$entry};
 1869:             } elsif ($result eq 'unknown_cmd') {
 1870:                 # Target server has old code running on it.
 1871:                 my %temphash=($entry => $value);
 1872:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1873:                     delete $accesshash{$entry};
 1874:                 }
 1875:             }
 1876:         } else {
 1877:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1878:             my %temphash=($entry => $accesshash{$entry});
 1879:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1880:                 delete $accesshash{$entry};
 1881:             }
 1882:         }
 1883:     }
 1884: #
 1885: # Roles
 1886: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1887: #
 1888:     foreach my $entry (keys(%userrolehash)) {
 1889:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1890: 	    split(/\:/,$entry);
 1891:         if (&Apache::lonnet::put('nohist_userroles',
 1892:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1893:                 $rudom,$runame) eq 'ok') {
 1894: 	    delete $userrolehash{$entry};
 1895:         }
 1896:     }
 1897: #
 1898: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1899: #
 1900:     my %domrolebuffer = ();
 1901:     foreach my $entry (keys %domainrolehash) {
 1902:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1903:         if ($domrolebuffer{$rudom}) {
 1904:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1905:                       '='.&escape($domainrolehash{$entry});
 1906:         } else {
 1907:             $domrolebuffer{$rudom}.=&escape($entry).
 1908:                       '='.&escape($domainrolehash{$entry});
 1909:         }
 1910:         delete $domainrolehash{$entry};
 1911:     }
 1912:     foreach my $dom (keys(%domrolebuffer)) {
 1913: 	my %servers = &get_servers($dom,'library');
 1914: 	foreach my $tryserver (keys(%servers)) {
 1915: 	    unless (&reply('domroleput:'.$dom.':'.
 1916: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1917: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1918: 	    }
 1919:         }
 1920:     }
 1921:     $dumpcount++;
 1922: }
 1923: 
 1924: sub courselog {
 1925:     my $what=shift;
 1926:     $what=time.':'.$what;
 1927:     unless ($env{'request.course.id'}) { return ''; }
 1928:     $coursedombuf{$env{'request.course.id'}}=
 1929:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1930:     $coursenumbuf{$env{'request.course.id'}}=
 1931:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1932:     $coursehombuf{$env{'request.course.id'}}=
 1933:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1934:     $coursedescrbuf{$env{'request.course.id'}}=
 1935:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1936:     $courseinstcodebuf{$env{'request.course.id'}}=
 1937:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1938:     $courseownerbuf{$env{'request.course.id'}}=
 1939:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1940:     $coursetypebuf{$env{'request.course.id'}}=
 1941:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1942:     if (defined $courselogs{$env{'request.course.id'}}) {
 1943: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1944:     } else {
 1945: 	$courselogs{$env{'request.course.id'}}.=$what;
 1946:     }
 1947:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1948: 	&flushcourselogs();
 1949:     }
 1950: }
 1951: 
 1952: sub courseacclog {
 1953:     my $fnsymb=shift;
 1954:     unless ($env{'request.course.id'}) { return ''; }
 1955:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1956:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1957:         $what.=':POST';
 1958:         # FIXME: Probably ought to escape things....
 1959: 	foreach my $key (keys(%env)) {
 1960:             if ($key=~/^form\.(.*)/) {
 1961: 		$what.=':'.$1.'='.$env{$key};
 1962:             }
 1963:         }
 1964:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1965:         # FIXME: We should not be depending on a form parameter that someone
 1966:         # editing lonsearchcat.pm might change in the future.
 1967:         if ($env{'form.phase'} eq 'course_search') {
 1968:             $what.= ':POST';
 1969:             # FIXME: Probably ought to escape things....
 1970:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1971:                                  'crsdiscuss') {
 1972:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1973:             }
 1974:         }
 1975:     }
 1976:     &courselog($what);
 1977: }
 1978: 
 1979: sub countacc {
 1980:     my $url=&declutter(shift);
 1981:     return if (! defined($url) || $url eq '');
 1982:     unless ($env{'request.course.id'}) { return ''; }
 1983:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1984:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1985:     $accesshash{$key}++;
 1986: }
 1987: 
 1988: sub linklog {
 1989:     my ($from,$to)=@_;
 1990:     $from=&declutter($from);
 1991:     $to=&declutter($to);
 1992:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1993:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1994: }
 1995:   
 1996: sub userrolelog {
 1997:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1998:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1999:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2000:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2001:         ($trole=~/^ta/)) {
 2002:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2003:        $userrolehash
 2004:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2005:                     =$tend.':'.$tstart;
 2006:     }
 2007:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2008:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2009:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2010:         ($trole=~/^sc/)) {
 2011:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2012:        $domainrolehash
 2013:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2014:                     = $tend.':'.$tstart;
 2015:     }
 2016: }
 2017: 
 2018: sub get_course_adv_roles {
 2019:     my $cid=shift;
 2020:     $cid=$env{'request.course.id'} unless (defined($cid));
 2021:     my %coursehash=&coursedescription($cid);
 2022:     my %nothide=();
 2023:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2024: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2025:     }
 2026:     my %returnhash=();
 2027:     my %dumphash=
 2028:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2029:     my $now=time;
 2030:     foreach my $entry (keys %dumphash) {
 2031: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2032:         if (($tstart) && ($tstart<0)) { next; }
 2033:         if (($tend) && ($tend<$now)) { next; }
 2034:         if (($tstart) && ($now<$tstart)) { next; }
 2035:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2036: 	if ($username eq '' || $domain eq '') { next; }
 2037: 	if ((&privileged($username,$domain)) && 
 2038: 	    (!$nothide{$username.':'.$domain})) { next; }
 2039: 	if ($role eq 'cr') { next; }
 2040:         my $key=&plaintext($role);
 2041:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2042:         if ($returnhash{$key}) {
 2043: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2044:         } else {
 2045:             $returnhash{$key}=$username.':'.$domain;
 2046:         }
 2047:      }
 2048:     return %returnhash;
 2049: }
 2050: 
 2051: sub get_my_roles {
 2052:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
 2053:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2054:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2055:     my %dumphash=
 2056:             &dump('nohist_userroles',$udom,$uname);
 2057:     my %returnhash=();
 2058:     my $now=time;
 2059:     foreach my $entry (keys(%dumphash)) {
 2060: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2061:         if (($tstart) && ($tstart<0)) { next; }
 2062:         my $status = 'active';
 2063:         if (($tend) && ($tend<$now)) {
 2064:             $status = 'previous';
 2065:         } 
 2066:         if (($tstart) && ($now<$tstart)) {
 2067:             $status = 'future';
 2068:         }
 2069:         if (ref($types) eq 'ARRAY') {
 2070:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2071:                 next;
 2072:             } 
 2073:         } else {
 2074:             if ($status ne 'active') {
 2075:                 next;
 2076:             }
 2077:         }
 2078:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2079:         if (ref($roledoms) eq 'ARRAY') {
 2080:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2081:                 next;
 2082:             }
 2083:         }
 2084:         if (ref($roles) eq 'ARRAY') {
 2085:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2086:                 next;
 2087:             }
 2088:         } 
 2089: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2090:     }
 2091:     return %returnhash;
 2092: }
 2093: 
 2094: # ----------------------------------------------------- Frontpage Announcements
 2095: #
 2096: #
 2097: 
 2098: sub postannounce {
 2099:     my ($server,$text)=@_;
 2100:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 2101:     unless ($text=~/\w/) { $text=''; }
 2102:     return &reply('setannounce:'.&escape($text),$server);
 2103: }
 2104: 
 2105: sub getannounce {
 2106: 
 2107:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2108: 	my $announcement='';
 2109: 	while (my $line = <$fh>) { $announcement .= $line; }
 2110: 	close($fh);
 2111: 	if ($announcement=~/\w/) { 
 2112: 	    return 
 2113:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2114:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2115: 	} else {
 2116: 	    return '';
 2117: 	}
 2118:     } else {
 2119: 	return '';
 2120:     }
 2121: }
 2122: 
 2123: # ---------------------------------------------------------- Course ID routines
 2124: # Deal with domain's nohist_courseid.db files
 2125: #
 2126: 
 2127: sub courseidput {
 2128:     my ($domain,$what,$coursehome)=@_;
 2129:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2130: }
 2131: 
 2132: sub courseiddump {
 2133:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2134:     my %returnhash=();
 2135:     unless ($domfilter) { $domfilter=''; }
 2136:     foreach my $tryserver (keys %libserv) {
 2137:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 2138: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 2139: 	        foreach my $line (
 2140:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 2141: 			       $sincefilter.':'.&escape($descfilter).':'.
 2142:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2143:                                $tryserver))) {
 2144: 		    my ($key,$value)=split(/\=/,$line,2);
 2145:                     if (($key) && ($value)) {
 2146: 		        $returnhash{&unescape($key)}=$value;
 2147:                     }
 2148:                 }
 2149:             }
 2150:         }
 2151:     }
 2152:     return %returnhash;
 2153: }
 2154: 
 2155: # ---------------------------------------------------------- DC e-mail
 2156: 
 2157: sub dcmailput {
 2158:     my ($domain,$msgid,$message,$server)=@_;
 2159:     my $status = &Apache::lonnet::critical(
 2160:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2161:        &escape($message),$server);
 2162:     return $status;
 2163: }
 2164: 
 2165: sub dcmaildump {
 2166:     my ($dom,$startdate,$enddate,$senders) = @_;
 2167:     my %returnhash=();
 2168:     if (exists($domain_primary{$dom})) {
 2169:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2170:                                                          &escape($enddate).':';
 2171: 	my @esc_senders=map { &escape($_)} @$senders;
 2172: 	$cmd.=&escape(join('&',@esc_senders));
 2173: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2174:             my ($key,$value) = split(/\=/,$line,2);
 2175:             if (($key) && ($value)) {
 2176:                 $returnhash{&unescape($key)} = &unescape($value);
 2177:             }
 2178:         }
 2179:     }
 2180:     return %returnhash;
 2181: }
 2182: # ---------------------------------------------------------- Domain roles
 2183: 
 2184: sub get_domain_roles {
 2185:     my ($dom,$roles,$startdate,$enddate)=@_;
 2186:     if (undef($startdate) || $startdate eq '') {
 2187:         $startdate = '.';
 2188:     }
 2189:     if (undef($enddate) || $enddate eq '') {
 2190:         $enddate = '.';
 2191:     }
 2192:     my $rolelist = join(':',@{$roles});
 2193:     my %personnel = ();
 2194: 
 2195:     my %servers = &get_servers($dom,'library');
 2196:     foreach my $tryserver (keys(%servers)) {
 2197: 	%{$personnel{$tryserver}}=();
 2198: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2199: 					    &escape($startdate).':'.
 2200: 					    &escape($enddate).':'.
 2201: 					    &escape($rolelist), $tryserver))) {
 2202: 	    my ($key,$value) = split(/\=/,$line,2);
 2203: 	    if (($key) && ($value)) {
 2204: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2205: 	    }
 2206: 	}
 2207:     }
 2208:     return %personnel;
 2209: }
 2210: 
 2211: # ----------------------------------------------------------- Check out an item
 2212: 
 2213: sub get_first_access {
 2214:     my ($type,$argsymb)=@_;
 2215:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2216:     if ($argsymb) { $symb=$argsymb; }
 2217:     my ($map,$id,$res)=&decode_symb($symb);
 2218:     if ($type eq 'map') {
 2219: 	$res=&symbread($map);
 2220:     } else {
 2221: 	$res=$symb;
 2222:     }
 2223:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2224:     return $times{"$courseid\0$res"};
 2225: }
 2226: 
 2227: sub set_first_access {
 2228:     my ($type)=@_;
 2229:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2230:     my ($map,$id,$res)=&decode_symb($symb);
 2231:     if ($type eq 'map') {
 2232: 	$res=&symbread($map);
 2233:     } else {
 2234: 	$res=$symb;
 2235:     }
 2236:     my $firstaccess=&get_first_access($type,$symb);
 2237:     if (!$firstaccess) {
 2238: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2239:     }
 2240:     return 'already_set';
 2241: }
 2242: 
 2243: sub checkout {
 2244:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2245:     my $now=time;
 2246:     my $lonhost=$perlvar{'lonHostID'};
 2247:     my $infostr=&escape(
 2248:                  'CHECKOUTTOKEN&'.
 2249:                  $tuname.'&'.
 2250:                  $tudom.'&'.
 2251:                  $tcrsid.'&'.
 2252:                  $symb.'&'.
 2253: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2254:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2255:     if ($token=~/^error\:/) { 
 2256:         &logthis("<font color=\"blue\">WARNING: ".
 2257:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2258:                  "</font>");
 2259:         return ''; 
 2260:     }
 2261: 
 2262:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2263:     $token=~tr/a-z/A-Z/;
 2264: 
 2265:     my %infohash=('resource.0.outtoken' => $token,
 2266:                   'resource.0.checkouttime' => $now,
 2267:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2268: 
 2269:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2270:        return '';
 2271:     } else {
 2272:         &logthis("<font color=\"blue\">WARNING: ".
 2273:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2274:                  "</font>");
 2275:     }    
 2276: 
 2277:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2278:                          &escape('Checkout '.$infostr.' - '.
 2279:                                                  $token)) ne 'ok') {
 2280: 	return '';
 2281:     } else {
 2282:         &logthis("<font color=\"blue\">WARNING: ".
 2283:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2284:                  "</font>");
 2285:     }
 2286:     return $token;
 2287: }
 2288: 
 2289: # ------------------------------------------------------------ Check in an item
 2290: 
 2291: sub checkin {
 2292:     my $token=shift;
 2293:     my $now=time;
 2294:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2295:     $lonhost=~tr/A-Z/a-z/;
 2296:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2297:     $dtoken=~s/\W/\_/g;
 2298:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2299:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2300: 
 2301:     unless (($tuname) && ($tudom)) {
 2302:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2303:         return '';
 2304:     }
 2305:     
 2306:     unless (&allowed('mgr',$tcrsid)) {
 2307:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2308:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2309:         return '';
 2310:     }
 2311: 
 2312:     my %infohash=('resource.0.intoken' => $token,
 2313:                   'resource.0.checkintime' => $now,
 2314:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2315: 
 2316:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2317:        return '';
 2318:     }    
 2319: 
 2320:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2321:                          &escape('Checkin - '.$token)) ne 'ok') {
 2322: 	return '';
 2323:     }
 2324: 
 2325:     return ($symb,$tuname,$tudom,$tcrsid);    
 2326: }
 2327: 
 2328: # --------------------------------------------- Set Expire Date for Spreadsheet
 2329: 
 2330: sub expirespread {
 2331:     my ($uname,$udom,$stype,$usymb)=@_;
 2332:     my $cid=$env{'request.course.id'}; 
 2333:     if ($cid) {
 2334:        my $now=time;
 2335:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2336:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2337:                             $env{'course.'.$cid.'.num'}.
 2338: 	        	    ':nohist_expirationdates:'.
 2339:                             &escape($key).'='.$now,
 2340:                             $env{'course.'.$cid.'.home'})
 2341:     }
 2342:     return 'ok';
 2343: }
 2344: 
 2345: # ----------------------------------------------------- Devalidate Spreadsheets
 2346: 
 2347: sub devalidate {
 2348:     my ($symb,$uname,$udom)=@_;
 2349:     my $cid=$env{'request.course.id'}; 
 2350:     if ($cid) {
 2351:         # delete the stored spreadsheets for
 2352:         # - the student level sheet of this user in course's homespace
 2353:         # - the assessment level sheet for this resource 
 2354:         #   for this user in user's homespace
 2355: 	# - current conditional state info
 2356: 	my $key=$uname.':'.$udom.':';
 2357:         my $status=
 2358: 	    &del('nohist_calculatedsheets',
 2359: 		 [$key.'studentcalc:'],
 2360: 		 $env{'course.'.$cid.'.domain'},
 2361: 		 $env{'course.'.$cid.'.num'})
 2362: 		.' '.
 2363: 	    &del('nohist_calculatedsheets_'.$cid,
 2364: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2365:         unless ($status eq 'ok ok') {
 2366:            &logthis('Could not devalidate spreadsheet '.
 2367:                     $uname.' at '.$udom.' for '.
 2368: 		    $symb.': '.$status);
 2369:         }
 2370: 	&delenv('user.state.'.$cid);
 2371:     }
 2372: }
 2373: 
 2374: sub get_scalar {
 2375:     my ($string,$end) = @_;
 2376:     my $value;
 2377:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2378: 	$value = $1;
 2379:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2380: 	$value = $1;
 2381:     }
 2382:     return &unescape($value);
 2383: }
 2384: 
 2385: sub array2str {
 2386:   my (@array) = @_;
 2387:   my $result=&arrayref2str(\@array);
 2388:   $result=~s/^__ARRAY_REF__//;
 2389:   $result=~s/__END_ARRAY_REF__$//;
 2390:   return $result;
 2391: }
 2392: 
 2393: sub arrayref2str {
 2394:   my ($arrayref) = @_;
 2395:   my $result='__ARRAY_REF__';
 2396:   foreach my $elem (@$arrayref) {
 2397:     if(ref($elem) eq 'ARRAY') {
 2398:       $result.=&arrayref2str($elem).'&';
 2399:     } elsif(ref($elem) eq 'HASH') {
 2400:       $result.=&hashref2str($elem).'&';
 2401:     } elsif(ref($elem)) {
 2402:       #print("Got a ref of ".(ref($elem))." skipping.");
 2403:     } else {
 2404:       $result.=&escape($elem).'&';
 2405:     }
 2406:   }
 2407:   $result=~s/\&$//;
 2408:   $result .= '__END_ARRAY_REF__';
 2409:   return $result;
 2410: }
 2411: 
 2412: sub hash2str {
 2413:   my (%hash) = @_;
 2414:   my $result=&hashref2str(\%hash);
 2415:   $result=~s/^__HASH_REF__//;
 2416:   $result=~s/__END_HASH_REF__$//;
 2417:   return $result;
 2418: }
 2419: 
 2420: sub hashref2str {
 2421:   my ($hashref)=@_;
 2422:   my $result='__HASH_REF__';
 2423:   foreach my $key (sort(keys(%$hashref))) {
 2424:     if (ref($key) eq 'ARRAY') {
 2425:       $result.=&arrayref2str($key).'=';
 2426:     } elsif (ref($key) eq 'HASH') {
 2427:       $result.=&hashref2str($key).'=';
 2428:     } elsif (ref($key)) {
 2429:       $result.='=';
 2430:       #print("Got a ref of ".(ref($key))." skipping.");
 2431:     } else {
 2432: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2433:     }
 2434: 
 2435:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2436:       $result.=&arrayref2str($hashref->{$key}).'&';
 2437:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2438:       $result.=&hashref2str($hashref->{$key}).'&';
 2439:     } elsif(ref($hashref->{$key})) {
 2440:        $result.='&';
 2441:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2442:     } else {
 2443:       $result.=&escape($hashref->{$key}).'&';
 2444:     }
 2445:   }
 2446:   $result=~s/\&$//;
 2447:   $result .= '__END_HASH_REF__';
 2448:   return $result;
 2449: }
 2450: 
 2451: sub str2hash {
 2452:     my ($string)=@_;
 2453:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2454:     return %$hash;
 2455: }
 2456: 
 2457: sub str2hashref {
 2458:   my ($string) = @_;
 2459: 
 2460:   my %hash;
 2461: 
 2462:   if($string !~ /^__HASH_REF__/) {
 2463:       if (! ($string eq '' || !defined($string))) {
 2464: 	  $hash{'error'}='Not hash reference';
 2465:       }
 2466:       return (\%hash, $string);
 2467:   }
 2468: 
 2469:   $string =~ s/^__HASH_REF__//;
 2470: 
 2471:   while($string !~ /^__END_HASH_REF__/) {
 2472:       #key
 2473:       my $key='';
 2474:       if($string =~ /^__HASH_REF__/) {
 2475:           ($key, $string)=&str2hashref($string);
 2476:           if(defined($key->{'error'})) {
 2477:               $hash{'error'}='Bad data';
 2478:               return (\%hash, $string);
 2479:           }
 2480:       } elsif($string =~ /^__ARRAY_REF__/) {
 2481:           ($key, $string)=&str2arrayref($string);
 2482:           if($key->[0] eq 'Array reference error') {
 2483:               $hash{'error'}='Bad data';
 2484:               return (\%hash, $string);
 2485:           }
 2486:       } else {
 2487:           $string =~ s/^(.*?)=//;
 2488: 	  $key=&unescape($1);
 2489:       }
 2490:       $string =~ s/^=//;
 2491: 
 2492:       #value
 2493:       my $value='';
 2494:       if($string =~ /^__HASH_REF__/) {
 2495:           ($value, $string)=&str2hashref($string);
 2496:           if(defined($value->{'error'})) {
 2497:               $hash{'error'}='Bad data';
 2498:               return (\%hash, $string);
 2499:           }
 2500:       } elsif($string =~ /^__ARRAY_REF__/) {
 2501:           ($value, $string)=&str2arrayref($string);
 2502:           if($value->[0] eq 'Array reference error') {
 2503:               $hash{'error'}='Bad data';
 2504:               return (\%hash, $string);
 2505:           }
 2506:       } else {
 2507: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2508:       }
 2509:       $string =~ s/^&//;
 2510: 
 2511:       $hash{$key}=$value;
 2512:   }
 2513: 
 2514:   $string =~ s/^__END_HASH_REF__//;
 2515: 
 2516:   return (\%hash, $string);
 2517: }
 2518: 
 2519: sub str2array {
 2520:     my ($string)=@_;
 2521:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2522:     return @$array;
 2523: }
 2524: 
 2525: sub str2arrayref {
 2526:   my ($string) = @_;
 2527:   my @array;
 2528: 
 2529:   if($string !~ /^__ARRAY_REF__/) {
 2530:       if (! ($string eq '' || !defined($string))) {
 2531: 	  $array[0]='Array reference error';
 2532:       }
 2533:       return (\@array, $string);
 2534:   }
 2535: 
 2536:   $string =~ s/^__ARRAY_REF__//;
 2537: 
 2538:   while($string !~ /^__END_ARRAY_REF__/) {
 2539:       my $value='';
 2540:       if($string =~ /^__HASH_REF__/) {
 2541:           ($value, $string)=&str2hashref($string);
 2542:           if(defined($value->{'error'})) {
 2543:               $array[0] ='Array reference error';
 2544:               return (\@array, $string);
 2545:           }
 2546:       } elsif($string =~ /^__ARRAY_REF__/) {
 2547:           ($value, $string)=&str2arrayref($string);
 2548:           if($value->[0] eq 'Array reference error') {
 2549:               $array[0] ='Array reference error';
 2550:               return (\@array, $string);
 2551:           }
 2552:       } else {
 2553: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2554:       }
 2555:       $string =~ s/^&//;
 2556: 
 2557:       push(@array, $value);
 2558:   }
 2559: 
 2560:   $string =~ s/^__END_ARRAY_REF__//;
 2561: 
 2562:   return (\@array, $string);
 2563: }
 2564: 
 2565: # -------------------------------------------------------------------Temp Store
 2566: 
 2567: sub tmpreset {
 2568:   my ($symb,$namespace,$domain,$stuname) = @_;
 2569:   if (!$symb) {
 2570:     $symb=&symbread();
 2571:     if (!$symb) { $symb= $env{'request.url'}; }
 2572:   }
 2573:   $symb=escape($symb);
 2574: 
 2575:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2576:   $namespace=~s/\//\_/g;
 2577:   $namespace=~s/\W//g;
 2578: 
 2579:   if (!$domain) { $domain=$env{'user.domain'}; }
 2580:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2581:   if ($domain eq 'public' && $stuname eq 'public') {
 2582:       $stuname=$ENV{'REMOTE_ADDR'};
 2583:   }
 2584:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2585:   my %hash;
 2586:   if (tie(%hash,'GDBM_File',
 2587: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2588: 	  &GDBM_WRCREAT(),0640)) {
 2589:     foreach my $key (keys %hash) {
 2590:       if ($key=~ /:$symb/) {
 2591: 	delete($hash{$key});
 2592:       }
 2593:     }
 2594:   }
 2595: }
 2596: 
 2597: sub tmpstore {
 2598:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2599: 
 2600:   if (!$symb) {
 2601:     $symb=&symbread();
 2602:     if (!$symb) { $symb= $env{'request.url'}; }
 2603:   }
 2604:   $symb=escape($symb);
 2605: 
 2606:   if (!$namespace) {
 2607:     # I don't think we would ever want to store this for a course.
 2608:     # it seems this will only be used if we don't have a course.
 2609:     #$namespace=$env{'request.course.id'};
 2610:     #if (!$namespace) {
 2611:       $namespace=$env{'request.state'};
 2612:     #}
 2613:   }
 2614:   $namespace=~s/\//\_/g;
 2615:   $namespace=~s/\W//g;
 2616:   if (!$domain) { $domain=$env{'user.domain'}; }
 2617:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2618:   if ($domain eq 'public' && $stuname eq 'public') {
 2619:       $stuname=$ENV{'REMOTE_ADDR'};
 2620:   }
 2621:   my $now=time;
 2622:   my %hash;
 2623:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2624:   if (tie(%hash,'GDBM_File',
 2625: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2626: 	  &GDBM_WRCREAT(),0640)) {
 2627:     $hash{"version:$symb"}++;
 2628:     my $version=$hash{"version:$symb"};
 2629:     my $allkeys=''; 
 2630:     foreach my $key (keys(%$storehash)) {
 2631:       $allkeys.=$key.':';
 2632:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2633:     }
 2634:     $hash{"$version:$symb:timestamp"}=$now;
 2635:     $allkeys.='timestamp';
 2636:     $hash{"$version:keys:$symb"}=$allkeys;
 2637:     if (untie(%hash)) {
 2638:       return 'ok';
 2639:     } else {
 2640:       return "error:$!";
 2641:     }
 2642:   } else {
 2643:     return "error:$!";
 2644:   }
 2645: }
 2646: 
 2647: # -----------------------------------------------------------------Temp Restore
 2648: 
 2649: sub tmprestore {
 2650:   my ($symb,$namespace,$domain,$stuname) = @_;
 2651: 
 2652:   if (!$symb) {
 2653:     $symb=&symbread();
 2654:     if (!$symb) { $symb= $env{'request.url'}; }
 2655:   }
 2656:   $symb=escape($symb);
 2657: 
 2658:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2659: 
 2660:   if (!$domain) { $domain=$env{'user.domain'}; }
 2661:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2662:   if ($domain eq 'public' && $stuname eq 'public') {
 2663:       $stuname=$ENV{'REMOTE_ADDR'};
 2664:   }
 2665:   my %returnhash;
 2666:   $namespace=~s/\//\_/g;
 2667:   $namespace=~s/\W//g;
 2668:   my %hash;
 2669:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2670:   if (tie(%hash,'GDBM_File',
 2671: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2672: 	  &GDBM_READER(),0640)) {
 2673:     my $version=$hash{"version:$symb"};
 2674:     $returnhash{'version'}=$version;
 2675:     my $scope;
 2676:     for ($scope=1;$scope<=$version;$scope++) {
 2677:       my $vkeys=$hash{"$scope:keys:$symb"};
 2678:       my @keys=split(/:/,$vkeys);
 2679:       my $key;
 2680:       $returnhash{"$scope:keys"}=$vkeys;
 2681:       foreach $key (@keys) {
 2682: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2683: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2684:       }
 2685:     }
 2686:     if (!(untie(%hash))) {
 2687:       return "error:$!";
 2688:     }
 2689:   } else {
 2690:     return "error:$!";
 2691:   }
 2692:   return %returnhash;
 2693: }
 2694: 
 2695: # ----------------------------------------------------------------------- Store
 2696: 
 2697: sub store {
 2698:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2699:     my $home='';
 2700: 
 2701:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2702: 
 2703:     $symb=&symbclean($symb);
 2704:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2705: 
 2706:     if (!$domain) { $domain=$env{'user.domain'}; }
 2707:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2708: 
 2709:     &devalidate($symb,$stuname,$domain);
 2710: 
 2711:     $symb=escape($symb);
 2712:     if (!$namespace) { 
 2713:        unless ($namespace=$env{'request.course.id'}) { 
 2714:           return ''; 
 2715:        } 
 2716:     }
 2717:     if (!$home) { $home=$env{'user.home'}; }
 2718: 
 2719:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2720:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2721: 
 2722:     my $namevalue='';
 2723:     foreach my $key (keys(%$storehash)) {
 2724:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2725:     }
 2726:     $namevalue=~s/\&$//;
 2727:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2728:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2729: }
 2730: 
 2731: # -------------------------------------------------------------- Critical Store
 2732: 
 2733: sub cstore {
 2734:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2735:     my $home='';
 2736: 
 2737:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2738: 
 2739:     $symb=&symbclean($symb);
 2740:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2741: 
 2742:     if (!$domain) { $domain=$env{'user.domain'}; }
 2743:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2744: 
 2745:     &devalidate($symb,$stuname,$domain);
 2746: 
 2747:     $symb=escape($symb);
 2748:     if (!$namespace) { 
 2749:        unless ($namespace=$env{'request.course.id'}) { 
 2750:           return ''; 
 2751:        } 
 2752:     }
 2753:     if (!$home) { $home=$env{'user.home'}; }
 2754: 
 2755:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2756:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2757: 
 2758:     my $namevalue='';
 2759:     foreach my $key (keys(%$storehash)) {
 2760:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2761:     }
 2762:     $namevalue=~s/\&$//;
 2763:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2764:     return critical
 2765:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2766: }
 2767: 
 2768: # --------------------------------------------------------------------- Restore
 2769: 
 2770: sub restore {
 2771:     my ($symb,$namespace,$domain,$stuname) = @_;
 2772:     my $home='';
 2773: 
 2774:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2775: 
 2776:     if (!$symb) {
 2777:       unless ($symb=escape(&symbread())) { return ''; }
 2778:     } else {
 2779:       $symb=&escape(&symbclean($symb));
 2780:     }
 2781:     if (!$namespace) { 
 2782:        unless ($namespace=$env{'request.course.id'}) { 
 2783:           return ''; 
 2784:        } 
 2785:     }
 2786:     if (!$domain) { $domain=$env{'user.domain'}; }
 2787:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2788:     if (!$home) { $home=$env{'user.home'}; }
 2789:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2790: 
 2791:     my %returnhash=();
 2792:     foreach my $line (split(/\&/,$answer)) {
 2793: 	my ($name,$value)=split(/\=/,$line);
 2794:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2795:     }
 2796:     my $version;
 2797:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2798:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2799:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2800:        }
 2801:     }
 2802:     return %returnhash;
 2803: }
 2804: 
 2805: # ---------------------------------------------------------- Course Description
 2806: 
 2807: sub coursedescription {
 2808:     my ($courseid,$args)=@_;
 2809:     $courseid=~s/^\///;
 2810:     $courseid=~s/\_/\//g;
 2811:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2812:     my $chome=&homeserver($cnum,$cdomain);
 2813:     my $normalid=$cdomain.'_'.$cnum;
 2814:     # need to always cache even if we get errors otherwise we keep 
 2815:     # trying and trying and trying to get the course description.
 2816:     my %envhash=();
 2817:     my %returnhash=();
 2818:     
 2819:     my $expiretime=600;
 2820:     if ($env{'request.course.id'} eq $normalid) {
 2821: 	$expiretime=120;
 2822:     }
 2823: 
 2824:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2825:     if (!$args->{'freshen_cache'}
 2826: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2827: 	foreach my $key (keys(%env)) {
 2828: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2829: 	    my ($setting) = $1;
 2830: 	    $returnhash{$setting} = $env{$key};
 2831: 	}
 2832: 	return %returnhash;
 2833:     }
 2834: 
 2835:     # get the data agin
 2836:     if (!$args->{'one_time'}) {
 2837: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2838:     }
 2839: 
 2840:     if ($chome ne 'no_host') {
 2841:        %returnhash=&dump('environment',$cdomain,$cnum);
 2842:        if (!exists($returnhash{'con_lost'})) {
 2843:            $returnhash{'home'}= $chome;
 2844: 	   $returnhash{'domain'} = $cdomain;
 2845: 	   $returnhash{'num'} = $cnum;
 2846:            if (!defined($returnhash{'type'})) {
 2847:                $returnhash{'type'} = 'Course';
 2848:            }
 2849:            while (my ($name,$value) = each %returnhash) {
 2850:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2851:            }
 2852:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2853:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2854: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2855:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2856:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2857:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2858:        }
 2859:     }
 2860:     if (!$args->{'one_time'}) {
 2861: 	&appenv(%envhash);
 2862:     }
 2863:     return %returnhash;
 2864: }
 2865: 
 2866: # -------------------------------------------------See if a user is privileged
 2867: 
 2868: sub privileged {
 2869:     my ($username,$domain)=@_;
 2870:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2871: 			&homeserver($username,$domain));
 2872:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2873:     my $now=time;
 2874:     if ($rolesdump ne '') {
 2875:         foreach my $entry (split(/&/,$rolesdump)) {
 2876: 	    if ($entry!~/^rolesdef_/) {
 2877: 		my ($area,$role)=split(/=/,$entry);
 2878: 		$area=~s/\_\w\w$//;
 2879: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2880: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2881: 		    my $active=1;
 2882: 		    if ($tend) {
 2883: 			if ($tend<$now) { $active=0; }
 2884: 		    }
 2885: 		    if ($tstart) {
 2886: 			if ($tstart>$now) { $active=0; }
 2887: 		    }
 2888: 		    if ($active) { return 1; }
 2889: 		}
 2890: 	    }
 2891: 	}
 2892:     }
 2893:     return 0;
 2894: }
 2895: 
 2896: # -------------------------------------------------------- Get user privileges
 2897: 
 2898: sub rolesinit {
 2899:     my ($domain,$username,$authhost)=@_;
 2900:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2901:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2902:     my %allroles=();
 2903:     my %allgroups=();   
 2904:     my $now=time;
 2905:     my %userroles = ('user.login.time' => $now);
 2906:     my $group_privs;
 2907: 
 2908:     if ($rolesdump ne '') {
 2909:         foreach my $entry (split(/&/,$rolesdump)) {
 2910: 	  if ($entry!~/^rolesdef_/) {
 2911:             my ($area,$role)=split(/=/,$entry);
 2912: 	    $area=~s/\_\w\w$//;
 2913:             my ($trole,$tend,$tstart,$group_privs);
 2914: 	    if ($role=~/^cr/) { 
 2915: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 2916: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 2917: 		    ($tend,$tstart)=split('_',$trest);
 2918: 		} else {
 2919: 		    $trole=$role;
 2920: 		}
 2921:             } elsif ($role =~ m|^gr/|) {
 2922:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2923:                 ($trole,$group_privs) = split(/\//,$trole);
 2924:                 $group_privs = &unescape($group_privs);
 2925: 	    } else {
 2926: 		($trole,$tend,$tstart)=split(/_/,$role);
 2927: 	    }
 2928: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2929: 					 $username);
 2930: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2931:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2932:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2933:             if (($area ne '') && ($trole ne '')) {
 2934: 		my $spec=$trole.'.'.$area;
 2935: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2936: 		if ($trole =~ /^cr\//) {
 2937:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2938:                 } elsif ($trole eq 'gr') {
 2939:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2940: 		} else {
 2941:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2942: 		}
 2943:             }
 2944:           }
 2945:         }
 2946:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2947:         $userroles{'user.adv'}    = $adv;
 2948: 	$userroles{'user.author'} = $author;
 2949:         $env{'user.adv'}=$adv;
 2950:     }
 2951:     return \%userroles;  
 2952: }
 2953: 
 2954: sub set_arearole {
 2955:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2956: # log the associated role with the area
 2957:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2958:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2959: }
 2960: 
 2961: sub custom_roleprivs {
 2962:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2963:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2964:     my $homsvr=homeserver($rauthor,$rdomain);
 2965:     if (&hostname($homsvr) ne '') {
 2966:         my ($rdummy,$roledef)=
 2967:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2968:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2969:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2970:             if (defined($syspriv)) {
 2971:                 $$allroles{'cm./'}.=':'.$syspriv;
 2972:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2973:             }
 2974:             if ($tdomain ne '') {
 2975:                 if (defined($dompriv)) {
 2976:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2977:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2978:                 }
 2979:                 if (($trest ne '') && (defined($coursepriv))) {
 2980:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2981:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2982:                 }
 2983:             }
 2984:         }
 2985:     }
 2986: }
 2987: 
 2988: sub group_roleprivs {
 2989:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2990:     my $access = 1;
 2991:     my $now = time;
 2992:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2993:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2994:     if ($access) {
 2995:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 2996:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2997:     }
 2998: }
 2999: 
 3000: sub standard_roleprivs {
 3001:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3002:     if (defined($pr{$trole.':s'})) {
 3003:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3004:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3005:     }
 3006:     if ($tdomain ne '') {
 3007:         if (defined($pr{$trole.':d'})) {
 3008:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3009:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3010:         }
 3011:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3012:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3013:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3014:         }
 3015:     }
 3016: }
 3017: 
 3018: sub set_userprivs {
 3019:     my ($userroles,$allroles,$allgroups) = @_; 
 3020:     my $author=0;
 3021:     my $adv=0;
 3022:     my %grouproles = ();
 3023:     if (keys(%{$allgroups}) > 0) {
 3024:         foreach my $role (keys %{$allroles}) {
 3025:             my ($trole,$area,$sec,$extendedarea);
 3026:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3027:                 $trole = $1;
 3028:                 $area = $2;
 3029:                 $sec = $3;
 3030:                 $extendedarea = $area.$sec;
 3031:                 if (exists($$allgroups{$area})) {
 3032:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3033:                         my $spec = $trole.'.'.$extendedarea;
 3034:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3035:                                                 $$allgroups{$area}{$group};
 3036:                     }
 3037:                 }
 3038:             }
 3039:         }
 3040:     }
 3041:     foreach my $group (keys(%grouproles)) {
 3042:         $$allroles{$group} = $grouproles{$group};
 3043:     }
 3044:     foreach my $role (keys(%{$allroles})) {
 3045:         my %thesepriv;
 3046:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3047:         foreach my $item (split(/:/,$$allroles{$role})) {
 3048:             if ($item ne '') {
 3049:                 my ($privilege,$restrictions)=split(/&/,$item);
 3050:                 if ($restrictions eq '') {
 3051:                     $thesepriv{$privilege}='F';
 3052:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3053:                     $thesepriv{$privilege}.=$restrictions;
 3054:                 }
 3055:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3056:             }
 3057:         }
 3058:         my $thesestr='';
 3059:         foreach my $priv (keys(%thesepriv)) {
 3060: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3061: 	}
 3062:         $userroles->{'user.priv.'.$role} = $thesestr;
 3063:     }
 3064:     return ($author,$adv);
 3065: }
 3066: 
 3067: # --------------------------------------------------------------- get interface
 3068: 
 3069: sub get {
 3070:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3071:    my $items='';
 3072:    foreach my $item (@$storearr) {
 3073:        $items.=&escape($item).'&';
 3074:    }
 3075:    $items=~s/\&$//;
 3076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3077:    if (!$uname) { $uname=$env{'user.name'}; }
 3078:    my $uhome=&homeserver($uname,$udomain);
 3079: 
 3080:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3081:    my @pairs=split(/\&/,$rep);
 3082:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3083:      return @pairs;
 3084:    }
 3085:    my %returnhash=();
 3086:    my $i=0;
 3087:    foreach my $item (@$storearr) {
 3088:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3089:       $i++;
 3090:    }
 3091:    return %returnhash;
 3092: }
 3093: 
 3094: # --------------------------------------------------------------- del interface
 3095: 
 3096: sub del {
 3097:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3098:    my $items='';
 3099:    foreach my $item (@$storearr) {
 3100:        $items.=&escape($item).'&';
 3101:    }
 3102:    $items=~s/\&$//;
 3103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3104:    if (!$uname) { $uname=$env{'user.name'}; }
 3105:    my $uhome=&homeserver($uname,$udomain);
 3106: 
 3107:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3108: }
 3109: 
 3110: # -------------------------------------------------------------- dump interface
 3111: 
 3112: sub dump {
 3113:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3114:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3115:     if (!$uname) { $uname=$env{'user.name'}; }
 3116:     my $uhome=&homeserver($uname,$udomain);
 3117:     if ($regexp) {
 3118: 	$regexp=&escape($regexp);
 3119:     } else {
 3120: 	$regexp='.';
 3121:     }
 3122:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3123:     my @pairs=split(/\&/,$rep);
 3124:     my %returnhash=();
 3125:     foreach my $item (@pairs) {
 3126: 	my ($key,$value)=split(/=/,$item,2);
 3127: 	$key = &unescape($key);
 3128: 	next if ($key =~ /^error: 2 /);
 3129: 	$returnhash{$key}=&thaw_unescape($value);
 3130:     }
 3131:     return %returnhash;
 3132: }
 3133: 
 3134: # --------------------------------------------------------- dumpstore interface
 3135: 
 3136: sub dumpstore {
 3137:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3138:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3139:    if (!$uname) { $uname=$env{'user.name'}; }
 3140:    my $uhome=&homeserver($uname,$udomain);
 3141:    if ($regexp) {
 3142:        $regexp=&escape($regexp);
 3143:    } else {
 3144:        $regexp='.';
 3145:    }
 3146:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3147:    my @pairs=split(/\&/,$rep);
 3148:    my %returnhash=();
 3149:    foreach my $item (@pairs) {
 3150:        my ($key,$value)=split(/=/,$item,2);
 3151:        next if ($key =~ /^error: 2 /);
 3152:        $returnhash{$key}=&thaw_unescape($value);
 3153:    }
 3154:    return %returnhash;
 3155: }
 3156: 
 3157: # -------------------------------------------------------------- keys interface
 3158: 
 3159: sub getkeys {
 3160:    my ($namespace,$udomain,$uname)=@_;
 3161:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3162:    if (!$uname) { $uname=$env{'user.name'}; }
 3163:    my $uhome=&homeserver($uname,$udomain);
 3164:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3165:    my @keyarray=();
 3166:    foreach my $key (split(/\&/,$rep)) {
 3167:       next if ($key =~ /^error: 2 /);
 3168:       push(@keyarray,&unescape($key));
 3169:    }
 3170:    return @keyarray;
 3171: }
 3172: 
 3173: # --------------------------------------------------------------- currentdump
 3174: sub currentdump {
 3175:    my ($courseid,$sdom,$sname)=@_;
 3176:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3177:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3178:    $sname    = $env{'user.name'}         if (! defined($sname));
 3179:    my $uhome = &homeserver($sname,$sdom);
 3180:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3181:    return if ($rep =~ /^(error:|no_such_host)/);
 3182:    #
 3183:    my %returnhash=();
 3184:    #
 3185:    if ($rep eq "unknown_cmd") { 
 3186:        # an old lond will not know currentdump
 3187:        # Do a dump and make it look like a currentdump
 3188:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3189:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3190:        my %hash = @tmp;
 3191:        @tmp=();
 3192:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3193:    } else {
 3194:        my @pairs=split(/\&/,$rep);
 3195:        foreach my $pair (@pairs) {
 3196:            my ($key,$value)=split(/=/,$pair,2);
 3197:            my ($symb,$param) = split(/:/,$key);
 3198:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3199:                                                         &thaw_unescape($value);
 3200:        }
 3201:    }
 3202:    return %returnhash;
 3203: }
 3204: 
 3205: sub convert_dump_to_currentdump{
 3206:     my %hash = %{shift()};
 3207:     my %returnhash;
 3208:     # Code ripped from lond, essentially.  The only difference
 3209:     # here is the unescaping done by lonnet::dump().  Conceivably
 3210:     # we might run in to problems with parameter names =~ /^v\./
 3211:     while (my ($key,$value) = each(%hash)) {
 3212:         my ($v,$symb,$param) = split(/:/,$key);
 3213: 	$symb  = &unescape($symb);
 3214: 	$param = &unescape($param);
 3215:         next if ($v eq 'version' || $symb eq 'keys');
 3216:         next if (exists($returnhash{$symb}) &&
 3217:                  exists($returnhash{$symb}->{$param}) &&
 3218:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3219:         $returnhash{$symb}->{$param}=$value;
 3220:         $returnhash{$symb}->{'v.'.$param}=$v;
 3221:     }
 3222:     #
 3223:     # Remove all of the keys in the hashes which keep track of
 3224:     # the version of the parameter.
 3225:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3226:         # use a foreach because we are going to delete from the hash.
 3227:         foreach my $key (keys(%$param_hash)) {
 3228:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3229:         }
 3230:     }
 3231:     return \%returnhash;
 3232: }
 3233: 
 3234: # ------------------------------------------------------ critical inc interface
 3235: 
 3236: sub cinc {
 3237:     return &inc(@_,'critical');
 3238: }
 3239: 
 3240: # --------------------------------------------------------------- inc interface
 3241: 
 3242: sub inc {
 3243:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3244:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3245:     if (!$uname) { $uname=$env{'user.name'}; }
 3246:     my $uhome=&homeserver($uname,$udomain);
 3247:     my $items='';
 3248:     if (! ref($store)) {
 3249:         # got a single value, so use that instead
 3250:         $items = &escape($store).'=&';
 3251:     } elsif (ref($store) eq 'SCALAR') {
 3252:         $items = &escape($$store).'=&';        
 3253:     } elsif (ref($store) eq 'ARRAY') {
 3254:         $items = join('=&',map {&escape($_);} @{$store});
 3255:     } elsif (ref($store) eq 'HASH') {
 3256:         while (my($key,$value) = each(%{$store})) {
 3257:             $items.= &escape($key).'='.&escape($value).'&';
 3258:         }
 3259:     }
 3260:     $items=~s/\&$//;
 3261:     if ($critical) {
 3262: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3263:     } else {
 3264: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3265:     }
 3266: }
 3267: 
 3268: # --------------------------------------------------------------- put interface
 3269: 
 3270: sub put {
 3271:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3273:    if (!$uname) { $uname=$env{'user.name'}; }
 3274:    my $uhome=&homeserver($uname,$udomain);
 3275:    my $items='';
 3276:    foreach my $item (keys(%$storehash)) {
 3277:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3278:    }
 3279:    $items=~s/\&$//;
 3280:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3281: }
 3282: 
 3283: # ------------------------------------------------------------ newput interface
 3284: 
 3285: sub newput {
 3286:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3288:    if (!$uname) { $uname=$env{'user.name'}; }
 3289:    my $uhome=&homeserver($uname,$udomain);
 3290:    my $items='';
 3291:    foreach my $key (keys(%$storehash)) {
 3292:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3293:    }
 3294:    $items=~s/\&$//;
 3295:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3296: }
 3297: 
 3298: # ---------------------------------------------------------  putstore interface
 3299: 
 3300: sub putstore {
 3301:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3302:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3303:    if (!$uname) { $uname=$env{'user.name'}; }
 3304:    my $uhome=&homeserver($uname,$udomain);
 3305:    my $items='';
 3306:    foreach my $key (keys(%$storehash)) {
 3307:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3308:    }
 3309:    $items=~s/\&$//;
 3310:    my $esc_symb=&escape($symb);
 3311:    my $esc_v=&escape($version);
 3312:    my $reply =
 3313:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3314: 	      $uhome);
 3315:    if ($reply eq 'unknown_cmd') {
 3316:        # gfall back to way things use to be done
 3317:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3318: 			    $uname);
 3319:    }
 3320:    return $reply;
 3321: }
 3322: 
 3323: sub old_putstore {
 3324:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3325:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3326:     if (!$uname) { $uname=$env{'user.name'}; }
 3327:     my $uhome=&homeserver($uname,$udomain);
 3328:     my %newstorehash;
 3329:     foreach my $item (keys(%$storehash)) {
 3330: 	my $key = $version.':'.&escape($symb).':'.$item;
 3331: 	$newstorehash{$key} = $storehash->{$item};
 3332:     }
 3333:     my $items='';
 3334:     my %allitems = ();
 3335:     foreach my $item (keys(%newstorehash)) {
 3336: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3337: 	    my $key = $1.':keys:'.$2;
 3338: 	    $allitems{$key} .= $3.':';
 3339: 	}
 3340: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3341:     }
 3342:     foreach my $item (keys(%allitems)) {
 3343: 	$allitems{$item} =~ s/\:$//;
 3344: 	$items.= $item.'='.$allitems{$item}.'&';
 3345:     }
 3346:     $items=~s/\&$//;
 3347:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3348: }
 3349: 
 3350: # ------------------------------------------------------ critical put interface
 3351: 
 3352: sub cput {
 3353:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3354:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3355:    if (!$uname) { $uname=$env{'user.name'}; }
 3356:    my $uhome=&homeserver($uname,$udomain);
 3357:    my $items='';
 3358:    foreach my $item (keys(%$storehash)) {
 3359:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3360:    }
 3361:    $items=~s/\&$//;
 3362:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3363: }
 3364: 
 3365: # -------------------------------------------------------------- eget interface
 3366: 
 3367: sub eget {
 3368:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3369:    my $items='';
 3370:    foreach my $item (@$storearr) {
 3371:        $items.=&escape($item).'&';
 3372:    }
 3373:    $items=~s/\&$//;
 3374:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3375:    if (!$uname) { $uname=$env{'user.name'}; }
 3376:    my $uhome=&homeserver($uname,$udomain);
 3377:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3378:    my @pairs=split(/\&/,$rep);
 3379:    my %returnhash=();
 3380:    my $i=0;
 3381:    foreach my $item (@$storearr) {
 3382:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3383:       $i++;
 3384:    }
 3385:    return %returnhash;
 3386: }
 3387: 
 3388: # ------------------------------------------------------------ tmpput interface
 3389: sub tmpput {
 3390:     my ($storehash,$server,$context)=@_;
 3391:     my $items='';
 3392:     foreach my $item (keys(%$storehash)) {
 3393: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3394:     }
 3395:     $items=~s/\&$//;
 3396:     if (defined($context)) {
 3397:         $items .= ':'.&escape($context);
 3398:     }
 3399:     return &reply("tmpput:$items",$server);
 3400: }
 3401: 
 3402: # ------------------------------------------------------------ tmpget interface
 3403: sub tmpget {
 3404:     my ($token,$server)=@_;
 3405:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3406:     my $rep=&reply("tmpget:$token",$server);
 3407:     my %returnhash;
 3408:     foreach my $item (split(/\&/,$rep)) {
 3409: 	my ($key,$value)=split(/=/,$item);
 3410: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3411:     }
 3412:     return %returnhash;
 3413: }
 3414: 
 3415: # ------------------------------------------------------------ tmpget interface
 3416: sub tmpdel {
 3417:     my ($token,$server)=@_;
 3418:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3419:     return &reply("tmpdel:$token",$server);
 3420: }
 3421: 
 3422: # -------------------------------------------------- portfolio access checking
 3423: 
 3424: sub portfolio_access {
 3425:     my ($requrl) = @_;
 3426:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3427:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3428:     if ($result) {
 3429:         my %setters;
 3430:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3431:             my ($startblock,$endblock) =
 3432:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3433:             if ($startblock && $endblock) {
 3434:                 return 'B';
 3435:             }
 3436:         } else {
 3437:             my ($startblock,$endblock) =
 3438:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3439:             if ($startblock && $endblock) {
 3440:                 return 'B';
 3441:             }
 3442:         }
 3443:     }
 3444:     if ($result eq 'ok') {
 3445:        return 'F';
 3446:     } elsif ($result =~ /^[^:]+:guest_/) {
 3447:        return 'A';
 3448:     }
 3449:     return '';
 3450: }
 3451: 
 3452: sub get_portfolio_access {
 3453:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3454: 
 3455:     if (!ref($access_hash)) {
 3456: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3457: 	my %access_controls = &get_access_controls($current_perms,$group,
 3458: 						   $file_name);
 3459: 	$access_hash = $access_controls{$file_name};
 3460:     }
 3461: 
 3462:     my ($public,$guest,@domains,@users,@courses,@groups);
 3463:     my $now = time;
 3464:     if (ref($access_hash) eq 'HASH') {
 3465:         foreach my $key (keys(%{$access_hash})) {
 3466:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3467:             if ($start > $now) {
 3468:                 next;
 3469:             }
 3470:             if ($end && $end<$now) {
 3471:                 next;
 3472:             }
 3473:             if ($scope eq 'public') {
 3474:                 $public = $key;
 3475:                 last;
 3476:             } elsif ($scope eq 'guest') {
 3477:                 $guest = $key;
 3478:             } elsif ($scope eq 'domains') {
 3479:                 push(@domains,$key);
 3480:             } elsif ($scope eq 'users') {
 3481:                 push(@users,$key);
 3482:             } elsif ($scope eq 'course') {
 3483:                 push(@courses,$key);
 3484:             } elsif ($scope eq 'group') {
 3485:                 push(@groups,$key);
 3486:             }
 3487:         }
 3488:         if ($public) {
 3489:             return 'ok';
 3490:         }
 3491:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3492:             if ($guest) {
 3493:                 return $guest;
 3494:             }
 3495:         } else {
 3496:             if (@domains > 0) {
 3497:                 foreach my $domkey (@domains) {
 3498:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3499:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3500:                             return 'ok';
 3501:                         }
 3502:                     }
 3503:                 }
 3504:             }
 3505:             if (@users > 0) {
 3506:                 foreach my $userkey (@users) {
 3507:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3508:                         return 'ok';
 3509:                     }
 3510:                 }
 3511:             }
 3512:             my %roleshash;
 3513:             my @courses_and_groups = @courses;
 3514:             push(@courses_and_groups,@groups); 
 3515:             if (@courses_and_groups > 0) {
 3516:                 my (%allgroups,%allroles); 
 3517:                 my ($start,$end,$role,$sec,$group);
 3518:                 foreach my $envkey (%env) {
 3519:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3520:                         my $cid = $2.'_'.$3; 
 3521:                         if ($1 eq 'gr') {
 3522:                             $group = $4;
 3523:                             $allgroups{$cid}{$group} = $env{$envkey};
 3524:                         } else {
 3525:                             if ($4 eq '') {
 3526:                                 $sec = 'none';
 3527:                             } else {
 3528:                                 $sec = $4;
 3529:                             }
 3530:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3531:                         }
 3532:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3533:                         my $cid = $2.'_'.$3;
 3534:                         if ($4 eq '') {
 3535:                             $sec = 'none';
 3536:                         } else {
 3537:                             $sec = $4;
 3538:                         }
 3539:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3540:                     }
 3541:                 }
 3542:                 if (keys(%allroles) == 0) {
 3543:                     return;
 3544:                 }
 3545:                 foreach my $key (@courses_and_groups) {
 3546:                     my %content = %{$$access_hash{$key}};
 3547:                     my $cnum = $content{'number'};
 3548:                     my $cdom = $content{'domain'};
 3549:                     my $cid = $cdom.'_'.$cnum;
 3550:                     if (!exists($allroles{$cid})) {
 3551:                         next;
 3552:                     }    
 3553:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3554:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3555:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3556:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3557:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3558:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3559:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3560:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3561:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3562:                                         if (grep/^all$/,@sections) {
 3563:                                             return 'ok';
 3564:                                         } else {
 3565:                                             if (grep/^$sec$/,@sections) {
 3566:                                                 return 'ok';
 3567:                                             }
 3568:                                         }
 3569:                                     }
 3570:                                 }
 3571:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3572:                                     if (grep/^none$/,@groups) {
 3573:                                         return 'ok';
 3574:                                     }
 3575:                                 } else {
 3576:                                     if (grep/^all$/,@groups) {
 3577:                                         return 'ok';
 3578:                                     } 
 3579:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3580:                                         if (grep/^$group$/,@groups) {
 3581:                                             return 'ok';
 3582:                                         }
 3583:                                     }
 3584:                                 } 
 3585:                             }
 3586:                         }
 3587:                     }
 3588:                 }
 3589:             }
 3590:             if ($guest) {
 3591:                 return $guest;
 3592:             }
 3593:         }
 3594:     }
 3595:     return;
 3596: }
 3597: 
 3598: sub course_group_datechecker {
 3599:     my ($dates,$now,$status) = @_;
 3600:     my ($start,$end) = split(/\./,$dates);
 3601:     if (!$start && !$end) {
 3602:         return 'ok';
 3603:     }
 3604:     if (grep/^active$/,@{$status}) {
 3605:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3606:             return 'ok';
 3607:         }
 3608:     }
 3609:     if (grep/^previous$/,@{$status}) {
 3610:         if ($end > $now ) {
 3611:             return 'ok';
 3612:         }
 3613:     }
 3614:     if (grep/^future$/,@{$status}) {
 3615:         if ($start > $now) {
 3616:             return 'ok';
 3617:         }
 3618:     }
 3619:     return; 
 3620: }
 3621: 
 3622: sub parse_portfolio_url {
 3623:     my ($url) = @_;
 3624: 
 3625:     my ($type,$udom,$unum,$group,$file_name);
 3626:     
 3627:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3628: 	$type = 1;
 3629:         $udom = $1;
 3630:         $unum = $2;
 3631:         $file_name = $3;
 3632:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3633: 	$type = 2;
 3634:         $udom = $1;
 3635:         $unum = $2;
 3636:         $group = $3;
 3637:         $file_name = $3.'/'.$4;
 3638:     }
 3639:     if (wantarray) {
 3640: 	return ($type,$udom,$unum,$file_name,$group);
 3641:     }
 3642:     return $type;
 3643: }
 3644: 
 3645: sub is_portfolio_url {
 3646:     my ($url) = @_;
 3647:     return scalar(&parse_portfolio_url($url));
 3648: }
 3649: 
 3650: sub is_portfolio_file {
 3651:     my ($file) = @_;
 3652:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3653:         return 1;
 3654:     }
 3655:     return;
 3656: }
 3657: 
 3658: 
 3659: # ---------------------------------------------- Custom access rule evaluation
 3660: 
 3661: sub customaccess {
 3662:     my ($priv,$uri)=@_;
 3663:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3664:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3665:     $udom = &LONCAPA::clean_domain($udom);
 3666:     $ucrs = &LONCAPA::clean_username($ucrs);
 3667:     my $access=0;
 3668:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3669: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3670:         if ($role) {
 3671: 	   if ($role ne $urole) { next; }
 3672:         }
 3673:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3674:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3675:             if ($tdom) {
 3676: 		if ($tdom ne $udom) { next; }
 3677:             }
 3678:             if ($tcrs) {
 3679: 		if ($tcrs ne $ucrs) { next; }
 3680:             }
 3681:             if ($tsec) {
 3682: 		if ($tsec ne $usec) { next; }
 3683:             }
 3684:             $access=($effect eq 'allow');
 3685:             last;
 3686:         }
 3687: 	if ($realm eq '' && $role eq '') {
 3688:             $access=($effect eq 'allow');
 3689: 	}
 3690:     }
 3691:     return $access;
 3692: }
 3693: 
 3694: # ------------------------------------------------- Check for a user privilege
 3695: 
 3696: sub allowed {
 3697:     my ($priv,$uri,$symb,$role)=@_;
 3698:     my $ver_orguri=$uri;
 3699:     $uri=&deversion($uri);
 3700:     my $orguri=$uri;
 3701:     $uri=&declutter($uri);
 3702: 
 3703:     if ($priv eq 'evb') {
 3704: # Evade communication block restrictions for specified role in a course
 3705:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3706:             return $1;
 3707:         } else {
 3708:             return;
 3709:         }
 3710:     }
 3711: 
 3712:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3713: # Free bre access to adm and meta resources
 3714:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3715: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3716: 	&& ($priv eq 'bre')) {
 3717: 	return 'F';
 3718:     }
 3719: 
 3720: # Free bre access to user's own portfolio contents
 3721:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3722:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3723: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3724:         my %setters;
 3725:         my ($startblock,$endblock) = 
 3726:             &Apache::loncommon::blockcheck(\%setters,'port');
 3727:         if ($startblock && $endblock) {
 3728:             return 'B';
 3729:         } else {
 3730:             return 'F';
 3731:         }
 3732:     }
 3733: 
 3734: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3735:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3736:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3737:         if (exists($env{'request.course.id'})) {
 3738:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3739:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3740:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3741:                 my $courseprivid=$env{'request.course.id'};
 3742:                 $courseprivid=~s/\_/\//;
 3743:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3744:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3745:                     return $1; 
 3746:                 } else {
 3747:                     if ($env{'request.course.sec'}) {
 3748:                         $courseprivid.='/'.$env{'request.course.sec'};
 3749:                     }
 3750:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3751:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3752:                         return $2;
 3753:                     }
 3754:                 }
 3755:             }
 3756:         }
 3757:     }
 3758: 
 3759: # Free bre to public access
 3760: 
 3761:     if ($priv eq 'bre') {
 3762:         my $copyright=&metadata($uri,'copyright');
 3763: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3764:            return 'F'; 
 3765:         }
 3766:         if ($copyright eq 'priv') {
 3767:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3768: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3769: 		return '';
 3770:             }
 3771:         }
 3772:         if ($copyright eq 'domain') {
 3773:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3774: 	    unless (($env{'user.domain'} eq $1) ||
 3775:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3776: 		return '';
 3777:             }
 3778:         }
 3779:         if ($env{'request.role'}=~ /li\.\//) {
 3780:             # Library role, so allow browsing of resources in this domain.
 3781:             return 'F';
 3782:         }
 3783:         if ($copyright eq 'custom') {
 3784: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3785:         }
 3786:     }
 3787:     # Domain coordinator is trying to create a course
 3788:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3789:         # uri is the requested domain in this case.
 3790:         # comparison to 'request.role.domain' shows if the user has selected
 3791:         # a role of dc for the domain in question.
 3792:         return 'F' if ($uri eq $env{'request.role.domain'});
 3793:     }
 3794: 
 3795:     my $thisallowed='';
 3796:     my $statecond=0;
 3797:     my $courseprivid='';
 3798: 
 3799: # Course
 3800: 
 3801:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3802:        $thisallowed.=$1;
 3803:     }
 3804: 
 3805: # Domain
 3806: 
 3807:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3808:        =~/\Q$priv\E\&([^\:]*)/) {
 3809:        $thisallowed.=$1;
 3810:     }
 3811: 
 3812: # Course: uri itself is a course
 3813:     my $courseuri=$uri;
 3814:     $courseuri=~s/\_(\d)/\/$1/;
 3815:     $courseuri=~s/^([^\/])/\/$1/;
 3816: 
 3817:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3818:        =~/\Q$priv\E\&([^\:]*)/) {
 3819:        $thisallowed.=$1;
 3820:     }
 3821: 
 3822: # URI is an uploaded document for this course, default permissions don't matter
 3823: # not allowing 'edit' access (editupload) to uploaded course docs
 3824:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3825: 	$thisallowed='';
 3826:         my ($match)=&is_on_map($uri);
 3827:         if ($match) {
 3828:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3829:                   =~/\Q$priv\E\&([^\:]*)/) {
 3830:                 $thisallowed.=$1;
 3831:             }
 3832:         } else {
 3833:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3834:             if ($refuri) {
 3835:                 if ($refuri =~ m|^/adm/|) {
 3836:                     $thisallowed='F';
 3837:                 } else {
 3838:                     $refuri=&declutter($refuri);
 3839:                     my ($match) = &is_on_map($refuri);
 3840:                     if ($match) {
 3841:                         $thisallowed='F';
 3842:                     }
 3843:                 }
 3844:             }
 3845:         }
 3846:     }
 3847: 
 3848:     if ($priv eq 'bre'
 3849: 	&& $thisallowed ne 'F' 
 3850: 	&& $thisallowed ne '2'
 3851: 	&& &is_portfolio_url($uri)) {
 3852: 	$thisallowed = &portfolio_access($uri);
 3853:     }
 3854:     
 3855: # Full access at system, domain or course-wide level? Exit.
 3856: 
 3857:     if ($thisallowed=~/F/) {
 3858: 	return 'F';
 3859:     }
 3860: 
 3861: # If this is generating or modifying users, exit with special codes
 3862: 
 3863:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3864: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3865: 	    my ($audom,$auname)=split('/',$uri);
 3866: # no author name given, so this just checks on the general right to make a co-author in this domain
 3867: 	    unless ($auname) { return $thisallowed; }
 3868: # an author name is given, so we are about to actually make a co-author for a certain account
 3869: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3870: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3871: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3872: 	}
 3873: 	return $thisallowed;
 3874:     }
 3875: #
 3876: # Gathered so far: system, domain and course wide privileges
 3877: #
 3878: # Course: See if uri or referer is an individual resource that is part of 
 3879: # the course
 3880: 
 3881:     if ($env{'request.course.id'}) {
 3882: 
 3883:        $courseprivid=$env{'request.course.id'};
 3884:        if ($env{'request.course.sec'}) {
 3885:           $courseprivid.='/'.$env{'request.course.sec'};
 3886:        }
 3887:        $courseprivid=~s/\_/\//;
 3888:        my $checkreferer=1;
 3889:        my ($match,$cond)=&is_on_map($uri);
 3890:        if ($match) {
 3891:            $statecond=$cond;
 3892:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3893:                =~/\Q$priv\E\&([^\:]*)/) {
 3894:                $thisallowed.=$1;
 3895:                $checkreferer=0;
 3896:            }
 3897:        }
 3898:        
 3899:        if ($checkreferer) {
 3900: 	  my $refuri=$env{'httpref.'.$orguri};
 3901:             unless ($refuri) {
 3902:                 foreach my $key (keys(%env)) {
 3903: 		    if ($key=~/^httpref\..*\*/) {
 3904: 			my $pattern=$key;
 3905:                         $pattern=~s/^httpref\.\/res\///;
 3906:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3907:                         $pattern=~s/\//\\\//g;
 3908:                         if ($orguri=~/$pattern/) {
 3909: 			    $refuri=$env{$key};
 3910:                         }
 3911:                     }
 3912:                 }
 3913:             }
 3914: 
 3915:          if ($refuri) { 
 3916: 	  $refuri=&declutter($refuri);
 3917:           my ($match,$cond)=&is_on_map($refuri);
 3918:             if ($match) {
 3919:               my $refstatecond=$cond;
 3920:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3921:                   =~/\Q$priv\E\&([^\:]*)/) {
 3922:                   $thisallowed.=$1;
 3923:                   $uri=$refuri;
 3924:                   $statecond=$refstatecond;
 3925:               }
 3926:           }
 3927:         }
 3928:        }
 3929:    }
 3930: 
 3931: #
 3932: # Gathered now: all privileges that could apply, and condition number
 3933: # 
 3934: #
 3935: # Full or no access?
 3936: #
 3937: 
 3938:     if ($thisallowed=~/F/) {
 3939: 	return 'F';
 3940:     }
 3941: 
 3942:     unless ($thisallowed) {
 3943:         return '';
 3944:     }
 3945: 
 3946: # Restrictions exist, deal with them
 3947: #
 3948: #   C:according to course preferences
 3949: #   R:according to resource settings
 3950: #   L:unless locked
 3951: #   X:according to user session state
 3952: #
 3953: 
 3954: # Possibly locked functionality, check all courses
 3955: # Locks might take effect only after 10 minutes cache expiration for other
 3956: # courses, and 2 minutes for current course
 3957: 
 3958:     my $envkey;
 3959:     if ($thisallowed=~/L/) {
 3960:         foreach $envkey (keys %env) {
 3961:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3962:                my $courseid=$2;
 3963:                my $roleid=$1.'.'.$2;
 3964:                $courseid=~s/^\///;
 3965:                my $expiretime=600;
 3966:                if ($env{'request.role'} eq $roleid) {
 3967: 		  $expiretime=120;
 3968:                }
 3969: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3970:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3971:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3972: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3973:                }
 3974:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3975:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3976: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3977:                        &log($env{'user.domain'},$env{'user.name'},
 3978:                             $env{'user.home'},
 3979:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3980:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3981:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3982: 		       return '';
 3983:                    }
 3984:                }
 3985:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3986:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3987: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3988:                        &log($env{'user.domain'},$env{'user.name'},
 3989:                             $env{'user.home'},
 3990:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3991:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3992:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3993: 		       return '';
 3994:                    }
 3995:                }
 3996: 	   }
 3997:        }
 3998:     }
 3999:    
 4000: #
 4001: # Rest of the restrictions depend on selected course
 4002: #
 4003: 
 4004:     unless ($env{'request.course.id'}) {
 4005: 	if ($thisallowed eq 'A') {
 4006: 	    return 'A';
 4007:         } elsif ($thisallowed eq 'B') {
 4008:             return 'B';
 4009: 	} else {
 4010: 	    return '1';
 4011: 	}
 4012:     }
 4013: 
 4014: #
 4015: # Now user is definitely in a course
 4016: #
 4017: 
 4018: 
 4019: # Course preferences
 4020: 
 4021:    if ($thisallowed=~/C/) {
 4022:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4023:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4024:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4025: 	   =~/\Q$rolecode\E/) {
 4026: 	   if ($priv ne 'pch') { 
 4027: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4028: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4029: 			$env{'request.course.id'});
 4030: 	   }
 4031:            return '';
 4032:        }
 4033: 
 4034:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4035: 	   =~/\Q$unamedom\E/) {
 4036: 	   if ($priv ne 'pch') { 
 4037: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4038: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4039: 			$env{'request.course.id'});
 4040: 	   }
 4041:            return '';
 4042:        }
 4043:    }
 4044: 
 4045: # Resource preferences
 4046: 
 4047:    if ($thisallowed=~/R/) {
 4048:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4049:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4050: 	   if ($priv ne 'pch') { 
 4051: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4052: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4053: 	   }
 4054: 	   return '';
 4055:        }
 4056:    }
 4057: 
 4058: # Restricted by state or randomout?
 4059: 
 4060:    if ($thisallowed=~/X/) {
 4061:       if ($env{'acc.randomout'}) {
 4062: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4063:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4064:             return ''; 
 4065:          }
 4066:       }
 4067:       if (&condval($statecond)) {
 4068: 	 return '2';
 4069:       } else {
 4070:          return '';
 4071:       }
 4072:    }
 4073: 
 4074:     if ($thisallowed eq 'A') {
 4075: 	return 'A';
 4076:     } elsif ($thisallowed eq 'B') {
 4077:         return 'B';
 4078:     }
 4079:    return 'F';
 4080: }
 4081: 
 4082: sub split_uri_for_cond {
 4083:     my $uri=&deversion(&declutter(shift));
 4084:     my @uriparts=split(/\//,$uri);
 4085:     my $filename=pop(@uriparts);
 4086:     my $pathname=join('/',@uriparts);
 4087:     return ($pathname,$filename);
 4088: }
 4089: # --------------------------------------------------- Is a resource on the map?
 4090: 
 4091: sub is_on_map {
 4092:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4093:     #Trying to find the conditional for the file
 4094:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4095: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4096:     if ($match) {
 4097: 	return (1,$1);
 4098:     } else {
 4099: 	return (0,0);
 4100:     }
 4101: }
 4102: 
 4103: # --------------------------------------------------------- Get symb from alias
 4104: 
 4105: sub get_symb_from_alias {
 4106:     my $symb=shift;
 4107:     my ($map,$resid,$url)=&decode_symb($symb);
 4108: # Already is a symb
 4109:     if ($url) { return $symb; }
 4110: # Must be an alias
 4111:     my $aliassymb='';
 4112:     my %bighash;
 4113:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4114:                             &GDBM_READER(),0640)) {
 4115:         my $rid=$bighash{'mapalias_'.$symb};
 4116: 	if ($rid) {
 4117: 	    my ($mapid,$resid)=split(/\./,$rid);
 4118: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4119: 				    $resid,$bighash{'src_'.$rid});
 4120: 	}
 4121:         untie %bighash;
 4122:     }
 4123:     return $aliassymb;
 4124: }
 4125: 
 4126: # ----------------------------------------------------------------- Define Role
 4127: 
 4128: sub definerole {
 4129:   if (allowed('mcr','/')) {
 4130:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4131:     foreach my $role (split(':',$sysrole)) {
 4132: 	my ($crole,$cqual)=split(/\&/,$role);
 4133:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4134:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4135: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4136:                return "refused:s:$crole&$cqual"; 
 4137:             }
 4138:         }
 4139:     }
 4140:     foreach my $role (split(':',$domrole)) {
 4141: 	my ($crole,$cqual)=split(/\&/,$role);
 4142:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4143:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4144: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4145:                return "refused:d:$crole&$cqual"; 
 4146:             }
 4147:         }
 4148:     }
 4149:     foreach my $role (split(':',$courole)) {
 4150: 	my ($crole,$cqual)=split(/\&/,$role);
 4151:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4152:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4153: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4154:                return "refused:c:$crole&$cqual"; 
 4155:             }
 4156:         }
 4157:     }
 4158:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4159:                 "$env{'user.domain'}:$env{'user.name'}:".
 4160: 	        "rolesdef_$rolename=".
 4161:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4162:     return reply($command,$env{'user.home'});
 4163:   } else {
 4164:     return 'refused';
 4165:   }
 4166: }
 4167: 
 4168: # ---------------- Make a metadata query against the network of library servers
 4169: 
 4170: sub metadata_query {
 4171:     my ($query,$custom,$customshow,$server_array)=@_;
 4172:     my %rhash;
 4173:     my @server_list = (defined($server_array) ? @$server_array
 4174:                                               : keys(%libserv) );
 4175:     for my $server (@server_list) {
 4176: 	unless ($custom or $customshow) {
 4177: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4178: 	    $rhash{$server}=$reply;
 4179: 	}
 4180: 	else {
 4181: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4182: 			     &escape($custom).':'.&escape($customshow),
 4183: 			     $server);
 4184: 	    $rhash{$server}=$reply;
 4185: 	}
 4186:     }
 4187:     return \%rhash;
 4188: }
 4189: 
 4190: # ----------------------------------------- Send log queries and wait for reply
 4191: 
 4192: sub log_query {
 4193:     my ($uname,$udom,$query,%filters)=@_;
 4194:     my $uhome=&homeserver($uname,$udom);
 4195:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4196:     my $uhost=&hostname($uhome);
 4197:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4198:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4199:                        $uhome);
 4200:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4201:     return get_query_reply($queryid);
 4202: }
 4203: 
 4204: # -------------------------- Update MySQL table for portfolio file
 4205: 
 4206: sub update_portfolio_table {
 4207:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4208:     my $homeserver = &homeserver($uname,$udom);
 4209:     my $queryid=
 4210:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4211:                ':'.&escape($file_name).':'.$action,$homeserver);
 4212:     my $reply = &get_query_reply($queryid);
 4213:     return $reply;
 4214: }
 4215: 
 4216: # ------- Request retrieval of institutional classlists for course(s)
 4217: 
 4218: sub fetch_enrollment_query {
 4219:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4220:     my $homeserver;
 4221:     my $maxtries = 1;
 4222:     if ($context eq 'automated') {
 4223:         $homeserver = $perlvar{'lonHostID'};
 4224:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4225:     } else {
 4226:         $homeserver = &homeserver($cnum,$dom);
 4227:     }
 4228:     my $host=&hostname($homeserver);
 4229:     my $cmd = '';
 4230:     foreach my $affiliate (keys %{$affiliatesref}) {
 4231:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4232:     }
 4233:     $cmd =~ s/%%$//;
 4234:     $cmd = &escape($cmd);
 4235:     my $query = 'fetchenrollment';
 4236:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4237:     unless ($queryid=~/^\Q$host\E\_/) { 
 4238:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4239:         return 'error: '.$queryid;
 4240:     }
 4241:     my $reply = &get_query_reply($queryid);
 4242:     my $tries = 1;
 4243:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4244:         $reply = &get_query_reply($queryid);
 4245:         $tries ++;
 4246:     }
 4247:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4248:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4249:     } else {
 4250:         my @responses = split/:/,$reply;
 4251:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4252:             foreach my $line (@responses) {
 4253:                 my ($key,$value) = split(/=/,$line,2);
 4254:                 $$replyref{$key} = $value;
 4255:             }
 4256:         } else {
 4257:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4258:             foreach my $line (@responses) {
 4259:                 my ($key,$value) = split(/=/,$line);
 4260:                 $$replyref{$key} = $value;
 4261:                 if ($value > 0) {
 4262:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4263:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4264:                         my $destname = $pathname.'/'.$filename;
 4265:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4266:                         if ($xml_classlist =~ /^error/) {
 4267:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4268:                         } else {
 4269:                             if ( open(FILE,">$destname") ) {
 4270:                                 print FILE &unescape($xml_classlist);
 4271:                                 close(FILE);
 4272:                             } else {
 4273:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4274:                             }
 4275:                         }
 4276:                     }
 4277:                 }
 4278:             }
 4279:         }
 4280:         return 'ok';
 4281:     }
 4282:     return 'error';
 4283: }
 4284: 
 4285: sub get_query_reply {
 4286:     my $queryid=shift;
 4287:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4288:     my $reply='';
 4289:     for (1..100) {
 4290: 	sleep 2;
 4291:         if (-e $replyfile.'.end') {
 4292: 	    if (open(my $fh,$replyfile)) {
 4293:                $reply.=<$fh>;
 4294:                close($fh);
 4295: 	   } else { return 'error: reply_file_error'; }
 4296:            return &unescape($reply);
 4297: 	}
 4298:     }
 4299:     return 'timeout:'.$queryid;
 4300: }
 4301: 
 4302: sub courselog_query {
 4303: #
 4304: # possible filters:
 4305: # url: url or symb
 4306: # username
 4307: # domain
 4308: # action: view, submit, grade
 4309: # start: timestamp
 4310: # end: timestamp
 4311: #
 4312:     my (%filters)=@_;
 4313:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4314:     if ($filters{'url'}) {
 4315: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4316:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4317:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4318:     }
 4319:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4320:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4321:     return &log_query($cname,$cdom,'courselog',%filters);
 4322: }
 4323: 
 4324: sub userlog_query {
 4325:     my ($uname,$udom,%filters)=@_;
 4326:     return &log_query($uname,$udom,'userlog',%filters);
 4327: }
 4328: 
 4329: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4330: 
 4331: sub auto_run {
 4332:     my ($cnum,$cdom) = @_;
 4333:     my $homeserver = &homeserver($cnum,$cdom);
 4334:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4335:     return $response;
 4336: }
 4337: 
 4338: sub auto_get_sections {
 4339:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4340:     my $homeserver = &homeserver($cnum,$cdom);
 4341:     my @secs = ();
 4342:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4343:     unless ($response eq 'refused') {
 4344:         @secs = split/:/,$response;
 4345:     }
 4346:     return @secs;
 4347: }
 4348: 
 4349: sub auto_new_course {
 4350:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4351:     my $homeserver = &homeserver($cnum,$cdom);
 4352:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4353:     return $response;
 4354: }
 4355: 
 4356: sub auto_validate_courseID {
 4357:     my ($cnum,$cdom,$inst_course_id) = @_;
 4358:     my $homeserver = &homeserver($cnum,$cdom);
 4359:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4360:     return $response;
 4361: }
 4362: 
 4363: sub auto_create_password {
 4364:     my ($cnum,$cdom,$authparam) = @_;
 4365:     my $homeserver = &homeserver($cnum,$cdom); 
 4366:     my $create_passwd = 0;
 4367:     my $authchk = '';
 4368:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4369:     if ($response eq 'refused') {
 4370:         $authchk = 'refused';
 4371:     } else {
 4372:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4373:     }
 4374:     return ($authparam,$create_passwd,$authchk);
 4375: }
 4376: 
 4377: sub auto_photo_permission {
 4378:     my ($cnum,$cdom,$students) = @_;
 4379:     my $homeserver = &homeserver($cnum,$cdom);
 4380:     my ($outcome,$perm_reqd,$conditions) = 
 4381: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4382:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4383: 	return (undef,undef);
 4384:     }
 4385:     return ($outcome,$perm_reqd,$conditions);
 4386: }
 4387: 
 4388: sub auto_checkphotos {
 4389:     my ($uname,$udom,$pid) = @_;
 4390:     my $homeserver = &homeserver($uname,$udom);
 4391:     my ($result,$resulttype);
 4392:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4393: 				   &escape($uname).':'.&escape($pid),
 4394: 				   $homeserver));
 4395:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4396: 	return (undef,undef);
 4397:     }
 4398:     if ($outcome) {
 4399:         ($result,$resulttype) = split(/:/,$outcome);
 4400:     } 
 4401:     return ($result,$resulttype);
 4402: }
 4403: 
 4404: sub auto_photochoice {
 4405:     my ($cnum,$cdom) = @_;
 4406:     my $homeserver = &homeserver($cnum,$cdom);
 4407:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4408: 						       &escape($cdom),
 4409: 						       $homeserver)));
 4410:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4411: 	return (undef,undef);
 4412:     }
 4413:     return ($update,$comment);
 4414: }
 4415: 
 4416: sub auto_photoupdate {
 4417:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4418:     my $homeserver = &homeserver($cnum,$dom);
 4419:     my $host=&hostname($homeserver);
 4420:     my $cmd = '';
 4421:     my $maxtries = 1;
 4422:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4423:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4424:     }
 4425:     $cmd =~ s/%%$//;
 4426:     $cmd = &escape($cmd);
 4427:     my $query = 'institutionalphotos';
 4428:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4429:     unless ($queryid=~/^\Q$host\E\_/) {
 4430:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4431:         return 'error: '.$queryid;
 4432:     }
 4433:     my $reply = &get_query_reply($queryid);
 4434:     my $tries = 1;
 4435:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4436:         $reply = &get_query_reply($queryid);
 4437:         $tries ++;
 4438:     }
 4439:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4440:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4441:     } else {
 4442:         my @responses = split(/:/,$reply);
 4443:         my $outcome = shift(@responses); 
 4444:         foreach my $item (@responses) {
 4445:             my ($key,$value) = split(/=/,$item);
 4446:             $$photo{$key} = $value;
 4447:         }
 4448:         return $outcome;
 4449:     }
 4450:     return 'error';
 4451: }
 4452: 
 4453: sub auto_instcode_format {
 4454:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4455: 	$cat_order) = @_;
 4456:     my $courses = '';
 4457:     my @homeservers;
 4458:     if ($caller eq 'global') {
 4459: 	my %servers = &get_servers($codedom,'library');
 4460: 	foreach my $tryserver (keys(%servers)) {
 4461: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4462: 		push(@homeservers,$tryserver);
 4463: 	    }
 4464:         }
 4465:     } else {
 4466:         push(@homeservers,&homeserver($caller,$codedom));
 4467:     }
 4468:     foreach my $code (keys(%{$instcodes})) {
 4469:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4470:     }
 4471:     chop($courses);
 4472:     my $ok_response = 0;
 4473:     my $response;
 4474:     while (@homeservers > 0 && $ok_response == 0) {
 4475:         my $server = shift(@homeservers); 
 4476:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4477:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4478:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4479: 		split/:/,$response;
 4480:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4481:             push(@{$codetitles},&str2array($codetitles_str));
 4482:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4483:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4484:             $ok_response = 1;
 4485:         }
 4486:     }
 4487:     if ($ok_response) {
 4488:         return 'ok';
 4489:     } else {
 4490:         return $response;
 4491:     }
 4492: }
 4493: 
 4494: sub auto_instcode_defaults {
 4495:     my ($domain,$returnhash,$code_order) = @_;
 4496:     my @homeservers;
 4497: 
 4498:     my %servers = &get_servers($domain,'library');
 4499:     foreach my $tryserver (keys(%servers)) {
 4500: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4501: 	    push(@homeservers,$tryserver);
 4502: 	}
 4503:     }
 4504: 
 4505:     my $response;
 4506:     foreach my $server (@homeservers) {
 4507:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4508:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4509: 	
 4510: 	foreach my $pair (split(/\&/,$response)) {
 4511: 	    my ($name,$value)=split(/\=/,$pair);
 4512: 	    if ($name eq 'code_order') {
 4513: 		@{$code_order} = split(/\&/,&unescape($value));
 4514: 	    } else {
 4515: 		$returnhash->{&unescape($name)}=&unescape($value);
 4516: 	    }
 4517: 	}
 4518: 	return 'ok';
 4519:     }
 4520: 
 4521:     return $response;
 4522: } 
 4523: 
 4524: sub auto_validate_class_sec {
 4525:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4526:     my $homeserver = &homeserver($cnum,$cdom);
 4527:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4528:                         &escape($owner).':'.$cdom,$homeserver);
 4529:     return $response;
 4530: }
 4531: 
 4532: # ------------------------------------------------------- Course Group routines
 4533: 
 4534: sub get_coursegroups {
 4535:     my ($cdom,$cnum,$group,$namespace) = @_;
 4536:     return(&dump($namespace,$cdom,$cnum,$group));
 4537: }
 4538: 
 4539: sub modify_coursegroup {
 4540:     my ($cdom,$cnum,$groupsettings) = @_;
 4541:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4542: }
 4543: 
 4544: sub toggle_coursegroup_status {
 4545:     my ($cdom,$cnum,$group,$action) = @_;
 4546:     my ($from_namespace,$to_namespace);
 4547:     if ($action eq 'delete') {
 4548:         $from_namespace = 'coursegroups';
 4549:         $to_namespace = 'deleted_groups';
 4550:     } else {
 4551:         $from_namespace = 'deleted_groups';
 4552:         $to_namespace = 'coursegroups';
 4553:     }
 4554:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4555:     if (my $tmp = &error(%curr_group)) {
 4556:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4557:         return ('read error',$tmp);
 4558:     } else {
 4559:         my %savedsettings = %curr_group; 
 4560:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4561:         my $deloutcome;
 4562:         if ($result eq 'ok') {
 4563:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4564:         } else {
 4565:             return ('write error',$result);
 4566:         }
 4567:         if ($deloutcome eq 'ok') {
 4568:             return 'ok';
 4569:         } else {
 4570:             return ('delete error',$deloutcome);
 4571:         }
 4572:     }
 4573: }
 4574: 
 4575: sub modify_group_roles {
 4576:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4577:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4578:     my $role = 'gr/'.&escape($userprivs);
 4579:     my ($uname,$udom) = split(/:/,$user);
 4580:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4581:     if ($result eq 'ok') {
 4582:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4583:     }
 4584:     return $result;
 4585: }
 4586: 
 4587: sub modify_coursegroup_membership {
 4588:     my ($cdom,$cnum,$membership) = @_;
 4589:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4590:     return $result;
 4591: }
 4592: 
 4593: sub get_active_groups {
 4594:     my ($udom,$uname,$cdom,$cnum) = @_;
 4595:     my $now = time;
 4596:     my %groups = ();
 4597:     foreach my $key (keys(%env)) {
 4598:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4599:             my ($start,$end) = split(/\./,$env{$key});
 4600:             if (($end!=0) && ($end<$now)) { next; }
 4601:             if (($start!=0) && ($start>$now)) { next; }
 4602:             if ($1 eq $cdom && $2 eq $cnum) {
 4603:                 $groups{$3} = $env{$key} ;
 4604:             }
 4605:         }
 4606:     }
 4607:     return %groups;
 4608: }
 4609: 
 4610: sub get_group_membership {
 4611:     my ($cdom,$cnum,$group) = @_;
 4612:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4613: }
 4614: 
 4615: sub get_users_groups {
 4616:     my ($udom,$uname,$courseid) = @_;
 4617:     my @usersgroups;
 4618:     my $cachetime=1800;
 4619: 
 4620:     my $hashid="$udom:$uname:$courseid";
 4621:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4622:     if (defined($cached)) {
 4623:         @usersgroups = split(/:/,$grouplist);
 4624:     } else {  
 4625:         $grouplist = '';
 4626:         my $courseurl = &courseid_to_courseurl($courseid);
 4627:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4628:         my $access_end = $env{'course.'.$courseid.
 4629:                               '.default_enrollment_end_date'};
 4630:         my $now = time;
 4631:         foreach my $key (keys(%roleshash)) {
 4632:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4633:                 my $group = $1;
 4634:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4635:                     my $start = $2;
 4636:                     my $end = $1;
 4637:                     if ($start == -1) { next; } # deleted from group
 4638:                     if (($start!=0) && ($start>$now)) { next; }
 4639:                     if (($end!=0) && ($end<$now)) {
 4640:                         if ($access_end && $access_end < $now) {
 4641:                             if ($access_end - $end < 86400) {
 4642:                                 push(@usersgroups,$group);
 4643:                             }
 4644:                         }
 4645:                         next;
 4646:                     }
 4647:                     push(@usersgroups,$group);
 4648:                 }
 4649:             }
 4650:         }
 4651:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4652:         $grouplist = join(':',@usersgroups);
 4653:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4654:     }
 4655:     return @usersgroups;
 4656: }
 4657: 
 4658: sub devalidate_getgroups_cache {
 4659:     my ($udom,$uname,$cdom,$cnum)=@_;
 4660:     my $courseid = $cdom.'_'.$cnum;
 4661: 
 4662:     my $hashid="$udom:$uname:$courseid";
 4663:     &devalidate_cache_new('getgroups',$hashid);
 4664: }
 4665: 
 4666: # ------------------------------------------------------------------ Plain Text
 4667: 
 4668: sub plaintext {
 4669:     my ($short,$type,$cid) = @_;
 4670:     if ($short =~ /^cr/) {
 4671: 	return (split('/',$short))[-1];
 4672:     }
 4673:     if (!defined($cid)) {
 4674:         $cid = $env{'request.course.id'};
 4675:     }
 4676:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4677:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4678:                                           '.plaintext'});
 4679:     }
 4680:     my %rolenames = (
 4681:                       Course => 'std',
 4682:                       Group => 'alt1',
 4683:                     );
 4684:     if (defined($type) && 
 4685:          defined($rolenames{$type}) && 
 4686:          defined($prp{$short}{$rolenames{$type}})) {
 4687:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4688:     } else {
 4689:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4690:     }
 4691: }
 4692: 
 4693: # ----------------------------------------------------------------- Assign Role
 4694: 
 4695: sub assignrole {
 4696:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4697:     my $mrole;
 4698:     if ($role =~ /^cr\//) {
 4699:         my $cwosec=$url;
 4700:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4701: 	unless (&allowed('ccr',$cwosec)) {
 4702:            &logthis('Refused custom assignrole: '.
 4703:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4704: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4705:            return 'refused'; 
 4706:         }
 4707:         $mrole='cr';
 4708:     } elsif ($role =~ /^gr\//) {
 4709:         my $cwogrp=$url;
 4710:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4711:         unless (&allowed('mdg',$cwogrp)) {
 4712:             &logthis('Refused group assignrole: '.
 4713:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4714:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4715:             return 'refused';
 4716:         }
 4717:         $mrole='gr';
 4718:     } else {
 4719:         my $cwosec=$url;
 4720:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4721:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4722:            &logthis('Refused assignrole: '.
 4723:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4724: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4725:            return 'refused'; 
 4726:         }
 4727:         $mrole=$role;
 4728:     }
 4729:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4730:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4731:     if ($end) { $command.='_'.$end; }
 4732:     if ($start) {
 4733: 	if ($end) { 
 4734:            $command.='_'.$start; 
 4735:         } else {
 4736:            $command.='_0_'.$start;
 4737:         }
 4738:     }
 4739:     my $origstart = $start;
 4740:     my $origend = $end;
 4741: # actually delete
 4742:     if ($deleteflag) {
 4743: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4744: # modify command to delete the role
 4745:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4746:                 "$udom:$uname:$url".'_'."$mrole";
 4747: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4748: # set start and finish to negative values for userrolelog
 4749:            $start=-1;
 4750:            $end=-1;
 4751:         }
 4752:     }
 4753: # send command
 4754:     my $answer=&reply($command,&homeserver($uname,$udom));
 4755: # log new user role if status is ok
 4756:     if ($answer eq 'ok') {
 4757: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4758: # for course roles, perform group memberships changes triggered by role change.
 4759:         unless ($role =~ /^gr/) {
 4760:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4761:                                              $origstart);
 4762:         }
 4763:     }
 4764:     return $answer;
 4765: }
 4766: 
 4767: # -------------------------------------------------- Modify user authentication
 4768: # Overrides without validation
 4769: 
 4770: sub modifyuserauth {
 4771:     my ($udom,$uname,$umode,$upass)=@_;
 4772:     my $uhome=&homeserver($uname,$udom);
 4773:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4774:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4775:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4776:              ' in domain '.$env{'request.role.domain'});  
 4777:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4778: 		     &escape($upass),$uhome);
 4779:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4780:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4781:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4782:     &log($udom,,$uname,$uhome,
 4783:         'Authentication changed by '.$env{'user.domain'}.', '.
 4784:                                      $env{'user.name'}.', '.$umode.
 4785:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4786:     unless ($reply eq 'ok') {
 4787:         &logthis('Authentication mode error: '.$reply);
 4788: 	return 'error: '.$reply;
 4789:     }   
 4790:     return 'ok';
 4791: }
 4792: 
 4793: # --------------------------------------------------------------- Modify a user
 4794: 
 4795: sub modifyuser {
 4796:     my ($udom,    $uname, $uid,
 4797:         $umode,   $upass, $first,
 4798:         $middle,  $last,  $gene,
 4799:         $forceid, $desiredhome, $email)=@_;
 4800:     $udom= &LONCAPA::clean_domain($udom);
 4801:     $uname=&LONCAPA::clean_username($uname);
 4802:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4803:              $umode.', '.$first.', '.$middle.', '.
 4804: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4805:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4806:                                      ' desiredhome not specified'). 
 4807:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4808:              ' in domain '.$env{'request.role.domain'});
 4809:     my $uhome=&homeserver($uname,$udom,'true');
 4810: # ----------------------------------------------------------------- Create User
 4811:     if (($uhome eq 'no_host') && 
 4812: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4813:         my $unhome='';
 4814:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4815:             $unhome = $desiredhome;
 4816: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4817: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4818:         } else { # load balancing routine for determining $unhome
 4819:             my $loadm=10000000;
 4820: 	    my %servers = &get_servers($udom,'library');
 4821: 	    foreach my $tryserver (keys(%servers)) {
 4822: 		my $answer=reply('load',$tryserver);
 4823: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4824: 		    $loadm=$answer;
 4825: 		    $unhome=$tryserver;
 4826: 		}
 4827: 	    }
 4828:         }
 4829:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4830: 	    return 'error: unable to find a home server for '.$uname.
 4831:                    ' in domain '.$udom;
 4832:         }
 4833:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4834:                          &escape($upass),$unhome);
 4835: 	unless ($reply eq 'ok') {
 4836:             return 'error: '.$reply;
 4837:         }   
 4838:         $uhome=&homeserver($uname,$udom,'true');
 4839:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4840: 	    return 'error: unable verify users home machine.';
 4841:         }
 4842:     }   # End of creation of new user
 4843: # ---------------------------------------------------------------------- Add ID
 4844:     if ($uid) {
 4845:        $uid=~tr/A-Z/a-z/;
 4846:        my %uidhash=&idrget($udom,$uname);
 4847:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4848:          && (!$forceid)) {
 4849: 	  unless ($uid eq $uidhash{$uname}) {
 4850: 	      return 'error: user id "'.$uid.'" does not match '.
 4851:                   'current user id "'.$uidhash{$uname}.'".';
 4852:           }
 4853:        } else {
 4854: 	  &idput($udom,($uname => $uid));
 4855:        }
 4856:     }
 4857: # -------------------------------------------------------------- Add names, etc
 4858:     my @tmp=&get('environment',
 4859: 		   ['firstname','middlename','lastname','generation'],
 4860: 		   $udom,$uname);
 4861:     my %names;
 4862:     if ($tmp[0] =~ m/^error:.*/) { 
 4863:         %names=(); 
 4864:     } else {
 4865:         %names = @tmp;
 4866:     }
 4867: #
 4868: # Make sure to not trash student environment if instructor does not bother
 4869: # to supply name and email information
 4870: #
 4871:     if ($first)  { $names{'firstname'}  = $first; }
 4872:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4873:     if ($last)   { $names{'lastname'}   = $last; }
 4874:     if (defined($gene))   { $names{'generation'} = $gene; }
 4875:     if ($email) {
 4876:        $email=~s/[^\w\@\.\-\,]//gs;
 4877:        if ($email=~/\@/) { $names{'notification'} = $email;
 4878: 			   $names{'critnotification'} = $email;
 4879: 			   $names{'permanentemail'} = $email; }
 4880:     }
 4881:     my $reply = &put('environment', \%names, $udom,$uname);
 4882:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4883:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4884:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4885:              $umode.', '.$first.', '.$middle.', '.
 4886: 	     $last.', '.$gene.' by '.
 4887:              $env{'user.name'}.' at '.$env{'user.domain'});
 4888:     return 'ok';
 4889: }
 4890: 
 4891: # -------------------------------------------------------------- Modify student
 4892: 
 4893: sub modifystudent {
 4894:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4895:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4896:     if (!$cid) {
 4897: 	unless ($cid=$env{'request.course.id'}) {
 4898: 	    return 'not_in_class';
 4899: 	}
 4900:     }
 4901: # --------------------------------------------------------------- Make the user
 4902:     my $reply=&modifyuser
 4903: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4904:          $desiredhome,$email);
 4905:     unless ($reply eq 'ok') { return $reply; }
 4906:     # This will cause &modify_student_enrollment to get the uid from the
 4907:     # students environment
 4908:     $uid = undef if (!$forceid);
 4909:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4910: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4911:     return $reply;
 4912: }
 4913: 
 4914: sub modify_student_enrollment {
 4915:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4916:     my ($cdom,$cnum,$chome);
 4917:     if (!$cid) {
 4918: 	unless ($cid=$env{'request.course.id'}) {
 4919: 	    return 'not_in_class';
 4920: 	}
 4921: 	$cdom=$env{'course.'.$cid.'.domain'};
 4922: 	$cnum=$env{'course.'.$cid.'.num'};
 4923:     } else {
 4924: 	($cdom,$cnum)=split(/_/,$cid);
 4925:     }
 4926:     $chome=$env{'course.'.$cid.'.home'};
 4927:     if (!$chome) {
 4928: 	$chome=&homeserver($cnum,$cdom);
 4929:     }
 4930:     if (!$chome) { return 'unknown_course'; }
 4931:     # Make sure the user exists
 4932:     my $uhome=&homeserver($uname,$udom);
 4933:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4934: 	return 'error: no such user';
 4935:     }
 4936:     # Get student data if we were not given enough information
 4937:     if (!defined($first)  || $first  eq '' || 
 4938:         !defined($last)   || $last   eq '' || 
 4939:         !defined($uid)    || $uid    eq '' || 
 4940:         !defined($middle) || $middle eq '' || 
 4941:         !defined($gene)   || $gene   eq '') {
 4942:         # They did not supply us with enough data to enroll the student, so
 4943:         # we need to pick up more information.
 4944:         my %tmp = &get('environment',
 4945:                        ['firstname','middlename','lastname', 'generation','id']
 4946:                        ,$udom,$uname);
 4947: 
 4948:         #foreach my $key (keys(%tmp)) {
 4949:         #    &logthis("key $key = ".$tmp{$key});
 4950:         #}
 4951:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4952:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4953:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4954:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4955:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4956:     }
 4957:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4958:     my $reply=cput('classlist',
 4959: 		   {"$uname:$udom" => 
 4960: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4961: 		   $cdom,$cnum);
 4962:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4963: 	return 'error: '.$reply;
 4964:     } else {
 4965: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4966:     }
 4967:     # Add student role to user
 4968:     my $uurl='/'.$cid;
 4969:     $uurl=~s/\_/\//g;
 4970:     if ($usec) {
 4971: 	$uurl.='/'.$usec;
 4972:     }
 4973:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4974: }
 4975: 
 4976: sub format_name {
 4977:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4978:     my $name;
 4979:     if ($first ne 'lastname') {
 4980: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4981:     } else {
 4982: 	if ($lastname=~/\S/) {
 4983: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4984: 	    $name=~s/\s+,/,/;
 4985: 	} else {
 4986: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4987: 	}
 4988:     }
 4989:     $name=~s/^\s+//;
 4990:     $name=~s/\s+$//;
 4991:     $name=~s/\s+/ /g;
 4992:     return $name;
 4993: }
 4994: 
 4995: # ------------------------------------------------- Write to course preferences
 4996: 
 4997: sub writecoursepref {
 4998:     my ($courseid,%prefs)=@_;
 4999:     $courseid=~s/^\///;
 5000:     $courseid=~s/\_/\//g;
 5001:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5002:     my $chome=homeserver($cnum,$cdomain);
 5003:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5004: 	return 'error: no such course';
 5005:     }
 5006:     my $cstring='';
 5007:     foreach my $pref (keys(%prefs)) {
 5008: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5009:     }
 5010:     $cstring=~s/\&$//;
 5011:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5012: }
 5013: 
 5014: # ---------------------------------------------------------- Make/modify course
 5015: 
 5016: sub createcourse {
 5017:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5018:         $course_owner,$crstype)=@_;
 5019:     $url=&declutter($url);
 5020:     my $cid='';
 5021:     unless (&allowed('ccc',$udom)) {
 5022:         return 'refused';
 5023:     }
 5024: # ------------------------------------------------------------------- Create ID
 5025:    my $uname=int(1+rand(9)).
 5026:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5027:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5028:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5029: # ----------------------------------------------- Make sure that does not exist
 5030:    my $uhome=&homeserver($uname,$udom,'true');
 5031:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5032:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5033:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5034:        $uhome=&homeserver($uname,$udom,'true');       
 5035:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5036:            return 'error: unable to generate unique course-ID';
 5037:        } 
 5038:    }
 5039: # ------------------------------------------------ Check supplied server name
 5040:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5041:     if (! exists($libserv{$course_server})) {
 5042:         return 'error:bad server name '.$course_server;
 5043:     }
 5044: # ------------------------------------------------------------- Make the course
 5045:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5046:                       $course_server);
 5047:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5048:     $uhome=&homeserver($uname,$udom,'true');
 5049:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5050: 	return 'error: no such course';
 5051:     }
 5052: # ----------------------------------------------------------------- Course made
 5053: # log existence
 5054:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5055:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5056:                   &escape($crstype),$uhome);
 5057:     &flushcourselogs();
 5058: # set toplevel url
 5059:     my $topurl=$url;
 5060:     unless ($nonstandard) {
 5061: # ------------------------------------------ For standard courses, make top url
 5062:         my $mapurl=&clutter($url);
 5063:         if ($mapurl eq '/res/') { $mapurl=''; }
 5064:         $env{'form.initmap'}=(<<ENDINITMAP);
 5065: <map>
 5066: <resource id="1" type="start"></resource>
 5067: <resource id="2" src="$mapurl"></resource>
 5068: <resource id="3" type="finish"></resource>
 5069: <link index="1" from="1" to="2"></link>
 5070: <link index="2" from="2" to="3"></link>
 5071: </map>
 5072: ENDINITMAP
 5073:         $topurl=&declutter(
 5074:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5075:                           );
 5076:     }
 5077: # ----------------------------------------------------------- Write preferences
 5078:     &writecoursepref($udom.'_'.$uname,
 5079:                      ('description' => $description,
 5080:                       'url'         => $topurl));
 5081:     return '/'.$udom.'/'.$uname;
 5082: }
 5083: 
 5084: sub is_course {
 5085:     my ($cdom,$cnum) = @_;
 5086:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5087: 				undef,'.');
 5088:     if (exists($courses{$cdom.'_'.$cnum})) {
 5089:         return 1;
 5090:     }
 5091:     return 0;
 5092: }
 5093: 
 5094: # ---------------------------------------------------------- Assign Custom Role
 5095: 
 5096: sub assigncustomrole {
 5097:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5098:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5099:                        $end,$start,$deleteflag);
 5100: }
 5101: 
 5102: # ----------------------------------------------------------------- Revoke Role
 5103: 
 5104: sub revokerole {
 5105:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5106:     my $now=time;
 5107:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5108: }
 5109: 
 5110: # ---------------------------------------------------------- Revoke Custom Role
 5111: 
 5112: sub revokecustomrole {
 5113:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5114:     my $now=time;
 5115:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5116:            $deleteflag);
 5117: }
 5118: 
 5119: # ------------------------------------------------------------ Disk usage
 5120: sub diskusage {
 5121:     my ($udom,$uname,$directoryRoot)=@_;
 5122:     $directoryRoot =~ s/\/$//;
 5123:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5124:     return $listing;
 5125: }
 5126: 
 5127: sub is_locked {
 5128:     my ($file_name, $domain, $user) = @_;
 5129:     my @check;
 5130:     my $is_locked;
 5131:     push @check, $file_name;
 5132:     my %locked = &get('file_permissions',\@check,
 5133: 		      $env{'user.domain'},$env{'user.name'});
 5134:     my ($tmp)=keys(%locked);
 5135:     if ($tmp=~/^error:/) { undef(%locked); }
 5136:     
 5137:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5138:         $is_locked = 'false';
 5139:         foreach my $entry (@{$locked{$file_name}}) {
 5140:            if (ref($entry) eq 'ARRAY') { 
 5141:                $is_locked = 'true';
 5142:                last;
 5143:            }
 5144:        }
 5145:     } else {
 5146:         $is_locked = 'false';
 5147:     }
 5148: }
 5149: 
 5150: sub declutter_portfile {
 5151:     my ($file) = @_;
 5152:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5153:     return $file;
 5154: }
 5155: 
 5156: # ------------------------------------------------------------- Mark as Read Only
 5157: 
 5158: sub mark_as_readonly {
 5159:     my ($domain,$user,$files,$what) = @_;
 5160:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5161:     my ($tmp)=keys(%current_permissions);
 5162:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5163:     foreach my $file (@{$files}) {
 5164: 	$file = &declutter_portfile($file);
 5165:         push(@{$current_permissions{$file}},$what);
 5166:     }
 5167:     &put('file_permissions',\%current_permissions,$domain,$user);
 5168:     return;
 5169: }
 5170: 
 5171: # ------------------------------------------------------------Save Selected Files
 5172: 
 5173: sub save_selected_files {
 5174:     my ($user, $path, @files) = @_;
 5175:     my $filename = $user."savedfiles";
 5176:     my @other_files = &files_not_in_path($user, $path);
 5177:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5178:     foreach my $file (@files) {
 5179:         print (OUT $env{'form.currentpath'}.$file."\n");
 5180:     }
 5181:     foreach my $file (@other_files) {
 5182:         print (OUT $file."\n");
 5183:     }
 5184:     close (OUT);
 5185:     return 'ok';
 5186: }
 5187: 
 5188: sub clear_selected_files {
 5189:     my ($user) = @_;
 5190:     my $filename = $user."savedfiles";
 5191:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5192:     print (OUT undef);
 5193:     close (OUT);
 5194:     return ("ok");    
 5195: }
 5196: 
 5197: sub files_in_path {
 5198:     my ($user, $path) = @_;
 5199:     my $filename = $user."savedfiles";
 5200:     my %return_files;
 5201:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5202:     while (my $line_in = <IN>) {
 5203:         chomp ($line_in);
 5204:         my @paths_and_file = split (m!/!, $line_in);
 5205:         my $file_part = pop (@paths_and_file);
 5206:         my $path_part = join ('/', @paths_and_file);
 5207:         $path_part.='/';
 5208:         my $path_and_file = $path_part.$file_part;
 5209:         if ($path_part eq $path) {
 5210:             $return_files{$file_part}= 'selected';
 5211:         }
 5212:     }
 5213:     close (IN);
 5214:     return (\%return_files);
 5215: }
 5216: 
 5217: # called in portfolio select mode, to show files selected NOT in current directory
 5218: sub files_not_in_path {
 5219:     my ($user, $path) = @_;
 5220:     my $filename = $user."savedfiles";
 5221:     my @return_files;
 5222:     my $path_part;
 5223:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5224:     while (my $line = <IN>) {
 5225:         #ok, I know it's clunky, but I want it to work
 5226:         my @paths_and_file = split(m|/|, $line);
 5227:         my $file_part = pop(@paths_and_file);
 5228:         chomp($file_part);
 5229:         my $path_part = join('/', @paths_and_file);
 5230:         $path_part .= '/';
 5231:         my $path_and_file = $path_part.$file_part;
 5232:         if ($path_part ne $path) {
 5233:             push(@return_files, ($path_and_file));
 5234:         }
 5235:     }
 5236:     close(OUT);
 5237:     return (@return_files);
 5238: }
 5239: 
 5240: #----------------------------------------------Get portfolio file permissions
 5241: 
 5242: sub get_portfile_permissions {
 5243:     my ($domain,$user) = @_;
 5244:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5245:     my ($tmp)=keys(%current_permissions);
 5246:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5247:     return \%current_permissions;
 5248: }
 5249: 
 5250: #---------------------------------------------Get portfolio file access controls
 5251: 
 5252: sub get_access_controls {
 5253:     my ($current_permissions,$group,$file) = @_;
 5254:     my %access;
 5255:     my $real_file = $file;
 5256:     $file =~ s/\.meta$//;
 5257:     if (defined($file)) {
 5258:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5259:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5260:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5261:             }
 5262:         }
 5263:     } else {
 5264:         foreach my $key (keys(%{$current_permissions})) {
 5265:             if ($key =~ /\0accesscontrol$/) {
 5266:                 if (defined($group)) {
 5267:                     if ($key !~ m-^\Q$group\E/-) {
 5268:                         next;
 5269:                     }
 5270:                 }
 5271:                 my ($fullpath) = split(/\0/,$key);
 5272:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5273:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5274:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5275:                     }
 5276:                 }
 5277:             }
 5278:         }
 5279:     }
 5280:     return %access;
 5281: }
 5282: 
 5283: sub modify_access_controls {
 5284:     my ($file_name,$changes,$domain,$user)=@_;
 5285:     my ($outcome,$deloutcome);
 5286:     my %store_permissions;
 5287:     my %new_values;
 5288:     my %new_control;
 5289:     my %translation;
 5290:     my @deletions = ();
 5291:     my $now = time;
 5292:     if (exists($$changes{'activate'})) {
 5293:         if (ref($$changes{'activate'}) eq 'HASH') {
 5294:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5295:             my $numnew = scalar(@newitems);
 5296:             for (my $i=0; $i<$numnew; $i++) {
 5297:                 my $newkey = $newitems[$i];
 5298:                 my $newid = &Apache::loncommon::get_cgi_id();
 5299:                 if ($newkey =~ /^\d+:/) { 
 5300:                     $newkey =~ s/^(\d+)/$newid/;
 5301:                     $translation{$1} = $newid;
 5302:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5303:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5304:                     $translation{$1} = $newid;
 5305:                 }
 5306:                 $new_values{$file_name."\0".$newkey} = 
 5307:                                           $$changes{'activate'}{$newitems[$i]};
 5308:                 $new_control{$newkey} = $now;
 5309:             }
 5310:         }
 5311:     }
 5312:     my %todelete;
 5313:     my %changed_items;
 5314:     foreach my $action ('delete','update') {
 5315:         if (exists($$changes{$action})) {
 5316:             if (ref($$changes{$action}) eq 'HASH') {
 5317:                 foreach my $key (keys(%{$$changes{$action}})) {
 5318:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5319:                     if ($action eq 'delete') { 
 5320:                         $todelete{$itemnum} = 1;
 5321:                     } else {
 5322:                         $changed_items{$itemnum} = $key;
 5323:                     }
 5324:                 }
 5325:             }
 5326:         }
 5327:     }
 5328:     # get lock on access controls for file.
 5329:     my $lockhash = {
 5330:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5331:                                                        ':'.$env{'user.domain'},
 5332:                    }; 
 5333:     my $tries = 0;
 5334:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5335:    
 5336:     while (($gotlock ne 'ok') && $tries <3) {
 5337:         $tries ++;
 5338:         sleep 1;
 5339:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5340:     }
 5341:     if ($gotlock eq 'ok') {
 5342:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5343:         my ($tmp)=keys(%curr_permissions);
 5344:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5345:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5346:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5347:             if (ref($curr_controls) eq 'HASH') {
 5348:                 foreach my $control_item (keys(%{$curr_controls})) {
 5349:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5350:                     if (defined($todelete{$itemnum})) {
 5351:                         push(@deletions,$file_name."\0".$control_item);
 5352:                     } else {
 5353:                         if (defined($changed_items{$itemnum})) {
 5354:                             $new_control{$changed_items{$itemnum}} = $now;
 5355:                             push(@deletions,$file_name."\0".$control_item);
 5356:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5357:                         } else {
 5358:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5359:                         }
 5360:                     }
 5361:                 }
 5362:             }
 5363:         }
 5364:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5365:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5366:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5367:         #  remove lock
 5368:         my @del_lock = ($file_name."\0".'locked_access_records');
 5369:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5370:         my ($file,$group);
 5371:         if (&is_course($domain,$user)) {
 5372:             ($group,$file) = split(/\//,$file_name,2);
 5373:         } else {
 5374:             $file = $file_name;
 5375:         }
 5376:         my $sqlresult =
 5377:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5378:                                     $group);
 5379:     } else {
 5380:         $outcome = "error: could not obtain lockfile\n";  
 5381:     }
 5382:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5383: }
 5384: 
 5385: sub make_public_indefinitely {
 5386:     my ($requrl) = @_;
 5387:     my $now = time;
 5388:     my $action = 'activate';
 5389:     my $aclnum = 0;
 5390:     if (&is_portfolio_url($requrl)) {
 5391:         my (undef,$udom,$unum,$file_name,$group) =
 5392:             &parse_portfolio_url($requrl);
 5393:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5394:         my %access_controls = &get_access_controls($current_perms,
 5395:                                                    $group,$file_name);
 5396:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5397:             my ($num,$scope,$end,$start) = 
 5398:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5399:             if ($scope eq 'public') {
 5400:                 if ($start <= $now && $end == 0) {
 5401:                     $action = 'none';
 5402:                 } else {
 5403:                     $action = 'update';
 5404:                     $aclnum = $num;
 5405:                 }
 5406:                 last;
 5407:             }
 5408:         }
 5409:         if ($action eq 'none') {
 5410:              return 'ok';
 5411:         } else {
 5412:             my %changes;
 5413:             my $newend = 0;
 5414:             my $newstart = $now;
 5415:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5416:             $changes{$action}{$newkey} = {
 5417:                 type => 'public',
 5418:                 time => {
 5419:                     start => $newstart,
 5420:                     end   => $newend,
 5421:                 },
 5422:             };
 5423:             my ($outcome,$deloutcome,$new_values,$translation) =
 5424:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5425:             return $outcome;
 5426:         }
 5427:     } else {
 5428:         return 'invalid';
 5429:     }
 5430: }
 5431: 
 5432: #------------------------------------------------------Get Marked as Read Only
 5433: 
 5434: sub get_marked_as_readonly {
 5435:     my ($domain,$user,$what,$group) = @_;
 5436:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5437:     my @readonly_files;
 5438:     my $cmp1=$what;
 5439:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5440:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5441:         if (defined($group)) {
 5442:             if ($file_name !~ m-^\Q$group\E/-) {
 5443:                 next;
 5444:             }
 5445:         }
 5446:         if (ref($value) eq "ARRAY"){
 5447:             foreach my $stored_what (@{$value}) {
 5448:                 my $cmp2=$stored_what;
 5449:                 if (ref($stored_what) eq 'ARRAY') {
 5450:                     $cmp2=join('',@{$stored_what});
 5451:                 }
 5452:                 if ($cmp1 eq $cmp2) {
 5453:                     push(@readonly_files, $file_name);
 5454:                     last;
 5455:                 } elsif (!defined($what)) {
 5456:                     push(@readonly_files, $file_name);
 5457:                     last;
 5458:                 }
 5459:             }
 5460:         }
 5461:     }
 5462:     return @readonly_files;
 5463: }
 5464: #-----------------------------------------------------------Get Marked as Read Only Hash
 5465: 
 5466: sub get_marked_as_readonly_hash {
 5467:     my ($current_permissions,$group,$what) = @_;
 5468:     my %readonly_files;
 5469:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5470:         if (defined($group)) {
 5471:             if ($file_name !~ m-^\Q$group\E/-) {
 5472:                 next;
 5473:             }
 5474:         }
 5475:         if (ref($value) eq "ARRAY"){
 5476:             foreach my $stored_what (@{$value}) {
 5477:                 if (ref($stored_what) eq 'ARRAY') {
 5478:                     foreach my $lock_descriptor(@{$stored_what}) {
 5479:                         if ($lock_descriptor eq 'graded') {
 5480:                             $readonly_files{$file_name} = 'graded';
 5481:                         } elsif ($lock_descriptor eq 'handback') {
 5482:                             $readonly_files{$file_name} = 'handback';
 5483:                         } else {
 5484:                             if (!exists($readonly_files{$file_name})) {
 5485:                                 $readonly_files{$file_name} = 'locked';
 5486:                             }
 5487:                         }
 5488:                     }
 5489:                 } 
 5490:             }
 5491:         } 
 5492:     }
 5493:     return %readonly_files;
 5494: }
 5495: # ------------------------------------------------------------ Unmark as Read Only
 5496: 
 5497: sub unmark_as_readonly {
 5498:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5499:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5500:     my ($domain,$user,$what,$file_name,$group) = @_;
 5501:     $file_name = &declutter_portfile($file_name);
 5502:     my $symb_crs = $what;
 5503:     if (ref($what)) { $symb_crs=join('',@$what); }
 5504:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5505:     my ($tmp)=keys(%current_permissions);
 5506:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5507:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5508:     foreach my $file (@readonly_files) {
 5509: 	my $clean_file = &declutter_portfile($file);
 5510: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5511: 	my $current_locks = $current_permissions{$file};
 5512:         my @new_locks;
 5513:         my @del_keys;
 5514:         if (ref($current_locks) eq "ARRAY"){
 5515:             foreach my $locker (@{$current_locks}) {
 5516:                 my $compare=$locker;
 5517:                 if (ref($locker) eq 'ARRAY') {
 5518:                     $compare=join('',@{$locker});
 5519:                     if ($compare ne $symb_crs) {
 5520:                         push(@new_locks, $locker);
 5521:                     }
 5522:                 }
 5523:             }
 5524:             if (scalar(@new_locks) > 0) {
 5525:                 $current_permissions{$file} = \@new_locks;
 5526:             } else {
 5527:                 push(@del_keys, $file);
 5528:                 &del('file_permissions',\@del_keys, $domain, $user);
 5529:                 delete($current_permissions{$file});
 5530:             }
 5531:         }
 5532:     }
 5533:     &put('file_permissions',\%current_permissions,$domain,$user);
 5534:     return;
 5535: }
 5536: 
 5537: # ------------------------------------------------------------ Directory lister
 5538: 
 5539: sub dirlist {
 5540:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5541: 
 5542:     $uri=~s/^\///;
 5543:     $uri=~s/\/$//;
 5544:     my ($udom, $uname);
 5545:     (undef,$udom,$uname)=split(/\//,$uri);
 5546:     if(defined($userdomain)) {
 5547:         $udom = $userdomain;
 5548:     }
 5549:     if(defined($username)) {
 5550:         $uname = $username;
 5551:     }
 5552: 
 5553:     my $dirRoot = $perlvar{'lonDocRoot'};
 5554:     if(defined($alternateDirectoryRoot)) {
 5555:         $dirRoot = $alternateDirectoryRoot;
 5556:         $dirRoot =~ s/\/$//;
 5557:     }
 5558: 
 5559:     if($udom) {
 5560:         if($uname) {
 5561:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5562: 				 &homeserver($uname,$udom));
 5563:             my @listing_results;
 5564:             if ($listing eq 'unknown_cmd') {
 5565:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5566: 				  &homeserver($uname,$udom));
 5567:                 @listing_results = split(/:/,$listing);
 5568:             } else {
 5569:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5570:             }
 5571:             return @listing_results;
 5572:         } elsif(!defined($alternateDirectoryRoot)) {
 5573:             my %allusers;
 5574: 	    my %servers = &get_servers($udom,'library');
 5575: 	    foreach my $tryserver (keys(%servers)) {
 5576: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5577: 				     $udom, $tryserver);
 5578: 		my @listing_results;
 5579: 		if ($listing eq 'unknown_cmd') {
 5580: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5581: 				      $udom, $tryserver);
 5582: 		    @listing_results = split(/:/,$listing);
 5583: 		} else {
 5584: 		    @listing_results =
 5585: 			map { &unescape($_); } split(/:/,$listing);
 5586: 		}
 5587: 		if ($listing_results[0] ne 'no_such_dir' && 
 5588: 		    $listing_results[0] ne 'empty'       &&
 5589: 		    $listing_results[0] ne 'con_lost') {
 5590: 		    foreach my $line (@listing_results) {
 5591: 			my ($entry) = split(/&/,$line,2);
 5592: 			$allusers{$entry} = 1;
 5593: 		    }
 5594: 		}
 5595:             }
 5596:             my $alluserstr='';
 5597:             foreach my $user (sort(keys(%allusers))) {
 5598:                 $alluserstr.=$user.'&user:';
 5599:             }
 5600:             $alluserstr=~s/:$//;
 5601:             return split(/:/,$alluserstr);
 5602:         } else {
 5603:             return ('missing user name');
 5604:         }
 5605:     } elsif(!defined($alternateDirectoryRoot)) {
 5606:         my @all_domains = sort(&all_domains());
 5607:          foreach my $domain (@all_domains) {
 5608:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5609:          }
 5610:          return @all_domains;
 5611:      } else {
 5612:         return ('missing domain');
 5613:     }
 5614: }
 5615: 
 5616: # --------------------------------------------- GetFileTimestamp
 5617: # This function utilizes dirlist and returns the date stamp for
 5618: # when it was last modified.  It will also return an error of -1
 5619: # if an error occurs
 5620: 
 5621: ##
 5622: ## FIXME: This subroutine assumes its caller knows something about the
 5623: ## directory structure of the home server for the student ($root).
 5624: ## Not a good assumption to make.  Since this is for looking up files
 5625: ## in user directories, the full path should be constructed by lond, not
 5626: ## whatever machine we request data from.
 5627: ##
 5628: sub GetFileTimestamp {
 5629:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5630:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5631:     $studentName   = &LONCAPA::clean_username($studentName);
 5632:     my $subdir=$studentName.'__';
 5633:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5634:     my $proname="$studentDomain/$subdir/$studentName";
 5635:     $proname .= '/'.$filename;
 5636:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5637:                                               $studentName, $root);
 5638:     my @stats = split('&', $fileStat);
 5639:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5640:         # @stats contains first the filename, then the stat output
 5641:         return $stats[10]; # so this is 10 instead of 9.
 5642:     } else {
 5643:         return -1;
 5644:     }
 5645: }
 5646: 
 5647: sub stat_file {
 5648:     my ($uri) = @_;
 5649:     $uri = &clutter_with_no_wrapper($uri);
 5650: 
 5651:     my ($udom,$uname,$file,$dir);
 5652:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5653: 	($udom,$uname,$file) =
 5654: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5655: 	$file = 'userfiles/'.$file;
 5656: 	$dir = &propath($udom,$uname);
 5657:     }
 5658:     if ($uri =~ m-^/res/-) {
 5659: 	($udom,$uname) = 
 5660: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5661: 	$file = $uri;
 5662:     }
 5663: 
 5664:     if (!$udom || !$uname || !$file) {
 5665: 	# unable to handle the uri
 5666: 	return ();
 5667:     }
 5668: 
 5669:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5670:     my @stats = split('&', $result);
 5671:     
 5672:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5673: 	shift(@stats); #filename is first
 5674: 	return @stats;
 5675:     }
 5676:     return ();
 5677: }
 5678: 
 5679: # -------------------------------------------------------- Value of a Condition
 5680: 
 5681: # gets the value of a specific preevaluated condition
 5682: #    stored in the string  $env{user.state.<cid>}
 5683: # or looks up a condition reference in the bighash and if if hasn't
 5684: # already been evaluated recurses into docondval to get the value of
 5685: # the condition, then memoizing it to 
 5686: #   $env{user.state.<cid>.<condition>}
 5687: sub directcondval {
 5688:     my $number=shift;
 5689:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5690: 	&Apache::lonuserstate::evalstate();
 5691:     }
 5692:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5693: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5694:     } elsif ($number =~ /^_/) {
 5695: 	my $sub_condition;
 5696: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5697: 		&GDBM_READER(),0640)) {
 5698: 	    $sub_condition=$bighash{'conditions'.$number};
 5699: 	    untie(%bighash);
 5700: 	}
 5701: 	my $value = &docondval($sub_condition);
 5702: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5703: 	return $value;
 5704:     }
 5705:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5706:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5707:     } else {
 5708:        return 2;
 5709:     }
 5710: }
 5711: 
 5712: # get the collection of conditions for this resource
 5713: sub condval {
 5714:     my $condidx=shift;
 5715:     my $allpathcond='';
 5716:     foreach my $cond (split(/\|/,$condidx)) {
 5717: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5718: 	    $allpathcond.=
 5719: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5720: 	}
 5721:     }
 5722:     $allpathcond=~s/\|$//;
 5723:     return &docondval($allpathcond);
 5724: }
 5725: 
 5726: #evaluates an expression of conditions
 5727: sub docondval {
 5728:     my ($allpathcond) = @_;
 5729:     my $result=0;
 5730:     if ($env{'request.course.id'}
 5731: 	&& defined($allpathcond)) {
 5732: 	my $operand='|';
 5733: 	my @stack;
 5734: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5735: 	    if ($chunk eq '(') {
 5736: 		push @stack,($operand,$result);
 5737: 	    } elsif ($chunk eq ')') {
 5738: 		my $before=pop @stack;
 5739: 		if (pop @stack eq '&') {
 5740: 		    $result=$result>$before?$before:$result;
 5741: 		} else {
 5742: 		    $result=$result>$before?$result:$before;
 5743: 		}
 5744: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5745: 		$operand=$chunk;
 5746: 	    } else {
 5747: 		my $new=directcondval($chunk);
 5748: 		if ($operand eq '&') {
 5749: 		    $result=$result>$new?$new:$result;
 5750: 		} else {
 5751: 		    $result=$result>$new?$result:$new;
 5752: 		}
 5753: 	    }
 5754: 	}
 5755:     }
 5756:     return $result;
 5757: }
 5758: 
 5759: # ---------------------------------------------------- Devalidate courseresdata
 5760: 
 5761: sub devalidatecourseresdata {
 5762:     my ($coursenum,$coursedomain)=@_;
 5763:     my $hashid=$coursenum.':'.$coursedomain;
 5764:     &devalidate_cache_new('courseres',$hashid);
 5765: }
 5766: 
 5767: 
 5768: # --------------------------------------------------- Course Resourcedata Query
 5769: 
 5770: sub get_courseresdata {
 5771:     my ($coursenum,$coursedomain)=@_;
 5772:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5773:     my $hashid=$coursenum.':'.$coursedomain;
 5774:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5775:     my %dumpreply;
 5776:     unless (defined($cached)) {
 5777: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5778: 	$result=\%dumpreply;
 5779: 	my ($tmp) = keys(%dumpreply);
 5780: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5781: 	    &do_cache_new('courseres',$hashid,$result,600);
 5782: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5783: 	    return $tmp;
 5784: 	} elsif ($tmp =~ /^(error)/) {
 5785: 	    $result=undef;
 5786: 	    &do_cache_new('courseres',$hashid,$result,600);
 5787: 	}
 5788:     }
 5789:     return $result;
 5790: }
 5791: 
 5792: sub devalidateuserresdata {
 5793:     my ($uname,$udom)=@_;
 5794:     my $hashid="$udom:$uname";
 5795:     &devalidate_cache_new('userres',$hashid);
 5796: }
 5797: 
 5798: sub get_userresdata {
 5799:     my ($uname,$udom)=@_;
 5800:     #most student don\'t have any data set, check if there is some data
 5801:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5802: 
 5803:     my $hashid="$udom:$uname";
 5804:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5805:     if (!defined($cached)) {
 5806: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5807: 	$result=\%resourcedata;
 5808: 	&do_cache_new('userres',$hashid,$result,600);
 5809:     }
 5810:     my ($tmp)=keys(%$result);
 5811:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5812: 	return $result;
 5813:     }
 5814:     #error 2 occurs when the .db doesn't exist
 5815:     if ($tmp!~/error: 2 /) {
 5816: 	&logthis("<font color=\"blue\">WARNING:".
 5817: 		 " Trying to get resource data for ".
 5818: 		 $uname." at ".$udom.": ".
 5819: 		 $tmp."</font>");
 5820:     } elsif ($tmp=~/error: 2 /) {
 5821: 	#&EXT_cache_set($udom,$uname);
 5822: 	&do_cache_new('userres',$hashid,undef,600);
 5823: 	undef($tmp); # not really an error so don't send it back
 5824:     }
 5825:     return $tmp;
 5826: }
 5827: 
 5828: sub resdata {
 5829:     my ($name,$domain,$type,@which)=@_;
 5830:     my $result;
 5831:     if ($type eq 'course') {
 5832: 	$result=&get_courseresdata($name,$domain);
 5833:     } elsif ($type eq 'user') {
 5834: 	$result=&get_userresdata($name,$domain);
 5835:     }
 5836:     if (!ref($result)) { return $result; }    
 5837:     foreach my $item (@which) {
 5838: 	if (defined($result->{$item})) {
 5839: 	    return $result->{$item};
 5840: 	}
 5841:     }
 5842:     return undef;
 5843: }
 5844: 
 5845: #
 5846: # EXT resource caching routines
 5847: #
 5848: 
 5849: sub clear_EXT_cache_status {
 5850:     &delenv('cache.EXT.');
 5851: }
 5852: 
 5853: sub EXT_cache_status {
 5854:     my ($target_domain,$target_user) = @_;
 5855:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5856:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5857:         # We know already the user has no data
 5858:         return 1;
 5859:     } else {
 5860:         return 0;
 5861:     }
 5862: }
 5863: 
 5864: sub EXT_cache_set {
 5865:     my ($target_domain,$target_user) = @_;
 5866:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5867:     #&appenv($cachename => time);
 5868: }
 5869: 
 5870: # --------------------------------------------------------- Value of a Variable
 5871: sub EXT {
 5872: 
 5873:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5874:     unless ($varname) { return ''; }
 5875:     #get real user name/domain, courseid and symb
 5876:     my $courseid;
 5877:     my $publicuser;
 5878:     if ($symbparm) {
 5879: 	$symbparm=&get_symb_from_alias($symbparm);
 5880:     }
 5881:     if (!($uname && $udom)) {
 5882:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5883:       if (!$symbparm) {	$symbparm=$cursymb; }
 5884:     } else {
 5885: 	$courseid=$env{'request.course.id'};
 5886:     }
 5887:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5888:     my $rest;
 5889:     if (defined($therest[0])) {
 5890:        $rest=join('.',@therest);
 5891:     } else {
 5892:        $rest='';
 5893:     }
 5894: 
 5895:     my $qualifierrest=$qualifier;
 5896:     if ($rest) { $qualifierrest.='.'.$rest; }
 5897:     my $spacequalifierrest=$space;
 5898:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5899:     if ($realm eq 'user') {
 5900: # --------------------------------------------------------------- user.resource
 5901: 	if ($space eq 'resource') {
 5902: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5903: 		  || defined($Apache::lonhomework::parsing_a_task))
 5904: 		 &&
 5905: 		 ($symbparm eq &symbread()) ) {	
 5906: 		# if we are in the middle of processing the resource the
 5907: 		# get the value we are planning on committing
 5908:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5909:                     return $Apache::lonhomework::results{$qualifierrest};
 5910:                 } else {
 5911:                     return $Apache::lonhomework::history{$qualifierrest};
 5912:                 }
 5913: 	    } else {
 5914: 		my %restored;
 5915: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5916: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5917: 		} else {
 5918: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5919: 		}
 5920: 		return $restored{$qualifierrest};
 5921: 	    }
 5922: # ----------------------------------------------------------------- user.access
 5923:         } elsif ($space eq 'access') {
 5924: 	    # FIXME - not supporting calls for a specific user
 5925:             return &allowed($qualifier,$rest);
 5926: # ------------------------------------------ user.preferences, user.environment
 5927:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5928: 	    if (($uname eq $env{'user.name'}) &&
 5929: 		($udom eq $env{'user.domain'})) {
 5930: 		return $env{join('.',('environment',$qualifierrest))};
 5931: 	    } else {
 5932: 		my %returnhash;
 5933: 		if (!$publicuser) {
 5934: 		    %returnhash=&userenvironment($udom,$uname,
 5935: 						 $qualifierrest);
 5936: 		}
 5937: 		return $returnhash{$qualifierrest};
 5938: 	    }
 5939: # ----------------------------------------------------------------- user.course
 5940:         } elsif ($space eq 'course') {
 5941: 	    # FIXME - not supporting calls for a specific user
 5942:             return $env{join('.',('request.course',$qualifier))};
 5943: # ------------------------------------------------------------------- user.role
 5944:         } elsif ($space eq 'role') {
 5945: 	    # FIXME - not supporting calls for a specific user
 5946:             my ($role,$where)=split(/\./,$env{'request.role'});
 5947:             if ($qualifier eq 'value') {
 5948: 		return $role;
 5949:             } elsif ($qualifier eq 'extent') {
 5950:                 return $where;
 5951:             }
 5952: # ----------------------------------------------------------------- user.domain
 5953:         } elsif ($space eq 'domain') {
 5954:             return $udom;
 5955: # ------------------------------------------------------------------- user.name
 5956:         } elsif ($space eq 'name') {
 5957:             return $uname;
 5958: # ---------------------------------------------------- Any other user namespace
 5959:         } else {
 5960: 	    my %reply;
 5961: 	    if (!$publicuser) {
 5962: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5963: 	    }
 5964: 	    return $reply{$qualifierrest};
 5965:         }
 5966:     } elsif ($realm eq 'query') {
 5967: # ---------------------------------------------- pull stuff out of query string
 5968:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5969: 						[$spacequalifierrest]);
 5970: 	return $env{'form.'.$spacequalifierrest}; 
 5971:    } elsif ($realm eq 'request') {
 5972: # ------------------------------------------------------------- request.browser
 5973:         if ($space eq 'browser') {
 5974: 	    if ($qualifier eq 'textremote') {
 5975: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5976: 		    return 1;
 5977: 		} else {
 5978: 		    return 0;
 5979: 		}
 5980: 	    } else {
 5981: 		return $env{'browser.'.$qualifier};
 5982: 	    }
 5983: # ------------------------------------------------------------ request.filename
 5984:         } else {
 5985:             return $env{'request.'.$spacequalifierrest};
 5986:         }
 5987:     } elsif ($realm eq 'course') {
 5988: # ---------------------------------------------------------- course.description
 5989:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5990:     } elsif ($realm eq 'resource') {
 5991: 
 5992: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5993: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5994: 	}
 5995: 
 5996: 	if ($space eq 'title') {
 5997: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5998: 	    return &gettitle($symbparm);
 5999: 	}
 6000: 	
 6001: 	if ($space eq 'map') {
 6002: 	    my ($map) = &decode_symb($symbparm);
 6003: 	    return &symbread($map);
 6004: 	}
 6005: 
 6006: 	my ($section, $group, @groups);
 6007: 	my ($courselevelm,$courselevel);
 6008: 	if ($symbparm && defined($courseid) && 
 6009: 	    $courseid eq $env{'request.course.id'}) {
 6010: 
 6011: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6012: 
 6013: # ----------------------------------------------------- Cascading lookup scheme
 6014: 	    my $symbp=$symbparm;
 6015: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6016: 
 6017: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6018: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6019: 
 6020: 	    if (($env{'user.name'} eq $uname) &&
 6021: 		($env{'user.domain'} eq $udom)) {
 6022: 		$section=$env{'request.course.sec'};
 6023:                 @groups = split(/:/,$env{'request.course.groups'});  
 6024:                 @groups=&sort_course_groups($courseid,@groups); 
 6025: 	    } else {
 6026: 		if (! defined($usection)) {
 6027: 		    $section=&getsection($udom,$uname,$courseid);
 6028: 		} else {
 6029: 		    $section = $usection;
 6030: 		}
 6031:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6032: 	    }
 6033: 
 6034: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6035: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6036: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6037: 
 6038: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6039: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6040: 	    $courselevelm=$courseid.'.'.$mapparm;
 6041: 
 6042: # ----------------------------------------------------------- first, check user
 6043: 
 6044: 	    my $userreply=&resdata($uname,$udom,'user',
 6045: 				       ($courselevelr,$courselevelm,
 6046: 					$courselevel));
 6047: 	    if (defined($userreply)) { return $userreply; }
 6048: 
 6049: # ------------------------------------------------ second, check some of course
 6050:             my $coursereply;
 6051:             if (@groups > 0) {
 6052:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6053:                                        $mapparm,$spacequalifierrest);
 6054:                 if (defined($coursereply)) { return $coursereply; }
 6055:             }
 6056: 
 6057: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6058: 				     $env{'course.'.$courseid.'.domain'},
 6059: 				     'course',
 6060: 				     ($seclevelr,$seclevelm,$seclevel,
 6061: 				      $courselevelr));
 6062: 	    if (defined($coursereply)) { return $coursereply; }
 6063: 
 6064: # ------------------------------------------------------ third, check map parms
 6065: 	    my %parmhash=();
 6066: 	    my $thisparm='';
 6067: 	    if (tie(%parmhash,'GDBM_File',
 6068: 		    $env{'request.course.fn'}.'_parms.db',
 6069: 		    &GDBM_READER(),0640)) {
 6070: 		$thisparm=$parmhash{$symbparm};
 6071: 		untie(%parmhash);
 6072: 	    }
 6073: 	    if ($thisparm) { return $thisparm; }
 6074: 	}
 6075: # ------------------------------------------ fourth, look in resource metadata
 6076: 
 6077: 	$spacequalifierrest=~s/\./\_/;
 6078: 	my $filename;
 6079: 	if (!$symbparm) { $symbparm=&symbread(); }
 6080: 	if ($symbparm) {
 6081: 	    $filename=(&decode_symb($symbparm))[2];
 6082: 	} else {
 6083: 	    $filename=$env{'request.filename'};
 6084: 	}
 6085: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6086: 	if (defined($metadata)) { return $metadata; }
 6087: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6088: 	if (defined($metadata)) { return $metadata; }
 6089: 
 6090: # ---------------------------------------------- fourth, look in rest pf course
 6091: 	if ($symbparm && defined($courseid) && 
 6092: 	    $courseid eq $env{'request.course.id'}) {
 6093: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6094: 				     $env{'course.'.$courseid.'.domain'},
 6095: 				     'course',
 6096: 				     ($courselevelm,$courselevel));
 6097: 	    if (defined($coursereply)) { return $coursereply; }
 6098: 	}
 6099: # ------------------------------------------------------------------ Cascade up
 6100: 	unless ($space eq '0') {
 6101: 	    my @parts=split(/_/,$space);
 6102: 	    my $id=pop(@parts);
 6103: 	    my $part=join('_',@parts);
 6104: 	    if ($part eq '') { $part='0'; }
 6105: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6106: 				 $symbparm,$udom,$uname,$section,1);
 6107: 	    if (defined($partgeneral)) { return $partgeneral; }
 6108: 	}
 6109: 	if ($recurse) { return undef; }
 6110: 	my $pack_def=&packages_tab_default($filename,$varname);
 6111: 	if (defined($pack_def)) { return $pack_def; }
 6112: 
 6113: # ---------------------------------------------------- Any other user namespace
 6114:     } elsif ($realm eq 'environment') {
 6115: # ----------------------------------------------------------------- environment
 6116: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6117: 	    return $env{'environment.'.$spacequalifierrest};
 6118: 	} else {
 6119: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6120: 		return '';
 6121: 	    }
 6122: 	    my %returnhash=&userenvironment($udom,$uname,
 6123: 					    $spacequalifierrest);
 6124: 	    return $returnhash{$spacequalifierrest};
 6125: 	}
 6126:     } elsif ($realm eq 'system') {
 6127: # ----------------------------------------------------------------- system.time
 6128: 	if ($space eq 'time') {
 6129: 	    return time;
 6130:         }
 6131:     } elsif ($realm eq 'server') {
 6132: # ----------------------------------------------------------------- system.time
 6133: 	if ($space eq 'name') {
 6134: 	    return $ENV{'SERVER_NAME'};
 6135:         }
 6136:     }
 6137:     return '';
 6138: }
 6139: 
 6140: sub check_group_parms {
 6141:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6142:     my @groupitems = ();
 6143:     my $resultitem;
 6144:     my @levels = ($symbparm,$mapparm,$what);
 6145:     foreach my $group (@{$groups}) {
 6146:         foreach my $level (@levels) {
 6147:              my $item = $courseid.'.['.$group.'].'.$level;
 6148:              push(@groupitems,$item);
 6149:         }
 6150:     }
 6151:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6152:                             $env{'course.'.$courseid.'.domain'},
 6153:                                      'course',@groupitems);
 6154:     return $coursereply;
 6155: }
 6156: 
 6157: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6158:     my ($courseid,@groups) = @_;
 6159:     @groups = sort(@groups);
 6160:     return @groups;
 6161: }
 6162: 
 6163: sub packages_tab_default {
 6164:     my ($uri,$varname)=@_;
 6165:     my (undef,$part,$name)=split(/\./,$varname);
 6166: 
 6167:     my (@extension,@specifics,$do_default);
 6168:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6169: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6170: 	if ($pack_type eq 'default') {
 6171: 	    $do_default=1;
 6172: 	} elsif ($pack_type eq 'extension') {
 6173: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6174: 	} else {
 6175: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6176: 	}
 6177:     }
 6178:     # first look for a package that matches the requested part id
 6179:     foreach my $package (@specifics) {
 6180: 	my (undef,$pack_type,$pack_part)=@{$package};
 6181: 	next if ($pack_part ne $part);
 6182: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6183: 	    return $packagetab{"$pack_type&$name&default"};
 6184: 	}
 6185:     }
 6186:     # look for any possible matching non extension_ package
 6187:     foreach my $package (@specifics) {
 6188: 	my (undef,$pack_type,$pack_part)=@{$package};
 6189: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6190: 	    return $packagetab{"$pack_type&$name&default"};
 6191: 	}
 6192: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6193: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6194: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6195: 	}
 6196:     }
 6197:     # look for any posible extension_ match
 6198:     foreach my $package (@extension) {
 6199: 	my ($package,$pack_type)=@{$package};
 6200: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6201: 	    return $packagetab{"$pack_type&$name&default"};
 6202: 	}
 6203: 	if (defined($packagetab{$package."&$name&default"})) {
 6204: 	    return $packagetab{$package."&$name&default"};
 6205: 	}
 6206:     }
 6207:     # look for a global default setting
 6208:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6209: 	return $packagetab{"default&$name&default"};
 6210:     }
 6211:     return undef;
 6212: }
 6213: 
 6214: sub add_prefix_and_part {
 6215:     my ($prefix,$part)=@_;
 6216:     my $keyroot;
 6217:     if (defined($prefix) && $prefix !~ /^__/) {
 6218: 	# prefix that has a part already
 6219: 	$keyroot=$prefix;
 6220:     } elsif (defined($prefix)) {
 6221: 	# prefix that is missing a part
 6222: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6223:     } else {
 6224: 	# no prefix at all
 6225: 	if (defined($part)) { $keyroot='_'.$part; }
 6226:     }
 6227:     return $keyroot;
 6228: }
 6229: 
 6230: # ---------------------------------------------------------------- Get metadata
 6231: 
 6232: my %metaentry;
 6233: sub metadata {
 6234:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6235:     $uri=&declutter($uri);
 6236:     # if it is a non metadata possible uri return quickly
 6237:     if (($uri eq '') || 
 6238: 	(($uri =~ m|^/*adm/|) && 
 6239: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6240:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6241: 	($uri =~ m|home/$match_username/public_html/|)) {
 6242: 	return undef;
 6243:     }
 6244:     my $filename=$uri;
 6245:     $uri=~s/\.meta$//;
 6246: #
 6247: # Is the metadata already cached?
 6248: # Look at timestamp of caching
 6249: # Everything is cached by the main uri, libraries are never directly cached
 6250: #
 6251:     if (!defined($liburi)) {
 6252: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6253: 	if (defined($cached)) { return $result->{':'.$what}; }
 6254:     }
 6255:     {
 6256: #
 6257: # Is this a recursive call for a library?
 6258: #
 6259: #	if (! exists($metacache{$uri})) {
 6260: #	    $metacache{$uri}={};
 6261: #	}
 6262:         if ($liburi) {
 6263: 	    $liburi=&declutter($liburi);
 6264:             $filename=$liburi;
 6265:         } else {
 6266: 	    &devalidate_cache_new('meta',$uri);
 6267: 	    undef(%metaentry);
 6268: 	}
 6269:         my %metathesekeys=();
 6270:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6271: 	my $metastring;
 6272: 	if ($uri !~ m -^(editupload)/-) {
 6273: 	    my $file=&filelocation('',&clutter($filename));
 6274: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6275: 	    $metastring=&getfile($file);
 6276: 	}
 6277:         my $parser=HTML::LCParser->new(\$metastring);
 6278:         my $token;
 6279:         undef %metathesekeys;
 6280:         while ($token=$parser->get_token) {
 6281: 	    if ($token->[0] eq 'S') {
 6282: 		if (defined($token->[2]->{'package'})) {
 6283: #
 6284: # This is a package - get package info
 6285: #
 6286: 		    my $package=$token->[2]->{'package'};
 6287: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6288: 		    if (defined($token->[2]->{'id'})) { 
 6289: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6290: 		    }
 6291: 		    if ($metaentry{':packages'}) {
 6292: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6293: 		    } else {
 6294: 			$metaentry{':packages'}=$package.$keyroot;
 6295: 		    }
 6296: 		    foreach my $pack_entry (keys(%packagetab)) {
 6297: 			my $part=$keyroot;
 6298: 			$part=~s/^\_//;
 6299: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6300: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6301: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6302: 			    # ignore package.tab specified default values
 6303:                             # here &package_tab_default() will fetch those
 6304: 			    if ($subp eq 'default') { next; }
 6305: 			    my $value=$packagetab{$pack_entry};
 6306: 			    my $unikey;
 6307: 			    if ($pack =~ /_0$/) {
 6308: 				$unikey='parameter_0_'.$name;
 6309: 				$part=0;
 6310: 			    } else {
 6311: 				$unikey='parameter'.$keyroot.'_'.$name;
 6312: 			    }
 6313: 			    if ($subp eq 'display') {
 6314: 				$value.=' [Part: '.$part.']';
 6315: 			    }
 6316: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6317: 			    $metathesekeys{$unikey}=1;
 6318: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6319: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6320: 			    }
 6321: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6322: 				$metaentry{':'.$unikey}=
 6323: 				    $metaentry{':'.$unikey.'.default'};
 6324: 			    }
 6325: 			}
 6326: 		    }
 6327: 		} else {
 6328: #
 6329: # This is not a package - some other kind of start tag
 6330: #
 6331: 		    my $entry=$token->[1];
 6332: 		    my $unikey;
 6333: 		    if ($entry eq 'import') {
 6334: 			$unikey='';
 6335: 		    } else {
 6336: 			$unikey=$entry;
 6337: 		    }
 6338: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6339: 
 6340: 		    if (defined($token->[2]->{'id'})) { 
 6341: 			$unikey.='_'.$token->[2]->{'id'}; 
 6342: 		    }
 6343: 
 6344: 		    if ($entry eq 'import') {
 6345: #
 6346: # Importing a library here
 6347: #
 6348: 			if ($depthcount<20) {
 6349: 			    my $location=$parser->get_text('/import');
 6350: 			    my $dir=$filename;
 6351: 			    $dir=~s|[^/]*$||;
 6352: 			    $location=&filelocation($dir,$location);
 6353: 			    my $metadata = 
 6354: 				&metadata($uri,'keys', $location,$unikey,
 6355: 					  $depthcount+1);
 6356: 			    foreach my $meta (split(',',$metadata)) {
 6357: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6358: 				$metathesekeys{$meta}=1;
 6359: 			    }
 6360: 			}
 6361: 		    } else { 
 6362: 			
 6363: 			if (defined($token->[2]->{'name'})) { 
 6364: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6365: 			}
 6366: 			$metathesekeys{$unikey}=1;
 6367: 			foreach my $param (@{$token->[3]}) {
 6368: 			    $metaentry{':'.$unikey.'.'.$param} =
 6369: 				$token->[2]->{$param};
 6370: 			}
 6371: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6372: 			my $default=$metaentry{':'.$unikey.'.default'};
 6373: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6374: 		 # only ws inside the tag, and not in default, so use default
 6375: 		 # as value
 6376: 			    $metaentry{':'.$unikey}=$default;
 6377: 			} else {
 6378: 		  # either something interesting inside the tag or default
 6379:                   # uninteresting
 6380: 			    $metaentry{':'.$unikey}=$internaltext;
 6381: 			}
 6382: # end of not-a-package not-a-library import
 6383: 		    }
 6384: # end of not-a-package start tag
 6385: 		}
 6386: # the next is the end of "start tag"
 6387: 	    }
 6388: 	}
 6389: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6390: 	foreach my $key (keys(%packagetab)) {
 6391: 	    #no specific packages #how's our extension
 6392: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6393: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6394: 					 \%metathesekeys);
 6395: 	}
 6396: 	if (!exists($metaentry{':packages'})) {
 6397: 	    foreach my $key (keys(%packagetab)) {
 6398: 		#no specific packages well let's get default then
 6399: 		if ($key!~/^default&/) { next; }
 6400: 		&metadata_create_package_def($uri,$key,'default',
 6401: 					     \%metathesekeys);
 6402: 	    }
 6403: 	}
 6404: # are there custom rights to evaluate
 6405: 	if ($metaentry{':copyright'} eq 'custom') {
 6406: 
 6407:     #
 6408:     # Importing a rights file here
 6409:     #
 6410: 	    unless ($depthcount) {
 6411: 		my $location=$metaentry{':customdistributionfile'};
 6412: 		my $dir=$filename;
 6413: 		$dir=~s|[^/]*$||;
 6414: 		$location=&filelocation($dir,$location);
 6415: 		my $rights_metadata =
 6416: 		    &metadata($uri,'keys',$location,'_rights',
 6417: 			      $depthcount+1);
 6418: 		foreach my $rights (split(',',$rights_metadata)) {
 6419: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6420: 		    $metathesekeys{$rights}=1;
 6421: 		}
 6422: 	    }
 6423: 	}
 6424: 	# uniqifiy package listing
 6425: 	my %seen;
 6426: 	my @uniq_packages =
 6427: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6428: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6429: 
 6430: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6431: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6432: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6433: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6434: # this is the end of "was not already recently cached
 6435:     }
 6436:     return $metaentry{':'.$what};
 6437: }
 6438: 
 6439: sub metadata_create_package_def {
 6440:     my ($uri,$key,$package,$metathesekeys)=@_;
 6441:     my ($pack,$name,$subp)=split(/\&/,$key);
 6442:     if ($subp eq 'default') { next; }
 6443:     
 6444:     if (defined($metaentry{':packages'})) {
 6445: 	$metaentry{':packages'}.=','.$package;
 6446:     } else {
 6447: 	$metaentry{':packages'}=$package;
 6448:     }
 6449:     my $value=$packagetab{$key};
 6450:     my $unikey;
 6451:     $unikey='parameter_0_'.$name;
 6452:     $metaentry{':'.$unikey.'.part'}=0;
 6453:     $$metathesekeys{$unikey}=1;
 6454:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6455: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6456:     }
 6457:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6458: 	$metaentry{':'.$unikey}=
 6459: 	    $metaentry{':'.$unikey.'.default'};
 6460:     }
 6461: }
 6462: 
 6463: sub metadata_generate_part0 {
 6464:     my ($metadata,$metacache,$uri) = @_;
 6465:     my %allnames;
 6466:     foreach my $metakey (keys(%$metadata)) {
 6467: 	if ($metakey=~/^parameter\_(.*)/) {
 6468: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6469: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6470: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6471: 	    $allnames{$name}=$part;
 6472: 	  }
 6473: 	}
 6474:     }
 6475:     foreach my $name (keys(%allnames)) {
 6476:       $$metadata{"parameter_0_$name"}=1;
 6477:       my $key=":parameter_0_$name";
 6478:       $$metacache{"$key.part"}='0';
 6479:       $$metacache{"$key.name"}=$name;
 6480:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6481: 					   $allnames{$name}.'_'.$name.
 6482: 					   '.type'};
 6483:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6484: 			     '.display'};
 6485:       my $expr='[Part: '.$allnames{$name}.']';
 6486:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6487:       $$metacache{"$key.display"}=$olddis;
 6488:     }
 6489: }
 6490: 
 6491: # ------------------------------------------------------ Devalidate title cache
 6492: 
 6493: sub devalidate_title_cache {
 6494:     my ($url)=@_;
 6495:     if (!$env{'request.course.id'}) { return; }
 6496:     my $symb=&symbread($url);
 6497:     if (!$symb) { return; }
 6498:     my $key=$env{'request.course.id'}."\0".$symb;
 6499:     &devalidate_cache_new('title',$key);
 6500: }
 6501: 
 6502: # ------------------------------------------------- Get the title of a resource
 6503: 
 6504: sub gettitle {
 6505:     my $urlsymb=shift;
 6506:     my $symb=&symbread($urlsymb);
 6507:     if ($symb) {
 6508: 	my $key=$env{'request.course.id'}."\0".$symb;
 6509: 	my ($result,$cached)=&is_cached_new('title',$key);
 6510: 	if (defined($cached)) { 
 6511: 	    return $result;
 6512: 	}
 6513: 	my ($map,$resid,$url)=&decode_symb($symb);
 6514: 	my $title='';
 6515: 	my %bighash;
 6516: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6517: 		&GDBM_READER(),0640)) {
 6518: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6519: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6520: 	    untie %bighash;
 6521: 	}
 6522: 	$title=~s/\&colon\;/\:/gs;
 6523: 	if ($title) {
 6524: 	    return &do_cache_new('title',$key,$title,600);
 6525: 	}
 6526: 	$urlsymb=$url;
 6527:     }
 6528:     my $title=&metadata($urlsymb,'title');
 6529:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6530:     return $title;
 6531: }
 6532: 
 6533: sub get_slot {
 6534:     my ($which,$cnum,$cdom)=@_;
 6535:     if (!$cnum || !$cdom) {
 6536: 	(undef,my $courseid)=&whichuser();
 6537: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6538: 	$cnum=$env{'course.'.$courseid.'.num'};
 6539:     }
 6540:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6541:     my %slotinfo;
 6542:     if (exists($remembered{$key})) {
 6543: 	$slotinfo{$which} = $remembered{$key};
 6544:     } else {
 6545: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6546: 	&Apache::lonhomework::showhash(%slotinfo);
 6547: 	my ($tmp)=keys(%slotinfo);
 6548: 	if ($tmp=~/^error:/) { return (); }
 6549: 	$remembered{$key} = $slotinfo{$which};
 6550:     }
 6551:     if (ref($slotinfo{$which}) eq 'HASH') {
 6552: 	return %{$slotinfo{$which}};
 6553:     }
 6554:     return $slotinfo{$which};
 6555: }
 6556: # ------------------------------------------------- Update symbolic store links
 6557: 
 6558: sub symblist {
 6559:     my ($mapname,%newhash)=@_;
 6560:     $mapname=&deversion(&declutter($mapname));
 6561:     my %hash;
 6562:     if (($env{'request.course.fn'}) && (%newhash)) {
 6563:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6564:                       &GDBM_WRCREAT(),0640)) {
 6565: 	    foreach my $url (keys %newhash) {
 6566: 		next if ($url eq 'last_known'
 6567: 			 && $env{'form.no_update_last_known'});
 6568: 		$hash{declutter($url)}=&encode_symb($mapname,
 6569: 						    $newhash{$url}->[1],
 6570: 						    $newhash{$url}->[0]);
 6571:             }
 6572:             if (untie(%hash)) {
 6573: 		return 'ok';
 6574:             }
 6575:         }
 6576:     }
 6577:     return 'error';
 6578: }
 6579: 
 6580: # --------------------------------------------------------------- Verify a symb
 6581: 
 6582: sub symbverify {
 6583:     my ($symb,$thisurl)=@_;
 6584:     my $thisfn=$thisurl;
 6585:     $thisfn=&declutter($thisfn);
 6586: # direct jump to resource in page or to a sequence - will construct own symbs
 6587:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6588: # check URL part
 6589:     my ($map,$resid,$url)=&decode_symb($symb);
 6590: 
 6591:     unless ($url eq $thisfn) { return 0; }
 6592: 
 6593:     $symb=&symbclean($symb);
 6594:     $thisurl=&deversion($thisurl);
 6595:     $thisfn=&deversion($thisfn);
 6596: 
 6597:     my %bighash;
 6598:     my $okay=0;
 6599: 
 6600:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6601:                             &GDBM_READER(),0640)) {
 6602:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6603:         unless ($ids) { 
 6604:            $ids=$bighash{'ids_/'.$thisurl};
 6605:         }
 6606:         if ($ids) {
 6607: # ------------------------------------------------------------------- Has ID(s)
 6608: 	    foreach my $id (split(/\,/,$ids)) {
 6609: 	       my ($mapid,$resid)=split(/\./,$id);
 6610:                if (
 6611:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6612:    eq $symb) { 
 6613: 		   if (($env{'request.role.adv'}) ||
 6614: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6615: 		       $okay=1; 
 6616: 		   }
 6617: 	       }
 6618: 	   }
 6619:         }
 6620: 	untie(%bighash);
 6621:     }
 6622:     return $okay;
 6623: }
 6624: 
 6625: # --------------------------------------------------------------- Clean-up symb
 6626: 
 6627: sub symbclean {
 6628:     my $symb=shift;
 6629:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6630: # remove version from map
 6631:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6632: 
 6633: # remove version from URL
 6634:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6635: 
 6636: # remove wrapper
 6637: 
 6638:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6639:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6640:     return $symb;
 6641: }
 6642: 
 6643: # ---------------------------------------------- Split symb to find map and url
 6644: 
 6645: sub encode_symb {
 6646:     my ($map,$resid,$url)=@_;
 6647:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6648: }
 6649: 
 6650: sub decode_symb {
 6651:     my $symb=shift;
 6652:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6653:     my ($map,$resid,$url)=split(/___/,$symb);
 6654:     return (&fixversion($map),$resid,&fixversion($url));
 6655: }
 6656: 
 6657: sub fixversion {
 6658:     my $fn=shift;
 6659:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6660:     my %bighash;
 6661:     my $uri=&clutter($fn);
 6662:     my $key=$env{'request.course.id'}.'_'.$uri;
 6663: # is this cached?
 6664:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6665:     if (defined($cached)) { return $result; }
 6666: # unfortunately not cached, or expired
 6667:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6668: 	    &GDBM_READER(),0640)) {
 6669:  	if ($bighash{'version_'.$uri}) {
 6670:  	    my $version=$bighash{'version_'.$uri};
 6671:  	    unless (($version eq 'mostrecent') || 
 6672: 		    ($version==&getversion($uri))) {
 6673:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6674:  	    }
 6675:  	}
 6676:  	untie %bighash;
 6677:     }
 6678:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6679: }
 6680: 
 6681: sub deversion {
 6682:     my $url=shift;
 6683:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6684:     return $url;
 6685: }
 6686: 
 6687: # ------------------------------------------------------ Return symb list entry
 6688: 
 6689: sub symbread {
 6690:     my ($thisfn,$donotrecurse)=@_;
 6691:     my $cache_str='request.symbread.cached.'.$thisfn;
 6692:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6693: # no filename provided? try from environment
 6694:     unless ($thisfn) {
 6695:         if ($env{'request.symb'}) {
 6696: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6697: 	}
 6698: 	$thisfn=$env{'request.filename'};
 6699:     }
 6700:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6701: # is that filename actually a symb? Verify, clean, and return
 6702:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6703: 	if (&symbverify($thisfn,$1)) {
 6704: 	    return $env{$cache_str}=&symbclean($thisfn);
 6705: 	}
 6706:     }
 6707:     $thisfn=declutter($thisfn);
 6708:     my %hash;
 6709:     my %bighash;
 6710:     my $syval='';
 6711:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6712:         my $targetfn = $thisfn;
 6713:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6714:             $targetfn = 'adm/wrapper/'.$thisfn;
 6715:         }
 6716: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6717: 	    $targetfn=$1;
 6718: 	}
 6719:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6720:                       &GDBM_READER(),0640)) {
 6721: 	    $syval=$hash{$targetfn};
 6722:             untie(%hash);
 6723:         }
 6724: # ---------------------------------------------------------- There was an entry
 6725:         if ($syval) {
 6726: 	    #unless ($syval=~/\_\d+$/) {
 6727: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6728: 		    #&appenv('request.ambiguous' => $thisfn);
 6729: 		    #return $env{$cache_str}='';
 6730: 		#}    
 6731: 		#$syval.=$1;
 6732: 	    #}
 6733:         } else {
 6734: # ------------------------------------------------------- Was not in symb table
 6735:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6736:                             &GDBM_READER(),0640)) {
 6737: # ---------------------------------------------- Get ID(s) for current resource
 6738:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6739:               unless ($ids) { 
 6740:                  $ids=$bighash{'ids_/'.$thisfn};
 6741:               }
 6742:               unless ($ids) {
 6743: # alias?
 6744: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6745:               }
 6746:               if ($ids) {
 6747: # ------------------------------------------------------------------- Has ID(s)
 6748:                  my @possibilities=split(/\,/,$ids);
 6749:                  if ($#possibilities==0) {
 6750: # ----------------------------------------------- There is only one possibility
 6751: 		     my ($mapid,$resid)=split(/\./,$ids);
 6752: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6753: 						    $resid,$thisfn);
 6754:                  } elsif (!$donotrecurse) {
 6755: # ------------------------------------------ There is more than one possibility
 6756:                      my $realpossible=0;
 6757:                      foreach my $id (@possibilities) {
 6758: 			 my $file=$bighash{'src_'.$id};
 6759:                          if (&allowed('bre',$file)) {
 6760:          		    my ($mapid,$resid)=split(/\./,$id);
 6761:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6762: 				$realpossible++;
 6763:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6764: 						    $resid,$thisfn);
 6765:                             }
 6766: 			 }
 6767:                      }
 6768: 		     if ($realpossible!=1) { $syval=''; }
 6769:                  } else {
 6770:                      $syval='';
 6771:                  }
 6772: 	      }
 6773:               untie(%bighash)
 6774:            }
 6775:         }
 6776:         if ($syval) {
 6777: 	    return $env{$cache_str}=$syval;
 6778:         }
 6779:     }
 6780:     &appenv('request.ambiguous' => $thisfn);
 6781:     return $env{$cache_str}='';
 6782: }
 6783: 
 6784: # ---------------------------------------------------------- Return random seed
 6785: 
 6786: sub numval {
 6787:     my $txt=shift;
 6788:     $txt=~tr/A-J/0-9/;
 6789:     $txt=~tr/a-j/0-9/;
 6790:     $txt=~tr/K-T/0-9/;
 6791:     $txt=~tr/k-t/0-9/;
 6792:     $txt=~tr/U-Z/0-5/;
 6793:     $txt=~tr/u-z/0-5/;
 6794:     $txt=~s/\D//g;
 6795:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6796:     return int($txt);
 6797: }
 6798: 
 6799: sub numval2 {
 6800:     my $txt=shift;
 6801:     $txt=~tr/A-J/0-9/;
 6802:     $txt=~tr/a-j/0-9/;
 6803:     $txt=~tr/K-T/0-9/;
 6804:     $txt=~tr/k-t/0-9/;
 6805:     $txt=~tr/U-Z/0-5/;
 6806:     $txt=~tr/u-z/0-5/;
 6807:     $txt=~s/\D//g;
 6808:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6809:     my $total;
 6810:     foreach my $val (@txts) { $total+=$val; }
 6811:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6812:     return int($total);
 6813: }
 6814: 
 6815: sub numval3 {
 6816:     use integer;
 6817:     my $txt=shift;
 6818:     $txt=~tr/A-J/0-9/;
 6819:     $txt=~tr/a-j/0-9/;
 6820:     $txt=~tr/K-T/0-9/;
 6821:     $txt=~tr/k-t/0-9/;
 6822:     $txt=~tr/U-Z/0-5/;
 6823:     $txt=~tr/u-z/0-5/;
 6824:     $txt=~s/\D//g;
 6825:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6826:     my $total;
 6827:     foreach my $val (@txts) { $total+=$val; }
 6828:     if ($_64bit) { $total=(($total<<32)>>32); }
 6829:     return $total;
 6830: }
 6831: 
 6832: sub digest {
 6833:     my ($data)=@_;
 6834:     my $digest=&Digest::MD5::md5($data);
 6835:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6836:     my ($e,$f);
 6837:     {
 6838:         use integer;
 6839:         $e=($a+$b);
 6840:         $f=($c+$d);
 6841:         if ($_64bit) {
 6842:             $e=(($e<<32)>>32);
 6843:             $f=(($f<<32)>>32);
 6844:         }
 6845:     }
 6846:     if (wantarray) {
 6847: 	return ($e,$f);
 6848:     } else {
 6849: 	my $g;
 6850: 	{
 6851: 	    use integer;
 6852: 	    $g=($e+$f);
 6853: 	    if ($_64bit) {
 6854: 		$g=(($g<<32)>>32);
 6855: 	    }
 6856: 	}
 6857: 	return $g;
 6858:     }
 6859: }
 6860: 
 6861: sub latest_rnd_algorithm_id {
 6862:     return '64bit5';
 6863: }
 6864: 
 6865: sub get_rand_alg {
 6866:     my ($courseid)=@_;
 6867:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6868:     if ($courseid) {
 6869: 	return $env{"course.$courseid.rndseed"};
 6870:     }
 6871:     return &latest_rnd_algorithm_id();
 6872: }
 6873: 
 6874: sub validCODE {
 6875:     my ($CODE)=@_;
 6876:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6877:     return 0;
 6878: }
 6879: 
 6880: sub getCODE {
 6881:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6882:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6883: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6884: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6885: 	return $Apache::lonhomework::history{'resource.CODE'};
 6886:     }
 6887:     return undef;
 6888: }
 6889: 
 6890: sub rndseed {
 6891:     my ($symb,$courseid,$domain,$username)=@_;
 6892: 
 6893:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6894:     if (!$symb) {
 6895: 	unless ($symb=$wsymb) { return time; }
 6896:     }
 6897:     if (!$courseid) { $courseid=$wcourseid; }
 6898:     if (!$domain) { $domain=$wdomain; }
 6899:     if (!$username) { $username=$wusername }
 6900:     my $which=&get_rand_alg();
 6901: 
 6902:     if (defined(&getCODE())) {
 6903: 	if ($which eq '64bit5') {
 6904: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6905: 	} elsif ($which eq '64bit4') {
 6906: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6907: 	} else {
 6908: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6909: 	}
 6910:     } elsif ($which eq '64bit5') {
 6911: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6912:     } elsif ($which eq '64bit4') {
 6913: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6914:     } elsif ($which eq '64bit3') {
 6915: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6916:     } elsif ($which eq '64bit2') {
 6917: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6918:     } elsif ($which eq '64bit') {
 6919: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6920:     }
 6921:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6922: }
 6923: 
 6924: sub rndseed_32bit {
 6925:     my ($symb,$courseid,$domain,$username)=@_;
 6926:     {
 6927: 	use integer;
 6928: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6929: 	my $symbseed=numval($symb) << 22;
 6930: 	my $namechck=unpack("%32C*",$username) << 17;
 6931: 	my $nameseed=numval($username) << 12;
 6932: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6933: 	my $courseseed=unpack("%32C*",$courseid);
 6934: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6936: 	#&logthis("rndseed :$num:$symb");
 6937: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6938: 	return $num;
 6939:     }
 6940: }
 6941: 
 6942: sub rndseed_64bit {
 6943:     my ($symb,$courseid,$domain,$username)=@_;
 6944:     {
 6945: 	use integer;
 6946: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6947: 	my $symbseed=numval($symb) << 10;
 6948: 	my $namechck=unpack("%32S*",$username);
 6949: 	
 6950: 	my $nameseed=numval($username) << 21;
 6951: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6952: 	my $courseseed=unpack("%32S*",$courseid);
 6953: 	
 6954: 	my $num1=$symbchck+$symbseed+$namechck;
 6955: 	my $num2=$nameseed+$domainseed+$courseseed;
 6956: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6957: 	#&logthis("rndseed :$num:$symb");
 6958: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6959: 	return "$num1,$num2";
 6960:     }
 6961: }
 6962: 
 6963: sub rndseed_64bit2 {
 6964:     my ($symb,$courseid,$domain,$username)=@_;
 6965:     {
 6966: 	use integer;
 6967: 	# strings need to be an even # of cahracters long, it it is odd the
 6968:         # last characters gets thrown away
 6969: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6970: 	my $symbseed=numval($symb) << 10;
 6971: 	my $namechck=unpack("%32S*",$username.' ');
 6972: 	
 6973: 	my $nameseed=numval($username) << 21;
 6974: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6975: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6976: 	
 6977: 	my $num1=$symbchck+$symbseed+$namechck;
 6978: 	my $num2=$nameseed+$domainseed+$courseseed;
 6979: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6980: 	#&logthis("rndseed :$num:$symb");
 6981: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6982: 	return "$num1,$num2";
 6983:     }
 6984: }
 6985: 
 6986: sub rndseed_64bit3 {
 6987:     my ($symb,$courseid,$domain,$username)=@_;
 6988:     {
 6989: 	use integer;
 6990: 	# strings need to be an even # of cahracters long, it it is odd the
 6991:         # last characters gets thrown away
 6992: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6993: 	my $symbseed=numval2($symb) << 10;
 6994: 	my $namechck=unpack("%32S*",$username.' ');
 6995: 	
 6996: 	my $nameseed=numval2($username) << 21;
 6997: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6998: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6999: 	
 7000: 	my $num1=$symbchck+$symbseed+$namechck;
 7001: 	my $num2=$nameseed+$domainseed+$courseseed;
 7002: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7003: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7004: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7005: 	
 7006: 	return "$num1:$num2";
 7007:     }
 7008: }
 7009: 
 7010: sub rndseed_64bit4 {
 7011:     my ($symb,$courseid,$domain,$username)=@_;
 7012:     {
 7013: 	use integer;
 7014: 	# strings need to be an even # of cahracters long, it it is odd the
 7015:         # last characters gets thrown away
 7016: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7017: 	my $symbseed=numval3($symb) << 10;
 7018: 	my $namechck=unpack("%32S*",$username.' ');
 7019: 	
 7020: 	my $nameseed=numval3($username) << 21;
 7021: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7022: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7023: 	
 7024: 	my $num1=$symbchck+$symbseed+$namechck;
 7025: 	my $num2=$nameseed+$domainseed+$courseseed;
 7026: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7027: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7028: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7029: 	
 7030: 	return "$num1:$num2";
 7031:     }
 7032: }
 7033: 
 7034: sub rndseed_64bit5 {
 7035:     my ($symb,$courseid,$domain,$username)=@_;
 7036:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7037:     return "$num1:$num2";
 7038: }
 7039: 
 7040: sub rndseed_CODE_64bit {
 7041:     my ($symb,$courseid,$domain,$username)=@_;
 7042:     {
 7043: 	use integer;
 7044: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7045: 	my $symbseed=numval2($symb);
 7046: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7047: 	my $CODEseed=numval(&getCODE());
 7048: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7049: 	my $num1=$symbseed+$CODEchck;
 7050: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7051: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7052: 	#&logthis("rndseed :$num1:$num2:$symb");
 7053: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7054: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7055: 	return "$num1:$num2";
 7056:     }
 7057: }
 7058: 
 7059: sub rndseed_CODE_64bit4 {
 7060:     my ($symb,$courseid,$domain,$username)=@_;
 7061:     {
 7062: 	use integer;
 7063: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7064: 	my $symbseed=numval3($symb);
 7065: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7066: 	my $CODEseed=numval3(&getCODE());
 7067: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7068: 	my $num1=$symbseed+$CODEchck;
 7069: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7070: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7071: 	#&logthis("rndseed :$num1:$num2:$symb");
 7072: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7073: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7074: 	return "$num1:$num2";
 7075:     }
 7076: }
 7077: 
 7078: sub rndseed_CODE_64bit5 {
 7079:     my ($symb,$courseid,$domain,$username)=@_;
 7080:     my $code = &getCODE();
 7081:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7082:     return "$num1:$num2";
 7083: }
 7084: 
 7085: sub setup_random_from_rndseed {
 7086:     my ($rndseed)=@_;
 7087:     if ($rndseed =~/([,:])/) {
 7088: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7089: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7090:     } else {
 7091: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7092:     }
 7093: }
 7094: 
 7095: sub latest_receipt_algorithm_id {
 7096:     return 'receipt3';
 7097: }
 7098: 
 7099: sub recunique {
 7100:     my $fucourseid=shift;
 7101:     my $unique;
 7102:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7103: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7104: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7105:     } else {
 7106: 	$unique=$perlvar{'lonReceipt'};
 7107:     }
 7108:     return unpack("%32C*",$unique);
 7109: }
 7110: 
 7111: sub recprefix {
 7112:     my $fucourseid=shift;
 7113:     my $prefix;
 7114:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7115: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7116: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7117:     } else {
 7118: 	$prefix=$perlvar{'lonHostID'};
 7119:     }
 7120:     return unpack("%32C*",$prefix);
 7121: }
 7122: 
 7123: sub ireceipt {
 7124:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7125: 
 7126:     my $return =&recprefix($fucourseid).'-';
 7127: 
 7128:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7129: 	$env{'request.state'} eq 'construct') {
 7130: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7131: 	return $return;
 7132:     }
 7133: 
 7134:     my $cuname=unpack("%32C*",$funame);
 7135:     my $cudom=unpack("%32C*",$fudom);
 7136:     my $cucourseid=unpack("%32C*",$fucourseid);
 7137:     my $cusymb=unpack("%32C*",$fusymb);
 7138:     my $cunique=&recunique($fucourseid);
 7139:     my $cpart=unpack("%32S*",$part);
 7140:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7141: 
 7142: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7143: 			       
 7144: 	$return.= ($cunique%$cuname+
 7145: 		   $cunique%$cudom+
 7146: 		   $cusymb%$cuname+
 7147: 		   $cusymb%$cudom+
 7148: 		   $cucourseid%$cuname+
 7149: 		   $cucourseid%$cudom+
 7150: 		   $cpart%$cuname+
 7151: 		   $cpart%$cudom);
 7152:     } else {
 7153: 	$return.= ($cunique%$cuname+
 7154: 		   $cunique%$cudom+
 7155: 		   $cusymb%$cuname+
 7156: 		   $cusymb%$cudom+
 7157: 		   $cucourseid%$cuname+
 7158: 		   $cucourseid%$cudom);
 7159:     }
 7160:     return $return;
 7161: }
 7162: 
 7163: sub receipt {
 7164:     my ($part)=@_;
 7165:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7166:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7167: }
 7168: 
 7169: sub whichuser {
 7170:     my ($passedsymb)=@_;
 7171:     my ($symb,$courseid,$domain,$name,$publicuser);
 7172:     if (defined($env{'form.grade_symb'})) {
 7173: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7174: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7175: 	if (!$allowed &&
 7176: 	    exists($env{'request.course.sec'}) &&
 7177: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7178: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7179: 			      '/'.$env{'request.course.sec'});
 7180: 	}
 7181: 	if ($allowed) {
 7182: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7183: 	    $courseid=$tmp_courseid;
 7184: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7185: 	    ($name)=&get_env_multiple('form.grade_username');
 7186: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7187: 	}
 7188:     }
 7189:     if (!$passedsymb) {
 7190: 	$symb=&symbread();
 7191:     } else {
 7192: 	$symb=$passedsymb;
 7193:     }
 7194:     $courseid=$env{'request.course.id'};
 7195:     $domain=$env{'user.domain'};
 7196:     $name=$env{'user.name'};
 7197:     if ($name eq 'public' && $domain eq 'public') {
 7198: 	if (!defined($env{'form.username'})) {
 7199: 	    $env{'form.username'}.=time.rand(10000000);
 7200: 	}
 7201: 	$name.=$env{'form.username'};
 7202:     }
 7203:     return ($symb,$courseid,$domain,$name,$publicuser);
 7204: 
 7205: }
 7206: 
 7207: # ------------------------------------------------------------ Serves up a file
 7208: # returns either the contents of the file or 
 7209: # -1 if the file doesn't exist
 7210: #
 7211: # if the target is a file that was uploaded via DOCS, 
 7212: # a check will be made to see if a current copy exists on the local server,
 7213: # if it does this will be served, otherwise a copy will be retrieved from
 7214: # the home server for the course and stored in /home/httpd/html/userfiles on
 7215: # the local server.   
 7216: 
 7217: sub getfile {
 7218:     my ($file) = @_;
 7219:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7220:     &repcopy($file);
 7221:     return &readfile($file);
 7222: }
 7223: 
 7224: sub repcopy_userfile {
 7225:     my ($file)=@_;
 7226:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7227:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7228:     my ($cdom,$cnum,$filename) = 
 7229: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7230:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7231:     if (-e "$file") {
 7232: # we already have a local copy, check it out
 7233: 	my @fileinfo = stat($file);
 7234: 	my $rtncode;
 7235: 	my $info;
 7236: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7237: 	if ($lwpresp ne 'ok') {
 7238: # there is no such file anymore, even though we had a local copy
 7239: 	    if ($rtncode eq '404') {
 7240: 		unlink($file);
 7241: 	    }
 7242: 	    return -1;
 7243: 	}
 7244: 	if ($info < $fileinfo[9]) {
 7245: # nice, the file we have is up-to-date, just say okay
 7246: 	    return 'ok';
 7247: 	} else {
 7248: # the file is outdated, get rid of it
 7249: 	    unlink($file);
 7250: 	}
 7251:     }
 7252: # one way or the other, at this point, we don't have the file
 7253: # construct the correct path for the file
 7254:     my @parts = ($cdom,$cnum); 
 7255:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7256: 	push @parts, split(/\//,$1);
 7257:     }
 7258:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7259:     foreach my $part (@parts) {
 7260: 	$path .= '/'.$part;
 7261: 	if (!-e $path) {
 7262: 	    mkdir($path,0770);
 7263: 	}
 7264:     }
 7265: # now the path exists for sure
 7266: # get a user agent
 7267:     my $ua=new LWP::UserAgent;
 7268:     my $transferfile=$file.'.in.transfer';
 7269: # FIXME: this should flock
 7270:     if (-e $transferfile) { return 'ok'; }
 7271:     my $request;
 7272:     $uri=~s/^\///;
 7273:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7274:     my $response=$ua->request($request,$transferfile);
 7275: # did it work?
 7276:     if ($response->is_error()) {
 7277: 	unlink($transferfile);
 7278: 	&logthis("Userfile repcopy failed for $uri");
 7279: 	return -1;
 7280:     }
 7281: # worked, rename the transfer file
 7282:     rename($transferfile,$file);
 7283:     return 'ok';
 7284: }
 7285: 
 7286: sub tokenwrapper {
 7287:     my $uri=shift;
 7288:     $uri=~s|^http\://([^/]+)||;
 7289:     $uri=~s|^/||;
 7290:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7291:     my $token=$1;
 7292:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7293:     if ($udom && $uname && $file) {
 7294: 	$file=~s|(\?\.*)*$||;
 7295:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7296:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7297:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7298:                                '&tokenissued='.$perlvar{'lonHostID'};
 7299:     } else {
 7300:         return '/adm/notfound.html';
 7301:     }
 7302: }
 7303: 
 7304: # call with reqtype HEAD: get last modification time
 7305: # call with reqtype GET: get the file contents
 7306: # Do not call this with reqtype GET for large files! It loads everything into memory
 7307: #
 7308: sub getuploaded {
 7309:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7310:     $uri=~s/^\///;
 7311:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7312:     my $ua=new LWP::UserAgent;
 7313:     my $request=new HTTP::Request($reqtype,$uri);
 7314:     my $response=$ua->request($request);
 7315:     $$rtncode = $response->code;
 7316:     if (! $response->is_success()) {
 7317: 	return 'failed';
 7318:     }      
 7319:     if ($reqtype eq 'HEAD') {
 7320: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7321:     } elsif ($reqtype eq 'GET') {
 7322: 	$$info = $response->content;
 7323:     }
 7324:     return 'ok';
 7325: }
 7326: 
 7327: sub readfile {
 7328:     my $file = shift;
 7329:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7330:     my $fh;
 7331:     open($fh,"<$file");
 7332:     my $a='';
 7333:     while (my $line = <$fh>) { $a .= $line; }
 7334:     return $a;
 7335: }
 7336: 
 7337: sub filelocation {
 7338:     my ($dir,$file) = @_;
 7339:     my $location;
 7340:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7341: 
 7342:     if ($file =~ m-^/adm/-) {
 7343: 	$file=~s-^/adm/wrapper/-/-;
 7344: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7345:     }
 7346:     if ($file=~m:^/~:) { # is a contruction space reference
 7347:         $location = $file;
 7348:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7349:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7350: 	# is a correct contruction space reference
 7351:         $location = $file;
 7352:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7353:         my ($udom,$uname,$filename)=
 7354:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7355:         my $home=&homeserver($uname,$udom);
 7356:         my $is_me=0;
 7357:         my @ids=&current_machine_ids();
 7358:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7359:         if ($is_me) {
 7360:   	    $location=&propath($udom,$uname).
 7361:   	      '/userfiles/'.$filename;
 7362:         } else {
 7363:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7364:   	      $udom.'/'.$uname.'/'.$filename;
 7365:         }
 7366:     } else {
 7367:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7368:         $file=~s:^/res/:/:;
 7369:         if ( !( $file =~ m:^/:) ) {
 7370:             $location = $dir. '/'.$file;
 7371:         } else {
 7372:             $location = '/home/httpd/html/res'.$file;
 7373:         }
 7374:     }
 7375:     $location=~s://+:/:g; # remove duplicate /
 7376:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7377:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7378:     return $location;
 7379: }
 7380: 
 7381: sub hreflocation {
 7382:     my ($dir,$file)=@_;
 7383:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7384: 	$file=filelocation($dir,$file);
 7385:     } elsif ($file=~m-^/adm/-) {
 7386: 	$file=~s-^/adm/wrapper/-/-;
 7387: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7388:     }
 7389:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7390: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7391:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7392: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7393:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7394: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7395: 	    -/uploaded/$1/$2/-x;
 7396:     }
 7397:     return $file;
 7398: }
 7399: 
 7400: sub current_machine_domains {
 7401:     my $hostname=&hostname($perlvar{'lonHostID'});
 7402:     my @domains;
 7403:     my %hostname = &all_hostnames();
 7404:     while( my($id, $name) = each(%hostname)) {
 7405: #	&logthis("-$id-$name-$hostname-");
 7406: 	if ($hostname eq $name) {
 7407: 	    push(@domains,$hostdom{$id});
 7408: 	}
 7409:     }
 7410:     return @domains;
 7411: }
 7412: 
 7413: sub current_machine_ids {
 7414:     my $hostname=&hostname($perlvar{'lonHostID'});
 7415:     my @ids;
 7416:     my %hostname = &all_hostnames();
 7417:     while( my($id, $name) = each(%hostname)) {
 7418: #	&logthis("-$id-$name-$hostname-");
 7419: 	if ($hostname eq $name) {
 7420: 	    push(@ids,$id);
 7421: 	}
 7422:     }
 7423:     return @ids;
 7424: }
 7425: 
 7426: sub additional_machine_domains {
 7427:     my @domains;
 7428:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7429:     while( my $line = <$fh>) {
 7430:         $line =~ s/\s//g;
 7431:         push(@domains,$line);
 7432:     }
 7433:     return @domains;
 7434: }
 7435: 
 7436: sub default_login_domain {
 7437:     my $domain = $perlvar{'lonDefDomain'};
 7438:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7439:     foreach my $posdom (&current_machine_domains(),
 7440:                         &additional_machine_domains()) {
 7441:         if (lc($posdom) eq lc($testdomain)) {
 7442:             $domain=$posdom;
 7443:             last;
 7444:         }
 7445:     }
 7446:     return $domain;
 7447: }
 7448: 
 7449: # ------------------------------------------------------------- Declutters URLs
 7450: 
 7451: sub declutter {
 7452:     my $thisfn=shift;
 7453:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7454:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7455:     $thisfn=~s/^\///;
 7456:     $thisfn=~s|^adm/wrapper/||;
 7457:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7458:     $thisfn=~s/^res\///;
 7459:     $thisfn=~s/\?.+$//;
 7460:     return $thisfn;
 7461: }
 7462: 
 7463: # ------------------------------------------------------------- Clutter up URLs
 7464: 
 7465: sub clutter {
 7466:     my $thisfn='/'.&declutter(shift);
 7467:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7468:        $thisfn='/res'.$thisfn; 
 7469:     }
 7470:     if ($thisfn !~m|/adm|) {
 7471: 	if ($thisfn =~ m|/ext/|) {
 7472: 	    $thisfn='/adm/wrapper'.$thisfn;
 7473: 	} else {
 7474: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7475: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7476: 	    if ($embstyle eq 'ssi'
 7477: 		|| ($embstyle eq 'hdn')
 7478: 		|| ($embstyle eq 'rat')
 7479: 		|| ($embstyle eq 'prv')
 7480: 		|| ($embstyle eq 'ign')) {
 7481: 		#do nothing with these
 7482: 	    } elsif (($embstyle eq 'img') 
 7483: 		|| ($embstyle eq 'emb')
 7484: 		|| ($embstyle eq 'wrp')) {
 7485: 		$thisfn='/adm/wrapper'.$thisfn;
 7486: 	    } elsif ($embstyle eq 'unk'
 7487: 		     && $thisfn!~/\.(sequence|page)$/) {
 7488: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7489: 	    } else {
 7490: #		&logthis("Got a blank emb style");
 7491: 	    }
 7492: 	}
 7493:     }
 7494:     return $thisfn;
 7495: }
 7496: 
 7497: sub clutter_with_no_wrapper {
 7498:     my $uri = &clutter(shift);
 7499:     if ($uri =~ m-^/adm/-) {
 7500: 	$uri =~ s-^/adm/wrapper/-/-;
 7501: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7502:     }
 7503:     return $uri;
 7504: }
 7505: 
 7506: sub freeze_escape {
 7507:     my ($value)=@_;
 7508:     if (ref($value)) {
 7509: 	$value=&nfreeze($value);
 7510: 	return '__FROZEN__'.&escape($value);
 7511:     }
 7512:     return &escape($value);
 7513: }
 7514: 
 7515: 
 7516: sub thaw_unescape {
 7517:     my ($value)=@_;
 7518:     if ($value =~ /^__FROZEN__/) {
 7519: 	substr($value,0,10,undef);
 7520: 	$value=&unescape($value);
 7521: 	return &thaw($value);
 7522:     }
 7523:     return &unescape($value);
 7524: }
 7525: 
 7526: sub correct_line_ends {
 7527:     my ($result)=@_;
 7528:     $$result =~s/\r\n/\n/mg;
 7529:     $$result =~s/\r/\n/mg;
 7530: }
 7531: # ================================================================ Main Program
 7532: 
 7533: sub goodbye {
 7534:    &logthis("Starting Shut down");
 7535: #not converted to using infrastruture and probably shouldn't be
 7536:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7537: #converted
 7538: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7539:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7540: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7541: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7542: #1.1 only
 7543: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7544: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7545: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7546: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7547:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7548:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7549:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7550:    &flushcourselogs();
 7551:    &logthis("Shutting down");
 7552: }
 7553: 
 7554: BEGIN {
 7555: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7556:     unless ($readit) {
 7557: {
 7558:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7559:     %perlvar = (%perlvar,%{$configvars});
 7560: }
 7561: 
 7562: # ------------------------------------------------------------ Read domain file
 7563: {
 7564:     %domaindescription = ();
 7565:     %domain_auth_def = ();
 7566:     %domain_auth_arg_def = ();
 7567:     my $fh;
 7568:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7569: 	while (my $line = <$fh>) {
 7570:            next if ($line =~ /^(\#|\s*$)/);
 7571: #           next if /^\#/;
 7572:            chomp $line;
 7573:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7574: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
 7575: 	   $domain_auth_def{$domain}=$def_auth;
 7576:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7577: 	   $domaindescription{$domain}=$domain_description;
 7578: 	   $domain_lang_def{$domain}=$def_lang;
 7579: 	   $domain_city{$domain}=$city;
 7580: 	   $domain_longi{$domain}=$longi;
 7581: 	   $domain_lati{$domain}=$lati;
 7582:            $domain_primary{$domain}=$primary;
 7583: 
 7584:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7585: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7586: 	}
 7587:     }
 7588:     close ($fh);
 7589: }
 7590: 
 7591: 
 7592: # ------------------------------------------------------------- Read hosts file
 7593: {
 7594:     my %hostname;
 7595:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7596: 
 7597:     while (my $configline=<$config>) {
 7598:        next if ($configline =~ /^(\#|\s*$)/);
 7599:        chomp($configline);
 7600:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7601:        $name=~s/\s//g;
 7602:        if ($id && $domain && $role && $name) {
 7603: 	 $hostname{$id}=$name;
 7604: 	 $hostdom{$id}=$domain;
 7605: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7606:        }
 7607:     }
 7608:     close($config);
 7609:     # FIXME: dev server don't want this, production servers _do_ want this
 7610:     #&get_iphost();
 7611: 
 7612:     sub hostname {
 7613: 	my ($lonid) = @_;
 7614: 	return $hostname{$lonid};
 7615:     }
 7616:     sub all_hostnames {
 7617: 	return %hostname;
 7618:     }
 7619:     sub get_servers {
 7620: 	my ($domain,$type) = @_;
 7621: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7622: 	                                          : %hostname;
 7623: 	my %result;
 7624: 	if (ref($domain) eq 'ARRAY') {
 7625: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7626: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7627: 		    $result{$host} = $hostname;
 7628: 		}
 7629: 	    }
 7630: 	} else {
 7631: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7632: 		if ($hostdom{$host} eq $domain) {
 7633: 		    $result{$host} = $hostname;
 7634: 		}
 7635: 	    }
 7636: 	}
 7637: 	return %result;
 7638:     }
 7639:     sub all_domains {
 7640: 	my %seen;
 7641: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7642: 	return @uniq;
 7643:     }
 7644: }
 7645: 
 7646: sub get_hosts_from_ip {
 7647:     my ($ip) = @_;
 7648:     my %iphosts = &get_iphost();
 7649:     if (ref($iphosts{$ip})) {
 7650: 	return @{$iphosts{$ip}};
 7651:     }
 7652:     return;
 7653: }
 7654: 
 7655: sub get_iphost {
 7656:     if (%iphost) { return %iphost; }
 7657:     my %name_to_ip;
 7658:     my %hostname = &all_hostnames();
 7659:     foreach my $id (keys(%hostname)) {
 7660: 	my $name=$hostname{$id};
 7661: 	my $ip;
 7662: 	if (!exists($name_to_ip{$name})) {
 7663: 	    $ip = gethostbyname($name);
 7664: 	    if (!$ip || length($ip) ne 4) {
 7665: 		&logthis("Skipping host $id name $name no IP found");
 7666: 		next;
 7667: 	    }
 7668: 	    $ip=inet_ntoa($ip);
 7669: 	    $name_to_ip{$name} = $ip;
 7670: 	} else {
 7671: 	    $ip = $name_to_ip{$name};
 7672: 	}
 7673: 	push(@{$iphost{$ip}},$id);
 7674:     }
 7675:     return %iphost;
 7676: }
 7677: 
 7678: # ------------------------------------------------------ Read spare server file
 7679: {
 7680:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7681: 
 7682:     while (my $configline=<$config>) {
 7683:        chomp($configline);
 7684:        if ($configline) {
 7685: 	   my ($host,$type) = split(':',$configline,2);
 7686: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7687: 	   push(@{ $spareid{$type} }, $host);
 7688:        }
 7689:     }
 7690:     close($config);
 7691: }
 7692: # ------------------------------------------------------------ Read permissions
 7693: {
 7694:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7695: 
 7696:     while (my $configline=<$config>) {
 7697: 	chomp($configline);
 7698: 	if ($configline) {
 7699: 	    my ($role,$perm)=split(/ /,$configline);
 7700: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7701: 	}
 7702:     }
 7703:     close($config);
 7704: }
 7705: 
 7706: # -------------------------------------------- Read plain texts for permissions
 7707: {
 7708:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7709: 
 7710:     while (my $configline=<$config>) {
 7711: 	chomp($configline);
 7712: 	if ($configline) {
 7713: 	    my ($short,@plain)=split(/:/,$configline);
 7714:             %{$prp{$short}} = ();
 7715: 	    if (@plain > 0) {
 7716:                 $prp{$short}{'std'} = $plain[0];
 7717:                 for (my $i=1; $i<@plain; $i++) {
 7718:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7719:                 }
 7720:             }
 7721: 	}
 7722:     }
 7723:     close($config);
 7724: }
 7725: 
 7726: # ---------------------------------------------------------- Read package table
 7727: {
 7728:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7729: 
 7730:     while (my $configline=<$config>) {
 7731: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7732: 	chomp($configline);
 7733: 	my ($short,$plain)=split(/:/,$configline);
 7734: 	my ($pack,$name)=split(/\&/,$short);
 7735: 	if ($plain ne '') {
 7736: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7737: 	    $packagetab{$short}=$plain; 
 7738: 	}
 7739:     }
 7740:     close($config);
 7741: }
 7742: 
 7743: # ------------- set up temporary directory
 7744: {
 7745:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7746: 
 7747: }
 7748: 
 7749: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7750: 				'compress_threshold'=> 20_000,
 7751:  			        });
 7752: 
 7753: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7754: $dumpcount=0;
 7755: 
 7756: &logtouch();
 7757: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7758: $readit=1;
 7759:     {
 7760: 	use integer;
 7761: 	my $test=(2**32)+1;
 7762: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7763: 	&logthis(" Detected 64bit platform ($_64bit)");
 7764:     }
 7765: }
 7766: }
 7767: 
 7768: 1;
 7769: __END__
 7770: 
 7771: =pod
 7772: 
 7773: =head1 NAME
 7774: 
 7775: Apache::lonnet - Subroutines to ask questions about things in the network.
 7776: 
 7777: =head1 SYNOPSIS
 7778: 
 7779: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7780: 
 7781:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7782: 
 7783: Common parameters:
 7784: 
 7785: =over 4
 7786: 
 7787: =item *
 7788: 
 7789: $uname : an internal username (if $cname expecting a course Id specifically)
 7790: 
 7791: =item *
 7792: 
 7793: $udom : a domain (if $cdom expecting a course's domain specifically)
 7794: 
 7795: =item *
 7796: 
 7797: $symb : a resource instance identifier
 7798: 
 7799: =item *
 7800: 
 7801: $namespace : the name of a .db file that contains the data needed or
 7802: being set.
 7803: 
 7804: =back
 7805: 
 7806: =head1 OVERVIEW
 7807: 
 7808: lonnet provides subroutines which interact with the
 7809: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7810: about classes, users, and resources.
 7811: 
 7812: For many of these objects you can also use this to store data about
 7813: them or modify them in various ways.
 7814: 
 7815: =head2 Symbs
 7816: 
 7817: To identify a specific instance of a resource, LON-CAPA uses symbols
 7818: or "symbs"X<symb>. These identifiers are built from the URL of the
 7819: map, the resource number of the resource in the map, and the URL of
 7820: the resource itself. The latter is somewhat redundant, but might help
 7821: if maps change.
 7822: 
 7823: An example is
 7824: 
 7825:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7826: 
 7827: The respective map entry is
 7828: 
 7829:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7830:   title="Problem 2">
 7831:  </resource>
 7832: 
 7833: Symbs are used by the random number generator, as well as to store and
 7834: restore data specific to a certain instance of for example a problem.
 7835: 
 7836: =head2 Storing And Retrieving Data
 7837: 
 7838: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7839: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7840: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7841: is is the non-critical message twin of cstore. These functions are for
 7842: handlers to store a perl hash to a user's permanent data space in an
 7843: easy manner, and to retrieve it again on another call. It is expected
 7844: that a handler would use this once at the beginning to retrieve data,
 7845: and then again once at the end to send only the new data back.
 7846: 
 7847: The data is stored in the user's data directory on the user's
 7848: homeserver under the ID of the course.
 7849: 
 7850: The hash that is returned by restore will have all of the previous
 7851: value for all of the elements of the hash.
 7852: 
 7853: Example:
 7854: 
 7855:  #creating a hash
 7856:  my %hash;
 7857:  $hash{'foo'}='bar';
 7858: 
 7859:  #storing it
 7860:  &Apache::lonnet::cstore(\%hash);
 7861: 
 7862:  #changing a value
 7863:  $hash{'foo'}='notbar';
 7864: 
 7865:  #adding a new value
 7866:  $hash{'bar'}='foo';
 7867:  &Apache::lonnet::cstore(\%hash);
 7868: 
 7869:  #retrieving the hash
 7870:  my %history=&Apache::lonnet::restore();
 7871: 
 7872:  #print the hash
 7873:  foreach my $key (sort(keys(%history))) {
 7874:    print("\%history{$key} = $history{$key}");
 7875:  }
 7876: 
 7877: Will print out:
 7878: 
 7879:  %history{1:foo} = bar
 7880:  %history{1:keys} = foo:timestamp
 7881:  %history{1:timestamp} = 990455579
 7882:  %history{2:bar} = foo
 7883:  %history{2:foo} = notbar
 7884:  %history{2:keys} = foo:bar:timestamp
 7885:  %history{2:timestamp} = 990455580
 7886:  %history{bar} = foo
 7887:  %history{foo} = notbar
 7888:  %history{timestamp} = 990455580
 7889:  %history{version} = 2
 7890: 
 7891: Note that the special hash entries C<keys>, C<version> and
 7892: C<timestamp> were added to the hash. C<version> will be equal to the
 7893: total number of versions of the data that have been stored. The
 7894: C<timestamp> attribute will be the UNIX time the hash was
 7895: stored. C<keys> is available in every historical section to list which
 7896: keys were added or changed at a specific historical revision of a
 7897: hash.
 7898: 
 7899: B<Warning>: do not store the hash that restore returns directly. This
 7900: will cause a mess since it will restore the historical keys as if the
 7901: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7902: 
 7903: Calling convention:
 7904: 
 7905:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7906:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7907: 
 7908: For more detailed information, see lonnet specific documentation.
 7909: 
 7910: =head1 RETURN MESSAGES
 7911: 
 7912: =over 4
 7913: 
 7914: =item * B<con_lost>: unable to contact remote host
 7915: 
 7916: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7917: when the connection is brought back up
 7918: 
 7919: =item * B<con_failed>: unable to contact remote host and unable to save message
 7920: for later delivery
 7921: 
 7922: =item * B<error:>: an error a occured, a description of the error follows the :
 7923: 
 7924: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7925: that was requested
 7926: 
 7927: =back
 7928: 
 7929: =head1 PUBLIC SUBROUTINES
 7930: 
 7931: =head2 Session Environment Functions
 7932: 
 7933: =over 4
 7934: 
 7935: =item * 
 7936: X<appenv()>
 7937: B<appenv(%hash)>: the value of %hash is written to
 7938: the user envirnoment file, and will be restored for each access this
 7939: user makes during this session, also modifies the %env for the current
 7940: process
 7941: 
 7942: =item *
 7943: X<delenv()>
 7944: B<delenv($regexp)>: removes all items from the session
 7945: environment file that matches the regular expression in $regexp. The
 7946: values are also delted from the current processes %env.
 7947: 
 7948: =item * get_env_multiple($name) 
 7949: 
 7950: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7951: values may be defined and end up as an array ref.
 7952: 
 7953: returns an array of values
 7954: 
 7955: =back
 7956: 
 7957: =head2 User Information
 7958: 
 7959: =over 4
 7960: 
 7961: =item *
 7962: X<queryauthenticate()>
 7963: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7964: authentication scheme
 7965: 
 7966: =item *
 7967: X<authenticate()>
 7968: B<authenticate($uname,$upass,$udom)>: try to
 7969: authenticate user from domain's lib servers (first use the current
 7970: one). C<$upass> should be the users password.
 7971: 
 7972: =item *
 7973: X<homeserver()>
 7974: B<homeserver($uname,$udom)>: find the server which has
 7975: the user's directory and files (there must be only one), this caches
 7976: the answer, and also caches if there is a borken connection.
 7977: 
 7978: =item *
 7979: X<idget()>
 7980: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7981: (IDs are a unique resource in a domain, there must be only 1 ID per
 7982: username, and only 1 username per ID in a specific domain) (returns
 7983: hash: id=>name,id=>name)
 7984: 
 7985: =item *
 7986: X<idrget()>
 7987: B<idrget($udom,@unames)>: find the IDs behind a list of
 7988: usernames (returns hash: name=>id,name=>id)
 7989: 
 7990: =item *
 7991: X<idput()>
 7992: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7993: 
 7994: =item *
 7995: X<rolesinit()>
 7996: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7997: 
 7998: =item *
 7999: X<getsection()>
 8000: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8001: course $cname, return section name/number or '' for "not in course"
 8002: and '-1' for "no section"
 8003: 
 8004: =item *
 8005: X<userenvironment()>
 8006: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8007: passed in @what from the requested user's environment, returns a hash
 8008: 
 8009: =back
 8010: 
 8011: =head2 User Roles
 8012: 
 8013: =over 4
 8014: 
 8015: =item *
 8016: 
 8017: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8018:  F: full access
 8019:  U,I,K: authentication modes (cxx only)
 8020:  '': forbidden
 8021:  1: user needs to choose course
 8022:  2: browse allowed
 8023:  A: passphrase authentication needed
 8024: 
 8025: =item *
 8026: 
 8027: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8028: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8029: and course level
 8030: 
 8031: =item *
 8032: 
 8033: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8034: explanation of a user role term
 8035: 
 8036: =item *
 8037: 
 8038: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
 8039: optional.  Returns a hash of a user's roles, with keys set to
 8040: colon-sparated $uname,$udom,and $role, and value set to
 8041: colon-separated start and end times for the role. If no username and
 8042: domain are specified, will default to current user/domain. Types,
 8043: roles, and roledoms are references to arrays, of role statuses
 8044: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
 8045: of the roles which can be used to restrict the list if roles
 8046: reported. If no array ref is provided for types, will default to
 8047: return only active roles.
 8048: 
 8049: =back
 8050: 
 8051: =head2 User Modification
 8052: 
 8053: =over 4
 8054: 
 8055: =item *
 8056: 
 8057: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8058: user for the level given by URL.  Optional start and end dates (leave empty
 8059: string or zero for "no date")
 8060: 
 8061: =item *
 8062: 
 8063: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8064: change a users, password, possible return values are: ok,
 8065: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8066: refused
 8067: 
 8068: =item *
 8069: 
 8070: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8071: 
 8072: =item *
 8073: 
 8074: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8075: modify user
 8076: 
 8077: =item *
 8078: 
 8079: modifystudent
 8080: 
 8081: modify a students enrollment and identification information.
 8082: The course id is resolved based on the current users environment.  
 8083: This means the envoking user must be a course coordinator or otherwise
 8084: associated with a course.
 8085: 
 8086: This call is essentially a wrapper for lonnet::modifyuser and
 8087: lonnet::modify_student_enrollment
 8088: 
 8089: Inputs: 
 8090: 
 8091: =over 4
 8092: 
 8093: =item B<$udom> Students loncapa domain
 8094: 
 8095: =item B<$uname> Students loncapa login name
 8096: 
 8097: =item B<$uid> Students id/student number
 8098: 
 8099: =item B<$umode> Students authentication mode
 8100: 
 8101: =item B<$upass> Students password
 8102: 
 8103: =item B<$first> Students first name
 8104: 
 8105: =item B<$middle> Students middle name
 8106: 
 8107: =item B<$last> Students last name
 8108: 
 8109: =item B<$gene> Students generation
 8110: 
 8111: =item B<$usec> Students section in course
 8112: 
 8113: =item B<$end> Unix time of the roles expiration
 8114: 
 8115: =item B<$start> Unix time of the roles start date
 8116: 
 8117: =item B<$forceid> If defined, allow $uid to be changed
 8118: 
 8119: =item B<$desiredhome> server to use as home server for student
 8120: 
 8121: =back
 8122: 
 8123: =item *
 8124: 
 8125: modify_student_enrollment
 8126: 
 8127: Change a students enrollment status in a class.  The environment variable
 8128: 'role.request.course' must be defined for this function to proceed.
 8129: 
 8130: Inputs:
 8131: 
 8132: =over 4
 8133: 
 8134: =item $udom, students domain
 8135: 
 8136: =item $uname, students name
 8137: 
 8138: =item $uid, students user id
 8139: 
 8140: =item $first, students first name
 8141: 
 8142: =item $middle
 8143: 
 8144: =item $last
 8145: 
 8146: =item $gene
 8147: 
 8148: =item $usec
 8149: 
 8150: =item $end
 8151: 
 8152: =item $start
 8153: 
 8154: =back
 8155: 
 8156: 
 8157: =item *
 8158: 
 8159: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8160: custom role; give a custom role to a user for the level given by URL.  Specify
 8161: name and domain of role author, and role name
 8162: 
 8163: =item *
 8164: 
 8165: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8166: 
 8167: =item *
 8168: 
 8169: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8170: 
 8171: =back
 8172: 
 8173: =head2 Course Infomation
 8174: 
 8175: =over 4
 8176: 
 8177: =item *
 8178: 
 8179: coursedescription($courseid) : returns a hash of information about the
 8180: specified course id, including all environment settings for the
 8181: course, the description of the course will be in the hash under the
 8182: key 'description'
 8183: 
 8184: =item *
 8185: 
 8186: resdata($name,$domain,$type,@which) : request for current parameter
 8187: setting for a specific $type, where $type is either 'course' or 'user',
 8188: @what should be a list of parameters to ask about. This routine caches
 8189: answers for 5 minutes.
 8190: 
 8191: =back
 8192: 
 8193: =head2 Course Modification
 8194: 
 8195: =over 4
 8196: 
 8197: =item *
 8198: 
 8199: writecoursepref($courseid,%prefs) : write preferences (environment
 8200: database) for a course
 8201: 
 8202: =item *
 8203: 
 8204: createcourse($udom,$description,$url) : make/modify course
 8205: 
 8206: =back
 8207: 
 8208: =head2 Resource Subroutines
 8209: 
 8210: =over 4
 8211: 
 8212: =item *
 8213: 
 8214: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8215: 
 8216: =item *
 8217: 
 8218: repcopy($filename) : subscribes to the requested file, and attempts to
 8219: replicate from the owning library server, Might return
 8220: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8221: 'bad_request', also attempts to grab the metadata for the
 8222: resource. Expects the local filesystem pathname
 8223: (/home/httpd/html/res/....)
 8224: 
 8225: =back
 8226: 
 8227: =head2 Resource Information
 8228: 
 8229: =over 4
 8230: 
 8231: =item *
 8232: 
 8233: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8234: a vairety of different possible values, $varname should be a request
 8235: string, and the other parameters can be used to specify who and what
 8236: one is asking about.
 8237: 
 8238: Possible values for $varname are environment.lastname (or other item
 8239: from the envirnment hash), user.name (or someother aspect about the
 8240: user), resource.0.maxtries (or some other part and parameter of a
 8241: resource)
 8242: 
 8243: =item *
 8244: 
 8245: directcondval($number) : get current value of a condition; reads from a state
 8246: string
 8247: 
 8248: =item *
 8249: 
 8250: condval($condidx) : value of condition index based on state
 8251: 
 8252: =item *
 8253: 
 8254: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8255: resource's metadata, $what should be either a specific key, or either
 8256: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8257: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8258: 
 8259: this function automatically caches all requests
 8260: 
 8261: =item *
 8262: 
 8263: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8264: network of library servers; returns file handle of where SQL and regex results
 8265: will be stored for query
 8266: 
 8267: =item *
 8268: 
 8269: symbread($filename) : return symbolic list entry (filename argument optional);
 8270: returns the data handle
 8271: 
 8272: =item *
 8273: 
 8274: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8275: a possible symb for the URL in $thisfn, and if is an encryypted
 8276: resource that the user accessed using /enc/ returns a 1 on success, 0
 8277: on failure, user must be in a course, as it assumes the existance of
 8278: the course initial hash, and uses $env('request.course.id'}
 8279: 
 8280: 
 8281: =item *
 8282: 
 8283: symbclean($symb) : removes versions numbers from a symb, returns the
 8284: cleaned symb
 8285: 
 8286: =item *
 8287: 
 8288: is_on_map($uri) : checks if the $uri is somewhere on the current
 8289: course map, user must be in a course for it to work.
 8290: 
 8291: =item *
 8292: 
 8293: numval($salt) : return random seed value (addend for rndseed)
 8294: 
 8295: =item *
 8296: 
 8297: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8298: a random seed, all arguments are optional, if they aren't sent it uses the
 8299: environment to derive them. Note: if symb isn't sent and it can't get one
 8300: from &symbread it will use the current time as its return value
 8301: 
 8302: =item *
 8303: 
 8304: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8305: unfakeable, receipt
 8306: 
 8307: =item *
 8308: 
 8309: receipt() : API to ireceipt working off of env values; given out to users
 8310: 
 8311: =item *
 8312: 
 8313: countacc($url) : count the number of accesses to a given URL
 8314: 
 8315: =item *
 8316: 
 8317: 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
 8318: 
 8319: =item *
 8320: 
 8321: 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)
 8322: 
 8323: =item *
 8324: 
 8325: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8326: 
 8327: =item *
 8328: 
 8329: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8330: forcing spreadsheet to reevaluate the resource scores next time.
 8331: 
 8332: =back
 8333: 
 8334: =head2 Storing/Retreiving Data
 8335: 
 8336: =over 4
 8337: 
 8338: =item *
 8339: 
 8340: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8341: for this url; hashref needs to be given and should be a \%hashname; the
 8342: remaining args aren't required and if they aren't passed or are '' they will
 8343: be derived from the env
 8344: 
 8345: =item *
 8346: 
 8347: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8348: uses critical subroutine
 8349: 
 8350: =item *
 8351: 
 8352: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8353: all args are optional
 8354: 
 8355: =item *
 8356: 
 8357: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8358: dumps the complete (or key matching regexp) namespace into a hash
 8359: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8360: normally &store()ed into
 8361: 
 8362: $range should be either an integer '100' (give me the first 100
 8363:                                            matching records)
 8364:               or be  two integers sperated by a - with no spaces
 8365:                  '30-50' (give me the 30th through the 50th matching
 8366:                           records)
 8367: 
 8368: 
 8369: =item *
 8370: 
 8371: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8372: replaces a &store() version of data with a replacement set of data
 8373: for a particular resource in a namespace passed in the $storehash hash 
 8374: reference
 8375: 
 8376: =item *
 8377: 
 8378: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8379: works very similar to store/cstore, but all data is stored in a
 8380: temporary location and can be reset using tmpreset, $storehash should
 8381: be a hash reference, returns nothing on success
 8382: 
 8383: =item *
 8384: 
 8385: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8386: similar to restore, but all data is stored in a temporary location and
 8387: can be reset using tmpreset. Returns a hash of values on success,
 8388: error string otherwise.
 8389: 
 8390: =item *
 8391: 
 8392: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8393: deltes all keys for $symb form the temporary storage hash.
 8394: 
 8395: =item *
 8396: 
 8397: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8398: reference filled in from namesp ($udom and $uname are optional)
 8399: 
 8400: =item *
 8401: 
 8402: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8403: namesp ($udom and $uname are optional)
 8404: 
 8405: =item *
 8406: 
 8407: dump($namespace,$udom,$uname,$regexp,$range) : 
 8408: dumps the complete (or key matching regexp) namespace into a hash
 8409: ($udom, $uname, $regexp, $range are optional)
 8410: 
 8411: $range should be either an integer '100' (give me the first 100
 8412:                                            matching records)
 8413:               or be  two integers sperated by a - with no spaces
 8414:                  '30-50' (give me the 30th through the 50th matching
 8415:                           records)
 8416: =item *
 8417: 
 8418: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8419: $store can be a scalar, an array reference, or if the amount to be 
 8420: incremented is > 1, a hash reference.
 8421: 
 8422: ($udom and $uname are optional)
 8423: 
 8424: =item *
 8425: 
 8426: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8427: ($udom and $uname are optional)
 8428: 
 8429: =item *
 8430: 
 8431: cput($namespace,$storehash,$udom,$uname) : critical put
 8432: ($udom and $uname are optional)
 8433: 
 8434: =item *
 8435: 
 8436: newput($namespace,$storehash,$udom,$uname) :
 8437: 
 8438: Attempts to store the items in the $storehash, but only if they don't
 8439: currently exist, if this succeeds you can be certain that you have 
 8440: successfully created a new key value pair in the $namespace db.
 8441: 
 8442: 
 8443: Args:
 8444:  $namespace: name of database to store values to
 8445:  $storehash: hashref to store to the db
 8446:  $udom: (optional) domain of user containing the db
 8447:  $uname: (optional) name of user caontaining the db
 8448: 
 8449: Returns:
 8450:  'ok' -> succeeded in storing all keys of $storehash
 8451:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8452:                         least <key> already existed in the db (other
 8453:                         requested keys may also already exist)
 8454:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8455:  'con_lost' -> unable to contact request server
 8456:  'refused' -> action was not allowed by remote machine
 8457: 
 8458: 
 8459: =item *
 8460: 
 8461: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8462: reference filled in from namesp (encrypts the return communication)
 8463: ($udom and $uname are optional)
 8464: 
 8465: =item *
 8466: 
 8467: log($udom,$name,$home,$message) : write to permanent log for user; use
 8468: critical subroutine
 8469: 
 8470: =item *
 8471: 
 8472: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
 8473: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
 8474: 
 8475: =item *
 8476: 
 8477: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
 8478: 
 8479: =back
 8480: 
 8481: =head2 Network Status Functions
 8482: 
 8483: =over 4
 8484: 
 8485: =item *
 8486: 
 8487: dirlist($uri) : return directory list based on URI
 8488: 
 8489: =item *
 8490: 
 8491: spareserver() : find server with least workload from spare.tab
 8492: 
 8493: =back
 8494: 
 8495: =head2 Apache Request
 8496: 
 8497: =over 4
 8498: 
 8499: =item *
 8500: 
 8501: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8502: localhost, posts hash
 8503: 
 8504: =back
 8505: 
 8506: =head2 Data to String to Data
 8507: 
 8508: =over 4
 8509: 
 8510: =item *
 8511: 
 8512: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8513: and '&' separators, supports elements that are arrayrefs and hashrefs
 8514: 
 8515: =item *
 8516: 
 8517: hashref2str($hashref) : convert a hashref into a string complete with
 8518: escaping and '=' and '&' separators, supports elements that are
 8519: arrayrefs and hashrefs
 8520: 
 8521: =item *
 8522: 
 8523: arrayref2str($arrayref) : convert an arrayref into a string complete
 8524: with escaping and '&' separators, supports elements that are arrayrefs
 8525: and hashrefs
 8526: 
 8527: =item *
 8528: 
 8529: str2hash($string) : convert string to hash using unescaping and
 8530: splitting on '=' and '&', supports elements that are arrayrefs and
 8531: hashrefs
 8532: 
 8533: =item *
 8534: 
 8535: str2array($string) : convert string to hash using unescaping and
 8536: splitting on '&', supports elements that are arrayrefs and hashrefs
 8537: 
 8538: =back
 8539: 
 8540: =head2 Logging Routines
 8541: 
 8542: =over 4
 8543: 
 8544: These routines allow one to make log messages in the lonnet.log and
 8545: lonnet.perm logfiles.
 8546: 
 8547: =item *
 8548: 
 8549: logtouch() : make sure the logfile, lonnet.log, exists
 8550: 
 8551: =item *
 8552: 
 8553: logthis() : append message to the normal lonnet.log file, it gets
 8554: preiodically rolled over and deleted.
 8555: 
 8556: =item *
 8557: 
 8558: logperm() : append a permanent message to lonnet.perm.log, this log
 8559: file never gets deleted by any automated portion of the system, only
 8560: messages of critical importance should go in here.
 8561: 
 8562: =back
 8563: 
 8564: =head2 General File Helper Routines
 8565: 
 8566: =over 4
 8567: 
 8568: =item *
 8569: 
 8570: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8571: (a) files in /uploaded
 8572:   (i) If a local copy of the file exists - 
 8573:       compares modification date of local copy with last-modified date for 
 8574:       definitive version stored on home server for course. If local copy is 
 8575:       stale, requests a new version from the home server and stores it. 
 8576:       If the original has been removed from the home server, then local copy 
 8577:       is unlinked.
 8578:   (ii) If local copy does not exist -
 8579:       requests the file from the home server and stores it. 
 8580:   
 8581:   If $caller is 'uploadrep':  
 8582:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8583:     for request for files originally uploaded via DOCS. 
 8584:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8585:   
 8586:   Otherwise:
 8587:      This indicates a call from the content generation phase of the request.
 8588:      -  returns the entire contents of the file or -1.
 8589:      
 8590: (b) files in /res
 8591:    - returns the entire contents of a file or -1; 
 8592:    it properly subscribes to and replicates the file if neccessary.
 8593: 
 8594: 
 8595: =item *
 8596: 
 8597: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8598:                   reference
 8599: 
 8600: returns either a stat() list of data about the file or an empty list
 8601: if the file doesn't exist or couldn't find out about it (connection
 8602: problems or user unknown)
 8603: 
 8604: =item *
 8605: 
 8606: filelocation($dir,$file) : returns file system location of a file
 8607: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8608: directory that relative $file lookups are to looked in ($dir of /a/dir
 8609: and a file of ../bob will become /a/bob)
 8610: 
 8611: =item *
 8612: 
 8613: hreflocation($dir,$file) : returns file system location or a URL; same as
 8614: filelocation except for hrefs
 8615: 
 8616: =item *
 8617: 
 8618: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8619: 
 8620: =back
 8621: 
 8622: =head2 Usererfile file routines (/uploaded*)
 8623: 
 8624: =over 4
 8625: 
 8626: =item *
 8627: 
 8628: userfileupload(): main rotine for putting a file in a user or course's
 8629:                   filespace, arguments are,
 8630: 
 8631:  formname - required - this is the name of the element in $env where the
 8632:            filename, and the contents of the file to create/modifed exist
 8633:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8634:            contents of the file is located in $env{'form.'.$formname}
 8635:  coursedoc - if true, store the file in the course of the active role
 8636:              of the current user
 8637:  subdir - required - subdirectory to put the file in under ../userfiles/
 8638:          if undefined, it will be placed in "unknown"
 8639: 
 8640:  (This routine calls clean_filename() to remove any dangerous
 8641:  characters from the filename, and then calls finuserfileupload() to
 8642:  complete the transaction)
 8643: 
 8644:  returns either the url of the uploaded file (/uploaded/....) if successful
 8645:  and /adm/notfound.html if unsuccessful
 8646: 
 8647: =item *
 8648: 
 8649: clean_filename(): routine for cleaing a filename up for storage in
 8650:                  userfile space, argument is:
 8651: 
 8652:  filename - proposed filename
 8653: 
 8654: returns: the new clean filename
 8655: 
 8656: =item *
 8657: 
 8658: finishuserfileupload(): routine that creaes and sends the file to
 8659: userspace, probably shouldn't be called directly
 8660: 
 8661:   docuname: username or courseid of destination for the file
 8662:   docudom: domain of user/course of destination for the file
 8663:   formname: same as for userfileupload()
 8664:   fname: filename (inculding subdirectories) for the file
 8665: 
 8666:  returns either the url of the uploaded file (/uploaded/....) if successful
 8667:  and /adm/notfound.html if unsuccessful
 8668: 
 8669: =item *
 8670: 
 8671: renameuserfile(): renames an existing userfile to a new name
 8672: 
 8673:   Args:
 8674:    docuname: username or courseid of destination for the file
 8675:    docudom: domain of user/course of destination for the file
 8676:    old: current file name (including any subdirs under userfiles)
 8677:    new: desired file name (including any subdirs under userfiles)
 8678: 
 8679: =item *
 8680: 
 8681: mkdiruserfile(): creates a directory is a userfiles dir
 8682: 
 8683:   Args:
 8684:    docuname: username or courseid of destination for the file
 8685:    docudom: domain of user/course of destination for the file
 8686:    dir: dir to create (including any subdirs under userfiles)
 8687: 
 8688: =item *
 8689: 
 8690: removeuserfile(): removes a file that exists in userfiles
 8691: 
 8692:   Args:
 8693:    docuname: username or courseid of destination for the file
 8694:    docudom: domain of user/course of destination for the file
 8695:    fname: filname to delete (including any subdirs under userfiles)
 8696: 
 8697: =item *
 8698: 
 8699: removeuploadedurl(): convience function for removeuserfile()
 8700: 
 8701:   Args:
 8702:    url:  a full /uploaded/... url to delete
 8703: 
 8704: =item * 
 8705: 
 8706: get_portfile_permissions():
 8707:   Args:
 8708:     domain: domain of user or course contain the portfolio files
 8709:     user: name of user or num of course contain the portfolio files
 8710:   Returns:
 8711:     hashref of a dump of the proper file_permissions.db
 8712:    
 8713: 
 8714: =item * 
 8715: 
 8716: get_access_controls():
 8717: 
 8718: Args:
 8719:   current_permissions: the hash ref returned from get_portfile_permissions()
 8720:   group: (optional) the group you want the files associated with
 8721:   file: (optional) the file you want access info on
 8722: 
 8723: Returns:
 8724:     a hash (keys are file names) of hashes containing
 8725:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8726:         values are XML containing access control settings (see below) 
 8727: 
 8728: Internal notes:
 8729: 
 8730:  access controls are stored in file_permissions.db as key=value pairs.
 8731:     key -> path to file/file_name\0uniqueID:scope_end_start
 8732:         where scope -> public,guest,course,group,domains or users.
 8733:               end -> UNIX time for end of access (0 -> no end date)
 8734:               start -> UNIX time for start of access
 8735: 
 8736:     value -> XML description of access control
 8737:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8738:             <start></start>
 8739:             <end></end>
 8740: 
 8741:             <password></password>  for scope type = guest
 8742: 
 8743:             <domain></domain>     for scope type = course or group
 8744:             <number></number>
 8745:             <roles id="">
 8746:              <role></role>
 8747:              <access></access>
 8748:              <section></section>
 8749:              <group></group>
 8750:             </roles>
 8751: 
 8752:             <dom></dom>         for scope type = domains
 8753: 
 8754:             <users>             for scope type = users
 8755:              <user>
 8756:               <uname></uname>
 8757:               <udom></udom>
 8758:              </user>
 8759:             </users>
 8760:            </scope> 
 8761:               
 8762:  Access data is also aggregated for each file in an additional key=value pair:
 8763:  key -> path to file/file_name\0accesscontrol 
 8764:  value -> reference to hash
 8765:           hash contains key = value pairs
 8766:           where key = uniqueID:scope_end_start
 8767:                 value = UNIX time record was last updated
 8768: 
 8769:           Used to improve speed of look-ups of access controls for each file.  
 8770:  
 8771:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8772: 
 8773: modify_access_controls():
 8774: 
 8775: Modifies access controls for a portfolio file
 8776: Args
 8777: 1. file name
 8778: 2. reference to hash of required changes,
 8779: 3. domain
 8780: 4. username
 8781:   where domain,username are the domain of the portfolio owner 
 8782:   (either a user or a course) 
 8783: 
 8784: Returns:
 8785: 1. result of additions or updates ('ok' or 'error', with error message). 
 8786: 2. result of deletions ('ok' or 'error', with error message).
 8787: 3. reference to hash of any new or updated access controls.
 8788: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8789:    key = integer (inbound ID)
 8790:    value = uniqueID  
 8791: 
 8792: =back
 8793: 
 8794: =head2 HTTP Helper Routines
 8795: 
 8796: =over 4
 8797: 
 8798: =item *
 8799: 
 8800: escape() : unpack non-word characters into CGI-compatible hex codes
 8801: 
 8802: =item *
 8803: 
 8804: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8805: 
 8806: =back
 8807: 
 8808: =head1 PRIVATE SUBROUTINES
 8809: 
 8810: =head2 Underlying communication routines (Shouldn't call)
 8811: 
 8812: =over 4
 8813: 
 8814: =item *
 8815: 
 8816: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8817: 
 8818: =item *
 8819: 
 8820: reply() : uses subreply to send a message to remote machine, logs all failures
 8821: 
 8822: =item *
 8823: 
 8824: critical() : passes a critical message to another server; if cannot
 8825: get through then place message in connection buffer directory and
 8826: returns con_delayed, if incapable of saving message, returns
 8827: con_failed
 8828: 
 8829: =item *
 8830: 
 8831: reconlonc() : tries to reconnect lonc client processes.
 8832: 
 8833: =back
 8834: 
 8835: =head2 Resource Access Logging
 8836: 
 8837: =over 4
 8838: 
 8839: =item *
 8840: 
 8841: flushcourselogs() : flush (save) buffer logs and access logs
 8842: 
 8843: =item *
 8844: 
 8845: courselog($what) : save message for course in hash
 8846: 
 8847: =item *
 8848: 
 8849: courseacclog($what) : save message for course using &courselog().  Perform
 8850: special processing for specific resource types (problems, exams, quizzes, etc).
 8851: 
 8852: =item *
 8853: 
 8854: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8855: as a PerlChildExitHandler
 8856: 
 8857: =back
 8858: 
 8859: =head2 Other
 8860: 
 8861: =over 4
 8862: 
 8863: =item *
 8864: 
 8865: symblist($mapname,%newhash) : update symbolic storage links
 8866: 
 8867: =back
 8868: 
 8869: =cut

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