File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.779: download - view: text, annotated - select for diffs
Fri Sep 15 07:14:04 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG#4977, appenv was doing alot of unneeded unesacpe and reescape which was slowing problem parsing down by about .5 second per problem

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.779 2006/09/15 07:14:04 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %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: # ------------------------------------------- check if return value is an error
  285: 
  286: sub error {
  287:     my ($result) = @_;
  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  289: 	if ($2 == 2) { return undef; }
  290: 	return $1;
  291:     }
  292:     return undef;
  293: }
  294: 
  295: # ------------------------------------------- Transfer profile into environment
  296: 
  297: sub transfer_profile_to_env {
  298:     my ($lonidsdir,$handle)=@_;
  299:     if (!defined($lonidsdir)) {
  300: 	$lonidsdir = $perlvar{'lonIDsDir'};
  301:     }
  302:     if (!defined($handle)) {
  303:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  304:     }
  305: 
  306:     my @profile;
  307:     {
  308: 	open(my $idf,"$lonidsdir/$handle.id");
  309: 	flock($idf,LOCK_SH);
  310: 	@profile=<$idf>;
  311: 	close($idf);
  312:     }
  313:     my $envi;
  314:     my %Remove;
  315:     for ($envi=0;$envi<=$#profile;$envi++) {
  316: 	chomp($profile[$envi]);
  317: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
  318: 	$envname=&unescape($envname);
  319: 	$envvalue=&unescape($envvalue);
  320: 	$env{$envname} = $envvalue;
  321:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  322:             if ($time < time-300) {
  323:                 $Remove{$key}++;
  324:             }
  325:         }
  326:     }
  327:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  328:     foreach my $expired_key (keys(%Remove)) {
  329:         &delenv($expired_key);
  330:     }
  331: }
  332: 
  333: # ---------------------------------------------------------- Append Environment
  334: 
  335: sub appenv {
  336:     my %newenv=@_;
  337:     foreach my $key (keys(%newenv)) {
  338: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  339:             &logthis("<font color=\"blue\">WARNING: ".
  340:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  341:                 .'</font>');
  342: 	    delete($newenv{$key});
  343:         } else {
  344:             $env{$key}=$newenv{$key};
  345:         }
  346:     }
  347:     foreach my $key (keys(%newenv)) {
  348: 	my $value = &escape($newenv{$key});
  349: 	delete($newenv{$key});
  350: 	$newenv{&escape($key)}=$value;
  351:     }
  352: 
  353:     my $lockfh;
  354:     unless (open($lockfh,"$env{'user.environment'}")) {
  355: 	return 'error: '.$!;
  356:     }
  357:     unless (flock($lockfh,LOCK_EX)) {
  358:          &logthis("<font color=\"blue\">WARNING: ".
  359:                   'Could not obtain exclusive lock in appenv: '.$!);
  360:          close($lockfh);
  361:          return 'error: '.$!;
  362:     }
  363: 
  364:     my @oldenv;
  365:     {
  366: 	my $fh;
  367: 	unless (open($fh,"$env{'user.environment'}")) {
  368: 	    return 'error: '.$!;
  369: 	}
  370: 	@oldenv=<$fh>;
  371: 	close($fh);
  372:     }
  373:     for (my $i=0; $i<=$#oldenv; $i++) {
  374:         chomp($oldenv[$i]);
  375:         if ($oldenv[$i] ne '') {
  376: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
  377: 	    unless (defined($newenv{$name})) {
  378: 		$newenv{$name}=$value;
  379: 	    }
  380:         }
  381:     }
  382:     {
  383: 	my $fh;
  384: 	unless (open($fh,">$env{'user.environment'}")) {
  385: 	    return 'error';
  386: 	}
  387: 	my $newname;
  388: 	foreach $newname (keys %newenv) {
  389: 	    print $fh $newname.'='.$newenv{$newname}."\n";
  390: 	}
  391: 	close($fh);
  392:     }
  393: 	
  394:     close($lockfh);
  395:     return 'ok';
  396: }
  397: # ----------------------------------------------------- Delete from Environment
  398: 
  399: sub delenv {
  400:     my $delthis=shift;
  401:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  402:         &logthis("<font color=\"blue\">WARNING: ".
  403:                 "Attempt to delete from environment ".$delthis);
  404:         return 'error';
  405:     }
  406:     my @oldenv;
  407:     {
  408: 	my $fh;
  409: 	unless (open($fh,"$env{'user.environment'}")) {
  410: 	    return 'error';
  411: 	}
  412: 	unless (flock($fh,LOCK_SH)) {
  413: 	    &logthis("<font color=\"blue\">WARNING: ".
  414: 		     'Could not obtain shared lock in delenv: '.$!);
  415: 	    close($fh);
  416: 	    return 'error: '.$!;
  417: 	}
  418: 	@oldenv=<$fh>;
  419: 	close($fh);
  420:     }
  421:     {
  422: 	my $fh;
  423: 	unless (open($fh,">$env{'user.environment'}")) {
  424: 	    return 'error';
  425: 	}
  426: 	unless (flock($fh,LOCK_EX)) {
  427: 	    &logthis("<font color=\"blue\">WARNING: ".
  428: 		     'Could not obtain exclusive lock in delenv: '.$!);
  429: 	    close($fh);
  430: 	    return 'error: '.$!;
  431: 	}
  432: 	foreach my $cur_key (@oldenv) {
  433: 	    my $unescaped_cur_key = &unescape($cur_key);
  434: 	    if ($unescaped_cur_key=~/^$delthis/) { 
  435:                 my ($key) = split('=',$cur_key,2);
  436: 		$key = &unescape($key);
  437:                 delete($env{$key});
  438:             } else {
  439:                 print $fh $cur_key; 
  440:             }
  441: 	}
  442: 	close($fh);
  443:     }
  444:     return 'ok';
  445: }
  446: 
  447: # ------------------------------------------ Find out current server userload
  448: # there is a copy in lond
  449: sub userload {
  450:     my $numusers=0;
  451:     {
  452: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  453: 	my $filename;
  454: 	my $curtime=time;
  455: 	while ($filename=readdir(LONIDS)) {
  456: 	    if ($filename eq '.' || $filename eq '..') {next;}
  457: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  458: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  459: 	}
  460: 	closedir(LONIDS);
  461:     }
  462:     my $userloadpercent=0;
  463:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  464:     if ($maxuserload) {
  465: 	$userloadpercent=100*$numusers/$maxuserload;
  466:     }
  467:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  468:     return $userloadpercent;
  469: }
  470: 
  471: # ------------------------------------------ Fight off request when overloaded
  472: 
  473: sub overloaderror {
  474:     my ($r,$checkserver)=@_;
  475:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  476:     my $loadavg;
  477:     if ($checkserver eq $perlvar{'lonHostID'}) {
  478:        open(my $loadfile,'/proc/loadavg');
  479:        $loadavg=<$loadfile>;
  480:        $loadavg =~ s/\s.*//g;
  481:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  482:        close($loadfile);
  483:     } else {
  484:        $loadavg=&reply('load',$checkserver);
  485:     }
  486:     my $overload=$loadavg-100;
  487:     if ($overload>0) {
  488: 	$r->err_headers_out->{'Retry-After'}=$overload;
  489:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  490:         return 413;
  491:     }    
  492:     return '';
  493: }
  494: 
  495: # ------------------------------ Find server with least workload from spare.tab
  496: 
  497: sub spareserver {
  498:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  499:     my $tryserver;
  500:     my $spareserver='';
  501:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  502:     my $lowestserver=$loadpercent > $userloadpercent?
  503: 	             $loadpercent :  $userloadpercent;
  504:     foreach $tryserver (keys(%spareid)) {
  505: 	my $loadans=&reply('load',$tryserver);
  506: 	my $userloadans=&reply('userload',$tryserver);
  507: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  508: 	    next; #didn't get a number from the server
  509: 	}
  510: 	my $answer;
  511: 	if ($loadans =~ /\d/) {
  512: 	    if ($userloadans =~ /\d/) {
  513: 		#both are numbers, pick the bigger one
  514: 		$answer=$loadans > $userloadans?
  515: 		    $loadans :  $userloadans;
  516: 	    } else {
  517: 		$answer = $loadans;
  518: 	    }
  519: 	} else {
  520: 	    $answer = $userloadans;
  521: 	}
  522: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  523: 	    if ($want_server_name) {
  524: 		$spareserver=$tryserver;
  525: 	    } else {
  526: 		$spareserver="http://$hostname{$tryserver}";
  527: 	    }
  528: 	    $lowestserver=$answer;
  529: 	}
  530:     }
  531:     return $spareserver;
  532: }
  533: 
  534: # --------------------------------------------- Try to change a user's password
  535: 
  536: sub changepass {
  537:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  538:     $currentpass = &escape($currentpass);
  539:     $newpass     = &escape($newpass);
  540:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  541: 		       $server);
  542:     if (! $answer) {
  543: 	&logthis("No reply on password change request to $server ".
  544: 		 "by $uname in domain $udom.");
  545:     } elsif ($answer =~ "^ok") {
  546:         &logthis("$uname in $udom successfully changed their password ".
  547: 		 "on $server.");
  548:     } elsif ($answer =~ "^pwchange_failure") {
  549: 	&logthis("$uname in $udom was unable to change their password ".
  550: 		 "on $server.  The action was blocked by either lcpasswd ".
  551: 		 "or pwchange");
  552:     } elsif ($answer =~ "^non_authorized") {
  553:         &logthis("$uname in $udom did not get their password correct when ".
  554: 		 "attempting to change it on $server.");
  555:     } elsif ($answer =~ "^auth_mode_error") {
  556:         &logthis("$uname in $udom attempted to change their password despite ".
  557: 		 "not being locally or internally authenticated on $server.");
  558:     } elsif ($answer =~ "^unknown_user") {
  559:         &logthis("$uname in $udom attempted to change their password ".
  560: 		 "on $server but were unable to because $server is not ".
  561: 		 "their home server.");
  562:     } elsif ($answer =~ "^refused") {
  563: 	&logthis("$server refused to change $uname in $udom password because ".
  564: 		 "it was sent an unencrypted request to change the password.");
  565:     }
  566:     return $answer;
  567: }
  568: 
  569: # ----------------------- Try to determine user's current authentication scheme
  570: 
  571: sub queryauthenticate {
  572:     my ($uname,$udom)=@_;
  573:     my $uhome=&homeserver($uname,$udom);
  574:     if (!$uhome) {
  575: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  576: 	return 'no_host';
  577:     }
  578:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  579:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  580: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  581:     }
  582:     return $answer;
  583: }
  584: 
  585: # --------- Try to authenticate user from domain's lib servers (first this one)
  586: 
  587: sub authenticate {
  588:     my ($uname,$upass,$udom)=@_;
  589:     $upass=escape($upass);
  590:     $uname=~s/\W//g;
  591:     my $uhome=&homeserver($uname,$udom);
  592:     if (!$uhome) {
  593: 	&logthis("User $uname at $udom is unknown in authenticate");
  594: 	return 'no_host';
  595:     }
  596:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  597:     if ($answer eq 'authorized') {
  598: 	&logthis("User $uname at $udom authorized by $uhome"); 
  599: 	return $uhome; 
  600:     }
  601:     if ($answer eq 'non_authorized') {
  602: 	&logthis("User $uname at $udom rejected by $uhome");
  603: 	return 'no_host'; 
  604:     }
  605:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  606:     return 'no_host';
  607: }
  608: 
  609: # ---------------------- Find the homebase for a user from domain's lib servers
  610: 
  611: my %homecache;
  612: sub homeserver {
  613:     my ($uname,$udom,$ignoreBadCache)=@_;
  614:     my $index="$uname:$udom";
  615: 
  616:     if (exists($homecache{$index})) { return $homecache{$index}; }
  617:     my $tryserver;
  618:     foreach $tryserver (keys %libserv) {
  619:         next if ($ignoreBadCache ne 'true' && 
  620: 		 exists($badServerCache{$tryserver}));
  621: 	if ($hostdom{$tryserver} eq $udom) {
  622:            my $answer=reply("home:$udom:$uname",$tryserver);
  623:            if ($answer eq 'found') { 
  624: 	       return $homecache{$index}=$tryserver;
  625:            } elsif ($answer eq 'no_host') {
  626: 	       $badServerCache{$tryserver}=1;
  627:            }
  628:        }
  629:     }    
  630:     return 'no_host';
  631: }
  632: 
  633: # ------------------------------------- Find the usernames behind a list of IDs
  634: 
  635: sub idget {
  636:     my ($udom,@ids)=@_;
  637:     my %returnhash=();
  638:     
  639:     my $tryserver;
  640:     foreach $tryserver (keys %libserv) {
  641:        if ($hostdom{$tryserver} eq $udom) {
  642: 	  my $idlist=join('&',@ids);
  643:           $idlist=~tr/A-Z/a-z/; 
  644: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  645:           my @answer=();
  646:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  647: 	      @answer=split(/\&/,$reply);
  648:           }                    ;
  649:           my $i;
  650:           for ($i=0;$i<=$#ids;$i++) {
  651:               if ($answer[$i]) {
  652: 		  $returnhash{$ids[$i]}=$answer[$i];
  653:               } 
  654:           }
  655:        }
  656:     }    
  657:     return %returnhash;
  658: }
  659: 
  660: # ------------------------------------- Find the IDs behind a list of usernames
  661: 
  662: sub idrget {
  663:     my ($udom,@unames)=@_;
  664:     my %returnhash=();
  665:     foreach (@unames) {
  666:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  667:     }
  668:     return %returnhash;
  669: }
  670: 
  671: # ------------------------------- Store away a list of names and associated IDs
  672: 
  673: sub idput {
  674:     my ($udom,%ids)=@_;
  675:     my %servers=();
  676:     foreach (keys %ids) {
  677: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  678:         my $uhom=&homeserver($_,$udom);
  679:         if ($uhom ne 'no_host') {
  680:             my $id=&escape($ids{$_});
  681:             $id=~tr/A-Z/a-z/;
  682:             my $unam=&escape($_);
  683: 	    if ($servers{$uhom}) {
  684: 		$servers{$uhom}.='&'.$id.'='.$unam;
  685:             } else {
  686:                 $servers{$uhom}=$id.'='.$unam;
  687:             }
  688:         }
  689:     }
  690:     foreach (keys %servers) {
  691:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  692:     }
  693: }
  694: 
  695: # --------------------------------------------------- Assign a key to a student
  696: 
  697: sub assign_access_key {
  698: #
  699: # a valid key looks like uname:udom#comments
  700: # comments are being appended
  701: #
  702:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  703:     $kdom=
  704:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  705:     $knum=
  706:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  707:     $cdom=
  708:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  709:     $cnum=
  710:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  711:     $udom=$env{'user.name'} unless (defined($udom));
  712:     $uname=$env{'user.domain'} unless (defined($uname));
  713:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  714:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  715:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  716:                                                   # assigned to this person
  717:                                                   # - this should not happen,
  718:                                                   # unless something went wrong
  719:                                                   # the first time around
  720: # ready to assign
  721:         $logentry=$1.'; '.$logentry;
  722:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  723:                                                  $kdom,$knum) eq 'ok') {
  724: # key now belongs to user
  725: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  726:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  727:                 &appenv('environment.'.$envkey => $ckey);
  728:                 return 'ok';
  729:             } else {
  730:                 return 
  731:   'error: Count not permanently assign key, will need to be re-entered later.';
  732: 	    }
  733:         } else {
  734:             return 'error: Could not assign key, try again later.';
  735:         }
  736:     } elsif (!$existing{$ckey}) {
  737: # the key does not exist
  738: 	return 'error: The key does not exist';
  739:     } else {
  740: # the key is somebody else's
  741: 	return 'error: The key is already in use';
  742:     }
  743: }
  744: 
  745: # ------------------------------------------ put an additional comment on a key
  746: 
  747: sub comment_access_key {
  748: #
  749: # a valid key looks like uname:udom#comments
  750: # comments are being appended
  751: #
  752:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  753:     $cdom=
  754:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  755:     $cnum=
  756:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  757:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  758:     if ($existing{$ckey}) {
  759:         $existing{$ckey}.='; '.$logentry;
  760: # ready to assign
  761:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  762:                                                  $cdom,$cnum) eq 'ok') {
  763: 	    return 'ok';
  764:         } else {
  765: 	    return 'error: Count not store comment.';
  766:         }
  767:     } else {
  768: # the key does not exist
  769: 	return 'error: The key does not exist';
  770:     }
  771: }
  772: 
  773: # ------------------------------------------------------ Generate a set of keys
  774: 
  775: sub generate_access_keys {
  776:     my ($number,$cdom,$cnum,$logentry)=@_;
  777:     $cdom=
  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  779:     $cnum=
  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  781:     unless (&allowed('mky',$cdom)) { return 0; }
  782:     unless (($cdom) && ($cnum)) { return 0; }
  783:     if ($number>10000) { return 0; }
  784:     sleep(2); # make sure don't get same seed twice
  785:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  786:     my $total=0;
  787:     for (my $i=1;$i<=$number;$i++) {
  788:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  789:                   sprintf("%lx",int(100000*rand)).'-'.
  790:                   sprintf("%lx",int(100000*rand));
  791:        $newkey=~s/1/g/g; # folks mix up 1 and l
  792:        $newkey=~s/0/h/g; # and also 0 and O
  793:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  794:        if ($existing{$newkey}) {
  795:            $i--;
  796:        } else {
  797: 	  if (&put('accesskeys',
  798:               { $newkey => '# generated '.localtime().
  799:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  800:                            '; '.$logentry },
  801: 		   $cdom,$cnum) eq 'ok') {
  802:               $total++;
  803: 	  }
  804:        }
  805:     }
  806:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  807:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  808:     return $total;
  809: }
  810: 
  811: # ------------------------------------------------------- Validate an accesskey
  812: 
  813: sub validate_access_key {
  814:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  815:     $cdom=
  816:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  817:     $cnum=
  818:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  819:     $udom=$env{'user.domain'} unless (defined($udom));
  820:     $uname=$env{'user.name'} unless (defined($uname));
  821:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  822:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  823: }
  824: 
  825: # ------------------------------------- Find the section of student in a course
  826: sub devalidate_getsection_cache {
  827:     my ($udom,$unam,$courseid)=@_;
  828:     $courseid=~s/\_/\//g;
  829:     $courseid=~s/^(\w)/\/$1/;
  830:     my $hashid="$udom:$unam:$courseid";
  831:     &devalidate_cache_new('getsection',$hashid);
  832: }
  833: 
  834: sub getsection {
  835:     my ($udom,$unam,$courseid)=@_;
  836:     my $cachetime=1800;
  837:     $courseid=~s/\_/\//g;
  838:     $courseid=~s/^(\w)/\/$1/;
  839: 
  840:     my $hashid="$udom:$unam:$courseid";
  841:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  842:     if (defined($cached)) { return $result; }
  843: 
  844:     my %Pending; 
  845:     my %Expired;
  846:     #
  847:     # Each role can either have not started yet (pending), be active, 
  848:     #    or have expired.
  849:     #
  850:     # If there is an active role, we are done.
  851:     #
  852:     # If there is more than one role which has not started yet, 
  853:     #     choose the one which will start sooner
  854:     # If there is one role which has not started yet, return it.
  855:     #
  856:     # If there is more than one expired role, choose the one which ended last.
  857:     # If there is a role which has expired, return it.
  858:     #
  859:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  860:                         &homeserver($unam,$udom)))) {
  861:         my ($key,$value)=split(/\=/,$_);
  862:         $key=&unescape($key);
  863:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  864:         my $section=$1;
  865:         if ($key eq $courseid.'_st') { $section=''; }
  866:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  867:         my $now=time;
  868:         if (defined($end) && $end && ($now > $end)) {
  869:             $Expired{$end}=$section;
  870:             next;
  871:         }
  872:         if (defined($start) && $start && ($now < $start)) {
  873:             $Pending{$start}=$section;
  874:             next;
  875:         }
  876:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  877:     }
  878:     #
  879:     # Presumedly there will be few matching roles from the above
  880:     # loop and the sorting time will be negligible.
  881:     if (scalar(keys(%Pending))) {
  882:         my ($time) = sort {$a <=> $b} keys(%Pending);
  883:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  884:     } 
  885:     if (scalar(keys(%Expired))) {
  886:         my @sorted = sort {$a <=> $b} keys(%Expired);
  887:         my $time = pop(@sorted);
  888:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  889:     }
  890:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  891: }
  892: 
  893: sub save_cache {
  894:     &purge_remembered();
  895:     #&Apache::loncommon::validate_page();
  896:     undef(%env);
  897: }
  898: 
  899: my $to_remember=-1;
  900: my %remembered;
  901: my %accessed;
  902: my $kicks=0;
  903: my $hits=0;
  904: sub devalidate_cache_new {
  905:     my ($name,$id,$debug) = @_;
  906:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  907:     $id=&escape($name.':'.$id);
  908:     $memcache->delete($id);
  909:     delete($remembered{$id});
  910:     delete($accessed{$id});
  911: }
  912: 
  913: sub is_cached_new {
  914:     my ($name,$id,$debug) = @_;
  915:     $id=&escape($name.':'.$id);
  916:     if (exists($remembered{$id})) {
  917: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  918: 	$accessed{$id}=[&gettimeofday()];
  919: 	$hits++;
  920: 	return ($remembered{$id},1);
  921:     }
  922:     my $value = $memcache->get($id);
  923:     if (!(defined($value))) {
  924: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  925: 	return (undef,undef);
  926:     }
  927:     if ($value eq '__undef__') {
  928: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  929: 	$value=undef;
  930:     }
  931:     &make_room($id,$value,$debug);
  932:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  933:     return ($value,1);
  934: }
  935: 
  936: sub do_cache_new {
  937:     my ($name,$id,$value,$time,$debug) = @_;
  938:     $id=&escape($name.':'.$id);
  939:     my $setvalue=$value;
  940:     if (!defined($setvalue)) {
  941: 	$setvalue='__undef__';
  942:     }
  943:     if (!defined($time) ) {
  944: 	$time=600;
  945:     }
  946:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  947:     $memcache->set($id,$setvalue,$time);
  948:     # need to make a copy of $value
  949:     #&make_room($id,$value,$debug);
  950:     return $value;
  951: }
  952: 
  953: sub make_room {
  954:     my ($id,$value,$debug)=@_;
  955:     $remembered{$id}=$value;
  956:     if ($to_remember<0) { return; }
  957:     $accessed{$id}=[&gettimeofday()];
  958:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  959:     my $to_kick;
  960:     my $max_time=0;
  961:     foreach my $other (keys(%accessed)) {
  962: 	if (&tv_interval($accessed{$other}) > $max_time) {
  963: 	    $to_kick=$other;
  964: 	    $max_time=&tv_interval($accessed{$other});
  965: 	}
  966:     }
  967:     delete($remembered{$to_kick});
  968:     delete($accessed{$to_kick});
  969:     $kicks++;
  970:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  971:     return;
  972: }
  973: 
  974: sub purge_remembered {
  975:     #&logthis("Tossing ".scalar(keys(%remembered)));
  976:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  977:     undef(%remembered);
  978:     undef(%accessed);
  979: }
  980: # ------------------------------------- Read an entry from a user's environment
  981: 
  982: sub userenvironment {
  983:     my ($udom,$unam,@what)=@_;
  984:     my %returnhash=();
  985:     my @answer=split(/\&/,
  986:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  987:                       &homeserver($unam,$udom)));
  988:     my $i;
  989:     for ($i=0;$i<=$#what;$i++) {
  990: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  991:     }
  992:     return %returnhash;
  993: }
  994: 
  995: # ---------------------------------------------------------- Get a studentphoto
  996: sub studentphoto {
  997:     my ($udom,$unam,$ext) = @_;
  998:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  999:     if (defined($env{'request.course.id'})) {
 1000:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1001:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1002:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1003:             } else {
 1004:                 my ($result,$perm_reqd)=
 1005: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1006:                 if ($result eq 'ok') {
 1007:                     if (!($perm_reqd eq 'yes')) {
 1008:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1009:                     }
 1010:                 }
 1011:             }
 1012:         }
 1013:     } else {
 1014:         my ($result,$perm_reqd) = 
 1015: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1016:         if ($result eq 'ok') {
 1017:             if (!($perm_reqd eq 'yes')) {
 1018:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1019:             }
 1020:         }
 1021:     }
 1022:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1023: }
 1024: 
 1025: sub retrievestudentphoto {
 1026:     my ($udom,$unam,$ext,$type) = @_;
 1027:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1028:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1029:     if ($ret eq 'ok') {
 1030:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1031:         if ($type eq 'thumbnail') {
 1032:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1033:         }
 1034:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1035:         return $tokenurl;
 1036:     } else {
 1037:         if ($type eq 'thumbnail') {
 1038:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1039:         } else { 
 1040:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1041:         }
 1042:     }
 1043: }
 1044: 
 1045: # -------------------------------------------------------------------- New chat
 1046: 
 1047: sub chatsend {
 1048:     my ($newentry,$anon,$group)=@_;
 1049:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1050:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1051:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1052:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1053: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1054: 		   &escape($newentry)).':'.$group,$chome);
 1055: }
 1056: 
 1057: # ------------------------------------------ Find current version of a resource
 1058: 
 1059: sub getversion {
 1060:     my $fname=&clutter(shift);
 1061:     unless ($fname=~/^\/res\//) { return -1; }
 1062:     return &currentversion(&filelocation('',$fname));
 1063: }
 1064: 
 1065: sub currentversion {
 1066:     my $fname=shift;
 1067:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1068:     if (defined($cached)) { return $result; }
 1069:     my $author=$fname;
 1070:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1071:     my ($udom,$uname)=split(/\//,$author);
 1072:     my $home=homeserver($uname,$udom);
 1073:     if ($home eq 'no_host') { 
 1074:         return -1; 
 1075:     }
 1076:     my $answer=reply("currentversion:$fname",$home);
 1077:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1078: 	return -1;
 1079:     }
 1080:     return &do_cache_new('resversion',$fname,$answer,600);
 1081: }
 1082: 
 1083: # ----------------------------- Subscribe to a resource, return URL if possible
 1084: 
 1085: sub subscribe {
 1086:     my $fname=shift;
 1087:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1088:     $fname=~s/[\n\r]//g;
 1089:     my $author=$fname;
 1090:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1091:     my ($udom,$uname)=split(/\//,$author);
 1092:     my $home=homeserver($uname,$udom);
 1093:     if ($home eq 'no_host') {
 1094:         return 'not_found';
 1095:     }
 1096:     my $answer=reply("sub:$fname",$home);
 1097:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1098: 	$answer.=' by '.$home;
 1099:     }
 1100:     return $answer;
 1101: }
 1102:     
 1103: # -------------------------------------------------------------- Replicate file
 1104: 
 1105: sub repcopy {
 1106:     my $filename=shift;
 1107:     $filename=~s/\/+/\//g;
 1108:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1109:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1110:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1111: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1112: 	return &repcopy_userfile($filename);
 1113:     }
 1114:     $filename=~s/[\n\r]//g;
 1115:     my $transname="$filename.in.transfer";
 1116:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1117:     my $remoteurl=subscribe($filename);
 1118:     if ($remoteurl =~ /^con_lost by/) {
 1119: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1120:            return 'unavailable';
 1121:     } elsif ($remoteurl eq 'not_found') {
 1122: 	   #&logthis("Subscribe returned not_found: $filename");
 1123: 	   return 'not_found';
 1124:     } elsif ($remoteurl =~ /^rejected by/) {
 1125: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1126:            return 'forbidden';
 1127:     } elsif ($remoteurl eq 'directory') {
 1128:            return 'ok';
 1129:     } else {
 1130:         my $author=$filename;
 1131:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1132:         my ($udom,$uname)=split(/\//,$author);
 1133:         my $home=homeserver($uname,$udom);
 1134:         unless ($home eq $perlvar{'lonHostID'}) {
 1135:            my @parts=split(/\//,$filename);
 1136:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1137:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1138:                &logthis("Malconfiguration for replication: $filename");
 1139: 	       return 'bad_request';
 1140:            }
 1141:            my $count;
 1142:            for ($count=5;$count<$#parts;$count++) {
 1143:                $path.="/$parts[$count]";
 1144:                if ((-e $path)!=1) {
 1145: 		   mkdir($path,0777);
 1146:                }
 1147:            }
 1148:            my $ua=new LWP::UserAgent;
 1149:            my $request=new HTTP::Request('GET',"$remoteurl");
 1150:            my $response=$ua->request($request,$transname);
 1151:            if ($response->is_error()) {
 1152: 	       unlink($transname);
 1153:                my $message=$response->status_line;
 1154:                &logthis("<font color=\"blue\">WARNING:"
 1155:                        ." LWP get: $message: $filename</font>");
 1156:                return 'unavailable';
 1157:            } else {
 1158: 	       if ($remoteurl!~/\.meta$/) {
 1159:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1160:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1161:                   if ($mresponse->is_error()) {
 1162: 		      unlink($filename.'.meta');
 1163:                       &logthis(
 1164:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1165:                   }
 1166: 	       }
 1167:                rename($transname,$filename);
 1168:                return 'ok';
 1169:            }
 1170:        }
 1171:     }
 1172: }
 1173: 
 1174: # ------------------------------------------------ Get server side include body
 1175: sub ssi_body {
 1176:     my ($filelink,%form)=@_;
 1177:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1178:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1179:     }
 1180:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1181:                                      &ssi($filelink,%form));
 1182:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1183:     $output=~s/^.*?\<body[^\>]*\>//si;
 1184:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1185:     return $output;
 1186: }
 1187: 
 1188: # --------------------------------------------------------- Server Side Include
 1189: 
 1190: sub ssi {
 1191: 
 1192:     my ($fn,%form)=@_;
 1193: 
 1194:     my $ua=new LWP::UserAgent;
 1195:     
 1196:     my $request;
 1197: 
 1198:     $form{'no_update_last_known'}=1;
 1199: 
 1200:     if (%form) {
 1201:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1202:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1203:     } else {
 1204:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1205:     }
 1206: 
 1207:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1208:     my $response=$ua->request($request);
 1209: 
 1210:     return $response->content;
 1211: }
 1212: 
 1213: sub externalssi {
 1214:     my ($url)=@_;
 1215:     my $ua=new LWP::UserAgent;
 1216:     my $request=new HTTP::Request('GET',$url);
 1217:     my $response=$ua->request($request);
 1218:     return $response->content;
 1219: }
 1220: 
 1221: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1222: 
 1223: sub allowuploaded {
 1224:     my ($srcurl,$url)=@_;
 1225:     $url=&clutter(&declutter($url));
 1226:     my $dir=$url;
 1227:     $dir=~s/\/[^\/]+$//;
 1228:     my %httpref=();
 1229:     my $httpurl=&hreflocation('',$url);
 1230:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1231:     &Apache::lonnet::appenv(%httpref);
 1232: }
 1233: 
 1234: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1235: # input: action, courseID, current domain, intended
 1236: #        path to file, source of file, instruction to parse file for objects,
 1237: #        ref to hash for embedded objects,
 1238: #        ref to hash for codebase of java objects.
 1239: #
 1240: # output: url to file (if action was uploaddoc), 
 1241: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1242: #
 1243: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1244: # course.
 1245: #
 1246: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1247: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1248: #          course's home server.
 1249: #
 1250: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1251: #          be copied from $source (current location) to 
 1252: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1253: #         and will then be copied to
 1254: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1255: #         course's home server.
 1256: #
 1257: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1258: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1259: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1260: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1261: #         in course's home server.
 1262: #
 1263: 
 1264: sub process_coursefile {
 1265:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1266:     my $fetchresult;
 1267:     my $home=&homeserver($docuname,$docudom);
 1268:     if ($action eq 'propagate') {
 1269:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1270: 			     $home);
 1271:     } else {
 1272:         my $fpath = '';
 1273:         my $fname = $file;
 1274:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1275:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1276:         my $filepath = &build_filepath($fpath);
 1277:         if ($action eq 'copy') {
 1278:             if ($source eq '') {
 1279:                 $fetchresult = 'no source file';
 1280:                 return $fetchresult;
 1281:             } else {
 1282:                 my $destination = $filepath.'/'.$fname;
 1283:                 rename($source,$destination);
 1284:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1285:                                  $home);
 1286:             }
 1287:         } elsif ($action eq 'uploaddoc') {
 1288:             open(my $fh,'>'.$filepath.'/'.$fname);
 1289:             print $fh $env{'form.'.$source};
 1290:             close($fh);
 1291:             if ($parser eq 'parse') {
 1292:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1293:                 unless ($parse_result eq 'ok') {
 1294:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1295:                 }
 1296:             }
 1297:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1298:                                  $home);
 1299:             if ($fetchresult eq 'ok') {
 1300:                 return '/uploaded/'.$fpath.'/'.$fname;
 1301:             } else {
 1302:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1303:                         ' to host '.$home.': '.$fetchresult);
 1304:                 return '/adm/notfound.html';
 1305:             }
 1306:         }
 1307:     }
 1308:     unless ( $fetchresult eq 'ok') {
 1309:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1310:              ' to host '.$home.': '.$fetchresult);
 1311:     }
 1312:     return $fetchresult;
 1313: }
 1314: 
 1315: sub build_filepath {
 1316:     my ($fpath) = @_;
 1317:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1318:     unless ($fpath eq '') {
 1319:         my @parts=split('/',$fpath);
 1320:         foreach my $part (@parts) {
 1321:             $filepath.= '/'.$part;
 1322:             if ((-e $filepath)!=1) {
 1323:                 mkdir($filepath,0777);
 1324:             }
 1325:         }
 1326:     }
 1327:     return $filepath;
 1328: }
 1329: 
 1330: sub store_edited_file {
 1331:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1332:     my $file = $primary_url;
 1333:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1334:     my $fpath = '';
 1335:     my $fname = $file;
 1336:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1337:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1338:     my $filepath = &build_filepath($fpath);
 1339:     open(my $fh,'>'.$filepath.'/'.$fname);
 1340:     print $fh $content;
 1341:     close($fh);
 1342:     my $home=&homeserver($docuname,$docudom);
 1343:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1344: 			  $home);
 1345:     if ($$fetchresult eq 'ok') {
 1346:         return '/uploaded/'.$fpath.'/'.$fname;
 1347:     } else {
 1348:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1349: 		 ' to host '.$home.': '.$$fetchresult);
 1350:         return '/adm/notfound.html';
 1351:     }
 1352: }
 1353: 
 1354: sub clean_filename {
 1355:     my ($fname)=@_;
 1356: # Replace Windows backslashes by forward slashes
 1357:     $fname=~s/\\/\//g;
 1358: # Get rid of everything but the actual filename
 1359:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1360: # Replace spaces by underscores
 1361:     $fname=~s/\s+/\_/g;
 1362: # Replace all other weird characters by nothing
 1363:     $fname=~s/[^\w\.\-]//g;
 1364: # Replace all .\d. sequences with _\d. so they no longer look like version
 1365: # numbers
 1366:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1367:     return $fname;
 1368: }
 1369: 
 1370: # --------------- Take an uploaded file and put it into the userfiles directory
 1371: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1372: #                    the desired filenam is in $env{"form.$formname.filename"}
 1373: #        $coursedoc - if true up to the current course
 1374: #                     if false
 1375: #        $subdir - directory in userfile to store the file into
 1376: #        $parser, $allfiles, $codebase - unknown
 1377: #
 1378: # output: url of file in userspace, or error: <message> 
 1379: #             or /adm/notfound.html if failure to upload occurse
 1380: 
 1381: 
 1382: sub userfileupload {
 1383:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1384:     if (!defined($subdir)) { $subdir='unknown'; }
 1385:     my $fname=$env{'form.'.$formname.'.filename'};
 1386:     $fname=&clean_filename($fname);
 1387: # See if there is anything left
 1388:     unless ($fname) { return 'error: no uploaded file'; }
 1389:     chop($env{'form.'.$formname});
 1390:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1391:         my $now = time;
 1392:         my $filepath = 'tmp/helprequests/'.$now;
 1393:         my @parts=split(/\//,$filepath);
 1394:         my $fullpath = $perlvar{'lonDaemons'};
 1395:         for (my $i=0;$i<@parts;$i++) {
 1396:             $fullpath .= '/'.$parts[$i];
 1397:             if ((-e $fullpath)!=1) {
 1398:                 mkdir($fullpath,0777);
 1399:             }
 1400:         }
 1401:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1402:         print $fh $env{'form.'.$formname};
 1403:         close($fh);
 1404:         return $fullpath.'/'.$fname;
 1405:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1406:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1407:                        '_'.$env{'user.domain'}.'/pending';
 1408:         my @parts=split(/\//,$filepath);
 1409:         my $fullpath = $perlvar{'lonDaemons'};
 1410:         for (my $i=0;$i<@parts;$i++) {
 1411:             $fullpath .= '/'.$parts[$i];
 1412:             if ((-e $fullpath)!=1) {
 1413:                 mkdir($fullpath,0777);
 1414:             }
 1415:         }
 1416:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1417:         print $fh $env{'form.'.$formname};
 1418:         close($fh);
 1419:         return $fullpath.'/'.$fname;
 1420:     }
 1421:     
 1422: # Create the directory if not present
 1423:     $fname="$subdir/$fname";
 1424:     if ($coursedoc) {
 1425: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1426: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1427:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1428:             return &finishuserfileupload($docuname,$docudom,
 1429: 					 $formname,$fname,$parser,$allfiles,
 1430: 					 $codebase);
 1431:         } else {
 1432:             $fname=$env{'form.folder'}.'/'.$fname;
 1433:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1434: 				       $fname,$formname,$parser,
 1435: 				       $allfiles,$codebase);
 1436:         }
 1437:     } elsif (defined($destuname)) {
 1438:         my $docuname=$destuname;
 1439:         my $docudom=$destudom;
 1440: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1441: 				     $fname,$parser,$allfiles,$codebase);
 1442:         
 1443:     } else {
 1444:         my $docuname=$env{'user.name'};
 1445:         my $docudom=$env{'user.domain'};
 1446:         if (exists($env{'form.group'})) {
 1447:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1448:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1449:         }
 1450: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1451: 				     $fname,$parser,$allfiles,$codebase);
 1452:     }
 1453: }
 1454: 
 1455: sub finishuserfileupload {
 1456:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1457:     my $path=$docudom.'/'.$docuname.'/';
 1458:     my $filepath=$perlvar{'lonDocRoot'};
 1459:     my ($fnamepath,$file);
 1460:     $file=$fname;
 1461:     if ($fname=~m|/|) {
 1462:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1463: 	$path.=$fnamepath.'/';
 1464:     }
 1465:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1466:     my $count;
 1467:     for ($count=4;$count<=$#parts;$count++) {
 1468:         $filepath.="/$parts[$count]";
 1469:         if ((-e $filepath)!=1) {
 1470: 	    mkdir($filepath,0777);
 1471:         }
 1472:     }
 1473: # Save the file
 1474:     {
 1475: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1476: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1477: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1478: 	    return '/adm/notfound.html';
 1479: 	}
 1480: 	if (!print FH ($env{'form.'.$formname})) {
 1481: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1482: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1483: 	    return '/adm/notfound.html';
 1484: 	}
 1485: 	close(FH);
 1486:     }
 1487:     if ($parser eq 'parse') {
 1488:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1489: 						   $codebase);
 1490:         unless ($parse_result eq 'ok') {
 1491:             &logthis('Failed to parse '.$filepath.$file.
 1492: 		     ' for embedded media: '.$parse_result); 
 1493:         }
 1494:     }
 1495: # Notify homeserver to grep it
 1496: #
 1497:     my $docuhome=&homeserver($docuname,$docudom);
 1498:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1499:     if ($fetchresult eq 'ok') {
 1500: #
 1501: # Return the URL to it
 1502:         return '/uploaded/'.$path.$file;
 1503:     } else {
 1504:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1505: 		 ': '.$fetchresult);
 1506:         return '/adm/notfound.html';
 1507:     }    
 1508: }
 1509: 
 1510: sub extract_embedded_items {
 1511:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1512:     my @state = ();
 1513:     my %javafiles = (
 1514:                       codebase => '',
 1515:                       code => '',
 1516:                       archive => ''
 1517:                     );
 1518:     my %mediafiles = (
 1519:                       src => '',
 1520:                       movie => '',
 1521:                      );
 1522:     my $p;
 1523:     if ($content) {
 1524:         $p = HTML::LCParser->new($content);
 1525:     } else {
 1526:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1527:     }
 1528:     while (my $t=$p->get_token()) {
 1529: 	if ($t->[0] eq 'S') {
 1530: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1531: 	    push (@state, $tagname);
 1532:             if (lc($tagname) eq 'allow') {
 1533:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1534:             }
 1535: 	    if (lc($tagname) eq 'img') {
 1536: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1537: 	    }
 1538:             if (lc($tagname) eq 'script') {
 1539:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1540:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1541:                 } else {
 1542:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1543:                 }
 1544:             }
 1545:             if (lc($tagname) eq 'link') {
 1546:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1547:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1548:                 }
 1549:             }
 1550: 	    if (lc($tagname) eq 'object' ||
 1551: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1552: 		foreach my $item (keys(%javafiles)) {
 1553: 		    $javafiles{$item} = '';
 1554: 		}
 1555: 	    }
 1556: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1557: 		my $name = lc($attr->{'name'});
 1558: 		foreach my $item (keys(%javafiles)) {
 1559: 		    if ($name eq $item) {
 1560: 			$javafiles{$item} = $attr->{'value'};
 1561: 			last;
 1562: 		    }
 1563: 		}
 1564: 		foreach my $item (keys(%mediafiles)) {
 1565: 		    if ($name eq $item) {
 1566: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1567: 			last;
 1568: 		    }
 1569: 		}
 1570: 	    }
 1571: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1572: 		foreach my $item (keys(%javafiles)) {
 1573: 		    if ($attr->{$item}) {
 1574: 			$javafiles{$item} = $attr->{$item};
 1575: 			last;
 1576: 		    }
 1577: 		}
 1578: 		foreach my $item (keys(%mediafiles)) {
 1579: 		    if ($attr->{$item}) {
 1580: 			&add_filetype($allfiles,$attr->{$item},$item);
 1581: 			last;
 1582: 		    }
 1583: 		}
 1584: 	    }
 1585: 	} elsif ($t->[0] eq 'E') {
 1586: 	    my ($tagname) = ($t->[1]);
 1587: 	    if ($javafiles{'codebase'} ne '') {
 1588: 		$javafiles{'codebase'} .= '/';
 1589: 	    }  
 1590: 	    if (lc($tagname) eq 'applet' ||
 1591: 		lc($tagname) eq 'object' ||
 1592: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1593: 		) {
 1594: 		foreach my $item (keys(%javafiles)) {
 1595: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1596: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1597: 			&add_filetype($allfiles,$file,$item);
 1598: 		    }
 1599: 		}
 1600: 	    } 
 1601: 	    pop @state;
 1602: 	}
 1603:     }
 1604:     return 'ok';
 1605: }
 1606: 
 1607: sub add_filetype {
 1608:     my ($allfiles,$file,$type)=@_;
 1609:     if (exists($allfiles->{$file})) {
 1610: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1611: 	    push(@{$allfiles->{$file}}, &escape($type));
 1612: 	}
 1613:     } else {
 1614: 	@{$allfiles->{$file}} = (&escape($type));
 1615:     }
 1616: }
 1617: 
 1618: sub removeuploadedurl {
 1619:     my ($url)=@_;
 1620:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1621:     return &removeuserfile($uname,$udom,$fname);
 1622: }
 1623: 
 1624: sub removeuserfile {
 1625:     my ($docuname,$docudom,$fname)=@_;
 1626:     my $home=&homeserver($docuname,$docudom);
 1627:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1628: }
 1629: 
 1630: sub mkdiruserfile {
 1631:     my ($docuname,$docudom,$dir)=@_;
 1632:     my $home=&homeserver($docuname,$docudom);
 1633:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1634: }
 1635: 
 1636: sub renameuserfile {
 1637:     my ($docuname,$docudom,$old,$new)=@_;
 1638:     my $home=&homeserver($docuname,$docudom);
 1639:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1640: 		  &escape("$new"),$home);
 1641: }
 1642: 
 1643: # ------------------------------------------------------------------------- Log
 1644: 
 1645: sub log {
 1646:     my ($dom,$nam,$hom,$what)=@_;
 1647:     return critical("log:$dom:$nam:$what",$hom);
 1648: }
 1649: 
 1650: # ------------------------------------------------------------------ Course Log
 1651: #
 1652: # This routine flushes several buffers of non-mission-critical nature
 1653: #
 1654: 
 1655: sub flushcourselogs {
 1656:     &logthis('Flushing log buffers');
 1657: #
 1658: # course logs
 1659: # This is a log of all transactions in a course, which can be used
 1660: # for data mining purposes
 1661: #
 1662: # It also collects the courseid database, which lists last transaction
 1663: # times and course titles for all courseids
 1664: #
 1665:     my %courseidbuffer=();
 1666:     foreach (keys %courselogs) {
 1667:         my $crsid=$_;
 1668:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1669: 		          &escape($courselogs{$crsid}),
 1670: 		          $coursehombuf{$crsid}) eq 'ok') {
 1671: 	    delete $courselogs{$crsid};
 1672:         } else {
 1673:             &logthis('Failed to flush log buffer for '.$crsid);
 1674:             if (length($courselogs{$crsid})>40000) {
 1675:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1676:                         " exceeded maximum size, deleting.</font>");
 1677:                delete $courselogs{$crsid};
 1678:             }
 1679:         }
 1680:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1681:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1682: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1683:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1684:         } else {
 1685:            $courseidbuffer{$coursehombuf{$crsid}}=
 1686: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1687:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1688:         }
 1689:     }
 1690: #
 1691: # Write course id database (reverse lookup) to homeserver of courses 
 1692: # Is used in pickcourse
 1693: #
 1694:     foreach (keys %courseidbuffer) {
 1695:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1696:     }
 1697: #
 1698: # File accesses
 1699: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1700: #
 1701:     foreach my $entry (keys(%accesshash)) {
 1702:         if ($entry =~ /___count$/) {
 1703:             my ($dom,$name);
 1704:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1705:             if (! defined($dom) || $dom eq '' || 
 1706:                 ! defined($name) || $name eq '') {
 1707:                 my $cid = $env{'request.course.id'};
 1708:                 $dom  = $env{'request.'.$cid.'.domain'};
 1709:                 $name = $env{'request.'.$cid.'.num'};
 1710:             }
 1711:             my $value = $accesshash{$entry};
 1712:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1713:             my %temphash=($url => $value);
 1714:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1715:             if ($result eq 'ok') {
 1716:                 delete $accesshash{$entry};
 1717:             } elsif ($result eq 'unknown_cmd') {
 1718:                 # Target server has old code running on it.
 1719:                 my %temphash=($entry => $value);
 1720:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1721:                     delete $accesshash{$entry};
 1722:                 }
 1723:             }
 1724:         } else {
 1725:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1726:             my %temphash=($entry => $accesshash{$entry});
 1727:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1728:                 delete $accesshash{$entry};
 1729:             }
 1730:         }
 1731:     }
 1732: #
 1733: # Roles
 1734: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1735: #
 1736:     foreach (keys %userrolehash) {
 1737:         my $entry=$_;
 1738:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1739: 	    split(/\:/,$entry);
 1740:         if (&Apache::lonnet::put('nohist_userroles',
 1741:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1742:                 $rudom,$runame) eq 'ok') {
 1743: 	    delete $userrolehash{$entry};
 1744:         }
 1745:     }
 1746: #
 1747: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1748: #
 1749:     my %domrolebuffer = ();
 1750:     foreach my $entry (keys %domainrolehash) {
 1751:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1752:         if ($domrolebuffer{$rudom}) {
 1753:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1754:                       '='.&escape($domainrolehash{$entry});
 1755:         } else {
 1756:             $domrolebuffer{$rudom}.=&escape($entry).
 1757:                       '='.&escape($domainrolehash{$entry});
 1758:         }
 1759:         delete $domainrolehash{$entry};
 1760:     }
 1761:     foreach my $dom (keys(%domrolebuffer)) {
 1762:         foreach my $tryserver (keys %libserv) {
 1763:             if ($hostdom{$tryserver} eq $dom) {
 1764:                 unless (&reply('domroleput:'.$dom.':'.
 1765:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1766:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1767:                 }
 1768:             }
 1769:         }
 1770:     }
 1771:     $dumpcount++;
 1772: }
 1773: 
 1774: sub courselog {
 1775:     my $what=shift;
 1776:     $what=time.':'.$what;
 1777:     unless ($env{'request.course.id'}) { return ''; }
 1778:     $coursedombuf{$env{'request.course.id'}}=
 1779:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1780:     $coursenumbuf{$env{'request.course.id'}}=
 1781:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1782:     $coursehombuf{$env{'request.course.id'}}=
 1783:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1784:     $coursedescrbuf{$env{'request.course.id'}}=
 1785:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1786:     $courseinstcodebuf{$env{'request.course.id'}}=
 1787:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1788:     $courseownerbuf{$env{'request.course.id'}}=
 1789:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1790:     $coursetypebuf{$env{'request.course.id'}}=
 1791:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1792:     if (defined $courselogs{$env{'request.course.id'}}) {
 1793: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1794:     } else {
 1795: 	$courselogs{$env{'request.course.id'}}.=$what;
 1796:     }
 1797:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1798: 	&flushcourselogs();
 1799:     }
 1800: }
 1801: 
 1802: sub courseacclog {
 1803:     my $fnsymb=shift;
 1804:     unless ($env{'request.course.id'}) { return ''; }
 1805:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1806:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1807:         $what.=':POST';
 1808:         # FIXME: Probably ought to escape things....
 1809: 	foreach (keys %env) {
 1810:             if ($_=~/^form\.(.*)/) {
 1811: 		$what.=':'.$1.'='.$env{$_};
 1812:             }
 1813:         }
 1814:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1815:         # FIXME: We should not be depending on a form parameter that someone
 1816:         # editing lonsearchcat.pm might change in the future.
 1817:         if ($env{'form.phase'} eq 'course_search') {
 1818:             $what.= ':POST';
 1819:             # FIXME: Probably ought to escape things....
 1820:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1821:                                  'crsdiscuss') {
 1822:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1823:             }
 1824:         }
 1825:     }
 1826:     &courselog($what);
 1827: }
 1828: 
 1829: sub countacc {
 1830:     my $url=&declutter(shift);
 1831:     return if (! defined($url) || $url eq '');
 1832:     unless ($env{'request.course.id'}) { return ''; }
 1833:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1834:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1835:     $accesshash{$key}++;
 1836: }
 1837: 
 1838: sub linklog {
 1839:     my ($from,$to)=@_;
 1840:     $from=&declutter($from);
 1841:     $to=&declutter($to);
 1842:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1843:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1844: }
 1845:   
 1846: sub userrolelog {
 1847:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1848:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1849:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1850:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1851:         ($trole=~/^ta/)) {
 1852:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1853:        $userrolehash
 1854:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1855:                     =$tend.':'.$tstart;
 1856:     }
 1857:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1858:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1859:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1860:         ($trole=~/^sc/)) {
 1861:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1862:        $domainrolehash
 1863:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1864:                     = $tend.':'.$tstart;
 1865:     }
 1866: }
 1867: 
 1868: sub get_course_adv_roles {
 1869:     my $cid=shift;
 1870:     $cid=$env{'request.course.id'} unless (defined($cid));
 1871:     my %coursehash=&coursedescription($cid);
 1872:     my %nothide=();
 1873:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1874: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1875:     }
 1876:     my %returnhash=();
 1877:     my %dumphash=
 1878:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1879:     my $now=time;
 1880:     foreach (keys %dumphash) {
 1881: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1882:         if (($tstart) && ($tstart<0)) { next; }
 1883:         if (($tend) && ($tend<$now)) { next; }
 1884:         if (($tstart) && ($now<$tstart)) { next; }
 1885:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1886: 	if ($username eq '' || $domain eq '') { next; }
 1887: 	if ((&privileged($username,$domain)) && 
 1888: 	    (!$nothide{$username.':'.$domain})) { next; }
 1889: 	if ($role eq 'cr') { next; }
 1890:         my $key=&plaintext($role);
 1891:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1892:         if ($returnhash{$key}) {
 1893: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1894:         } else {
 1895:             $returnhash{$key}=$username.':'.$domain;
 1896:         }
 1897:      }
 1898:     return %returnhash;
 1899: }
 1900: 
 1901: sub get_my_roles {
 1902:     my ($uname,$udom)=@_;
 1903:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1904:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1905:     my %dumphash=
 1906:             &dump('nohist_userroles',$udom,$uname);
 1907:     my %returnhash=();
 1908:     my $now=time;
 1909:     foreach (keys %dumphash) {
 1910: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1911:         if (($tstart) && ($tstart<0)) { next; }
 1912:         if (($tend) && ($tend<$now)) { next; }
 1913:         if (($tstart) && ($now<$tstart)) { next; }
 1914:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1915: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1916:      }
 1917:     return %returnhash;
 1918: }
 1919: 
 1920: # ----------------------------------------------------- Frontpage Announcements
 1921: #
 1922: #
 1923: 
 1924: sub postannounce {
 1925:     my ($server,$text)=@_;
 1926:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1927:     unless ($text=~/\w/) { $text=''; }
 1928:     return &reply('setannounce:'.&escape($text),$server);
 1929: }
 1930: 
 1931: sub getannounce {
 1932: 
 1933:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1934: 	my $announcement='';
 1935: 	while (<$fh>) { $announcement .=$_; }
 1936: 	close($fh);
 1937: 	if ($announcement=~/\w/) { 
 1938: 	    return 
 1939:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1940:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1941: 	} else {
 1942: 	    return '';
 1943: 	}
 1944:     } else {
 1945: 	return '';
 1946:     }
 1947: }
 1948: 
 1949: # ---------------------------------------------------------- Course ID routines
 1950: # Deal with domain's nohist_courseid.db files
 1951: #
 1952: 
 1953: sub courseidput {
 1954:     my ($domain,$what,$coursehome)=@_;
 1955:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1956: }
 1957: 
 1958: sub courseiddump {
 1959:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
 1960:     my %returnhash=();
 1961:     unless ($domfilter) { $domfilter=''; }
 1962:     foreach my $tryserver (keys %libserv) {
 1963:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1964: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1965: 	        foreach (
 1966:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1967: 			       $sincefilter.':'.&escape($descfilter).':'.
 1968:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
 1969:                                $tryserver))) {
 1970: 		    my ($key,$value)=split(/\=/,$_);
 1971:                     if (($key) && ($value)) {
 1972: 		        $returnhash{&unescape($key)}=$value;
 1973:                     }
 1974:                 }
 1975:             }
 1976:         }
 1977:     }
 1978:     return %returnhash;
 1979: }
 1980: 
 1981: # ---------------------------------------------------------- DC e-mail
 1982: 
 1983: sub dcmailput {
 1984:     my ($domain,$msgid,$message,$server)=@_;
 1985:     my $status = &Apache::lonnet::critical(
 1986:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 1987:        &escape($message),$server);
 1988:     return $status;
 1989: }
 1990: 
 1991: sub dcmaildump {
 1992:     my ($dom,$startdate,$enddate,$senders) = @_;
 1993:     my %returnhash=();
 1994:     if (exists($domain_primary{$dom})) {
 1995:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 1996:                                                          &escape($enddate).':';
 1997: 	my @esc_senders=map { &escape($_)} @$senders;
 1998: 	$cmd.=&escape(join('&',@esc_senders));
 1999: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2000:             my ($key,$value) = split(/\=/,$_);
 2001:             if (($key) && ($value)) {
 2002:                 $returnhash{&unescape($key)} = &unescape($value);
 2003:             }
 2004:         }
 2005:     }
 2006:     return %returnhash;
 2007: }
 2008: # ---------------------------------------------------------- Domain roles
 2009: 
 2010: sub get_domain_roles {
 2011:     my ($dom,$roles,$startdate,$enddate)=@_;
 2012:     if (undef($startdate) || $startdate eq '') {
 2013:         $startdate = '.';
 2014:     }
 2015:     if (undef($enddate) || $enddate eq '') {
 2016:         $enddate = '.';
 2017:     }
 2018:     my $rolelist = join(':',@{$roles});
 2019:     my %personnel = ();
 2020:     foreach my $tryserver (keys(%libserv)) {
 2021:         if ($hostdom{$tryserver} eq $dom) {
 2022:             %{$personnel{$tryserver}}=();
 2023:             foreach (
 2024:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2025:                    &escape($startdate).':'.&escape($enddate).':'.
 2026:                    &escape($rolelist), $tryserver))) {
 2027:                 my($key,$value) = split(/\=/,$_);
 2028:                 if (($key) && ($value)) {
 2029:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     return %personnel;
 2035: }
 2036: 
 2037: # ----------------------------------------------------------- Check out an item
 2038: 
 2039: sub get_first_access {
 2040:     my ($type,$argsymb)=@_;
 2041:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2042:     if ($argsymb) { $symb=$argsymb; }
 2043:     my ($map,$id,$res)=&decode_symb($symb);
 2044:     if ($type eq 'map') {
 2045: 	$res=&symbread($map);
 2046:     } else {
 2047: 	$res=$symb;
 2048:     }
 2049:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2050:     return $times{"$courseid\0$res"};
 2051: }
 2052: 
 2053: sub set_first_access {
 2054:     my ($type)=@_;
 2055:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2056:     my ($map,$id,$res)=&decode_symb($symb);
 2057:     if ($type eq 'map') {
 2058: 	$res=&symbread($map);
 2059:     } else {
 2060: 	$res=$symb;
 2061:     }
 2062:     my $firstaccess=&get_first_access($type,$symb);
 2063:     if (!$firstaccess) {
 2064: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2065:     }
 2066:     return 'already_set';
 2067: }
 2068: 
 2069: sub checkout {
 2070:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2071:     my $now=time;
 2072:     my $lonhost=$perlvar{'lonHostID'};
 2073:     my $infostr=&escape(
 2074:                  'CHECKOUTTOKEN&'.
 2075:                  $tuname.'&'.
 2076:                  $tudom.'&'.
 2077:                  $tcrsid.'&'.
 2078:                  $symb.'&'.
 2079: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2080:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2081:     if ($token=~/^error\:/) { 
 2082:         &logthis("<font color=\"blue\">WARNING: ".
 2083:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2084:                  "</font>");
 2085:         return ''; 
 2086:     }
 2087: 
 2088:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2089:     $token=~tr/a-z/A-Z/;
 2090: 
 2091:     my %infohash=('resource.0.outtoken' => $token,
 2092:                   'resource.0.checkouttime' => $now,
 2093:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2094: 
 2095:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2096:        return '';
 2097:     } else {
 2098:         &logthis("<font color=\"blue\">WARNING: ".
 2099:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2100:                  "</font>");
 2101:     }    
 2102: 
 2103:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2104:                          &escape('Checkout '.$infostr.' - '.
 2105:                                                  $token)) ne 'ok') {
 2106: 	return '';
 2107:     } else {
 2108:         &logthis("<font color=\"blue\">WARNING: ".
 2109:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2110:                  "</font>");
 2111:     }
 2112:     return $token;
 2113: }
 2114: 
 2115: # ------------------------------------------------------------ Check in an item
 2116: 
 2117: sub checkin {
 2118:     my $token=shift;
 2119:     my $now=time;
 2120:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2121:     $lonhost=~tr/A-Z/a-z/;
 2122:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2123:     $dtoken=~s/\W/\_/g;
 2124:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2125:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2126: 
 2127:     unless (($tuname) && ($tudom)) {
 2128:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2129:         return '';
 2130:     }
 2131:     
 2132:     unless (&allowed('mgr',$tcrsid)) {
 2133:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2134:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2135:         return '';
 2136:     }
 2137: 
 2138:     my %infohash=('resource.0.intoken' => $token,
 2139:                   'resource.0.checkintime' => $now,
 2140:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2141: 
 2142:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2143:        return '';
 2144:     }    
 2145: 
 2146:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2147:                          &escape('Checkin - '.$token)) ne 'ok') {
 2148: 	return '';
 2149:     }
 2150: 
 2151:     return ($symb,$tuname,$tudom,$tcrsid);    
 2152: }
 2153: 
 2154: # --------------------------------------------- Set Expire Date for Spreadsheet
 2155: 
 2156: sub expirespread {
 2157:     my ($uname,$udom,$stype,$usymb)=@_;
 2158:     my $cid=$env{'request.course.id'}; 
 2159:     if ($cid) {
 2160:        my $now=time;
 2161:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2162:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2163:                             $env{'course.'.$cid.'.num'}.
 2164: 	        	    ':nohist_expirationdates:'.
 2165:                             &escape($key).'='.$now,
 2166:                             $env{'course.'.$cid.'.home'})
 2167:     }
 2168:     return 'ok';
 2169: }
 2170: 
 2171: # ----------------------------------------------------- Devalidate Spreadsheets
 2172: 
 2173: sub devalidate {
 2174:     my ($symb,$uname,$udom)=@_;
 2175:     my $cid=$env{'request.course.id'}; 
 2176:     if ($cid) {
 2177:         # delete the stored spreadsheets for
 2178:         # - the student level sheet of this user in course's homespace
 2179:         # - the assessment level sheet for this resource 
 2180:         #   for this user in user's homespace
 2181: 	# - current conditional state info
 2182: 	my $key=$uname.':'.$udom.':';
 2183:         my $status=
 2184: 	    &del('nohist_calculatedsheets',
 2185: 		 [$key.'studentcalc:'],
 2186: 		 $env{'course.'.$cid.'.domain'},
 2187: 		 $env{'course.'.$cid.'.num'})
 2188: 		.' '.
 2189: 	    &del('nohist_calculatedsheets_'.$cid,
 2190: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2191:         unless ($status eq 'ok ok') {
 2192:            &logthis('Could not devalidate spreadsheet '.
 2193:                     $uname.' at '.$udom.' for '.
 2194: 		    $symb.': '.$status);
 2195:         }
 2196: 	&delenv('user.state.'.$cid);
 2197:     }
 2198: }
 2199: 
 2200: sub get_scalar {
 2201:     my ($string,$end) = @_;
 2202:     my $value;
 2203:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2204: 	$value = $1;
 2205:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2206: 	$value = $1;
 2207:     }
 2208:     return &unescape($value);
 2209: }
 2210: 
 2211: sub array2str {
 2212:   my (@array) = @_;
 2213:   my $result=&arrayref2str(\@array);
 2214:   $result=~s/^__ARRAY_REF__//;
 2215:   $result=~s/__END_ARRAY_REF__$//;
 2216:   return $result;
 2217: }
 2218: 
 2219: sub arrayref2str {
 2220:   my ($arrayref) = @_;
 2221:   my $result='__ARRAY_REF__';
 2222:   foreach my $elem (@$arrayref) {
 2223:     if(ref($elem) eq 'ARRAY') {
 2224:       $result.=&arrayref2str($elem).'&';
 2225:     } elsif(ref($elem) eq 'HASH') {
 2226:       $result.=&hashref2str($elem).'&';
 2227:     } elsif(ref($elem)) {
 2228:       #print("Got a ref of ".(ref($elem))." skipping.");
 2229:     } else {
 2230:       $result.=&escape($elem).'&';
 2231:     }
 2232:   }
 2233:   $result=~s/\&$//;
 2234:   $result .= '__END_ARRAY_REF__';
 2235:   return $result;
 2236: }
 2237: 
 2238: sub hash2str {
 2239:   my (%hash) = @_;
 2240:   my $result=&hashref2str(\%hash);
 2241:   $result=~s/^__HASH_REF__//;
 2242:   $result=~s/__END_HASH_REF__$//;
 2243:   return $result;
 2244: }
 2245: 
 2246: sub hashref2str {
 2247:   my ($hashref)=@_;
 2248:   my $result='__HASH_REF__';
 2249:   foreach (sort(keys(%$hashref))) {
 2250:     if (ref($_) eq 'ARRAY') {
 2251:       $result.=&arrayref2str($_).'=';
 2252:     } elsif (ref($_) eq 'HASH') {
 2253:       $result.=&hashref2str($_).'=';
 2254:     } elsif (ref($_)) {
 2255:       $result.='=';
 2256:       #print("Got a ref of ".(ref($_))." skipping.");
 2257:     } else {
 2258: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2259:     }
 2260: 
 2261:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2262:       $result.=&arrayref2str($hashref->{$_}).'&';
 2263:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2264:       $result.=&hashref2str($hashref->{$_}).'&';
 2265:     } elsif(ref($hashref->{$_})) {
 2266:        $result.='&';
 2267:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2268:     } else {
 2269:       $result.=&escape($hashref->{$_}).'&';
 2270:     }
 2271:   }
 2272:   $result=~s/\&$//;
 2273:   $result .= '__END_HASH_REF__';
 2274:   return $result;
 2275: }
 2276: 
 2277: sub str2hash {
 2278:     my ($string)=@_;
 2279:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2280:     return %$hash;
 2281: }
 2282: 
 2283: sub str2hashref {
 2284:   my ($string) = @_;
 2285: 
 2286:   my %hash;
 2287: 
 2288:   if($string !~ /^__HASH_REF__/) {
 2289:       if (! ($string eq '' || !defined($string))) {
 2290: 	  $hash{'error'}='Not hash reference';
 2291:       }
 2292:       return (\%hash, $string);
 2293:   }
 2294: 
 2295:   $string =~ s/^__HASH_REF__//;
 2296: 
 2297:   while($string !~ /^__END_HASH_REF__/) {
 2298:       #key
 2299:       my $key='';
 2300:       if($string =~ /^__HASH_REF__/) {
 2301:           ($key, $string)=&str2hashref($string);
 2302:           if(defined($key->{'error'})) {
 2303:               $hash{'error'}='Bad data';
 2304:               return (\%hash, $string);
 2305:           }
 2306:       } elsif($string =~ /^__ARRAY_REF__/) {
 2307:           ($key, $string)=&str2arrayref($string);
 2308:           if($key->[0] eq 'Array reference error') {
 2309:               $hash{'error'}='Bad data';
 2310:               return (\%hash, $string);
 2311:           }
 2312:       } else {
 2313:           $string =~ s/^(.*?)=//;
 2314: 	  $key=&unescape($1);
 2315:       }
 2316:       $string =~ s/^=//;
 2317: 
 2318:       #value
 2319:       my $value='';
 2320:       if($string =~ /^__HASH_REF__/) {
 2321:           ($value, $string)=&str2hashref($string);
 2322:           if(defined($value->{'error'})) {
 2323:               $hash{'error'}='Bad data';
 2324:               return (\%hash, $string);
 2325:           }
 2326:       } elsif($string =~ /^__ARRAY_REF__/) {
 2327:           ($value, $string)=&str2arrayref($string);
 2328:           if($value->[0] eq 'Array reference error') {
 2329:               $hash{'error'}='Bad data';
 2330:               return (\%hash, $string);
 2331:           }
 2332:       } else {
 2333: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2334:       }
 2335:       $string =~ s/^&//;
 2336: 
 2337:       $hash{$key}=$value;
 2338:   }
 2339: 
 2340:   $string =~ s/^__END_HASH_REF__//;
 2341: 
 2342:   return (\%hash, $string);
 2343: }
 2344: 
 2345: sub str2array {
 2346:     my ($string)=@_;
 2347:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2348:     return @$array;
 2349: }
 2350: 
 2351: sub str2arrayref {
 2352:   my ($string) = @_;
 2353:   my @array;
 2354: 
 2355:   if($string !~ /^__ARRAY_REF__/) {
 2356:       if (! ($string eq '' || !defined($string))) {
 2357: 	  $array[0]='Array reference error';
 2358:       }
 2359:       return (\@array, $string);
 2360:   }
 2361: 
 2362:   $string =~ s/^__ARRAY_REF__//;
 2363: 
 2364:   while($string !~ /^__END_ARRAY_REF__/) {
 2365:       my $value='';
 2366:       if($string =~ /^__HASH_REF__/) {
 2367:           ($value, $string)=&str2hashref($string);
 2368:           if(defined($value->{'error'})) {
 2369:               $array[0] ='Array reference error';
 2370:               return (\@array, $string);
 2371:           }
 2372:       } elsif($string =~ /^__ARRAY_REF__/) {
 2373:           ($value, $string)=&str2arrayref($string);
 2374:           if($value->[0] eq 'Array reference error') {
 2375:               $array[0] ='Array reference error';
 2376:               return (\@array, $string);
 2377:           }
 2378:       } else {
 2379: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2380:       }
 2381:       $string =~ s/^&//;
 2382: 
 2383:       push(@array, $value);
 2384:   }
 2385: 
 2386:   $string =~ s/^__END_ARRAY_REF__//;
 2387: 
 2388:   return (\@array, $string);
 2389: }
 2390: 
 2391: # -------------------------------------------------------------------Temp Store
 2392: 
 2393: sub tmpreset {
 2394:   my ($symb,$namespace,$domain,$stuname) = @_;
 2395:   if (!$symb) {
 2396:     $symb=&symbread();
 2397:     if (!$symb) { $symb= $env{'request.url'}; }
 2398:   }
 2399:   $symb=escape($symb);
 2400: 
 2401:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2402:   $namespace=~s/\//\_/g;
 2403:   $namespace=~s/\W//g;
 2404: 
 2405:   if (!$domain) { $domain=$env{'user.domain'}; }
 2406:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2407:   if ($domain eq 'public' && $stuname eq 'public') {
 2408:       $stuname=$ENV{'REMOTE_ADDR'};
 2409:   }
 2410:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2411:   my %hash;
 2412:   if (tie(%hash,'GDBM_File',
 2413: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2414: 	  &GDBM_WRCREAT(),0640)) {
 2415:     foreach my $key (keys %hash) {
 2416:       if ($key=~ /:$symb/) {
 2417: 	delete($hash{$key});
 2418:       }
 2419:     }
 2420:   }
 2421: }
 2422: 
 2423: sub tmpstore {
 2424:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2425: 
 2426:   if (!$symb) {
 2427:     $symb=&symbread();
 2428:     if (!$symb) { $symb= $env{'request.url'}; }
 2429:   }
 2430:   $symb=escape($symb);
 2431: 
 2432:   if (!$namespace) {
 2433:     # I don't think we would ever want to store this for a course.
 2434:     # it seems this will only be used if we don't have a course.
 2435:     #$namespace=$env{'request.course.id'};
 2436:     #if (!$namespace) {
 2437:       $namespace=$env{'request.state'};
 2438:     #}
 2439:   }
 2440:   $namespace=~s/\//\_/g;
 2441:   $namespace=~s/\W//g;
 2442:   if (!$domain) { $domain=$env{'user.domain'}; }
 2443:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2444:   if ($domain eq 'public' && $stuname eq 'public') {
 2445:       $stuname=$ENV{'REMOTE_ADDR'};
 2446:   }
 2447:   my $now=time;
 2448:   my %hash;
 2449:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2450:   if (tie(%hash,'GDBM_File',
 2451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2452: 	  &GDBM_WRCREAT(),0640)) {
 2453:     $hash{"version:$symb"}++;
 2454:     my $version=$hash{"version:$symb"};
 2455:     my $allkeys=''; 
 2456:     foreach my $key (keys(%$storehash)) {
 2457:       $allkeys.=$key.':';
 2458:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2459:     }
 2460:     $hash{"$version:$symb:timestamp"}=$now;
 2461:     $allkeys.='timestamp';
 2462:     $hash{"$version:keys:$symb"}=$allkeys;
 2463:     if (untie(%hash)) {
 2464:       return 'ok';
 2465:     } else {
 2466:       return "error:$!";
 2467:     }
 2468:   } else {
 2469:     return "error:$!";
 2470:   }
 2471: }
 2472: 
 2473: # -----------------------------------------------------------------Temp Restore
 2474: 
 2475: sub tmprestore {
 2476:   my ($symb,$namespace,$domain,$stuname) = @_;
 2477: 
 2478:   if (!$symb) {
 2479:     $symb=&symbread();
 2480:     if (!$symb) { $symb= $env{'request.url'}; }
 2481:   }
 2482:   $symb=escape($symb);
 2483: 
 2484:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2485: 
 2486:   if (!$domain) { $domain=$env{'user.domain'}; }
 2487:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2488:   if ($domain eq 'public' && $stuname eq 'public') {
 2489:       $stuname=$ENV{'REMOTE_ADDR'};
 2490:   }
 2491:   my %returnhash;
 2492:   $namespace=~s/\//\_/g;
 2493:   $namespace=~s/\W//g;
 2494:   my %hash;
 2495:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2496:   if (tie(%hash,'GDBM_File',
 2497: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2498: 	  &GDBM_READER(),0640)) {
 2499:     my $version=$hash{"version:$symb"};
 2500:     $returnhash{'version'}=$version;
 2501:     my $scope;
 2502:     for ($scope=1;$scope<=$version;$scope++) {
 2503:       my $vkeys=$hash{"$scope:keys:$symb"};
 2504:       my @keys=split(/:/,$vkeys);
 2505:       my $key;
 2506:       $returnhash{"$scope:keys"}=$vkeys;
 2507:       foreach $key (@keys) {
 2508: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2509: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2510:       }
 2511:     }
 2512:     if (!(untie(%hash))) {
 2513:       return "error:$!";
 2514:     }
 2515:   } else {
 2516:     return "error:$!";
 2517:   }
 2518:   return %returnhash;
 2519: }
 2520: 
 2521: # ----------------------------------------------------------------------- Store
 2522: 
 2523: sub store {
 2524:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2525:     my $home='';
 2526: 
 2527:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2528: 
 2529:     $symb=&symbclean($symb);
 2530:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2531: 
 2532:     if (!$domain) { $domain=$env{'user.domain'}; }
 2533:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2534: 
 2535:     &devalidate($symb,$stuname,$domain);
 2536: 
 2537:     $symb=escape($symb);
 2538:     if (!$namespace) { 
 2539:        unless ($namespace=$env{'request.course.id'}) { 
 2540:           return ''; 
 2541:        } 
 2542:     }
 2543:     if (!$home) { $home=$env{'user.home'}; }
 2544: 
 2545:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2546:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2547: 
 2548:     my $namevalue='';
 2549:     foreach (keys %$storehash) {
 2550:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2551:     }
 2552:     $namevalue=~s/\&$//;
 2553:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2554:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2555: }
 2556: 
 2557: # -------------------------------------------------------------- Critical Store
 2558: 
 2559: sub cstore {
 2560:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2561:     my $home='';
 2562: 
 2563:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2564: 
 2565:     $symb=&symbclean($symb);
 2566:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2567: 
 2568:     if (!$domain) { $domain=$env{'user.domain'}; }
 2569:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2570: 
 2571:     &devalidate($symb,$stuname,$domain);
 2572: 
 2573:     $symb=escape($symb);
 2574:     if (!$namespace) { 
 2575:        unless ($namespace=$env{'request.course.id'}) { 
 2576:           return ''; 
 2577:        } 
 2578:     }
 2579:     if (!$home) { $home=$env{'user.home'}; }
 2580: 
 2581:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2582:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2583: 
 2584:     my $namevalue='';
 2585:     foreach (keys %$storehash) {
 2586:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2587:     }
 2588:     $namevalue=~s/\&$//;
 2589:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2590:     return critical
 2591:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2592: }
 2593: 
 2594: # --------------------------------------------------------------------- Restore
 2595: 
 2596: sub restore {
 2597:     my ($symb,$namespace,$domain,$stuname) = @_;
 2598:     my $home='';
 2599: 
 2600:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2601: 
 2602:     if (!$symb) {
 2603:       unless ($symb=escape(&symbread())) { return ''; }
 2604:     } else {
 2605:       $symb=&escape(&symbclean($symb));
 2606:     }
 2607:     if (!$namespace) { 
 2608:        unless ($namespace=$env{'request.course.id'}) { 
 2609:           return ''; 
 2610:        } 
 2611:     }
 2612:     if (!$domain) { $domain=$env{'user.domain'}; }
 2613:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2614:     if (!$home) { $home=$env{'user.home'}; }
 2615:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2616: 
 2617:     my %returnhash=();
 2618:     foreach (split(/\&/,$answer)) {
 2619: 	my ($name,$value)=split(/\=/,$_);
 2620:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2621:     }
 2622:     my $version;
 2623:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2624:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2625:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2626:        }
 2627:     }
 2628:     return %returnhash;
 2629: }
 2630: 
 2631: # ---------------------------------------------------------- Course Description
 2632: 
 2633: sub coursedescription {
 2634:     my ($courseid,$args)=@_;
 2635:     $courseid=~s/^\///;
 2636:     $courseid=~s/\_/\//g;
 2637:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2638:     my $chome=&homeserver($cnum,$cdomain);
 2639:     my $normalid=$cdomain.'_'.$cnum;
 2640:     # need to always cache even if we get errors otherwise we keep 
 2641:     # trying and trying and trying to get the course description.
 2642:     my %envhash=();
 2643:     my %returnhash=();
 2644:     
 2645:     my $expiretime=600;
 2646:     if ($env{'request.course.id'} eq $normalid) {
 2647: 	$expiretime=120;
 2648:     }
 2649: 
 2650:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2651:     if (!$args->{'freshen_cache'}
 2652: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2653: 	foreach my $key (keys(%env)) {
 2654: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2655: 	    my ($setting) = $1;
 2656: 	    $returnhash{$setting} = $env{$key};
 2657: 	}
 2658: 	return %returnhash;
 2659:     }
 2660: 
 2661:     # get the data agin
 2662:     if (!$args->{'one_time'}) {
 2663: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2664:     }
 2665:     if ($chome ne 'no_host') {
 2666:        %returnhash=&dump('environment',$cdomain,$cnum);
 2667:        if (!exists($returnhash{'con_lost'})) {
 2668:            $returnhash{'home'}= $chome;
 2669: 	   $returnhash{'domain'} = $cdomain;
 2670: 	   $returnhash{'num'} = $cnum;
 2671:            if (!defined($returnhash{'type'})) {
 2672:                $returnhash{'type'} = 'Course';
 2673:            }
 2674:            while (my ($name,$value) = each %returnhash) {
 2675:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2676:            }
 2677:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2678:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2679: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2680:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2681:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2682:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2683:        }
 2684:     }
 2685:     if (!$args->{'one_time'}) {
 2686: 	&appenv(%envhash);
 2687:     }
 2688:     return %returnhash;
 2689: }
 2690: 
 2691: # -------------------------------------------------See if a user is privileged
 2692: 
 2693: sub privileged {
 2694:     my ($username,$domain)=@_;
 2695:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2696: 			&homeserver($username,$domain));
 2697:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2698:     my $now=time;
 2699:     if ($rolesdump ne '') {
 2700:         foreach (split(/&/,$rolesdump)) {
 2701: 	    if ($_!~/^rolesdef_/) {
 2702: 		my ($area,$role)=split(/=/,$_);
 2703: 		$area=~s/\_\w\w$//;
 2704: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2705: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2706: 		    my $active=1;
 2707: 		    if ($tend) {
 2708: 			if ($tend<$now) { $active=0; }
 2709: 		    }
 2710: 		    if ($tstart) {
 2711: 			if ($tstart>$now) { $active=0; }
 2712: 		    }
 2713: 		    if ($active) { return 1; }
 2714: 		}
 2715: 	    }
 2716: 	}
 2717:     }
 2718:     return 0;
 2719: }
 2720: 
 2721: # -------------------------------------------------------- Get user privileges
 2722: 
 2723: sub rolesinit {
 2724:     my ($domain,$username,$authhost)=@_;
 2725:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2726:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2727:     my %allroles=();
 2728:     my %allgroups=();   
 2729:     my $now=time;
 2730:     my %userroles = ('user.login.time' => $now);
 2731:     my $group_privs;
 2732: 
 2733:     if ($rolesdump ne '') {
 2734:         foreach (split(/&/,$rolesdump)) {
 2735: 	  if ($_!~/^rolesdef_/) {
 2736:             my ($area,$role)=split(/=/,$_);
 2737: 	    $area=~s/\_\w\w$//;
 2738:             my ($trole,$tend,$tstart,$group_privs);
 2739: 	    if ($role=~/^cr/) { 
 2740: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2741: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2742: 		    ($tend,$tstart)=split('_',$trest);
 2743: 		} else {
 2744: 		    $trole=$role;
 2745: 		}
 2746:             } elsif ($role =~ m|^gr/|) {
 2747:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2748:                 ($trole,$group_privs) = split(/\//,$trole);
 2749:                 $group_privs = &unescape($group_privs);
 2750: 	    } else {
 2751: 		($trole,$tend,$tstart)=split(/_/,$role);
 2752: 	    }
 2753: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2754: 					 $username);
 2755: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2756:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2757:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2758:             if (($area ne '') && ($trole ne '')) {
 2759: 		my $spec=$trole.'.'.$area;
 2760: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2761: 		if ($trole =~ /^cr\//) {
 2762:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2763:                 } elsif ($trole eq 'gr') {
 2764:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2765: 		} else {
 2766:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2767: 		}
 2768:             }
 2769:           }
 2770:         }
 2771:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2772:         $userroles{'user.adv'}    = $adv;
 2773: 	$userroles{'user.author'} = $author;
 2774:         $env{'user.adv'}=$adv;
 2775:     }
 2776:     return \%userroles;  
 2777: }
 2778: 
 2779: sub set_arearole {
 2780:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2781: # log the associated role with the area
 2782:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2783:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2784: }
 2785: 
 2786: sub custom_roleprivs {
 2787:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2788:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2789:     my $homsvr=homeserver($rauthor,$rdomain);
 2790:     if ($hostname{$homsvr} ne '') {
 2791:         my ($rdummy,$roledef)=
 2792:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2793:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2794:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2795:             if (defined($syspriv)) {
 2796:                 $$allroles{'cm./'}.=':'.$syspriv;
 2797:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2798:             }
 2799:             if ($tdomain ne '') {
 2800:                 if (defined($dompriv)) {
 2801:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2802:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2803:                 }
 2804:                 if (($trest ne '') && (defined($coursepriv))) {
 2805:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2806:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2807:                 }
 2808:             }
 2809:         }
 2810:     }
 2811: }
 2812: 
 2813: sub group_roleprivs {
 2814:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2815:     my $access = 1;
 2816:     my $now = time;
 2817:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2818:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2819:     if ($access) {
 2820:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2821:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2822:     }
 2823: }
 2824: 
 2825: sub standard_roleprivs {
 2826:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2827:     if (defined($pr{$trole.':s'})) {
 2828:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2829:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2830:     }
 2831:     if ($tdomain ne '') {
 2832:         if (defined($pr{$trole.':d'})) {
 2833:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2834:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2835:         }
 2836:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2837:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2838:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2839:         }
 2840:     }
 2841: }
 2842: 
 2843: sub set_userprivs {
 2844:     my ($userroles,$allroles,$allgroups) = @_; 
 2845:     my $author=0;
 2846:     my $adv=0;
 2847:     my %grouproles = ();
 2848:     if (keys(%{$allgroups}) > 0) {
 2849:         foreach my $role (keys %{$allroles}) {
 2850:             my ($trole,$area,$sec,$extendedarea);
 2851:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
 2852:                 $trole = $1;
 2853:                 $area = $2;
 2854:                 $sec = $3;
 2855:                 $extendedarea = $area.$sec;
 2856:                 if (exists($$allgroups{$area})) {
 2857:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2858:                         my $spec = $trole.'.'.$extendedarea;
 2859:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2860:                                                 $$allgroups{$area}{$group};
 2861:                     }
 2862:                 }
 2863:             }
 2864:         }
 2865:     }
 2866:     foreach (keys(%grouproles)) {
 2867:         $$allroles{$_} = $grouproles{$_};
 2868:     }
 2869:     foreach (keys %{$allroles}) {
 2870:         my %thesepriv=();
 2871:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2872:         foreach (split(/:/,$$allroles{$_})) {
 2873:             if ($_ ne '') {
 2874:                 my ($privilege,$restrictions)=split(/&/,$_);
 2875:                 if ($restrictions eq '') {
 2876:                     $thesepriv{$privilege}='F';
 2877:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2878:                     $thesepriv{$privilege}.=$restrictions;
 2879:                 }
 2880:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2881:             }
 2882:         }
 2883:         my $thesestr='';
 2884:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2885:         $userroles->{'user.priv.'.$_} = $thesestr;
 2886:     }
 2887:     return ($author,$adv);
 2888: }
 2889: 
 2890: # --------------------------------------------------------------- get interface
 2891: 
 2892: sub get {
 2893:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2894:    my $items='';
 2895:    foreach (@$storearr) {
 2896:        $items.=escape($_).'&';
 2897:    }
 2898:    $items=~s/\&$//;
 2899:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2900:    if (!$uname) { $uname=$env{'user.name'}; }
 2901:    my $uhome=&homeserver($uname,$udomain);
 2902: 
 2903:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2904:    my @pairs=split(/\&/,$rep);
 2905:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2906:      return @pairs;
 2907:    }
 2908:    my %returnhash=();
 2909:    my $i=0;
 2910:    foreach (@$storearr) {
 2911:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2912:       $i++;
 2913:    }
 2914:    return %returnhash;
 2915: }
 2916: 
 2917: # --------------------------------------------------------------- del interface
 2918: 
 2919: sub del {
 2920:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2921:    my $items='';
 2922:    foreach (@$storearr) {
 2923:        $items.=escape($_).'&';
 2924:    }
 2925:    $items=~s/\&$//;
 2926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2927:    if (!$uname) { $uname=$env{'user.name'}; }
 2928:    my $uhome=&homeserver($uname,$udomain);
 2929: 
 2930:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2931: }
 2932: 
 2933: # -------------------------------------------------------------- dump interface
 2934: 
 2935: sub dump {
 2936:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2937:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2938:     if (!$uname) { $uname=$env{'user.name'}; }
 2939:     my $uhome=&homeserver($uname,$udomain);
 2940:     if ($regexp) {
 2941: 	$regexp=&escape($regexp);
 2942:     } else {
 2943: 	$regexp='.';
 2944:     }
 2945:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2946:     my @pairs=split(/\&/,$rep);
 2947:     my %returnhash=();
 2948:     foreach my $item (@pairs) {
 2949: 	my ($key,$value)=split(/=/,$item,2);
 2950: 	$key = &unescape($key);
 2951: 	next if ($key =~ /^error: 2 /);
 2952: 	$returnhash{$key}=&thaw_unescape($value);
 2953:     }
 2954:     return %returnhash;
 2955: }
 2956: 
 2957: # --------------------------------------------------------- dumpstore interface
 2958: 
 2959: sub dumpstore {
 2960:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2961:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2962: }
 2963: 
 2964: # -------------------------------------------------------------- keys interface
 2965: 
 2966: sub getkeys {
 2967:    my ($namespace,$udomain,$uname)=@_;
 2968:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2969:    if (!$uname) { $uname=$env{'user.name'}; }
 2970:    my $uhome=&homeserver($uname,$udomain);
 2971:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2972:    my @keyarray=();
 2973:    foreach (split(/\&/,$rep)) {
 2974:       push (@keyarray,&unescape($_));
 2975:    }
 2976:    return @keyarray;
 2977: }
 2978: 
 2979: # --------------------------------------------------------------- currentdump
 2980: sub currentdump {
 2981:    my ($courseid,$sdom,$sname)=@_;
 2982:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2983:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2984:    $sname    = $env{'user.name'}         if (! defined($sname));
 2985:    my $uhome = &homeserver($sname,$sdom);
 2986:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2987:    return if ($rep =~ /^(error:|no_such_host)/);
 2988:    #
 2989:    my %returnhash=();
 2990:    #
 2991:    if ($rep eq "unknown_cmd") { 
 2992:        # an old lond will not know currentdump
 2993:        # Do a dump and make it look like a currentdump
 2994:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2995:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2996:        my %hash = @tmp;
 2997:        @tmp=();
 2998:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2999:    } else {
 3000:        my @pairs=split(/\&/,$rep);
 3001:        foreach (@pairs) {
 3002:            my ($key,$value)=split(/=/,$_);
 3003:            my ($symb,$param) = split(/:/,$key);
 3004:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3005:                                                         &thaw_unescape($value);
 3006:        }
 3007:    }
 3008:    return %returnhash;
 3009: }
 3010: 
 3011: sub convert_dump_to_currentdump{
 3012:     my %hash = %{shift()};
 3013:     my %returnhash;
 3014:     # Code ripped from lond, essentially.  The only difference
 3015:     # here is the unescaping done by lonnet::dump().  Conceivably
 3016:     # we might run in to problems with parameter names =~ /^v\./
 3017:     while (my ($key,$value) = each(%hash)) {
 3018:         my ($v,$symb,$param) = split(/:/,$key);
 3019:         next if ($v eq 'version' || $symb eq 'keys');
 3020:         next if (exists($returnhash{$symb}) &&
 3021:                  exists($returnhash{$symb}->{$param}) &&
 3022:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3023:         $returnhash{$symb}->{$param}=$value;
 3024:         $returnhash{$symb}->{'v.'.$param}=$v;
 3025:     }
 3026:     #
 3027:     # Remove all of the keys in the hashes which keep track of
 3028:     # the version of the parameter.
 3029:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3030:         # use a foreach because we are going to delete from the hash.
 3031:         foreach my $key (keys(%$param_hash)) {
 3032:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3033:         }
 3034:     }
 3035:     return \%returnhash;
 3036: }
 3037: 
 3038: # ------------------------------------------------------ critical inc interface
 3039: 
 3040: sub cinc {
 3041:     return &inc(@_,'critical');
 3042: }
 3043: 
 3044: # --------------------------------------------------------------- inc interface
 3045: 
 3046: sub inc {
 3047:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3048:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3049:     if (!$uname) { $uname=$env{'user.name'}; }
 3050:     my $uhome=&homeserver($uname,$udomain);
 3051:     my $items='';
 3052:     if (! ref($store)) {
 3053:         # got a single value, so use that instead
 3054:         $items = &escape($store).'=&';
 3055:     } elsif (ref($store) eq 'SCALAR') {
 3056:         $items = &escape($$store).'=&';        
 3057:     } elsif (ref($store) eq 'ARRAY') {
 3058:         $items = join('=&',map {&escape($_);} @{$store});
 3059:     } elsif (ref($store) eq 'HASH') {
 3060:         while (my($key,$value) = each(%{$store})) {
 3061:             $items.= &escape($key).'='.&escape($value).'&';
 3062:         }
 3063:     }
 3064:     $items=~s/\&$//;
 3065:     if ($critical) {
 3066: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3067:     } else {
 3068: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3069:     }
 3070: }
 3071: 
 3072: # --------------------------------------------------------------- put interface
 3073: 
 3074: sub put {
 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 (keys %$storehash) {
 3081:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3082:    }
 3083:    $items=~s/\&$//;
 3084:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3085: }
 3086: 
 3087: # ------------------------------------------------------------ newput interface
 3088: 
 3089: sub newput {
 3090:    my ($namespace,$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:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3100: }
 3101: 
 3102: # ---------------------------------------------------------  putstore interface
 3103: 
 3104: sub putstore {
 3105:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3107:    if (!$uname) { $uname=$env{'user.name'}; }
 3108:    my $uhome=&homeserver($uname,$udomain);
 3109:    my $items='';
 3110:    foreach my $key (keys(%$storehash)) {
 3111:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3112:    }
 3113:    $items=~s/\&$//;
 3114:    my $esc_symb=&escape($symb);
 3115:    my $esc_v=&escape($version);
 3116:    my $reply =
 3117:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3118: 	      $uhome);
 3119:    if ($reply eq 'unknown_cmd') {
 3120:        # gfall back to way things use to be done
 3121:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3122: 			    $uname);
 3123:    }
 3124:    return $reply;
 3125: }
 3126: 
 3127: sub old_putstore {
 3128:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3129:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3130:     if (!$uname) { $uname=$env{'user.name'}; }
 3131:     my $uhome=&homeserver($uname,$udomain);
 3132:     my %newstorehash;
 3133:     foreach (keys %$storehash) {
 3134: 	my $key = $version.':'.&escape($symb).':'.$_;
 3135: 	$newstorehash{$key} = $storehash->{$_};
 3136:     }
 3137:     my $items='';
 3138:     my %allitems = ();
 3139:     foreach (keys %newstorehash) {
 3140: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3141: 	    my $key = $1.':keys:'.$2;
 3142: 	    $allitems{$key} .= $3.':';
 3143: 	}
 3144: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3145:     }
 3146:     foreach (keys %allitems) {
 3147: 	$allitems{$_} =~ s/\:$//;
 3148: 	$items.= $_.'='.$allitems{$_}.'&';
 3149:     }
 3150:     $items=~s/\&$//;
 3151:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3152: }
 3153: 
 3154: # ------------------------------------------------------ critical put interface
 3155: 
 3156: sub cput {
 3157:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3158:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3159:    if (!$uname) { $uname=$env{'user.name'}; }
 3160:    my $uhome=&homeserver($uname,$udomain);
 3161:    my $items='';
 3162:    foreach (keys %$storehash) {
 3163:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3164:    }
 3165:    $items=~s/\&$//;
 3166:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3167: }
 3168: 
 3169: # -------------------------------------------------------------- eget interface
 3170: 
 3171: sub eget {
 3172:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3173:    my $items='';
 3174:    foreach (@$storearr) {
 3175:        $items.=escape($_).'&';
 3176:    }
 3177:    $items=~s/\&$//;
 3178:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3179:    if (!$uname) { $uname=$env{'user.name'}; }
 3180:    my $uhome=&homeserver($uname,$udomain);
 3181:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3182:    my @pairs=split(/\&/,$rep);
 3183:    my %returnhash=();
 3184:    my $i=0;
 3185:    foreach (@$storearr) {
 3186:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3187:       $i++;
 3188:    }
 3189:    return %returnhash;
 3190: }
 3191: 
 3192: # ------------------------------------------------------------ tmpput interface
 3193: sub tmpput {
 3194:     my ($storehash,$server)=@_;
 3195:     my $items='';
 3196:     foreach (keys(%$storehash)) {
 3197: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3198:     }
 3199:     $items=~s/\&$//;
 3200:     return &reply("tmpput:$items",$server);
 3201: }
 3202: 
 3203: # ------------------------------------------------------------ tmpget interface
 3204: sub tmpget {
 3205:     my ($token,$server)=@_;
 3206:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3207:     my $rep=&reply("tmpget:$token",$server);
 3208:     my %returnhash;
 3209:     foreach my $item (split(/\&/,$rep)) {
 3210: 	my ($key,$value)=split(/=/,$item);
 3211: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3212:     }
 3213:     return %returnhash;
 3214: }
 3215: 
 3216: # ------------------------------------------------------------ tmpget interface
 3217: sub tmpdel {
 3218:     my ($token,$server)=@_;
 3219:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3220:     return &reply("tmpdel:$token",$server);
 3221: }
 3222: 
 3223: # -------------------------------------------------- portfolio access checking
 3224: 
 3225: sub portfolio_access {
 3226:     my ($requrl) = @_;
 3227:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3228:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3229:     if ($result eq 'ok') {
 3230:        return 'F';
 3231:     } elsif ($result =~ /^[^:]+:guest_/) {
 3232:        return 'A';
 3233:     }
 3234:     return '';
 3235: }
 3236: 
 3237: sub get_portfolio_access {
 3238:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3239: 
 3240:     if (!ref($access_hash)) {
 3241: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3242: 	my %access_controls = &get_access_controls($current_perms,$group,
 3243: 						   $file_name);
 3244: 	$access_hash = $access_controls{$file_name};
 3245:     }
 3246: 
 3247:     my ($public,$guest,@domains,@users,@courses,@groups);
 3248:     my $now = time;
 3249:     if (ref($access_hash) eq 'HASH') {
 3250:         foreach my $key (keys(%{$access_hash})) {
 3251:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3252:             if ($start > $now) {
 3253:                 next;
 3254:             }
 3255:             if ($end && $end<$now) {
 3256:                 next;
 3257:             }
 3258:             if ($scope eq 'public') {
 3259:                 $public = $key;
 3260:                 last;
 3261:             } elsif ($scope eq 'guest') {
 3262:                 $guest = $key;
 3263:             } elsif ($scope eq 'domains') {
 3264:                 push(@domains,$key);
 3265:             } elsif ($scope eq 'users') {
 3266:                 push(@users,$key);
 3267:             } elsif ($scope eq 'course') {
 3268:                 push(@courses,$key);
 3269:             } elsif ($scope eq 'group') {
 3270:                 push(@groups,$key);
 3271:             }
 3272:         }
 3273:         if ($public) {
 3274:             return 'ok';
 3275:         }
 3276:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3277:             if ($guest) {
 3278:                 return $guest;
 3279:             }
 3280:         } else {
 3281:             if (@domains > 0) {
 3282:                 foreach my $domkey (@domains) {
 3283:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3284:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3285:                             return 'ok';
 3286:                         }
 3287:                     }
 3288:                 }
 3289:             }
 3290:             if (@users > 0) {
 3291:                 foreach my $userkey (@users) {
 3292:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3293:                         return 'ok';
 3294:                     }
 3295:                 }
 3296:             }
 3297:             my %roleshash;
 3298:             my @courses_and_groups = @courses;
 3299:             push(@courses_and_groups,@groups); 
 3300:             if (@courses_and_groups > 0) {
 3301:                 my (%allgroups,%allroles); 
 3302:                 my ($start,$end,$role,$sec,$group);
 3303:                 foreach my $envkey (%env) {
 3304:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
 3305:                         my $cid = $2.'_'.$3; 
 3306:                         if ($1 eq 'gr') {
 3307:                             $group = $4;
 3308:                             $allgroups{$cid}{$group} = $env{$envkey};
 3309:                         } else {
 3310:                             if ($4 eq '') {
 3311:                                 $sec = 'none';
 3312:                             } else {
 3313:                                 $sec = $4;
 3314:                             }
 3315:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3316:                         }
 3317:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
 3318:                         my $cid = $2.'_'.$3;
 3319:                         if ($4 eq '') {
 3320:                             $sec = 'none';
 3321:                         } else {
 3322:                             $sec = $4;
 3323:                         }
 3324:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3325:                     }
 3326:                 }
 3327:                 if (keys(%allroles) == 0) {
 3328:                     return;
 3329:                 }
 3330:                 foreach my $key (@courses_and_groups) {
 3331:                     my %content = %{$$access_hash{$key}};
 3332:                     my $cnum = $content{'number'};
 3333:                     my $cdom = $content{'domain'};
 3334:                     my $cid = $cdom.'_'.$cnum;
 3335:                     if (!exists($allroles{$cid})) {
 3336:                         next;
 3337:                     }    
 3338:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3339:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3340:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3341:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3342:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3343:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3344:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3345:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3346:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3347:                                         if (grep/^all$/,@sections) {
 3348:                                             return 'ok';
 3349:                                         } else {
 3350:                                             if (grep/^$sec$/,@sections) {
 3351:                                                 return 'ok';
 3352:                                             }
 3353:                                         }
 3354:                                     }
 3355:                                 }
 3356:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3357:                                     if (grep/^none$/,@groups) {
 3358:                                         return 'ok';
 3359:                                     }
 3360:                                 } else {
 3361:                                     if (grep/^all$/,@groups) {
 3362:                                         return 'ok';
 3363:                                     } 
 3364:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3365:                                         if (grep/^$group$/,@groups) {
 3366:                                             return 'ok';
 3367:                                         }
 3368:                                     }
 3369:                                 } 
 3370:                             }
 3371:                         }
 3372:                     }
 3373:                 }
 3374:             }
 3375:             if ($guest) {
 3376:                 return $guest;
 3377:             }
 3378:         }
 3379:     }
 3380:     return;
 3381: }
 3382: 
 3383: sub course_group_datechecker {
 3384:     my ($dates,$now,$status) = @_;
 3385:     my ($start,$end) = split(/\./,$dates);
 3386:     if (!$start && !$end) {
 3387:         return 'ok';
 3388:     }
 3389:     if (grep/^active$/,@{$status}) {
 3390:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3391:             return 'ok';
 3392:         }
 3393:     }
 3394:     if (grep/^previous$/,@{$status}) {
 3395:         if ($end > $now ) {
 3396:             return 'ok';
 3397:         }
 3398:     }
 3399:     if (grep/^future$/,@{$status}) {
 3400:         if ($start > $now) {
 3401:             return 'ok';
 3402:         }
 3403:     }
 3404:     return; 
 3405: }
 3406: 
 3407: sub parse_portfolio_url {
 3408:     my ($url) = @_;
 3409: 
 3410:     my ($type,$udom,$unum,$group,$file_name);
 3411:     
 3412:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
 3413: 	$type = 1;
 3414:         $udom = $1;
 3415:         $unum = $2;
 3416:         $file_name = $3;
 3417:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
 3418: 	$type = 2;
 3419:         $udom = $1;
 3420:         $unum = $2;
 3421:         $group = $3;
 3422:         $file_name = $3.'/'.$4;
 3423:     }
 3424:     if (wantarray) {
 3425: 	return ($type,$udom,$unum,$file_name,$group);
 3426:     }
 3427:     return $type;
 3428: }
 3429: 
 3430: sub is_portfolio_url {
 3431:     my ($url) = @_;
 3432:     return scalar(&parse_portfolio_url($url));
 3433: }
 3434: 
 3435: # ---------------------------------------------- Custom access rule evaluation
 3436: 
 3437: sub customaccess {
 3438:     my ($priv,$uri)=@_;
 3439:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3440:     $urealm=~s/^\W//;
 3441:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3442:     my $access=0;
 3443:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3444: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3445:         if ($role) {
 3446: 	   if ($role ne $urole) { next; }
 3447:         }
 3448:         foreach (split(/\s*\,\s*/,$realm)) {
 3449:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3450:             if ($tdom) {
 3451: 		if ($tdom ne $udom) { next; }
 3452:             }
 3453:             if ($tcrs) {
 3454: 		if ($tcrs ne $ucrs) { next; }
 3455:             }
 3456:             if ($tsec) {
 3457: 		if ($tsec ne $usec) { next; }
 3458:             }
 3459:             $access=($effect eq 'allow');
 3460:             last;
 3461:         }
 3462: 	if ($realm eq '' && $role eq '') {
 3463:             $access=($effect eq 'allow');
 3464: 	}
 3465:     }
 3466:     return $access;
 3467: }
 3468: 
 3469: # ------------------------------------------------- Check for a user privilege
 3470: 
 3471: sub allowed {
 3472:     my ($priv,$uri,$symb)=@_;
 3473:     my $ver_orguri=$uri;
 3474:     $uri=&deversion($uri);
 3475:     my $orguri=$uri;
 3476:     $uri=&declutter($uri);
 3477:     
 3478:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3479: # Free bre access to adm and meta resources
 3480:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3481: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3482: 	&& ($priv eq 'bre')) {
 3483: 	return 'F';
 3484:     }
 3485: 
 3486: # Free bre access to user's own portfolio contents
 3487:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3488:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3489: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3490:         return 'F';
 3491:     }
 3492: 
 3493: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3494:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3495:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3496:         if (exists($env{'request.course.id'})) {
 3497:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3498:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3499:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3500:                 my $courseprivid=$env{'request.course.id'};
 3501:                 $courseprivid=~s/\_/\//;
 3502:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3503:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3504:                     return $1; 
 3505:                 } else {
 3506:                     if ($env{'request.course.sec'}) {
 3507:                         $courseprivid.='/'.$env{'request.course.sec'};
 3508:                     }
 3509:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3510:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3511:                         return $2;
 3512:                     }
 3513:                 }
 3514:             }
 3515:         }
 3516:     }
 3517: 
 3518: # Free bre to public access
 3519: 
 3520:     if ($priv eq 'bre') {
 3521:         my $copyright=&metadata($uri,'copyright');
 3522: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3523:            return 'F'; 
 3524:         }
 3525:         if ($copyright eq 'priv') {
 3526:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3527: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3528: 		return '';
 3529:             }
 3530:         }
 3531:         if ($copyright eq 'domain') {
 3532:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3533: 	    unless (($env{'user.domain'} eq $1) ||
 3534:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3535: 		return '';
 3536:             }
 3537:         }
 3538:         if ($env{'request.role'}=~ /li\.\//) {
 3539:             # Library role, so allow browsing of resources in this domain.
 3540:             return 'F';
 3541:         }
 3542:         if ($copyright eq 'custom') {
 3543: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3544:         }
 3545:     }
 3546:     # Domain coordinator is trying to create a course
 3547:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3548:         # uri is the requested domain in this case.
 3549:         # comparison to 'request.role.domain' shows if the user has selected
 3550:         # a role of dc for the domain in question.
 3551:         return 'F' if ($uri eq $env{'request.role.domain'});
 3552:     }
 3553: 
 3554:     my $thisallowed='';
 3555:     my $statecond=0;
 3556:     my $courseprivid='';
 3557: 
 3558: # Course
 3559: 
 3560:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3561:        $thisallowed.=$1;
 3562:     }
 3563: 
 3564: # Domain
 3565: 
 3566:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3567:        =~/\Q$priv\E\&([^\:]*)/) {
 3568:        $thisallowed.=$1;
 3569:     }
 3570: 
 3571: # Course: uri itself is a course
 3572:     my $courseuri=$uri;
 3573:     $courseuri=~s/\_(\d)/\/$1/;
 3574:     $courseuri=~s/^([^\/])/\/$1/;
 3575: 
 3576:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3577:        =~/\Q$priv\E\&([^\:]*)/) {
 3578:        $thisallowed.=$1;
 3579:     }
 3580: 
 3581: # URI is an uploaded document for this course, default permissions don't matter
 3582: # not allowing 'edit' access (editupload) to uploaded course docs
 3583:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3584: 	$thisallowed='';
 3585:         my ($match)=&is_on_map($uri);
 3586:         if ($match) {
 3587:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3588:                   =~/\Q$priv\E\&([^\:]*)/) {
 3589:                 $thisallowed.=$1;
 3590:             }
 3591:         } else {
 3592:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3593:             if ($refuri) {
 3594:                 if ($refuri =~ m|^/adm/|) {
 3595:                     $thisallowed='F';
 3596:                 } else {
 3597:                     $refuri=&declutter($refuri);
 3598:                     my ($match) = &is_on_map($refuri);
 3599:                     if ($match) {
 3600:                         $thisallowed='F';
 3601:                     }
 3602:                 }
 3603:             }
 3604:         }
 3605:     }
 3606: 
 3607:     if ($priv eq 'bre'
 3608: 	&& $thisallowed ne 'F' 
 3609: 	&& $thisallowed ne '2'
 3610: 	&& &is_portfolio_url($uri)) {
 3611: 	$thisallowed = &portfolio_access($uri);
 3612:     }
 3613:     
 3614: # Full access at system, domain or course-wide level? Exit.
 3615: 
 3616:     if ($thisallowed=~/F/) {
 3617: 	return 'F';
 3618:     }
 3619: 
 3620: # If this is generating or modifying users, exit with special codes
 3621: 
 3622:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3623: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3624: 	    my ($audom,$auname)=split('/',$uri);
 3625: # no author name given, so this just checks on the general right to make a co-author in this domain
 3626: 	    unless ($auname) { return $thisallowed; }
 3627: # an author name is given, so we are about to actually make a co-author for a certain account
 3628: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3629: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3630: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3631: 	}
 3632: 	return $thisallowed;
 3633:     }
 3634: #
 3635: # Gathered so far: system, domain and course wide privileges
 3636: #
 3637: # Course: See if uri or referer is an individual resource that is part of 
 3638: # the course
 3639: 
 3640:     if ($env{'request.course.id'}) {
 3641: 
 3642:        $courseprivid=$env{'request.course.id'};
 3643:        if ($env{'request.course.sec'}) {
 3644:           $courseprivid.='/'.$env{'request.course.sec'};
 3645:        }
 3646:        $courseprivid=~s/\_/\//;
 3647:        my $checkreferer=1;
 3648:        my ($match,$cond)=&is_on_map($uri);
 3649:        if ($match) {
 3650:            $statecond=$cond;
 3651:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3652:                =~/\Q$priv\E\&([^\:]*)/) {
 3653:                $thisallowed.=$1;
 3654:                $checkreferer=0;
 3655:            }
 3656:        }
 3657:        
 3658:        if ($checkreferer) {
 3659: 	  my $refuri=$env{'httpref.'.$orguri};
 3660:             unless ($refuri) {
 3661:                 foreach (keys %env) {
 3662: 		    if ($_=~/^httpref\..*\*/) {
 3663: 			my $pattern=$_;
 3664:                         $pattern=~s/^httpref\.\/res\///;
 3665:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3666:                         $pattern=~s/\//\\\//g;
 3667:                         if ($orguri=~/$pattern/) {
 3668: 			    $refuri=$env{$_};
 3669:                         }
 3670:                     }
 3671:                 }
 3672:             }
 3673: 
 3674:          if ($refuri) { 
 3675: 	  $refuri=&declutter($refuri);
 3676:           my ($match,$cond)=&is_on_map($refuri);
 3677:             if ($match) {
 3678:               my $refstatecond=$cond;
 3679:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3680:                   =~/\Q$priv\E\&([^\:]*)/) {
 3681:                   $thisallowed.=$1;
 3682:                   $uri=$refuri;
 3683:                   $statecond=$refstatecond;
 3684:               }
 3685:           }
 3686:         }
 3687:        }
 3688:    }
 3689: 
 3690: #
 3691: # Gathered now: all privileges that could apply, and condition number
 3692: # 
 3693: #
 3694: # Full or no access?
 3695: #
 3696: 
 3697:     if ($thisallowed=~/F/) {
 3698: 	return 'F';
 3699:     }
 3700: 
 3701:     unless ($thisallowed) {
 3702:         return '';
 3703:     }
 3704: 
 3705: # Restrictions exist, deal with them
 3706: #
 3707: #   C:according to course preferences
 3708: #   R:according to resource settings
 3709: #   L:unless locked
 3710: #   X:according to user session state
 3711: #
 3712: 
 3713: # Possibly locked functionality, check all courses
 3714: # Locks might take effect only after 10 minutes cache expiration for other
 3715: # courses, and 2 minutes for current course
 3716: 
 3717:     my $envkey;
 3718:     if ($thisallowed=~/L/) {
 3719:         foreach $envkey (keys %env) {
 3720:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3721:                my $courseid=$2;
 3722:                my $roleid=$1.'.'.$2;
 3723:                $courseid=~s/^\///;
 3724:                my $expiretime=600;
 3725:                if ($env{'request.role'} eq $roleid) {
 3726: 		  $expiretime=120;
 3727:                }
 3728: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3729:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3730:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3731: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3732:                }
 3733:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3734:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3735: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3736:                        &log($env{'user.domain'},$env{'user.name'},
 3737:                             $env{'user.home'},
 3738:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3739:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3740:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3741: 		       return '';
 3742:                    }
 3743:                }
 3744:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3745:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3746: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3747:                        &log($env{'user.domain'},$env{'user.name'},
 3748:                             $env{'user.home'},
 3749:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3750:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3751:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3752: 		       return '';
 3753:                    }
 3754:                }
 3755: 	   }
 3756:        }
 3757:     }
 3758:    
 3759: #
 3760: # Rest of the restrictions depend on selected course
 3761: #
 3762: 
 3763:     unless ($env{'request.course.id'}) {
 3764: 	if ($thisallowed eq 'A') {
 3765: 	    return 'A';
 3766: 	} else {
 3767: 	    return '1';
 3768: 	}
 3769:     }
 3770: 
 3771: #
 3772: # Now user is definitely in a course
 3773: #
 3774: 
 3775: 
 3776: # Course preferences
 3777: 
 3778:    if ($thisallowed=~/C/) {
 3779:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3780:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3781:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3782: 	   =~/\Q$rolecode\E/) {
 3783: 	   if ($priv ne 'pch') { 
 3784: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3785: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3786: 			$env{'request.course.id'});
 3787: 	   }
 3788:            return '';
 3789:        }
 3790: 
 3791:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3792: 	   =~/\Q$unamedom\E/) {
 3793: 	   if ($priv ne 'pch') { 
 3794: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3795: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3796: 			$env{'request.course.id'});
 3797: 	   }
 3798:            return '';
 3799:        }
 3800:    }
 3801: 
 3802: # Resource preferences
 3803: 
 3804:    if ($thisallowed=~/R/) {
 3805:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3806:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3807: 	   if ($priv ne 'pch') { 
 3808: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3809: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3810: 	   }
 3811: 	   return '';
 3812:        }
 3813:    }
 3814: 
 3815: # Restricted by state or randomout?
 3816: 
 3817:    if ($thisallowed=~/X/) {
 3818:       if ($env{'acc.randomout'}) {
 3819: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3820:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3821:             return ''; 
 3822:          }
 3823:       }
 3824:       if (&condval($statecond)) {
 3825: 	 return '2';
 3826:       } else {
 3827:          return '';
 3828:       }
 3829:    }
 3830: 
 3831:     if ($thisallowed eq 'A') {
 3832: 	return 'A';
 3833:     }
 3834:    return 'F';
 3835: }
 3836: 
 3837: sub split_uri_for_cond {
 3838:     my $uri=&deversion(&declutter(shift));
 3839:     my @uriparts=split(/\//,$uri);
 3840:     my $filename=pop(@uriparts);
 3841:     my $pathname=join('/',@uriparts);
 3842:     return ($pathname,$filename);
 3843: }
 3844: # --------------------------------------------------- Is a resource on the map?
 3845: 
 3846: sub is_on_map {
 3847:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3848:     #Trying to find the conditional for the file
 3849:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3850: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3851:     if ($match) {
 3852: 	return (1,$1);
 3853:     } else {
 3854: 	return (0,0);
 3855:     }
 3856: }
 3857: 
 3858: # --------------------------------------------------------- Get symb from alias
 3859: 
 3860: sub get_symb_from_alias {
 3861:     my $symb=shift;
 3862:     my ($map,$resid,$url)=&decode_symb($symb);
 3863: # Already is a symb
 3864:     if ($url) { return $symb; }
 3865: # Must be an alias
 3866:     my $aliassymb='';
 3867:     my %bighash;
 3868:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3869:                             &GDBM_READER(),0640)) {
 3870:         my $rid=$bighash{'mapalias_'.$symb};
 3871: 	if ($rid) {
 3872: 	    my ($mapid,$resid)=split(/\./,$rid);
 3873: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3874: 				    $resid,$bighash{'src_'.$rid});
 3875: 	}
 3876:         untie %bighash;
 3877:     }
 3878:     return $aliassymb;
 3879: }
 3880: 
 3881: # ----------------------------------------------------------------- Define Role
 3882: 
 3883: sub definerole {
 3884:   if (allowed('mcr','/')) {
 3885:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3886:     foreach (split(':',$sysrole)) {
 3887: 	my ($crole,$cqual)=split(/\&/,$_);
 3888:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3889:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3890: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3891:                return "refused:s:$crole&$cqual"; 
 3892:             }
 3893:         }
 3894:     }
 3895:     foreach (split(':',$domrole)) {
 3896: 	my ($crole,$cqual)=split(/\&/,$_);
 3897:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3898:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3899: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3900:                return "refused:d:$crole&$cqual"; 
 3901:             }
 3902:         }
 3903:     }
 3904:     foreach (split(':',$courole)) {
 3905: 	my ($crole,$cqual)=split(/\&/,$_);
 3906:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3907:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3908: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3909:                return "refused:c:$crole&$cqual"; 
 3910:             }
 3911:         }
 3912:     }
 3913:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3914:                 "$env{'user.domain'}:$env{'user.name'}:".
 3915: 	        "rolesdef_$rolename=".
 3916:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3917:     return reply($command,$env{'user.home'});
 3918:   } else {
 3919:     return 'refused';
 3920:   }
 3921: }
 3922: 
 3923: # ---------------- Make a metadata query against the network of library servers
 3924: 
 3925: sub metadata_query {
 3926:     my ($query,$custom,$customshow,$server_array)=@_;
 3927:     my %rhash;
 3928:     my @server_list = (defined($server_array) ? @$server_array
 3929:                                               : keys(%libserv) );
 3930:     for my $server (@server_list) {
 3931: 	unless ($custom or $customshow) {
 3932: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3933: 	    $rhash{$server}=$reply;
 3934: 	}
 3935: 	else {
 3936: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3937: 			     &escape($custom).':'.&escape($customshow),
 3938: 			     $server);
 3939: 	    $rhash{$server}=$reply;
 3940: 	}
 3941:     }
 3942:     return \%rhash;
 3943: }
 3944: 
 3945: # ----------------------------------------- Send log queries and wait for reply
 3946: 
 3947: sub log_query {
 3948:     my ($uname,$udom,$query,%filters)=@_;
 3949:     my $uhome=&homeserver($uname,$udom);
 3950:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3951:     my $uhost=$hostname{$uhome};
 3952:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3953:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3954:                        $uhome);
 3955:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3956:     return get_query_reply($queryid);
 3957: }
 3958: 
 3959: # ------- Request retrieval of institutional classlists for course(s)
 3960: 
 3961: sub fetch_enrollment_query {
 3962:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3963:     my $homeserver;
 3964:     my $maxtries = 1;
 3965:     if ($context eq 'automated') {
 3966:         $homeserver = $perlvar{'lonHostID'};
 3967:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3968:     } else {
 3969:         $homeserver = &homeserver($cnum,$dom);
 3970:     }
 3971:     my $host=$hostname{$homeserver};
 3972:     my $cmd = '';
 3973:     foreach (keys %{$affiliatesref}) {
 3974:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3975:     }
 3976:     $cmd =~ s/%%$//;
 3977:     $cmd = &escape($cmd);
 3978:     my $query = 'fetchenrollment';
 3979:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3980:     unless ($queryid=~/^\Q$host\E\_/) { 
 3981:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3982:         return 'error: '.$queryid;
 3983:     }
 3984:     my $reply = &get_query_reply($queryid);
 3985:     my $tries = 1;
 3986:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3987:         $reply = &get_query_reply($queryid);
 3988:         $tries ++;
 3989:     }
 3990:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3991:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3992:     } else {
 3993:         my @responses = split/:/,$reply;
 3994:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3995:             foreach (@responses) {
 3996:                 my ($key,$value) = split/=/,$_;
 3997:                 $$replyref{$key} = $value;
 3998:             }
 3999:         } else {
 4000:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4001:             foreach (@responses) {
 4002:                 my ($key,$value) = split/=/,$_;
 4003:                 $$replyref{$key} = $value;
 4004:                 if ($value > 0) {
 4005:                     foreach (@{$$affiliatesref{$key}}) {
 4006:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 4007:                         my $destname = $pathname.'/'.$filename;
 4008:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4009:                         if ($xml_classlist =~ /^error/) {
 4010:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4011:                         } else {
 4012:                             if ( open(FILE,">$destname") ) {
 4013:                                 print FILE &unescape($xml_classlist);
 4014:                                 close(FILE);
 4015:                             } else {
 4016:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4017:                             }
 4018:                         }
 4019:                     }
 4020:                 }
 4021:             }
 4022:         }
 4023:         return 'ok';
 4024:     }
 4025:     return 'error';
 4026: }
 4027: 
 4028: sub get_query_reply {
 4029:     my $queryid=shift;
 4030:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4031:     my $reply='';
 4032:     for (1..100) {
 4033: 	sleep 2;
 4034:         if (-e $replyfile.'.end') {
 4035: 	    if (open(my $fh,$replyfile)) {
 4036:                $reply.=<$fh>;
 4037:                close($fh);
 4038: 	   } else { return 'error: reply_file_error'; }
 4039:            return &unescape($reply);
 4040: 	}
 4041:     }
 4042:     return 'timeout:'.$queryid;
 4043: }
 4044: 
 4045: sub courselog_query {
 4046: #
 4047: # possible filters:
 4048: # url: url or symb
 4049: # username
 4050: # domain
 4051: # action: view, submit, grade
 4052: # start: timestamp
 4053: # end: timestamp
 4054: #
 4055:     my (%filters)=@_;
 4056:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4057:     if ($filters{'url'}) {
 4058: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4059:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4060:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4061:     }
 4062:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4063:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4064:     return &log_query($cname,$cdom,'courselog',%filters);
 4065: }
 4066: 
 4067: sub userlog_query {
 4068:     my ($uname,$udom,%filters)=@_;
 4069:     return &log_query($uname,$udom,'userlog',%filters);
 4070: }
 4071: 
 4072: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4073: 
 4074: sub auto_run {
 4075:     my ($cnum,$cdom) = @_;
 4076:     my $homeserver = &homeserver($cnum,$cdom);
 4077:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4078:     return $response;
 4079: }
 4080: 
 4081: sub auto_get_sections {
 4082:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4083:     my $homeserver = &homeserver($cnum,$cdom);
 4084:     my @secs = ();
 4085:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4086:     unless ($response eq 'refused') {
 4087:         @secs = split/:/,$response;
 4088:     }
 4089:     return @secs;
 4090: }
 4091: 
 4092: sub auto_new_course {
 4093:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4094:     my $homeserver = &homeserver($cnum,$cdom);
 4095:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4096:     return $response;
 4097: }
 4098: 
 4099: sub auto_validate_courseID {
 4100:     my ($cnum,$cdom,$inst_course_id) = @_;
 4101:     my $homeserver = &homeserver($cnum,$cdom);
 4102:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4103:     return $response;
 4104: }
 4105: 
 4106: sub auto_create_password {
 4107:     my ($cnum,$cdom,$authparam) = @_;
 4108:     my $homeserver = &homeserver($cnum,$cdom); 
 4109:     my $create_passwd = 0;
 4110:     my $authchk = '';
 4111:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4112:     if ($response eq 'refused') {
 4113:         $authchk = 'refused';
 4114:     } else {
 4115:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4116:     }
 4117:     return ($authparam,$create_passwd,$authchk);
 4118: }
 4119: 
 4120: sub auto_photo_permission {
 4121:     my ($cnum,$cdom,$students) = @_;
 4122:     my $homeserver = &homeserver($cnum,$cdom);
 4123:     my ($outcome,$perm_reqd,$conditions) = 
 4124: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4125:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4126: 	return (undef,undef);
 4127:     }
 4128:     return ($outcome,$perm_reqd,$conditions);
 4129: }
 4130: 
 4131: sub auto_checkphotos {
 4132:     my ($uname,$udom,$pid) = @_;
 4133:     my $homeserver = &homeserver($uname,$udom);
 4134:     my ($result,$resulttype);
 4135:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4136: 				   &escape($uname).':'.&escape($pid),
 4137: 				   $homeserver));
 4138:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4139: 	return (undef,undef);
 4140:     }
 4141:     if ($outcome) {
 4142:         ($result,$resulttype) = split(/:/,$outcome);
 4143:     } 
 4144:     return ($result,$resulttype);
 4145: }
 4146: 
 4147: sub auto_photochoice {
 4148:     my ($cnum,$cdom) = @_;
 4149:     my $homeserver = &homeserver($cnum,$cdom);
 4150:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4151: 						       &escape($cdom),
 4152: 						       $homeserver)));
 4153:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4154: 	return (undef,undef);
 4155:     }
 4156:     return ($update,$comment);
 4157: }
 4158: 
 4159: sub auto_photoupdate {
 4160:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4161:     my $homeserver = &homeserver($cnum,$dom);
 4162:     my $host=$hostname{$homeserver};
 4163:     my $cmd = '';
 4164:     my $maxtries = 1;
 4165:     foreach (keys %{$affiliatesref}) {
 4166:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 4167:     }
 4168:     $cmd =~ s/%%$//;
 4169:     $cmd = &escape($cmd);
 4170:     my $query = 'institutionalphotos';
 4171:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4172:     unless ($queryid=~/^\Q$host\E\_/) {
 4173:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4174:         return 'error: '.$queryid;
 4175:     }
 4176:     my $reply = &get_query_reply($queryid);
 4177:     my $tries = 1;
 4178:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4179:         $reply = &get_query_reply($queryid);
 4180:         $tries ++;
 4181:     }
 4182:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4183:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4184:     } else {
 4185:         my @responses = split(/:/,$reply);
 4186:         my $outcome = shift(@responses); 
 4187:         foreach my $item (@responses) {
 4188:             my ($key,$value) = split(/=/,$item);
 4189:             $$photo{$key} = $value;
 4190:         }
 4191:         return $outcome;
 4192:     }
 4193:     return 'error';
 4194: }
 4195: 
 4196: sub auto_instcode_format {
 4197:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 4198:     my $courses = '';
 4199:     my @homeservers;
 4200:     if ($caller eq 'global') {
 4201:         foreach my $tryserver (keys %libserv) {
 4202:             if ($hostdom{$tryserver} eq $codedom) {
 4203:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
 4204:                     push(@homeservers,$tryserver);
 4205:                 }
 4206:             }
 4207:         }
 4208:     } else {
 4209:         push(@homeservers,&homeserver($caller,$codedom));
 4210:     }
 4211:     foreach (keys %{$instcodes}) {
 4212:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 4213:     }
 4214:     chop($courses);
 4215:     my $ok_response = 0;
 4216:     my $response;
 4217:     while (@homeservers > 0 && $ok_response == 0) {
 4218:         my $server = shift(@homeservers); 
 4219:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4220:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4221:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4222:                                                             split/:/,$response;
 4223:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4224:             push(@{$codetitles},&str2array($codetitles_str));
 4225:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4226:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4227:             $ok_response = 1;
 4228:         }
 4229:     }
 4230:     if ($ok_response) {
 4231:         return 'ok';
 4232:     } else {
 4233:         return $response;
 4234:     }
 4235: }
 4236: 
 4237: sub auto_validate_class_sec {
 4238:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4239:     my $homeserver = &homeserver($cnum,$cdom);
 4240:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4241:                         &escape($owner).':'.$cdom,$homeserver);
 4242:     return $response;
 4243: }
 4244: 
 4245: # ------------------------------------------------------- Course Group routines
 4246: 
 4247: sub get_coursegroups {
 4248:     my ($cdom,$cnum,$group) = @_;
 4249:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4250: }
 4251: 
 4252: sub modify_coursegroup {
 4253:     my ($cdom,$cnum,$groupsettings) = @_;
 4254:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4255: }
 4256: 
 4257: sub modify_group_roles {
 4258:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4259:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4260:     my $role = 'gr/'.&escape($userprivs);
 4261:     my ($uname,$udom) = split(/:/,$user);
 4262:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4263:     if ($result eq 'ok') {
 4264:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4265:     }
 4266:     return $result;
 4267: }
 4268: 
 4269: sub modify_coursegroup_membership {
 4270:     my ($cdom,$cnum,$membership) = @_;
 4271:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4272:     return $result;
 4273: }
 4274: 
 4275: sub get_active_groups {
 4276:     my ($udom,$uname,$cdom,$cnum) = @_;
 4277:     my $now = time;
 4278:     my %groups = ();
 4279:     foreach my $key (keys(%env)) {
 4280:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4281:             my ($start,$end) = split(/\./,$env{$key});
 4282:             if (($end!=0) && ($end<$now)) { next; }
 4283:             if (($start!=0) && ($start>$now)) { next; }
 4284:             if ($1 eq $cdom && $2 eq $cnum) {
 4285:                 $groups{$3} = $env{$key} ;
 4286:             }
 4287:         }
 4288:     }
 4289:     return %groups;
 4290: }
 4291: 
 4292: sub get_group_membership {
 4293:     my ($cdom,$cnum,$group) = @_;
 4294:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4295: }
 4296: 
 4297: sub get_users_groups {
 4298:     my ($udom,$uname,$courseid) = @_;
 4299:     my @usersgroups;
 4300:     my $cachetime=1800;
 4301:     $courseid=~s/\_/\//g;
 4302:     $courseid=~s/^(\w)/\/$1/;
 4303: 
 4304:     my $hashid="$udom:$uname:$courseid";
 4305:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4306:     if (defined($cached)) {
 4307:         @usersgroups = split(/:/,$grouplist);
 4308:     } else {  
 4309:         $grouplist = '';
 4310:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4311:         my ($tmp) = keys(%roleshash);
 4312:         if ($tmp=~/^error:/) {
 4313:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4314:         } else {
 4315:             my $access_end = $env{'course.'.$courseid.
 4316:                                   '.default_enrollment_end_date'};
 4317:             my $now = time;
 4318:             foreach my $key (keys(%roleshash)) {
 4319:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4320:                     my $group = $1;
 4321:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4322:                         my $start = $2;
 4323:                         my $end = $1;
 4324:                         if ($start == -1) { next; } # deleted from group
 4325:                         if (($start!=0) && ($start>$now)) { next; }
 4326:                         if (($end!=0) && ($end<$now)) {
 4327:                             if ($access_end && $access_end < $now) {
 4328:                                 if ($access_end - $end < 86400) {
 4329:                                     push(@usersgroups,$group);
 4330:                                 }
 4331:                             }
 4332:                             next;
 4333:                         }
 4334:                         push(@usersgroups,$group);
 4335:                     }
 4336:                 }
 4337:             }
 4338:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4339:             $grouplist = join(':',@usersgroups);
 4340:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4341:         }
 4342:     }
 4343:     return @usersgroups;
 4344: }
 4345: 
 4346: sub devalidate_getgroups_cache {
 4347:     my ($udom,$uname,$cdom,$cnum)=@_;
 4348:     my $courseid = $cdom.'_'.$cnum;
 4349:     $courseid=~s/\_/\//g;
 4350:     $courseid=~s/^(\w)/\/$1/;
 4351:     my $hashid="$udom:$uname:$courseid";
 4352:     &devalidate_cache_new('getgroups',$hashid);
 4353: }
 4354: 
 4355: # ------------------------------------------------------------------ Plain Text
 4356: 
 4357: sub plaintext {
 4358:     my ($short,$type,$cid) = @_;
 4359:     if ($short =~ /^cr/) {
 4360: 	return (split('/',$short))[-1];
 4361:     }
 4362:     if (!defined($cid)) {
 4363:         $cid = $env{'request.course.id'};
 4364:     }
 4365:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4366:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4367:                                           '.plaintext'});
 4368:     }
 4369:     my %rolenames = (
 4370:                       Course => 'std',
 4371:                       Group => 'alt1',
 4372:                     );
 4373:     if (defined($type) && 
 4374:          defined($rolenames{$type}) && 
 4375:          defined($prp{$short}{$rolenames{$type}})) {
 4376:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4377:     } else {
 4378:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4379:     }
 4380: }
 4381: 
 4382: # ----------------------------------------------------------------- Assign Role
 4383: 
 4384: sub assignrole {
 4385:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4386:     my $mrole;
 4387:     if ($role =~ /^cr\//) {
 4388:         my $cwosec=$url;
 4389:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4390: 	unless (&allowed('ccr',$cwosec)) {
 4391:            &logthis('Refused custom assignrole: '.
 4392:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4393: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4394:            return 'refused'; 
 4395:         }
 4396:         $mrole='cr';
 4397:     } elsif ($role =~ /^gr\//) {
 4398:         my $cwogrp=$url;
 4399:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4400:         unless (&allowed('mdg',$cwogrp)) {
 4401:             &logthis('Refused group assignrole: '.
 4402:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4403:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4404:             return 'refused';
 4405:         }
 4406:         $mrole='gr';
 4407:     } else {
 4408:         my $cwosec=$url;
 4409:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4410:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4411:            &logthis('Refused assignrole: '.
 4412:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4413: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4414:            return 'refused'; 
 4415:         }
 4416:         $mrole=$role;
 4417:     }
 4418:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4419:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4420:     if ($end) { $command.='_'.$end; }
 4421:     if ($start) {
 4422: 	if ($end) { 
 4423:            $command.='_'.$start; 
 4424:         } else {
 4425:            $command.='_0_'.$start;
 4426:         }
 4427:     }
 4428:     my $origstart = $start;
 4429:     my $origend = $end;
 4430: # actually delete
 4431:     if ($deleteflag) {
 4432: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4433: # modify command to delete the role
 4434:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4435:                 "$udom:$uname:$url".'_'."$mrole";
 4436: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4437: # set start and finish to negative values for userrolelog
 4438:            $start=-1;
 4439:            $end=-1;
 4440:         }
 4441:     }
 4442: # send command
 4443:     my $answer=&reply($command,&homeserver($uname,$udom));
 4444: # log new user role if status is ok
 4445:     if ($answer eq 'ok') {
 4446: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4447: # for course roles, perform group memberships changes triggered by role change.
 4448:         unless ($role =~ /^gr/) {
 4449:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4450:                                              $origstart);
 4451:         }
 4452:     }
 4453:     return $answer;
 4454: }
 4455: 
 4456: # -------------------------------------------------- Modify user authentication
 4457: # Overrides without validation
 4458: 
 4459: sub modifyuserauth {
 4460:     my ($udom,$uname,$umode,$upass)=@_;
 4461:     my $uhome=&homeserver($uname,$udom);
 4462:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4463:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4464:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4465:              ' in domain '.$env{'request.role.domain'});  
 4466:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4467: 		     &escape($upass),$uhome);
 4468:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4469:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4470:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4471:     &log($udom,,$uname,$uhome,
 4472:         'Authentication changed by '.$env{'user.domain'}.', '.
 4473:                                      $env{'user.name'}.', '.$umode.
 4474:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4475:     unless ($reply eq 'ok') {
 4476:         &logthis('Authentication mode error: '.$reply);
 4477: 	return 'error: '.$reply;
 4478:     }   
 4479:     return 'ok';
 4480: }
 4481: 
 4482: # --------------------------------------------------------------- Modify a user
 4483: 
 4484: sub modifyuser {
 4485:     my ($udom,    $uname, $uid,
 4486:         $umode,   $upass, $first,
 4487:         $middle,  $last,  $gene,
 4488:         $forceid, $desiredhome, $email)=@_;
 4489:     $udom=~s/\W//g;
 4490:     $uname=~s/\W//g;
 4491:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4492:              $umode.', '.$first.', '.$middle.', '.
 4493: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4494:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4495:                                      ' desiredhome not specified'). 
 4496:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4497:              ' in domain '.$env{'request.role.domain'});
 4498:     my $uhome=&homeserver($uname,$udom,'true');
 4499: # ----------------------------------------------------------------- Create User
 4500:     if (($uhome eq 'no_host') && 
 4501: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4502:         my $unhome='';
 4503:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4504:             $unhome = $desiredhome;
 4505: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4506: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4507:         } else { # load balancing routine for determining $unhome
 4508:             my $tryserver;
 4509:             my $loadm=10000000;
 4510:             foreach $tryserver (keys %libserv) {
 4511: 	       if ($hostdom{$tryserver} eq $udom) {
 4512:                   my $answer=reply('load',$tryserver);
 4513:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4514: 		      $loadm=$answer;
 4515:                       $unhome=$tryserver;
 4516:                   }
 4517: 	       }
 4518: 	    }
 4519:         }
 4520:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4521: 	    return 'error: unable to find a home server for '.$uname.
 4522:                    ' in domain '.$udom;
 4523:         }
 4524:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4525:                          &escape($upass),$unhome);
 4526: 	unless ($reply eq 'ok') {
 4527:             return 'error: '.$reply;
 4528:         }   
 4529:         $uhome=&homeserver($uname,$udom,'true');
 4530:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4531: 	    return 'error: unable verify users home machine.';
 4532:         }
 4533:     }   # End of creation of new user
 4534: # ---------------------------------------------------------------------- Add ID
 4535:     if ($uid) {
 4536:        $uid=~tr/A-Z/a-z/;
 4537:        my %uidhash=&idrget($udom,$uname);
 4538:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4539:          && (!$forceid)) {
 4540: 	  unless ($uid eq $uidhash{$uname}) {
 4541: 	      return 'error: user id "'.$uid.'" does not match '.
 4542:                   'current user id "'.$uidhash{$uname}.'".';
 4543:           }
 4544:        } else {
 4545: 	  &idput($udom,($uname => $uid));
 4546:        }
 4547:     }
 4548: # -------------------------------------------------------------- Add names, etc
 4549:     my @tmp=&get('environment',
 4550: 		   ['firstname','middlename','lastname','generation'],
 4551: 		   $udom,$uname);
 4552:     my %names;
 4553:     if ($tmp[0] =~ m/^error:.*/) { 
 4554:         %names=(); 
 4555:     } else {
 4556:         %names = @tmp;
 4557:     }
 4558: #
 4559: # Make sure to not trash student environment if instructor does not bother
 4560: # to supply name and email information
 4561: #
 4562:     if ($first)  { $names{'firstname'}  = $first; }
 4563:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4564:     if ($last)   { $names{'lastname'}   = $last; }
 4565:     if (defined($gene))   { $names{'generation'} = $gene; }
 4566:     if ($email) {
 4567:        $email=~s/[^\w\@\.\-\,]//gs;
 4568:        if ($email=~/\@/) { $names{'notification'} = $email;
 4569: 			   $names{'critnotification'} = $email;
 4570: 			   $names{'permanentemail'} = $email; }
 4571:     }
 4572:     my $reply = &put('environment', \%names, $udom,$uname);
 4573:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4574:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4575:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4576:              $umode.', '.$first.', '.$middle.', '.
 4577: 	     $last.', '.$gene.' by '.
 4578:              $env{'user.name'}.' at '.$env{'user.domain'});
 4579:     return 'ok';
 4580: }
 4581: 
 4582: # -------------------------------------------------------------- Modify student
 4583: 
 4584: sub modifystudent {
 4585:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4586:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4587:     if (!$cid) {
 4588: 	unless ($cid=$env{'request.course.id'}) {
 4589: 	    return 'not_in_class';
 4590: 	}
 4591:     }
 4592: # --------------------------------------------------------------- Make the user
 4593:     my $reply=&modifyuser
 4594: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4595:          $desiredhome,$email);
 4596:     unless ($reply eq 'ok') { return $reply; }
 4597:     # This will cause &modify_student_enrollment to get the uid from the
 4598:     # students environment
 4599:     $uid = undef if (!$forceid);
 4600:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4601: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4602:     return $reply;
 4603: }
 4604: 
 4605: sub modify_student_enrollment {
 4606:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4607:     my ($cdom,$cnum,$chome);
 4608:     if (!$cid) {
 4609: 	unless ($cid=$env{'request.course.id'}) {
 4610: 	    return 'not_in_class';
 4611: 	}
 4612: 	$cdom=$env{'course.'.$cid.'.domain'};
 4613: 	$cnum=$env{'course.'.$cid.'.num'};
 4614:     } else {
 4615: 	($cdom,$cnum)=split(/_/,$cid);
 4616:     }
 4617:     $chome=$env{'course.'.$cid.'.home'};
 4618:     if (!$chome) {
 4619: 	$chome=&homeserver($cnum,$cdom);
 4620:     }
 4621:     if (!$chome) { return 'unknown_course'; }
 4622:     # Make sure the user exists
 4623:     my $uhome=&homeserver($uname,$udom);
 4624:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4625: 	return 'error: no such user';
 4626:     }
 4627:     # Get student data if we were not given enough information
 4628:     if (!defined($first)  || $first  eq '' || 
 4629:         !defined($last)   || $last   eq '' || 
 4630:         !defined($uid)    || $uid    eq '' || 
 4631:         !defined($middle) || $middle eq '' || 
 4632:         !defined($gene)   || $gene   eq '') {
 4633:         # They did not supply us with enough data to enroll the student, so
 4634:         # we need to pick up more information.
 4635:         my %tmp = &get('environment',
 4636:                        ['firstname','middlename','lastname', 'generation','id']
 4637:                        ,$udom,$uname);
 4638: 
 4639:         #foreach (keys(%tmp)) {
 4640:         #    &logthis("key $_ = ".$tmp{$_});
 4641:         #}
 4642:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4643:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4644:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4645:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4646:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4647:     }
 4648:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4649:     my $reply=cput('classlist',
 4650: 		   {"$uname:$udom" => 
 4651: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4652: 		   $cdom,$cnum);
 4653:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4654: 	return 'error: '.$reply;
 4655:     } else {
 4656: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4657:     }
 4658:     # Add student role to user
 4659:     my $uurl='/'.$cid;
 4660:     $uurl=~s/\_/\//g;
 4661:     if ($usec) {
 4662: 	$uurl.='/'.$usec;
 4663:     }
 4664:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4665: }
 4666: 
 4667: sub format_name {
 4668:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4669:     my $name;
 4670:     if ($first ne 'lastname') {
 4671: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4672:     } else {
 4673: 	if ($lastname=~/\S/) {
 4674: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4675: 	    $name=~s/\s+,/,/;
 4676: 	} else {
 4677: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4678: 	}
 4679:     }
 4680:     $name=~s/^\s+//;
 4681:     $name=~s/\s+$//;
 4682:     $name=~s/\s+/ /g;
 4683:     return $name;
 4684: }
 4685: 
 4686: # ------------------------------------------------- Write to course preferences
 4687: 
 4688: sub writecoursepref {
 4689:     my ($courseid,%prefs)=@_;
 4690:     $courseid=~s/^\///;
 4691:     $courseid=~s/\_/\//g;
 4692:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4693:     my $chome=homeserver($cnum,$cdomain);
 4694:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4695: 	return 'error: no such course';
 4696:     }
 4697:     my $cstring='';
 4698:     foreach (keys %prefs) {
 4699: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4700:     }
 4701:     $cstring=~s/\&$//;
 4702:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4703: }
 4704: 
 4705: # ---------------------------------------------------------- Make/modify course
 4706: 
 4707: sub createcourse {
 4708:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4709:         $course_owner,$crstype)=@_;
 4710:     $url=&declutter($url);
 4711:     my $cid='';
 4712:     unless (&allowed('ccc',$udom)) {
 4713:         return 'refused';
 4714:     }
 4715: # ------------------------------------------------------------------- Create ID
 4716:    my $uname=int(1+rand(9)).
 4717:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4718:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4719:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4720: # ----------------------------------------------- Make sure that does not exist
 4721:    my $uhome=&homeserver($uname,$udom,'true');
 4722:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4723:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4724:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4725:        $uhome=&homeserver($uname,$udom,'true');       
 4726:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4727:            return 'error: unable to generate unique course-ID';
 4728:        } 
 4729:    }
 4730: # ------------------------------------------------ Check supplied server name
 4731:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4732:     if (! exists($libserv{$course_server})) {
 4733:         return 'error:bad server name '.$course_server;
 4734:     }
 4735: # ------------------------------------------------------------- Make the course
 4736:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4737:                       $course_server);
 4738:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4739:     $uhome=&homeserver($uname,$udom,'true');
 4740:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4741: 	return 'error: no such course';
 4742:     }
 4743: # ----------------------------------------------------------------- Course made
 4744: # log existence
 4745:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4746:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4747:                   &escape($crstype),$uhome);
 4748:     &flushcourselogs();
 4749: # set toplevel url
 4750:     my $topurl=$url;
 4751:     unless ($nonstandard) {
 4752: # ------------------------------------------ For standard courses, make top url
 4753:         my $mapurl=&clutter($url);
 4754:         if ($mapurl eq '/res/') { $mapurl=''; }
 4755:         $env{'form.initmap'}=(<<ENDINITMAP);
 4756: <map>
 4757: <resource id="1" type="start"></resource>
 4758: <resource id="2" src="$mapurl"></resource>
 4759: <resource id="3" type="finish"></resource>
 4760: <link index="1" from="1" to="2"></link>
 4761: <link index="2" from="2" to="3"></link>
 4762: </map>
 4763: ENDINITMAP
 4764:         $topurl=&declutter(
 4765:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4766:                           );
 4767:     }
 4768: # ----------------------------------------------------------- Write preferences
 4769:     &writecoursepref($udom.'_'.$uname,
 4770:                      ('description' => $description,
 4771:                       'url'         => $topurl));
 4772:     return '/'.$udom.'/'.$uname;
 4773: }
 4774: 
 4775: # ---------------------------------------------------------- Assign Custom Role
 4776: 
 4777: sub assigncustomrole {
 4778:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4779:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4780:                        $end,$start,$deleteflag);
 4781: }
 4782: 
 4783: # ----------------------------------------------------------------- Revoke Role
 4784: 
 4785: sub revokerole {
 4786:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4787:     my $now=time;
 4788:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4789: }
 4790: 
 4791: # ---------------------------------------------------------- Revoke Custom Role
 4792: 
 4793: sub revokecustomrole {
 4794:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4795:     my $now=time;
 4796:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4797:            $deleteflag);
 4798: }
 4799: 
 4800: # ------------------------------------------------------------ Disk usage
 4801: sub diskusage {
 4802:     my ($udom,$uname,$directoryRoot)=@_;
 4803:     $directoryRoot =~ s/\/$//;
 4804:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4805:     return $listing;
 4806: }
 4807: 
 4808: sub is_locked {
 4809:     my ($file_name, $domain, $user) = @_;
 4810:     my @check;
 4811:     my $is_locked;
 4812:     push @check, $file_name;
 4813:     my %locked = &get('file_permissions',\@check,
 4814: 		      $env{'user.domain'},$env{'user.name'});
 4815:     my ($tmp)=keys(%locked);
 4816:     if ($tmp=~/^error:/) { undef(%locked); }
 4817:     
 4818:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4819:         $is_locked = 'false';
 4820:         foreach my $entry (@{$locked{$file_name}}) {
 4821:            if (ref($entry) eq 'ARRAY') { 
 4822:                $is_locked = 'true';
 4823:                last;
 4824:            }
 4825:        }
 4826:     } else {
 4827:         $is_locked = 'false';
 4828:     }
 4829: }
 4830: 
 4831: sub declutter_portfile {
 4832:     my ($file) = @_;
 4833:     &logthis("got $file");
 4834:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 4835:     &logthis("ret $file");
 4836:     return $file;
 4837: }
 4838: 
 4839: # ------------------------------------------------------------- Mark as Read Only
 4840: 
 4841: sub mark_as_readonly {
 4842:     my ($domain,$user,$files,$what) = @_;
 4843:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4844:     my ($tmp)=keys(%current_permissions);
 4845:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4846:     foreach my $file (@{$files}) {
 4847: 	$file = &declutter_portfile($file);
 4848:         push(@{$current_permissions{$file}},$what);
 4849:     }
 4850:     &put('file_permissions',\%current_permissions,$domain,$user);
 4851:     return;
 4852: }
 4853: 
 4854: # ------------------------------------------------------------Save Selected Files
 4855: 
 4856: sub save_selected_files {
 4857:     my ($user, $path, @files) = @_;
 4858:     my $filename = $user."savedfiles";
 4859:     my @other_files = &files_not_in_path($user, $path);
 4860:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4861:     foreach my $file (@files) {
 4862:         print (OUT $env{'form.currentpath'}.$file."\n");
 4863:     }
 4864:     foreach my $file (@other_files) {
 4865:         print (OUT $file."\n");
 4866:     }
 4867:     close (OUT);
 4868:     return 'ok';
 4869: }
 4870: 
 4871: sub clear_selected_files {
 4872:     my ($user) = @_;
 4873:     my $filename = $user."savedfiles";
 4874:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4875:     print (OUT undef);
 4876:     close (OUT);
 4877:     return ("ok");    
 4878: }
 4879: 
 4880: sub files_in_path {
 4881:     my ($user, $path) = @_;
 4882:     my $filename = $user."savedfiles";
 4883:     my %return_files;
 4884:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4885:     while (my $line_in = <IN>) {
 4886:         chomp ($line_in);
 4887:         my @paths_and_file = split (m!/!, $line_in);
 4888:         my $file_part = pop (@paths_and_file);
 4889:         my $path_part = join ('/', @paths_and_file);
 4890:         $path_part.='/';
 4891:         my $path_and_file = $path_part.$file_part;
 4892:         if ($path_part eq $path) {
 4893:             $return_files{$file_part}= 'selected';
 4894:         }
 4895:     }
 4896:     close (IN);
 4897:     return (\%return_files);
 4898: }
 4899: 
 4900: # called in portfolio select mode, to show files selected NOT in current directory
 4901: sub files_not_in_path {
 4902:     my ($user, $path) = @_;
 4903:     my $filename = $user."savedfiles";
 4904:     my @return_files;
 4905:     my $path_part;
 4906:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4907:     while (<IN>) {
 4908:         #ok, I know it's clunky, but I want it to work
 4909:         my @paths_and_file = split m!/!, $_;
 4910:         my $file_part = pop (@paths_and_file);
 4911:         chomp ($file_part);
 4912:         my $path_part = join ('/', @paths_and_file);
 4913:         $path_part .= '/';
 4914:         my $path_and_file = $path_part.$file_part;
 4915:         if ($path_part ne $path) {
 4916:             push (@return_files, ($path_and_file));
 4917:         }
 4918:     }
 4919:     close (OUT);
 4920:     return (@return_files);
 4921: }
 4922: 
 4923: #----------------------------------------------Get portfolio file permissions
 4924: 
 4925: sub get_portfile_permissions {
 4926:     my ($domain,$user) = @_;
 4927:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4928:     my ($tmp)=keys(%current_permissions);
 4929:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4930:     return \%current_permissions;
 4931: }
 4932: 
 4933: #---------------------------------------------Get portfolio file access controls
 4934: 
 4935: sub get_access_controls {
 4936:     my ($current_permissions,$group,$file) = @_;
 4937:     my %access;
 4938:     my $real_file = $file;
 4939:     $file =~ s/\.meta$//;
 4940:     if (defined($file)) {
 4941:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 4942:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 4943:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 4944:             }
 4945:         }
 4946:     } else {
 4947:         foreach my $key (keys(%{$current_permissions})) {
 4948:             if ($key =~ /\0accesscontrol$/) {
 4949:                 if (defined($group)) {
 4950:                     if ($key !~ m-^\Q$group\E/-) {
 4951:                         next;
 4952:                     }
 4953:                 }
 4954:                 my ($fullpath) = split(/\0/,$key);
 4955:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 4956:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 4957:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 4958:                     }
 4959:                 }
 4960:             }
 4961:         }
 4962:     }
 4963:     return %access;
 4964: }
 4965: 
 4966: sub modify_access_controls {
 4967:     my ($file_name,$changes,$domain,$user)=@_;
 4968:     my ($outcome,$deloutcome);
 4969:     my %store_permissions;
 4970:     my %new_values;
 4971:     my %new_control;
 4972:     my %translation;
 4973:     my @deletions = ();
 4974:     my $now = time;
 4975:     if (exists($$changes{'activate'})) {
 4976:         if (ref($$changes{'activate'}) eq 'HASH') {
 4977:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 4978:             my $numnew = scalar(@newitems);
 4979:             for (my $i=0; $i<$numnew; $i++) {
 4980:                 my $newkey = $newitems[$i];
 4981:                 my $newid = &Apache::loncommon::get_cgi_id();
 4982:                 $newkey =~ s/^(\d+)/$newid/;
 4983:                 $translation{$1} = $newid;
 4984:                 $new_values{$file_name."\0".$newkey} = 
 4985:                                           $$changes{'activate'}{$newitems[$i]};
 4986:                 $new_control{$newkey} = $now;
 4987:             }
 4988:         }
 4989:     }
 4990:     my %todelete;
 4991:     my %changed_items;
 4992:     foreach my $action ('delete','update') {
 4993:         if (exists($$changes{$action})) {
 4994:             if (ref($$changes{$action}) eq 'HASH') {
 4995:                 foreach my $key (keys(%{$$changes{$action}})) {
 4996:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 4997:                     if ($action eq 'delete') { 
 4998:                         $todelete{$itemnum} = 1;
 4999:                     } else {
 5000:                         $changed_items{$itemnum} = $key;
 5001:                     }
 5002:                 }
 5003:             }
 5004:         }
 5005:     }
 5006:     # get lock on access controls for file.
 5007:     my $lockhash = {
 5008:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5009:                                                        ':'.$env{'user.domain'},
 5010:                    }; 
 5011:     my $tries = 0;
 5012:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5013:    
 5014:     while (($gotlock ne 'ok') && $tries <3) {
 5015:         $tries ++;
 5016:         sleep 1;
 5017:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5018:     }
 5019:     if ($gotlock eq 'ok') {
 5020:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5021:         my ($tmp)=keys(%curr_permissions);
 5022:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5023:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5024:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5025:             if (ref($curr_controls) eq 'HASH') {
 5026:                 foreach my $control_item (keys(%{$curr_controls})) {
 5027:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5028:                     if (defined($todelete{$itemnum})) {
 5029:                         push(@deletions,$file_name."\0".$control_item);
 5030:                     } else {
 5031:                         if (defined($changed_items{$itemnum})) {
 5032:                             $new_control{$changed_items{$itemnum}} = $now;
 5033:                             push(@deletions,$file_name."\0".$control_item);
 5034:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5035:                         } else {
 5036:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5037:                         }
 5038:                     }
 5039:                 }
 5040:             }
 5041:         }
 5042:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5043:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5044:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5045:         #  remove lock
 5046:         my @del_lock = ($file_name."\0".'locked_access_records');
 5047:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5048:     } else {
 5049:         $outcome = "error: could not obtain lockfile\n";  
 5050:     }
 5051:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5052: }
 5053: 
 5054: #------------------------------------------------------Get Marked as Read Only
 5055: 
 5056: sub get_marked_as_readonly {
 5057:     my ($domain,$user,$what,$group) = @_;
 5058:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5059:     my @readonly_files;
 5060:     my $cmp1=$what;
 5061:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5062:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5063:         if (defined($group)) {
 5064:             if ($file_name !~ m-^\Q$group\E/-) {
 5065:                 next;
 5066:             }
 5067:         }
 5068:         if (ref($value) eq "ARRAY"){
 5069:             foreach my $stored_what (@{$value}) {
 5070:                 my $cmp2=$stored_what;
 5071:                 if (ref($stored_what) eq 'ARRAY') {
 5072:                     $cmp2=join('',@{$stored_what});
 5073:                 }
 5074:                 if ($cmp1 eq $cmp2) {
 5075:                     push(@readonly_files, $file_name);
 5076:                     last;
 5077:                 } elsif (!defined($what)) {
 5078:                     push(@readonly_files, $file_name);
 5079:                     last;
 5080:                 }
 5081:             }
 5082:         }
 5083:     }
 5084:     return @readonly_files;
 5085: }
 5086: #-----------------------------------------------------------Get Marked as Read Only Hash
 5087: 
 5088: sub get_marked_as_readonly_hash {
 5089:     my ($current_permissions,$group,$what) = @_;
 5090:     my %readonly_files;
 5091:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5092:         if (defined($group)) {
 5093:             if ($file_name !~ m-^\Q$group\E/-) {
 5094:                 next;
 5095:             }
 5096:         }
 5097:         if (ref($value) eq "ARRAY"){
 5098:             foreach my $stored_what (@{$value}) {
 5099:                 if (ref($stored_what) eq 'ARRAY') {
 5100:                     foreach my $lock_descriptor(@{$stored_what}) {
 5101:                         if ($lock_descriptor eq 'graded') {
 5102:                             $readonly_files{$file_name} = 'graded';
 5103:                         } elsif ($lock_descriptor eq 'handback') {
 5104:                             $readonly_files{$file_name} = 'handback';
 5105:                         } else {
 5106:                             if (!exists($readonly_files{$file_name})) {
 5107:                                 $readonly_files{$file_name} = 'locked';
 5108:                             }
 5109:                         }
 5110:                     }
 5111:                 } 
 5112:             }
 5113:         } 
 5114:     }
 5115:     return %readonly_files;
 5116: }
 5117: # ------------------------------------------------------------ Unmark as Read Only
 5118: 
 5119: sub unmark_as_readonly {
 5120:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5121:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5122:     my ($domain,$user,$what,$file_name,$group) = @_;
 5123:     $file_name = &declutter_portfile($file_name);
 5124:     my $symb_crs = $what;
 5125:     if (ref($what)) { $symb_crs=join('',@$what); }
 5126:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5127:     my ($tmp)=keys(%current_permissions);
 5128:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5129:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5130:     foreach my $file (@readonly_files) {
 5131: 	my $clean_file = &declutter_portfile($file);
 5132: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5133: 	my $current_locks = $current_permissions{$file};
 5134:         my @new_locks;
 5135:         my @del_keys;
 5136:         if (ref($current_locks) eq "ARRAY"){
 5137:             foreach my $locker (@{$current_locks}) {
 5138:                 my $compare=$locker;
 5139:                 if (ref($locker) eq 'ARRAY') {
 5140:                     $compare=join('',@{$locker});
 5141:                     if ($compare ne $symb_crs) {
 5142:                         push(@new_locks, $locker);
 5143:                     }
 5144:                 }
 5145:             }
 5146:             if (scalar(@new_locks) > 0) {
 5147:                 $current_permissions{$file} = \@new_locks;
 5148:             } else {
 5149:                 push(@del_keys, $file);
 5150:                 &del('file_permissions',\@del_keys, $domain, $user);
 5151:                 delete($current_permissions{$file});
 5152:             }
 5153:         }
 5154:     }
 5155:     &put('file_permissions',\%current_permissions,$domain,$user);
 5156:     return;
 5157: }
 5158: 
 5159: # ------------------------------------------------------------ Directory lister
 5160: 
 5161: sub dirlist {
 5162:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5163: 
 5164:     $uri=~s/^\///;
 5165:     $uri=~s/\/$//;
 5166:     my ($udom, $uname);
 5167:     (undef,$udom,$uname)=split(/\//,$uri);
 5168:     if(defined($userdomain)) {
 5169:         $udom = $userdomain;
 5170:     }
 5171:     if(defined($username)) {
 5172:         $uname = $username;
 5173:     }
 5174: 
 5175:     my $dirRoot = $perlvar{'lonDocRoot'};
 5176:     if(defined($alternateDirectoryRoot)) {
 5177:         $dirRoot = $alternateDirectoryRoot;
 5178:         $dirRoot =~ s/\/$//;
 5179:     }
 5180: 
 5181:     if($udom) {
 5182:         if($uname) {
 5183:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 5184:                               homeserver($uname,$udom));
 5185:             my @listing_results;
 5186:             if ($listing eq 'unknown_cmd') {
 5187:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 5188:                                homeserver($uname,$udom));
 5189:                 @listing_results = split(/:/,$listing);
 5190:             } else {
 5191:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5192:             }
 5193:             return @listing_results;
 5194:         } elsif(!defined($alternateDirectoryRoot)) {
 5195:             my $tryserver;
 5196:             my %allusers=();
 5197:             foreach $tryserver (keys %libserv) {
 5198:                 if($hostdom{$tryserver} eq $udom) {
 5199:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5200:                                       $udom, $tryserver);
 5201:                     my @listing_results;
 5202:                     if ($listing eq 'unknown_cmd') {
 5203:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5204:                                        $udom, $tryserver);
 5205:                         @listing_results = split(/:/,$listing);
 5206:                     } else {
 5207:                         @listing_results =
 5208:                             map { &unescape($_); } split(/:/,$listing);
 5209:                     }
 5210:                     if ($listing_results[0] ne 'no_such_dir' && 
 5211:                         $listing_results[0] ne 'empty'       &&
 5212:                         $listing_results[0] ne 'con_lost') {
 5213:                         foreach (@listing_results) {
 5214:                             my ($entry,@stat)=split(/&/,$_);
 5215:                             $allusers{$entry}=1;
 5216:                         }
 5217:                     }
 5218:                 }
 5219:             }
 5220:             my $alluserstr='';
 5221:             foreach (sort keys %allusers) {
 5222:                 $alluserstr.=$_.'&user:';
 5223:             }
 5224:             $alluserstr=~s/:$//;
 5225:             return split(/:/,$alluserstr);
 5226:         } else {
 5227:             my @emptyResults = ();
 5228:             push(@emptyResults, 'missing user name');
 5229:             return split(':',@emptyResults);
 5230:         }
 5231:     } elsif(!defined($alternateDirectoryRoot)) {
 5232:         my $tryserver;
 5233:         my %alldom=();
 5234:         foreach $tryserver (keys %libserv) {
 5235:             $alldom{$hostdom{$tryserver}}=1;
 5236:         }
 5237:         my $alldomstr='';
 5238:         foreach (sort keys %alldom) {
 5239:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 5240:         }
 5241:         $alldomstr=~s/:$//;
 5242:         return split(/:/,$alldomstr);       
 5243:     } else {
 5244:         my @emptyResults = ();
 5245:         push(@emptyResults, 'missing domain');
 5246:         return split(':',@emptyResults);
 5247:     }
 5248: }
 5249: 
 5250: # --------------------------------------------- GetFileTimestamp
 5251: # This function utilizes dirlist and returns the date stamp for
 5252: # when it was last modified.  It will also return an error of -1
 5253: # if an error occurs
 5254: 
 5255: ##
 5256: ## FIXME: This subroutine assumes its caller knows something about the
 5257: ## directory structure of the home server for the student ($root).
 5258: ## Not a good assumption to make.  Since this is for looking up files
 5259: ## in user directories, the full path should be constructed by lond, not
 5260: ## whatever machine we request data from.
 5261: ##
 5262: sub GetFileTimestamp {
 5263:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5264:     $studentDomain=~s/\W//g;
 5265:     $studentName=~s/\W//g;
 5266:     my $subdir=$studentName.'__';
 5267:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5268:     my $proname="$studentDomain/$subdir/$studentName";
 5269:     $proname .= '/'.$filename;
 5270:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5271:                                               $studentName, $root);
 5272:     my @stats = split('&', $fileStat);
 5273:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5274:         # @stats contains first the filename, then the stat output
 5275:         return $stats[10]; # so this is 10 instead of 9.
 5276:     } else {
 5277:         return -1;
 5278:     }
 5279: }
 5280: 
 5281: sub stat_file {
 5282:     my ($uri) = @_;
 5283:     $uri = &clutter($uri);
 5284: 
 5285:     # we want just the url part without the unneeded accessor url bits
 5286:     if ($uri =~ m-^/adm/-) {
 5287: 	$uri=~s-^/adm/wrapper/-/-;
 5288: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 5289:     }
 5290:     my ($udom,$uname,$file,$dir);
 5291:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5292: 	($udom,$uname,$file) =
 5293: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5294: 	$file = 'userfiles/'.$file;
 5295: 	$dir = &propath($udom,$uname);
 5296:     }
 5297:     if ($uri =~ m-^/res/-) {
 5298: 	($udom,$uname) = 
 5299: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5300: 	$file = $uri;
 5301:     }
 5302: 
 5303:     if (!$udom || !$uname || !$file) {
 5304: 	# unable to handle the uri
 5305: 	return ();
 5306:     }
 5307: 
 5308:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5309:     my @stats = split('&', $result);
 5310:     
 5311:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5312: 	shift(@stats); #filename is first
 5313: 	return @stats;
 5314:     }
 5315:     return ();
 5316: }
 5317: 
 5318: # -------------------------------------------------------- Value of a Condition
 5319: 
 5320: # gets the value of a specific preevaluated condition
 5321: #    stored in the string  $env{user.state.<cid>}
 5322: # or looks up a condition reference in the bighash and if if hasn't
 5323: # already been evaluated recurses into docondval to get the value of
 5324: # the condition, then memoizing it to 
 5325: #   $env{user.state.<cid>.<condition>}
 5326: sub directcondval {
 5327:     my $number=shift;
 5328:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5329: 	&Apache::lonuserstate::evalstate();
 5330:     }
 5331:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5332: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5333:     } elsif ($number =~ /^_/) {
 5334: 	my $sub_condition;
 5335: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5336: 		&GDBM_READER(),0640)) {
 5337: 	    $sub_condition=$bighash{'conditions'.$number};
 5338: 	    untie(%bighash);
 5339: 	}
 5340: 	my $value = &docondval($sub_condition);
 5341: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5342: 	return $value;
 5343:     }
 5344:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5345:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5346:     } else {
 5347:        return 2;
 5348:     }
 5349: }
 5350: 
 5351: # get the collection of conditions for this resource
 5352: sub condval {
 5353:     my $condidx=shift;
 5354:     my $allpathcond='';
 5355:     foreach my $cond (split(/\|/,$condidx)) {
 5356: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5357: 	    $allpathcond.=
 5358: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5359: 	}
 5360:     }
 5361:     $allpathcond=~s/\|$//;
 5362:     return &docondval($allpathcond);
 5363: }
 5364: 
 5365: #evaluates an expression of conditions
 5366: sub docondval {
 5367:     my ($allpathcond) = @_;
 5368:     my $result=0;
 5369:     if ($env{'request.course.id'}
 5370: 	&& defined($allpathcond)) {
 5371: 	my $operand='|';
 5372: 	my @stack;
 5373: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5374: 	    if ($chunk eq '(') {
 5375: 		push @stack,($operand,$result);
 5376: 	    } elsif ($chunk eq ')') {
 5377: 		my $before=pop @stack;
 5378: 		if (pop @stack eq '&') {
 5379: 		    $result=$result>$before?$before:$result;
 5380: 		} else {
 5381: 		    $result=$result>$before?$result:$before;
 5382: 		}
 5383: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5384: 		$operand=$chunk;
 5385: 	    } else {
 5386: 		my $new=directcondval($chunk);
 5387: 		if ($operand eq '&') {
 5388: 		    $result=$result>$new?$new:$result;
 5389: 		} else {
 5390: 		    $result=$result>$new?$result:$new;
 5391: 		}
 5392: 	    }
 5393: 	}
 5394:     }
 5395:     return $result;
 5396: }
 5397: 
 5398: # ---------------------------------------------------- Devalidate courseresdata
 5399: 
 5400: sub devalidatecourseresdata {
 5401:     my ($coursenum,$coursedomain)=@_;
 5402:     my $hashid=$coursenum.':'.$coursedomain;
 5403:     &devalidate_cache_new('courseres',$hashid);
 5404: }
 5405: 
 5406: 
 5407: # --------------------------------------------------- Course Resourcedata Query
 5408: 
 5409: sub get_courseresdata {
 5410:     my ($coursenum,$coursedomain)=@_;
 5411:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5412:     my $hashid=$coursenum.':'.$coursedomain;
 5413:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5414:     my %dumpreply;
 5415:     unless (defined($cached)) {
 5416: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5417: 	$result=\%dumpreply;
 5418: 	my ($tmp) = keys(%dumpreply);
 5419: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5420: 	    &do_cache_new('courseres',$hashid,$result,600);
 5421: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5422: 	    return $tmp;
 5423: 	} elsif ($tmp =~ /^(error)/) {
 5424: 	    $result=undef;
 5425: 	    &do_cache_new('courseres',$hashid,$result,600);
 5426: 	}
 5427:     }
 5428:     return $result;
 5429: }
 5430: 
 5431: sub devalidateuserresdata {
 5432:     my ($uname,$udom)=@_;
 5433:     my $hashid="$udom:$uname";
 5434:     &devalidate_cache_new('userres',$hashid);
 5435: }
 5436: 
 5437: sub get_userresdata {
 5438:     my ($uname,$udom)=@_;
 5439:     #most student don\'t have any data set, check if there is some data
 5440:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5441: 
 5442:     my $hashid="$udom:$uname";
 5443:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5444:     if (!defined($cached)) {
 5445: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5446: 	$result=\%resourcedata;
 5447: 	&do_cache_new('userres',$hashid,$result,600);
 5448:     }
 5449:     my ($tmp)=keys(%$result);
 5450:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5451: 	return $result;
 5452:     }
 5453:     #error 2 occurs when the .db doesn't exist
 5454:     if ($tmp!~/error: 2 /) {
 5455: 	&logthis("<font color=\"blue\">WARNING:".
 5456: 		 " Trying to get resource data for ".
 5457: 		 $uname." at ".$udom.": ".
 5458: 		 $tmp."</font>");
 5459:     } elsif ($tmp=~/error: 2 /) {
 5460: 	#&EXT_cache_set($udom,$uname);
 5461: 	&do_cache_new('userres',$hashid,undef,600);
 5462: 	undef($tmp); # not really an error so don't send it back
 5463:     }
 5464:     return $tmp;
 5465: }
 5466: 
 5467: sub resdata {
 5468:     my ($name,$domain,$type,@which)=@_;
 5469:     my $result;
 5470:     if ($type eq 'course') {
 5471: 	$result=&get_courseresdata($name,$domain);
 5472:     } elsif ($type eq 'user') {
 5473: 	$result=&get_userresdata($name,$domain);
 5474:     }
 5475:     if (!ref($result)) { return $result; }    
 5476:     foreach my $item (@which) {
 5477: 	if (defined($result->{$item})) {
 5478: 	    return $result->{$item};
 5479: 	}
 5480:     }
 5481:     return undef;
 5482: }
 5483: 
 5484: #
 5485: # EXT resource caching routines
 5486: #
 5487: 
 5488: sub clear_EXT_cache_status {
 5489:     &delenv('cache.EXT.');
 5490: }
 5491: 
 5492: sub EXT_cache_status {
 5493:     my ($target_domain,$target_user) = @_;
 5494:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5495:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5496:         # We know already the user has no data
 5497:         return 1;
 5498:     } else {
 5499:         return 0;
 5500:     }
 5501: }
 5502: 
 5503: sub EXT_cache_set {
 5504:     my ($target_domain,$target_user) = @_;
 5505:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5506:     #&appenv($cachename => time);
 5507: }
 5508: 
 5509: # --------------------------------------------------------- Value of a Variable
 5510: sub EXT {
 5511: 
 5512:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5513:     unless ($varname) { return ''; }
 5514:     #get real user name/domain, courseid and symb
 5515:     my $courseid;
 5516:     my $publicuser;
 5517:     if ($symbparm) {
 5518: 	$symbparm=&get_symb_from_alias($symbparm);
 5519:     }
 5520:     if (!($uname && $udom)) {
 5521:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5522: 	  &Apache::lonxml::whichuser($symbparm);
 5523:       if (!$symbparm) {	$symbparm=$cursymb; }
 5524:     } else {
 5525: 	$courseid=$env{'request.course.id'};
 5526:     }
 5527:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5528:     my $rest;
 5529:     if (defined($therest[0])) {
 5530:        $rest=join('.',@therest);
 5531:     } else {
 5532:        $rest='';
 5533:     }
 5534: 
 5535:     my $qualifierrest=$qualifier;
 5536:     if ($rest) { $qualifierrest.='.'.$rest; }
 5537:     my $spacequalifierrest=$space;
 5538:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5539:     if ($realm eq 'user') {
 5540: # --------------------------------------------------------------- user.resource
 5541: 	if ($space eq 'resource') {
 5542: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5543: 		  || defined($Apache::lonhomework::parsing_a_task))
 5544: 		 &&
 5545: 		 ($symbparm eq &symbread()) ) {	
 5546: 		# if we are in the middle of processing the resource the
 5547: 		# get the value we are planning on committing
 5548:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5549:                     return $Apache::lonhomework::results{$qualifierrest};
 5550:                 } else {
 5551:                     return $Apache::lonhomework::history{$qualifierrest};
 5552:                 }
 5553: 	    } else {
 5554: 		my %restored;
 5555: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5556: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5557: 		} else {
 5558: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5559: 		}
 5560: 		return $restored{$qualifierrest};
 5561: 	    }
 5562: # ----------------------------------------------------------------- user.access
 5563:         } elsif ($space eq 'access') {
 5564: 	    # FIXME - not supporting calls for a specific user
 5565:             return &allowed($qualifier,$rest);
 5566: # ------------------------------------------ user.preferences, user.environment
 5567:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5568: 	    if (($uname eq $env{'user.name'}) &&
 5569: 		($udom eq $env{'user.domain'})) {
 5570: 		return $env{join('.',('environment',$qualifierrest))};
 5571: 	    } else {
 5572: 		my %returnhash;
 5573: 		if (!$publicuser) {
 5574: 		    %returnhash=&userenvironment($udom,$uname,
 5575: 						 $qualifierrest);
 5576: 		}
 5577: 		return $returnhash{$qualifierrest};
 5578: 	    }
 5579: # ----------------------------------------------------------------- user.course
 5580:         } elsif ($space eq 'course') {
 5581: 	    # FIXME - not supporting calls for a specific user
 5582:             return $env{join('.',('request.course',$qualifier))};
 5583: # ------------------------------------------------------------------- user.role
 5584:         } elsif ($space eq 'role') {
 5585: 	    # FIXME - not supporting calls for a specific user
 5586:             my ($role,$where)=split(/\./,$env{'request.role'});
 5587:             if ($qualifier eq 'value') {
 5588: 		return $role;
 5589:             } elsif ($qualifier eq 'extent') {
 5590:                 return $where;
 5591:             }
 5592: # ----------------------------------------------------------------- user.domain
 5593:         } elsif ($space eq 'domain') {
 5594:             return $udom;
 5595: # ------------------------------------------------------------------- user.name
 5596:         } elsif ($space eq 'name') {
 5597:             return $uname;
 5598: # ---------------------------------------------------- Any other user namespace
 5599:         } else {
 5600: 	    my %reply;
 5601: 	    if (!$publicuser) {
 5602: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5603: 	    }
 5604: 	    return $reply{$qualifierrest};
 5605:         }
 5606:     } elsif ($realm eq 'query') {
 5607: # ---------------------------------------------- pull stuff out of query string
 5608:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5609: 						[$spacequalifierrest]);
 5610: 	return $env{'form.'.$spacequalifierrest}; 
 5611:    } elsif ($realm eq 'request') {
 5612: # ------------------------------------------------------------- request.browser
 5613:         if ($space eq 'browser') {
 5614: 	    if ($qualifier eq 'textremote') {
 5615: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5616: 		    return 1;
 5617: 		} else {
 5618: 		    return 0;
 5619: 		}
 5620: 	    } else {
 5621: 		return $env{'browser.'.$qualifier};
 5622: 	    }
 5623: # ------------------------------------------------------------ request.filename
 5624:         } else {
 5625:             return $env{'request.'.$spacequalifierrest};
 5626:         }
 5627:     } elsif ($realm eq 'course') {
 5628: # ---------------------------------------------------------- course.description
 5629:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5630:     } elsif ($realm eq 'resource') {
 5631: 
 5632: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5633: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5634: 	}
 5635: 
 5636: 	if ($space eq 'title') {
 5637: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5638: 	    return &gettitle($symbparm);
 5639: 	}
 5640: 	
 5641: 	if ($space eq 'map') {
 5642: 	    my ($map) = &decode_symb($symbparm);
 5643: 	    return &symbread($map);
 5644: 	}
 5645: 
 5646: 	my ($section, $group, @groups);
 5647: 	my ($courselevelm,$courselevel);
 5648: 	if ($symbparm && defined($courseid) && 
 5649: 	    $courseid eq $env{'request.course.id'}) {
 5650: 
 5651: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5652: 
 5653: # ----------------------------------------------------- Cascading lookup scheme
 5654: 	    my $symbp=$symbparm;
 5655: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5656: 
 5657: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5658: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5659: 
 5660: 	    if (($env{'user.name'} eq $uname) &&
 5661: 		($env{'user.domain'} eq $udom)) {
 5662: 		$section=$env{'request.course.sec'};
 5663:                 @groups = split(/:/,$env{'request.course.groups'});  
 5664:                 @groups=&sort_course_groups($courseid,@groups); 
 5665: 	    } else {
 5666: 		if (! defined($usection)) {
 5667: 		    $section=&getsection($udom,$uname,$courseid);
 5668: 		} else {
 5669: 		    $section = $usection;
 5670: 		}
 5671:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5672: 	    }
 5673: 
 5674: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5675: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5676: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5677: 
 5678: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5679: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5680: 	    $courselevelm=$courseid.'.'.$mapparm;
 5681: 
 5682: # ----------------------------------------------------------- first, check user
 5683: 
 5684: 	    my $userreply=&resdata($uname,$udom,'user',
 5685: 				       ($courselevelr,$courselevelm,
 5686: 					$courselevel));
 5687: 	    if (defined($userreply)) { return $userreply; }
 5688: 
 5689: # ------------------------------------------------ second, check some of course
 5690:             my $coursereply;
 5691:             if (@groups > 0) {
 5692:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5693:                                        $mapparm,$spacequalifierrest);
 5694:                 if (defined($coursereply)) { return $coursereply; }
 5695:             }
 5696: 
 5697: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5698: 				     $env{'course.'.$courseid.'.domain'},
 5699: 				     'course',
 5700: 				     ($seclevelr,$seclevelm,$seclevel,
 5701: 				      $courselevelr));
 5702: 	    if (defined($coursereply)) { return $coursereply; }
 5703: 
 5704: # ------------------------------------------------------ third, check map parms
 5705: 	    my %parmhash=();
 5706: 	    my $thisparm='';
 5707: 	    if (tie(%parmhash,'GDBM_File',
 5708: 		    $env{'request.course.fn'}.'_parms.db',
 5709: 		    &GDBM_READER(),0640)) {
 5710: 		$thisparm=$parmhash{$symbparm};
 5711: 		untie(%parmhash);
 5712: 	    }
 5713: 	    if ($thisparm) { return $thisparm; }
 5714: 	}
 5715: # ------------------------------------------ fourth, look in resource metadata
 5716: 
 5717: 	$spacequalifierrest=~s/\./\_/;
 5718: 	my $filename;
 5719: 	if (!$symbparm) { $symbparm=&symbread(); }
 5720: 	if ($symbparm) {
 5721: 	    $filename=(&decode_symb($symbparm))[2];
 5722: 	} else {
 5723: 	    $filename=$env{'request.filename'};
 5724: 	}
 5725: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5726: 	if (defined($metadata)) { return $metadata; }
 5727: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5728: 	if (defined($metadata)) { return $metadata; }
 5729: 
 5730: # ---------------------------------------------- fourth, look in rest pf course
 5731: 	if ($symbparm && defined($courseid) && 
 5732: 	    $courseid eq $env{'request.course.id'}) {
 5733: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5734: 				     $env{'course.'.$courseid.'.domain'},
 5735: 				     'course',
 5736: 				     ($courselevelm,$courselevel));
 5737: 	    if (defined($coursereply)) { return $coursereply; }
 5738: 	}
 5739: # ------------------------------------------------------------------ Cascade up
 5740: 	unless ($space eq '0') {
 5741: 	    my @parts=split(/_/,$space);
 5742: 	    my $id=pop(@parts);
 5743: 	    my $part=join('_',@parts);
 5744: 	    if ($part eq '') { $part='0'; }
 5745: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5746: 				 $symbparm,$udom,$uname,$section,1);
 5747: 	    if (defined($partgeneral)) { return $partgeneral; }
 5748: 	}
 5749: 	if ($recurse) { return undef; }
 5750: 	my $pack_def=&packages_tab_default($filename,$varname);
 5751: 	if (defined($pack_def)) { return $pack_def; }
 5752: 
 5753: # ---------------------------------------------------- Any other user namespace
 5754:     } elsif ($realm eq 'environment') {
 5755: # ----------------------------------------------------------------- environment
 5756: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5757: 	    return $env{'environment.'.$spacequalifierrest};
 5758: 	} else {
 5759: 	    if ($uname eq 'anonymous' && $udom eq '') {
 5760: 		return '';
 5761: 	    }
 5762: 	    my %returnhash=&userenvironment($udom,$uname,
 5763: 					    $spacequalifierrest);
 5764: 	    return $returnhash{$spacequalifierrest};
 5765: 	}
 5766:     } elsif ($realm eq 'system') {
 5767: # ----------------------------------------------------------------- system.time
 5768: 	if ($space eq 'time') {
 5769: 	    return time;
 5770:         }
 5771:     } elsif ($realm eq 'server') {
 5772: # ----------------------------------------------------------------- system.time
 5773: 	if ($space eq 'name') {
 5774: 	    return $ENV{'SERVER_NAME'};
 5775:         }
 5776:     }
 5777:     return '';
 5778: }
 5779: 
 5780: sub check_group_parms {
 5781:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5782:     my @groupitems = ();
 5783:     my $resultitem;
 5784:     my @levels = ($symbparm,$mapparm,$what);
 5785:     foreach my $group (@{$groups}) {
 5786:         foreach my $level (@levels) {
 5787:              my $item = $courseid.'.['.$group.'].'.$level;
 5788:              push(@groupitems,$item);
 5789:         }
 5790:     }
 5791:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5792:                             $env{'course.'.$courseid.'.domain'},
 5793:                                      'course',@groupitems);
 5794:     return $coursereply;
 5795: }
 5796: 
 5797: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5798:     my ($courseid,@groups) = @_;
 5799:     @groups = sort(@groups);
 5800:     return @groups;
 5801: }
 5802: 
 5803: sub packages_tab_default {
 5804:     my ($uri,$varname)=@_;
 5805:     my (undef,$part,$name)=split(/\./,$varname);
 5806: 
 5807:     my (@extension,@specifics,$do_default);
 5808:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5809: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5810: 	if ($pack_type eq 'default') {
 5811: 	    $do_default=1;
 5812: 	} elsif ($pack_type eq 'extension') {
 5813: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5814: 	} else {
 5815: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5816: 	}
 5817:     }
 5818:     # first look for a package that matches the requested part id
 5819:     foreach my $package (@specifics) {
 5820: 	my (undef,$pack_type,$pack_part)=@{$package};
 5821: 	next if ($pack_part ne $part);
 5822: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5823: 	    return $packagetab{"$pack_type&$name&default"};
 5824: 	}
 5825:     }
 5826:     # look for any possible matching non extension_ package
 5827:     foreach my $package (@specifics) {
 5828: 	my (undef,$pack_type,$pack_part)=@{$package};
 5829: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5830: 	    return $packagetab{"$pack_type&$name&default"};
 5831: 	}
 5832: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5833: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5834: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5835: 	}
 5836:     }
 5837:     # look for any posible extension_ match
 5838:     foreach my $package (@extension) {
 5839: 	my ($package,$pack_type)=@{$package};
 5840: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5841: 	    return $packagetab{"$pack_type&$name&default"};
 5842: 	}
 5843: 	if (defined($packagetab{$package."&$name&default"})) {
 5844: 	    return $packagetab{$package."&$name&default"};
 5845: 	}
 5846:     }
 5847:     # look for a global default setting
 5848:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5849: 	return $packagetab{"default&$name&default"};
 5850:     }
 5851:     return undef;
 5852: }
 5853: 
 5854: sub add_prefix_and_part {
 5855:     my ($prefix,$part)=@_;
 5856:     my $keyroot;
 5857:     if (defined($prefix) && $prefix !~ /^__/) {
 5858: 	# prefix that has a part already
 5859: 	$keyroot=$prefix;
 5860:     } elsif (defined($prefix)) {
 5861: 	# prefix that is missing a part
 5862: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5863:     } else {
 5864: 	# no prefix at all
 5865: 	if (defined($part)) { $keyroot='_'.$part; }
 5866:     }
 5867:     return $keyroot;
 5868: }
 5869: 
 5870: # ---------------------------------------------------------------- Get metadata
 5871: 
 5872: my %metaentry;
 5873: sub metadata {
 5874:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5875:     $uri=&declutter($uri);
 5876:     # if it is a non metadata possible uri return quickly
 5877:     if (($uri eq '') || 
 5878: 	(($uri =~ m|^/*adm/|) && 
 5879: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5880:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5881: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5882: 	return undef;
 5883:     }
 5884:     my $filename=$uri;
 5885:     $uri=~s/\.meta$//;
 5886: #
 5887: # Is the metadata already cached?
 5888: # Look at timestamp of caching
 5889: # Everything is cached by the main uri, libraries are never directly cached
 5890: #
 5891:     if (!defined($liburi)) {
 5892: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5893: 	if (defined($cached)) { return $result->{':'.$what}; }
 5894:     }
 5895:     {
 5896: #
 5897: # Is this a recursive call for a library?
 5898: #
 5899: #	if (! exists($metacache{$uri})) {
 5900: #	    $metacache{$uri}={};
 5901: #	}
 5902:         if ($liburi) {
 5903: 	    $liburi=&declutter($liburi);
 5904:             $filename=$liburi;
 5905:         } else {
 5906: 	    &devalidate_cache_new('meta',$uri);
 5907: 	    undef(%metaentry);
 5908: 	}
 5909:         my %metathesekeys=();
 5910:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5911: 	my $metastring;
 5912: 	if ($uri !~ m -^(editupload)/-) {
 5913: 	    my $file=&filelocation('',&clutter($filename));
 5914: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5915: 	    $metastring=&getfile($file);
 5916: 	}
 5917:         my $parser=HTML::LCParser->new(\$metastring);
 5918:         my $token;
 5919:         undef %metathesekeys;
 5920:         while ($token=$parser->get_token) {
 5921: 	    if ($token->[0] eq 'S') {
 5922: 		if (defined($token->[2]->{'package'})) {
 5923: #
 5924: # This is a package - get package info
 5925: #
 5926: 		    my $package=$token->[2]->{'package'};
 5927: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5928: 		    if (defined($token->[2]->{'id'})) { 
 5929: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5930: 		    }
 5931: 		    if ($metaentry{':packages'}) {
 5932: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5933: 		    } else {
 5934: 			$metaentry{':packages'}=$package.$keyroot;
 5935: 		    }
 5936: 		    foreach my $pack_entry (keys(%packagetab)) {
 5937: 			my $part=$keyroot;
 5938: 			$part=~s/^\_//;
 5939: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 5940: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 5941: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 5942: 			    # ignore package.tab specified default values
 5943:                             # here &package_tab_default() will fetch those
 5944: 			    if ($subp eq 'default') { next; }
 5945: 			    my $value=$packagetab{$pack_entry};
 5946: 			    my $unikey;
 5947: 			    if ($pack =~ /_0$/) {
 5948: 				$unikey='parameter_0_'.$name;
 5949: 				$part=0;
 5950: 			    } else {
 5951: 				$unikey='parameter'.$keyroot.'_'.$name;
 5952: 			    }
 5953: 			    if ($subp eq 'display') {
 5954: 				$value.=' [Part: '.$part.']';
 5955: 			    }
 5956: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5957: 			    $metathesekeys{$unikey}=1;
 5958: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5959: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5960: 			    }
 5961: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5962: 				$metaentry{':'.$unikey}=
 5963: 				    $metaentry{':'.$unikey.'.default'};
 5964: 			    }
 5965: 			}
 5966: 		    }
 5967: 		} else {
 5968: #
 5969: # This is not a package - some other kind of start tag
 5970: #
 5971: 		    my $entry=$token->[1];
 5972: 		    my $unikey;
 5973: 		    if ($entry eq 'import') {
 5974: 			$unikey='';
 5975: 		    } else {
 5976: 			$unikey=$entry;
 5977: 		    }
 5978: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5979: 
 5980: 		    if (defined($token->[2]->{'id'})) { 
 5981: 			$unikey.='_'.$token->[2]->{'id'}; 
 5982: 		    }
 5983: 
 5984: 		    if ($entry eq 'import') {
 5985: #
 5986: # Importing a library here
 5987: #
 5988: 			if ($depthcount<20) {
 5989: 			    my $location=$parser->get_text('/import');
 5990: 			    my $dir=$filename;
 5991: 			    $dir=~s|[^/]*$||;
 5992: 			    $location=&filelocation($dir,$location);
 5993: 			    my $metadata = 
 5994: 				&metadata($uri,'keys', $location,$unikey,
 5995: 					  $depthcount+1);
 5996: 			    foreach my $meta (split(',',$metadata)) {
 5997: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 5998: 				$metathesekeys{$meta}=1;
 5999: 			    }
 6000: 			}
 6001: 		    } else { 
 6002: 			
 6003: 			if (defined($token->[2]->{'name'})) { 
 6004: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6005: 			}
 6006: 			$metathesekeys{$unikey}=1;
 6007: 			foreach my $param (@{$token->[3]}) {
 6008: 			    $metaentry{':'.$unikey.'.'.$param} =
 6009: 				$token->[2]->{$param};
 6010: 			}
 6011: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6012: 			my $default=$metaentry{':'.$unikey.'.default'};
 6013: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6014: 		 # only ws inside the tag, and not in default, so use default
 6015: 		 # as value
 6016: 			    $metaentry{':'.$unikey}=$default;
 6017: 			} else {
 6018: 		  # either something interesting inside the tag or default
 6019:                   # uninteresting
 6020: 			    $metaentry{':'.$unikey}=$internaltext;
 6021: 			}
 6022: # end of not-a-package not-a-library import
 6023: 		    }
 6024: # end of not-a-package start tag
 6025: 		}
 6026: # the next is the end of "start tag"
 6027: 	    }
 6028: 	}
 6029: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6030: 	foreach my $key (keys(%packagetab)) {
 6031: 	    #no specific packages #how's our extension
 6032: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6033: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6034: 					 \%metathesekeys);
 6035: 	}
 6036: 	if (!exists($metaentry{':packages'})) {
 6037: 	    foreach my $key (keys(%packagetab)) {
 6038: 		#no specific packages well let's get default then
 6039: 		if ($key!~/^default&/) { next; }
 6040: 		&metadata_create_package_def($uri,$key,'default',
 6041: 					     \%metathesekeys);
 6042: 	    }
 6043: 	}
 6044: # are there custom rights to evaluate
 6045: 	if ($metaentry{':copyright'} eq 'custom') {
 6046: 
 6047:     #
 6048:     # Importing a rights file here
 6049:     #
 6050: 	    unless ($depthcount) {
 6051: 		my $location=$metaentry{':customdistributionfile'};
 6052: 		my $dir=$filename;
 6053: 		$dir=~s|[^/]*$||;
 6054: 		$location=&filelocation($dir,$location);
 6055: 		my $rights_metadata =
 6056: 		    &metadata($uri,'keys',$location,'_rights',
 6057: 			      $depthcount+1);
 6058: 		foreach my $rights (split(',',$rights_metadata)) {
 6059: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6060: 		    $metathesekeys{$rights}=1;
 6061: 		}
 6062: 	    }
 6063: 	}
 6064: 	# uniqifiy package listing
 6065: 	my %seen;
 6066: 	my @uniq_packages =
 6067: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6068: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6069: 
 6070: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6071: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6072: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6073: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6074: # this is the end of "was not already recently cached
 6075:     }
 6076:     return $metaentry{':'.$what};
 6077: }
 6078: 
 6079: sub metadata_create_package_def {
 6080:     my ($uri,$key,$package,$metathesekeys)=@_;
 6081:     my ($pack,$name,$subp)=split(/\&/,$key);
 6082:     if ($subp eq 'default') { next; }
 6083:     
 6084:     if (defined($metaentry{':packages'})) {
 6085: 	$metaentry{':packages'}.=','.$package;
 6086:     } else {
 6087: 	$metaentry{':packages'}=$package;
 6088:     }
 6089:     my $value=$packagetab{$key};
 6090:     my $unikey;
 6091:     $unikey='parameter_0_'.$name;
 6092:     $metaentry{':'.$unikey.'.part'}=0;
 6093:     $$metathesekeys{$unikey}=1;
 6094:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6095: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6096:     }
 6097:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6098: 	$metaentry{':'.$unikey}=
 6099: 	    $metaentry{':'.$unikey.'.default'};
 6100:     }
 6101: }
 6102: 
 6103: sub metadata_generate_part0 {
 6104:     my ($metadata,$metacache,$uri) = @_;
 6105:     my %allnames;
 6106:     foreach my $metakey (keys(%$metadata)) {
 6107: 	if ($metakey=~/^parameter\_(.*)/) {
 6108: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6109: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6110: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6111: 	    $allnames{$name}=$part;
 6112: 	  }
 6113: 	}
 6114:     }
 6115:     foreach my $name (keys(%allnames)) {
 6116:       $$metadata{"parameter_0_$name"}=1;
 6117:       my $key=":parameter_0_$name";
 6118:       $$metacache{"$key.part"}='0';
 6119:       $$metacache{"$key.name"}=$name;
 6120:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6121: 					   $allnames{$name}.'_'.$name.
 6122: 					   '.type'};
 6123:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6124: 			     '.display'};
 6125:       my $expr='[Part: '.$allnames{$name}.']';
 6126:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6127:       $$metacache{"$key.display"}=$olddis;
 6128:     }
 6129: }
 6130: 
 6131: # ------------------------------------------------------ Devalidate title cache
 6132: 
 6133: sub devalidate_title_cache {
 6134:     my ($url)=@_;
 6135:     if (!$env{'request.course.id'}) { return; }
 6136:     my $symb=&symbread($url);
 6137:     if (!$symb) { return; }
 6138:     my $key=$env{'request.course.id'}."\0".$symb;
 6139:     &devalidate_cache_new('title',$key);
 6140: }
 6141: 
 6142: # ------------------------------------------------- Get the title of a resource
 6143: 
 6144: sub gettitle {
 6145:     my $urlsymb=shift;
 6146:     my $symb=&symbread($urlsymb);
 6147:     if ($symb) {
 6148: 	my $key=$env{'request.course.id'}."\0".$symb;
 6149: 	my ($result,$cached)=&is_cached_new('title',$key);
 6150: 	if (defined($cached)) { 
 6151: 	    return $result;
 6152: 	}
 6153: 	my ($map,$resid,$url)=&decode_symb($symb);
 6154: 	my $title='';
 6155: 	my %bighash;
 6156: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6157: 		&GDBM_READER(),0640)) {
 6158: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6159: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6160: 	    untie %bighash;
 6161: 	}
 6162: 	$title=~s/\&colon\;/\:/gs;
 6163: 	if ($title) {
 6164: 	    return &do_cache_new('title',$key,$title,600);
 6165: 	}
 6166: 	$urlsymb=$url;
 6167:     }
 6168:     my $title=&metadata($urlsymb,'title');
 6169:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6170:     return $title;
 6171: }
 6172: 
 6173: sub get_slot {
 6174:     my ($which,$cnum,$cdom)=@_;
 6175:     if (!$cnum || !$cdom) {
 6176: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 6177: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6178: 	$cnum=$env{'course.'.$courseid.'.num'};
 6179:     }
 6180:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6181:     my %slotinfo;
 6182:     if (exists($remembered{$key})) {
 6183: 	$slotinfo{$which} = $remembered{$key};
 6184:     } else {
 6185: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6186: 	&Apache::lonhomework::showhash(%slotinfo);
 6187: 	my ($tmp)=keys(%slotinfo);
 6188: 	if ($tmp=~/^error:/) { return (); }
 6189: 	$remembered{$key} = $slotinfo{$which};
 6190:     }
 6191:     if (ref($slotinfo{$which}) eq 'HASH') {
 6192: 	return %{$slotinfo{$which}};
 6193:     }
 6194:     return $slotinfo{$which};
 6195: }
 6196: # ------------------------------------------------- Update symbolic store links
 6197: 
 6198: sub symblist {
 6199:     my ($mapname,%newhash)=@_;
 6200:     $mapname=&deversion(&declutter($mapname));
 6201:     my %hash;
 6202:     if (($env{'request.course.fn'}) && (%newhash)) {
 6203:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6204:                       &GDBM_WRCREAT(),0640)) {
 6205: 	    foreach my $url (keys %newhash) {
 6206: 		next if ($url eq 'last_known'
 6207: 			 && $env{'form.no_update_last_known'});
 6208: 		$hash{declutter($url)}=&encode_symb($mapname,
 6209: 						    $newhash{$url}->[1],
 6210: 						    $newhash{$url}->[0]);
 6211:             }
 6212:             if (untie(%hash)) {
 6213: 		return 'ok';
 6214:             }
 6215:         }
 6216:     }
 6217:     return 'error';
 6218: }
 6219: 
 6220: # --------------------------------------------------------------- Verify a symb
 6221: 
 6222: sub symbverify {
 6223:     my ($symb,$thisurl)=@_;
 6224:     my $thisfn=$thisurl;
 6225: # wrapper not part of symbs
 6226:     $thisfn=~s/^\/adm\/wrapper//;
 6227:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 6228:     $thisfn=&declutter($thisfn);
 6229: # direct jump to resource in page or to a sequence - will construct own symbs
 6230:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6231: # check URL part
 6232:     my ($map,$resid,$url)=&decode_symb($symb);
 6233: 
 6234:     unless ($url eq $thisfn) { return 0; }
 6235: 
 6236:     $symb=&symbclean($symb);
 6237:     $thisurl=&deversion($thisurl);
 6238:     $thisfn=&deversion($thisfn);
 6239: 
 6240:     my %bighash;
 6241:     my $okay=0;
 6242: 
 6243:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6244:                             &GDBM_READER(),0640)) {
 6245:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6246:         unless ($ids) { 
 6247:            $ids=$bighash{'ids_/'.$thisurl};
 6248:         }
 6249:         if ($ids) {
 6250: # ------------------------------------------------------------------- Has ID(s)
 6251: 	    foreach (split(/\,/,$ids)) {
 6252: 	       my ($mapid,$resid)=split(/\./,$_);
 6253:                if (
 6254:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6255:    eq $symb) { 
 6256: 		   if (($env{'request.role.adv'}) ||
 6257: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 6258: 		       $okay=1; 
 6259: 		   }
 6260: 	       }
 6261: 	   }
 6262:         }
 6263: 	untie(%bighash);
 6264:     }
 6265:     return $okay;
 6266: }
 6267: 
 6268: # --------------------------------------------------------------- Clean-up symb
 6269: 
 6270: sub symbclean {
 6271:     my $symb=shift;
 6272:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6273: # remove version from map
 6274:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6275: 
 6276: # remove version from URL
 6277:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6278: 
 6279: # remove wrapper
 6280: 
 6281:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6282:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6283:     return $symb;
 6284: }
 6285: 
 6286: # ---------------------------------------------- Split symb to find map and url
 6287: 
 6288: sub encode_symb {
 6289:     my ($map,$resid,$url)=@_;
 6290:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6291: }
 6292: 
 6293: sub decode_symb {
 6294:     my $symb=shift;
 6295:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6296:     my ($map,$resid,$url)=split(/___/,$symb);
 6297:     return (&fixversion($map),$resid,&fixversion($url));
 6298: }
 6299: 
 6300: sub fixversion {
 6301:     my $fn=shift;
 6302:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6303:     my %bighash;
 6304:     my $uri=&clutter($fn);
 6305:     my $key=$env{'request.course.id'}.'_'.$uri;
 6306: # is this cached?
 6307:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6308:     if (defined($cached)) { return $result; }
 6309: # unfortunately not cached, or expired
 6310:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6311: 	    &GDBM_READER(),0640)) {
 6312:  	if ($bighash{'version_'.$uri}) {
 6313:  	    my $version=$bighash{'version_'.$uri};
 6314:  	    unless (($version eq 'mostrecent') || 
 6315: 		    ($version==&getversion($uri))) {
 6316:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6317:  	    }
 6318:  	}
 6319:  	untie %bighash;
 6320:     }
 6321:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6322: }
 6323: 
 6324: sub deversion {
 6325:     my $url=shift;
 6326:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6327:     return $url;
 6328: }
 6329: 
 6330: # ------------------------------------------------------ Return symb list entry
 6331: 
 6332: sub symbread {
 6333:     my ($thisfn,$donotrecurse)=@_;
 6334:     my $cache_str='request.symbread.cached.'.$thisfn;
 6335:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6336: # no filename provided? try from environment
 6337:     unless ($thisfn) {
 6338:         if ($env{'request.symb'}) {
 6339: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6340: 	}
 6341: 	$thisfn=$env{'request.filename'};
 6342:     }
 6343:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6344: # is that filename actually a symb? Verify, clean, and return
 6345:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6346: 	if (&symbverify($thisfn,$1)) {
 6347: 	    return $env{$cache_str}=&symbclean($thisfn);
 6348: 	}
 6349:     }
 6350:     $thisfn=declutter($thisfn);
 6351:     my %hash;
 6352:     my %bighash;
 6353:     my $syval='';
 6354:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6355:         my $targetfn = $thisfn;
 6356:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6357:             $targetfn = 'adm/wrapper/'.$thisfn;
 6358:         }
 6359: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6360: 	    $targetfn=$1;
 6361: 	}
 6362:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6363:                       &GDBM_READER(),0640)) {
 6364: 	    $syval=$hash{$targetfn};
 6365:             untie(%hash);
 6366:         }
 6367: # ---------------------------------------------------------- There was an entry
 6368:         if ($syval) {
 6369: 	    #unless ($syval=~/\_\d+$/) {
 6370: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6371: 		    #&appenv('request.ambiguous' => $thisfn);
 6372: 		    #return $env{$cache_str}='';
 6373: 		#}    
 6374: 		#$syval.=$1;
 6375: 	    #}
 6376:         } else {
 6377: # ------------------------------------------------------- Was not in symb table
 6378:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6379:                             &GDBM_READER(),0640)) {
 6380: # ---------------------------------------------- Get ID(s) for current resource
 6381:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6382:               unless ($ids) { 
 6383:                  $ids=$bighash{'ids_/'.$thisfn};
 6384:               }
 6385:               unless ($ids) {
 6386: # alias?
 6387: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6388:               }
 6389:               if ($ids) {
 6390: # ------------------------------------------------------------------- Has ID(s)
 6391:                  my @possibilities=split(/\,/,$ids);
 6392:                  if ($#possibilities==0) {
 6393: # ----------------------------------------------- There is only one possibility
 6394: 		     my ($mapid,$resid)=split(/\./,$ids);
 6395: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6396: 						    $resid,$thisfn);
 6397:                  } elsif (!$donotrecurse) {
 6398: # ------------------------------------------ There is more than one possibility
 6399:                      my $realpossible=0;
 6400:                      foreach (@possibilities) {
 6401: 			 my $file=$bighash{'src_'.$_};
 6402:                          if (&allowed('bre',$file)) {
 6403:          		    my ($mapid,$resid)=split(/\./,$_);
 6404:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6405: 				$realpossible++;
 6406:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6407: 						    $resid,$thisfn);
 6408:                             }
 6409: 			 }
 6410:                      }
 6411: 		     if ($realpossible!=1) { $syval=''; }
 6412:                  } else {
 6413:                      $syval='';
 6414:                  }
 6415: 	      }
 6416:               untie(%bighash)
 6417:            }
 6418:         }
 6419:         if ($syval) {
 6420: 	    return $env{$cache_str}=$syval;
 6421:         }
 6422:     }
 6423:     &appenv('request.ambiguous' => $thisfn);
 6424:     return $env{$cache_str}='';
 6425: }
 6426: 
 6427: # ---------------------------------------------------------- Return random seed
 6428: 
 6429: sub numval {
 6430:     my $txt=shift;
 6431:     $txt=~tr/A-J/0-9/;
 6432:     $txt=~tr/a-j/0-9/;
 6433:     $txt=~tr/K-T/0-9/;
 6434:     $txt=~tr/k-t/0-9/;
 6435:     $txt=~tr/U-Z/0-5/;
 6436:     $txt=~tr/u-z/0-5/;
 6437:     $txt=~s/\D//g;
 6438:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6439:     return int($txt);
 6440: }
 6441: 
 6442: sub numval2 {
 6443:     my $txt=shift;
 6444:     $txt=~tr/A-J/0-9/;
 6445:     $txt=~tr/a-j/0-9/;
 6446:     $txt=~tr/K-T/0-9/;
 6447:     $txt=~tr/k-t/0-9/;
 6448:     $txt=~tr/U-Z/0-5/;
 6449:     $txt=~tr/u-z/0-5/;
 6450:     $txt=~s/\D//g;
 6451:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6452:     my $total;
 6453:     foreach my $val (@txts) { $total+=$val; }
 6454:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6455:     return int($total);
 6456: }
 6457: 
 6458: sub numval3 {
 6459:     use integer;
 6460:     my $txt=shift;
 6461:     $txt=~tr/A-J/0-9/;
 6462:     $txt=~tr/a-j/0-9/;
 6463:     $txt=~tr/K-T/0-9/;
 6464:     $txt=~tr/k-t/0-9/;
 6465:     $txt=~tr/U-Z/0-5/;
 6466:     $txt=~tr/u-z/0-5/;
 6467:     $txt=~s/\D//g;
 6468:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6469:     my $total;
 6470:     foreach my $val (@txts) { $total+=$val; }
 6471:     if ($_64bit) { $total=(($total<<32)>>32); }
 6472:     return $total;
 6473: }
 6474: 
 6475: sub digest {
 6476:     my ($data)=@_;
 6477:     my $digest=&Digest::MD5::md5($data);
 6478:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6479:     my ($e,$f);
 6480:     {
 6481:         use integer;
 6482:         $e=($a+$b);
 6483:         $f=($c+$d);
 6484:         if ($_64bit) {
 6485:             $e=(($e<<32)>>32);
 6486:             $f=(($f<<32)>>32);
 6487:         }
 6488:     }
 6489:     if (wantarray) {
 6490: 	return ($e,$f);
 6491:     } else {
 6492: 	my $g;
 6493: 	{
 6494: 	    use integer;
 6495: 	    $g=($e+$f);
 6496: 	    if ($_64bit) {
 6497: 		$g=(($g<<32)>>32);
 6498: 	    }
 6499: 	}
 6500: 	return $g;
 6501:     }
 6502: }
 6503: 
 6504: sub latest_rnd_algorithm_id {
 6505:     return '64bit5';
 6506: }
 6507: 
 6508: sub get_rand_alg {
 6509:     my ($courseid)=@_;
 6510:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 6511:     if ($courseid) {
 6512: 	return $env{"course.$courseid.rndseed"};
 6513:     }
 6514:     return &latest_rnd_algorithm_id();
 6515: }
 6516: 
 6517: sub validCODE {
 6518:     my ($CODE)=@_;
 6519:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6520:     return 0;
 6521: }
 6522: 
 6523: sub getCODE {
 6524:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6525:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6526: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6527: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6528: 	return $Apache::lonhomework::history{'resource.CODE'};
 6529:     }
 6530:     return undef;
 6531: }
 6532: 
 6533: sub rndseed {
 6534:     my ($symb,$courseid,$domain,$username)=@_;
 6535: 
 6536:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 6537:     if (!$symb) {
 6538: 	unless ($symb=$wsymb) { return time; }
 6539:     }
 6540:     if (!$courseid) { $courseid=$wcourseid; }
 6541:     if (!$domain) { $domain=$wdomain; }
 6542:     if (!$username) { $username=$wusername }
 6543:     my $which=&get_rand_alg();
 6544:     if (defined(&getCODE())) {
 6545: 	if ($which eq '64bit5') {
 6546: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6547: 	} elsif ($which eq '64bit4') {
 6548: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6549: 	} else {
 6550: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6551: 	}
 6552:     } elsif ($which eq '64bit5') {
 6553: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6554:     } elsif ($which eq '64bit4') {
 6555: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6556:     } elsif ($which eq '64bit3') {
 6557: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6558:     } elsif ($which eq '64bit2') {
 6559: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6560:     } elsif ($which eq '64bit') {
 6561: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6562:     }
 6563:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6564: }
 6565: 
 6566: sub rndseed_32bit {
 6567:     my ($symb,$courseid,$domain,$username)=@_;
 6568:     {
 6569: 	use integer;
 6570: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6571: 	my $symbseed=numval($symb) << 22;
 6572: 	my $namechck=unpack("%32C*",$username) << 17;
 6573: 	my $nameseed=numval($username) << 12;
 6574: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6575: 	my $courseseed=unpack("%32C*",$courseid);
 6576: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6577: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6578: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6579: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6580: 	return $num;
 6581:     }
 6582: }
 6583: 
 6584: sub rndseed_64bit {
 6585:     my ($symb,$courseid,$domain,$username)=@_;
 6586:     {
 6587: 	use integer;
 6588: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6589: 	my $symbseed=numval($symb) << 10;
 6590: 	my $namechck=unpack("%32S*",$username);
 6591: 	
 6592: 	my $nameseed=numval($username) << 21;
 6593: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6594: 	my $courseseed=unpack("%32S*",$courseid);
 6595: 	
 6596: 	my $num1=$symbchck+$symbseed+$namechck;
 6597: 	my $num2=$nameseed+$domainseed+$courseseed;
 6598: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6599: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6600: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6601: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6602: 	return "$num1,$num2";
 6603:     }
 6604: }
 6605: 
 6606: sub rndseed_64bit2 {
 6607:     my ($symb,$courseid,$domain,$username)=@_;
 6608:     {
 6609: 	use integer;
 6610: 	# strings need to be an even # of cahracters long, it it is odd the
 6611:         # last characters gets thrown away
 6612: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6613: 	my $symbseed=numval($symb) << 10;
 6614: 	my $namechck=unpack("%32S*",$username.' ');
 6615: 	
 6616: 	my $nameseed=numval($username) << 21;
 6617: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6618: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6619: 	
 6620: 	my $num1=$symbchck+$symbseed+$namechck;
 6621: 	my $num2=$nameseed+$domainseed+$courseseed;
 6622: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6623: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6624: 	return "$num1,$num2";
 6625:     }
 6626: }
 6627: 
 6628: sub rndseed_64bit3 {
 6629:     my ($symb,$courseid,$domain,$username)=@_;
 6630:     {
 6631: 	use integer;
 6632: 	# strings need to be an even # of cahracters long, it it is odd the
 6633:         # last characters gets thrown away
 6634: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6635: 	my $symbseed=numval2($symb) << 10;
 6636: 	my $namechck=unpack("%32S*",$username.' ');
 6637: 	
 6638: 	my $nameseed=numval2($username) << 21;
 6639: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6640: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6641: 	
 6642: 	my $num1=$symbchck+$symbseed+$namechck;
 6643: 	my $num2=$nameseed+$domainseed+$courseseed;
 6644: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6645: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6646: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6647: 	
 6648: 	return "$num1:$num2";
 6649:     }
 6650: }
 6651: 
 6652: sub rndseed_64bit4 {
 6653:     my ($symb,$courseid,$domain,$username)=@_;
 6654:     {
 6655: 	use integer;
 6656: 	# strings need to be an even # of cahracters long, it it is odd the
 6657:         # last characters gets thrown away
 6658: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6659: 	my $symbseed=numval3($symb) << 10;
 6660: 	my $namechck=unpack("%32S*",$username.' ');
 6661: 	
 6662: 	my $nameseed=numval3($username) << 21;
 6663: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6664: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6665: 	
 6666: 	my $num1=$symbchck+$symbseed+$namechck;
 6667: 	my $num2=$nameseed+$domainseed+$courseseed;
 6668: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6669: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6670: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6671: 	
 6672: 	return "$num1:$num2";
 6673:     }
 6674: }
 6675: 
 6676: sub rndseed_64bit5 {
 6677:     my ($symb,$courseid,$domain,$username)=@_;
 6678:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6679:     return "$num1:$num2";
 6680: }
 6681: 
 6682: sub rndseed_CODE_64bit {
 6683:     my ($symb,$courseid,$domain,$username)=@_;
 6684:     {
 6685: 	use integer;
 6686: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6687: 	my $symbseed=numval2($symb);
 6688: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6689: 	my $CODEseed=numval(&getCODE());
 6690: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6691: 	my $num1=$symbseed+$CODEchck;
 6692: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6693: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6694: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6695: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6696: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6697: 	return "$num1:$num2";
 6698:     }
 6699: }
 6700: 
 6701: sub rndseed_CODE_64bit4 {
 6702:     my ($symb,$courseid,$domain,$username)=@_;
 6703:     {
 6704: 	use integer;
 6705: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6706: 	my $symbseed=numval3($symb);
 6707: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6708: 	my $CODEseed=numval3(&getCODE());
 6709: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6710: 	my $num1=$symbseed+$CODEchck;
 6711: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6712: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6713: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6714: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6715: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6716: 	return "$num1:$num2";
 6717:     }
 6718: }
 6719: 
 6720: sub rndseed_CODE_64bit5 {
 6721:     my ($symb,$courseid,$domain,$username)=@_;
 6722:     my $code = &getCODE();
 6723:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6724:     return "$num1:$num2";
 6725: }
 6726: 
 6727: sub setup_random_from_rndseed {
 6728:     my ($rndseed)=@_;
 6729:     if ($rndseed =~/([,:])/) {
 6730: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6731: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6732:     } else {
 6733: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6734:     }
 6735: }
 6736: 
 6737: sub latest_receipt_algorithm_id {
 6738:     return 'receipt2';
 6739: }
 6740: 
 6741: sub recunique {
 6742:     my $fucourseid=shift;
 6743:     my $unique;
 6744:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6745: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6746:     } else {
 6747: 	$unique=$perlvar{'lonReceipt'};
 6748:     }
 6749:     return unpack("%32C*",$unique);
 6750: }
 6751: 
 6752: sub recprefix {
 6753:     my $fucourseid=shift;
 6754:     my $prefix;
 6755:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6756: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6757:     } else {
 6758: 	$prefix=$perlvar{'lonHostID'};
 6759:     }
 6760:     return unpack("%32C*",$prefix);
 6761: }
 6762: 
 6763: sub ireceipt {
 6764:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6765:     my $cuname=unpack("%32C*",$funame);
 6766:     my $cudom=unpack("%32C*",$fudom);
 6767:     my $cucourseid=unpack("%32C*",$fucourseid);
 6768:     my $cusymb=unpack("%32C*",$fusymb);
 6769:     my $cunique=&recunique($fucourseid);
 6770:     my $cpart=unpack("%32S*",$part);
 6771:     my $return =&recprefix($fucourseid).'-';
 6772:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6773: 	$env{'request.state'} eq 'construct') {
 6774: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6775: 			       " and ".($cpart%$cudom));
 6776: 			       
 6777: 	$return.= ($cunique%$cuname+
 6778: 		   $cunique%$cudom+
 6779: 		   $cusymb%$cuname+
 6780: 		   $cusymb%$cudom+
 6781: 		   $cucourseid%$cuname+
 6782: 		   $cucourseid%$cudom+
 6783: 		   $cpart%$cuname+
 6784: 		   $cpart%$cudom);
 6785:     } else {
 6786: 	$return.= ($cunique%$cuname+
 6787: 		   $cunique%$cudom+
 6788: 		   $cusymb%$cuname+
 6789: 		   $cusymb%$cudom+
 6790: 		   $cucourseid%$cuname+
 6791: 		   $cucourseid%$cudom);
 6792:     }
 6793:     return $return;
 6794: }
 6795: 
 6796: sub receipt {
 6797:     my ($part)=@_;
 6798:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6799:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6800: }
 6801: 
 6802: # ------------------------------------------------------------ Serves up a file
 6803: # returns either the contents of the file or 
 6804: # -1 if the file doesn't exist
 6805: #
 6806: # if the target is a file that was uploaded via DOCS, 
 6807: # a check will be made to see if a current copy exists on the local server,
 6808: # if it does this will be served, otherwise a copy will be retrieved from
 6809: # the home server for the course and stored in /home/httpd/html/userfiles on
 6810: # the local server.   
 6811: 
 6812: sub getfile {
 6813:     my ($file) = @_;
 6814:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6815:     &repcopy($file);
 6816:     return &readfile($file);
 6817: }
 6818: 
 6819: sub repcopy_userfile {
 6820:     my ($file)=@_;
 6821:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6822:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6823:     my ($cdom,$cnum,$filename) = 
 6824: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6825:     my ($info,$rtncode);
 6826:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6827:     if (-e "$file") {
 6828: 	my @fileinfo = stat($file);
 6829: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6830: 	if ($lwpresp ne 'ok') {
 6831: 	    if ($rtncode eq '404') {
 6832: 		unlink($file);
 6833: 	    }
 6834: 	    #my $ua=new LWP::UserAgent;
 6835: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6836: 	    #my $response=$ua->request($request);
 6837: 	    #if ($response->is_success()) {
 6838: 	#	return $response->content;
 6839: 	#    } else {
 6840: 	#	return -1;
 6841: 	#    }
 6842: 	    return -1;
 6843: 	}
 6844: 	if ($info < $fileinfo[9]) {
 6845: 	    return 'ok';
 6846: 	}
 6847: 	$info = '';
 6848: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6849: 	if ($lwpresp ne 'ok') {
 6850: 	    return -1;
 6851: 	}
 6852:     } else {
 6853: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6854: 	if ($lwpresp ne 'ok') {
 6855: 	    my $ua=new LWP::UserAgent;
 6856: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6857: 	    my $response=$ua->request($request);
 6858: 	    if ($response->is_success()) {
 6859: 		$info=$response->content;
 6860: 	    } else {
 6861: 		return -1;
 6862: 	    }
 6863: 	}
 6864: 	my @parts = ($cdom,$cnum); 
 6865: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6866: 	    push @parts, split(/\//,$1);
 6867: 	}
 6868: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6869: 	foreach my $part (@parts) {
 6870: 	    $path .= '/'.$part;
 6871: 	    if (!-e $path) {
 6872: 		mkdir($path,0770);
 6873: 	    }
 6874: 	}
 6875:     }
 6876:     open(FILE,">$file");
 6877:     print FILE $info;
 6878:     close(FILE);
 6879:     return 'ok';
 6880: }
 6881: 
 6882: sub tokenwrapper {
 6883:     my $uri=shift;
 6884:     $uri=~s|^http\://([^/]+)||;
 6885:     $uri=~s|^/||;
 6886:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6887:     my $token=$1;
 6888:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6889:     if ($udom && $uname && $file) {
 6890: 	$file=~s|(\?\.*)*$||;
 6891:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6892:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6893:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6894:                                '&tokenissued='.$perlvar{'lonHostID'};
 6895:     } else {
 6896:         return '/adm/notfound.html';
 6897:     }
 6898: }
 6899: 
 6900: sub getuploaded {
 6901:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6902:     $uri=~s/^\///;
 6903:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6904:     my $ua=new LWP::UserAgent;
 6905:     my $request=new HTTP::Request($reqtype,$uri);
 6906:     my $response=$ua->request($request);
 6907:     $$rtncode = $response->code;
 6908:     if (! $response->is_success()) {
 6909: 	return 'failed';
 6910:     }      
 6911:     if ($reqtype eq 'HEAD') {
 6912: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6913:     } elsif ($reqtype eq 'GET') {
 6914: 	$$info = $response->content;
 6915:     }
 6916:     return 'ok';
 6917: }
 6918: 
 6919: sub readfile {
 6920:     my $file = shift;
 6921:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6922:     my $fh;
 6923:     open($fh,"<$file");
 6924:     my $a='';
 6925:     while (<$fh>) { $a .=$_; }
 6926:     return $a;
 6927: }
 6928: 
 6929: sub filelocation {
 6930:     my ($dir,$file) = @_;
 6931:     my $location;
 6932:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6933: 
 6934:     if ($file =~ m-^/adm/-) {
 6935: 	$file=~s-^/adm/wrapper/-/-;
 6936: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6937:     }
 6938:     if ($file=~m:^/~:) { # is a contruction space reference
 6939:         $location = $file;
 6940:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6941:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6942: 	# is a correct contruction space reference
 6943:         $location = $file;
 6944:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6945:         my ($udom,$uname,$filename)=
 6946:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6947:         my $home=&homeserver($uname,$udom);
 6948:         my $is_me=0;
 6949:         my @ids=&current_machine_ids();
 6950:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6951:         if ($is_me) {
 6952:   	    $location=&propath($udom,$uname).
 6953:   	      '/userfiles/'.$filename;
 6954:         } else {
 6955:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6956:   	      $udom.'/'.$uname.'/'.$filename;
 6957:         }
 6958:     } else {
 6959:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6960:         $file=~s:^/res/:/:;
 6961:         if ( !( $file =~ m:^/:) ) {
 6962:             $location = $dir. '/'.$file;
 6963:         } else {
 6964:             $location = '/home/httpd/html/res'.$file;
 6965:         }
 6966:     }
 6967:     $location=~s://+:/:g; # remove duplicate /
 6968:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6969:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6970:     return $location;
 6971: }
 6972: 
 6973: sub hreflocation {
 6974:     my ($dir,$file)=@_;
 6975:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6976: 	$file=filelocation($dir,$file);
 6977:     } elsif ($file=~m-^/adm/-) {
 6978: 	$file=~s-^/adm/wrapper/-/-;
 6979: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6980:     }
 6981:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6982: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6983:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6984: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6985:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6986: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6987: 	    -/uploaded/$1/$2/-x;
 6988:     }
 6989:     return $file;
 6990: }
 6991: 
 6992: sub current_machine_domains {
 6993:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6994:     my @domains;
 6995:     while( my($id, $name) = each(%hostname)) {
 6996: #	&logthis("-$id-$name-$hostname-");
 6997: 	if ($hostname eq $name) {
 6998: 	    push(@domains,$hostdom{$id});
 6999: 	}
 7000:     }
 7001:     return @domains;
 7002: }
 7003: 
 7004: sub current_machine_ids {
 7005:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7006:     my @ids;
 7007:     while( my($id, $name) = each(%hostname)) {
 7008: #	&logthis("-$id-$name-$hostname-");
 7009: 	if ($hostname eq $name) {
 7010: 	    push(@ids,$id);
 7011: 	}
 7012:     }
 7013:     return @ids;
 7014: }
 7015: 
 7016: # ------------------------------------------------------------- Declutters URLs
 7017: 
 7018: sub declutter {
 7019:     my $thisfn=shift;
 7020:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7021:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7022:     $thisfn=~s/^\///;
 7023:     $thisfn=~s|^adm/wrapper/||;
 7024:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7025:     $thisfn=~s/^res\///;
 7026:     $thisfn=~s/\?.+$//;
 7027:     return $thisfn;
 7028: }
 7029: 
 7030: # ------------------------------------------------------------- Clutter up URLs
 7031: 
 7032: sub clutter {
 7033:     my $thisfn='/'.&declutter(shift);
 7034:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7035:        $thisfn='/res'.$thisfn; 
 7036:     }
 7037:     if ($thisfn !~m|/adm|) {
 7038: 	if ($thisfn =~ m|/ext/|) {
 7039: 	    $thisfn='/adm/wrapper'.$thisfn;
 7040: 	} else {
 7041: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7042: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7043: 	    if ($embstyle eq 'ssi'
 7044: 		|| ($embstyle eq 'hdn')
 7045: 		|| ($embstyle eq 'rat')
 7046: 		|| ($embstyle eq 'prv')
 7047: 		|| ($embstyle eq 'ign')) {
 7048: 		#do nothing with these
 7049: 	    } elsif (($embstyle eq 'img') 
 7050: 		|| ($embstyle eq 'emb')
 7051: 		|| ($embstyle eq 'wrp')) {
 7052: 		$thisfn='/adm/wrapper'.$thisfn;
 7053: 	    } elsif ($embstyle eq 'unk'
 7054: 		     && $thisfn!~/\.(sequence|page)$/) {
 7055: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7056: 	    } else {
 7057: #		&logthis("Got a blank emb style");
 7058: 	    }
 7059: 	}
 7060:     }
 7061:     return $thisfn;
 7062: }
 7063: 
 7064: sub freeze_escape {
 7065:     my ($value)=@_;
 7066:     if (ref($value)) {
 7067: 	$value=&nfreeze($value);
 7068: 	return '__FROZEN__'.&escape($value);
 7069:     }
 7070:     return &escape($value);
 7071: }
 7072: 
 7073: 
 7074: sub thaw_unescape {
 7075:     my ($value)=@_;
 7076:     if ($value =~ /^__FROZEN__/) {
 7077: 	substr($value,0,10,undef);
 7078: 	$value=&unescape($value);
 7079: 	return &thaw($value);
 7080:     }
 7081:     return &unescape($value);
 7082: }
 7083: 
 7084: sub correct_line_ends {
 7085:     my ($result)=@_;
 7086:     $$result =~s/\r\n/\n/mg;
 7087:     $$result =~s/\r/\n/mg;
 7088: }
 7089: # ================================================================ Main Program
 7090: 
 7091: sub goodbye {
 7092:    &logthis("Starting Shut down");
 7093: #not converted to using infrastruture and probably shouldn't be
 7094:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7095: #converted
 7096: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7097:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7098: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7099: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7100: #1.1 only
 7101: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7102: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7103: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7104: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7105:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7106:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7107:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7108:    &flushcourselogs();
 7109:    &logthis("Shutting down");
 7110: }
 7111: 
 7112: BEGIN {
 7113: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7114:     unless ($readit) {
 7115: {
 7116:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 7117:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 7118: 
 7119:     while (my $configline=<$config>) {
 7120:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 7121: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 7122:            chomp($varvalue);
 7123:            $perlvar{$varname}=$varvalue;
 7124:         }
 7125:     }
 7126:     close($config);
 7127: }
 7128: {
 7129:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 7130: 
 7131:     while (my $configline=<$config>) {
 7132:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 7133: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 7134:            chomp($varvalue);
 7135:            $perlvar{$varname}=$varvalue;
 7136:         }
 7137:     }
 7138:     close($config);
 7139: }
 7140: 
 7141: # ------------------------------------------------------------ Read domain file
 7142: {
 7143:     %domaindescription = ();
 7144:     %domain_auth_def = ();
 7145:     %domain_auth_arg_def = ();
 7146:     my $fh;
 7147:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7148:        while (<$fh>) {
 7149:            next if (/^(\#|\s*$)/);
 7150: #           next if /^\#/;
 7151:            chomp;
 7152:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7153: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 7154: 	   $domain_auth_def{$domain}=$def_auth;
 7155:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7156: 	   $domaindescription{$domain}=$domain_description;
 7157: 	   $domain_lang_def{$domain}=$def_lang;
 7158: 	   $domain_city{$domain}=$city;
 7159: 	   $domain_longi{$domain}=$longi;
 7160: 	   $domain_lati{$domain}=$lati;
 7161:            $domain_primary{$domain}=$primary;
 7162: 
 7163:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7164: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7165: 	}
 7166:     }
 7167:     close ($fh);
 7168: }
 7169: 
 7170: 
 7171: # ------------------------------------------------------------- Read hosts file
 7172: {
 7173:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7174: 
 7175:     while (my $configline=<$config>) {
 7176:        next if ($configline =~ /^(\#|\s*$)/);
 7177:        chomp($configline);
 7178:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7179:        $name=~s/\s//g;
 7180:        if ($id && $domain && $role && $name) {
 7181: 	 $hostname{$id}=$name;
 7182: 	 $hostdom{$id}=$domain;
 7183: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7184:        }
 7185:     }
 7186:     close($config);
 7187:     # FIXME: dev server don't want this, production servers _do_ want this
 7188:     #&get_iphost();
 7189: }
 7190: 
 7191: sub get_iphost {
 7192:     if (%iphost) { return %iphost; }
 7193:     my %name_to_ip;
 7194:     foreach my $id (keys(%hostname)) {
 7195: 	my $name=$hostname{$id};
 7196: 	my $ip;
 7197: 	if (!exists($name_to_ip{$name})) {
 7198: 	    $ip = gethostbyname($name);
 7199: 	    if (!$ip || length($ip) ne 4) {
 7200: 		&logthis("Skipping host $id name $name no IP found\n");
 7201: 		next;
 7202: 	    }
 7203: 	    $ip=inet_ntoa($ip);
 7204: 	    $name_to_ip{$name} = $ip;
 7205: 	} else {
 7206: 	    $ip = $name_to_ip{$name};
 7207: 	}
 7208: 	push(@{$iphost{$ip}},$id);
 7209:     }
 7210:     return %iphost;
 7211: }
 7212: 
 7213: # ------------------------------------------------------ Read spare server file
 7214: {
 7215:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7216: 
 7217:     while (my $configline=<$config>) {
 7218:        chomp($configline);
 7219:        if ($configline) {
 7220:           $spareid{$configline}=1;
 7221:        }
 7222:     }
 7223:     close($config);
 7224: }
 7225: # ------------------------------------------------------------ Read permissions
 7226: {
 7227:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7228: 
 7229:     while (my $configline=<$config>) {
 7230: 	chomp($configline);
 7231: 	if ($configline) {
 7232: 	    my ($role,$perm)=split(/ /,$configline);
 7233: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7234: 	}
 7235:     }
 7236:     close($config);
 7237: }
 7238: 
 7239: # -------------------------------------------- Read plain texts for permissions
 7240: {
 7241:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7242: 
 7243:     while (my $configline=<$config>) {
 7244: 	chomp($configline);
 7245: 	if ($configline) {
 7246: 	    my ($short,@plain)=split(/:/,$configline);
 7247:             %{$prp{$short}} = ();
 7248: 	    if (@plain > 0) {
 7249:                 $prp{$short}{'std'} = $plain[0];
 7250:                 for (my $i=1; $i<@plain; $i++) {
 7251:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7252:                 }
 7253:             }
 7254: 	}
 7255:     }
 7256:     close($config);
 7257: }
 7258: 
 7259: # ---------------------------------------------------------- Read package table
 7260: {
 7261:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7262: 
 7263:     while (my $configline=<$config>) {
 7264: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7265: 	chomp($configline);
 7266: 	my ($short,$plain)=split(/:/,$configline);
 7267: 	my ($pack,$name)=split(/\&/,$short);
 7268: 	if ($plain ne '') {
 7269: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7270: 	    $packagetab{$short}=$plain; 
 7271: 	}
 7272:     }
 7273:     close($config);
 7274: }
 7275: 
 7276: # ------------- set up temporary directory
 7277: {
 7278:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7279: 
 7280: }
 7281: 
 7282: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 7283: 
 7284: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7285: $dumpcount=0;
 7286: 
 7287: &logtouch();
 7288: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7289: $readit=1;
 7290:     {
 7291: 	use integer;
 7292: 	my $test=(2**32)+1;
 7293: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7294: 	&logthis(" Detected 64bit platform ($_64bit)");
 7295:     }
 7296: }
 7297: }
 7298: 
 7299: 1;
 7300: __END__
 7301: 
 7302: =pod
 7303: 
 7304: =head1 NAME
 7305: 
 7306: Apache::lonnet - Subroutines to ask questions about things in the network.
 7307: 
 7308: =head1 SYNOPSIS
 7309: 
 7310: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7311: 
 7312:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7313: 
 7314: Common parameters:
 7315: 
 7316: =over 4
 7317: 
 7318: =item *
 7319: 
 7320: $uname : an internal username (if $cname expecting a course Id specifically)
 7321: 
 7322: =item *
 7323: 
 7324: $udom : a domain (if $cdom expecting a course's domain specifically)
 7325: 
 7326: =item *
 7327: 
 7328: $symb : a resource instance identifier
 7329: 
 7330: =item *
 7331: 
 7332: $namespace : the name of a .db file that contains the data needed or
 7333: being set.
 7334: 
 7335: =back
 7336: 
 7337: =head1 OVERVIEW
 7338: 
 7339: lonnet provides subroutines which interact with the
 7340: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7341: about classes, users, and resources.
 7342: 
 7343: For many of these objects you can also use this to store data about
 7344: them or modify them in various ways.
 7345: 
 7346: =head2 Symbs
 7347: 
 7348: To identify a specific instance of a resource, LON-CAPA uses symbols
 7349: or "symbs"X<symb>. These identifiers are built from the URL of the
 7350: map, the resource number of the resource in the map, and the URL of
 7351: the resource itself. The latter is somewhat redundant, but might help
 7352: if maps change.
 7353: 
 7354: An example is
 7355: 
 7356:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7357: 
 7358: The respective map entry is
 7359: 
 7360:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7361:   title="Problem 2">
 7362:  </resource>
 7363: 
 7364: Symbs are used by the random number generator, as well as to store and
 7365: restore data specific to a certain instance of for example a problem.
 7366: 
 7367: =head2 Storing And Retrieving Data
 7368: 
 7369: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7370: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7371: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7372: is is the non-critical message twin of cstore. These functions are for
 7373: handlers to store a perl hash to a user's permanent data space in an
 7374: easy manner, and to retrieve it again on another call. It is expected
 7375: that a handler would use this once at the beginning to retrieve data,
 7376: and then again once at the end to send only the new data back.
 7377: 
 7378: The data is stored in the user's data directory on the user's
 7379: homeserver under the ID of the course.
 7380: 
 7381: The hash that is returned by restore will have all of the previous
 7382: value for all of the elements of the hash.
 7383: 
 7384: Example:
 7385: 
 7386:  #creating a hash
 7387:  my %hash;
 7388:  $hash{'foo'}='bar';
 7389: 
 7390:  #storing it
 7391:  &Apache::lonnet::cstore(\%hash);
 7392: 
 7393:  #changing a value
 7394:  $hash{'foo'}='notbar';
 7395: 
 7396:  #adding a new value
 7397:  $hash{'bar'}='foo';
 7398:  &Apache::lonnet::cstore(\%hash);
 7399: 
 7400:  #retrieving the hash
 7401:  my %history=&Apache::lonnet::restore();
 7402: 
 7403:  #print the hash
 7404:  foreach my $key (sort(keys(%history))) {
 7405:    print("\%history{$key} = $history{$key}");
 7406:  }
 7407: 
 7408: Will print out:
 7409: 
 7410:  %history{1:foo} = bar
 7411:  %history{1:keys} = foo:timestamp
 7412:  %history{1:timestamp} = 990455579
 7413:  %history{2:bar} = foo
 7414:  %history{2:foo} = notbar
 7415:  %history{2:keys} = foo:bar:timestamp
 7416:  %history{2:timestamp} = 990455580
 7417:  %history{bar} = foo
 7418:  %history{foo} = notbar
 7419:  %history{timestamp} = 990455580
 7420:  %history{version} = 2
 7421: 
 7422: Note that the special hash entries C<keys>, C<version> and
 7423: C<timestamp> were added to the hash. C<version> will be equal to the
 7424: total number of versions of the data that have been stored. The
 7425: C<timestamp> attribute will be the UNIX time the hash was
 7426: stored. C<keys> is available in every historical section to list which
 7427: keys were added or changed at a specific historical revision of a
 7428: hash.
 7429: 
 7430: B<Warning>: do not store the hash that restore returns directly. This
 7431: will cause a mess since it will restore the historical keys as if the
 7432: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7433: 
 7434: Calling convention:
 7435: 
 7436:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7437:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7438: 
 7439: For more detailed information, see lonnet specific documentation.
 7440: 
 7441: =head1 RETURN MESSAGES
 7442: 
 7443: =over 4
 7444: 
 7445: =item * B<con_lost>: unable to contact remote host
 7446: 
 7447: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7448: when the connection is brought back up
 7449: 
 7450: =item * B<con_failed>: unable to contact remote host and unable to save message
 7451: for later delivery
 7452: 
 7453: =item * B<error:>: an error a occured, a description of the error follows the :
 7454: 
 7455: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7456: that was requested
 7457: 
 7458: =back
 7459: 
 7460: =head1 PUBLIC SUBROUTINES
 7461: 
 7462: =head2 Session Environment Functions
 7463: 
 7464: =over 4
 7465: 
 7466: =item * 
 7467: X<appenv()>
 7468: B<appenv(%hash)>: the value of %hash is written to
 7469: the user envirnoment file, and will be restored for each access this
 7470: user makes during this session, also modifies the %env for the current
 7471: process
 7472: 
 7473: =item *
 7474: X<delenv()>
 7475: B<delenv($regexp)>: removes all items from the session
 7476: environment file that matches the regular expression in $regexp. The
 7477: values are also delted from the current processes %env.
 7478: 
 7479: =back
 7480: 
 7481: =head2 User Information
 7482: 
 7483: =over 4
 7484: 
 7485: =item *
 7486: X<queryauthenticate()>
 7487: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7488: authentication scheme
 7489: 
 7490: =item *
 7491: X<authenticate()>
 7492: B<authenticate($uname,$upass,$udom)>: try to
 7493: authenticate user from domain's lib servers (first use the current
 7494: one). C<$upass> should be the users password.
 7495: 
 7496: =item *
 7497: X<homeserver()>
 7498: B<homeserver($uname,$udom)>: find the server which has
 7499: the user's directory and files (there must be only one), this caches
 7500: the answer, and also caches if there is a borken connection.
 7501: 
 7502: =item *
 7503: X<idget()>
 7504: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7505: (IDs are a unique resource in a domain, there must be only 1 ID per
 7506: username, and only 1 username per ID in a specific domain) (returns
 7507: hash: id=>name,id=>name)
 7508: 
 7509: =item *
 7510: X<idrget()>
 7511: B<idrget($udom,@unames)>: find the IDs behind a list of
 7512: usernames (returns hash: name=>id,name=>id)
 7513: 
 7514: =item *
 7515: X<idput()>
 7516: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7517: 
 7518: =item *
 7519: X<rolesinit()>
 7520: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7521: 
 7522: =item *
 7523: X<getsection()>
 7524: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7525: course $cname, return section name/number or '' for "not in course"
 7526: and '-1' for "no section"
 7527: 
 7528: =item *
 7529: X<userenvironment()>
 7530: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7531: passed in @what from the requested user's environment, returns a hash
 7532: 
 7533: =back
 7534: 
 7535: =head2 User Roles
 7536: 
 7537: =over 4
 7538: 
 7539: =item *
 7540: 
 7541: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7542: actions
 7543:  F: full access
 7544:  U,I,K: authentication modes (cxx only)
 7545:  '': forbidden
 7546:  1: user needs to choose course
 7547:  2: browse allowed
 7548:  A: passphrase authentication needed
 7549: 
 7550: =item *
 7551: 
 7552: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7553: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7554: and course level
 7555: 
 7556: =item *
 7557: 
 7558: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7559: explanation of a user role term
 7560: 
 7561: =back
 7562: 
 7563: =head2 User Modification
 7564: 
 7565: =over 4
 7566: 
 7567: =item *
 7568: 
 7569: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7570: user for the level given by URL.  Optional start and end dates (leave empty
 7571: string or zero for "no date")
 7572: 
 7573: =item *
 7574: 
 7575: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7576: change a users, password, possible return values are: ok,
 7577: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7578: refused
 7579: 
 7580: =item *
 7581: 
 7582: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7583: 
 7584: =item *
 7585: 
 7586: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7587: modify user
 7588: 
 7589: =item *
 7590: 
 7591: modifystudent
 7592: 
 7593: modify a students enrollment and identification information.
 7594: The course id is resolved based on the current users environment.  
 7595: This means the envoking user must be a course coordinator or otherwise
 7596: associated with a course.
 7597: 
 7598: This call is essentially a wrapper for lonnet::modifyuser and
 7599: lonnet::modify_student_enrollment
 7600: 
 7601: Inputs: 
 7602: 
 7603: =over 4
 7604: 
 7605: =item B<$udom> Students loncapa domain
 7606: 
 7607: =item B<$uname> Students loncapa login name
 7608: 
 7609: =item B<$uid> Students id/student number
 7610: 
 7611: =item B<$umode> Students authentication mode
 7612: 
 7613: =item B<$upass> Students password
 7614: 
 7615: =item B<$first> Students first name
 7616: 
 7617: =item B<$middle> Students middle name
 7618: 
 7619: =item B<$last> Students last name
 7620: 
 7621: =item B<$gene> Students generation
 7622: 
 7623: =item B<$usec> Students section in course
 7624: 
 7625: =item B<$end> Unix time of the roles expiration
 7626: 
 7627: =item B<$start> Unix time of the roles start date
 7628: 
 7629: =item B<$forceid> If defined, allow $uid to be changed
 7630: 
 7631: =item B<$desiredhome> server to use as home server for student
 7632: 
 7633: =back
 7634: 
 7635: =item *
 7636: 
 7637: modify_student_enrollment
 7638: 
 7639: Change a students enrollment status in a class.  The environment variable
 7640: 'role.request.course' must be defined for this function to proceed.
 7641: 
 7642: Inputs:
 7643: 
 7644: =over 4
 7645: 
 7646: =item $udom, students domain
 7647: 
 7648: =item $uname, students name
 7649: 
 7650: =item $uid, students user id
 7651: 
 7652: =item $first, students first name
 7653: 
 7654: =item $middle
 7655: 
 7656: =item $last
 7657: 
 7658: =item $gene
 7659: 
 7660: =item $usec
 7661: 
 7662: =item $end
 7663: 
 7664: =item $start
 7665: 
 7666: =back
 7667: 
 7668: 
 7669: =item *
 7670: 
 7671: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7672: custom role; give a custom role to a user for the level given by URL.  Specify
 7673: name and domain of role author, and role name
 7674: 
 7675: =item *
 7676: 
 7677: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7678: 
 7679: =item *
 7680: 
 7681: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7682: 
 7683: =back
 7684: 
 7685: =head2 Course Infomation
 7686: 
 7687: =over 4
 7688: 
 7689: =item *
 7690: 
 7691: coursedescription($courseid) : returns a hash of information about the
 7692: specified course id, including all environment settings for the
 7693: course, the description of the course will be in the hash under the
 7694: key 'description'
 7695: 
 7696: =item *
 7697: 
 7698: resdata($name,$domain,$type,@which) : request for current parameter
 7699: setting for a specific $type, where $type is either 'course' or 'user',
 7700: @what should be a list of parameters to ask about. This routine caches
 7701: answers for 5 minutes.
 7702: 
 7703: =back
 7704: 
 7705: =head2 Course Modification
 7706: 
 7707: =over 4
 7708: 
 7709: =item *
 7710: 
 7711: writecoursepref($courseid,%prefs) : write preferences (environment
 7712: database) for a course
 7713: 
 7714: =item *
 7715: 
 7716: createcourse($udom,$description,$url) : make/modify course
 7717: 
 7718: =back
 7719: 
 7720: =head2 Resource Subroutines
 7721: 
 7722: =over 4
 7723: 
 7724: =item *
 7725: 
 7726: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7727: 
 7728: =item *
 7729: 
 7730: repcopy($filename) : subscribes to the requested file, and attempts to
 7731: replicate from the owning library server, Might return
 7732: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7733: 'bad_request', also attempts to grab the metadata for the
 7734: resource. Expects the local filesystem pathname
 7735: (/home/httpd/html/res/....)
 7736: 
 7737: =back
 7738: 
 7739: =head2 Resource Information
 7740: 
 7741: =over 4
 7742: 
 7743: =item *
 7744: 
 7745: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7746: a vairety of different possible values, $varname should be a request
 7747: string, and the other parameters can be used to specify who and what
 7748: one is asking about.
 7749: 
 7750: Possible values for $varname are environment.lastname (or other item
 7751: from the envirnment hash), user.name (or someother aspect about the
 7752: user), resource.0.maxtries (or some other part and parameter of a
 7753: resource)
 7754: 
 7755: =item *
 7756: 
 7757: directcondval($number) : get current value of a condition; reads from a state
 7758: string
 7759: 
 7760: =item *
 7761: 
 7762: condval($condidx) : value of condition index based on state
 7763: 
 7764: =item *
 7765: 
 7766: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7767: resource's metadata, $what should be either a specific key, or either
 7768: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7769: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7770: 
 7771: this function automatically caches all requests
 7772: 
 7773: =item *
 7774: 
 7775: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7776: network of library servers; returns file handle of where SQL and regex results
 7777: will be stored for query
 7778: 
 7779: =item *
 7780: 
 7781: symbread($filename) : return symbolic list entry (filename argument optional);
 7782: returns the data handle
 7783: 
 7784: =item *
 7785: 
 7786: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7787: a possible symb for the URL in $thisfn, and if is an encryypted
 7788: resource that the user accessed using /enc/ returns a 1 on success, 0
 7789: on failure, user must be in a course, as it assumes the existance of
 7790: the course initial hash, and uses $env('request.course.id'}
 7791: 
 7792: 
 7793: =item *
 7794: 
 7795: symbclean($symb) : removes versions numbers from a symb, returns the
 7796: cleaned symb
 7797: 
 7798: =item *
 7799: 
 7800: is_on_map($uri) : checks if the $uri is somewhere on the current
 7801: course map, user must be in a course for it to work.
 7802: 
 7803: =item *
 7804: 
 7805: numval($salt) : return random seed value (addend for rndseed)
 7806: 
 7807: =item *
 7808: 
 7809: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7810: a random seed, all arguments are optional, if they aren't sent it uses the
 7811: environment to derive them. Note: if symb isn't sent and it can't get one
 7812: from &symbread it will use the current time as its return value
 7813: 
 7814: =item *
 7815: 
 7816: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7817: unfakeable, receipt
 7818: 
 7819: =item *
 7820: 
 7821: receipt() : API to ireceipt working off of env values; given out to users
 7822: 
 7823: =item *
 7824: 
 7825: countacc($url) : count the number of accesses to a given URL
 7826: 
 7827: =item *
 7828: 
 7829: 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
 7830: 
 7831: =item *
 7832: 
 7833: 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)
 7834: 
 7835: =item *
 7836: 
 7837: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7838: 
 7839: =item *
 7840: 
 7841: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7842: forcing spreadsheet to reevaluate the resource scores next time.
 7843: 
 7844: =back
 7845: 
 7846: =head2 Storing/Retreiving Data
 7847: 
 7848: =over 4
 7849: 
 7850: =item *
 7851: 
 7852: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7853: for this url; hashref needs to be given and should be a \%hashname; the
 7854: remaining args aren't required and if they aren't passed or are '' they will
 7855: be derived from the env
 7856: 
 7857: =item *
 7858: 
 7859: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7860: uses critical subroutine
 7861: 
 7862: =item *
 7863: 
 7864: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7865: all args are optional
 7866: 
 7867: =item *
 7868: 
 7869: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7870: dumps the complete (or key matching regexp) namespace into a hash
 7871: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7872: normally &store()ed into
 7873: 
 7874: $range should be either an integer '100' (give me the first 100
 7875:                                            matching records)
 7876:               or be  two integers sperated by a - with no spaces
 7877:                  '30-50' (give me the 30th through the 50th matching
 7878:                           records)
 7879: 
 7880: 
 7881: =item *
 7882: 
 7883: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7884: replaces a &store() version of data with a replacement set of data
 7885: for a particular resource in a namespace passed in the $storehash hash 
 7886: reference
 7887: 
 7888: =item *
 7889: 
 7890: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7891: works very similar to store/cstore, but all data is stored in a
 7892: temporary location and can be reset using tmpreset, $storehash should
 7893: be a hash reference, returns nothing on success
 7894: 
 7895: =item *
 7896: 
 7897: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7898: similar to restore, but all data is stored in a temporary location and
 7899: can be reset using tmpreset. Returns a hash of values on success,
 7900: error string otherwise.
 7901: 
 7902: =item *
 7903: 
 7904: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7905: deltes all keys for $symb form the temporary storage hash.
 7906: 
 7907: =item *
 7908: 
 7909: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7910: reference filled in from namesp ($udom and $uname are optional)
 7911: 
 7912: =item *
 7913: 
 7914: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7915: namesp ($udom and $uname are optional)
 7916: 
 7917: =item *
 7918: 
 7919: dump($namespace,$udom,$uname,$regexp,$range) : 
 7920: dumps the complete (or key matching regexp) namespace into a hash
 7921: ($udom, $uname, $regexp, $range are optional)
 7922: 
 7923: $range should be either an integer '100' (give me the first 100
 7924:                                            matching records)
 7925:               or be  two integers sperated by a - with no spaces
 7926:                  '30-50' (give me the 30th through the 50th matching
 7927:                           records)
 7928: =item *
 7929: 
 7930: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7931: $store can be a scalar, an array reference, or if the amount to be 
 7932: incremented is > 1, a hash reference.
 7933: 
 7934: ($udom and $uname are optional)
 7935: 
 7936: =item *
 7937: 
 7938: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7939: ($udom and $uname are optional)
 7940: 
 7941: =item *
 7942: 
 7943: cput($namespace,$storehash,$udom,$uname) : critical put
 7944: ($udom and $uname are optional)
 7945: 
 7946: =item *
 7947: 
 7948: newput($namespace,$storehash,$udom,$uname) :
 7949: 
 7950: Attempts to store the items in the $storehash, but only if they don't
 7951: currently exist, if this succeeds you can be certain that you have 
 7952: successfully created a new key value pair in the $namespace db.
 7953: 
 7954: 
 7955: Args:
 7956:  $namespace: name of database to store values to
 7957:  $storehash: hashref to store to the db
 7958:  $udom: (optional) domain of user containing the db
 7959:  $uname: (optional) name of user caontaining the db
 7960: 
 7961: Returns:
 7962:  'ok' -> succeeded in storing all keys of $storehash
 7963:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 7964:                         least <key> already existed in the db (other
 7965:                         requested keys may also already exist)
 7966:  'error: <msg>' -> unable to tie the DB or other erorr occured
 7967:  'con_lost' -> unable to contact request server
 7968:  'refused' -> action was not allowed by remote machine
 7969: 
 7970: 
 7971: =item *
 7972: 
 7973: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7974: reference filled in from namesp (encrypts the return communication)
 7975: ($udom and $uname are optional)
 7976: 
 7977: =item *
 7978: 
 7979: log($udom,$name,$home,$message) : write to permanent log for user; use
 7980: critical subroutine
 7981: 
 7982: =back
 7983: 
 7984: =head2 Network Status Functions
 7985: 
 7986: =over 4
 7987: 
 7988: =item *
 7989: 
 7990: dirlist($uri) : return directory list based on URI
 7991: 
 7992: =item *
 7993: 
 7994: spareserver() : find server with least workload from spare.tab
 7995: 
 7996: =back
 7997: 
 7998: =head2 Apache Request
 7999: 
 8000: =over 4
 8001: 
 8002: =item *
 8003: 
 8004: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8005: localhost, posts hash
 8006: 
 8007: =back
 8008: 
 8009: =head2 Data to String to Data
 8010: 
 8011: =over 4
 8012: 
 8013: =item *
 8014: 
 8015: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8016: and '&' separators, supports elements that are arrayrefs and hashrefs
 8017: 
 8018: =item *
 8019: 
 8020: hashref2str($hashref) : convert a hashref into a string complete with
 8021: escaping and '=' and '&' separators, supports elements that are
 8022: arrayrefs and hashrefs
 8023: 
 8024: =item *
 8025: 
 8026: arrayref2str($arrayref) : convert an arrayref into a string complete
 8027: with escaping and '&' separators, supports elements that are arrayrefs
 8028: and hashrefs
 8029: 
 8030: =item *
 8031: 
 8032: str2hash($string) : convert string to hash using unescaping and
 8033: splitting on '=' and '&', supports elements that are arrayrefs and
 8034: hashrefs
 8035: 
 8036: =item *
 8037: 
 8038: str2array($string) : convert string to hash using unescaping and
 8039: splitting on '&', supports elements that are arrayrefs and hashrefs
 8040: 
 8041: =back
 8042: 
 8043: =head2 Logging Routines
 8044: 
 8045: =over 4
 8046: 
 8047: These routines allow one to make log messages in the lonnet.log and
 8048: lonnet.perm logfiles.
 8049: 
 8050: =item *
 8051: 
 8052: logtouch() : make sure the logfile, lonnet.log, exists
 8053: 
 8054: =item *
 8055: 
 8056: logthis() : append message to the normal lonnet.log file, it gets
 8057: preiodically rolled over and deleted.
 8058: 
 8059: =item *
 8060: 
 8061: logperm() : append a permanent message to lonnet.perm.log, this log
 8062: file never gets deleted by any automated portion of the system, only
 8063: messages of critical importance should go in here.
 8064: 
 8065: =back
 8066: 
 8067: =head2 General File Helper Routines
 8068: 
 8069: =over 4
 8070: 
 8071: =item *
 8072: 
 8073: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8074: (a) files in /uploaded
 8075:   (i) If a local copy of the file exists - 
 8076:       compares modification date of local copy with last-modified date for 
 8077:       definitive version stored on home server for course. If local copy is 
 8078:       stale, requests a new version from the home server and stores it. 
 8079:       If the original has been removed from the home server, then local copy 
 8080:       is unlinked.
 8081:   (ii) If local copy does not exist -
 8082:       requests the file from the home server and stores it. 
 8083:   
 8084:   If $caller is 'uploadrep':  
 8085:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8086:     for request for files originally uploaded via DOCS. 
 8087:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8088:   
 8089:   Otherwise:
 8090:      This indicates a call from the content generation phase of the request.
 8091:      -  returns the entire contents of the file or -1.
 8092:      
 8093: (b) files in /res
 8094:    - returns the entire contents of a file or -1; 
 8095:    it properly subscribes to and replicates the file if neccessary.
 8096: 
 8097: 
 8098: =item *
 8099: 
 8100: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8101:                   reference
 8102: 
 8103: returns either a stat() list of data about the file or an empty list
 8104: if the file doesn't exist or couldn't find out about it (connection
 8105: problems or user unknown)
 8106: 
 8107: =item *
 8108: 
 8109: filelocation($dir,$file) : returns file system location of a file
 8110: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8111: directory that relative $file lookups are to looked in ($dir of /a/dir
 8112: and a file of ../bob will become /a/bob)
 8113: 
 8114: =item *
 8115: 
 8116: hreflocation($dir,$file) : returns file system location or a URL; same as
 8117: filelocation except for hrefs
 8118: 
 8119: =item *
 8120: 
 8121: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8122: 
 8123: =back
 8124: 
 8125: =head2 Usererfile file routines (/uploaded*)
 8126: 
 8127: =over 4
 8128: 
 8129: =item *
 8130: 
 8131: userfileupload(): main rotine for putting a file in a user or course's
 8132:                   filespace, arguments are,
 8133: 
 8134:  formname - required - this is the name of the element in $env where the
 8135:            filename, and the contents of the file to create/modifed exist
 8136:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8137:            contents of the file is located in $env{'form.'.$formname}
 8138:  coursedoc - if true, store the file in the course of the active role
 8139:              of the current user
 8140:  subdir - required - subdirectory to put the file in under ../userfiles/
 8141:          if undefined, it will be placed in "unknown"
 8142: 
 8143:  (This routine calls clean_filename() to remove any dangerous
 8144:  characters from the filename, and then calls finuserfileupload() to
 8145:  complete the transaction)
 8146: 
 8147:  returns either the url of the uploaded file (/uploaded/....) if successful
 8148:  and /adm/notfound.html if unsuccessful
 8149: 
 8150: =item *
 8151: 
 8152: clean_filename(): routine for cleaing a filename up for storage in
 8153:                  userfile space, argument is:
 8154: 
 8155:  filename - proposed filename
 8156: 
 8157: returns: the new clean filename
 8158: 
 8159: =item *
 8160: 
 8161: finishuserfileupload(): routine that creaes and sends the file to
 8162: userspace, probably shouldn't be called directly
 8163: 
 8164:   docuname: username or courseid of destination for the file
 8165:   docudom: domain of user/course of destination for the file
 8166:   formname: same as for userfileupload()
 8167:   fname: filename (inculding subdirectories) for the file
 8168: 
 8169:  returns either the url of the uploaded file (/uploaded/....) if successful
 8170:  and /adm/notfound.html if unsuccessful
 8171: 
 8172: =item *
 8173: 
 8174: renameuserfile(): renames an existing userfile to a new name
 8175: 
 8176:   Args:
 8177:    docuname: username or courseid of destination for the file
 8178:    docudom: domain of user/course of destination for the file
 8179:    old: current file name (including any subdirs under userfiles)
 8180:    new: desired file name (including any subdirs under userfiles)
 8181: 
 8182: =item *
 8183: 
 8184: mkdiruserfile(): creates a directory is a userfiles dir
 8185: 
 8186:   Args:
 8187:    docuname: username or courseid of destination for the file
 8188:    docudom: domain of user/course of destination for the file
 8189:    dir: dir to create (including any subdirs under userfiles)
 8190: 
 8191: =item *
 8192: 
 8193: removeuserfile(): removes a file that exists in userfiles
 8194: 
 8195:   Args:
 8196:    docuname: username or courseid of destination for the file
 8197:    docudom: domain of user/course of destination for the file
 8198:    fname: filname to delete (including any subdirs under userfiles)
 8199: 
 8200: =item *
 8201: 
 8202: removeuploadedurl(): convience function for removeuserfile()
 8203: 
 8204:   Args:
 8205:    url:  a full /uploaded/... url to delete
 8206: 
 8207: =item * 
 8208: 
 8209: get_portfile_permissions():
 8210:   Args:
 8211:     domain: domain of user or course contain the portfolio files
 8212:     user: name of user or num of course contain the portfolio files
 8213:   Returns:
 8214:     hashref of a dump of the proper file_permissions.db
 8215:    
 8216: 
 8217: =item * 
 8218: 
 8219: get_access_controls():
 8220: 
 8221: Args:
 8222:   current_permissions: the hash ref returned from get_portfile_permissions()
 8223:   group: (optional) the group you want the files associated with
 8224:   file: (optional) the file you want access info on
 8225: 
 8226: Returns:
 8227:     a hash (keys are file names) of hashes containing
 8228:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8229:         values are XML containing access control settings (see below) 
 8230: 
 8231: Internal notes:
 8232: 
 8233:  access controls are stored in file_permissions.db as key=value pairs.
 8234:     key -> path to file/file_name\0uniqueID:scope_end_start
 8235:         where scope -> public,guest,course,group,domains or users.
 8236:               end -> UNIX time for end of access (0 -> no end date)
 8237:               start -> UNIX time for start of access
 8238: 
 8239:     value -> XML description of access control
 8240:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8241:             <start></start>
 8242:             <end></end>
 8243: 
 8244:             <password></password>  for scope type = guest
 8245: 
 8246:             <domain></domain>     for scope type = course or group
 8247:             <number></number>
 8248:             <roles id="">
 8249:              <role></role>
 8250:              <access></access>
 8251:              <section></section>
 8252:              <group></group>
 8253:             </roles>
 8254: 
 8255:             <dom></dom>         for scope type = domains
 8256: 
 8257:             <users>             for scope type = users
 8258:              <user>
 8259:               <uname></uname>
 8260:               <udom></udom>
 8261:              </user>
 8262:             </users>
 8263:            </scope> 
 8264:               
 8265:  Access data is also aggregated for each file in an additional key=value pair:
 8266:  key -> path to file/file_name\0accesscontrol 
 8267:  value -> reference to hash
 8268:           hash contains key = value pairs
 8269:           where key = uniqueID:scope_end_start
 8270:                 value = UNIX time record was last updated
 8271: 
 8272:           Used to improve speed of look-ups of access controls for each file.  
 8273:  
 8274:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8275: 
 8276: modify_access_controls():
 8277: 
 8278: Modifies access controls for a portfolio file
 8279: Args
 8280: 1. file name
 8281: 2. reference to hash of required changes,
 8282: 3. domain
 8283: 4. username
 8284:   where domain,username are the domain of the portfolio owner 
 8285:   (either a user or a course) 
 8286: 
 8287: Returns:
 8288: 1. result of additions or updates ('ok' or 'error', with error message). 
 8289: 2. result of deletions ('ok' or 'error', with error message).
 8290: 3. reference to hash of any new or updated access controls.
 8291: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8292:    key = integer (inbound ID)
 8293:    value = uniqueID  
 8294: 
 8295: =back
 8296: 
 8297: =head2 HTTP Helper Routines
 8298: 
 8299: =over 4
 8300: 
 8301: =item *
 8302: 
 8303: escape() : unpack non-word characters into CGI-compatible hex codes
 8304: 
 8305: =item *
 8306: 
 8307: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8308: 
 8309: =back
 8310: 
 8311: =head1 PRIVATE SUBROUTINES
 8312: 
 8313: =head2 Underlying communication routines (Shouldn't call)
 8314: 
 8315: =over 4
 8316: 
 8317: =item *
 8318: 
 8319: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8320: 
 8321: =item *
 8322: 
 8323: reply() : uses subreply to send a message to remote machine, logs all failures
 8324: 
 8325: =item *
 8326: 
 8327: critical() : passes a critical message to another server; if cannot
 8328: get through then place message in connection buffer directory and
 8329: returns con_delayed, if incapable of saving message, returns
 8330: con_failed
 8331: 
 8332: =item *
 8333: 
 8334: reconlonc() : tries to reconnect lonc client processes.
 8335: 
 8336: =back
 8337: 
 8338: =head2 Resource Access Logging
 8339: 
 8340: =over 4
 8341: 
 8342: =item *
 8343: 
 8344: flushcourselogs() : flush (save) buffer logs and access logs
 8345: 
 8346: =item *
 8347: 
 8348: courselog($what) : save message for course in hash
 8349: 
 8350: =item *
 8351: 
 8352: courseacclog($what) : save message for course using &courselog().  Perform
 8353: special processing for specific resource types (problems, exams, quizzes, etc).
 8354: 
 8355: =item *
 8356: 
 8357: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8358: as a PerlChildExitHandler
 8359: 
 8360: =back
 8361: 
 8362: =head2 Other
 8363: 
 8364: =over 4
 8365: 
 8366: =item *
 8367: 
 8368: symblist($mapname,%newhash) : update symbolic storage links
 8369: 
 8370: =back
 8371: 
 8372: =cut

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