File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.742: download - view: text, annotated - select for diffs
Fri Jun 2 13:58:58 2006 UTC (18 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Conversion of role names now occurs in lonnet::plaintext().  If rolename is set for a specific role in the course environment this is used, otherwise defaults to name defined in rolesplain.tab.  rolesplain.tab can now contain multiple entries (: separated) - which one is used depends on course type. loncommon::course_type() is accesssor function added to provide type; loncommon::convert_role() eliminated.  loncommon::bodytag() now includes $realm information for co-author role.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.742 2006/06/02 13:58:58 raeburn 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 %hostname %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 lib '/home/httpd/lib/perl';
   56: use LONCAPA;
   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:     my $peerfile=shift;
  205:     &logthis("Trying to reconnect for $peerfile");
  206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  207:     if (open(my $fh,"<$loncfile")) {
  208: 	my $loncpid=<$fh>;
  209:         chomp($loncpid);
  210:         if (kill 0 => $loncpid) {
  211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  212:             kill USR1 => $loncpid;
  213:             sleep 1;
  214:             if (-e "$peerfile") { return; }
  215:             &logthis("$peerfile still not there, give it another try");
  216:             sleep 5;
  217:             if (-e "$peerfile") { return; }
  218:             &logthis(
  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
  220:         } else {
  221: 	    &logthis(
  222:                "<font color=\"blue\">WARNING:".
  223:                " lonc at pid $loncpid not responding, giving up</font>");
  224:         }
  225:     } else {
  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  227:     }
  228: }
  229: 
  230: # ------------------------------------------------------ Critical communication
  231: 
  232: sub critical {
  233:     my ($cmd,$server)=@_;
  234:     unless ($hostname{$server}) {
  235:         &logthis("<font color=\"blue\">WARNING:".
  236:                " Critical message to unknown server ($server)</font>");
  237:         return 'no_such_host';
  238:     }
  239:     my $answer=reply($cmd,$server);
  240:     if ($answer eq 'con_lost') {
  241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  242: 	my $answer=reply($cmd,$server);
  243:         if ($answer eq 'con_lost') {
  244:             my $now=time;
  245:             my $middlename=$cmd;
  246:             $middlename=substr($middlename,0,16);
  247:             $middlename=~s/\W//g;
  248:             my $dfilename=
  249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  250:             $dumpcount++;
  251:             {
  252: 		my $dfh;
  253: 		if (open($dfh,">$dfilename")) {
  254: 		    print $dfh "$cmd\n"; 
  255: 		    close($dfh);
  256: 		}
  257:             }
  258:             sleep 2;
  259:             my $wcmd='';
  260:             {
  261: 		my $dfh;
  262: 		if (open($dfh,"<$dfilename")) {
  263: 		    $wcmd=<$dfh>; 
  264: 		    close($dfh);
  265: 		}
  266:             }
  267:             chomp($wcmd);
  268:             if ($wcmd eq $cmd) {
  269: 		&logthis("<font color=\"blue\">WARNING: ".
  270:                          "Connection buffer $dfilename: $cmd</font>");
  271:                 &logperm("D:$server:$cmd");
  272: 	        return 'con_delayed';
  273:             } else {
  274:                 &logthis("<font color=\"red\">CRITICAL:"
  275:                         ." Critical connection failed: $server $cmd</font>");
  276:                 &logperm("F:$server:$cmd");
  277:                 return 'con_failed';
  278:             }
  279:         }
  280:     }
  281:     return $answer;
  282: }
  283: 
  284: # ------------------------------------------- Transfer profile into environment
  285: 
  286: sub transfer_profile_to_env {
  287:     my ($lonidsdir,$handle)=@_;
  288:     if (!defined($lonidsdir)) {
  289: 	$lonidsdir = $perlvar{'lonIDsDir'};
  290:     }
  291:     if (!defined($handle)) {
  292:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  293:     }
  294: 
  295:     my @profile;
  296:     {
  297: 	open(my $idf,"$lonidsdir/$handle.id");
  298: 	flock($idf,LOCK_SH);
  299: 	@profile=<$idf>;
  300: 	close($idf);
  301:     }
  302:     my $envi;
  303:     my %Remove;
  304:     for ($envi=0;$envi<=$#profile;$envi++) {
  305: 	chomp($profile[$envi]);
  306: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
  307: 	$envname=&unescape($envname);
  308: 	$envvalue=&unescape($envvalue);
  309: 	$env{$envname} = $envvalue;
  310:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  311:             if ($time < time-300) {
  312:                 $Remove{$key}++;
  313:             }
  314:         }
  315:     }
  316:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  317:     foreach my $expired_key (keys(%Remove)) {
  318:         &delenv($expired_key);
  319:     }
  320: }
  321: 
  322: # ---------------------------------------------------------- Append Environment
  323: 
  324: sub appenv {
  325:     my %newenv=@_;
  326:     foreach my $key (keys(%newenv)) {
  327: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  328:             &logthis("<font color=\"blue\">WARNING: ".
  329:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  330:                 .'</font>');
  331: 	    delete($newenv{$key});
  332:         } else {
  333:             $env{$key}=$newenv{$key};
  334:         }
  335:     }
  336: 
  337:     my $lockfh;
  338:     unless (open($lockfh,"$env{'user.environment'}")) {
  339: 	return 'error: '.$!;
  340:     }
  341:     unless (flock($lockfh,LOCK_EX)) {
  342:          &logthis("<font color=\"blue\">WARNING: ".
  343:                   'Could not obtain exclusive lock in appenv: '.$!);
  344:          close($lockfh);
  345:          return 'error: '.$!;
  346:     }
  347: 
  348:     my @oldenv;
  349:     {
  350: 	my $fh;
  351: 	unless (open($fh,"$env{'user.environment'}")) {
  352: 	    return 'error: '.$!;
  353: 	}
  354: 	@oldenv=<$fh>;
  355: 	close($fh);
  356:     }
  357:     for (my $i=0; $i<=$#oldenv; $i++) {
  358:         chomp($oldenv[$i]);
  359:         if ($oldenv[$i] ne '') {
  360: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
  361: 	    $name=&unescape($name);
  362: 	    $value=&unescape($value);
  363: 	    unless (defined($newenv{$name})) {
  364: 		$newenv{$name}=$value;
  365: 	    }
  366:         }
  367:     }
  368:     {
  369: 	my $fh;
  370: 	unless (open($fh,">$env{'user.environment'}")) {
  371: 	    return 'error';
  372: 	}
  373: 	my $newname;
  374: 	foreach $newname (keys %newenv) {
  375: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
  376: 	}
  377: 	close($fh);
  378:     }
  379: 	
  380:     close($lockfh);
  381:     return 'ok';
  382: }
  383: # ----------------------------------------------------- Delete from Environment
  384: 
  385: sub delenv {
  386:     my $delthis=shift;
  387:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  388:         &logthis("<font color=\"blue\">WARNING: ".
  389:                 "Attempt to delete from environment ".$delthis);
  390:         return 'error';
  391:     }
  392:     my @oldenv;
  393:     {
  394: 	my $fh;
  395: 	unless (open($fh,"$env{'user.environment'}")) {
  396: 	    return 'error';
  397: 	}
  398: 	unless (flock($fh,LOCK_SH)) {
  399: 	    &logthis("<font color=\"blue\">WARNING: ".
  400: 		     'Could not obtain shared lock in delenv: '.$!);
  401: 	    close($fh);
  402: 	    return 'error: '.$!;
  403: 	}
  404: 	@oldenv=<$fh>;
  405: 	close($fh);
  406:     }
  407:     {
  408: 	my $fh;
  409: 	unless (open($fh,">$env{'user.environment'}")) {
  410: 	    return 'error';
  411: 	}
  412: 	unless (flock($fh,LOCK_EX)) {
  413: 	    &logthis("<font color=\"blue\">WARNING: ".
  414: 		     'Could not obtain exclusive lock in delenv: '.$!);
  415: 	    close($fh);
  416: 	    return 'error: '.$!;
  417: 	}
  418: 	foreach my $cur_key (@oldenv) {
  419: 	    my $unescaped_cur_key = &unescape($cur_key);
  420: 	    if ($unescaped_cur_key=~/^$delthis/) { 
  421:                 my ($key) = split('=',$cur_key,2);
  422: 		$key = &unescape($key);
  423:                 delete($env{$key});
  424:             } else {
  425:                 print $fh $cur_key; 
  426:             }
  427: 	}
  428: 	close($fh);
  429:     }
  430:     return 'ok';
  431: }
  432: 
  433: # ------------------------------------------ Find out current server userload
  434: # there is a copy in lond
  435: sub userload {
  436:     my $numusers=0;
  437:     {
  438: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  439: 	my $filename;
  440: 	my $curtime=time;
  441: 	while ($filename=readdir(LONIDS)) {
  442: 	    if ($filename eq '.' || $filename eq '..') {next;}
  443: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  444: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  445: 	}
  446: 	closedir(LONIDS);
  447:     }
  448:     my $userloadpercent=0;
  449:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  450:     if ($maxuserload) {
  451: 	$userloadpercent=100*$numusers/$maxuserload;
  452:     }
  453:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  454:     return $userloadpercent;
  455: }
  456: 
  457: # ------------------------------------------ Fight off request when overloaded
  458: 
  459: sub overloaderror {
  460:     my ($r,$checkserver)=@_;
  461:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  462:     my $loadavg;
  463:     if ($checkserver eq $perlvar{'lonHostID'}) {
  464:        open(my $loadfile,'/proc/loadavg');
  465:        $loadavg=<$loadfile>;
  466:        $loadavg =~ s/\s.*//g;
  467:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  468:        close($loadfile);
  469:     } else {
  470:        $loadavg=&reply('load',$checkserver);
  471:     }
  472:     my $overload=$loadavg-100;
  473:     if ($overload>0) {
  474: 	$r->err_headers_out->{'Retry-After'}=$overload;
  475:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  476:         return 413;
  477:     }    
  478:     return '';
  479: }
  480: 
  481: # ------------------------------ Find server with least workload from spare.tab
  482: 
  483: sub spareserver {
  484:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  485:     my $tryserver;
  486:     my $spareserver='';
  487:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  488:     my $lowestserver=$loadpercent > $userloadpercent?
  489: 	             $loadpercent :  $userloadpercent;
  490:     foreach $tryserver (keys(%spareid)) {
  491: 	my $loadans=&reply('load',$tryserver);
  492: 	my $userloadans=&reply('userload',$tryserver);
  493: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  494: 	    next; #didn't get a number from the server
  495: 	}
  496: 	my $answer;
  497: 	if ($loadans =~ /\d/) {
  498: 	    if ($userloadans =~ /\d/) {
  499: 		#both are numbers, pick the bigger one
  500: 		$answer=$loadans > $userloadans?
  501: 		    $loadans :  $userloadans;
  502: 	    } else {
  503: 		$answer = $loadans;
  504: 	    }
  505: 	} else {
  506: 	    $answer = $userloadans;
  507: 	}
  508: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  509: 	    if ($want_server_name) {
  510: 		$spareserver=$tryserver;
  511: 	    } else {
  512: 		$spareserver="http://$hostname{$tryserver}";
  513: 	    }
  514: 	    $lowestserver=$answer;
  515: 	}
  516:     }
  517:     return $spareserver;
  518: }
  519: 
  520: # --------------------------------------------- Try to change a user's password
  521: 
  522: sub changepass {
  523:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  524:     $currentpass = &escape($currentpass);
  525:     $newpass     = &escape($newpass);
  526:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  527: 		       $server);
  528:     if (! $answer) {
  529: 	&logthis("No reply on password change request to $server ".
  530: 		 "by $uname in domain $udom.");
  531:     } elsif ($answer =~ "^ok") {
  532:         &logthis("$uname in $udom successfully changed their password ".
  533: 		 "on $server.");
  534:     } elsif ($answer =~ "^pwchange_failure") {
  535: 	&logthis("$uname in $udom was unable to change their password ".
  536: 		 "on $server.  The action was blocked by either lcpasswd ".
  537: 		 "or pwchange");
  538:     } elsif ($answer =~ "^non_authorized") {
  539:         &logthis("$uname in $udom did not get their password correct when ".
  540: 		 "attempting to change it on $server.");
  541:     } elsif ($answer =~ "^auth_mode_error") {
  542:         &logthis("$uname in $udom attempted to change their password despite ".
  543: 		 "not being locally or internally authenticated on $server.");
  544:     } elsif ($answer =~ "^unknown_user") {
  545:         &logthis("$uname in $udom attempted to change their password ".
  546: 		 "on $server but were unable to because $server is not ".
  547: 		 "their home server.");
  548:     } elsif ($answer =~ "^refused") {
  549: 	&logthis("$server refused to change $uname in $udom password because ".
  550: 		 "it was sent an unencrypted request to change the password.");
  551:     }
  552:     return $answer;
  553: }
  554: 
  555: # ----------------------- Try to determine user's current authentication scheme
  556: 
  557: sub queryauthenticate {
  558:     my ($uname,$udom)=@_;
  559:     my $uhome=&homeserver($uname,$udom);
  560:     if (!$uhome) {
  561: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  562: 	return 'no_host';
  563:     }
  564:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  565:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  566: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  567:     }
  568:     return $answer;
  569: }
  570: 
  571: # --------- Try to authenticate user from domain's lib servers (first this one)
  572: 
  573: sub authenticate {
  574:     my ($uname,$upass,$udom)=@_;
  575:     $upass=escape($upass);
  576:     $uname=~s/\W//g;
  577:     my $uhome=&homeserver($uname,$udom);
  578:     if (!$uhome) {
  579: 	&logthis("User $uname at $udom is unknown in authenticate");
  580: 	return 'no_host';
  581:     }
  582:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  583:     if ($answer eq 'authorized') {
  584: 	&logthis("User $uname at $udom authorized by $uhome"); 
  585: 	return $uhome; 
  586:     }
  587:     if ($answer eq 'non_authorized') {
  588: 	&logthis("User $uname at $udom rejected by $uhome");
  589: 	return 'no_host'; 
  590:     }
  591:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  592:     return 'no_host';
  593: }
  594: 
  595: # ---------------------- Find the homebase for a user from domain's lib servers
  596: 
  597: my %homecache;
  598: sub homeserver {
  599:     my ($uname,$udom,$ignoreBadCache)=@_;
  600:     my $index="$uname:$udom";
  601: 
  602:     if (exists($homecache{$index})) { return $homecache{$index}; }
  603:     my $tryserver;
  604:     foreach $tryserver (keys %libserv) {
  605:         next if ($ignoreBadCache ne 'true' && 
  606: 		 exists($badServerCache{$tryserver}));
  607: 	if ($hostdom{$tryserver} eq $udom) {
  608:            my $answer=reply("home:$udom:$uname",$tryserver);
  609:            if ($answer eq 'found') { 
  610: 	       return $homecache{$index}=$tryserver;
  611:            } elsif ($answer eq 'no_host') {
  612: 	       $badServerCache{$tryserver}=1;
  613:            }
  614:        }
  615:     }    
  616:     return 'no_host';
  617: }
  618: 
  619: # ------------------------------------- Find the usernames behind a list of IDs
  620: 
  621: sub idget {
  622:     my ($udom,@ids)=@_;
  623:     my %returnhash=();
  624:     
  625:     my $tryserver;
  626:     foreach $tryserver (keys %libserv) {
  627:        if ($hostdom{$tryserver} eq $udom) {
  628: 	  my $idlist=join('&',@ids);
  629:           $idlist=~tr/A-Z/a-z/; 
  630: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  631:           my @answer=();
  632:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  633: 	      @answer=split(/\&/,$reply);
  634:           }                    ;
  635:           my $i;
  636:           for ($i=0;$i<=$#ids;$i++) {
  637:               if ($answer[$i]) {
  638: 		  $returnhash{$ids[$i]}=$answer[$i];
  639:               } 
  640:           }
  641:        }
  642:     }    
  643:     return %returnhash;
  644: }
  645: 
  646: # ------------------------------------- Find the IDs behind a list of usernames
  647: 
  648: sub idrget {
  649:     my ($udom,@unames)=@_;
  650:     my %returnhash=();
  651:     foreach (@unames) {
  652:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  653:     }
  654:     return %returnhash;
  655: }
  656: 
  657: # ------------------------------- Store away a list of names and associated IDs
  658: 
  659: sub idput {
  660:     my ($udom,%ids)=@_;
  661:     my %servers=();
  662:     foreach (keys %ids) {
  663: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  664:         my $uhom=&homeserver($_,$udom);
  665:         if ($uhom ne 'no_host') {
  666:             my $id=&escape($ids{$_});
  667:             $id=~tr/A-Z/a-z/;
  668:             my $unam=&escape($_);
  669: 	    if ($servers{$uhom}) {
  670: 		$servers{$uhom}.='&'.$id.'='.$unam;
  671:             } else {
  672:                 $servers{$uhom}=$id.'='.$unam;
  673:             }
  674:         }
  675:     }
  676:     foreach (keys %servers) {
  677:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  678:     }
  679: }
  680: 
  681: # --------------------------------------------------- Assign a key to a student
  682: 
  683: sub assign_access_key {
  684: #
  685: # a valid key looks like uname:udom#comments
  686: # comments are being appended
  687: #
  688:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  689:     $kdom=
  690:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  691:     $knum=
  692:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  693:     $cdom=
  694:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  695:     $cnum=
  696:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  697:     $udom=$env{'user.name'} unless (defined($udom));
  698:     $uname=$env{'user.domain'} unless (defined($uname));
  699:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  700:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  701:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  702:                                                   # assigned to this person
  703:                                                   # - this should not happen,
  704:                                                   # unless something went wrong
  705:                                                   # the first time around
  706: # ready to assign
  707:         $logentry=$1.'; '.$logentry;
  708:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  709:                                                  $kdom,$knum) eq 'ok') {
  710: # key now belongs to user
  711: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  712:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  713:                 &appenv('environment.'.$envkey => $ckey);
  714:                 return 'ok';
  715:             } else {
  716:                 return 
  717:   'error: Count not permanently assign key, will need to be re-entered later.';
  718: 	    }
  719:         } else {
  720:             return 'error: Could not assign key, try again later.';
  721:         }
  722:     } elsif (!$existing{$ckey}) {
  723: # the key does not exist
  724: 	return 'error: The key does not exist';
  725:     } else {
  726: # the key is somebody else's
  727: 	return 'error: The key is already in use';
  728:     }
  729: }
  730: 
  731: # ------------------------------------------ put an additional comment on a key
  732: 
  733: sub comment_access_key {
  734: #
  735: # a valid key looks like uname:udom#comments
  736: # comments are being appended
  737: #
  738:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  739:     $cdom=
  740:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  741:     $cnum=
  742:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  743:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  744:     if ($existing{$ckey}) {
  745:         $existing{$ckey}.='; '.$logentry;
  746: # ready to assign
  747:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  748:                                                  $cdom,$cnum) eq 'ok') {
  749: 	    return 'ok';
  750:         } else {
  751: 	    return 'error: Count not store comment.';
  752:         }
  753:     } else {
  754: # the key does not exist
  755: 	return 'error: The key does not exist';
  756:     }
  757: }
  758: 
  759: # ------------------------------------------------------ Generate a set of keys
  760: 
  761: sub generate_access_keys {
  762:     my ($number,$cdom,$cnum,$logentry)=@_;
  763:     $cdom=
  764:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  765:     $cnum=
  766:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  767:     unless (&allowed('mky',$cdom)) { return 0; }
  768:     unless (($cdom) && ($cnum)) { return 0; }
  769:     if ($number>10000) { return 0; }
  770:     sleep(2); # make sure don't get same seed twice
  771:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  772:     my $total=0;
  773:     for (my $i=1;$i<=$number;$i++) {
  774:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  775:                   sprintf("%lx",int(100000*rand)).'-'.
  776:                   sprintf("%lx",int(100000*rand));
  777:        $newkey=~s/1/g/g; # folks mix up 1 and l
  778:        $newkey=~s/0/h/g; # and also 0 and O
  779:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  780:        if ($existing{$newkey}) {
  781:            $i--;
  782:        } else {
  783: 	  if (&put('accesskeys',
  784:               { $newkey => '# generated '.localtime().
  785:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  786:                            '; '.$logentry },
  787: 		   $cdom,$cnum) eq 'ok') {
  788:               $total++;
  789: 	  }
  790:        }
  791:     }
  792:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  793:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  794:     return $total;
  795: }
  796: 
  797: # ------------------------------------------------------- Validate an accesskey
  798: 
  799: sub validate_access_key {
  800:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  801:     $cdom=
  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  803:     $cnum=
  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  805:     $udom=$env{'user.domain'} unless (defined($udom));
  806:     $uname=$env{'user.name'} unless (defined($uname));
  807:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  808:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  809: }
  810: 
  811: # ------------------------------------- Find the section of student in a course
  812: sub devalidate_getsection_cache {
  813:     my ($udom,$unam,$courseid)=@_;
  814:     $courseid=~s/\_/\//g;
  815:     $courseid=~s/^(\w)/\/$1/;
  816:     my $hashid="$udom:$unam:$courseid";
  817:     &devalidate_cache_new('getsection',$hashid);
  818: }
  819: 
  820: sub getsection {
  821:     my ($udom,$unam,$courseid)=@_;
  822:     my $cachetime=1800;
  823:     $courseid=~s/\_/\//g;
  824:     $courseid=~s/^(\w)/\/$1/;
  825: 
  826:     my $hashid="$udom:$unam:$courseid";
  827:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  828:     if (defined($cached)) { return $result; }
  829: 
  830:     my %Pending; 
  831:     my %Expired;
  832:     #
  833:     # Each role can either have not started yet (pending), be active, 
  834:     #    or have expired.
  835:     #
  836:     # If there is an active role, we are done.
  837:     #
  838:     # If there is more than one role which has not started yet, 
  839:     #     choose the one which will start sooner
  840:     # If there is one role which has not started yet, return it.
  841:     #
  842:     # If there is more than one expired role, choose the one which ended last.
  843:     # If there is a role which has expired, return it.
  844:     #
  845:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  846:                         &homeserver($unam,$udom)))) {
  847:         my ($key,$value)=split(/\=/,$_);
  848:         $key=&unescape($key);
  849:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  850:         my $section=$1;
  851:         if ($key eq $courseid.'_st') { $section=''; }
  852:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  853:         my $now=time;
  854:         if (defined($end) && $end && ($now > $end)) {
  855:             $Expired{$end}=$section;
  856:             next;
  857:         }
  858:         if (defined($start) && $start && ($now < $start)) {
  859:             $Pending{$start}=$section;
  860:             next;
  861:         }
  862:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  863:     }
  864:     #
  865:     # Presumedly there will be few matching roles from the above
  866:     # loop and the sorting time will be negligible.
  867:     if (scalar(keys(%Pending))) {
  868:         my ($time) = sort {$a <=> $b} keys(%Pending);
  869:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  870:     } 
  871:     if (scalar(keys(%Expired))) {
  872:         my @sorted = sort {$a <=> $b} keys(%Expired);
  873:         my $time = pop(@sorted);
  874:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  875:     }
  876:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  877: }
  878: 
  879: sub save_cache {
  880:     &purge_remembered();
  881:     #&Apache::loncommon::validate_page();
  882:     undef(%env);
  883: }
  884: 
  885: my $to_remember=-1;
  886: my %remembered;
  887: my %accessed;
  888: my $kicks=0;
  889: my $hits=0;
  890: sub devalidate_cache_new {
  891:     my ($name,$id,$debug) = @_;
  892:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  893:     $id=&escape($name.':'.$id);
  894:     $memcache->delete($id);
  895:     delete($remembered{$id});
  896:     delete($accessed{$id});
  897: }
  898: 
  899: sub is_cached_new {
  900:     my ($name,$id,$debug) = @_;
  901:     $id=&escape($name.':'.$id);
  902:     if (exists($remembered{$id})) {
  903: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  904: 	$accessed{$id}=[&gettimeofday()];
  905: 	$hits++;
  906: 	return ($remembered{$id},1);
  907:     }
  908:     my $value = $memcache->get($id);
  909:     if (!(defined($value))) {
  910: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  911: 	return (undef,undef);
  912:     }
  913:     if ($value eq '__undef__') {
  914: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  915: 	$value=undef;
  916:     }
  917:     &make_room($id,$value,$debug);
  918:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  919:     return ($value,1);
  920: }
  921: 
  922: sub do_cache_new {
  923:     my ($name,$id,$value,$time,$debug) = @_;
  924:     $id=&escape($name.':'.$id);
  925:     my $setvalue=$value;
  926:     if (!defined($setvalue)) {
  927: 	$setvalue='__undef__';
  928:     }
  929:     if (!defined($time) ) {
  930: 	$time=600;
  931:     }
  932:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  933:     $memcache->set($id,$setvalue,$time);
  934:     # need to make a copy of $value
  935:     #&make_room($id,$value,$debug);
  936:     return $value;
  937: }
  938: 
  939: sub make_room {
  940:     my ($id,$value,$debug)=@_;
  941:     $remembered{$id}=$value;
  942:     if ($to_remember<0) { return; }
  943:     $accessed{$id}=[&gettimeofday()];
  944:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  945:     my $to_kick;
  946:     my $max_time=0;
  947:     foreach my $other (keys(%accessed)) {
  948: 	if (&tv_interval($accessed{$other}) > $max_time) {
  949: 	    $to_kick=$other;
  950: 	    $max_time=&tv_interval($accessed{$other});
  951: 	}
  952:     }
  953:     delete($remembered{$to_kick});
  954:     delete($accessed{$to_kick});
  955:     $kicks++;
  956:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  957:     return;
  958: }
  959: 
  960: sub purge_remembered {
  961:     #&logthis("Tossing ".scalar(keys(%remembered)));
  962:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  963:     undef(%remembered);
  964:     undef(%accessed);
  965: }
  966: # ------------------------------------- Read an entry from a user's environment
  967: 
  968: sub userenvironment {
  969:     my ($udom,$unam,@what)=@_;
  970:     my %returnhash=();
  971:     my @answer=split(/\&/,
  972:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  973:                       &homeserver($unam,$udom)));
  974:     my $i;
  975:     for ($i=0;$i<=$#what;$i++) {
  976: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  977:     }
  978:     return %returnhash;
  979: }
  980: 
  981: # ---------------------------------------------------------- Get a studentphoto
  982: sub studentphoto {
  983:     my ($udom,$unam,$ext) = @_;
  984:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  985:     if (defined($env{'request.course.id'})) {
  986:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
  987:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
  988:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
  989:             } else {
  990:                 my ($result,$perm_reqd)=
  991: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
  992:                 if ($result eq 'ok') {
  993:                     if (!($perm_reqd eq 'yes')) {
  994:                         return(&retrievestudentphoto($udom,$unam,$ext));
  995:                     }
  996:                 }
  997:             }
  998:         }
  999:     } else {
 1000:         my ($result,$perm_reqd) = 
 1001: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1002:         if ($result eq 'ok') {
 1003:             if (!($perm_reqd eq 'yes')) {
 1004:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1005:             }
 1006:         }
 1007:     }
 1008:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1009: }
 1010: 
 1011: sub retrievestudentphoto {
 1012:     my ($udom,$unam,$ext,$type) = @_;
 1013:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1014:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1015:     if ($ret eq 'ok') {
 1016:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1017:         if ($type eq 'thumbnail') {
 1018:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1019:         }
 1020:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1021:         return $tokenurl;
 1022:     } else {
 1023:         if ($type eq 'thumbnail') {
 1024:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1025:         } else { 
 1026:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1027:         }
 1028:     }
 1029: }
 1030: 
 1031: # -------------------------------------------------------------------- New chat
 1032: 
 1033: sub chatsend {
 1034:     my ($newentry,$anon,$group)=@_;
 1035:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1036:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1037:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1038:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1039: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1040: 		   &escape($newentry)).':'.$group,$chome);
 1041: }
 1042: 
 1043: # ------------------------------------------ Find current version of a resource
 1044: 
 1045: sub getversion {
 1046:     my $fname=&clutter(shift);
 1047:     unless ($fname=~/^\/res\//) { return -1; }
 1048:     return &currentversion(&filelocation('',$fname));
 1049: }
 1050: 
 1051: sub currentversion {
 1052:     my $fname=shift;
 1053:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1054:     if (defined($cached)) { return $result; }
 1055:     my $author=$fname;
 1056:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1057:     my ($udom,$uname)=split(/\//,$author);
 1058:     my $home=homeserver($uname,$udom);
 1059:     if ($home eq 'no_host') { 
 1060:         return -1; 
 1061:     }
 1062:     my $answer=reply("currentversion:$fname",$home);
 1063:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1064: 	return -1;
 1065:     }
 1066:     return &do_cache_new('resversion',$fname,$answer,600);
 1067: }
 1068: 
 1069: # ----------------------------- Subscribe to a resource, return URL if possible
 1070: 
 1071: sub subscribe {
 1072:     my $fname=shift;
 1073:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1074:     $fname=~s/[\n\r]//g;
 1075:     my $author=$fname;
 1076:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1077:     my ($udom,$uname)=split(/\//,$author);
 1078:     my $home=homeserver($uname,$udom);
 1079:     if ($home eq 'no_host') {
 1080:         return 'not_found';
 1081:     }
 1082:     my $answer=reply("sub:$fname",$home);
 1083:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1084: 	$answer.=' by '.$home;
 1085:     }
 1086:     return $answer;
 1087: }
 1088:     
 1089: # -------------------------------------------------------------- Replicate file
 1090: 
 1091: sub repcopy {
 1092:     my $filename=shift;
 1093:     $filename=~s/\/+/\//g;
 1094:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1095:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1096:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1097: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1098: 	return &repcopy_userfile($filename);
 1099:     }
 1100:     $filename=~s/[\n\r]//g;
 1101:     my $transname="$filename.in.transfer";
 1102:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1103:     my $remoteurl=subscribe($filename);
 1104:     if ($remoteurl =~ /^con_lost by/) {
 1105: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1106:            return 'unavailable';
 1107:     } elsif ($remoteurl eq 'not_found') {
 1108: 	   #&logthis("Subscribe returned not_found: $filename");
 1109: 	   return 'not_found';
 1110:     } elsif ($remoteurl =~ /^rejected by/) {
 1111: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1112:            return 'forbidden';
 1113:     } elsif ($remoteurl eq 'directory') {
 1114:            return 'ok';
 1115:     } else {
 1116:         my $author=$filename;
 1117:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1118:         my ($udom,$uname)=split(/\//,$author);
 1119:         my $home=homeserver($uname,$udom);
 1120:         unless ($home eq $perlvar{'lonHostID'}) {
 1121:            my @parts=split(/\//,$filename);
 1122:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1123:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1124:                &logthis("Malconfiguration for replication: $filename");
 1125: 	       return 'bad_request';
 1126:            }
 1127:            my $count;
 1128:            for ($count=5;$count<$#parts;$count++) {
 1129:                $path.="/$parts[$count]";
 1130:                if ((-e $path)!=1) {
 1131: 		   mkdir($path,0777);
 1132:                }
 1133:            }
 1134:            my $ua=new LWP::UserAgent;
 1135:            my $request=new HTTP::Request('GET',"$remoteurl");
 1136:            my $response=$ua->request($request,$transname);
 1137:            if ($response->is_error()) {
 1138: 	       unlink($transname);
 1139:                my $message=$response->status_line;
 1140:                &logthis("<font color=\"blue\">WARNING:"
 1141:                        ." LWP get: $message: $filename</font>");
 1142:                return 'unavailable';
 1143:            } else {
 1144: 	       if ($remoteurl!~/\.meta$/) {
 1145:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1146:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1147:                   if ($mresponse->is_error()) {
 1148: 		      unlink($filename.'.meta');
 1149:                       &logthis(
 1150:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1151:                   }
 1152: 	       }
 1153:                rename($transname,$filename);
 1154:                return 'ok';
 1155:            }
 1156:        }
 1157:     }
 1158: }
 1159: 
 1160: # ------------------------------------------------ Get server side include body
 1161: sub ssi_body {
 1162:     my ($filelink,%form)=@_;
 1163:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1164:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1165:     }
 1166:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1167:                                      &ssi($filelink,%form));
 1168:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
 1169:     $output=~s/^.*?\<body[^\>]*\>//si;
 1170:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1171:     return $output;
 1172: }
 1173: 
 1174: # --------------------------------------------------------- Server Side Include
 1175: 
 1176: sub ssi {
 1177: 
 1178:     my ($fn,%form)=@_;
 1179: 
 1180:     my $ua=new LWP::UserAgent;
 1181:     
 1182:     my $request;
 1183: 
 1184:     $form{'no_update_last_known'}=1;
 1185: 
 1186:     if (%form) {
 1187:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1188:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1189:     } else {
 1190:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1191:     }
 1192: 
 1193:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1194:     my $response=$ua->request($request);
 1195: 
 1196:     return $response->content;
 1197: }
 1198: 
 1199: sub externalssi {
 1200:     my ($url)=@_;
 1201:     my $ua=new LWP::UserAgent;
 1202:     my $request=new HTTP::Request('GET',$url);
 1203:     my $response=$ua->request($request);
 1204:     return $response->content;
 1205: }
 1206: 
 1207: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1208: 
 1209: sub allowuploaded {
 1210:     my ($srcurl,$url)=@_;
 1211:     $url=&clutter(&declutter($url));
 1212:     my $dir=$url;
 1213:     $dir=~s/\/[^\/]+$//;
 1214:     my %httpref=();
 1215:     my $httpurl=&hreflocation('',$url);
 1216:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1217:     &Apache::lonnet::appenv(%httpref);
 1218: }
 1219: 
 1220: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1221: # input: action, courseID, current domain, intended
 1222: #        path to file, source of file, instruction to parse file for objects,
 1223: #        ref to hash for embedded objects,
 1224: #        ref to hash for codebase of java objects.
 1225: #
 1226: # output: url to file (if action was uploaddoc), 
 1227: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1228: #
 1229: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1230: # course.
 1231: #
 1232: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1233: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1234: #          course's home server.
 1235: #
 1236: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1237: #          be copied from $source (current location) to 
 1238: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1239: #         and will then be copied to
 1240: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1241: #         course's home server.
 1242: #
 1243: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1244: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1245: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1246: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1247: #         in course's home server.
 1248: #
 1249: 
 1250: sub process_coursefile {
 1251:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1252:     my $fetchresult;
 1253:     my $home=&homeserver($docuname,$docudom);
 1254:     if ($action eq 'propagate') {
 1255:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1256: 			     $home);
 1257:     } else {
 1258:         my $fpath = '';
 1259:         my $fname = $file;
 1260:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1261:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1262:         my $filepath = &build_filepath($fpath);
 1263:         if ($action eq 'copy') {
 1264:             if ($source eq '') {
 1265:                 $fetchresult = 'no source file';
 1266:                 return $fetchresult;
 1267:             } else {
 1268:                 my $destination = $filepath.'/'.$fname;
 1269:                 rename($source,$destination);
 1270:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1271:                                  $home);
 1272:             }
 1273:         } elsif ($action eq 'uploaddoc') {
 1274:             open(my $fh,'>'.$filepath.'/'.$fname);
 1275:             print $fh $env{'form.'.$source};
 1276:             close($fh);
 1277:             if ($parser eq 'parse') {
 1278:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1279:                 unless ($parse_result eq 'ok') {
 1280:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1281:                 }
 1282:             }
 1283:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1284:                                  $home);
 1285:             if ($fetchresult eq 'ok') {
 1286:                 return '/uploaded/'.$fpath.'/'.$fname;
 1287:             } else {
 1288:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1289:                         ' to host '.$home.': '.$fetchresult);
 1290:                 return '/adm/notfound.html';
 1291:             }
 1292:         }
 1293:     }
 1294:     unless ( $fetchresult eq 'ok') {
 1295:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1296:              ' to host '.$home.': '.$fetchresult);
 1297:     }
 1298:     return $fetchresult;
 1299: }
 1300: 
 1301: sub build_filepath {
 1302:     my ($fpath) = @_;
 1303:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1304:     unless ($fpath eq '') {
 1305:         my @parts=split('/',$fpath);
 1306:         foreach my $part (@parts) {
 1307:             $filepath.= '/'.$part;
 1308:             if ((-e $filepath)!=1) {
 1309:                 mkdir($filepath,0777);
 1310:             }
 1311:         }
 1312:     }
 1313:     return $filepath;
 1314: }
 1315: 
 1316: sub store_edited_file {
 1317:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1318:     my $file = $primary_url;
 1319:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1320:     my $fpath = '';
 1321:     my $fname = $file;
 1322:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1323:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1324:     my $filepath = &build_filepath($fpath);
 1325:     open(my $fh,'>'.$filepath.'/'.$fname);
 1326:     print $fh $content;
 1327:     close($fh);
 1328:     my $home=&homeserver($docuname,$docudom);
 1329:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1330: 			  $home);
 1331:     if ($$fetchresult eq 'ok') {
 1332:         return '/uploaded/'.$fpath.'/'.$fname;
 1333:     } else {
 1334:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1335: 		 ' to host '.$home.': '.$$fetchresult);
 1336:         return '/adm/notfound.html';
 1337:     }
 1338: }
 1339: 
 1340: sub clean_filename {
 1341:     my ($fname)=@_;
 1342: # Replace Windows backslashes by forward slashes
 1343:     $fname=~s/\\/\//g;
 1344: # Get rid of everything but the actual filename
 1345:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1346: # Replace spaces by underscores
 1347:     $fname=~s/\s+/\_/g;
 1348: # Replace all other weird characters by nothing
 1349:     $fname=~s/[^\w\.\-]//g;
 1350: # Replace all .\d. sequences with _\d. so they no longer look like version
 1351: # numbers
 1352:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1353:     return $fname;
 1354: }
 1355: 
 1356: # --------------- Take an uploaded file and put it into the userfiles directory
 1357: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1358: #                    the desired filenam is in $env{"form.$formname.filename"}
 1359: #        $coursedoc - if true up to the current course
 1360: #                     if false
 1361: #        $subdir - directory in userfile to store the file into
 1362: #        $parser, $allfiles, $codebase - unknown
 1363: #
 1364: # output: url of file in userspace, or error: <message> 
 1365: #             or /adm/notfound.html if failure to upload occurse
 1366: 
 1367: 
 1368: sub userfileupload {
 1369:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1370:     if (!defined($subdir)) { $subdir='unknown'; }
 1371:     my $fname=$env{'form.'.$formname.'.filename'};
 1372:     $fname=&clean_filename($fname);
 1373: # See if there is anything left
 1374:     unless ($fname) { return 'error: no uploaded file'; }
 1375:     chop($env{'form.'.$formname});
 1376:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1377:         my $now = time;
 1378:         my $filepath = 'tmp/helprequests/'.$now;
 1379:         my @parts=split(/\//,$filepath);
 1380:         my $fullpath = $perlvar{'lonDaemons'};
 1381:         for (my $i=0;$i<@parts;$i++) {
 1382:             $fullpath .= '/'.$parts[$i];
 1383:             if ((-e $fullpath)!=1) {
 1384:                 mkdir($fullpath,0777);
 1385:             }
 1386:         }
 1387:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1388:         print $fh $env{'form.'.$formname};
 1389:         close($fh);
 1390:         return $fullpath.'/'.$fname;
 1391:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1392:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1393:                        '_'.$env{'user.domain'}.'/pending';
 1394:         my @parts=split(/\//,$filepath);
 1395:         my $fullpath = $perlvar{'lonDaemons'};
 1396:         for (my $i=0;$i<@parts;$i++) {
 1397:             $fullpath .= '/'.$parts[$i];
 1398:             if ((-e $fullpath)!=1) {
 1399:                 mkdir($fullpath,0777);
 1400:             }
 1401:         }
 1402:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1403:         print $fh $env{'form.'.$formname};
 1404:         close($fh);
 1405:         return $fullpath.'/'.$fname;
 1406:     }
 1407:     
 1408: # Create the directory if not present
 1409:     $fname="$subdir/$fname";
 1410:     if ($coursedoc) {
 1411: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1412: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1413:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1414:             return &finishuserfileupload($docuname,$docudom,
 1415: 					 $formname,$fname,$parser,$allfiles,
 1416: 					 $codebase);
 1417:         } else {
 1418:             $fname=$env{'form.folder'}.'/'.$fname;
 1419:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1420: 				       $fname,$formname,$parser,
 1421: 				       $allfiles,$codebase);
 1422:         }
 1423:     } elsif (defined($destuname)) {
 1424:         my $docuname=$destuname;
 1425:         my $docudom=$destudom;
 1426: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1427: 				     $fname,$parser,$allfiles,$codebase);
 1428:         
 1429:     } else {
 1430:         my $docuname=$env{'user.name'};
 1431:         my $docudom=$env{'user.domain'};
 1432:         if (exists($env{'form.group'})) {
 1433:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1434:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1435:         }
 1436: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1437: 				     $fname,$parser,$allfiles,$codebase);
 1438:     }
 1439: }
 1440: 
 1441: sub finishuserfileupload {
 1442:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1443:     my $path=$docudom.'/'.$docuname.'/';
 1444:     my $filepath=$perlvar{'lonDocRoot'};
 1445:     my ($fnamepath,$file);
 1446:     $file=$fname;
 1447:     if ($fname=~m|/|) {
 1448:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1449: 	$path.=$fnamepath.'/';
 1450:     }
 1451:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1452:     my $count;
 1453:     for ($count=4;$count<=$#parts;$count++) {
 1454:         $filepath.="/$parts[$count]";
 1455:         if ((-e $filepath)!=1) {
 1456: 	    mkdir($filepath,0777);
 1457:         }
 1458:     }
 1459: # Save the file
 1460:     {
 1461: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1462: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1463: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1464: 	    return '/adm/notfound.html';
 1465: 	}
 1466: 	if (!print FH ($env{'form.'.$formname})) {
 1467: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1468: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1469: 	    return '/adm/notfound.html';
 1470: 	}
 1471: 	close(FH);
 1472:     }
 1473:     if ($parser eq 'parse') {
 1474:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1475: 						   $codebase);
 1476:         unless ($parse_result eq 'ok') {
 1477:             &logthis('Failed to parse '.$filepath.$file.
 1478: 		     ' for embedded media: '.$parse_result); 
 1479:         }
 1480:     }
 1481: # Notify homeserver to grep it
 1482: #
 1483:     my $docuhome=&homeserver($docuname,$docudom);
 1484:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1485:     if ($fetchresult eq 'ok') {
 1486: #
 1487: # Return the URL to it
 1488:         return '/uploaded/'.$path.$file;
 1489:     } else {
 1490:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1491: 		 ': '.$fetchresult);
 1492:         return '/adm/notfound.html';
 1493:     }    
 1494: }
 1495: 
 1496: sub extract_embedded_items {
 1497:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1498:     my @state = ();
 1499:     my %javafiles = (
 1500:                       codebase => '',
 1501:                       code => '',
 1502:                       archive => ''
 1503:                     );
 1504:     my %mediafiles = (
 1505:                       src => '',
 1506:                       movie => '',
 1507:                      );
 1508:     my $p;
 1509:     if ($content) {
 1510:         $p = HTML::LCParser->new($content);
 1511:     } else {
 1512:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1513:     }
 1514:     while (my $t=$p->get_token()) {
 1515: 	if ($t->[0] eq 'S') {
 1516: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1517: 	    push (@state, $tagname);
 1518:             if (lc($tagname) eq 'allow') {
 1519:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1520:             }
 1521: 	    if (lc($tagname) eq 'img') {
 1522: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1523: 	    }
 1524:             if (lc($tagname) eq 'script') {
 1525:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1526:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1527:                 } else {
 1528:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1529:                 }
 1530:             }
 1531:             if (lc($tagname) eq 'link') {
 1532:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1533:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1534:                 }
 1535:             }
 1536: 	    if (lc($tagname) eq 'object' ||
 1537: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1538: 		foreach my $item (keys(%javafiles)) {
 1539: 		    $javafiles{$item} = '';
 1540: 		}
 1541: 	    }
 1542: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1543: 		my $name = lc($attr->{'name'});
 1544: 		foreach my $item (keys(%javafiles)) {
 1545: 		    if ($name eq $item) {
 1546: 			$javafiles{$item} = $attr->{'value'};
 1547: 			last;
 1548: 		    }
 1549: 		}
 1550: 		foreach my $item (keys(%mediafiles)) {
 1551: 		    if ($name eq $item) {
 1552: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1553: 			last;
 1554: 		    }
 1555: 		}
 1556: 	    }
 1557: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1558: 		foreach my $item (keys(%javafiles)) {
 1559: 		    if ($attr->{$item}) {
 1560: 			$javafiles{$item} = $attr->{$item};
 1561: 			last;
 1562: 		    }
 1563: 		}
 1564: 		foreach my $item (keys(%mediafiles)) {
 1565: 		    if ($attr->{$item}) {
 1566: 			&add_filetype($allfiles,$attr->{$item},$item);
 1567: 			last;
 1568: 		    }
 1569: 		}
 1570: 	    }
 1571: 	} elsif ($t->[0] eq 'E') {
 1572: 	    my ($tagname) = ($t->[1]);
 1573: 	    if ($javafiles{'codebase'} ne '') {
 1574: 		$javafiles{'codebase'} .= '/';
 1575: 	    }  
 1576: 	    if (lc($tagname) eq 'applet' ||
 1577: 		lc($tagname) eq 'object' ||
 1578: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1579: 		) {
 1580: 		foreach my $item (keys(%javafiles)) {
 1581: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1582: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1583: 			&add_filetype($allfiles,$file,$item);
 1584: 		    }
 1585: 		}
 1586: 	    } 
 1587: 	    pop @state;
 1588: 	}
 1589:     }
 1590:     return 'ok';
 1591: }
 1592: 
 1593: sub add_filetype {
 1594:     my ($allfiles,$file,$type)=@_;
 1595:     if (exists($allfiles->{$file})) {
 1596: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1597: 	    push(@{$allfiles->{$file}}, &escape($type));
 1598: 	}
 1599:     } else {
 1600: 	@{$allfiles->{$file}} = (&escape($type));
 1601:     }
 1602: }
 1603: 
 1604: sub removeuploadedurl {
 1605:     my ($url)=@_;
 1606:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1607:     return &removeuserfile($uname,$udom,$fname);
 1608: }
 1609: 
 1610: sub removeuserfile {
 1611:     my ($docuname,$docudom,$fname)=@_;
 1612:     my $home=&homeserver($docuname,$docudom);
 1613:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1614: }
 1615: 
 1616: sub mkdiruserfile {
 1617:     my ($docuname,$docudom,$dir)=@_;
 1618:     my $home=&homeserver($docuname,$docudom);
 1619:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1620: }
 1621: 
 1622: sub renameuserfile {
 1623:     my ($docuname,$docudom,$old,$new)=@_;
 1624:     my $home=&homeserver($docuname,$docudom);
 1625:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1626: 		  &escape("$new"),$home);
 1627: }
 1628: 
 1629: # ------------------------------------------------------------------------- Log
 1630: 
 1631: sub log {
 1632:     my ($dom,$nam,$hom,$what)=@_;
 1633:     return critical("log:$dom:$nam:$what",$hom);
 1634: }
 1635: 
 1636: # ------------------------------------------------------------------ Course Log
 1637: #
 1638: # This routine flushes several buffers of non-mission-critical nature
 1639: #
 1640: 
 1641: sub flushcourselogs {
 1642:     &logthis('Flushing log buffers');
 1643: #
 1644: # course logs
 1645: # This is a log of all transactions in a course, which can be used
 1646: # for data mining purposes
 1647: #
 1648: # It also collects the courseid database, which lists last transaction
 1649: # times and course titles for all courseids
 1650: #
 1651:     my %courseidbuffer=();
 1652:     foreach (keys %courselogs) {
 1653:         my $crsid=$_;
 1654:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1655: 		          &escape($courselogs{$crsid}),
 1656: 		          $coursehombuf{$crsid}) eq 'ok') {
 1657: 	    delete $courselogs{$crsid};
 1658:         } else {
 1659:             &logthis('Failed to flush log buffer for '.$crsid);
 1660:             if (length($courselogs{$crsid})>40000) {
 1661:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1662:                         " exceeded maximum size, deleting.</font>");
 1663:                delete $courselogs{$crsid};
 1664:             }
 1665:         }
 1666:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1667:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1668: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1669:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1670:         } else {
 1671:            $courseidbuffer{$coursehombuf{$crsid}}=
 1672: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1673:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1674:         }
 1675:     }
 1676: #
 1677: # Write course id database (reverse lookup) to homeserver of courses 
 1678: # Is used in pickcourse
 1679: #
 1680:     foreach (keys %courseidbuffer) {
 1681:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1682:     }
 1683: #
 1684: # File accesses
 1685: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1686: #
 1687:     foreach my $entry (keys(%accesshash)) {
 1688:         if ($entry =~ /___count$/) {
 1689:             my ($dom,$name);
 1690:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1691:             if (! defined($dom) || $dom eq '' || 
 1692:                 ! defined($name) || $name eq '') {
 1693:                 my $cid = $env{'request.course.id'};
 1694:                 $dom  = $env{'request.'.$cid.'.domain'};
 1695:                 $name = $env{'request.'.$cid.'.num'};
 1696:             }
 1697:             my $value = $accesshash{$entry};
 1698:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1699:             my %temphash=($url => $value);
 1700:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1701:             if ($result eq 'ok') {
 1702:                 delete $accesshash{$entry};
 1703:             } elsif ($result eq 'unknown_cmd') {
 1704:                 # Target server has old code running on it.
 1705:                 my %temphash=($entry => $value);
 1706:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1707:                     delete $accesshash{$entry};
 1708:                 }
 1709:             }
 1710:         } else {
 1711:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1712:             my %temphash=($entry => $accesshash{$entry});
 1713:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1714:                 delete $accesshash{$entry};
 1715:             }
 1716:         }
 1717:     }
 1718: #
 1719: # Roles
 1720: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1721: #
 1722:     foreach (keys %userrolehash) {
 1723:         my $entry=$_;
 1724:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1725: 	    split(/\:/,$entry);
 1726:         if (&Apache::lonnet::put('nohist_userroles',
 1727:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1728:                 $rudom,$runame) eq 'ok') {
 1729: 	    delete $userrolehash{$entry};
 1730:         }
 1731:     }
 1732: #
 1733: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1734: #
 1735:     my %domrolebuffer = ();
 1736:     foreach my $entry (keys %domainrolehash) {
 1737:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1738:         if ($domrolebuffer{$rudom}) {
 1739:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1740:                       '='.&escape($domainrolehash{$entry});
 1741:         } else {
 1742:             $domrolebuffer{$rudom}.=&escape($entry).
 1743:                       '='.&escape($domainrolehash{$entry});
 1744:         }
 1745:         delete $domainrolehash{$entry};
 1746:     }
 1747:     foreach my $dom (keys(%domrolebuffer)) {
 1748:         foreach my $tryserver (keys %libserv) {
 1749:             if ($hostdom{$tryserver} eq $dom) {
 1750:                 unless (&reply('domroleput:'.$dom.':'.
 1751:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1752:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1753:                 }
 1754:             }
 1755:         }
 1756:     }
 1757:     $dumpcount++;
 1758: }
 1759: 
 1760: sub courselog {
 1761:     my $what=shift;
 1762:     $what=time.':'.$what;
 1763:     unless ($env{'request.course.id'}) { return ''; }
 1764:     $coursedombuf{$env{'request.course.id'}}=
 1765:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1766:     $coursenumbuf{$env{'request.course.id'}}=
 1767:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1768:     $coursehombuf{$env{'request.course.id'}}=
 1769:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1770:     $coursedescrbuf{$env{'request.course.id'}}=
 1771:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1772:     $courseinstcodebuf{$env{'request.course.id'}}=
 1773:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1774:     $courseownerbuf{$env{'request.course.id'}}=
 1775:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1776:     $coursetypebuf{$env{'request.course.id'}}=
 1777:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1778:     if (defined $courselogs{$env{'request.course.id'}}) {
 1779: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1780:     } else {
 1781: 	$courselogs{$env{'request.course.id'}}.=$what;
 1782:     }
 1783:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1784: 	&flushcourselogs();
 1785:     }
 1786: }
 1787: 
 1788: sub courseacclog {
 1789:     my $fnsymb=shift;
 1790:     unless ($env{'request.course.id'}) { return ''; }
 1791:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1792:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1793:         $what.=':POST';
 1794:         # FIXME: Probably ought to escape things....
 1795: 	foreach (keys %env) {
 1796:             if ($_=~/^form\.(.*)/) {
 1797: 		$what.=':'.$1.'='.$env{$_};
 1798:             }
 1799:         }
 1800:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1801:         # FIXME: We should not be depending on a form parameter that someone
 1802:         # editing lonsearchcat.pm might change in the future.
 1803:         if ($env{'form.phase'} eq 'course_search') {
 1804:             $what.= ':POST';
 1805:             # FIXME: Probably ought to escape things....
 1806:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1807:                                  'crsdiscuss') {
 1808:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1809:             }
 1810:         }
 1811:     }
 1812:     &courselog($what);
 1813: }
 1814: 
 1815: sub countacc {
 1816:     my $url=&declutter(shift);
 1817:     return if (! defined($url) || $url eq '');
 1818:     unless ($env{'request.course.id'}) { return ''; }
 1819:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1820:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1821:     $accesshash{$key}++;
 1822: }
 1823: 
 1824: sub linklog {
 1825:     my ($from,$to)=@_;
 1826:     $from=&declutter($from);
 1827:     $to=&declutter($to);
 1828:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1829:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1830: }
 1831:   
 1832: sub userrolelog {
 1833:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1834:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1835:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1836:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1837:         ($trole=~/^ta/)) {
 1838:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1839:        $userrolehash
 1840:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1841:                     =$tend.':'.$tstart;
 1842:     }
 1843:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1844:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1845:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1846:         ($trole=~/^sc/)) {
 1847:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1848:        $domainrolehash
 1849:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1850:                     = $tend.':'.$tstart;
 1851:     }
 1852: }
 1853: 
 1854: sub get_course_adv_roles {
 1855:     my $cid=shift;
 1856:     $cid=$env{'request.course.id'} unless (defined($cid));
 1857:     my %coursehash=&coursedescription($cid);
 1858:     my %nothide=();
 1859:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1860: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1861:     }
 1862:     my %returnhash=();
 1863:     my %dumphash=
 1864:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1865:     my $now=time;
 1866:     foreach (keys %dumphash) {
 1867: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1868:         if (($tstart) && ($tstart<0)) { next; }
 1869:         if (($tend) && ($tend<$now)) { next; }
 1870:         if (($tstart) && ($now<$tstart)) { next; }
 1871:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1872: 	if ($username eq '' || $domain eq '') { next; }
 1873: 	if ((&privileged($username,$domain)) && 
 1874: 	    (!$nothide{$username.':'.$domain})) { next; }
 1875: 	if ($role eq 'cr') { next; }
 1876:         my $key=&plaintext($role);
 1877: 	if ($role =~ /^cr/) {
 1878: 	    $key=(split('/',$role))[3];
 1879: 	}
 1880:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1881:         if ($returnhash{$key}) {
 1882: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1883:         } else {
 1884:             $returnhash{$key}=$username.':'.$domain;
 1885:         }
 1886:      }
 1887:     return %returnhash;
 1888: }
 1889: 
 1890: sub get_my_roles {
 1891:     my ($uname,$udom)=@_;
 1892:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1893:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1894:     my %dumphash=
 1895:             &dump('nohist_userroles',$udom,$uname);
 1896:     my %returnhash=();
 1897:     my $now=time;
 1898:     foreach (keys %dumphash) {
 1899: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1900:         if (($tstart) && ($tstart<0)) { next; }
 1901:         if (($tend) && ($tend<$now)) { next; }
 1902:         if (($tstart) && ($now<$tstart)) { next; }
 1903:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1904: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1905:      }
 1906:     return %returnhash;
 1907: }
 1908: 
 1909: # ----------------------------------------------------- Frontpage Announcements
 1910: #
 1911: #
 1912: 
 1913: sub postannounce {
 1914:     my ($server,$text)=@_;
 1915:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1916:     unless ($text=~/\w/) { $text=''; }
 1917:     return &reply('setannounce:'.&escape($text),$server);
 1918: }
 1919: 
 1920: sub getannounce {
 1921: 
 1922:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1923: 	my $announcement='';
 1924: 	while (<$fh>) { $announcement .=$_; }
 1925: 	close($fh);
 1926: 	if ($announcement=~/\w/) { 
 1927: 	    return 
 1928:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1929:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1930: 	} else {
 1931: 	    return '';
 1932: 	}
 1933:     } else {
 1934: 	return '';
 1935:     }
 1936: }
 1937: 
 1938: # ---------------------------------------------------------- Course ID routines
 1939: # Deal with domain's nohist_courseid.db files
 1940: #
 1941: 
 1942: sub courseidput {
 1943:     my ($domain,$what,$coursehome)=@_;
 1944:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1945: }
 1946: 
 1947: sub courseiddump {
 1948:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
 1949:     my %returnhash=();
 1950:     unless ($domfilter) { $domfilter=''; }
 1951:     foreach my $tryserver (keys %libserv) {
 1952:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1953: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1954: 	        foreach (
 1955:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1956: 			       $sincefilter.':'.&escape($descfilter).':'.
 1957:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
 1958:                                $tryserver))) {
 1959: 		    my ($key,$value)=split(/\=/,$_);
 1960:                     if (($key) && ($value)) {
 1961: 		        $returnhash{&unescape($key)}=$value;
 1962:                     }
 1963:                 }
 1964:             }
 1965:         }
 1966:     }
 1967:     return %returnhash;
 1968: }
 1969: 
 1970: # ---------------------------------------------------------- DC e-mail
 1971: 
 1972: sub dcmailput {
 1973:     my ($domain,$msgid,$message,$server)=@_;
 1974:     my $status = &Apache::lonnet::critical(
 1975:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 1976:        &escape($message),$server);
 1977:     return $status;
 1978: }
 1979: 
 1980: sub dcmaildump {
 1981:     my ($dom,$startdate,$enddate,$senders) = @_;
 1982:     my %returnhash=();
 1983:     if (exists($domain_primary{$dom})) {
 1984:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 1985:                                                          &escape($enddate).':';
 1986: 	my @esc_senders=map { &escape($_)} @$senders;
 1987: 	$cmd.=&escape(join('&',@esc_senders));
 1988: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 1989:             my ($key,$value) = split(/\=/,$_);
 1990:             if (($key) && ($value)) {
 1991:                 $returnhash{&unescape($key)} = &unescape($value);
 1992:             }
 1993:         }
 1994:     }
 1995:     return %returnhash;
 1996: }
 1997: # ---------------------------------------------------------- Domain roles
 1998: 
 1999: sub get_domain_roles {
 2000:     my ($dom,$roles,$startdate,$enddate)=@_;
 2001:     if (undef($startdate) || $startdate eq '') {
 2002:         $startdate = '.';
 2003:     }
 2004:     if (undef($enddate) || $enddate eq '') {
 2005:         $enddate = '.';
 2006:     }
 2007:     my $rolelist = join(':',@{$roles});
 2008:     my %personnel = ();
 2009:     foreach my $tryserver (keys(%libserv)) {
 2010:         if ($hostdom{$tryserver} eq $dom) {
 2011:             %{$personnel{$tryserver}}=();
 2012:             foreach (
 2013:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2014:                    &escape($startdate).':'.&escape($enddate).':'.
 2015:                    &escape($rolelist), $tryserver))) {
 2016:                 my($key,$value) = split(/\=/,$_);
 2017:                 if (($key) && ($value)) {
 2018:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2019:                 }
 2020:             }
 2021:         }
 2022:     }
 2023:     return %personnel;
 2024: }
 2025: 
 2026: # ----------------------------------------------------------- Check out an item
 2027: 
 2028: sub get_first_access {
 2029:     my ($type,$argsymb)=@_;
 2030:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2031:     if ($argsymb) { $symb=$argsymb; }
 2032:     my ($map,$id,$res)=&decode_symb($symb);
 2033:     if ($type eq 'map') {
 2034: 	$res=&symbread($map);
 2035:     } else {
 2036: 	$res=$symb;
 2037:     }
 2038:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2039:     return $times{"$courseid\0$res"};
 2040: }
 2041: 
 2042: sub set_first_access {
 2043:     my ($type)=@_;
 2044:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2045:     my ($map,$id,$res)=&decode_symb($symb);
 2046:     if ($type eq 'map') {
 2047: 	$res=&symbread($map);
 2048:     } else {
 2049: 	$res=$symb;
 2050:     }
 2051:     my $firstaccess=&get_first_access($type,$symb);
 2052:     if (!$firstaccess) {
 2053: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2054:     }
 2055:     return 'already_set';
 2056: }
 2057: 
 2058: sub checkout {
 2059:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2060:     my $now=time;
 2061:     my $lonhost=$perlvar{'lonHostID'};
 2062:     my $infostr=&escape(
 2063:                  'CHECKOUTTOKEN&'.
 2064:                  $tuname.'&'.
 2065:                  $tudom.'&'.
 2066:                  $tcrsid.'&'.
 2067:                  $symb.'&'.
 2068: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2069:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2070:     if ($token=~/^error\:/) { 
 2071:         &logthis("<font color=\"blue\">WARNING: ".
 2072:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2073:                  "</font>");
 2074:         return ''; 
 2075:     }
 2076: 
 2077:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2078:     $token=~tr/a-z/A-Z/;
 2079: 
 2080:     my %infohash=('resource.0.outtoken' => $token,
 2081:                   'resource.0.checkouttime' => $now,
 2082:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2083: 
 2084:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2085:        return '';
 2086:     } else {
 2087:         &logthis("<font color=\"blue\">WARNING: ".
 2088:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2089:                  "</font>");
 2090:     }    
 2091: 
 2092:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2093:                          &escape('Checkout '.$infostr.' - '.
 2094:                                                  $token)) ne 'ok') {
 2095: 	return '';
 2096:     } else {
 2097:         &logthis("<font color=\"blue\">WARNING: ".
 2098:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2099:                  "</font>");
 2100:     }
 2101:     return $token;
 2102: }
 2103: 
 2104: # ------------------------------------------------------------ Check in an item
 2105: 
 2106: sub checkin {
 2107:     my $token=shift;
 2108:     my $now=time;
 2109:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2110:     $lonhost=~tr/A-Z/a-z/;
 2111:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2112:     $dtoken=~s/\W/\_/g;
 2113:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2114:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2115: 
 2116:     unless (($tuname) && ($tudom)) {
 2117:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2118:         return '';
 2119:     }
 2120:     
 2121:     unless (&allowed('mgr',$tcrsid)) {
 2122:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2123:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2124:         return '';
 2125:     }
 2126: 
 2127:     my %infohash=('resource.0.intoken' => $token,
 2128:                   'resource.0.checkintime' => $now,
 2129:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2130: 
 2131:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2132:        return '';
 2133:     }    
 2134: 
 2135:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2136:                          &escape('Checkin - '.$token)) ne 'ok') {
 2137: 	return '';
 2138:     }
 2139: 
 2140:     return ($symb,$tuname,$tudom,$tcrsid);    
 2141: }
 2142: 
 2143: # --------------------------------------------- Set Expire Date for Spreadsheet
 2144: 
 2145: sub expirespread {
 2146:     my ($uname,$udom,$stype,$usymb)=@_;
 2147:     my $cid=$env{'request.course.id'}; 
 2148:     if ($cid) {
 2149:        my $now=time;
 2150:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2151:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2152:                             $env{'course.'.$cid.'.num'}.
 2153: 	        	    ':nohist_expirationdates:'.
 2154:                             &escape($key).'='.$now,
 2155:                             $env{'course.'.$cid.'.home'})
 2156:     }
 2157:     return 'ok';
 2158: }
 2159: 
 2160: # ----------------------------------------------------- Devalidate Spreadsheets
 2161: 
 2162: sub devalidate {
 2163:     my ($symb,$uname,$udom)=@_;
 2164:     my $cid=$env{'request.course.id'}; 
 2165:     if ($cid) {
 2166:         # delete the stored spreadsheets for
 2167:         # - the student level sheet of this user in course's homespace
 2168:         # - the assessment level sheet for this resource 
 2169:         #   for this user in user's homespace
 2170: 	# - current conditional state info
 2171: 	my $key=$uname.':'.$udom.':';
 2172:         my $status=
 2173: 	    &del('nohist_calculatedsheets',
 2174: 		 [$key.'studentcalc:'],
 2175: 		 $env{'course.'.$cid.'.domain'},
 2176: 		 $env{'course.'.$cid.'.num'})
 2177: 		.' '.
 2178: 	    &del('nohist_calculatedsheets_'.$cid,
 2179: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2180:         unless ($status eq 'ok ok') {
 2181:            &logthis('Could not devalidate spreadsheet '.
 2182:                     $uname.' at '.$udom.' for '.
 2183: 		    $symb.': '.$status);
 2184:         }
 2185: 	&delenv('user.state.'.$cid);
 2186:     }
 2187: }
 2188: 
 2189: sub get_scalar {
 2190:     my ($string,$end) = @_;
 2191:     my $value;
 2192:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2193: 	$value = $1;
 2194:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2195: 	$value = $1;
 2196:     }
 2197:     return &unescape($value);
 2198: }
 2199: 
 2200: sub array2str {
 2201:   my (@array) = @_;
 2202:   my $result=&arrayref2str(\@array);
 2203:   $result=~s/^__ARRAY_REF__//;
 2204:   $result=~s/__END_ARRAY_REF__$//;
 2205:   return $result;
 2206: }
 2207: 
 2208: sub arrayref2str {
 2209:   my ($arrayref) = @_;
 2210:   my $result='__ARRAY_REF__';
 2211:   foreach my $elem (@$arrayref) {
 2212:     if(ref($elem) eq 'ARRAY') {
 2213:       $result.=&arrayref2str($elem).'&';
 2214:     } elsif(ref($elem) eq 'HASH') {
 2215:       $result.=&hashref2str($elem).'&';
 2216:     } elsif(ref($elem)) {
 2217:       #print("Got a ref of ".(ref($elem))." skipping.");
 2218:     } else {
 2219:       $result.=&escape($elem).'&';
 2220:     }
 2221:   }
 2222:   $result=~s/\&$//;
 2223:   $result .= '__END_ARRAY_REF__';
 2224:   return $result;
 2225: }
 2226: 
 2227: sub hash2str {
 2228:   my (%hash) = @_;
 2229:   my $result=&hashref2str(\%hash);
 2230:   $result=~s/^__HASH_REF__//;
 2231:   $result=~s/__END_HASH_REF__$//;
 2232:   return $result;
 2233: }
 2234: 
 2235: sub hashref2str {
 2236:   my ($hashref)=@_;
 2237:   my $result='__HASH_REF__';
 2238:   foreach (sort(keys(%$hashref))) {
 2239:     if (ref($_) eq 'ARRAY') {
 2240:       $result.=&arrayref2str($_).'=';
 2241:     } elsif (ref($_) eq 'HASH') {
 2242:       $result.=&hashref2str($_).'=';
 2243:     } elsif (ref($_)) {
 2244:       $result.='=';
 2245:       #print("Got a ref of ".(ref($_))." skipping.");
 2246:     } else {
 2247: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2248:     }
 2249: 
 2250:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2251:       $result.=&arrayref2str($hashref->{$_}).'&';
 2252:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2253:       $result.=&hashref2str($hashref->{$_}).'&';
 2254:     } elsif(ref($hashref->{$_})) {
 2255:        $result.='&';
 2256:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2257:     } else {
 2258:       $result.=&escape($hashref->{$_}).'&';
 2259:     }
 2260:   }
 2261:   $result=~s/\&$//;
 2262:   $result .= '__END_HASH_REF__';
 2263:   return $result;
 2264: }
 2265: 
 2266: sub str2hash {
 2267:     my ($string)=@_;
 2268:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2269:     return %$hash;
 2270: }
 2271: 
 2272: sub str2hashref {
 2273:   my ($string) = @_;
 2274: 
 2275:   my %hash;
 2276: 
 2277:   if($string !~ /^__HASH_REF__/) {
 2278:       if (! ($string eq '' || !defined($string))) {
 2279: 	  $hash{'error'}='Not hash reference';
 2280:       }
 2281:       return (\%hash, $string);
 2282:   }
 2283: 
 2284:   $string =~ s/^__HASH_REF__//;
 2285: 
 2286:   while($string !~ /^__END_HASH_REF__/) {
 2287:       #key
 2288:       my $key='';
 2289:       if($string =~ /^__HASH_REF__/) {
 2290:           ($key, $string)=&str2hashref($string);
 2291:           if(defined($key->{'error'})) {
 2292:               $hash{'error'}='Bad data';
 2293:               return (\%hash, $string);
 2294:           }
 2295:       } elsif($string =~ /^__ARRAY_REF__/) {
 2296:           ($key, $string)=&str2arrayref($string);
 2297:           if($key->[0] eq 'Array reference error') {
 2298:               $hash{'error'}='Bad data';
 2299:               return (\%hash, $string);
 2300:           }
 2301:       } else {
 2302:           $string =~ s/^(.*?)=//;
 2303: 	  $key=&unescape($1);
 2304:       }
 2305:       $string =~ s/^=//;
 2306: 
 2307:       #value
 2308:       my $value='';
 2309:       if($string =~ /^__HASH_REF__/) {
 2310:           ($value, $string)=&str2hashref($string);
 2311:           if(defined($value->{'error'})) {
 2312:               $hash{'error'}='Bad data';
 2313:               return (\%hash, $string);
 2314:           }
 2315:       } elsif($string =~ /^__ARRAY_REF__/) {
 2316:           ($value, $string)=&str2arrayref($string);
 2317:           if($value->[0] eq 'Array reference error') {
 2318:               $hash{'error'}='Bad data';
 2319:               return (\%hash, $string);
 2320:           }
 2321:       } else {
 2322: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2323:       }
 2324:       $string =~ s/^&//;
 2325: 
 2326:       $hash{$key}=$value;
 2327:   }
 2328: 
 2329:   $string =~ s/^__END_HASH_REF__//;
 2330: 
 2331:   return (\%hash, $string);
 2332: }
 2333: 
 2334: sub str2array {
 2335:     my ($string)=@_;
 2336:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2337:     return @$array;
 2338: }
 2339: 
 2340: sub str2arrayref {
 2341:   my ($string) = @_;
 2342:   my @array;
 2343: 
 2344:   if($string !~ /^__ARRAY_REF__/) {
 2345:       if (! ($string eq '' || !defined($string))) {
 2346: 	  $array[0]='Array reference error';
 2347:       }
 2348:       return (\@array, $string);
 2349:   }
 2350: 
 2351:   $string =~ s/^__ARRAY_REF__//;
 2352: 
 2353:   while($string !~ /^__END_ARRAY_REF__/) {
 2354:       my $value='';
 2355:       if($string =~ /^__HASH_REF__/) {
 2356:           ($value, $string)=&str2hashref($string);
 2357:           if(defined($value->{'error'})) {
 2358:               $array[0] ='Array reference error';
 2359:               return (\@array, $string);
 2360:           }
 2361:       } elsif($string =~ /^__ARRAY_REF__/) {
 2362:           ($value, $string)=&str2arrayref($string);
 2363:           if($value->[0] eq 'Array reference error') {
 2364:               $array[0] ='Array reference error';
 2365:               return (\@array, $string);
 2366:           }
 2367:       } else {
 2368: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2369:       }
 2370:       $string =~ s/^&//;
 2371: 
 2372:       push(@array, $value);
 2373:   }
 2374: 
 2375:   $string =~ s/^__END_ARRAY_REF__//;
 2376: 
 2377:   return (\@array, $string);
 2378: }
 2379: 
 2380: # -------------------------------------------------------------------Temp Store
 2381: 
 2382: sub tmpreset {
 2383:   my ($symb,$namespace,$domain,$stuname) = @_;
 2384:   if (!$symb) {
 2385:     $symb=&symbread();
 2386:     if (!$symb) { $symb= $env{'request.url'}; }
 2387:   }
 2388:   $symb=escape($symb);
 2389: 
 2390:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2391:   $namespace=~s/\//\_/g;
 2392:   $namespace=~s/\W//g;
 2393: 
 2394:   if (!$domain) { $domain=$env{'user.domain'}; }
 2395:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2396:   if ($domain eq 'public' && $stuname eq 'public') {
 2397:       $stuname=$ENV{'REMOTE_ADDR'};
 2398:   }
 2399:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2400:   my %hash;
 2401:   if (tie(%hash,'GDBM_File',
 2402: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2403: 	  &GDBM_WRCREAT(),0640)) {
 2404:     foreach my $key (keys %hash) {
 2405:       if ($key=~ /:$symb/) {
 2406: 	delete($hash{$key});
 2407:       }
 2408:     }
 2409:   }
 2410: }
 2411: 
 2412: sub tmpstore {
 2413:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2414: 
 2415:   if (!$symb) {
 2416:     $symb=&symbread();
 2417:     if (!$symb) { $symb= $env{'request.url'}; }
 2418:   }
 2419:   $symb=escape($symb);
 2420: 
 2421:   if (!$namespace) {
 2422:     # I don't think we would ever want to store this for a course.
 2423:     # it seems this will only be used if we don't have a course.
 2424:     #$namespace=$env{'request.course.id'};
 2425:     #if (!$namespace) {
 2426:       $namespace=$env{'request.state'};
 2427:     #}
 2428:   }
 2429:   $namespace=~s/\//\_/g;
 2430:   $namespace=~s/\W//g;
 2431:   if (!$domain) { $domain=$env{'user.domain'}; }
 2432:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2433:   if ($domain eq 'public' && $stuname eq 'public') {
 2434:       $stuname=$ENV{'REMOTE_ADDR'};
 2435:   }
 2436:   my $now=time;
 2437:   my %hash;
 2438:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2439:   if (tie(%hash,'GDBM_File',
 2440: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2441: 	  &GDBM_WRCREAT(),0640)) {
 2442:     $hash{"version:$symb"}++;
 2443:     my $version=$hash{"version:$symb"};
 2444:     my $allkeys=''; 
 2445:     foreach my $key (keys(%$storehash)) {
 2446:       $allkeys.=$key.':';
 2447:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2448:     }
 2449:     $hash{"$version:$symb:timestamp"}=$now;
 2450:     $allkeys.='timestamp';
 2451:     $hash{"$version:keys:$symb"}=$allkeys;
 2452:     if (untie(%hash)) {
 2453:       return 'ok';
 2454:     } else {
 2455:       return "error:$!";
 2456:     }
 2457:   } else {
 2458:     return "error:$!";
 2459:   }
 2460: }
 2461: 
 2462: # -----------------------------------------------------------------Temp Restore
 2463: 
 2464: sub tmprestore {
 2465:   my ($symb,$namespace,$domain,$stuname) = @_;
 2466: 
 2467:   if (!$symb) {
 2468:     $symb=&symbread();
 2469:     if (!$symb) { $symb= $env{'request.url'}; }
 2470:   }
 2471:   $symb=escape($symb);
 2472: 
 2473:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2474: 
 2475:   if (!$domain) { $domain=$env{'user.domain'}; }
 2476:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2477:   if ($domain eq 'public' && $stuname eq 'public') {
 2478:       $stuname=$ENV{'REMOTE_ADDR'};
 2479:   }
 2480:   my %returnhash;
 2481:   $namespace=~s/\//\_/g;
 2482:   $namespace=~s/\W//g;
 2483:   my %hash;
 2484:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2485:   if (tie(%hash,'GDBM_File',
 2486: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2487: 	  &GDBM_READER(),0640)) {
 2488:     my $version=$hash{"version:$symb"};
 2489:     $returnhash{'version'}=$version;
 2490:     my $scope;
 2491:     for ($scope=1;$scope<=$version;$scope++) {
 2492:       my $vkeys=$hash{"$scope:keys:$symb"};
 2493:       my @keys=split(/:/,$vkeys);
 2494:       my $key;
 2495:       $returnhash{"$scope:keys"}=$vkeys;
 2496:       foreach $key (@keys) {
 2497: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2498: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2499:       }
 2500:     }
 2501:     if (!(untie(%hash))) {
 2502:       return "error:$!";
 2503:     }
 2504:   } else {
 2505:     return "error:$!";
 2506:   }
 2507:   return %returnhash;
 2508: }
 2509: 
 2510: # ----------------------------------------------------------------------- Store
 2511: 
 2512: sub store {
 2513:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2514:     my $home='';
 2515: 
 2516:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2517: 
 2518:     $symb=&symbclean($symb);
 2519:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2520: 
 2521:     if (!$domain) { $domain=$env{'user.domain'}; }
 2522:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2523: 
 2524:     &devalidate($symb,$stuname,$domain);
 2525: 
 2526:     $symb=escape($symb);
 2527:     if (!$namespace) { 
 2528:        unless ($namespace=$env{'request.course.id'}) { 
 2529:           return ''; 
 2530:        } 
 2531:     }
 2532:     if (!$home) { $home=$env{'user.home'}; }
 2533: 
 2534:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2535:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2536: 
 2537:     my $namevalue='';
 2538:     foreach (keys %$storehash) {
 2539:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2540:     }
 2541:     $namevalue=~s/\&$//;
 2542:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2543:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2544: }
 2545: 
 2546: # -------------------------------------------------------------- Critical Store
 2547: 
 2548: sub cstore {
 2549:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2550:     my $home='';
 2551: 
 2552:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2553: 
 2554:     $symb=&symbclean($symb);
 2555:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2556: 
 2557:     if (!$domain) { $domain=$env{'user.domain'}; }
 2558:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2559: 
 2560:     &devalidate($symb,$stuname,$domain);
 2561: 
 2562:     $symb=escape($symb);
 2563:     if (!$namespace) { 
 2564:        unless ($namespace=$env{'request.course.id'}) { 
 2565:           return ''; 
 2566:        } 
 2567:     }
 2568:     if (!$home) { $home=$env{'user.home'}; }
 2569: 
 2570:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2571:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2572: 
 2573:     my $namevalue='';
 2574:     foreach (keys %$storehash) {
 2575:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2576:     }
 2577:     $namevalue=~s/\&$//;
 2578:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2579:     return critical
 2580:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2581: }
 2582: 
 2583: # --------------------------------------------------------------------- Restore
 2584: 
 2585: sub restore {
 2586:     my ($symb,$namespace,$domain,$stuname) = @_;
 2587:     my $home='';
 2588: 
 2589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2590: 
 2591:     if (!$symb) {
 2592:       unless ($symb=escape(&symbread())) { return ''; }
 2593:     } else {
 2594:       $symb=&escape(&symbclean($symb));
 2595:     }
 2596:     if (!$namespace) { 
 2597:        unless ($namespace=$env{'request.course.id'}) { 
 2598:           return ''; 
 2599:        } 
 2600:     }
 2601:     if (!$domain) { $domain=$env{'user.domain'}; }
 2602:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2603:     if (!$home) { $home=$env{'user.home'}; }
 2604:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2605: 
 2606:     my %returnhash=();
 2607:     foreach (split(/\&/,$answer)) {
 2608: 	my ($name,$value)=split(/\=/,$_);
 2609:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2610:     }
 2611:     my $version;
 2612:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2613:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2614:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2615:        }
 2616:     }
 2617:     return %returnhash;
 2618: }
 2619: 
 2620: # ---------------------------------------------------------- Course Description
 2621: 
 2622: sub coursedescription {
 2623:     my ($courseid,$args)=@_;
 2624:     $courseid=~s/^\///;
 2625:     $courseid=~s/\_/\//g;
 2626:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2627:     my $chome=&homeserver($cnum,$cdomain);
 2628:     my $normalid=$cdomain.'_'.$cnum;
 2629:     # need to always cache even if we get errors otherwise we keep 
 2630:     # trying and trying and trying to get the course description.
 2631:     my %envhash=();
 2632:     my %returnhash=();
 2633:     
 2634:     my $expiretime=600;
 2635:     if ($env{'request.course.id'} eq $normalid) {
 2636: 	$expiretime=120;
 2637:     }
 2638: 
 2639:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2640:     if (!$args->{'freshen_cache'}
 2641: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2642: 	foreach my $key (keys(%env)) {
 2643: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2644: 	    my ($setting) = $1;
 2645: 	    $returnhash{$setting} = $env{$key};
 2646: 	}
 2647: 	return %returnhash;
 2648:     }
 2649: 
 2650:     # get the data agin
 2651:     if (!$args->{'one_time'}) {
 2652: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2653:     }
 2654:     if ($chome ne 'no_host') {
 2655:        %returnhash=&dump('environment',$cdomain,$cnum);
 2656:        if (!exists($returnhash{'con_lost'})) {
 2657:            $returnhash{'home'}= $chome;
 2658: 	   $returnhash{'domain'} = $cdomain;
 2659: 	   $returnhash{'num'} = $cnum;
 2660:            if (!defined($returnhash{'type'})) {
 2661:                $returnhash{'type'} = 'Course';
 2662:            }
 2663:            while (my ($name,$value) = each %returnhash) {
 2664:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2665:            }
 2666:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2667:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2668: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2669:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2670:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2671:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2672:        }
 2673:     }
 2674:     if (!$args->{'one_time'}) {
 2675: 	&appenv(%envhash);
 2676:     }
 2677:     return %returnhash;
 2678: }
 2679: 
 2680: # -------------------------------------------------See if a user is privileged
 2681: 
 2682: sub privileged {
 2683:     my ($username,$domain)=@_;
 2684:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2685: 			&homeserver($username,$domain));
 2686:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2687:     my $now=time;
 2688:     if ($rolesdump ne '') {
 2689:         foreach (split(/&/,$rolesdump)) {
 2690: 	    if ($_!~/^rolesdef_/) {
 2691: 		my ($area,$role)=split(/=/,$_);
 2692: 		$area=~s/\_\w\w$//;
 2693: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2694: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2695: 		    my $active=1;
 2696: 		    if ($tend) {
 2697: 			if ($tend<$now) { $active=0; }
 2698: 		    }
 2699: 		    if ($tstart) {
 2700: 			if ($tstart>$now) { $active=0; }
 2701: 		    }
 2702: 		    if ($active) { return 1; }
 2703: 		}
 2704: 	    }
 2705: 	}
 2706:     }
 2707:     return 0;
 2708: }
 2709: 
 2710: # -------------------------------------------------------- Get user privileges
 2711: 
 2712: sub rolesinit {
 2713:     my ($domain,$username,$authhost)=@_;
 2714:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2715:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2716:     my %allroles=();
 2717:     my %allgroups=();   
 2718:     my $now=time;
 2719:     my $userroles="user.login.time=$now\n";
 2720:     my $group_privs;
 2721: 
 2722:     if ($rolesdump ne '') {
 2723:         foreach (split(/&/,$rolesdump)) {
 2724: 	  if ($_!~/^rolesdef_/) {
 2725:             my ($area,$role)=split(/=/,$_);
 2726: 	    $area=~s/\_\w\w$//;
 2727:             my ($trole,$tend,$tstart,$group_privs);
 2728: 	    if ($role=~/^cr/) { 
 2729: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2730: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2731: 		    ($tend,$tstart)=split('_',$trest);
 2732: 		} else {
 2733: 		    $trole=$role;
 2734: 		}
 2735:             } elsif ($role =~ m|^gr/|) {
 2736:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2737:                 ($trole,$group_privs) = split(/\//,$trole);
 2738:                 $group_privs = &unescape($group_privs);
 2739: 	    } else {
 2740: 		($trole,$tend,$tstart)=split(/_/,$role);
 2741: 	    }
 2742:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
 2743:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2744:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2745:             if (($area ne '') && ($trole ne '')) {
 2746: 		my $spec=$trole.'.'.$area;
 2747: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2748: 		if ($trole =~ /^cr\//) {
 2749:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2750:                 } elsif ($trole eq 'gr') {
 2751:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2752: 		} else {
 2753:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2754: 		}
 2755:             }
 2756:           }
 2757:         }
 2758:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles,\%allgroups);
 2759:         $userroles.='user.adv='.$adv."\n".
 2760: 	            'user.author='.$author."\n";
 2761:         $env{'user.adv'}=$adv;
 2762:     }
 2763:     return $userroles;  
 2764: }
 2765: 
 2766: sub set_arearole {
 2767:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2768: # log the associated role with the area
 2769:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2770:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
 2771: }
 2772: 
 2773: sub custom_roleprivs {
 2774:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2775:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2776:     my $homsvr=homeserver($rauthor,$rdomain);
 2777:     if ($hostname{$homsvr} ne '') {
 2778:         my ($rdummy,$roledef)=
 2779:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2780:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2781:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2782:             if (defined($syspriv)) {
 2783:                 $$allroles{'cm./'}.=':'.$syspriv;
 2784:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2785:             }
 2786:             if ($tdomain ne '') {
 2787:                 if (defined($dompriv)) {
 2788:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2789:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2790:                 }
 2791:                 if (($trest ne '') && (defined($coursepriv))) {
 2792:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2793:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2794:                 }
 2795:             }
 2796:         }
 2797:     }
 2798: }
 2799: 
 2800: sub group_roleprivs {
 2801:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2802:     my $access = 1;
 2803:     my $now = time;
 2804:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2805:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2806:     if ($access) {
 2807:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2808:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2809:     }
 2810: }
 2811: 
 2812: sub standard_roleprivs {
 2813:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2814:     if (defined($pr{$trole.':s'})) {
 2815:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2816:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2817:     }
 2818:     if ($tdomain ne '') {
 2819:         if (defined($pr{$trole.':d'})) {
 2820:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2821:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2822:         }
 2823:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2824:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2825:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2826:         }
 2827:     }
 2828: }
 2829: 
 2830: sub set_userprivs {
 2831:     my ($userroles,$allroles,$allgroups) = @_; 
 2832:     my $author=0;
 2833:     my $adv=0;
 2834:     my %grouproles = ();
 2835:     if (keys(%{$allgroups}) > 0) {
 2836:         foreach my $role (keys %{$allroles}) {
 2837:             my ($trole,$area,$sec,$extendedarea);
 2838:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
 2839:                 $trole = $1;
 2840:                 $area = $2;
 2841:                 $sec = $3;
 2842:                 $extendedarea = $area.$sec;
 2843:                 if (exists($$allgroups{$area})) {
 2844:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2845:                         my $spec = $trole.'.'.$extendedarea;
 2846:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2847:                                                 $$allgroups{$area}{$group};
 2848:                     }
 2849:                 }
 2850:             }
 2851:         }
 2852:     }
 2853:     foreach (keys(%grouproles)) {
 2854:         $$allroles{$_} = $grouproles{$_};
 2855:     }
 2856:     foreach (keys %{$allroles}) {
 2857:         my %thesepriv=();
 2858:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2859:         foreach (split(/:/,$$allroles{$_})) {
 2860:             if ($_ ne '') {
 2861:                 my ($privilege,$restrictions)=split(/&/,$_);
 2862:                 if ($restrictions eq '') {
 2863:                     $thesepriv{$privilege}='F';
 2864:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2865:                     $thesepriv{$privilege}.=$restrictions;
 2866:                 }
 2867:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2868:             }
 2869:         }
 2870:         my $thesestr='';
 2871:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2872:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2873:     }
 2874:     return ($author,$adv);
 2875: }
 2876: 
 2877: # --------------------------------------------------------------- get interface
 2878: 
 2879: sub get {
 2880:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2881:    my $items='';
 2882:    foreach (@$storearr) {
 2883:        $items.=escape($_).'&';
 2884:    }
 2885:    $items=~s/\&$//;
 2886:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2887:    if (!$uname) { $uname=$env{'user.name'}; }
 2888:    my $uhome=&homeserver($uname,$udomain);
 2889: 
 2890:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2891:    my @pairs=split(/\&/,$rep);
 2892:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2893:      return @pairs;
 2894:    }
 2895:    my %returnhash=();
 2896:    my $i=0;
 2897:    foreach (@$storearr) {
 2898:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2899:       $i++;
 2900:    }
 2901:    return %returnhash;
 2902: }
 2903: 
 2904: # --------------------------------------------------------------- del interface
 2905: 
 2906: sub del {
 2907:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2908:    my $items='';
 2909:    foreach (@$storearr) {
 2910:        $items.=escape($_).'&';
 2911:    }
 2912:    $items=~s/\&$//;
 2913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2914:    if (!$uname) { $uname=$env{'user.name'}; }
 2915:    my $uhome=&homeserver($uname,$udomain);
 2916: 
 2917:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2918: }
 2919: 
 2920: # -------------------------------------------------------------- dump interface
 2921: 
 2922: sub dump {
 2923:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2924:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2925:    if (!$uname) { $uname=$env{'user.name'}; }
 2926:    my $uhome=&homeserver($uname,$udomain);
 2927:    if ($regexp) {
 2928:        $regexp=&escape($regexp);
 2929:    } else {
 2930:        $regexp='.';
 2931:    }
 2932:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2933:    my @pairs=split(/\&/,$rep);
 2934:    my %returnhash=();
 2935:    foreach (@pairs) {
 2936:       my ($key,$value)=split(/=/,$_,2);
 2937:       $returnhash{unescape($key)}=&thaw_unescape($value);
 2938:    }
 2939:    return %returnhash;
 2940: }
 2941: 
 2942: # --------------------------------------------------------- dumpstore interface
 2943: 
 2944: sub dumpstore {
 2945:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2946:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2947: }
 2948: 
 2949: # -------------------------------------------------------------- keys interface
 2950: 
 2951: sub getkeys {
 2952:    my ($namespace,$udomain,$uname)=@_;
 2953:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2954:    if (!$uname) { $uname=$env{'user.name'}; }
 2955:    my $uhome=&homeserver($uname,$udomain);
 2956:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2957:    my @keyarray=();
 2958:    foreach (split(/\&/,$rep)) {
 2959:       push (@keyarray,&unescape($_));
 2960:    }
 2961:    return @keyarray;
 2962: }
 2963: 
 2964: # --------------------------------------------------------------- currentdump
 2965: sub currentdump {
 2966:    my ($courseid,$sdom,$sname)=@_;
 2967:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2968:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2969:    $sname    = $env{'user.name'}         if (! defined($sname));
 2970:    my $uhome = &homeserver($sname,$sdom);
 2971:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2972:    return if ($rep =~ /^(error:|no_such_host)/);
 2973:    #
 2974:    my %returnhash=();
 2975:    #
 2976:    if ($rep eq "unknown_cmd") { 
 2977:        # an old lond will not know currentdump
 2978:        # Do a dump and make it look like a currentdump
 2979:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2980:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2981:        my %hash = @tmp;
 2982:        @tmp=();
 2983:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2984:    } else {
 2985:        my @pairs=split(/\&/,$rep);
 2986:        foreach (@pairs) {
 2987:            my ($key,$value)=split(/=/,$_);
 2988:            my ($symb,$param) = split(/:/,$key);
 2989:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2990:                                                         &thaw_unescape($value);
 2991:        }
 2992:    }
 2993:    return %returnhash;
 2994: }
 2995: 
 2996: sub convert_dump_to_currentdump{
 2997:     my %hash = %{shift()};
 2998:     my %returnhash;
 2999:     # Code ripped from lond, essentially.  The only difference
 3000:     # here is the unescaping done by lonnet::dump().  Conceivably
 3001:     # we might run in to problems with parameter names =~ /^v\./
 3002:     while (my ($key,$value) = each(%hash)) {
 3003:         my ($v,$symb,$param) = split(/:/,$key);
 3004:         next if ($v eq 'version' || $symb eq 'keys');
 3005:         next if (exists($returnhash{$symb}) &&
 3006:                  exists($returnhash{$symb}->{$param}) &&
 3007:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3008:         $returnhash{$symb}->{$param}=$value;
 3009:         $returnhash{$symb}->{'v.'.$param}=$v;
 3010:     }
 3011:     #
 3012:     # Remove all of the keys in the hashes which keep track of
 3013:     # the version of the parameter.
 3014:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3015:         # use a foreach because we are going to delete from the hash.
 3016:         foreach my $key (keys(%$param_hash)) {
 3017:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3018:         }
 3019:     }
 3020:     return \%returnhash;
 3021: }
 3022: 
 3023: # ------------------------------------------------------ critical inc interface
 3024: 
 3025: sub cinc {
 3026:     return &inc(@_,'critical');
 3027: }
 3028: 
 3029: # --------------------------------------------------------------- inc interface
 3030: 
 3031: sub inc {
 3032:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3033:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3034:     if (!$uname) { $uname=$env{'user.name'}; }
 3035:     my $uhome=&homeserver($uname,$udomain);
 3036:     my $items='';
 3037:     if (! ref($store)) {
 3038:         # got a single value, so use that instead
 3039:         $items = &escape($store).'=&';
 3040:     } elsif (ref($store) eq 'SCALAR') {
 3041:         $items = &escape($$store).'=&';        
 3042:     } elsif (ref($store) eq 'ARRAY') {
 3043:         $items = join('=&',map {&escape($_);} @{$store});
 3044:     } elsif (ref($store) eq 'HASH') {
 3045:         while (my($key,$value) = each(%{$store})) {
 3046:             $items.= &escape($key).'='.&escape($value).'&';
 3047:         }
 3048:     }
 3049:     $items=~s/\&$//;
 3050:     if ($critical) {
 3051: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3052:     } else {
 3053: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3054:     }
 3055: }
 3056: 
 3057: # --------------------------------------------------------------- put interface
 3058: 
 3059: sub put {
 3060:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3062:    if (!$uname) { $uname=$env{'user.name'}; }
 3063:    my $uhome=&homeserver($uname,$udomain);
 3064:    my $items='';
 3065:    foreach (keys %$storehash) {
 3066:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3067:    }
 3068:    $items=~s/\&$//;
 3069:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3070: }
 3071: 
 3072: # ------------------------------------------------------------ newput interface
 3073: 
 3074: sub newput {
 3075:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3076:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3077:    if (!$uname) { $uname=$env{'user.name'}; }
 3078:    my $uhome=&homeserver($uname,$udomain);
 3079:    my $items='';
 3080:    foreach my $key (keys(%$storehash)) {
 3081:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3082:    }
 3083:    $items=~s/\&$//;
 3084:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3085: }
 3086: 
 3087: # ---------------------------------------------------------  putstore interface
 3088: 
 3089: sub putstore {
 3090:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3092:    if (!$uname) { $uname=$env{'user.name'}; }
 3093:    my $uhome=&homeserver($uname,$udomain);
 3094:    my $items='';
 3095:    foreach my $key (keys(%$storehash)) {
 3096:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3097:    }
 3098:    $items=~s/\&$//;
 3099:    my $esc_symb=&escape($symb);
 3100:    my $esc_v=&escape($version);
 3101:    my $reply =
 3102:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3103: 	      $uhome);
 3104:    if ($reply eq 'unknown_cmd') {
 3105:        # gfall back to way things use to be done
 3106:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3107: 			    $uname);
 3108:    }
 3109:    return $reply;
 3110: }
 3111: 
 3112: sub old_putstore {
 3113:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3114:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3115:     if (!$uname) { $uname=$env{'user.name'}; }
 3116:     my $uhome=&homeserver($uname,$udomain);
 3117:     my %newstorehash;
 3118:     foreach (keys %$storehash) {
 3119: 	my $key = $version.':'.&escape($symb).':'.$_;
 3120: 	$newstorehash{$key} = $storehash->{$_};
 3121:     }
 3122:     my $items='';
 3123:     my %allitems = ();
 3124:     foreach (keys %newstorehash) {
 3125: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3126: 	    my $key = $1.':keys:'.$2;
 3127: 	    $allitems{$key} .= $3.':';
 3128: 	}
 3129: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3130:     }
 3131:     foreach (keys %allitems) {
 3132: 	$allitems{$_} =~ s/\:$//;
 3133: 	$items.= $_.'='.$allitems{$_}.'&';
 3134:     }
 3135:     $items=~s/\&$//;
 3136:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3137: }
 3138: 
 3139: # ------------------------------------------------------ critical put interface
 3140: 
 3141: sub cput {
 3142:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3144:    if (!$uname) { $uname=$env{'user.name'}; }
 3145:    my $uhome=&homeserver($uname,$udomain);
 3146:    my $items='';
 3147:    foreach (keys %$storehash) {
 3148:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3149:    }
 3150:    $items=~s/\&$//;
 3151:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3152: }
 3153: 
 3154: # -------------------------------------------------------------- eget interface
 3155: 
 3156: sub eget {
 3157:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3158:    my $items='';
 3159:    foreach (@$storearr) {
 3160:        $items.=escape($_).'&';
 3161:    }
 3162:    $items=~s/\&$//;
 3163:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3164:    if (!$uname) { $uname=$env{'user.name'}; }
 3165:    my $uhome=&homeserver($uname,$udomain);
 3166:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3167:    my @pairs=split(/\&/,$rep);
 3168:    my %returnhash=();
 3169:    my $i=0;
 3170:    foreach (@$storearr) {
 3171:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3172:       $i++;
 3173:    }
 3174:    return %returnhash;
 3175: }
 3176: 
 3177: # ------------------------------------------------------------ tmpput interface
 3178: sub tmpput {
 3179:     my ($storehash,$server)=@_;
 3180:     my $items='';
 3181:     foreach (keys(%$storehash)) {
 3182: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3183:     }
 3184:     $items=~s/\&$//;
 3185:     return &reply("tmpput:$items",$server);
 3186: }
 3187: 
 3188: # ------------------------------------------------------------ tmpget interface
 3189: sub tmpget {
 3190:     my ($token,$server)=@_;
 3191:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3192:     my $rep=&reply("tmpget:$token",$server);
 3193:     my %returnhash;
 3194:     foreach my $item (split(/\&/,$rep)) {
 3195: 	my ($key,$value)=split(/=/,$item);
 3196: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3197:     }
 3198:     return %returnhash;
 3199: }
 3200: 
 3201: # ------------------------------------------------------------ tmpget interface
 3202: sub tmpdel {
 3203:     my ($token,$server)=@_;
 3204:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3205:     return &reply("tmpdel:$token",$server);
 3206: }
 3207: 
 3208: # ---------------------------------------------- Custom access rule evaluation
 3209: 
 3210: sub customaccess {
 3211:     my ($priv,$uri)=@_;
 3212:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3213:     $urealm=~s/^\W//;
 3214:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3215:     my $access=0;
 3216:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3217: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3218:         if ($role) {
 3219: 	   if ($role ne $urole) { next; }
 3220:         }
 3221:         foreach (split(/\s*\,\s*/,$realm)) {
 3222:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3223:             if ($tdom) {
 3224: 		if ($tdom ne $udom) { next; }
 3225:             }
 3226:             if ($tcrs) {
 3227: 		if ($tcrs ne $ucrs) { next; }
 3228:             }
 3229:             if ($tsec) {
 3230: 		if ($tsec ne $usec) { next; }
 3231:             }
 3232:             $access=($effect eq 'allow');
 3233:             last;
 3234:         }
 3235: 	if ($realm eq '' && $role eq '') {
 3236:             $access=($effect eq 'allow');
 3237: 	}
 3238:     }
 3239:     return $access;
 3240: }
 3241: 
 3242: # ------------------------------------------------- Check for a user privilege
 3243: 
 3244: sub allowed {
 3245:     my ($priv,$uri,$symb)=@_;
 3246:     my $ver_orguri=$uri;
 3247:     $uri=&deversion($uri);
 3248:     my $orguri=$uri;
 3249:     $uri=&declutter($uri);
 3250:     
 3251:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3252: # Free bre access to adm and meta resources
 3253:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 3254: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 3255: 	return 'F';
 3256:     }
 3257: 
 3258: # Free bre access to user's own portfolio contents
 3259:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3260:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3261: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3262:         return 'F';
 3263:     }
 3264: 
 3265: # bre access to group if user has rgf priv for this group and course.
 3266:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3267:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3268:         if (exists($env{'request.course.id'})) {
 3269:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3270:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3271:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3272:                 my $courseprivid=$env{'request.course.id'};
 3273:                 $courseprivid=~s/\_/\//;
 3274:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3275:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3276:                     return $1; 
 3277:                 }
 3278:             }
 3279:         }
 3280:     }
 3281: 
 3282: # Free bre to public access
 3283: 
 3284:     if ($priv eq 'bre') {
 3285:         my $copyright=&metadata($uri,'copyright');
 3286: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3287:            return 'F'; 
 3288:         }
 3289:         if ($copyright eq 'priv') {
 3290:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3291: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3292: 		return '';
 3293:             }
 3294:         }
 3295:         if ($copyright eq 'domain') {
 3296:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3297: 	    unless (($env{'user.domain'} eq $1) ||
 3298:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3299: 		return '';
 3300:             }
 3301:         }
 3302:         if ($env{'request.role'}=~ /li\.\//) {
 3303:             # Library role, so allow browsing of resources in this domain.
 3304:             return 'F';
 3305:         }
 3306:         if ($copyright eq 'custom') {
 3307: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3308:         }
 3309:     }
 3310:     # Domain coordinator is trying to create a course
 3311:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3312:         # uri is the requested domain in this case.
 3313:         # comparison to 'request.role.domain' shows if the user has selected
 3314:         # a role of dc for the domain in question.
 3315:         return 'F' if ($uri eq $env{'request.role.domain'});
 3316:     }
 3317: 
 3318:     my $thisallowed='';
 3319:     my $statecond=0;
 3320:     my $courseprivid='';
 3321: 
 3322: # Course
 3323: 
 3324:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3325:        $thisallowed.=$1;
 3326:     }
 3327: 
 3328: # Domain
 3329: 
 3330:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3331:        =~/\Q$priv\E\&([^\:]*)/) {
 3332:        $thisallowed.=$1;
 3333:     }
 3334: 
 3335: # Course: uri itself is a course
 3336:     my $courseuri=$uri;
 3337:     $courseuri=~s/\_(\d)/\/$1/;
 3338:     $courseuri=~s/^([^\/])/\/$1/;
 3339: 
 3340:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3341:        =~/\Q$priv\E\&([^\:]*)/) {
 3342:        $thisallowed.=$1;
 3343:     }
 3344: 
 3345: # Group: uri itself is a group
 3346:     my $groupuri=$uri;
 3347:     $groupuri=~s/^([^\/])/\/$1/;
 3348:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
 3349:        =~/\Q$priv\E\&([^\:]*)/) {
 3350:        $thisallowed.=$1;
 3351:     }
 3352: 
 3353: # URI is an uploaded document for this course, default permissions don't matter
 3354: # not allowing 'edit' access (editupload) to uploaded course docs
 3355:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3356: 	$thisallowed='';
 3357:         my ($match)=&is_on_map($uri);
 3358:         if ($match) {
 3359:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3360:                   =~/\Q$priv\E\&([^\:]*)/) {
 3361:                 $thisallowed.=$1;
 3362:             }
 3363:         } else {
 3364:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3365:             if ($refuri) {
 3366:                 if ($refuri =~ m|^/adm/|) {
 3367:                     $thisallowed='F';
 3368:                 } else {
 3369:                     $refuri=&declutter($refuri);
 3370:                     my ($match) = &is_on_map($refuri);
 3371:                     if ($match) {
 3372:                         $thisallowed='F';
 3373:                     }
 3374:                 }
 3375:             }
 3376:         }
 3377:     }
 3378: 
 3379: # Full access at system, domain or course-wide level? Exit.
 3380: 
 3381:     if ($thisallowed=~/F/) {
 3382: 	return 'F';
 3383:     }
 3384: 
 3385: # If this is generating or modifying users, exit with special codes
 3386: 
 3387:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3388: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3389: 	    my ($audom,$auname)=split('/',$uri);
 3390: # no author name given, so this just checks on the general right to make a co-author in this domain
 3391: 	    unless ($auname) { return $thisallowed; }
 3392: # an author name is given, so we are about to actually make a co-author for a certain account
 3393: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3394: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3395: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3396: 	}
 3397: 	return $thisallowed;
 3398:     }
 3399: #
 3400: # Gathered so far: system, domain and course wide privileges
 3401: #
 3402: # Course: See if uri or referer is an individual resource that is part of 
 3403: # the course
 3404: 
 3405:     if ($env{'request.course.id'}) {
 3406: 
 3407:        $courseprivid=$env{'request.course.id'};
 3408:        if ($env{'request.course.sec'}) {
 3409:           $courseprivid.='/'.$env{'request.course.sec'};
 3410:        }
 3411:        $courseprivid=~s/\_/\//;
 3412:        my $checkreferer=1;
 3413:        my ($match,$cond)=&is_on_map($uri);
 3414:        if ($match) {
 3415:            $statecond=$cond;
 3416:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3417:                =~/\Q$priv\E\&([^\:]*)/) {
 3418:                $thisallowed.=$1;
 3419:                $checkreferer=0;
 3420:            }
 3421:        }
 3422:        
 3423:        if ($checkreferer) {
 3424: 	  my $refuri=$env{'httpref.'.$orguri};
 3425:             unless ($refuri) {
 3426:                 foreach (keys %env) {
 3427: 		    if ($_=~/^httpref\..*\*/) {
 3428: 			my $pattern=$_;
 3429:                         $pattern=~s/^httpref\.\/res\///;
 3430:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3431:                         $pattern=~s/\//\\\//g;
 3432:                         if ($orguri=~/$pattern/) {
 3433: 			    $refuri=$env{$_};
 3434:                         }
 3435:                     }
 3436:                 }
 3437:             }
 3438: 
 3439:          if ($refuri) { 
 3440: 	  $refuri=&declutter($refuri);
 3441:           my ($match,$cond)=&is_on_map($refuri);
 3442:             if ($match) {
 3443:               my $refstatecond=$cond;
 3444:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3445:                   =~/\Q$priv\E\&([^\:]*)/) {
 3446:                   $thisallowed.=$1;
 3447:                   $uri=$refuri;
 3448:                   $statecond=$refstatecond;
 3449:               }
 3450:           }
 3451:         }
 3452:        }
 3453:    }
 3454: 
 3455: #
 3456: # Gathered now: all privileges that could apply, and condition number
 3457: # 
 3458: #
 3459: # Full or no access?
 3460: #
 3461: 
 3462:     if ($thisallowed=~/F/) {
 3463: 	return 'F';
 3464:     }
 3465: 
 3466:     unless ($thisallowed) {
 3467:         return '';
 3468:     }
 3469: 
 3470: # Restrictions exist, deal with them
 3471: #
 3472: #   C:according to course preferences
 3473: #   R:according to resource settings
 3474: #   L:unless locked
 3475: #   X:according to user session state
 3476: #
 3477: 
 3478: # Possibly locked functionality, check all courses
 3479: # Locks might take effect only after 10 minutes cache expiration for other
 3480: # courses, and 2 minutes for current course
 3481: 
 3482:     my $envkey;
 3483:     if ($thisallowed=~/L/) {
 3484:         foreach $envkey (keys %env) {
 3485:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3486:                my $courseid=$2;
 3487:                my $roleid=$1.'.'.$2;
 3488:                $courseid=~s/^\///;
 3489:                my $expiretime=600;
 3490:                if ($env{'request.role'} eq $roleid) {
 3491: 		  $expiretime=120;
 3492:                }
 3493: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3494:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3495:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3496: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3497:                }
 3498:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3499:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3500: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3501:                        &log($env{'user.domain'},$env{'user.name'},
 3502:                             $env{'user.home'},
 3503:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3504:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3505:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3506: 		       return '';
 3507:                    }
 3508:                }
 3509:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3510:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3511: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3512:                        &log($env{'user.domain'},$env{'user.name'},
 3513:                             $env{'user.home'},
 3514:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3515:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3516:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3517: 		       return '';
 3518:                    }
 3519:                }
 3520: 	   }
 3521:        }
 3522:     }
 3523:    
 3524: #
 3525: # Rest of the restrictions depend on selected course
 3526: #
 3527: 
 3528:     unless ($env{'request.course.id'}) {
 3529:        return '1';
 3530:     }
 3531: 
 3532: #
 3533: # Now user is definitely in a course
 3534: #
 3535: 
 3536: 
 3537: # Course preferences
 3538: 
 3539:    if ($thisallowed=~/C/) {
 3540:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3541:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3542:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3543: 	   =~/\Q$rolecode\E/) {
 3544: 	   if ($priv ne 'pch') { 
 3545: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3546: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3547: 			$env{'request.course.id'});
 3548: 	   }
 3549:            return '';
 3550:        }
 3551: 
 3552:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3553: 	   =~/\Q$unamedom\E/) {
 3554: 	   if ($priv ne 'pch') { 
 3555: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3556: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3557: 			$env{'request.course.id'});
 3558: 	   }
 3559:            return '';
 3560:        }
 3561:    }
 3562: 
 3563: # Resource preferences
 3564: 
 3565:    if ($thisallowed=~/R/) {
 3566:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3567:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3568: 	   if ($priv ne 'pch') { 
 3569: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3570: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3571: 	   }
 3572: 	   return '';
 3573:        }
 3574:    }
 3575: 
 3576: # Restricted by state or randomout?
 3577: 
 3578:    if ($thisallowed=~/X/) {
 3579:       if ($env{'acc.randomout'}) {
 3580: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3581:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3582:             return ''; 
 3583:          }
 3584:       }
 3585:       if (&condval($statecond)) {
 3586: 	 return '2';
 3587:       } else {
 3588:          return '';
 3589:       }
 3590:    }
 3591: 
 3592:    return 'F';
 3593: }
 3594: 
 3595: sub split_uri_for_cond {
 3596:     my $uri=&deversion(&declutter(shift));
 3597:     my @uriparts=split(/\//,$uri);
 3598:     my $filename=pop(@uriparts);
 3599:     my $pathname=join('/',@uriparts);
 3600:     return ($pathname,$filename);
 3601: }
 3602: # --------------------------------------------------- Is a resource on the map?
 3603: 
 3604: sub is_on_map {
 3605:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3606:     #Trying to find the conditional for the file
 3607:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3608: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3609:     if ($match) {
 3610: 	return (1,$1);
 3611:     } else {
 3612: 	return (0,0);
 3613:     }
 3614: }
 3615: 
 3616: # --------------------------------------------------------- Get symb from alias
 3617: 
 3618: sub get_symb_from_alias {
 3619:     my $symb=shift;
 3620:     my ($map,$resid,$url)=&decode_symb($symb);
 3621: # Already is a symb
 3622:     if ($url) { return $symb; }
 3623: # Must be an alias
 3624:     my $aliassymb='';
 3625:     my %bighash;
 3626:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3627:                             &GDBM_READER(),0640)) {
 3628:         my $rid=$bighash{'mapalias_'.$symb};
 3629: 	if ($rid) {
 3630: 	    my ($mapid,$resid)=split(/\./,$rid);
 3631: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3632: 				    $resid,$bighash{'src_'.$rid});
 3633: 	}
 3634:         untie %bighash;
 3635:     }
 3636:     return $aliassymb;
 3637: }
 3638: 
 3639: # ----------------------------------------------------------------- Define Role
 3640: 
 3641: sub definerole {
 3642:   if (allowed('mcr','/')) {
 3643:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3644:     foreach (split(':',$sysrole)) {
 3645: 	my ($crole,$cqual)=split(/\&/,$_);
 3646:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3647:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3648: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3649:                return "refused:s:$crole&$cqual"; 
 3650:             }
 3651:         }
 3652:     }
 3653:     foreach (split(':',$domrole)) {
 3654: 	my ($crole,$cqual)=split(/\&/,$_);
 3655:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3656:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3657: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3658:                return "refused:d:$crole&$cqual"; 
 3659:             }
 3660:         }
 3661:     }
 3662:     foreach (split(':',$courole)) {
 3663: 	my ($crole,$cqual)=split(/\&/,$_);
 3664:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3665:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3666: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3667:                return "refused:c:$crole&$cqual"; 
 3668:             }
 3669:         }
 3670:     }
 3671:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3672:                 "$env{'user.domain'}:$env{'user.name'}:".
 3673: 	        "rolesdef_$rolename=".
 3674:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3675:     return reply($command,$env{'user.home'});
 3676:   } else {
 3677:     return 'refused';
 3678:   }
 3679: }
 3680: 
 3681: # ---------------- Make a metadata query against the network of library servers
 3682: 
 3683: sub metadata_query {
 3684:     my ($query,$custom,$customshow,$server_array)=@_;
 3685:     my %rhash;
 3686:     my @server_list = (defined($server_array) ? @$server_array
 3687:                                               : keys(%libserv) );
 3688:     for my $server (@server_list) {
 3689: 	unless ($custom or $customshow) {
 3690: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3691: 	    $rhash{$server}=$reply;
 3692: 	}
 3693: 	else {
 3694: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3695: 			     &escape($custom).':'.&escape($customshow),
 3696: 			     $server);
 3697: 	    $rhash{$server}=$reply;
 3698: 	}
 3699:     }
 3700:     return \%rhash;
 3701: }
 3702: 
 3703: # ----------------------------------------- Send log queries and wait for reply
 3704: 
 3705: sub log_query {
 3706:     my ($uname,$udom,$query,%filters)=@_;
 3707:     my $uhome=&homeserver($uname,$udom);
 3708:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3709:     my $uhost=$hostname{$uhome};
 3710:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3711:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3712:                        $uhome);
 3713:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3714:     return get_query_reply($queryid);
 3715: }
 3716: 
 3717: # ------- Request retrieval of institutional classlists for course(s)
 3718: 
 3719: sub fetch_enrollment_query {
 3720:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3721:     my $homeserver;
 3722:     my $maxtries = 1;
 3723:     if ($context eq 'automated') {
 3724:         $homeserver = $perlvar{'lonHostID'};
 3725:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3726:     } else {
 3727:         $homeserver = &homeserver($cnum,$dom);
 3728:     }
 3729:     my $host=$hostname{$homeserver};
 3730:     my $cmd = '';
 3731:     foreach (keys %{$affiliatesref}) {
 3732:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3733:     }
 3734:     $cmd =~ s/%%$//;
 3735:     $cmd = &escape($cmd);
 3736:     my $query = 'fetchenrollment';
 3737:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3738:     unless ($queryid=~/^\Q$host\E\_/) { 
 3739:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3740:         return 'error: '.$queryid;
 3741:     }
 3742:     my $reply = &get_query_reply($queryid);
 3743:     my $tries = 1;
 3744:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3745:         $reply = &get_query_reply($queryid);
 3746:         $tries ++;
 3747:     }
 3748:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3749:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3750:     } else {
 3751:         my @responses = split/:/,$reply;
 3752:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3753:             foreach (@responses) {
 3754:                 my ($key,$value) = split/=/,$_;
 3755:                 $$replyref{$key} = $value;
 3756:             }
 3757:         } else {
 3758:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3759:             foreach (@responses) {
 3760:                 my ($key,$value) = split/=/,$_;
 3761:                 $$replyref{$key} = $value;
 3762:                 if ($value > 0) {
 3763:                     foreach (@{$$affiliatesref{$key}}) {
 3764:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3765:                         my $destname = $pathname.'/'.$filename;
 3766:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3767:                         if ($xml_classlist =~ /^error/) {
 3768:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3769:                         } else {
 3770:                             if ( open(FILE,">$destname") ) {
 3771:                                 print FILE &unescape($xml_classlist);
 3772:                                 close(FILE);
 3773:                             } else {
 3774:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3775:                             }
 3776:                         }
 3777:                     }
 3778:                 }
 3779:             }
 3780:         }
 3781:         return 'ok';
 3782:     }
 3783:     return 'error';
 3784: }
 3785: 
 3786: sub get_query_reply {
 3787:     my $queryid=shift;
 3788:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3789:     my $reply='';
 3790:     for (1..100) {
 3791: 	sleep 2;
 3792:         if (-e $replyfile.'.end') {
 3793: 	    if (open(my $fh,$replyfile)) {
 3794:                $reply.=<$fh>;
 3795:                close($fh);
 3796: 	   } else { return 'error: reply_file_error'; }
 3797:            return &unescape($reply);
 3798: 	}
 3799:     }
 3800:     return 'timeout:'.$queryid;
 3801: }
 3802: 
 3803: sub courselog_query {
 3804: #
 3805: # possible filters:
 3806: # url: url or symb
 3807: # username
 3808: # domain
 3809: # action: view, submit, grade
 3810: # start: timestamp
 3811: # end: timestamp
 3812: #
 3813:     my (%filters)=@_;
 3814:     unless ($env{'request.course.id'}) { return 'no_course'; }
 3815:     if ($filters{'url'}) {
 3816: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3817:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3818:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3819:     }
 3820:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3821:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3822:     return &log_query($cname,$cdom,'courselog',%filters);
 3823: }
 3824: 
 3825: sub userlog_query {
 3826:     my ($uname,$udom,%filters)=@_;
 3827:     return &log_query($uname,$udom,'userlog',%filters);
 3828: }
 3829: 
 3830: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3831: 
 3832: sub auto_run {
 3833:     my ($cnum,$cdom) = @_;
 3834:     my $homeserver = &homeserver($cnum,$cdom);
 3835:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3836:     return $response;
 3837: }
 3838:                                                                                    
 3839: sub auto_get_sections {
 3840:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3841:     my $homeserver = &homeserver($cnum,$cdom);
 3842:     my @secs = ();
 3843:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3844:     unless ($response eq 'refused') {
 3845:         @secs = split/:/,$response;
 3846:     }
 3847:     return @secs;
 3848: }
 3849:                                                                                    
 3850: sub auto_new_course {
 3851:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3852:     my $homeserver = &homeserver($cnum,$cdom);
 3853:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3854:     return $response;
 3855: }
 3856:                                                                                    
 3857: sub auto_validate_courseID {
 3858:     my ($cnum,$cdom,$inst_course_id) = @_;
 3859:     my $homeserver = &homeserver($cnum,$cdom);
 3860:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3861:     return $response;
 3862: }
 3863:                                                                                    
 3864: sub auto_create_password {
 3865:     my ($cnum,$cdom,$authparam) = @_;
 3866:     my $homeserver = &homeserver($cnum,$cdom); 
 3867:     my $create_passwd = 0;
 3868:     my $authchk = '';
 3869:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3870:     if ($response eq 'refused') {
 3871:         $authchk = 'refused';
 3872:     } else {
 3873:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3874:     }
 3875:     return ($authparam,$create_passwd,$authchk);
 3876: }
 3877: 
 3878: sub auto_photo_permission {
 3879:     my ($cnum,$cdom,$students) = @_;
 3880:     my $homeserver = &homeserver($cnum,$cdom);
 3881:     my ($outcome,$perm_reqd,$conditions) = 
 3882: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 3883:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3884: 	return (undef,undef);
 3885:     }
 3886:     return ($outcome,$perm_reqd,$conditions);
 3887: }
 3888: 
 3889: sub auto_checkphotos {
 3890:     my ($uname,$udom,$pid) = @_;
 3891:     my $homeserver = &homeserver($uname,$udom);
 3892:     my ($result,$resulttype);
 3893:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 3894: 				   &escape($uname).':'.&escape($pid),
 3895: 				   $homeserver));
 3896:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3897: 	return (undef,undef);
 3898:     }
 3899:     if ($outcome) {
 3900:         ($result,$resulttype) = split(/:/,$outcome);
 3901:     } 
 3902:     return ($result,$resulttype);
 3903: }
 3904: 
 3905: sub auto_photochoice {
 3906:     my ($cnum,$cdom) = @_;
 3907:     my $homeserver = &homeserver($cnum,$cdom);
 3908:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 3909: 						       &escape($cdom),
 3910: 						       $homeserver)));
 3911:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3912: 	return (undef,undef);
 3913:     }
 3914:     return ($update,$comment);
 3915: }
 3916: 
 3917: sub auto_photoupdate {
 3918:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 3919:     my $homeserver = &homeserver($cnum,$dom);
 3920:     my $host=$hostname{$homeserver};
 3921:     my $cmd = '';
 3922:     my $maxtries = 1;
 3923:     foreach (keys %{$affiliatesref}) {
 3924:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3925:     }
 3926:     $cmd =~ s/%%$//;
 3927:     $cmd = &escape($cmd);
 3928:     my $query = 'institutionalphotos';
 3929:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 3930:     unless ($queryid=~/^\Q$host\E\_/) {
 3931:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 3932:         return 'error: '.$queryid;
 3933:     }
 3934:     my $reply = &get_query_reply($queryid);
 3935:     my $tries = 1;
 3936:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3937:         $reply = &get_query_reply($queryid);
 3938:         $tries ++;
 3939:     }
 3940:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3941:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3942:     } else {
 3943:         my @responses = split(/:/,$reply);
 3944:         my $outcome = shift(@responses); 
 3945:         foreach my $item (@responses) {
 3946:             my ($key,$value) = split(/=/,$item);
 3947:             $$photo{$key} = $value;
 3948:         }
 3949:         return $outcome;
 3950:     }
 3951:     return 'error';
 3952: }
 3953: 
 3954: sub auto_instcode_format {
 3955:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3956:     my $courses = '';
 3957:     my $homeserver;
 3958:     if ($caller eq 'global') {
 3959:         foreach my $tryserver (keys %libserv) {
 3960:             if ($hostdom{$tryserver} eq $codedom) {
 3961:                 $homeserver = $tryserver;
 3962:                 last;
 3963:             }
 3964:         }
 3965:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
 3966:             $homeserver = &homeserver($env{'user.name'},$codedom);
 3967:         }
 3968:     } else {
 3969:         $homeserver = &homeserver($caller,$codedom);
 3970:     }
 3971:     foreach (keys %{$instcodes}) {
 3972:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3973:     }
 3974:     chop($courses);
 3975:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3976:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3977:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3978:         %{$codes} = &str2hash($codes_str);
 3979:         @{$codetitles} = &str2array($codetitles_str);
 3980:         %{$cat_titles} = &str2hash($cat_titles_str);
 3981:         %{$cat_order} = &str2hash($cat_order_str);
 3982:         return 'ok';
 3983:     }
 3984:     return $response;
 3985: }
 3986: 
 3987: # ------------------------------------------------------- Course Group routines
 3988: 
 3989: sub get_coursegroups {
 3990:     my ($cdom,$cnum,$group) = @_;
 3991:     return(&dump('coursegroups',$cdom,$cnum,$group));
 3992: }
 3993: 
 3994: sub modify_coursegroup {
 3995:     my ($cdom,$cnum,$groupsettings) = @_;
 3996:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 3997: }
 3998: 
 3999: sub modify_group_roles {
 4000:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4001:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4002:     my $role = 'gr/'.&escape($userprivs);
 4003:     my ($uname,$udom) = split(/:/,$user);
 4004:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4005:     if ($result eq 'ok') {
 4006:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4007:     }
 4008:     return $result;
 4009: }
 4010: 
 4011: sub modify_coursegroup_membership {
 4012:     my ($cdom,$cnum,$membership) = @_;
 4013:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4014:     return $result;
 4015: }
 4016: 
 4017: sub get_active_groups {
 4018:     my ($udom,$uname,$cdom,$cnum) = @_;
 4019:     my $now = time;
 4020:     my %groups = ();
 4021:     foreach my $key (keys(%env)) {
 4022:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4023:             my ($start,$end) = split(/\./,$env{$key});
 4024:             if (($end!=0) && ($end<$now)) { next; }
 4025:             if (($start!=0) && ($start>$now)) { next; }
 4026:             if ($1 eq $cdom && $2 eq $cnum) {
 4027:                 $groups{$3} = $env{$key} ;
 4028:             }
 4029:         }
 4030:     }
 4031:     return %groups;
 4032: }
 4033: 
 4034: sub get_group_membership {
 4035:     my ($cdom,$cnum,$group) = @_;
 4036:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4037: }
 4038: 
 4039: sub get_users_groups {
 4040:     my ($udom,$uname,$courseid) = @_;
 4041:     my @usersgroups;
 4042:     my $cachetime=1800;
 4043:     $courseid=~s/\_/\//g;
 4044:     $courseid=~s/^(\w)/\/$1/;
 4045: 
 4046:     my $hashid="$udom:$uname:$courseid";
 4047:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4048:     if (defined($cached)) {
 4049:         @usersgroups = split(/:/,$grouplist);
 4050:     } else {  
 4051:         $grouplist = '';
 4052:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4053:         my ($tmp) = keys(%roleshash);
 4054:         if ($tmp=~/^error:/) {
 4055:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4056:         } else {
 4057:             my $access_end = $env{'course.'.$courseid.
 4058:                                   '.default_enrollment_end_date'};
 4059:             my $now = time;
 4060:             foreach my $key (keys(%roleshash)) {
 4061:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4062:                     my $group = $1;
 4063:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4064:                         my $start = $2;
 4065:                         my $end = $1;
 4066:                         if ($start == -1) { next; } # deleted from group
 4067:                         if (($start!=0) && ($start>$now)) { next; }
 4068:                         if (($end!=0) && ($end<$now)) {
 4069:                             if ($access_end && $access_end < $now) {
 4070:                                 if ($access_end - $end < 86400) {
 4071:                                     push(@usersgroups,$group);
 4072:                                 }
 4073:                             }
 4074:                             next;
 4075:                         }
 4076:                         push(@usersgroups,$group);
 4077:                     }
 4078:                 }
 4079:             }
 4080:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4081:             $grouplist = join(':',@usersgroups);
 4082:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4083:         }
 4084:     }
 4085:     return @usersgroups;
 4086: }
 4087: 
 4088: sub devalidate_getgroups_cache {
 4089:     my ($udom,$uname,$cdom,$cnum)=@_;
 4090:     my $courseid = $cdom.'_'.$cnum;
 4091:     $courseid=~s/\_/\//g;
 4092:     $courseid=~s/^(\w)/\/$1/;
 4093:     my $hashid="$udom:$uname:$courseid";
 4094:     &devalidate_cache_new('getgroups',$hashid);
 4095: }
 4096: 
 4097: # ------------------------------------------------------------------ Plain Text
 4098: 
 4099: sub plaintext {
 4100:     my ($short,$type,$cid) = @_;
 4101:     if (!defined($cid)) {
 4102:         $cid = $env{'request.course.id'};
 4103:     }
 4104:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4105:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4106:                                           '.plaintext'});
 4107:     }
 4108:     my %rolenames = (
 4109:                       Course => 'std',
 4110:                       Group => 'alt1',
 4111:                     );
 4112:     if (defined($type) && 
 4113:          defined($rolenames{$type}) && 
 4114:          defined($prp{$short}{$rolenames{$type}})) {
 4115:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4116:     } else {
 4117:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4118:     }
 4119: }
 4120: 
 4121: # ----------------------------------------------------------------- Assign Role
 4122: 
 4123: sub assignrole {
 4124:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4125:     my $mrole;
 4126:     if ($role =~ /^cr\//) {
 4127:         my $cwosec=$url;
 4128:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4129: 	unless (&allowed('ccr',$cwosec)) {
 4130:            &logthis('Refused custom assignrole: '.
 4131:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4132: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4133:            return 'refused'; 
 4134:         }
 4135:         $mrole='cr';
 4136:     } elsif ($role =~ /^gr\//) {
 4137:         my $cwogrp=$url;
 4138:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4139:         unless (&allowed('mdg',$cwogrp)) {
 4140:             &logthis('Refused group assignrole: '.
 4141:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4142:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4143:             return 'refused';
 4144:         }
 4145:         $mrole='gr';
 4146:     } else {
 4147:         my $cwosec=$url;
 4148:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4149:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4150:            &logthis('Refused assignrole: '.
 4151:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4152: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4153:            return 'refused'; 
 4154:         }
 4155:         $mrole=$role;
 4156:     }
 4157:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4158:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4159:     if ($end) { $command.='_'.$end; }
 4160:     if ($start) {
 4161: 	if ($end) { 
 4162:            $command.='_'.$start; 
 4163:         } else {
 4164:            $command.='_0_'.$start;
 4165:         }
 4166:     }
 4167:     my $origstart = $start;
 4168:     my $origend = $end;
 4169: # actually delete
 4170:     if ($deleteflag) {
 4171: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4172: # modify command to delete the role
 4173:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4174:                 "$udom:$uname:$url".'_'."$mrole";
 4175: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4176: # set start and finish to negative values for userrolelog
 4177:            $start=-1;
 4178:            $end=-1;
 4179:         }
 4180:     }
 4181: # send command
 4182:     my $answer=&reply($command,&homeserver($uname,$udom));
 4183: # log new user role if status is ok
 4184:     if ($answer eq 'ok') {
 4185: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4186: # for course roles, perform group memberships changes triggered by role change.
 4187:         unless ($role =~ /^gr/) {
 4188:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4189:                                              $origstart);
 4190:         }
 4191:     }
 4192:     return $answer;
 4193: }
 4194: 
 4195: # -------------------------------------------------- Modify user authentication
 4196: # Overrides without validation
 4197: 
 4198: sub modifyuserauth {
 4199:     my ($udom,$uname,$umode,$upass)=@_;
 4200:     my $uhome=&homeserver($uname,$udom);
 4201:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4202:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4203:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4204:              ' in domain '.$env{'request.role.domain'});  
 4205:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4206: 		     &escape($upass),$uhome);
 4207:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4208:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4209:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4210:     &log($udom,,$uname,$uhome,
 4211:         'Authentication changed by '.$env{'user.domain'}.', '.
 4212:                                      $env{'user.name'}.', '.$umode.
 4213:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4214:     unless ($reply eq 'ok') {
 4215:         &logthis('Authentication mode error: '.$reply);
 4216: 	return 'error: '.$reply;
 4217:     }   
 4218:     return 'ok';
 4219: }
 4220: 
 4221: # --------------------------------------------------------------- Modify a user
 4222: 
 4223: sub modifyuser {
 4224:     my ($udom,    $uname, $uid,
 4225:         $umode,   $upass, $first,
 4226:         $middle,  $last,  $gene,
 4227:         $forceid, $desiredhome, $email)=@_;
 4228:     $udom=~s/\W//g;
 4229:     $uname=~s/\W//g;
 4230:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4231:              $umode.', '.$first.', '.$middle.', '.
 4232: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4233:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4234:                                      ' desiredhome not specified'). 
 4235:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4236:              ' in domain '.$env{'request.role.domain'});
 4237:     my $uhome=&homeserver($uname,$udom,'true');
 4238: # ----------------------------------------------------------------- Create User
 4239:     if (($uhome eq 'no_host') && 
 4240: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4241:         my $unhome='';
 4242:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4243:             $unhome = $desiredhome;
 4244: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4245: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4246:         } else { # load balancing routine for determining $unhome
 4247:             my $tryserver;
 4248:             my $loadm=10000000;
 4249:             foreach $tryserver (keys %libserv) {
 4250: 	       if ($hostdom{$tryserver} eq $udom) {
 4251:                   my $answer=reply('load',$tryserver);
 4252:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4253: 		      $loadm=$answer;
 4254:                       $unhome=$tryserver;
 4255:                   }
 4256: 	       }
 4257: 	    }
 4258:         }
 4259:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4260: 	    return 'error: unable to find a home server for '.$uname.
 4261:                    ' in domain '.$udom;
 4262:         }
 4263:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4264:                          &escape($upass),$unhome);
 4265: 	unless ($reply eq 'ok') {
 4266:             return 'error: '.$reply;
 4267:         }   
 4268:         $uhome=&homeserver($uname,$udom,'true');
 4269:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4270: 	    return 'error: unable verify users home machine.';
 4271:         }
 4272:     }   # End of creation of new user
 4273: # ---------------------------------------------------------------------- Add ID
 4274:     if ($uid) {
 4275:        $uid=~tr/A-Z/a-z/;
 4276:        my %uidhash=&idrget($udom,$uname);
 4277:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4278:          && (!$forceid)) {
 4279: 	  unless ($uid eq $uidhash{$uname}) {
 4280: 	      return 'error: user id "'.$uid.'" does not match '.
 4281:                   'current user id "'.$uidhash{$uname}.'".';
 4282:           }
 4283:        } else {
 4284: 	  &idput($udom,($uname => $uid));
 4285:        }
 4286:     }
 4287: # -------------------------------------------------------------- Add names, etc
 4288:     my @tmp=&get('environment',
 4289: 		   ['firstname','middlename','lastname','generation'],
 4290: 		   $udom,$uname);
 4291:     my %names;
 4292:     if ($tmp[0] =~ m/^error:.*/) { 
 4293:         %names=(); 
 4294:     } else {
 4295:         %names = @tmp;
 4296:     }
 4297: #
 4298: # Make sure to not trash student environment if instructor does not bother
 4299: # to supply name and email information
 4300: #
 4301:     if ($first)  { $names{'firstname'}  = $first; }
 4302:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4303:     if ($last)   { $names{'lastname'}   = $last; }
 4304:     if (defined($gene))   { $names{'generation'} = $gene; }
 4305:     if ($email) {
 4306:        $email=~s/[^\w\@\.\-\,]//gs;
 4307:        if ($email=~/\@/) { $names{'notification'} = $email;
 4308: 			   $names{'critnotification'} = $email;
 4309: 			   $names{'permanentemail'} = $email; }
 4310:     }
 4311:     my $reply = &put('environment', \%names, $udom,$uname);
 4312:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4313:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4314:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4315:              $umode.', '.$first.', '.$middle.', '.
 4316: 	     $last.', '.$gene.' by '.
 4317:              $env{'user.name'}.' at '.$env{'user.domain'});
 4318:     return 'ok';
 4319: }
 4320: 
 4321: # -------------------------------------------------------------- Modify student
 4322: 
 4323: sub modifystudent {
 4324:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4325:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4326:     if (!$cid) {
 4327: 	unless ($cid=$env{'request.course.id'}) {
 4328: 	    return 'not_in_class';
 4329: 	}
 4330:     }
 4331: # --------------------------------------------------------------- Make the user
 4332:     my $reply=&modifyuser
 4333: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4334:          $desiredhome,$email);
 4335:     unless ($reply eq 'ok') { return $reply; }
 4336:     # This will cause &modify_student_enrollment to get the uid from the
 4337:     # students environment
 4338:     $uid = undef if (!$forceid);
 4339:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4340: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4341:     return $reply;
 4342: }
 4343: 
 4344: sub modify_student_enrollment {
 4345:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4346:     my ($cdom,$cnum,$chome);
 4347:     if (!$cid) {
 4348: 	unless ($cid=$env{'request.course.id'}) {
 4349: 	    return 'not_in_class';
 4350: 	}
 4351: 	$cdom=$env{'course.'.$cid.'.domain'};
 4352: 	$cnum=$env{'course.'.$cid.'.num'};
 4353:     } else {
 4354: 	($cdom,$cnum)=split(/_/,$cid);
 4355:     }
 4356:     $chome=$env{'course.'.$cid.'.home'};
 4357:     if (!$chome) {
 4358: 	$chome=&homeserver($cnum,$cdom);
 4359:     }
 4360:     if (!$chome) { return 'unknown_course'; }
 4361:     # Make sure the user exists
 4362:     my $uhome=&homeserver($uname,$udom);
 4363:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4364: 	return 'error: no such user';
 4365:     }
 4366:     # Get student data if we were not given enough information
 4367:     if (!defined($first)  || $first  eq '' || 
 4368:         !defined($last)   || $last   eq '' || 
 4369:         !defined($uid)    || $uid    eq '' || 
 4370:         !defined($middle) || $middle eq '' || 
 4371:         !defined($gene)   || $gene   eq '') {
 4372:         # They did not supply us with enough data to enroll the student, so
 4373:         # we need to pick up more information.
 4374:         my %tmp = &get('environment',
 4375:                        ['firstname','middlename','lastname', 'generation','id']
 4376:                        ,$udom,$uname);
 4377: 
 4378:         #foreach (keys(%tmp)) {
 4379:         #    &logthis("key $_ = ".$tmp{$_});
 4380:         #}
 4381:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4382:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4383:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4384:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4385:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4386:     }
 4387:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4388:     my $reply=cput('classlist',
 4389: 		   {"$uname:$udom" => 
 4390: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4391: 		   $cdom,$cnum);
 4392:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4393: 	return 'error: '.$reply;
 4394:     } else {
 4395: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4396:     }
 4397:     # Add student role to user
 4398:     my $uurl='/'.$cid;
 4399:     $uurl=~s/\_/\//g;
 4400:     if ($usec) {
 4401: 	$uurl.='/'.$usec;
 4402:     }
 4403:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4404: }
 4405: 
 4406: sub format_name {
 4407:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4408:     my $name;
 4409:     if ($first ne 'lastname') {
 4410: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4411:     } else {
 4412: 	if ($lastname=~/\S/) {
 4413: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4414: 	    $name=~s/\s+,/,/;
 4415: 	} else {
 4416: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4417: 	}
 4418:     }
 4419:     $name=~s/^\s+//;
 4420:     $name=~s/\s+$//;
 4421:     $name=~s/\s+/ /g;
 4422:     return $name;
 4423: }
 4424: 
 4425: # ------------------------------------------------- Write to course preferences
 4426: 
 4427: sub writecoursepref {
 4428:     my ($courseid,%prefs)=@_;
 4429:     $courseid=~s/^\///;
 4430:     $courseid=~s/\_/\//g;
 4431:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4432:     my $chome=homeserver($cnum,$cdomain);
 4433:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4434: 	return 'error: no such course';
 4435:     }
 4436:     my $cstring='';
 4437:     foreach (keys %prefs) {
 4438: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4439:     }
 4440:     $cstring=~s/\&$//;
 4441:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4442: }
 4443: 
 4444: # ---------------------------------------------------------- Make/modify course
 4445: 
 4446: sub createcourse {
 4447:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4448:         $course_owner,$crstype)=@_;
 4449:     $url=&declutter($url);
 4450:     my $cid='';
 4451:     unless (&allowed('ccc',$udom)) {
 4452:         return 'refused';
 4453:     }
 4454: # ------------------------------------------------------------------- Create ID
 4455:    my $uname=int(1+rand(9)).
 4456:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4457:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4458:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4459: # ----------------------------------------------- Make sure that does not exist
 4460:    my $uhome=&homeserver($uname,$udom,'true');
 4461:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4462:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4463:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4464:        $uhome=&homeserver($uname,$udom,'true');       
 4465:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4466:            return 'error: unable to generate unique course-ID';
 4467:        } 
 4468:    }
 4469: # ------------------------------------------------ Check supplied server name
 4470:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4471:     if (! exists($libserv{$course_server})) {
 4472:         return 'error:bad server name '.$course_server;
 4473:     }
 4474: # ------------------------------------------------------------- Make the course
 4475:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4476:                       $course_server);
 4477:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4478:     $uhome=&homeserver($uname,$udom,'true');
 4479:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4480: 	return 'error: no such course';
 4481:     }
 4482: # ----------------------------------------------------------------- Course made
 4483: # log existence
 4484:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4485:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4486:                   &escape($crstype),$uhome);
 4487:     &flushcourselogs();
 4488: # set toplevel url
 4489:     my $topurl=$url;
 4490:     unless ($nonstandard) {
 4491: # ------------------------------------------ For standard courses, make top url
 4492:         my $mapurl=&clutter($url);
 4493:         if ($mapurl eq '/res/') { $mapurl=''; }
 4494:         $env{'form.initmap'}=(<<ENDINITMAP);
 4495: <map>
 4496: <resource id="1" type="start"></resource>
 4497: <resource id="2" src="$mapurl"></resource>
 4498: <resource id="3" type="finish"></resource>
 4499: <link index="1" from="1" to="2"></link>
 4500: <link index="2" from="2" to="3"></link>
 4501: </map>
 4502: ENDINITMAP
 4503:         $topurl=&declutter(
 4504:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4505:                           );
 4506:     }
 4507: # ----------------------------------------------------------- Write preferences
 4508:     &writecoursepref($udom.'_'.$uname,
 4509:                      ('description' => $description,
 4510:                       'url'         => $topurl));
 4511:     return '/'.$udom.'/'.$uname;
 4512: }
 4513: 
 4514: # ---------------------------------------------------------- Assign Custom Role
 4515: 
 4516: sub assigncustomrole {
 4517:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4518:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4519:                        $end,$start,$deleteflag);
 4520: }
 4521: 
 4522: # ----------------------------------------------------------------- Revoke Role
 4523: 
 4524: sub revokerole {
 4525:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4526:     my $now=time;
 4527:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4528: }
 4529: 
 4530: # ---------------------------------------------------------- Revoke Custom Role
 4531: 
 4532: sub revokecustomrole {
 4533:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4534:     my $now=time;
 4535:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4536:            $deleteflag);
 4537: }
 4538: 
 4539: # ------------------------------------------------------------ Disk usage
 4540: sub diskusage {
 4541:     my ($udom,$uname,$directoryRoot)=@_;
 4542:     $directoryRoot =~ s/\/$//;
 4543:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4544:     return $listing;
 4545: }
 4546: 
 4547: sub is_locked {
 4548:     my ($file_name, $domain, $user) = @_;
 4549:     my @check;
 4550:     my $is_locked;
 4551:     push @check, $file_name;
 4552:     my %locked = &get('file_permissions',\@check,
 4553: 		      $env{'user.domain'},$env{'user.name'});
 4554:     my ($tmp)=keys(%locked);
 4555:     if ($tmp=~/^error:/) { undef(%locked); }
 4556: 
 4557:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4558:         $is_locked = 'true';
 4559:     } else {
 4560:         $is_locked = 'false';
 4561:     }
 4562: }
 4563: 
 4564: # ------------------------------------------------------------- Mark as Read Only
 4565: 
 4566: sub mark_as_readonly {
 4567:     my ($domain,$user,$files,$what) = @_;
 4568:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4569:     my ($tmp)=keys(%current_permissions);
 4570:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4571:     foreach my $file (@{$files}) {
 4572:         push(@{$current_permissions{$file}},$what);
 4573:     }
 4574:     &put('file_permissions',\%current_permissions,$domain,$user);
 4575:     return;
 4576: }
 4577: 
 4578: # ------------------------------------------------------------Save Selected Files
 4579: 
 4580: sub save_selected_files {
 4581:     my ($user, $path, @files) = @_;
 4582:     my $filename = $user."savedfiles";
 4583:     my @other_files = &files_not_in_path($user, $path);
 4584:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4585:     foreach my $file (@files) {
 4586:         print (OUT $env{'form.currentpath'}.$file."\n");
 4587:     }
 4588:     foreach my $file (@other_files) {
 4589:         print (OUT $file."\n");
 4590:     }
 4591:     close (OUT);
 4592:     return 'ok';
 4593: }
 4594: 
 4595: sub clear_selected_files {
 4596:     my ($user) = @_;
 4597:     my $filename = $user."savedfiles";
 4598:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4599:     print (OUT undef);
 4600:     close (OUT);
 4601:     return ("ok");    
 4602: }
 4603: 
 4604: sub files_in_path {
 4605:     my ($user, $path) = @_;
 4606:     my $filename = $user."savedfiles";
 4607:     my %return_files;
 4608:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4609:     while (my $line_in = <IN>) {
 4610:         chomp ($line_in);
 4611:         my @paths_and_file = split (m!/!, $line_in);
 4612:         my $file_part = pop (@paths_and_file);
 4613:         my $path_part = join ('/', @paths_and_file);
 4614:         $path_part.='/';
 4615:         my $path_and_file = $path_part.$file_part;
 4616:         if ($path_part eq $path) {
 4617:             $return_files{$file_part}= 'selected';
 4618:         }
 4619:     }
 4620:     close (IN);
 4621:     return (\%return_files);
 4622: }
 4623: 
 4624: # called in portfolio select mode, to show files selected NOT in current directory
 4625: sub files_not_in_path {
 4626:     my ($user, $path) = @_;
 4627:     my $filename = $user."savedfiles";
 4628:     my @return_files;
 4629:     my $path_part;
 4630:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4631:     while (<IN>) {
 4632:         #ok, I know it's clunky, but I want it to work
 4633:         my @paths_and_file = split m!/!, $_;
 4634:         my $file_part = pop (@paths_and_file);
 4635:         chomp ($file_part);
 4636:         my $path_part = join ('/', @paths_and_file);
 4637:         $path_part .= '/';
 4638:         my $path_and_file = $path_part.$file_part;
 4639:         if ($path_part ne $path) {
 4640:             push (@return_files, ($path_and_file));
 4641:         }
 4642:     }
 4643:     close (OUT);
 4644:     return (@return_files);
 4645: }
 4646: 
 4647: #--------------------------------------------------------------Get Marked as Read Only
 4648: 
 4649: 
 4650: sub get_marked_as_readonly {
 4651:     my ($domain,$user,$what) = @_;
 4652:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4653:     my ($tmp)=keys(%current_permissions);
 4654:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4655:     my @readonly_files;
 4656:     my $cmp1=$what;
 4657:     if (ref($what)) { $cmp1=join('',@{$what}) };
 4658:     while (my ($file_name,$value) = each(%current_permissions)) {
 4659:         if (ref($value) eq "ARRAY"){
 4660:             foreach my $stored_what (@{$value}) {
 4661:                 my $cmp2=$stored_what;
 4662:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
 4663:                 if ($cmp1 eq $cmp2) {
 4664:                     push(@readonly_files, $file_name);
 4665:                 } elsif (!defined($what)) {
 4666:                     push(@readonly_files, $file_name);
 4667:                 }
 4668:             }
 4669:         } 
 4670:     }
 4671:     return @readonly_files;
 4672: }
 4673: #-----------------------------------------------------------Get Marked as Read Only Hash
 4674: 
 4675: sub get_marked_as_readonly_hash {
 4676:     my ($domain,$user,$what) = @_;
 4677:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4678:     my ($tmp)=keys(%current_permissions);
 4679:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4680: 
 4681:     my %readonly_files;
 4682:     while (my ($file_name,$value) = each(%current_permissions)) {
 4683:         if (ref($value) eq "ARRAY"){
 4684:             foreach my $stored_what (@{$value}) {
 4685:                 if ($stored_what eq $what) {
 4686:                     $readonly_files{$file_name} = 'locked';
 4687:                 } elsif (!defined($what)) {
 4688:                     $readonly_files{$file_name} = 'locked';
 4689:                 }
 4690:             }
 4691:         } 
 4692:     }
 4693:     return %readonly_files;
 4694: }
 4695: # ------------------------------------------------------------ Unmark as Read Only
 4696: 
 4697: sub unmark_as_readonly {
 4698:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 4699:     # for portfolio submissions, $what contains [$symb,$crsid] 
 4700:     my ($domain,$user,$what,$file_name) = @_;
 4701:     my $symb_crs = $what;
 4702:     if (ref($what)) { $symb_crs=join('',@$what); }
 4703:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4704:     my ($tmp)=keys(%current_permissions);
 4705:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4706:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
 4707:     foreach my $file (@readonly_files) {
 4708: 	if (defined($file_name) && ($file_name ne $file)) { next; }
 4709: 	my $current_locks = $current_permissions{$file};
 4710:         my @new_locks;
 4711:         my @del_keys;
 4712:         if (ref($current_locks) eq "ARRAY"){
 4713:             foreach my $locker (@{$current_locks}) {
 4714:                 my $compare=$locker;
 4715:                 if (ref($locker)) { $compare=join('',@{$locker}) };
 4716:                 if ($compare ne $symb_crs) {
 4717:                     push(@new_locks, $locker);
 4718:                 }
 4719:             }
 4720:             if (scalar(@new_locks) > 0) {
 4721:                 $current_permissions{$file} = \@new_locks;
 4722:             } else {
 4723:                 push(@del_keys, $file);
 4724:                 &del('file_permissions',\@del_keys, $domain, $user);
 4725:                 delete($current_permissions{$file});
 4726:             }
 4727:         }
 4728:     }
 4729:     &put('file_permissions',\%current_permissions,$domain,$user);
 4730:     return;
 4731: }
 4732: 
 4733: # ------------------------------------------------------------ Directory lister
 4734: 
 4735: sub dirlist {
 4736:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 4737: 
 4738:     $uri=~s/^\///;
 4739:     $uri=~s/\/$//;
 4740:     my ($udom, $uname);
 4741:     (undef,$udom,$uname)=split(/\//,$uri);
 4742:     if(defined($userdomain)) {
 4743:         $udom = $userdomain;
 4744:     }
 4745:     if(defined($username)) {
 4746:         $uname = $username;
 4747:     }
 4748: 
 4749:     my $dirRoot = $perlvar{'lonDocRoot'};
 4750:     if(defined($alternateDirectoryRoot)) {
 4751:         $dirRoot = $alternateDirectoryRoot;
 4752:         $dirRoot =~ s/\/$//;
 4753:     }
 4754: 
 4755:     if($udom) {
 4756:         if($uname) {
 4757:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 4758:                               homeserver($uname,$udom));
 4759:             my @listing_results;
 4760:             if ($listing eq 'unknown_cmd') {
 4761:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4762:                                homeserver($uname,$udom));
 4763:                 @listing_results = split(/:/,$listing);
 4764:             } else {
 4765:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 4766:             }
 4767:             return @listing_results;
 4768:         } elsif(!defined($alternateDirectoryRoot)) {
 4769:             my $tryserver;
 4770:             my %allusers=();
 4771:             foreach $tryserver (keys %libserv) {
 4772:                 if($hostdom{$tryserver} eq $udom) {
 4773:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 4774:                                       $udom, $tryserver);
 4775:                     my @listing_results;
 4776:                     if ($listing eq 'unknown_cmd') {
 4777:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 4778:                                        $udom, $tryserver);
 4779:                         @listing_results = split(/:/,$listing);
 4780:                     } else {
 4781:                         @listing_results =
 4782:                             map { &unescape($_); } split(/:/,$listing);
 4783:                     }
 4784:                     if ($listing_results[0] ne 'no_such_dir' && 
 4785:                         $listing_results[0] ne 'empty'       &&
 4786:                         $listing_results[0] ne 'con_lost') {
 4787:                         foreach (@listing_results) {
 4788:                             my ($entry,@stat)=split(/&/,$_);
 4789:                             $allusers{$entry}=1;
 4790:                         }
 4791:                     }
 4792:                 }
 4793:             }
 4794:             my $alluserstr='';
 4795:             foreach (sort keys %allusers) {
 4796:                 $alluserstr.=$_.'&user:';
 4797:             }
 4798:             $alluserstr=~s/:$//;
 4799:             return split(/:/,$alluserstr);
 4800:         } else {
 4801:             my @emptyResults = ();
 4802:             push(@emptyResults, 'missing user name');
 4803:             return split(':',@emptyResults);
 4804:         }
 4805:     } elsif(!defined($alternateDirectoryRoot)) {
 4806:         my $tryserver;
 4807:         my %alldom=();
 4808:         foreach $tryserver (keys %libserv) {
 4809:             $alldom{$hostdom{$tryserver}}=1;
 4810:         }
 4811:         my $alldomstr='';
 4812:         foreach (sort keys %alldom) {
 4813:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 4814:         }
 4815:         $alldomstr=~s/:$//;
 4816:         return split(/:/,$alldomstr);       
 4817:     } else {
 4818:         my @emptyResults = ();
 4819:         push(@emptyResults, 'missing domain');
 4820:         return split(':',@emptyResults);
 4821:     }
 4822: }
 4823: 
 4824: # --------------------------------------------- GetFileTimestamp
 4825: # This function utilizes dirlist and returns the date stamp for
 4826: # when it was last modified.  It will also return an error of -1
 4827: # if an error occurs
 4828: 
 4829: ##
 4830: ## FIXME: This subroutine assumes its caller knows something about the
 4831: ## directory structure of the home server for the student ($root).
 4832: ## Not a good assumption to make.  Since this is for looking up files
 4833: ## in user directories, the full path should be constructed by lond, not
 4834: ## whatever machine we request data from.
 4835: ##
 4836: sub GetFileTimestamp {
 4837:     my ($studentDomain,$studentName,$filename,$root)=@_;
 4838:     $studentDomain=~s/\W//g;
 4839:     $studentName=~s/\W//g;
 4840:     my $subdir=$studentName.'__';
 4841:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4842:     my $proname="$studentDomain/$subdir/$studentName";
 4843:     $proname .= '/'.$filename;
 4844:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 4845:                                               $studentName, $root);
 4846:     my @stats = split('&', $fileStat);
 4847:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4848:         # @stats contains first the filename, then the stat output
 4849:         return $stats[10]; # so this is 10 instead of 9.
 4850:     } else {
 4851:         return -1;
 4852:     }
 4853: }
 4854: 
 4855: sub stat_file {
 4856:     my ($uri) = @_;
 4857:     $uri = &clutter($uri);
 4858: 
 4859:     # we want just the url part without the unneeded accessor url bits
 4860:     if ($uri =~ m-^/adm/-) {
 4861: 	$uri=~s-^/adm/wrapper/-/-;
 4862: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 4863:     }
 4864:     my ($udom,$uname,$file,$dir);
 4865:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 4866: 	($udom,$uname,$file) =
 4867: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 4868: 	$file = 'userfiles/'.$file;
 4869: 	$dir = &propath($udom,$uname);
 4870:     }
 4871:     if ($uri =~ m-^/res/-) {
 4872: 	($udom,$uname) = 
 4873: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 4874: 	$file = $uri;
 4875:     }
 4876: 
 4877:     if (!$udom || !$uname || !$file) {
 4878: 	# unable to handle the uri
 4879: 	return ();
 4880:     }
 4881: 
 4882:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 4883:     my @stats = split('&', $result);
 4884:     
 4885:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4886: 	shift(@stats); #filename is first
 4887: 	return @stats;
 4888:     }
 4889:     return ();
 4890: }
 4891: 
 4892: # -------------------------------------------------------- Value of a Condition
 4893: 
 4894: # gets the value of a specific preevaluated condition
 4895: #    stored in the string  $env{user.state.<cid>}
 4896: # or looks up a condition reference in the bighash and if if hasn't
 4897: # already been evaluated recurses into docondval to get the value of
 4898: # the condition, then memoizing it to 
 4899: #   $env{user.state.<cid>.<condition>}
 4900: sub directcondval {
 4901:     my $number=shift;
 4902:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 4903: 	&Apache::lonuserstate::evalstate();
 4904:     }
 4905:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 4906: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 4907:     } elsif ($number =~ /^_/) {
 4908: 	my $sub_condition;
 4909: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4910: 		&GDBM_READER(),0640)) {
 4911: 	    $sub_condition=$bighash{'conditions'.$number};
 4912: 	    untie(%bighash);
 4913: 	}
 4914: 	my $value = &docondval($sub_condition);
 4915: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 4916: 	return $value;
 4917:     }
 4918:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 4919:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 4920:     } else {
 4921:        return 2;
 4922:     }
 4923: }
 4924: 
 4925: # get the collection of conditions for this resource
 4926: sub condval {
 4927:     my $condidx=shift;
 4928:     my $allpathcond='';
 4929:     foreach my $cond (split(/\|/,$condidx)) {
 4930: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 4931: 	    $allpathcond.=
 4932: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 4933: 	}
 4934:     }
 4935:     $allpathcond=~s/\|$//;
 4936:     return &docondval($allpathcond);
 4937: }
 4938: 
 4939: #evaluates an expression of conditions
 4940: sub docondval {
 4941:     my ($allpathcond) = @_;
 4942:     my $result=0;
 4943:     if ($env{'request.course.id'}
 4944: 	&& defined($allpathcond)) {
 4945: 	my $operand='|';
 4946: 	my @stack;
 4947: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 4948: 	    if ($chunk eq '(') {
 4949: 		push @stack,($operand,$result);
 4950: 	    } elsif ($chunk eq ')') {
 4951: 		my $before=pop @stack;
 4952: 		if (pop @stack eq '&') {
 4953: 		    $result=$result>$before?$before:$result;
 4954: 		} else {
 4955: 		    $result=$result>$before?$result:$before;
 4956: 		}
 4957: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 4958: 		$operand=$chunk;
 4959: 	    } else {
 4960: 		my $new=directcondval($chunk);
 4961: 		if ($operand eq '&') {
 4962: 		    $result=$result>$new?$new:$result;
 4963: 		} else {
 4964: 		    $result=$result>$new?$result:$new;
 4965: 		}
 4966: 	    }
 4967: 	}
 4968:     }
 4969:     return $result;
 4970: }
 4971: 
 4972: # ---------------------------------------------------- Devalidate courseresdata
 4973: 
 4974: sub devalidatecourseresdata {
 4975:     my ($coursenum,$coursedomain)=@_;
 4976:     my $hashid=$coursenum.':'.$coursedomain;
 4977:     &devalidate_cache_new('courseres',$hashid);
 4978: }
 4979: 
 4980: # --------------------------------------------------- Course Resourcedata Query
 4981: 
 4982: sub get_courseresdata {
 4983:     my ($coursenum,$coursedomain)=@_;
 4984:     my $coursehom=&homeserver($coursenum,$coursedomain);
 4985:     my $hashid=$coursenum.':'.$coursedomain;
 4986:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 4987:     my %dumpreply;
 4988:     unless (defined($cached)) {
 4989: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 4990: 	$result=\%dumpreply;
 4991: 	my ($tmp) = keys(%dumpreply);
 4992: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4993: 	    &do_cache_new('courseres',$hashid,$result,600);
 4994: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4995: 	    return $tmp;
 4996: 	} elsif ($tmp =~ /^(error)/) {
 4997: 	    $result=undef;
 4998: 	    &do_cache_new('courseres',$hashid,$result,600);
 4999: 	}
 5000:     }
 5001:     return $result;
 5002: }
 5003: 
 5004: sub devalidateuserresdata {
 5005:     my ($uname,$udom)=@_;
 5006:     my $hashid="$udom:$uname";
 5007:     &devalidate_cache_new('userres',$hashid);
 5008: }
 5009: 
 5010: sub get_userresdata {
 5011:     my ($uname,$udom)=@_;
 5012:     #most student don\'t have any data set, check if there is some data
 5013:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5014: 
 5015:     my $hashid="$udom:$uname";
 5016:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5017:     if (!defined($cached)) {
 5018: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5019: 	$result=\%resourcedata;
 5020: 	&do_cache_new('userres',$hashid,$result,600);
 5021:     }
 5022:     my ($tmp)=keys(%$result);
 5023:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5024: 	return $result;
 5025:     }
 5026:     #error 2 occurs when the .db doesn't exist
 5027:     if ($tmp!~/error: 2 /) {
 5028: 	&logthis("<font color=\"blue\">WARNING:".
 5029: 		 " Trying to get resource data for ".
 5030: 		 $uname." at ".$udom.": ".
 5031: 		 $tmp."</font>");
 5032:     } elsif ($tmp=~/error: 2 /) {
 5033: 	#&EXT_cache_set($udom,$uname);
 5034: 	&do_cache_new('userres',$hashid,undef,600);
 5035: 	undef($tmp); # not really an error so don't send it back
 5036:     }
 5037:     return $tmp;
 5038: }
 5039: 
 5040: sub resdata {
 5041:     my ($name,$domain,$type,@which)=@_;
 5042:     my $result;
 5043:     if ($type eq 'course') {
 5044: 	$result=&get_courseresdata($name,$domain);
 5045:     } elsif ($type eq 'user') {
 5046: 	$result=&get_userresdata($name,$domain);
 5047:     }
 5048:     if (!ref($result)) { return $result; }    
 5049:     foreach my $item (@which) {
 5050: 	if (defined($result->{$item})) {
 5051: 	    return $result->{$item};
 5052: 	}
 5053:     }
 5054:     return undef;
 5055: }
 5056: 
 5057: #
 5058: # EXT resource caching routines
 5059: #
 5060: 
 5061: sub clear_EXT_cache_status {
 5062:     &delenv('cache.EXT.');
 5063: }
 5064: 
 5065: sub EXT_cache_status {
 5066:     my ($target_domain,$target_user) = @_;
 5067:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5068:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5069:         # We know already the user has no data
 5070:         return 1;
 5071:     } else {
 5072:         return 0;
 5073:     }
 5074: }
 5075: 
 5076: sub EXT_cache_set {
 5077:     my ($target_domain,$target_user) = @_;
 5078:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5079:     #&appenv($cachename => time);
 5080: }
 5081: 
 5082: # --------------------------------------------------------- Value of a Variable
 5083: sub EXT {
 5084: 
 5085:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5086:     unless ($varname) { return ''; }
 5087:     #get real user name/domain, courseid and symb
 5088:     my $courseid;
 5089:     my $publicuser;
 5090:     if ($symbparm) {
 5091: 	$symbparm=&get_symb_from_alias($symbparm);
 5092:     }
 5093:     if (!($uname && $udom)) {
 5094:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5095: 	  &Apache::lonxml::whichuser($symbparm);
 5096:       if (!$symbparm) {	$symbparm=$cursymb; }
 5097:     } else {
 5098: 	$courseid=$env{'request.course.id'};
 5099:     }
 5100:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5101:     my $rest;
 5102:     if (defined($therest[0])) {
 5103:        $rest=join('.',@therest);
 5104:     } else {
 5105:        $rest='';
 5106:     }
 5107: 
 5108:     my $qualifierrest=$qualifier;
 5109:     if ($rest) { $qualifierrest.='.'.$rest; }
 5110:     my $spacequalifierrest=$space;
 5111:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5112:     if ($realm eq 'user') {
 5113: # --------------------------------------------------------------- user.resource
 5114: 	if ($space eq 'resource') {
 5115: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5116: 		  || defined($Apache::lonhomework::parsing_a_task))
 5117: 		 &&
 5118: 		 ($symbparm eq &symbread()) ) {
 5119: 		return $Apache::lonhomework::history{$qualifierrest};
 5120: 	    } else {
 5121: 		my %restored;
 5122: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5123: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5124: 		} else {
 5125: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5126: 		}
 5127: 		return $restored{$qualifierrest};
 5128: 	    }
 5129: # ----------------------------------------------------------------- user.access
 5130:         } elsif ($space eq 'access') {
 5131: 	    # FIXME - not supporting calls for a specific user
 5132:             return &allowed($qualifier,$rest);
 5133: # ------------------------------------------ user.preferences, user.environment
 5134:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5135: 	    if (($uname eq $env{'user.name'}) &&
 5136: 		($udom eq $env{'user.domain'})) {
 5137: 		return $env{join('.',('environment',$qualifierrest))};
 5138: 	    } else {
 5139: 		my %returnhash;
 5140: 		if (!$publicuser) {
 5141: 		    %returnhash=&userenvironment($udom,$uname,
 5142: 						 $qualifierrest);
 5143: 		}
 5144: 		return $returnhash{$qualifierrest};
 5145: 	    }
 5146: # ----------------------------------------------------------------- user.course
 5147:         } elsif ($space eq 'course') {
 5148: 	    # FIXME - not supporting calls for a specific user
 5149:             return $env{join('.',('request.course',$qualifier))};
 5150: # ------------------------------------------------------------------- user.role
 5151:         } elsif ($space eq 'role') {
 5152: 	    # FIXME - not supporting calls for a specific user
 5153:             my ($role,$where)=split(/\./,$env{'request.role'});
 5154:             if ($qualifier eq 'value') {
 5155: 		return $role;
 5156:             } elsif ($qualifier eq 'extent') {
 5157:                 return $where;
 5158:             }
 5159: # ----------------------------------------------------------------- user.domain
 5160:         } elsif ($space eq 'domain') {
 5161:             return $udom;
 5162: # ------------------------------------------------------------------- user.name
 5163:         } elsif ($space eq 'name') {
 5164:             return $uname;
 5165: # ---------------------------------------------------- Any other user namespace
 5166:         } else {
 5167: 	    my %reply;
 5168: 	    if (!$publicuser) {
 5169: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5170: 	    }
 5171: 	    return $reply{$qualifierrest};
 5172:         }
 5173:     } elsif ($realm eq 'query') {
 5174: # ---------------------------------------------- pull stuff out of query string
 5175:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5176: 						[$spacequalifierrest]);
 5177: 	return $env{'form.'.$spacequalifierrest}; 
 5178:    } elsif ($realm eq 'request') {
 5179: # ------------------------------------------------------------- request.browser
 5180:         if ($space eq 'browser') {
 5181: 	    if ($qualifier eq 'textremote') {
 5182: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5183: 		    return 1;
 5184: 		} else {
 5185: 		    return 0;
 5186: 		}
 5187: 	    } else {
 5188: 		return $env{'browser.'.$qualifier};
 5189: 	    }
 5190: # ------------------------------------------------------------ request.filename
 5191:         } else {
 5192:             return $env{'request.'.$spacequalifierrest};
 5193:         }
 5194:     } elsif ($realm eq 'course') {
 5195: # ---------------------------------------------------------- course.description
 5196:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5197:     } elsif ($realm eq 'resource') {
 5198: 
 5199: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5200: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5201: 	}
 5202: 
 5203: 	if ($space eq 'title') {
 5204: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5205: 	    return &gettitle($symbparm);
 5206: 	}
 5207: 	
 5208: 	if ($space eq 'map') {
 5209: 	    my ($map) = &decode_symb($symbparm);
 5210: 	    return &symbread($map);
 5211: 	}
 5212: 
 5213: 	my ($section, $group, @groups);
 5214: 	my ($courselevelm,$courselevel);
 5215: 	if ($symbparm && defined($courseid) && 
 5216: 	    $courseid eq $env{'request.course.id'}) {
 5217: 
 5218: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5219: 
 5220: # ----------------------------------------------------- Cascading lookup scheme
 5221: 	    my $symbp=$symbparm;
 5222: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5223: 
 5224: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5225: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5226: 
 5227: 	    if (($env{'user.name'} eq $uname) &&
 5228: 		($env{'user.domain'} eq $udom)) {
 5229: 		$section=$env{'request.course.sec'};
 5230:                 @groups = split(/:/,$env{'request.course.groups'});  
 5231:                 @groups=&sort_course_groups($courseid,@groups); 
 5232: 	    } else {
 5233: 		if (! defined($usection)) {
 5234: 		    $section=&getsection($udom,$uname,$courseid);
 5235: 		} else {
 5236: 		    $section = $usection;
 5237: 		}
 5238:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5239: 	    }
 5240: 
 5241: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5242: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5243: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5244: 
 5245: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5246: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5247: 	    $courselevelm=$courseid.'.'.$mapparm;
 5248: 
 5249: # ----------------------------------------------------------- first, check user
 5250: 
 5251: 	    my $userreply=&resdata($uname,$udom,'user',
 5252: 				       ($courselevelr,$courselevelm,
 5253: 					$courselevel));
 5254: 	    if (defined($userreply)) { return $userreply; }
 5255: 
 5256: # ------------------------------------------------ second, check some of course
 5257:             my $coursereply;
 5258:             if (@groups > 0) {
 5259:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5260:                                        $mapparm,$spacequalifierrest);
 5261:                 if (defined($coursereply)) { return $coursereply; }
 5262:             }
 5263: 
 5264: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5265: 				     $env{'course.'.$courseid.'.domain'},
 5266: 				     'course',
 5267: 				     ($seclevelr,$seclevelm,$seclevel,
 5268: 				      $courselevelr));
 5269: 	    if (defined($coursereply)) { return $coursereply; }
 5270: 
 5271: # ------------------------------------------------------ third, check map parms
 5272: 	    my %parmhash=();
 5273: 	    my $thisparm='';
 5274: 	    if (tie(%parmhash,'GDBM_File',
 5275: 		    $env{'request.course.fn'}.'_parms.db',
 5276: 		    &GDBM_READER(),0640)) {
 5277: 		$thisparm=$parmhash{$symbparm};
 5278: 		untie(%parmhash);
 5279: 	    }
 5280: 	    if ($thisparm) { return $thisparm; }
 5281: 	}
 5282: # ------------------------------------------ fourth, look in resource metadata
 5283: 
 5284: 	$spacequalifierrest=~s/\./\_/;
 5285: 	my $filename;
 5286: 	if (!$symbparm) { $symbparm=&symbread(); }
 5287: 	if ($symbparm) {
 5288: 	    $filename=(&decode_symb($symbparm))[2];
 5289: 	} else {
 5290: 	    $filename=$env{'request.filename'};
 5291: 	}
 5292: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5293: 	if (defined($metadata)) { return $metadata; }
 5294: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5295: 	if (defined($metadata)) { return $metadata; }
 5296: 
 5297: # ---------------------------------------------- fourth, look in rest pf course
 5298: 	if ($symbparm && defined($courseid) && 
 5299: 	    $courseid eq $env{'request.course.id'}) {
 5300: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5301: 				     $env{'course.'.$courseid.'.domain'},
 5302: 				     'course',
 5303: 				     ($courselevelm,$courselevel));
 5304: 	    if (defined($coursereply)) { return $coursereply; }
 5305: 	}
 5306: # ------------------------------------------------------------------ Cascade up
 5307: 	unless ($space eq '0') {
 5308: 	    my @parts=split(/_/,$space);
 5309: 	    my $id=pop(@parts);
 5310: 	    my $part=join('_',@parts);
 5311: 	    if ($part eq '') { $part='0'; }
 5312: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5313: 				 $symbparm,$udom,$uname,$section,1);
 5314: 	    if (defined($partgeneral)) { return $partgeneral; }
 5315: 	}
 5316: 	if ($recurse) { return undef; }
 5317: 	my $pack_def=&packages_tab_default($filename,$varname);
 5318: 	if (defined($pack_def)) { return $pack_def; }
 5319: 
 5320: # ---------------------------------------------------- Any other user namespace
 5321:     } elsif ($realm eq 'environment') {
 5322: # ----------------------------------------------------------------- environment
 5323: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5324: 	    return $env{'environment.'.$spacequalifierrest};
 5325: 	} else {
 5326: 	    my %returnhash=&userenvironment($udom,$uname,
 5327: 					    $spacequalifierrest);
 5328: 	    return $returnhash{$spacequalifierrest};
 5329: 	}
 5330:     } elsif ($realm eq 'system') {
 5331: # ----------------------------------------------------------------- system.time
 5332: 	if ($space eq 'time') {
 5333: 	    return time;
 5334:         }
 5335:     } elsif ($realm eq 'server') {
 5336: # ----------------------------------------------------------------- system.time
 5337: 	if ($space eq 'name') {
 5338: 	    return $ENV{'SERVER_NAME'};
 5339:         }
 5340:     }
 5341:     return '';
 5342: }
 5343: 
 5344: sub check_group_parms {
 5345:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5346:     my @groupitems = ();
 5347:     my $resultitem;
 5348:     my @levels = ($symbparm,$mapparm,$what);
 5349:     foreach my $group (@{$groups}) {
 5350:         foreach my $level (@levels) {
 5351:              my $item = $courseid.'.['.$group.'].'.$level;
 5352:              push(@groupitems,$item);
 5353:         }
 5354:     }
 5355:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5356:                             $env{'course.'.$courseid.'.domain'},
 5357:                                      'course',@groupitems);
 5358:     return $coursereply;
 5359: }
 5360: 
 5361: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5362:     my ($courseid,@groups) = @_;
 5363:     @groups = sort(@groups);
 5364:     return @groups;
 5365: }
 5366: 
 5367: sub packages_tab_default {
 5368:     my ($uri,$varname)=@_;
 5369:     my (undef,$part,$name)=split(/\./,$varname);
 5370: 
 5371:     my (@extension,@specifics,$do_default);
 5372:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5373: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5374: 	if ($pack_type eq 'default') {
 5375: 	    $do_default=1;
 5376: 	} elsif ($pack_type eq 'extension') {
 5377: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5378: 	} else {
 5379: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5380: 	}
 5381:     }
 5382:     # first look for a package that matches the requested part id
 5383:     foreach my $package (@specifics) {
 5384: 	my (undef,$pack_type,$pack_part)=@{$package};
 5385: 	next if ($pack_part ne $part);
 5386: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5387: 	    return $packagetab{"$pack_type&$name&default"};
 5388: 	}
 5389:     }
 5390:     # look for any possible matching non extension_ package
 5391:     foreach my $package (@specifics) {
 5392: 	my (undef,$pack_type,$pack_part)=@{$package};
 5393: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5394: 	    return $packagetab{"$pack_type&$name&default"};
 5395: 	}
 5396: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5397: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5398: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5399: 	}
 5400:     }
 5401:     # look for any posible extension_ match
 5402:     foreach my $package (@extension) {
 5403: 	my ($package,$pack_type)=@{$package};
 5404: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5405: 	    return $packagetab{"$pack_type&$name&default"};
 5406: 	}
 5407: 	if (defined($packagetab{$package."&$name&default"})) {
 5408: 	    return $packagetab{$package."&$name&default"};
 5409: 	}
 5410:     }
 5411:     # look for a global default setting
 5412:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5413: 	return $packagetab{"default&$name&default"};
 5414:     }
 5415:     return undef;
 5416: }
 5417: 
 5418: sub add_prefix_and_part {
 5419:     my ($prefix,$part)=@_;
 5420:     my $keyroot;
 5421:     if (defined($prefix) && $prefix !~ /^__/) {
 5422: 	# prefix that has a part already
 5423: 	$keyroot=$prefix;
 5424:     } elsif (defined($prefix)) {
 5425: 	# prefix that is missing a part
 5426: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5427:     } else {
 5428: 	# no prefix at all
 5429: 	if (defined($part)) { $keyroot='_'.$part; }
 5430:     }
 5431:     return $keyroot;
 5432: }
 5433: 
 5434: # ---------------------------------------------------------------- Get metadata
 5435: 
 5436: my %metaentry;
 5437: sub metadata {
 5438:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5439:     $uri=&declutter($uri);
 5440:     # if it is a non metadata possible uri return quickly
 5441:     if (($uri eq '') || 
 5442: 	(($uri =~ m|^/*adm/|) && 
 5443: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5444:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5445: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5446: 	return undef;
 5447:     }
 5448:     my $filename=$uri;
 5449:     $uri=~s/\.meta$//;
 5450: #
 5451: # Is the metadata already cached?
 5452: # Look at timestamp of caching
 5453: # Everything is cached by the main uri, libraries are never directly cached
 5454: #
 5455:     if (!defined($liburi)) {
 5456: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5457: 	if (defined($cached)) { return $result->{':'.$what}; }
 5458:     }
 5459:     {
 5460: #
 5461: # Is this a recursive call for a library?
 5462: #
 5463: #	if (! exists($metacache{$uri})) {
 5464: #	    $metacache{$uri}={};
 5465: #	}
 5466:         if ($liburi) {
 5467: 	    $liburi=&declutter($liburi);
 5468:             $filename=$liburi;
 5469:         } else {
 5470: 	    &devalidate_cache_new('meta',$uri);
 5471: 	    undef(%metaentry);
 5472: 	}
 5473:         my %metathesekeys=();
 5474:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5475: 	my $metastring;
 5476: 	if ($uri !~ m -^(uploaded|editupload)/-) {
 5477: 	    my $file=&filelocation('',&clutter($filename));
 5478: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5479: 	    $metastring=&getfile($file);
 5480: 	}
 5481:         my $parser=HTML::LCParser->new(\$metastring);
 5482:         my $token;
 5483:         undef %metathesekeys;
 5484:         while ($token=$parser->get_token) {
 5485: 	    if ($token->[0] eq 'S') {
 5486: 		if (defined($token->[2]->{'package'})) {
 5487: #
 5488: # This is a package - get package info
 5489: #
 5490: 		    my $package=$token->[2]->{'package'};
 5491: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5492: 		    if (defined($token->[2]->{'id'})) { 
 5493: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5494: 		    }
 5495: 		    if ($metaentry{':packages'}) {
 5496: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5497: 		    } else {
 5498: 			$metaentry{':packages'}=$package.$keyroot;
 5499: 		    }
 5500: 		    foreach my $pack_entry (keys(%packagetab)) {
 5501: 			my $part=$keyroot;
 5502: 			$part=~s/^\_//;
 5503: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 5504: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 5505: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 5506: 			    # ignore package.tab specified default values
 5507:                             # here &package_tab_default() will fetch those
 5508: 			    if ($subp eq 'default') { next; }
 5509: 			    my $value=$packagetab{$pack_entry};
 5510: 			    my $unikey;
 5511: 			    if ($pack =~ /_0$/) {
 5512: 				$unikey='parameter_0_'.$name;
 5513: 				$part=0;
 5514: 			    } else {
 5515: 				$unikey='parameter'.$keyroot.'_'.$name;
 5516: 			    }
 5517: 			    if ($subp eq 'display') {
 5518: 				$value.=' [Part: '.$part.']';
 5519: 			    }
 5520: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5521: 			    $metathesekeys{$unikey}=1;
 5522: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5523: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5524: 			    }
 5525: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5526: 				$metaentry{':'.$unikey}=
 5527: 				    $metaentry{':'.$unikey.'.default'};
 5528: 			    }
 5529: 			}
 5530: 		    }
 5531: 		} else {
 5532: #
 5533: # This is not a package - some other kind of start tag
 5534: #
 5535: 		    my $entry=$token->[1];
 5536: 		    my $unikey;
 5537: 		    if ($entry eq 'import') {
 5538: 			$unikey='';
 5539: 		    } else {
 5540: 			$unikey=$entry;
 5541: 		    }
 5542: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5543: 
 5544: 		    if (defined($token->[2]->{'id'})) { 
 5545: 			$unikey.='_'.$token->[2]->{'id'}; 
 5546: 		    }
 5547: 
 5548: 		    if ($entry eq 'import') {
 5549: #
 5550: # Importing a library here
 5551: #
 5552: 			if ($depthcount<20) {
 5553: 			    my $location=$parser->get_text('/import');
 5554: 			    my $dir=$filename;
 5555: 			    $dir=~s|[^/]*$||;
 5556: 			    $location=&filelocation($dir,$location);
 5557: 			    my $metadata = 
 5558: 				&metadata($uri,'keys', $location,$unikey,
 5559: 					  $depthcount+1);
 5560: 			    foreach my $meta (split(',',$metadata)) {
 5561: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 5562: 				$metathesekeys{$meta}=1;
 5563: 			    }
 5564: 			}
 5565: 		    } else { 
 5566: 			
 5567: 			if (defined($token->[2]->{'name'})) { 
 5568: 			    $unikey.='_'.$token->[2]->{'name'}; 
 5569: 			}
 5570: 			$metathesekeys{$unikey}=1;
 5571: 			foreach my $param (@{$token->[3]}) {
 5572: 			    $metaentry{':'.$unikey.'.'.$param} =
 5573: 				$token->[2]->{$param};
 5574: 			}
 5575: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 5576: 			my $default=$metaentry{':'.$unikey.'.default'};
 5577: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 5578: 		 # only ws inside the tag, and not in default, so use default
 5579: 		 # as value
 5580: 			    $metaentry{':'.$unikey}=$default;
 5581: 			} else {
 5582: 		  # either something interesting inside the tag or default
 5583:                   # uninteresting
 5584: 			    $metaentry{':'.$unikey}=$internaltext;
 5585: 			}
 5586: # end of not-a-package not-a-library import
 5587: 		    }
 5588: # end of not-a-package start tag
 5589: 		}
 5590: # the next is the end of "start tag"
 5591: 	    }
 5592: 	}
 5593: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 5594: 	foreach my $key (keys(%packagetab)) {
 5595: 	    #no specific packages #how's our extension
 5596: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 5597: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 5598: 					 \%metathesekeys);
 5599: 	}
 5600: 	if (!exists($metaentry{':packages'})) {
 5601: 	    foreach my $key (keys(%packagetab)) {
 5602: 		#no specific packages well let's get default then
 5603: 		if ($key!~/^default&/) { next; }
 5604: 		&metadata_create_package_def($uri,$key,'default',
 5605: 					     \%metathesekeys);
 5606: 	    }
 5607: 	}
 5608: # are there custom rights to evaluate
 5609: 	if ($metaentry{':copyright'} eq 'custom') {
 5610: 
 5611:     #
 5612:     # Importing a rights file here
 5613:     #
 5614: 	    unless ($depthcount) {
 5615: 		my $location=$metaentry{':customdistributionfile'};
 5616: 		my $dir=$filename;
 5617: 		$dir=~s|[^/]*$||;
 5618: 		$location=&filelocation($dir,$location);
 5619: 		my $rights_metadata =
 5620: 		    &metadata($uri,'keys',$location,'_rights',
 5621: 			      $depthcount+1);
 5622: 		foreach my $rights (split(',',$rights_metadata)) {
 5623: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 5624: 		    $metathesekeys{$rights}=1;
 5625: 		}
 5626: 	    }
 5627: 	}
 5628: 	# uniqifiy package listing
 5629: 	my %seen;
 5630: 	my @uniq_packages =
 5631: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 5632: 	$metaentry{':packages'} = join(',',@uniq_packages);
 5633: 
 5634: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 5635: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 5636: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 5637: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 5638: # this is the end of "was not already recently cached
 5639:     }
 5640:     return $metaentry{':'.$what};
 5641: }
 5642: 
 5643: sub metadata_create_package_def {
 5644:     my ($uri,$key,$package,$metathesekeys)=@_;
 5645:     my ($pack,$name,$subp)=split(/\&/,$key);
 5646:     if ($subp eq 'default') { next; }
 5647:     
 5648:     if (defined($metaentry{':packages'})) {
 5649: 	$metaentry{':packages'}.=','.$package;
 5650:     } else {
 5651: 	$metaentry{':packages'}=$package;
 5652:     }
 5653:     my $value=$packagetab{$key};
 5654:     my $unikey;
 5655:     $unikey='parameter_0_'.$name;
 5656:     $metaentry{':'.$unikey.'.part'}=0;
 5657:     $$metathesekeys{$unikey}=1;
 5658:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5659: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 5660:     }
 5661:     if (defined($metaentry{':'.$unikey.'.default'})) {
 5662: 	$metaentry{':'.$unikey}=
 5663: 	    $metaentry{':'.$unikey.'.default'};
 5664:     }
 5665: }
 5666: 
 5667: sub metadata_generate_part0 {
 5668:     my ($metadata,$metacache,$uri) = @_;
 5669:     my %allnames;
 5670:     foreach my $metakey (keys(%$metadata)) {
 5671: 	if ($metakey=~/^parameter\_(.*)/) {
 5672: 	  my $part=$$metacache{':'.$metakey.'.part'};
 5673: 	  my $name=$$metacache{':'.$metakey.'.name'};
 5674: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 5675: 	    $allnames{$name}=$part;
 5676: 	  }
 5677: 	}
 5678:     }
 5679:     foreach my $name (keys(%allnames)) {
 5680:       $$metadata{"parameter_0_$name"}=1;
 5681:       my $key=":parameter_0_$name";
 5682:       $$metacache{"$key.part"}='0';
 5683:       $$metacache{"$key.name"}=$name;
 5684:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 5685: 					   $allnames{$name}.'_'.$name.
 5686: 					   '.type'};
 5687:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 5688: 			     '.display'};
 5689:       my $expr='[Part: '.$allnames{$name}.']';
 5690:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 5691:       $$metacache{"$key.display"}=$olddis;
 5692:     }
 5693: }
 5694: 
 5695: # ------------------------------------------------- Get the title of a resource
 5696: 
 5697: sub gettitle {
 5698:     my $urlsymb=shift;
 5699:     my $symb=&symbread($urlsymb);
 5700:     if ($symb) {
 5701: 	my $key=$env{'request.course.id'}."\0".$symb;
 5702: 	my ($result,$cached)=&is_cached_new('title',$key);
 5703: 	if (defined($cached)) { 
 5704: 	    return $result;
 5705: 	}
 5706: 	my ($map,$resid,$url)=&decode_symb($symb);
 5707: 	my $title='';
 5708: 	my %bighash;
 5709: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5710: 		&GDBM_READER(),0640)) {
 5711: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 5712: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 5713: 	    untie %bighash;
 5714: 	}
 5715: 	$title=~s/\&colon\;/\:/gs;
 5716: 	if ($title) {
 5717: 	    return &do_cache_new('title',$key,$title,600);
 5718: 	}
 5719: 	$urlsymb=$url;
 5720:     }
 5721:     my $title=&metadata($urlsymb,'title');
 5722:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 5723:     return $title;
 5724: }
 5725: 
 5726: sub get_slot {
 5727:     my ($which,$cnum,$cdom)=@_;
 5728:     if (!$cnum || !$cdom) {
 5729: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 5730: 	$cdom=$env{'course.'.$courseid.'.domain'};
 5731: 	$cnum=$env{'course.'.$courseid.'.num'};
 5732:     }
 5733:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 5734:     my %slotinfo;
 5735:     if (exists($remembered{$key})) {
 5736: 	$slotinfo{$which} = $remembered{$key};
 5737:     } else {
 5738: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 5739: 	&Apache::lonhomework::showhash(%slotinfo);
 5740: 	my ($tmp)=keys(%slotinfo);
 5741: 	if ($tmp=~/^error:/) { return (); }
 5742: 	$remembered{$key} = $slotinfo{$which};
 5743:     }
 5744:     if (ref($slotinfo{$which}) eq 'HASH') {
 5745: 	return %{$slotinfo{$which}};
 5746:     }
 5747:     return $slotinfo{$which};
 5748: }
 5749: # ------------------------------------------------- Update symbolic store links
 5750: 
 5751: sub symblist {
 5752:     my ($mapname,%newhash)=@_;
 5753:     $mapname=&deversion(&declutter($mapname));
 5754:     my %hash;
 5755:     if (($env{'request.course.fn'}) && (%newhash)) {
 5756:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5757:                       &GDBM_WRCREAT(),0640)) {
 5758: 	    foreach my $url (keys %newhash) {
 5759: 		next if ($url eq 'last_known'
 5760: 			 && $env{'form.no_update_last_known'});
 5761: 		$hash{declutter($url)}=&encode_symb($mapname,
 5762: 						    $newhash{$url}->[1],
 5763: 						    $newhash{$url}->[0]);
 5764:             }
 5765:             if (untie(%hash)) {
 5766: 		return 'ok';
 5767:             }
 5768:         }
 5769:     }
 5770:     return 'error';
 5771: }
 5772: 
 5773: # --------------------------------------------------------------- Verify a symb
 5774: 
 5775: sub symbverify {
 5776:     my ($symb,$thisurl)=@_;
 5777:     my $thisfn=$thisurl;
 5778: # wrapper not part of symbs
 5779:     $thisfn=~s/^\/adm\/wrapper//;
 5780:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 5781:     $thisfn=&declutter($thisfn);
 5782: # direct jump to resource in page or to a sequence - will construct own symbs
 5783:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 5784: # check URL part
 5785:     my ($map,$resid,$url)=&decode_symb($symb);
 5786: 
 5787:     unless ($url eq $thisfn) { return 0; }
 5788: 
 5789:     $symb=&symbclean($symb);
 5790:     $thisurl=&deversion($thisurl);
 5791:     $thisfn=&deversion($thisfn);
 5792: 
 5793:     my %bighash;
 5794:     my $okay=0;
 5795: 
 5796:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5797:                             &GDBM_READER(),0640)) {
 5798:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 5799:         unless ($ids) { 
 5800:            $ids=$bighash{'ids_/'.$thisurl};
 5801:         }
 5802:         if ($ids) {
 5803: # ------------------------------------------------------------------- Has ID(s)
 5804: 	    foreach (split(/\,/,$ids)) {
 5805: 	       my ($mapid,$resid)=split(/\./,$_);
 5806:                if (
 5807:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 5808:    eq $symb) { 
 5809: 		   if (($env{'request.role.adv'}) ||
 5810: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 5811: 		       $okay=1; 
 5812: 		   }
 5813: 	       }
 5814: 	   }
 5815:         }
 5816: 	untie(%bighash);
 5817:     }
 5818:     return $okay;
 5819: }
 5820: 
 5821: # --------------------------------------------------------------- Clean-up symb
 5822: 
 5823: sub symbclean {
 5824:     my $symb=shift;
 5825:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5826: # remove version from map
 5827:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 5828: 
 5829: # remove version from URL
 5830:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 5831: 
 5832: # remove wrapper
 5833: 
 5834:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 5835:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 5836:     return $symb;
 5837: }
 5838: 
 5839: # ---------------------------------------------- Split symb to find map and url
 5840: 
 5841: sub encode_symb {
 5842:     my ($map,$resid,$url)=@_;
 5843:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 5844: }
 5845: 
 5846: sub decode_symb {
 5847:     my $symb=shift;
 5848:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5849:     my ($map,$resid,$url)=split(/___/,$symb);
 5850:     return (&fixversion($map),$resid,&fixversion($url));
 5851: }
 5852: 
 5853: sub fixversion {
 5854:     my $fn=shift;
 5855:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 5856:     my %bighash;
 5857:     my $uri=&clutter($fn);
 5858:     my $key=$env{'request.course.id'}.'_'.$uri;
 5859: # is this cached?
 5860:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 5861:     if (defined($cached)) { return $result; }
 5862: # unfortunately not cached, or expired
 5863:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5864: 	    &GDBM_READER(),0640)) {
 5865:  	if ($bighash{'version_'.$uri}) {
 5866:  	    my $version=$bighash{'version_'.$uri};
 5867:  	    unless (($version eq 'mostrecent') || 
 5868: 		    ($version==&getversion($uri))) {
 5869:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 5870:  	    }
 5871:  	}
 5872:  	untie %bighash;
 5873:     }
 5874:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 5875: }
 5876: 
 5877: sub deversion {
 5878:     my $url=shift;
 5879:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 5880:     return $url;
 5881: }
 5882: 
 5883: # ------------------------------------------------------ Return symb list entry
 5884: 
 5885: sub symbread {
 5886:     my ($thisfn,$donotrecurse)=@_;
 5887:     my $cache_str='request.symbread.cached.'.$thisfn;
 5888:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 5889: # no filename provided? try from environment
 5890:     unless ($thisfn) {
 5891:         if ($env{'request.symb'}) {
 5892: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 5893: 	}
 5894: 	$thisfn=$env{'request.filename'};
 5895:     }
 5896:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5897: # is that filename actually a symb? Verify, clean, and return
 5898:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 5899: 	if (&symbverify($thisfn,$1)) {
 5900: 	    return $env{$cache_str}=&symbclean($thisfn);
 5901: 	}
 5902:     }
 5903:     $thisfn=declutter($thisfn);
 5904:     my %hash;
 5905:     my %bighash;
 5906:     my $syval='';
 5907:     if (($env{'request.course.fn'}) && ($thisfn)) {
 5908:         my $targetfn = $thisfn;
 5909:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 5910:             $targetfn = 'adm/wrapper/'.$thisfn;
 5911:         }
 5912: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 5913: 	    $targetfn=$1;
 5914: 	}
 5915:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5916:                       &GDBM_READER(),0640)) {
 5917: 	    $syval=$hash{$targetfn};
 5918:             untie(%hash);
 5919:         }
 5920: # ---------------------------------------------------------- There was an entry
 5921:         if ($syval) {
 5922: 	    #unless ($syval=~/\_\d+$/) {
 5923: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 5924: 		    #&appenv('request.ambiguous' => $thisfn);
 5925: 		    #return $env{$cache_str}='';
 5926: 		#}    
 5927: 		#$syval.=$1;
 5928: 	    #}
 5929:         } else {
 5930: # ------------------------------------------------------- Was not in symb table
 5931:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5932:                             &GDBM_READER(),0640)) {
 5933: # ---------------------------------------------- Get ID(s) for current resource
 5934:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 5935:               unless ($ids) { 
 5936:                  $ids=$bighash{'ids_/'.$thisfn};
 5937:               }
 5938:               unless ($ids) {
 5939: # alias?
 5940: 		  $ids=$bighash{'mapalias_'.$thisfn};
 5941:               }
 5942:               if ($ids) {
 5943: # ------------------------------------------------------------------- Has ID(s)
 5944:                  my @possibilities=split(/\,/,$ids);
 5945:                  if ($#possibilities==0) {
 5946: # ----------------------------------------------- There is only one possibility
 5947: 		     my ($mapid,$resid)=split(/\./,$ids);
 5948: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5949: 						    $resid,$thisfn);
 5950:                  } elsif (!$donotrecurse) {
 5951: # ------------------------------------------ There is more than one possibility
 5952:                      my $realpossible=0;
 5953:                      foreach (@possibilities) {
 5954: 			 my $file=$bighash{'src_'.$_};
 5955:                          if (&allowed('bre',$file)) {
 5956:          		    my ($mapid,$resid)=split(/\./,$_);
 5957:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 5958: 				$realpossible++;
 5959:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5960: 						    $resid,$thisfn);
 5961:                             }
 5962: 			 }
 5963:                      }
 5964: 		     if ($realpossible!=1) { $syval=''; }
 5965:                  } else {
 5966:                      $syval='';
 5967:                  }
 5968: 	      }
 5969:               untie(%bighash)
 5970:            }
 5971:         }
 5972:         if ($syval) {
 5973: 	    return $env{$cache_str}=$syval;
 5974:         }
 5975:     }
 5976:     &appenv('request.ambiguous' => $thisfn);
 5977:     return $env{$cache_str}='';
 5978: }
 5979: 
 5980: # ---------------------------------------------------------- Return random seed
 5981: 
 5982: sub numval {
 5983:     my $txt=shift;
 5984:     $txt=~tr/A-J/0-9/;
 5985:     $txt=~tr/a-j/0-9/;
 5986:     $txt=~tr/K-T/0-9/;
 5987:     $txt=~tr/k-t/0-9/;
 5988:     $txt=~tr/U-Z/0-5/;
 5989:     $txt=~tr/u-z/0-5/;
 5990:     $txt=~s/\D//g;
 5991:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 5992:     return int($txt);
 5993: }
 5994: 
 5995: sub numval2 {
 5996:     my $txt=shift;
 5997:     $txt=~tr/A-J/0-9/;
 5998:     $txt=~tr/a-j/0-9/;
 5999:     $txt=~tr/K-T/0-9/;
 6000:     $txt=~tr/k-t/0-9/;
 6001:     $txt=~tr/U-Z/0-5/;
 6002:     $txt=~tr/u-z/0-5/;
 6003:     $txt=~s/\D//g;
 6004:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6005:     my $total;
 6006:     foreach my $val (@txts) { $total+=$val; }
 6007:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6008:     return int($total);
 6009: }
 6010: 
 6011: sub numval3 {
 6012:     use integer;
 6013:     my $txt=shift;
 6014:     $txt=~tr/A-J/0-9/;
 6015:     $txt=~tr/a-j/0-9/;
 6016:     $txt=~tr/K-T/0-9/;
 6017:     $txt=~tr/k-t/0-9/;
 6018:     $txt=~tr/U-Z/0-5/;
 6019:     $txt=~tr/u-z/0-5/;
 6020:     $txt=~s/\D//g;
 6021:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6022:     my $total;
 6023:     foreach my $val (@txts) { $total+=$val; }
 6024:     if ($_64bit) { $total=(($total<<32)>>32); }
 6025:     return $total;
 6026: }
 6027: 
 6028: sub digest {
 6029:     my ($data)=@_;
 6030:     my $digest=&Digest::MD5::md5($data);
 6031:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6032:     my ($e,$f);
 6033:     {
 6034:         use integer;
 6035:         $e=($a+$b);
 6036:         $f=($c+$d);
 6037:         if ($_64bit) {
 6038:             $e=(($e<<32)>>32);
 6039:             $f=(($f<<32)>>32);
 6040:         }
 6041:     }
 6042:     if (wantarray) {
 6043: 	return ($e,$f);
 6044:     } else {
 6045: 	my $g;
 6046: 	{
 6047: 	    use integer;
 6048: 	    $g=($e+$f);
 6049: 	    if ($_64bit) {
 6050: 		$g=(($g<<32)>>32);
 6051: 	    }
 6052: 	}
 6053: 	return $g;
 6054:     }
 6055: }
 6056: 
 6057: sub latest_rnd_algorithm_id {
 6058:     return '64bit5';
 6059: }
 6060: 
 6061: sub get_rand_alg {
 6062:     my ($courseid)=@_;
 6063:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 6064:     if ($courseid) {
 6065: 	return $env{"course.$courseid.rndseed"};
 6066:     }
 6067:     return &latest_rnd_algorithm_id();
 6068: }
 6069: 
 6070: sub validCODE {
 6071:     my ($CODE)=@_;
 6072:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6073:     return 0;
 6074: }
 6075: 
 6076: sub getCODE {
 6077:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6078:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6079: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6080: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6081: 	return $Apache::lonhomework::history{'resource.CODE'};
 6082:     }
 6083:     return undef;
 6084: }
 6085: 
 6086: sub rndseed {
 6087:     my ($symb,$courseid,$domain,$username)=@_;
 6088: 
 6089:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 6090:     if (!$symb) {
 6091: 	unless ($symb=$wsymb) { return time; }
 6092:     }
 6093:     if (!$courseid) { $courseid=$wcourseid; }
 6094:     if (!$domain) { $domain=$wdomain; }
 6095:     if (!$username) { $username=$wusername }
 6096:     my $which=&get_rand_alg();
 6097:     if (defined(&getCODE())) {
 6098: 	if ($which eq '64bit5') {
 6099: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6100: 	} elsif ($which eq '64bit4') {
 6101: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6102: 	} else {
 6103: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6104: 	}
 6105:     } elsif ($which eq '64bit5') {
 6106: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6107:     } elsif ($which eq '64bit4') {
 6108: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6109:     } elsif ($which eq '64bit3') {
 6110: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6111:     } elsif ($which eq '64bit2') {
 6112: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6113:     } elsif ($which eq '64bit') {
 6114: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6115:     }
 6116:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6117: }
 6118: 
 6119: sub rndseed_32bit {
 6120:     my ($symb,$courseid,$domain,$username)=@_;
 6121:     {
 6122: 	use integer;
 6123: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6124: 	my $symbseed=numval($symb) << 22;
 6125: 	my $namechck=unpack("%32C*",$username) << 17;
 6126: 	my $nameseed=numval($username) << 12;
 6127: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6128: 	my $courseseed=unpack("%32C*",$courseid);
 6129: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6130: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6131: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6132: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6133: 	return $num;
 6134:     }
 6135: }
 6136: 
 6137: sub rndseed_64bit {
 6138:     my ($symb,$courseid,$domain,$username)=@_;
 6139:     {
 6140: 	use integer;
 6141: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6142: 	my $symbseed=numval($symb) << 10;
 6143: 	my $namechck=unpack("%32S*",$username);
 6144: 	
 6145: 	my $nameseed=numval($username) << 21;
 6146: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6147: 	my $courseseed=unpack("%32S*",$courseid);
 6148: 	
 6149: 	my $num1=$symbchck+$symbseed+$namechck;
 6150: 	my $num2=$nameseed+$domainseed+$courseseed;
 6151: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6152: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6153: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6154: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6155: 	return "$num1,$num2";
 6156:     }
 6157: }
 6158: 
 6159: sub rndseed_64bit2 {
 6160:     my ($symb,$courseid,$domain,$username)=@_;
 6161:     {
 6162: 	use integer;
 6163: 	# strings need to be an even # of cahracters long, it it is odd the
 6164:         # last characters gets thrown away
 6165: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6166: 	my $symbseed=numval($symb) << 10;
 6167: 	my $namechck=unpack("%32S*",$username.' ');
 6168: 	
 6169: 	my $nameseed=numval($username) << 21;
 6170: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6171: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6172: 	
 6173: 	my $num1=$symbchck+$symbseed+$namechck;
 6174: 	my $num2=$nameseed+$domainseed+$courseseed;
 6175: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6176: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6177: 	return "$num1,$num2";
 6178:     }
 6179: }
 6180: 
 6181: sub rndseed_64bit3 {
 6182:     my ($symb,$courseid,$domain,$username)=@_;
 6183:     {
 6184: 	use integer;
 6185: 	# strings need to be an even # of cahracters long, it it is odd the
 6186:         # last characters gets thrown away
 6187: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6188: 	my $symbseed=numval2($symb) << 10;
 6189: 	my $namechck=unpack("%32S*",$username.' ');
 6190: 	
 6191: 	my $nameseed=numval2($username) << 21;
 6192: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6193: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6194: 	
 6195: 	my $num1=$symbchck+$symbseed+$namechck;
 6196: 	my $num2=$nameseed+$domainseed+$courseseed;
 6197: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6198: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6199: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6200: 	
 6201: 	return "$num1:$num2";
 6202:     }
 6203: }
 6204: 
 6205: sub rndseed_64bit4 {
 6206:     my ($symb,$courseid,$domain,$username)=@_;
 6207:     {
 6208: 	use integer;
 6209: 	# strings need to be an even # of cahracters long, it it is odd the
 6210:         # last characters gets thrown away
 6211: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6212: 	my $symbseed=numval3($symb) << 10;
 6213: 	my $namechck=unpack("%32S*",$username.' ');
 6214: 	
 6215: 	my $nameseed=numval3($username) << 21;
 6216: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6217: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6218: 	
 6219: 	my $num1=$symbchck+$symbseed+$namechck;
 6220: 	my $num2=$nameseed+$domainseed+$courseseed;
 6221: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6222: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6223: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6224: 	
 6225: 	return "$num1:$num2";
 6226:     }
 6227: }
 6228: 
 6229: sub rndseed_64bit5 {
 6230:     my ($symb,$courseid,$domain,$username)=@_;
 6231:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6232:     return "$num1:$num2";
 6233: }
 6234: 
 6235: sub rndseed_CODE_64bit {
 6236:     my ($symb,$courseid,$domain,$username)=@_;
 6237:     {
 6238: 	use integer;
 6239: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6240: 	my $symbseed=numval2($symb);
 6241: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6242: 	my $CODEseed=numval(&getCODE());
 6243: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6244: 	my $num1=$symbseed+$CODEchck;
 6245: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6246: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6247: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6248: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6249: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6250: 	return "$num1:$num2";
 6251:     }
 6252: }
 6253: 
 6254: sub rndseed_CODE_64bit4 {
 6255:     my ($symb,$courseid,$domain,$username)=@_;
 6256:     {
 6257: 	use integer;
 6258: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6259: 	my $symbseed=numval3($symb);
 6260: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6261: 	my $CODEseed=numval3(&getCODE());
 6262: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6263: 	my $num1=$symbseed+$CODEchck;
 6264: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6265: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6266: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6267: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6268: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6269: 	return "$num1:$num2";
 6270:     }
 6271: }
 6272: 
 6273: sub rndseed_CODE_64bit5 {
 6274:     my ($symb,$courseid,$domain,$username)=@_;
 6275:     my $code = &getCODE();
 6276:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6277:     return "$num1:$num2";
 6278: }
 6279: 
 6280: sub setup_random_from_rndseed {
 6281:     my ($rndseed)=@_;
 6282:     if ($rndseed =~/([,:])/) {
 6283: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6284: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6285:     } else {
 6286: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6287:     }
 6288: }
 6289: 
 6290: sub latest_receipt_algorithm_id {
 6291:     return 'receipt2';
 6292: }
 6293: 
 6294: sub recunique {
 6295:     my $fucourseid=shift;
 6296:     my $unique;
 6297:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6298: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6299:     } else {
 6300: 	$unique=$perlvar{'lonReceipt'};
 6301:     }
 6302:     return unpack("%32C*",$unique);
 6303: }
 6304: 
 6305: sub recprefix {
 6306:     my $fucourseid=shift;
 6307:     my $prefix;
 6308:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6309: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6310:     } else {
 6311: 	$prefix=$perlvar{'lonHostID'};
 6312:     }
 6313:     return unpack("%32C*",$prefix);
 6314: }
 6315: 
 6316: sub ireceipt {
 6317:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6318:     my $cuname=unpack("%32C*",$funame);
 6319:     my $cudom=unpack("%32C*",$fudom);
 6320:     my $cucourseid=unpack("%32C*",$fucourseid);
 6321:     my $cusymb=unpack("%32C*",$fusymb);
 6322:     my $cunique=&recunique($fucourseid);
 6323:     my $cpart=unpack("%32S*",$part);
 6324:     my $return =&recprefix($fucourseid).'-';
 6325:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6326: 	$env{'request.state'} eq 'construct') {
 6327: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6328: 			       " and ".($cpart%$cudom));
 6329: 			       
 6330: 	$return.= ($cunique%$cuname+
 6331: 		   $cunique%$cudom+
 6332: 		   $cusymb%$cuname+
 6333: 		   $cusymb%$cudom+
 6334: 		   $cucourseid%$cuname+
 6335: 		   $cucourseid%$cudom+
 6336: 		   $cpart%$cuname+
 6337: 		   $cpart%$cudom);
 6338:     } else {
 6339: 	$return.= ($cunique%$cuname+
 6340: 		   $cunique%$cudom+
 6341: 		   $cusymb%$cuname+
 6342: 		   $cusymb%$cudom+
 6343: 		   $cucourseid%$cuname+
 6344: 		   $cucourseid%$cudom);
 6345:     }
 6346:     return $return;
 6347: }
 6348: 
 6349: sub receipt {
 6350:     my ($part)=@_;
 6351:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6352:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6353: }
 6354: 
 6355: # ------------------------------------------------------------ Serves up a file
 6356: # returns either the contents of the file or 
 6357: # -1 if the file doesn't exist
 6358: #
 6359: # if the target is a file that was uploaded via DOCS, 
 6360: # a check will be made to see if a current copy exists on the local server,
 6361: # if it does this will be served, otherwise a copy will be retrieved from
 6362: # the home server for the course and stored in /home/httpd/html/userfiles on
 6363: # the local server.   
 6364: 
 6365: sub getfile {
 6366:     my ($file) = @_;
 6367:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6368:     &repcopy($file);
 6369:     return &readfile($file);
 6370: }
 6371: 
 6372: sub repcopy_userfile {
 6373:     my ($file)=@_;
 6374:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6375:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6376:     my ($cdom,$cnum,$filename) = 
 6377: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6378:     my ($info,$rtncode);
 6379:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6380:     if (-e "$file") {
 6381: 	my @fileinfo = stat($file);
 6382: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6383: 	if ($lwpresp ne 'ok') {
 6384: 	    if ($rtncode eq '404') {
 6385: 		unlink($file);
 6386: 	    }
 6387: 	    #my $ua=new LWP::UserAgent;
 6388: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6389: 	    #my $response=$ua->request($request);
 6390: 	    #if ($response->is_success()) {
 6391: 	#	return $response->content;
 6392: 	#    } else {
 6393: 	#	return -1;
 6394: 	#    }
 6395: 	    return -1;
 6396: 	}
 6397: 	if ($info < $fileinfo[9]) {
 6398: 	    return 'ok';
 6399: 	}
 6400: 	$info = '';
 6401: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6402: 	if ($lwpresp ne 'ok') {
 6403: 	    return -1;
 6404: 	}
 6405:     } else {
 6406: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6407: 	if ($lwpresp ne 'ok') {
 6408: 	    my $ua=new LWP::UserAgent;
 6409: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6410: 	    my $response=$ua->request($request);
 6411: 	    if ($response->is_success()) {
 6412: 		$info=$response->content;
 6413: 	    } else {
 6414: 		return -1;
 6415: 	    }
 6416: 	}
 6417: 	my @parts = ($cdom,$cnum); 
 6418: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6419: 	    push @parts, split(/\//,$1);
 6420: 	}
 6421: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6422: 	foreach my $part (@parts) {
 6423: 	    $path .= '/'.$part;
 6424: 	    if (!-e $path) {
 6425: 		mkdir($path,0770);
 6426: 	    }
 6427: 	}
 6428:     }
 6429:     open(FILE,">$file");
 6430:     print FILE $info;
 6431:     close(FILE);
 6432:     return 'ok';
 6433: }
 6434: 
 6435: sub tokenwrapper {
 6436:     my $uri=shift;
 6437:     $uri=~s|^http\://([^/]+)||;
 6438:     $uri=~s|^/||;
 6439:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6440:     my $token=$1;
 6441:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6442:     if ($udom && $uname && $file) {
 6443: 	$file=~s|(\?\.*)*$||;
 6444:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6445:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6446:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6447:                                '&tokenissued='.$perlvar{'lonHostID'};
 6448:     } else {
 6449:         return '/adm/notfound.html';
 6450:     }
 6451: }
 6452: 
 6453: sub getuploaded {
 6454:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6455:     $uri=~s/^\///;
 6456:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6457:     my $ua=new LWP::UserAgent;
 6458:     my $request=new HTTP::Request($reqtype,$uri);
 6459:     my $response=$ua->request($request);
 6460:     $$rtncode = $response->code;
 6461:     if (! $response->is_success()) {
 6462: 	return 'failed';
 6463:     }      
 6464:     if ($reqtype eq 'HEAD') {
 6465: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6466:     } elsif ($reqtype eq 'GET') {
 6467: 	$$info = $response->content;
 6468:     }
 6469:     return 'ok';
 6470: }
 6471: 
 6472: sub readfile {
 6473:     my $file = shift;
 6474:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6475:     my $fh;
 6476:     open($fh,"<$file");
 6477:     my $a='';
 6478:     while (<$fh>) { $a .=$_; }
 6479:     return $a;
 6480: }
 6481: 
 6482: sub filelocation {
 6483:     my ($dir,$file) = @_;
 6484:     my $location;
 6485:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6486: 
 6487:     if ($file =~ m-^/adm/-) {
 6488: 	$file=~s-^/adm/wrapper/-/-;
 6489: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6490:     }
 6491:     if ($file=~m:^/~:) { # is a contruction space reference
 6492:         $location = $file;
 6493:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6494:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6495: 	# is a correct contruction space reference
 6496:         $location = $file;
 6497:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6498:         my ($udom,$uname,$filename)=
 6499:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6500:         my $home=&homeserver($uname,$udom);
 6501:         my $is_me=0;
 6502:         my @ids=&current_machine_ids();
 6503:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6504:         if ($is_me) {
 6505:   	    $location=&propath($udom,$uname).
 6506:   	      '/userfiles/'.$filename;
 6507:         } else {
 6508:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6509:   	      $udom.'/'.$uname.'/'.$filename;
 6510:         }
 6511:     } else {
 6512:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6513:         $file=~s:^/res/:/:;
 6514:         if ( !( $file =~ m:^/:) ) {
 6515:             $location = $dir. '/'.$file;
 6516:         } else {
 6517:             $location = '/home/httpd/html/res'.$file;
 6518:         }
 6519:     }
 6520:     $location=~s://+:/:g; # remove duplicate /
 6521:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6522:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6523:     return $location;
 6524: }
 6525: 
 6526: sub hreflocation {
 6527:     my ($dir,$file)=@_;
 6528:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6529: 	$file=filelocation($dir,$file);
 6530:     } elsif ($file=~m-^/adm/-) {
 6531: 	$file=~s-^/adm/wrapper/-/-;
 6532: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6533:     }
 6534:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6535: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6536:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6537: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6538:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6539: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6540: 	    -/uploaded/$1/$2/-x;
 6541:     }
 6542:     return $file;
 6543: }
 6544: 
 6545: sub current_machine_domains {
 6546:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6547:     my @domains;
 6548:     while( my($id, $name) = each(%hostname)) {
 6549: #	&logthis("-$id-$name-$hostname-");
 6550: 	if ($hostname eq $name) {
 6551: 	    push(@domains,$hostdom{$id});
 6552: 	}
 6553:     }
 6554:     return @domains;
 6555: }
 6556: 
 6557: sub current_machine_ids {
 6558:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6559:     my @ids;
 6560:     while( my($id, $name) = each(%hostname)) {
 6561: #	&logthis("-$id-$name-$hostname-");
 6562: 	if ($hostname eq $name) {
 6563: 	    push(@ids,$id);
 6564: 	}
 6565:     }
 6566:     return @ids;
 6567: }
 6568: 
 6569: # ------------------------------------------------------------- Declutters URLs
 6570: 
 6571: sub declutter {
 6572:     my $thisfn=shift;
 6573:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6574:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6575:     $thisfn=~s/^\///;
 6576:     $thisfn=~s|^adm/wrapper/||;
 6577:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 6578:     $thisfn=~s/^res\///;
 6579:     $thisfn=~s/\?.+$//;
 6580:     return $thisfn;
 6581: }
 6582: 
 6583: # ------------------------------------------------------------- Clutter up URLs
 6584: 
 6585: sub clutter {
 6586:     my $thisfn='/'.&declutter(shift);
 6587:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 6588:        $thisfn='/res'.$thisfn; 
 6589:     }
 6590:     if ($thisfn !~m|/adm|) {
 6591: 	if ($thisfn =~ m|/ext/|) {
 6592: 	    $thisfn='/adm/wrapper'.$thisfn;
 6593: 	} else {
 6594: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 6595: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 6596: 	    if ($embstyle eq 'ssi'
 6597: 		|| ($embstyle eq 'hdn')
 6598: 		|| ($embstyle eq 'rat')
 6599: 		|| ($embstyle eq 'prv')
 6600: 		|| ($embstyle eq 'ign')) {
 6601: 		#do nothing with these
 6602: 	    } elsif (($embstyle eq 'img') 
 6603: 		|| ($embstyle eq 'emb')
 6604: 		|| ($embstyle eq 'wrp')) {
 6605: 		$thisfn='/adm/wrapper'.$thisfn;
 6606: 	    } elsif ($embstyle eq 'unk'
 6607: 		     && $thisfn!~/\.(sequence|page)$/) {
 6608: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 6609: 	    } else {
 6610: #		&logthis("Got a blank emb style");
 6611: 	    }
 6612: 	}
 6613:     }
 6614:     return $thisfn;
 6615: }
 6616: 
 6617: sub freeze_escape {
 6618:     my ($value)=@_;
 6619:     if (ref($value)) {
 6620: 	$value=&nfreeze($value);
 6621: 	return '__FROZEN__'.&escape($value);
 6622:     }
 6623:     return &escape($value);
 6624: }
 6625: 
 6626: 
 6627: sub thaw_unescape {
 6628:     my ($value)=@_;
 6629:     if ($value =~ /^__FROZEN__/) {
 6630: 	substr($value,0,10,undef);
 6631: 	$value=&unescape($value);
 6632: 	return &thaw($value);
 6633:     }
 6634:     return &unescape($value);
 6635: }
 6636: 
 6637: sub correct_line_ends {
 6638:     my ($result)=@_;
 6639:     $$result =~s/\r\n/\n/mg;
 6640:     $$result =~s/\r/\n/mg;
 6641: }
 6642: # ================================================================ Main Program
 6643: 
 6644: sub goodbye {
 6645:    &logthis("Starting Shut down");
 6646: #not converted to using infrastruture and probably shouldn't be
 6647:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 6648: #converted
 6649: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 6650:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 6651: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 6652: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 6653: #1.1 only
 6654: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 6655: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 6656: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 6657: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 6658:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 6659:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 6660:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 6661:    &flushcourselogs();
 6662:    &logthis("Shutting down");
 6663: }
 6664: 
 6665: BEGIN {
 6666: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 6667:     unless ($readit) {
 6668: {
 6669:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 6670:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 6671: 
 6672:     while (my $configline=<$config>) {
 6673:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 6674: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6675:            chomp($varvalue);
 6676:            $perlvar{$varname}=$varvalue;
 6677:         }
 6678:     }
 6679:     close($config);
 6680: }
 6681: {
 6682:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 6683: 
 6684:     while (my $configline=<$config>) {
 6685:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 6686: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6687:            chomp($varvalue);
 6688:            $perlvar{$varname}=$varvalue;
 6689:         }
 6690:     }
 6691:     close($config);
 6692: }
 6693: 
 6694: # ------------------------------------------------------------ Read domain file
 6695: {
 6696:     %domaindescription = ();
 6697:     %domain_auth_def = ();
 6698:     %domain_auth_arg_def = ();
 6699:     my $fh;
 6700:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 6701:        while (<$fh>) {
 6702:            next if (/^(\#|\s*$)/);
 6703: #           next if /^\#/;
 6704:            chomp;
 6705:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 6706: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 6707: 	   $domain_auth_def{$domain}=$def_auth;
 6708:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 6709: 	   $domaindescription{$domain}=$domain_description;
 6710: 	   $domain_lang_def{$domain}=$def_lang;
 6711: 	   $domain_city{$domain}=$city;
 6712: 	   $domain_longi{$domain}=$longi;
 6713: 	   $domain_lati{$domain}=$lati;
 6714:            $domain_primary{$domain}=$primary;
 6715: 
 6716:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 6717: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 6718: 	}
 6719:     }
 6720:     close ($fh);
 6721: }
 6722: 
 6723: 
 6724: # ------------------------------------------------------------- Read hosts file
 6725: {
 6726:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 6727: 
 6728:     while (my $configline=<$config>) {
 6729:        next if ($configline =~ /^(\#|\s*$)/);
 6730:        chomp($configline);
 6731:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 6732:        $name=~s/\s//g;
 6733:        if ($id && $domain && $role && $name) {
 6734: 	 $hostname{$id}=$name;
 6735: 	 $hostdom{$id}=$domain;
 6736: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 6737:        }
 6738:     }
 6739:     close($config);
 6740:     # FIXME: dev server don't want this, production servers _do_ want this
 6741:     #&get_iphost();
 6742: }
 6743: 
 6744: sub get_iphost {
 6745:     if (%iphost) { return %iphost; }
 6746:     my %name_to_ip;
 6747:     foreach my $id (keys(%hostname)) {
 6748: 	my $name=$hostname{$id};
 6749: 	my $ip;
 6750: 	if (!exists($name_to_ip{$name})) {
 6751: 	    $ip = gethostbyname($name);
 6752: 	    if (!$ip || length($ip) ne 4) {
 6753: 		&logthis("Skipping host $id name $name no IP found\n");
 6754: 		next;
 6755: 	    }
 6756: 	    $ip=inet_ntoa($ip);
 6757: 	    $name_to_ip{$name} = $ip;
 6758: 	} else {
 6759: 	    $ip = $name_to_ip{$name};
 6760: 	}
 6761: 	push(@{$iphost{$ip}},$id);
 6762:     }
 6763:     return %iphost;
 6764: }
 6765: 
 6766: # ------------------------------------------------------ Read spare server file
 6767: {
 6768:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 6769: 
 6770:     while (my $configline=<$config>) {
 6771:        chomp($configline);
 6772:        if ($configline) {
 6773:           $spareid{$configline}=1;
 6774:        }
 6775:     }
 6776:     close($config);
 6777: }
 6778: # ------------------------------------------------------------ Read permissions
 6779: {
 6780:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 6781: 
 6782:     while (my $configline=<$config>) {
 6783: 	chomp($configline);
 6784: 	if ($configline) {
 6785: 	    my ($role,$perm)=split(/ /,$configline);
 6786: 	    if ($perm ne '') { $pr{$role}=$perm; }
 6787: 	}
 6788:     }
 6789:     close($config);
 6790: }
 6791: 
 6792: # -------------------------------------------- Read plain texts for permissions
 6793: {
 6794:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 6795: 
 6796:     while (my $configline=<$config>) {
 6797: 	chomp($configline);
 6798: 	if ($configline) {
 6799: 	    my ($short,@plain)=split(/:/,$configline);
 6800:             %{$prp{$short}} = ();
 6801: 	    if (@plain > 0) {
 6802:                 $prp{$short}{'std'} = $plain[0];
 6803:                 for (my $i=1; $i<@plain; $i++) {
 6804:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 6805:                 }
 6806:             }
 6807: 	}
 6808:     }
 6809:     close($config);
 6810: }
 6811: 
 6812: # ---------------------------------------------------------- Read package table
 6813: {
 6814:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 6815: 
 6816:     while (my $configline=<$config>) {
 6817: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 6818: 	chomp($configline);
 6819: 	my ($short,$plain)=split(/:/,$configline);
 6820: 	my ($pack,$name)=split(/\&/,$short);
 6821: 	if ($plain ne '') {
 6822: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 6823: 	    $packagetab{$short}=$plain; 
 6824: 	}
 6825:     }
 6826:     close($config);
 6827: }
 6828: 
 6829: # ------------- set up temporary directory
 6830: {
 6831:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 6832: 
 6833: }
 6834: 
 6835: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 6836: 
 6837: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 6838: $dumpcount=0;
 6839: 
 6840: &logtouch();
 6841: &logthis('<font color="yellow">INFO: Read configuration</font>');
 6842: $readit=1;
 6843:     {
 6844: 	use integer;
 6845: 	my $test=(2**32)+1;
 6846: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 6847: 	&logthis(" Detected 64bit platform ($_64bit)");
 6848:     }
 6849: }
 6850: }
 6851: 
 6852: 1;
 6853: __END__
 6854: 
 6855: =pod
 6856: 
 6857: =head1 NAME
 6858: 
 6859: Apache::lonnet - Subroutines to ask questions about things in the network.
 6860: 
 6861: =head1 SYNOPSIS
 6862: 
 6863: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 6864: 
 6865:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 6866: 
 6867: Common parameters:
 6868: 
 6869: =over 4
 6870: 
 6871: =item *
 6872: 
 6873: $uname : an internal username (if $cname expecting a course Id specifically)
 6874: 
 6875: =item *
 6876: 
 6877: $udom : a domain (if $cdom expecting a course's domain specifically)
 6878: 
 6879: =item *
 6880: 
 6881: $symb : a resource instance identifier
 6882: 
 6883: =item *
 6884: 
 6885: $namespace : the name of a .db file that contains the data needed or
 6886: being set.
 6887: 
 6888: =back
 6889: 
 6890: =head1 OVERVIEW
 6891: 
 6892: lonnet provides subroutines which interact with the
 6893: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 6894: about classes, users, and resources.
 6895: 
 6896: For many of these objects you can also use this to store data about
 6897: them or modify them in various ways.
 6898: 
 6899: =head2 Symbs
 6900: 
 6901: To identify a specific instance of a resource, LON-CAPA uses symbols
 6902: or "symbs"X<symb>. These identifiers are built from the URL of the
 6903: map, the resource number of the resource in the map, and the URL of
 6904: the resource itself. The latter is somewhat redundant, but might help
 6905: if maps change.
 6906: 
 6907: An example is
 6908: 
 6909:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 6910: 
 6911: The respective map entry is
 6912: 
 6913:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 6914:   title="Problem 2">
 6915:  </resource>
 6916: 
 6917: Symbs are used by the random number generator, as well as to store and
 6918: restore data specific to a certain instance of for example a problem.
 6919: 
 6920: =head2 Storing And Retrieving Data
 6921: 
 6922: X<store()>X<cstore()>X<restore()>Three of the most important functions
 6923: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 6924: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 6925: is is the non-critical message twin of cstore. These functions are for
 6926: handlers to store a perl hash to a user's permanent data space in an
 6927: easy manner, and to retrieve it again on another call. It is expected
 6928: that a handler would use this once at the beginning to retrieve data,
 6929: and then again once at the end to send only the new data back.
 6930: 
 6931: The data is stored in the user's data directory on the user's
 6932: homeserver under the ID of the course.
 6933: 
 6934: The hash that is returned by restore will have all of the previous
 6935: value for all of the elements of the hash.
 6936: 
 6937: Example:
 6938: 
 6939:  #creating a hash
 6940:  my %hash;
 6941:  $hash{'foo'}='bar';
 6942: 
 6943:  #storing it
 6944:  &Apache::lonnet::cstore(\%hash);
 6945: 
 6946:  #changing a value
 6947:  $hash{'foo'}='notbar';
 6948: 
 6949:  #adding a new value
 6950:  $hash{'bar'}='foo';
 6951:  &Apache::lonnet::cstore(\%hash);
 6952: 
 6953:  #retrieving the hash
 6954:  my %history=&Apache::lonnet::restore();
 6955: 
 6956:  #print the hash
 6957:  foreach my $key (sort(keys(%history))) {
 6958:    print("\%history{$key} = $history{$key}");
 6959:  }
 6960: 
 6961: Will print out:
 6962: 
 6963:  %history{1:foo} = bar
 6964:  %history{1:keys} = foo:timestamp
 6965:  %history{1:timestamp} = 990455579
 6966:  %history{2:bar} = foo
 6967:  %history{2:foo} = notbar
 6968:  %history{2:keys} = foo:bar:timestamp
 6969:  %history{2:timestamp} = 990455580
 6970:  %history{bar} = foo
 6971:  %history{foo} = notbar
 6972:  %history{timestamp} = 990455580
 6973:  %history{version} = 2
 6974: 
 6975: Note that the special hash entries C<keys>, C<version> and
 6976: C<timestamp> were added to the hash. C<version> will be equal to the
 6977: total number of versions of the data that have been stored. The
 6978: C<timestamp> attribute will be the UNIX time the hash was
 6979: stored. C<keys> is available in every historical section to list which
 6980: keys were added or changed at a specific historical revision of a
 6981: hash.
 6982: 
 6983: B<Warning>: do not store the hash that restore returns directly. This
 6984: will cause a mess since it will restore the historical keys as if the
 6985: were new keys. I.E. 1:foo will become 1:1:foo etc.
 6986: 
 6987: Calling convention:
 6988: 
 6989:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 6990:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 6991: 
 6992: For more detailed information, see lonnet specific documentation.
 6993: 
 6994: =head1 RETURN MESSAGES
 6995: 
 6996: =over 4
 6997: 
 6998: =item * B<con_lost>: unable to contact remote host
 6999: 
 7000: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7001: when the connection is brought back up
 7002: 
 7003: =item * B<con_failed>: unable to contact remote host and unable to save message
 7004: for later delivery
 7005: 
 7006: =item * B<error:>: an error a occured, a description of the error follows the :
 7007: 
 7008: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7009: that was requested
 7010: 
 7011: =back
 7012: 
 7013: =head1 PUBLIC SUBROUTINES
 7014: 
 7015: =head2 Session Environment Functions
 7016: 
 7017: =over 4
 7018: 
 7019: =item * 
 7020: X<appenv()>
 7021: B<appenv(%hash)>: the value of %hash is written to
 7022: the user envirnoment file, and will be restored for each access this
 7023: user makes during this session, also modifies the %env for the current
 7024: process
 7025: 
 7026: =item *
 7027: X<delenv()>
 7028: B<delenv($regexp)>: removes all items from the session
 7029: environment file that matches the regular expression in $regexp. The
 7030: values are also delted from the current processes %env.
 7031: 
 7032: =back
 7033: 
 7034: =head2 User Information
 7035: 
 7036: =over 4
 7037: 
 7038: =item *
 7039: X<queryauthenticate()>
 7040: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7041: authentication scheme
 7042: 
 7043: =item *
 7044: X<authenticate()>
 7045: B<authenticate($uname,$upass,$udom)>: try to
 7046: authenticate user from domain's lib servers (first use the current
 7047: one). C<$upass> should be the users password.
 7048: 
 7049: =item *
 7050: X<homeserver()>
 7051: B<homeserver($uname,$udom)>: find the server which has
 7052: the user's directory and files (there must be only one), this caches
 7053: the answer, and also caches if there is a borken connection.
 7054: 
 7055: =item *
 7056: X<idget()>
 7057: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7058: (IDs are a unique resource in a domain, there must be only 1 ID per
 7059: username, and only 1 username per ID in a specific domain) (returns
 7060: hash: id=>name,id=>name)
 7061: 
 7062: =item *
 7063: X<idrget()>
 7064: B<idrget($udom,@unames)>: find the IDs behind a list of
 7065: usernames (returns hash: name=>id,name=>id)
 7066: 
 7067: =item *
 7068: X<idput()>
 7069: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7070: 
 7071: =item *
 7072: X<rolesinit()>
 7073: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7074: 
 7075: =item *
 7076: X<getsection()>
 7077: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7078: course $cname, return section name/number or '' for "not in course"
 7079: and '-1' for "no section"
 7080: 
 7081: =item *
 7082: X<userenvironment()>
 7083: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7084: passed in @what from the requested user's environment, returns a hash
 7085: 
 7086: =back
 7087: 
 7088: =head2 User Roles
 7089: 
 7090: =over 4
 7091: 
 7092: =item *
 7093: 
 7094: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7095: actions
 7096:  F: full access
 7097:  U,I,K: authentication modes (cxx only)
 7098:  '': forbidden
 7099:  1: user needs to choose course
 7100:  2: browse allowed
 7101: 
 7102: =item *
 7103: 
 7104: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7105: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7106: and course level
 7107: 
 7108: =item *
 7109: 
 7110: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7111: explanation of a user role term
 7112: 
 7113: =back
 7114: 
 7115: =head2 User Modification
 7116: 
 7117: =over 4
 7118: 
 7119: =item *
 7120: 
 7121: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7122: user for the level given by URL.  Optional start and end dates (leave empty
 7123: string or zero for "no date")
 7124: 
 7125: =item *
 7126: 
 7127: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7128: change a users, password, possible return values are: ok,
 7129: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7130: refused
 7131: 
 7132: =item *
 7133: 
 7134: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7135: 
 7136: =item *
 7137: 
 7138: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7139: modify user
 7140: 
 7141: =item *
 7142: 
 7143: modifystudent
 7144: 
 7145: modify a students enrollment and identification information.
 7146: The course id is resolved based on the current users environment.  
 7147: This means the envoking user must be a course coordinator or otherwise
 7148: associated with a course.
 7149: 
 7150: This call is essentially a wrapper for lonnet::modifyuser and
 7151: lonnet::modify_student_enrollment
 7152: 
 7153: Inputs: 
 7154: 
 7155: =over 4
 7156: 
 7157: =item B<$udom> Students loncapa domain
 7158: 
 7159: =item B<$uname> Students loncapa login name
 7160: 
 7161: =item B<$uid> Students id/student number
 7162: 
 7163: =item B<$umode> Students authentication mode
 7164: 
 7165: =item B<$upass> Students password
 7166: 
 7167: =item B<$first> Students first name
 7168: 
 7169: =item B<$middle> Students middle name
 7170: 
 7171: =item B<$last> Students last name
 7172: 
 7173: =item B<$gene> Students generation
 7174: 
 7175: =item B<$usec> Students section in course
 7176: 
 7177: =item B<$end> Unix time of the roles expiration
 7178: 
 7179: =item B<$start> Unix time of the roles start date
 7180: 
 7181: =item B<$forceid> If defined, allow $uid to be changed
 7182: 
 7183: =item B<$desiredhome> server to use as home server for student
 7184: 
 7185: =back
 7186: 
 7187: =item *
 7188: 
 7189: modify_student_enrollment
 7190: 
 7191: Change a students enrollment status in a class.  The environment variable
 7192: 'role.request.course' must be defined for this function to proceed.
 7193: 
 7194: Inputs:
 7195: 
 7196: =over 4
 7197: 
 7198: =item $udom, students domain
 7199: 
 7200: =item $uname, students name
 7201: 
 7202: =item $uid, students user id
 7203: 
 7204: =item $first, students first name
 7205: 
 7206: =item $middle
 7207: 
 7208: =item $last
 7209: 
 7210: =item $gene
 7211: 
 7212: =item $usec
 7213: 
 7214: =item $end
 7215: 
 7216: =item $start
 7217: 
 7218: =back
 7219: 
 7220: 
 7221: =item *
 7222: 
 7223: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7224: custom role; give a custom role to a user for the level given by URL.  Specify
 7225: name and domain of role author, and role name
 7226: 
 7227: =item *
 7228: 
 7229: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7230: 
 7231: =item *
 7232: 
 7233: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7234: 
 7235: =back
 7236: 
 7237: =head2 Course Infomation
 7238: 
 7239: =over 4
 7240: 
 7241: =item *
 7242: 
 7243: coursedescription($courseid) : returns a hash of information about the
 7244: specified course id, including all environment settings for the
 7245: course, the description of the course will be in the hash under the
 7246: key 'description'
 7247: 
 7248: =item *
 7249: 
 7250: resdata($name,$domain,$type,@which) : request for current parameter
 7251: setting for a specific $type, where $type is either 'course' or 'user',
 7252: @what should be a list of parameters to ask about. This routine caches
 7253: answers for 5 minutes.
 7254: 
 7255: =back
 7256: 
 7257: =head2 Course Modification
 7258: 
 7259: =over 4
 7260: 
 7261: =item *
 7262: 
 7263: writecoursepref($courseid,%prefs) : write preferences (environment
 7264: database) for a course
 7265: 
 7266: =item *
 7267: 
 7268: createcourse($udom,$description,$url) : make/modify course
 7269: 
 7270: =back
 7271: 
 7272: =head2 Resource Subroutines
 7273: 
 7274: =over 4
 7275: 
 7276: =item *
 7277: 
 7278: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7279: 
 7280: =item *
 7281: 
 7282: repcopy($filename) : subscribes to the requested file, and attempts to
 7283: replicate from the owning library server, Might return
 7284: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7285: 'bad_request', also attempts to grab the metadata for the
 7286: resource. Expects the local filesystem pathname
 7287: (/home/httpd/html/res/....)
 7288: 
 7289: =back
 7290: 
 7291: =head2 Resource Information
 7292: 
 7293: =over 4
 7294: 
 7295: =item *
 7296: 
 7297: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7298: a vairety of different possible values, $varname should be a request
 7299: string, and the other parameters can be used to specify who and what
 7300: one is asking about.
 7301: 
 7302: Possible values for $varname are environment.lastname (or other item
 7303: from the envirnment hash), user.name (or someother aspect about the
 7304: user), resource.0.maxtries (or some other part and parameter of a
 7305: resource)
 7306: 
 7307: =item *
 7308: 
 7309: directcondval($number) : get current value of a condition; reads from a state
 7310: string
 7311: 
 7312: =item *
 7313: 
 7314: condval($condidx) : value of condition index based on state
 7315: 
 7316: =item *
 7317: 
 7318: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7319: resource's metadata, $what should be either a specific key, or either
 7320: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7321: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7322: 
 7323: this function automatically caches all requests
 7324: 
 7325: =item *
 7326: 
 7327: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7328: network of library servers; returns file handle of where SQL and regex results
 7329: will be stored for query
 7330: 
 7331: =item *
 7332: 
 7333: symbread($filename) : return symbolic list entry (filename argument optional);
 7334: returns the data handle
 7335: 
 7336: =item *
 7337: 
 7338: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7339: a possible symb for the URL in $thisfn, and if is an encryypted
 7340: resource that the user accessed using /enc/ returns a 1 on success, 0
 7341: on failure, user must be in a course, as it assumes the existance of
 7342: the course initial hash, and uses $env('request.course.id'}
 7343: 
 7344: 
 7345: =item *
 7346: 
 7347: symbclean($symb) : removes versions numbers from a symb, returns the
 7348: cleaned symb
 7349: 
 7350: =item *
 7351: 
 7352: is_on_map($uri) : checks if the $uri is somewhere on the current
 7353: course map, user must be in a course for it to work.
 7354: 
 7355: =item *
 7356: 
 7357: numval($salt) : return random seed value (addend for rndseed)
 7358: 
 7359: =item *
 7360: 
 7361: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7362: a random seed, all arguments are optional, if they aren't sent it uses the
 7363: environment to derive them. Note: if symb isn't sent and it can't get one
 7364: from &symbread it will use the current time as its return value
 7365: 
 7366: =item *
 7367: 
 7368: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7369: unfakeable, receipt
 7370: 
 7371: =item *
 7372: 
 7373: receipt() : API to ireceipt working off of env values; given out to users
 7374: 
 7375: =item *
 7376: 
 7377: countacc($url) : count the number of accesses to a given URL
 7378: 
 7379: =item *
 7380: 
 7381: 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
 7382: 
 7383: =item *
 7384: 
 7385: 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)
 7386: 
 7387: =item *
 7388: 
 7389: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7390: 
 7391: =item *
 7392: 
 7393: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7394: forcing spreadsheet to reevaluate the resource scores next time.
 7395: 
 7396: =back
 7397: 
 7398: =head2 Storing/Retreiving Data
 7399: 
 7400: =over 4
 7401: 
 7402: =item *
 7403: 
 7404: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7405: for this url; hashref needs to be given and should be a \%hashname; the
 7406: remaining args aren't required and if they aren't passed or are '' they will
 7407: be derived from the env
 7408: 
 7409: =item *
 7410: 
 7411: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7412: uses critical subroutine
 7413: 
 7414: =item *
 7415: 
 7416: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7417: all args are optional
 7418: 
 7419: =item *
 7420: 
 7421: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7422: dumps the complete (or key matching regexp) namespace into a hash
 7423: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7424: normally &store()ed into
 7425: 
 7426: $range should be either an integer '100' (give me the first 100
 7427:                                            matching records)
 7428:               or be  two integers sperated by a - with no spaces
 7429:                  '30-50' (give me the 30th through the 50th matching
 7430:                           records)
 7431: 
 7432: 
 7433: =item *
 7434: 
 7435: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7436: replaces a &store() version of data with a replacement set of data
 7437: for a particular resource in a namespace passed in the $storehash hash 
 7438: reference
 7439: 
 7440: =item *
 7441: 
 7442: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7443: works very similar to store/cstore, but all data is stored in a
 7444: temporary location and can be reset using tmpreset, $storehash should
 7445: be a hash reference, returns nothing on success
 7446: 
 7447: =item *
 7448: 
 7449: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7450: similar to restore, but all data is stored in a temporary location and
 7451: can be reset using tmpreset. Returns a hash of values on success,
 7452: error string otherwise.
 7453: 
 7454: =item *
 7455: 
 7456: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7457: deltes all keys for $symb form the temporary storage hash.
 7458: 
 7459: =item *
 7460: 
 7461: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7462: reference filled in from namesp ($udom and $uname are optional)
 7463: 
 7464: =item *
 7465: 
 7466: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7467: namesp ($udom and $uname are optional)
 7468: 
 7469: =item *
 7470: 
 7471: dump($namespace,$udom,$uname,$regexp,$range) : 
 7472: dumps the complete (or key matching regexp) namespace into a hash
 7473: ($udom, $uname, $regexp, $range are optional)
 7474: 
 7475: $range should be either an integer '100' (give me the first 100
 7476:                                            matching records)
 7477:               or be  two integers sperated by a - with no spaces
 7478:                  '30-50' (give me the 30th through the 50th matching
 7479:                           records)
 7480: =item *
 7481: 
 7482: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7483: $store can be a scalar, an array reference, or if the amount to be 
 7484: incremented is > 1, a hash reference.
 7485: 
 7486: ($udom and $uname are optional)
 7487: 
 7488: =item *
 7489: 
 7490: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7491: ($udom and $uname are optional)
 7492: 
 7493: =item *
 7494: 
 7495: cput($namespace,$storehash,$udom,$uname) : critical put
 7496: ($udom and $uname are optional)
 7497: 
 7498: =item *
 7499: 
 7500: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7501: reference filled in from namesp (encrypts the return communication)
 7502: ($udom and $uname are optional)
 7503: 
 7504: =item *
 7505: 
 7506: log($udom,$name,$home,$message) : write to permanent log for user; use
 7507: critical subroutine
 7508: 
 7509: =back
 7510: 
 7511: =head2 Network Status Functions
 7512: 
 7513: =over 4
 7514: 
 7515: =item *
 7516: 
 7517: dirlist($uri) : return directory list based on URI
 7518: 
 7519: =item *
 7520: 
 7521: spareserver() : find server with least workload from spare.tab
 7522: 
 7523: =back
 7524: 
 7525: =head2 Apache Request
 7526: 
 7527: =over 4
 7528: 
 7529: =item *
 7530: 
 7531: ssi($url,%hash) : server side include, does a complete request cycle on url to
 7532: localhost, posts hash
 7533: 
 7534: =back
 7535: 
 7536: =head2 Data to String to Data
 7537: 
 7538: =over 4
 7539: 
 7540: =item *
 7541: 
 7542: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 7543: and '&' separators, supports elements that are arrayrefs and hashrefs
 7544: 
 7545: =item *
 7546: 
 7547: hashref2str($hashref) : convert a hashref into a string complete with
 7548: escaping and '=' and '&' separators, supports elements that are
 7549: arrayrefs and hashrefs
 7550: 
 7551: =item *
 7552: 
 7553: arrayref2str($arrayref) : convert an arrayref into a string complete
 7554: with escaping and '&' separators, supports elements that are arrayrefs
 7555: and hashrefs
 7556: 
 7557: =item *
 7558: 
 7559: str2hash($string) : convert string to hash using unescaping and
 7560: splitting on '=' and '&', supports elements that are arrayrefs and
 7561: hashrefs
 7562: 
 7563: =item *
 7564: 
 7565: str2array($string) : convert string to hash using unescaping and
 7566: splitting on '&', supports elements that are arrayrefs and hashrefs
 7567: 
 7568: =back
 7569: 
 7570: =head2 Logging Routines
 7571: 
 7572: =over 4
 7573: 
 7574: These routines allow one to make log messages in the lonnet.log and
 7575: lonnet.perm logfiles.
 7576: 
 7577: =item *
 7578: 
 7579: logtouch() : make sure the logfile, lonnet.log, exists
 7580: 
 7581: =item *
 7582: 
 7583: logthis() : append message to the normal lonnet.log file, it gets
 7584: preiodically rolled over and deleted.
 7585: 
 7586: =item *
 7587: 
 7588: logperm() : append a permanent message to lonnet.perm.log, this log
 7589: file never gets deleted by any automated portion of the system, only
 7590: messages of critical importance should go in here.
 7591: 
 7592: =back
 7593: 
 7594: =head2 General File Helper Routines
 7595: 
 7596: =over 4
 7597: 
 7598: =item *
 7599: 
 7600: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 7601: (a) files in /uploaded
 7602:   (i) If a local copy of the file exists - 
 7603:       compares modification date of local copy with last-modified date for 
 7604:       definitive version stored on home server for course. If local copy is 
 7605:       stale, requests a new version from the home server and stores it. 
 7606:       If the original has been removed from the home server, then local copy 
 7607:       is unlinked.
 7608:   (ii) If local copy does not exist -
 7609:       requests the file from the home server and stores it. 
 7610:   
 7611:   If $caller is 'uploadrep':  
 7612:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 7613:     for request for files originally uploaded via DOCS. 
 7614:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 7615:   
 7616:   Otherwise:
 7617:      This indicates a call from the content generation phase of the request.
 7618:      -  returns the entire contents of the file or -1.
 7619:      
 7620: (b) files in /res
 7621:    - returns the entire contents of a file or -1; 
 7622:    it properly subscribes to and replicates the file if neccessary.
 7623: 
 7624: 
 7625: =item *
 7626: 
 7627: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 7628:                   reference
 7629: 
 7630: returns either a stat() list of data about the file or an empty list
 7631: if the file doesn't exist or couldn't find out about it (connection
 7632: problems or user unknown)
 7633: 
 7634: =item *
 7635: 
 7636: filelocation($dir,$file) : returns file system location of a file
 7637: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 7638: directory that relative $file lookups are to looked in ($dir of /a/dir
 7639: and a file of ../bob will become /a/bob)
 7640: 
 7641: =item *
 7642: 
 7643: hreflocation($dir,$file) : returns file system location or a URL; same as
 7644: filelocation except for hrefs
 7645: 
 7646: =item *
 7647: 
 7648: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 7649: 
 7650: =back
 7651: 
 7652: =head2 Usererfile file routines (/uploaded*)
 7653: 
 7654: =over 4
 7655: 
 7656: =item *
 7657: 
 7658: userfileupload(): main rotine for putting a file in a user or course's
 7659:                   filespace, arguments are,
 7660: 
 7661:  formname - required - this is the name of the element in $env where the
 7662:            filename, and the contents of the file to create/modifed exist
 7663:            the filename is in $env{'form.'.$formname.'.filename'} and the
 7664:            contents of the file is located in $env{'form.'.$formname}
 7665:  coursedoc - if true, store the file in the course of the active role
 7666:              of the current user
 7667:  subdir - required - subdirectory to put the file in under ../userfiles/
 7668:          if undefined, it will be placed in "unknown"
 7669: 
 7670:  (This routine calls clean_filename() to remove any dangerous
 7671:  characters from the filename, and then calls finuserfileupload() to
 7672:  complete the transaction)
 7673: 
 7674:  returns either the url of the uploaded file (/uploaded/....) if successful
 7675:  and /adm/notfound.html if unsuccessful
 7676: 
 7677: =item *
 7678: 
 7679: clean_filename(): routine for cleaing a filename up for storage in
 7680:                  userfile space, argument is:
 7681: 
 7682:  filename - proposed filename
 7683: 
 7684: returns: the new clean filename
 7685: 
 7686: =item *
 7687: 
 7688: finishuserfileupload(): routine that creaes and sends the file to
 7689: userspace, probably shouldn't be called directly
 7690: 
 7691:   docuname: username or courseid of destination for the file
 7692:   docudom: domain of user/course of destination for the file
 7693:   formname: same as for userfileupload()
 7694:   fname: filename (inculding subdirectories) for the file
 7695: 
 7696:  returns either the url of the uploaded file (/uploaded/....) if successful
 7697:  and /adm/notfound.html if unsuccessful
 7698: 
 7699: =item *
 7700: 
 7701: renameuserfile(): renames an existing userfile to a new name
 7702: 
 7703:   Args:
 7704:    docuname: username or courseid of destination for the file
 7705:    docudom: domain of user/course of destination for the file
 7706:    old: current file name (including any subdirs under userfiles)
 7707:    new: desired file name (including any subdirs under userfiles)
 7708: 
 7709: =item *
 7710: 
 7711: mkdiruserfile(): creates a directory is a userfiles dir
 7712: 
 7713:   Args:
 7714:    docuname: username or courseid of destination for the file
 7715:    docudom: domain of user/course of destination for the file
 7716:    dir: dir to create (including any subdirs under userfiles)
 7717: 
 7718: =item *
 7719: 
 7720: removeuserfile(): removes a file that exists in userfiles
 7721: 
 7722:   Args:
 7723:    docuname: username or courseid of destination for the file
 7724:    docudom: domain of user/course of destination for the file
 7725:    fname: filname to delete (including any subdirs under userfiles)
 7726: 
 7727: =item *
 7728: 
 7729: removeuploadedurl(): convience function for removeuserfile()
 7730: 
 7731:   Args:
 7732:    url:  a full /uploaded/... url to delete
 7733: 
 7734: =back
 7735: 
 7736: =head2 HTTP Helper Routines
 7737: 
 7738: =over 4
 7739: 
 7740: =item *
 7741: 
 7742: escape() : unpack non-word characters into CGI-compatible hex codes
 7743: 
 7744: =item *
 7745: 
 7746: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 7747: 
 7748: =back
 7749: 
 7750: =head1 PRIVATE SUBROUTINES
 7751: 
 7752: =head2 Underlying communication routines (Shouldn't call)
 7753: 
 7754: =over 4
 7755: 
 7756: =item *
 7757: 
 7758: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 7759: 
 7760: =item *
 7761: 
 7762: reply() : uses subreply to send a message to remote machine, logs all failures
 7763: 
 7764: =item *
 7765: 
 7766: critical() : passes a critical message to another server; if cannot
 7767: get through then place message in connection buffer directory and
 7768: returns con_delayed, if incapable of saving message, returns
 7769: con_failed
 7770: 
 7771: =item *
 7772: 
 7773: reconlonc() : tries to reconnect lonc client processes.
 7774: 
 7775: =back
 7776: 
 7777: =head2 Resource Access Logging
 7778: 
 7779: =over 4
 7780: 
 7781: =item *
 7782: 
 7783: flushcourselogs() : flush (save) buffer logs and access logs
 7784: 
 7785: =item *
 7786: 
 7787: courselog($what) : save message for course in hash
 7788: 
 7789: =item *
 7790: 
 7791: courseacclog($what) : save message for course using &courselog().  Perform
 7792: special processing for specific resource types (problems, exams, quizzes, etc).
 7793: 
 7794: =item *
 7795: 
 7796: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 7797: as a PerlChildExitHandler
 7798: 
 7799: =back
 7800: 
 7801: =head2 Other
 7802: 
 7803: =over 4
 7804: 
 7805: =item *
 7806: 
 7807: symblist($mapname,%newhash) : update symbolic storage links
 7808: 
 7809: =back
 7810: 
 7811: =cut

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