File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.784: download - view: text, annotated - select for diffs
Thu Sep 28 01:38:59 2006 UTC (17 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- now there are two class of spare servers 'primary' and default

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.784 2006/09/28 01:38:59 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %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: sub convert_and_load_session_env {
  296:     my ($lonidsdir,$handle)=@_;
  297:     my @profile;
  298:     {
  299: 	open(my $idf,"$lonidsdir/$handle.id");
  300: 	flock($idf,LOCK_SH);
  301: 	@profile=<$idf>;
  302: 	close($idf);
  303:     }
  304:     my %temp_env;
  305:     foreach my $line (@profile) {
  306: 	chomp($line);
  307: 	my ($envname,$envvalue)=split(/=/,$line,2);
  308: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  309:     }
  310:     unlink("$lonidsdir/$handle.id");
  311:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  312: 	    0640)) {
  313: 	%disk_env = %temp_env;
  314: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  315: 	untie(%disk_env);
  316:     }
  317: }
  318: 
  319: # ------------------------------------------- Transfer profile into environment
  320: my $env_loaded;
  321: sub transfer_profile_to_env {
  322:     if ($env_loaded) { return; } 
  323: 
  324:     my ($lonidsdir,$handle)=@_;
  325:     if (!defined($lonidsdir)) {
  326: 	$lonidsdir = $perlvar{'lonIDsDir'};
  327:     }
  328:     if (!defined($handle)) {
  329:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  330:     }
  331: 
  332:     my %remove;
  333:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_READER(),
  334: 	    0640)) {
  335: 	@env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  336: 	untie(%disk_env);
  337:     } else {
  338: 	&convert_and_load_session_env($lonidsdir,$handle);
  339:     }
  340: 
  341:     while ( my $envname = each(%env) ) {
  342:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  343:             if ($time < time-300) {
  344:                 $remove{$key}++;
  345:             }
  346:         }
  347:     }
  348: 
  349:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  350:     $env_loaded=1;
  351:     foreach my $expired_key (keys(%remove)) {
  352:         &delenv($expired_key);
  353:     }
  354: }
  355: 
  356: # ---------------------------------------------------------- Append Environment
  357: 
  358: sub appenv {
  359:     my %newenv=@_;
  360:     foreach my $key (keys(%newenv)) {
  361: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  362:             &logthis("<font color=\"blue\">WARNING: ".
  363:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  364:                 .'</font>');
  365: 	    delete($newenv{$key});
  366:         } else {
  367:             $env{$key}=$newenv{$key};
  368:         }
  369:     }
  370:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
  371: 	    0640)) {
  372: 	while (my ($key,$value) = each(%newenv)) {
  373: 	    $disk_env{$key} = $value;
  374: 	}
  375: 	untie(%disk_env);
  376:     }
  377:     return 'ok';
  378: }
  379: # ----------------------------------------------------- Delete from Environment
  380: 
  381: sub delenv {
  382:     my $delthis=shift;
  383:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  384:         &logthis("<font color=\"blue\">WARNING: ".
  385:                 "Attempt to delete from environment ".$delthis);
  386:         return 'error';
  387:     }
  388:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
  389: 	    0640)) {
  390: 	foreach my $key (keys(%disk_env)) {
  391: 	    if ($key=~/^$delthis/) { 
  392:                 delete($env{$key});
  393:                 delete($disk_env{$key});
  394:             }
  395: 	}
  396: 	untie(%disk_env);
  397:     }
  398:     return 'ok';
  399: }
  400: 
  401: # ------------------------------------------ Find out current server userload
  402: # there is a copy in lond
  403: sub userload {
  404:     my $numusers=0;
  405:     {
  406: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  407: 	my $filename;
  408: 	my $curtime=time;
  409: 	while ($filename=readdir(LONIDS)) {
  410: 	    if ($filename eq '.' || $filename eq '..') {next;}
  411: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  412: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  413: 	}
  414: 	closedir(LONIDS);
  415:     }
  416:     my $userloadpercent=0;
  417:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  418:     if ($maxuserload) {
  419: 	$userloadpercent=100*$numusers/$maxuserload;
  420:     }
  421:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  422:     return $userloadpercent;
  423: }
  424: 
  425: # ------------------------------------------ Fight off request when overloaded
  426: 
  427: sub overloaderror {
  428:     my ($r,$checkserver)=@_;
  429:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  430:     my $loadavg;
  431:     if ($checkserver eq $perlvar{'lonHostID'}) {
  432:        open(my $loadfile,'/proc/loadavg');
  433:        $loadavg=<$loadfile>;
  434:        $loadavg =~ s/\s.*//g;
  435:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  436:        close($loadfile);
  437:     } else {
  438:        $loadavg=&reply('load',$checkserver);
  439:     }
  440:     my $overload=$loadavg-100;
  441:     if ($overload>0) {
  442: 	$r->err_headers_out->{'Retry-After'}=$overload;
  443:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  444:         return 413;
  445:     }    
  446:     return '';
  447: }
  448: 
  449: # ------------------------------ Find server with least workload from spare.tab
  450: 
  451: sub spareserver {
  452:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  453:     my $spare_server;
  454:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  455:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  456:                                                      :  $userloadpercent;
  457:     
  458:     foreach my $try_server (@{ $spareid{'primary'} }) {
  459: 	($spare_server, $lowest_load) =
  460: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  461:     }
  462: 
  463:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  464: 
  465:     if (!$found_server) {
  466: 	foreach my $try_server (@{ $spareid{'default'} }) {
  467: 	    ($spare_server, $lowest_load) =
  468: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  469: 	}
  470:     }
  471: 
  472:     if (!$want_server_name) {
  473: 	$spare_server="http://$hostname{$spare_server}";
  474:     }
  475:     return $spare_server;
  476: }
  477: 
  478: sub compare_server_load {
  479:     my ($try_server, $spare_server, $lowest_load) = @_;
  480: 
  481:     my $loadans     = &reply('load',    $try_server);
  482:     my $userloadans = &reply('userload',$try_server);
  483: 
  484:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  485: 	next; #didn't get a number from the server
  486:     }
  487: 
  488:     my $load;
  489:     if ($loadans =~ /\d/) {
  490: 	if ($userloadans =~ /\d/) {
  491: 	    #both are numbers, pick the bigger one
  492: 	    $load = ($loadans > $userloadans) ? $loadans 
  493: 		                              : $userloadans;
  494: 	} else {
  495: 	    $load = $loadans;
  496: 	}
  497:     } else {
  498: 	$load = $userloadans;
  499:     }
  500: 
  501:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  502: 	$spare_server = $try_server;
  503: 	$lowest_load  = $load;
  504:     }
  505:     return ($spare_server,$lowest_load);
  506: }
  507: # --------------------------------------------- Try to change a user's password
  508: 
  509: sub changepass {
  510:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  511:     $currentpass = &escape($currentpass);
  512:     $newpass     = &escape($newpass);
  513:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  514: 		       $server);
  515:     if (! $answer) {
  516: 	&logthis("No reply on password change request to $server ".
  517: 		 "by $uname in domain $udom.");
  518:     } elsif ($answer =~ "^ok") {
  519:         &logthis("$uname in $udom successfully changed their password ".
  520: 		 "on $server.");
  521:     } elsif ($answer =~ "^pwchange_failure") {
  522: 	&logthis("$uname in $udom was unable to change their password ".
  523: 		 "on $server.  The action was blocked by either lcpasswd ".
  524: 		 "or pwchange");
  525:     } elsif ($answer =~ "^non_authorized") {
  526:         &logthis("$uname in $udom did not get their password correct when ".
  527: 		 "attempting to change it on $server.");
  528:     } elsif ($answer =~ "^auth_mode_error") {
  529:         &logthis("$uname in $udom attempted to change their password despite ".
  530: 		 "not being locally or internally authenticated on $server.");
  531:     } elsif ($answer =~ "^unknown_user") {
  532:         &logthis("$uname in $udom attempted to change their password ".
  533: 		 "on $server but were unable to because $server is not ".
  534: 		 "their home server.");
  535:     } elsif ($answer =~ "^refused") {
  536: 	&logthis("$server refused to change $uname in $udom password because ".
  537: 		 "it was sent an unencrypted request to change the password.");
  538:     }
  539:     return $answer;
  540: }
  541: 
  542: # ----------------------- Try to determine user's current authentication scheme
  543: 
  544: sub queryauthenticate {
  545:     my ($uname,$udom)=@_;
  546:     my $uhome=&homeserver($uname,$udom);
  547:     if (!$uhome) {
  548: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  549: 	return 'no_host';
  550:     }
  551:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  552:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  553: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  554:     }
  555:     return $answer;
  556: }
  557: 
  558: # --------- Try to authenticate user from domain's lib servers (first this one)
  559: 
  560: sub authenticate {
  561:     my ($uname,$upass,$udom)=@_;
  562:     $upass=escape($upass);
  563:     $uname=~s/\W//g;
  564:     my $uhome=&homeserver($uname,$udom);
  565:     if (!$uhome) {
  566: 	&logthis("User $uname at $udom is unknown in authenticate");
  567: 	return 'no_host';
  568:     }
  569:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  570:     if ($answer eq 'authorized') {
  571: 	&logthis("User $uname at $udom authorized by $uhome"); 
  572: 	return $uhome; 
  573:     }
  574:     if ($answer eq 'non_authorized') {
  575: 	&logthis("User $uname at $udom rejected by $uhome");
  576: 	return 'no_host'; 
  577:     }
  578:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  579:     return 'no_host';
  580: }
  581: 
  582: # ---------------------- Find the homebase for a user from domain's lib servers
  583: 
  584: my %homecache;
  585: sub homeserver {
  586:     my ($uname,$udom,$ignoreBadCache)=@_;
  587:     my $index="$uname:$udom";
  588: 
  589:     if (exists($homecache{$index})) { return $homecache{$index}; }
  590:     my $tryserver;
  591:     foreach $tryserver (keys %libserv) {
  592:         next if ($ignoreBadCache ne 'true' && 
  593: 		 exists($badServerCache{$tryserver}));
  594: 	if ($hostdom{$tryserver} eq $udom) {
  595:            my $answer=reply("home:$udom:$uname",$tryserver);
  596:            if ($answer eq 'found') { 
  597: 	       return $homecache{$index}=$tryserver;
  598:            } elsif ($answer eq 'no_host') {
  599: 	       $badServerCache{$tryserver}=1;
  600:            }
  601:        }
  602:     }    
  603:     return 'no_host';
  604: }
  605: 
  606: # ------------------------------------- Find the usernames behind a list of IDs
  607: 
  608: sub idget {
  609:     my ($udom,@ids)=@_;
  610:     my %returnhash=();
  611:     
  612:     my $tryserver;
  613:     foreach $tryserver (keys %libserv) {
  614:        if ($hostdom{$tryserver} eq $udom) {
  615: 	  my $idlist=join('&',@ids);
  616:           $idlist=~tr/A-Z/a-z/; 
  617: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  618:           my @answer=();
  619:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  620: 	      @answer=split(/\&/,$reply);
  621:           }                    ;
  622:           my $i;
  623:           for ($i=0;$i<=$#ids;$i++) {
  624:               if ($answer[$i]) {
  625: 		  $returnhash{$ids[$i]}=$answer[$i];
  626:               } 
  627:           }
  628:        }
  629:     }    
  630:     return %returnhash;
  631: }
  632: 
  633: # ------------------------------------- Find the IDs behind a list of usernames
  634: 
  635: sub idrget {
  636:     my ($udom,@unames)=@_;
  637:     my %returnhash=();
  638:     foreach (@unames) {
  639:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  640:     }
  641:     return %returnhash;
  642: }
  643: 
  644: # ------------------------------- Store away a list of names and associated IDs
  645: 
  646: sub idput {
  647:     my ($udom,%ids)=@_;
  648:     my %servers=();
  649:     foreach (keys %ids) {
  650: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  651:         my $uhom=&homeserver($_,$udom);
  652:         if ($uhom ne 'no_host') {
  653:             my $id=&escape($ids{$_});
  654:             $id=~tr/A-Z/a-z/;
  655:             my $unam=&escape($_);
  656: 	    if ($servers{$uhom}) {
  657: 		$servers{$uhom}.='&'.$id.'='.$unam;
  658:             } else {
  659:                 $servers{$uhom}=$id.'='.$unam;
  660:             }
  661:         }
  662:     }
  663:     foreach (keys %servers) {
  664:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  665:     }
  666: }
  667: 
  668: # --------------------------------------------------- Assign a key to a student
  669: 
  670: sub assign_access_key {
  671: #
  672: # a valid key looks like uname:udom#comments
  673: # comments are being appended
  674: #
  675:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  676:     $kdom=
  677:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  678:     $knum=
  679:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  680:     $cdom=
  681:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  682:     $cnum=
  683:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  684:     $udom=$env{'user.name'} unless (defined($udom));
  685:     $uname=$env{'user.domain'} unless (defined($uname));
  686:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  687:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  688:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  689:                                                   # assigned to this person
  690:                                                   # - this should not happen,
  691:                                                   # unless something went wrong
  692:                                                   # the first time around
  693: # ready to assign
  694:         $logentry=$1.'; '.$logentry;
  695:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  696:                                                  $kdom,$knum) eq 'ok') {
  697: # key now belongs to user
  698: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  699:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  700:                 &appenv('environment.'.$envkey => $ckey);
  701:                 return 'ok';
  702:             } else {
  703:                 return 
  704:   'error: Count not permanently assign key, will need to be re-entered later.';
  705: 	    }
  706:         } else {
  707:             return 'error: Could not assign key, try again later.';
  708:         }
  709:     } elsif (!$existing{$ckey}) {
  710: # the key does not exist
  711: 	return 'error: The key does not exist';
  712:     } else {
  713: # the key is somebody else's
  714: 	return 'error: The key is already in use';
  715:     }
  716: }
  717: 
  718: # ------------------------------------------ put an additional comment on a key
  719: 
  720: sub comment_access_key {
  721: #
  722: # a valid key looks like uname:udom#comments
  723: # comments are being appended
  724: #
  725:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  726:     $cdom=
  727:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  728:     $cnum=
  729:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  730:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  731:     if ($existing{$ckey}) {
  732:         $existing{$ckey}.='; '.$logentry;
  733: # ready to assign
  734:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  735:                                                  $cdom,$cnum) eq 'ok') {
  736: 	    return 'ok';
  737:         } else {
  738: 	    return 'error: Count not store comment.';
  739:         }
  740:     } else {
  741: # the key does not exist
  742: 	return 'error: The key does not exist';
  743:     }
  744: }
  745: 
  746: # ------------------------------------------------------ Generate a set of keys
  747: 
  748: sub generate_access_keys {
  749:     my ($number,$cdom,$cnum,$logentry)=@_;
  750:     $cdom=
  751:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  752:     $cnum=
  753:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  754:     unless (&allowed('mky',$cdom)) { return 0; }
  755:     unless (($cdom) && ($cnum)) { return 0; }
  756:     if ($number>10000) { return 0; }
  757:     sleep(2); # make sure don't get same seed twice
  758:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  759:     my $total=0;
  760:     for (my $i=1;$i<=$number;$i++) {
  761:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  762:                   sprintf("%lx",int(100000*rand)).'-'.
  763:                   sprintf("%lx",int(100000*rand));
  764:        $newkey=~s/1/g/g; # folks mix up 1 and l
  765:        $newkey=~s/0/h/g; # and also 0 and O
  766:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  767:        if ($existing{$newkey}) {
  768:            $i--;
  769:        } else {
  770: 	  if (&put('accesskeys',
  771:               { $newkey => '# generated '.localtime().
  772:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  773:                            '; '.$logentry },
  774: 		   $cdom,$cnum) eq 'ok') {
  775:               $total++;
  776: 	  }
  777:        }
  778:     }
  779:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  780:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  781:     return $total;
  782: }
  783: 
  784: # ------------------------------------------------------- Validate an accesskey
  785: 
  786: sub validate_access_key {
  787:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  788:     $cdom=
  789:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  790:     $cnum=
  791:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  792:     $udom=$env{'user.domain'} unless (defined($udom));
  793:     $uname=$env{'user.name'} unless (defined($uname));
  794:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  795:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  796: }
  797: 
  798: # ------------------------------------- Find the section of student in a course
  799: sub devalidate_getsection_cache {
  800:     my ($udom,$unam,$courseid)=@_;
  801:     $courseid=~s/\_/\//g;
  802:     $courseid=~s/^(\w)/\/$1/;
  803:     my $hashid="$udom:$unam:$courseid";
  804:     &devalidate_cache_new('getsection',$hashid);
  805: }
  806: 
  807: sub getsection {
  808:     my ($udom,$unam,$courseid)=@_;
  809:     my $cachetime=1800;
  810:     $courseid=~s/\_/\//g;
  811:     $courseid=~s/^(\w)/\/$1/;
  812: 
  813:     my $hashid="$udom:$unam:$courseid";
  814:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  815:     if (defined($cached)) { return $result; }
  816: 
  817:     my %Pending; 
  818:     my %Expired;
  819:     #
  820:     # Each role can either have not started yet (pending), be active, 
  821:     #    or have expired.
  822:     #
  823:     # If there is an active role, we are done.
  824:     #
  825:     # If there is more than one role which has not started yet, 
  826:     #     choose the one which will start sooner
  827:     # If there is one role which has not started yet, return it.
  828:     #
  829:     # If there is more than one expired role, choose the one which ended last.
  830:     # If there is a role which has expired, return it.
  831:     #
  832:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  833:                         &homeserver($unam,$udom)))) {
  834:         my ($key,$value)=split(/\=/,$_);
  835:         $key=&unescape($key);
  836:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  837:         my $section=$1;
  838:         if ($key eq $courseid.'_st') { $section=''; }
  839:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  840:         my $now=time;
  841:         if (defined($end) && $end && ($now > $end)) {
  842:             $Expired{$end}=$section;
  843:             next;
  844:         }
  845:         if (defined($start) && $start && ($now < $start)) {
  846:             $Pending{$start}=$section;
  847:             next;
  848:         }
  849:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  850:     }
  851:     #
  852:     # Presumedly there will be few matching roles from the above
  853:     # loop and the sorting time will be negligible.
  854:     if (scalar(keys(%Pending))) {
  855:         my ($time) = sort {$a <=> $b} keys(%Pending);
  856:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  857:     } 
  858:     if (scalar(keys(%Expired))) {
  859:         my @sorted = sort {$a <=> $b} keys(%Expired);
  860:         my $time = pop(@sorted);
  861:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  862:     }
  863:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  864: }
  865: 
  866: sub save_cache {
  867:     &purge_remembered();
  868:     #&Apache::loncommon::validate_page();
  869:     undef(%env);
  870:     undef($env_loaded);
  871: }
  872: 
  873: my $to_remember=-1;
  874: my %remembered;
  875: my %accessed;
  876: my $kicks=0;
  877: my $hits=0;
  878: sub devalidate_cache_new {
  879:     my ($name,$id,$debug) = @_;
  880:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  881:     $id=&escape($name.':'.$id);
  882:     $memcache->delete($id);
  883:     delete($remembered{$id});
  884:     delete($accessed{$id});
  885: }
  886: 
  887: sub is_cached_new {
  888:     my ($name,$id,$debug) = @_;
  889:     $id=&escape($name.':'.$id);
  890:     if (exists($remembered{$id})) {
  891: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  892: 	$accessed{$id}=[&gettimeofday()];
  893: 	$hits++;
  894: 	return ($remembered{$id},1);
  895:     }
  896:     my $value = $memcache->get($id);
  897:     if (!(defined($value))) {
  898: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  899: 	return (undef,undef);
  900:     }
  901:     if ($value eq '__undef__') {
  902: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  903: 	$value=undef;
  904:     }
  905:     &make_room($id,$value,$debug);
  906:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  907:     return ($value,1);
  908: }
  909: 
  910: sub do_cache_new {
  911:     my ($name,$id,$value,$time,$debug) = @_;
  912:     $id=&escape($name.':'.$id);
  913:     my $setvalue=$value;
  914:     if (!defined($setvalue)) {
  915: 	$setvalue='__undef__';
  916:     }
  917:     if (!defined($time) ) {
  918: 	$time=600;
  919:     }
  920:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  921:     $memcache->set($id,$setvalue,$time);
  922:     # need to make a copy of $value
  923:     #&make_room($id,$value,$debug);
  924:     return $value;
  925: }
  926: 
  927: sub make_room {
  928:     my ($id,$value,$debug)=@_;
  929:     $remembered{$id}=$value;
  930:     if ($to_remember<0) { return; }
  931:     $accessed{$id}=[&gettimeofday()];
  932:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  933:     my $to_kick;
  934:     my $max_time=0;
  935:     foreach my $other (keys(%accessed)) {
  936: 	if (&tv_interval($accessed{$other}) > $max_time) {
  937: 	    $to_kick=$other;
  938: 	    $max_time=&tv_interval($accessed{$other});
  939: 	}
  940:     }
  941:     delete($remembered{$to_kick});
  942:     delete($accessed{$to_kick});
  943:     $kicks++;
  944:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  945:     return;
  946: }
  947: 
  948: sub purge_remembered {
  949:     #&logthis("Tossing ".scalar(keys(%remembered)));
  950:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  951:     undef(%remembered);
  952:     undef(%accessed);
  953: }
  954: # ------------------------------------- Read an entry from a user's environment
  955: 
  956: sub userenvironment {
  957:     my ($udom,$unam,@what)=@_;
  958:     my %returnhash=();
  959:     my @answer=split(/\&/,
  960:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  961:                       &homeserver($unam,$udom)));
  962:     my $i;
  963:     for ($i=0;$i<=$#what;$i++) {
  964: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  965:     }
  966:     return %returnhash;
  967: }
  968: 
  969: # ---------------------------------------------------------- Get a studentphoto
  970: sub studentphoto {
  971:     my ($udom,$unam,$ext) = @_;
  972:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  973:     if (defined($env{'request.course.id'})) {
  974:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
  975:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
  976:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
  977:             } else {
  978:                 my ($result,$perm_reqd)=
  979: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
  980:                 if ($result eq 'ok') {
  981:                     if (!($perm_reqd eq 'yes')) {
  982:                         return(&retrievestudentphoto($udom,$unam,$ext));
  983:                     }
  984:                 }
  985:             }
  986:         }
  987:     } else {
  988:         my ($result,$perm_reqd) = 
  989: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
  990:         if ($result eq 'ok') {
  991:             if (!($perm_reqd eq 'yes')) {
  992:                 return(&retrievestudentphoto($udom,$unam,$ext));
  993:             }
  994:         }
  995:     }
  996:     return '/adm/lonKaputt/lonlogo_broken.gif';
  997: }
  998: 
  999: sub retrievestudentphoto {
 1000:     my ($udom,$unam,$ext,$type) = @_;
 1001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1002:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1003:     if ($ret eq 'ok') {
 1004:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1005:         if ($type eq 'thumbnail') {
 1006:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1007:         }
 1008:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1009:         return $tokenurl;
 1010:     } else {
 1011:         if ($type eq 'thumbnail') {
 1012:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1013:         } else { 
 1014:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1015:         }
 1016:     }
 1017: }
 1018: 
 1019: # -------------------------------------------------------------------- New chat
 1020: 
 1021: sub chatsend {
 1022:     my ($newentry,$anon,$group)=@_;
 1023:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1024:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1025:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1026:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1027: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1028: 		   &escape($newentry)).':'.$group,$chome);
 1029: }
 1030: 
 1031: # ------------------------------------------ Find current version of a resource
 1032: 
 1033: sub getversion {
 1034:     my $fname=&clutter(shift);
 1035:     unless ($fname=~/^\/res\//) { return -1; }
 1036:     return &currentversion(&filelocation('',$fname));
 1037: }
 1038: 
 1039: sub currentversion {
 1040:     my $fname=shift;
 1041:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1042:     if (defined($cached)) { return $result; }
 1043:     my $author=$fname;
 1044:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1045:     my ($udom,$uname)=split(/\//,$author);
 1046:     my $home=homeserver($uname,$udom);
 1047:     if ($home eq 'no_host') { 
 1048:         return -1; 
 1049:     }
 1050:     my $answer=reply("currentversion:$fname",$home);
 1051:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1052: 	return -1;
 1053:     }
 1054:     return &do_cache_new('resversion',$fname,$answer,600);
 1055: }
 1056: 
 1057: # ----------------------------- Subscribe to a resource, return URL if possible
 1058: 
 1059: sub subscribe {
 1060:     my $fname=shift;
 1061:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1062:     $fname=~s/[\n\r]//g;
 1063:     my $author=$fname;
 1064:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1065:     my ($udom,$uname)=split(/\//,$author);
 1066:     my $home=homeserver($uname,$udom);
 1067:     if ($home eq 'no_host') {
 1068:         return 'not_found';
 1069:     }
 1070:     my $answer=reply("sub:$fname",$home);
 1071:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1072: 	$answer.=' by '.$home;
 1073:     }
 1074:     return $answer;
 1075: }
 1076:     
 1077: # -------------------------------------------------------------- Replicate file
 1078: 
 1079: sub repcopy {
 1080:     my $filename=shift;
 1081:     $filename=~s/\/+/\//g;
 1082:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1083:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1084:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1085: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1086: 	return &repcopy_userfile($filename);
 1087:     }
 1088:     $filename=~s/[\n\r]//g;
 1089:     my $transname="$filename.in.transfer";
 1090:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1091:     my $remoteurl=subscribe($filename);
 1092:     if ($remoteurl =~ /^con_lost by/) {
 1093: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1094:            return 'unavailable';
 1095:     } elsif ($remoteurl eq 'not_found') {
 1096: 	   #&logthis("Subscribe returned not_found: $filename");
 1097: 	   return 'not_found';
 1098:     } elsif ($remoteurl =~ /^rejected by/) {
 1099: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1100:            return 'forbidden';
 1101:     } elsif ($remoteurl eq 'directory') {
 1102:            return 'ok';
 1103:     } else {
 1104:         my $author=$filename;
 1105:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1106:         my ($udom,$uname)=split(/\//,$author);
 1107:         my $home=homeserver($uname,$udom);
 1108:         unless ($home eq $perlvar{'lonHostID'}) {
 1109:            my @parts=split(/\//,$filename);
 1110:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1111:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1112:                &logthis("Malconfiguration for replication: $filename");
 1113: 	       return 'bad_request';
 1114:            }
 1115:            my $count;
 1116:            for ($count=5;$count<$#parts;$count++) {
 1117:                $path.="/$parts[$count]";
 1118:                if ((-e $path)!=1) {
 1119: 		   mkdir($path,0777);
 1120:                }
 1121:            }
 1122:            my $ua=new LWP::UserAgent;
 1123:            my $request=new HTTP::Request('GET',"$remoteurl");
 1124:            my $response=$ua->request($request,$transname);
 1125:            if ($response->is_error()) {
 1126: 	       unlink($transname);
 1127:                my $message=$response->status_line;
 1128:                &logthis("<font color=\"blue\">WARNING:"
 1129:                        ." LWP get: $message: $filename</font>");
 1130:                return 'unavailable';
 1131:            } else {
 1132: 	       if ($remoteurl!~/\.meta$/) {
 1133:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1134:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1135:                   if ($mresponse->is_error()) {
 1136: 		      unlink($filename.'.meta');
 1137:                       &logthis(
 1138:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1139:                   }
 1140: 	       }
 1141:                rename($transname,$filename);
 1142:                return 'ok';
 1143:            }
 1144:        }
 1145:     }
 1146: }
 1147: 
 1148: # ------------------------------------------------ Get server side include body
 1149: sub ssi_body {
 1150:     my ($filelink,%form)=@_;
 1151:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1152:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1153:     }
 1154:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1155:                                      &ssi($filelink,%form));
 1156:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1157:     $output=~s/^.*?\<body[^\>]*\>//si;
 1158:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1159:     return $output;
 1160: }
 1161: 
 1162: # --------------------------------------------------------- Server Side Include
 1163: 
 1164: sub absolute_url {
 1165:     my ($host_name) = @_;
 1166:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1167:     if ($host_name eq '') {
 1168: 	$host_name = $ENV{'SERVER_NAME'};
 1169:     }
 1170:     return $protocol.$host_name;
 1171: }
 1172: 
 1173: sub absolute_url {
 1174:     my ($host_name) = @_;
 1175:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1176:     if ($host_name eq '') {
 1177: 	$host_name = $ENV{'SERVER_NAME'};
 1178:     }
 1179:     return $protocol.$host_name;
 1180: }
 1181: 
 1182: sub ssi {
 1183: 
 1184:     my ($fn,%form)=@_;
 1185: 
 1186:     my $ua=new LWP::UserAgent;
 1187:     
 1188:     my $request;
 1189: 
 1190:     $form{'no_update_last_known'}=1;
 1191: 
 1192:     if (%form) {
 1193:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1194:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1195:     } else {
 1196:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1197:     }
 1198: 
 1199:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1200:     my $response=$ua->request($request);
 1201: 
 1202:     return $response->content;
 1203: }
 1204: 
 1205: sub externalssi {
 1206:     my ($url)=@_;
 1207:     my $ua=new LWP::UserAgent;
 1208:     my $request=new HTTP::Request('GET',$url);
 1209:     my $response=$ua->request($request);
 1210:     return $response->content;
 1211: }
 1212: 
 1213: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1214: 
 1215: sub allowuploaded {
 1216:     my ($srcurl,$url)=@_;
 1217:     $url=&clutter(&declutter($url));
 1218:     my $dir=$url;
 1219:     $dir=~s/\/[^\/]+$//;
 1220:     my %httpref=();
 1221:     my $httpurl=&hreflocation('',$url);
 1222:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1223:     &Apache::lonnet::appenv(%httpref);
 1224: }
 1225: 
 1226: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1227: # input: action, courseID, current domain, intended
 1228: #        path to file, source of file, instruction to parse file for objects,
 1229: #        ref to hash for embedded objects,
 1230: #        ref to hash for codebase of java objects.
 1231: #
 1232: # output: url to file (if action was uploaddoc), 
 1233: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1234: #
 1235: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1236: # course.
 1237: #
 1238: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1239: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1240: #          course's home server.
 1241: #
 1242: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1243: #          be copied from $source (current location) to 
 1244: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1245: #         and will then be copied to
 1246: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1247: #         course's home server.
 1248: #
 1249: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1250: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1251: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1252: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1253: #         in course's home server.
 1254: #
 1255: 
 1256: sub process_coursefile {
 1257:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1258:     my $fetchresult;
 1259:     my $home=&homeserver($docuname,$docudom);
 1260:     if ($action eq 'propagate') {
 1261:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1262: 			     $home);
 1263:     } else {
 1264:         my $fpath = '';
 1265:         my $fname = $file;
 1266:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1267:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1268:         my $filepath = &build_filepath($fpath);
 1269:         if ($action eq 'copy') {
 1270:             if ($source eq '') {
 1271:                 $fetchresult = 'no source file';
 1272:                 return $fetchresult;
 1273:             } else {
 1274:                 my $destination = $filepath.'/'.$fname;
 1275:                 rename($source,$destination);
 1276:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1277:                                  $home);
 1278:             }
 1279:         } elsif ($action eq 'uploaddoc') {
 1280:             open(my $fh,'>'.$filepath.'/'.$fname);
 1281:             print $fh $env{'form.'.$source};
 1282:             close($fh);
 1283:             if ($parser eq 'parse') {
 1284:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1285:                 unless ($parse_result eq 'ok') {
 1286:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1287:                 }
 1288:             }
 1289:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1290:                                  $home);
 1291:             if ($fetchresult eq 'ok') {
 1292:                 return '/uploaded/'.$fpath.'/'.$fname;
 1293:             } else {
 1294:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1295:                         ' to host '.$home.': '.$fetchresult);
 1296:                 return '/adm/notfound.html';
 1297:             }
 1298:         }
 1299:     }
 1300:     unless ( $fetchresult eq 'ok') {
 1301:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1302:              ' to host '.$home.': '.$fetchresult);
 1303:     }
 1304:     return $fetchresult;
 1305: }
 1306: 
 1307: sub build_filepath {
 1308:     my ($fpath) = @_;
 1309:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1310:     unless ($fpath eq '') {
 1311:         my @parts=split('/',$fpath);
 1312:         foreach my $part (@parts) {
 1313:             $filepath.= '/'.$part;
 1314:             if ((-e $filepath)!=1) {
 1315:                 mkdir($filepath,0777);
 1316:             }
 1317:         }
 1318:     }
 1319:     return $filepath;
 1320: }
 1321: 
 1322: sub store_edited_file {
 1323:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1324:     my $file = $primary_url;
 1325:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1326:     my $fpath = '';
 1327:     my $fname = $file;
 1328:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1329:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1330:     my $filepath = &build_filepath($fpath);
 1331:     open(my $fh,'>'.$filepath.'/'.$fname);
 1332:     print $fh $content;
 1333:     close($fh);
 1334:     my $home=&homeserver($docuname,$docudom);
 1335:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1336: 			  $home);
 1337:     if ($$fetchresult eq 'ok') {
 1338:         return '/uploaded/'.$fpath.'/'.$fname;
 1339:     } else {
 1340:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1341: 		 ' to host '.$home.': '.$$fetchresult);
 1342:         return '/adm/notfound.html';
 1343:     }
 1344: }
 1345: 
 1346: sub clean_filename {
 1347:     my ($fname)=@_;
 1348: # Replace Windows backslashes by forward slashes
 1349:     $fname=~s/\\/\//g;
 1350: # Get rid of everything but the actual filename
 1351:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1352: # Replace spaces by underscores
 1353:     $fname=~s/\s+/\_/g;
 1354: # Replace all other weird characters by nothing
 1355:     $fname=~s/[^\w\.\-]//g;
 1356: # Replace all .\d. sequences with _\d. so they no longer look like version
 1357: # numbers
 1358:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1359:     return $fname;
 1360: }
 1361: 
 1362: # --------------- Take an uploaded file and put it into the userfiles directory
 1363: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1364: #                    the desired filenam is in $env{"form.$formname.filename"}
 1365: #        $coursedoc - if true up to the current course
 1366: #                     if false
 1367: #        $subdir - directory in userfile to store the file into
 1368: #        $parser, $allfiles, $codebase - unknown
 1369: #
 1370: # output: url of file in userspace, or error: <message> 
 1371: #             or /adm/notfound.html if failure to upload occurse
 1372: 
 1373: 
 1374: sub userfileupload {
 1375:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1376:     if (!defined($subdir)) { $subdir='unknown'; }
 1377:     my $fname=$env{'form.'.$formname.'.filename'};
 1378:     $fname=&clean_filename($fname);
 1379: # See if there is anything left
 1380:     unless ($fname) { return 'error: no uploaded file'; }
 1381:     chop($env{'form.'.$formname});
 1382:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1383:         my $now = time;
 1384:         my $filepath = 'tmp/helprequests/'.$now;
 1385:         my @parts=split(/\//,$filepath);
 1386:         my $fullpath = $perlvar{'lonDaemons'};
 1387:         for (my $i=0;$i<@parts;$i++) {
 1388:             $fullpath .= '/'.$parts[$i];
 1389:             if ((-e $fullpath)!=1) {
 1390:                 mkdir($fullpath,0777);
 1391:             }
 1392:         }
 1393:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1394:         print $fh $env{'form.'.$formname};
 1395:         close($fh);
 1396:         return $fullpath.'/'.$fname;
 1397:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1398:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1399:                        '_'.$env{'user.domain'}.'/pending';
 1400:         my @parts=split(/\//,$filepath);
 1401:         my $fullpath = $perlvar{'lonDaemons'};
 1402:         for (my $i=0;$i<@parts;$i++) {
 1403:             $fullpath .= '/'.$parts[$i];
 1404:             if ((-e $fullpath)!=1) {
 1405:                 mkdir($fullpath,0777);
 1406:             }
 1407:         }
 1408:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1409:         print $fh $env{'form.'.$formname};
 1410:         close($fh);
 1411:         return $fullpath.'/'.$fname;
 1412:     }
 1413:     
 1414: # Create the directory if not present
 1415:     $fname="$subdir/$fname";
 1416:     if ($coursedoc) {
 1417: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1418: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1419:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1420:             return &finishuserfileupload($docuname,$docudom,
 1421: 					 $formname,$fname,$parser,$allfiles,
 1422: 					 $codebase);
 1423:         } else {
 1424:             $fname=$env{'form.folder'}.'/'.$fname;
 1425:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1426: 				       $fname,$formname,$parser,
 1427: 				       $allfiles,$codebase);
 1428:         }
 1429:     } elsif (defined($destuname)) {
 1430:         my $docuname=$destuname;
 1431:         my $docudom=$destudom;
 1432: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1433: 				     $fname,$parser,$allfiles,$codebase);
 1434:         
 1435:     } else {
 1436:         my $docuname=$env{'user.name'};
 1437:         my $docudom=$env{'user.domain'};
 1438:         if (exists($env{'form.group'})) {
 1439:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1440:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1441:         }
 1442: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1443: 				     $fname,$parser,$allfiles,$codebase);
 1444:     }
 1445: }
 1446: 
 1447: sub finishuserfileupload {
 1448:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1449:     my $path=$docudom.'/'.$docuname.'/';
 1450:     my $filepath=$perlvar{'lonDocRoot'};
 1451:     my ($fnamepath,$file);
 1452:     $file=$fname;
 1453:     if ($fname=~m|/|) {
 1454:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1455: 	$path.=$fnamepath.'/';
 1456:     }
 1457:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1458:     my $count;
 1459:     for ($count=4;$count<=$#parts;$count++) {
 1460:         $filepath.="/$parts[$count]";
 1461:         if ((-e $filepath)!=1) {
 1462: 	    mkdir($filepath,0777);
 1463:         }
 1464:     }
 1465: # Save the file
 1466:     {
 1467: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1468: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1469: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1470: 	    return '/adm/notfound.html';
 1471: 	}
 1472: 	if (!print FH ($env{'form.'.$formname})) {
 1473: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1474: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1475: 	    return '/adm/notfound.html';
 1476: 	}
 1477: 	close(FH);
 1478:     }
 1479:     if ($parser eq 'parse') {
 1480:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1481: 						   $codebase);
 1482:         unless ($parse_result eq 'ok') {
 1483:             &logthis('Failed to parse '.$filepath.$file.
 1484: 		     ' for embedded media: '.$parse_result); 
 1485:         }
 1486:     }
 1487: # Notify homeserver to grep it
 1488: #
 1489:     my $docuhome=&homeserver($docuname,$docudom);
 1490:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1491:     if ($fetchresult eq 'ok') {
 1492: #
 1493: # Return the URL to it
 1494:         return '/uploaded/'.$path.$file;
 1495:     } else {
 1496:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1497: 		 ': '.$fetchresult);
 1498:         return '/adm/notfound.html';
 1499:     }    
 1500: }
 1501: 
 1502: sub extract_embedded_items {
 1503:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1504:     my @state = ();
 1505:     my %javafiles = (
 1506:                       codebase => '',
 1507:                       code => '',
 1508:                       archive => ''
 1509:                     );
 1510:     my %mediafiles = (
 1511:                       src => '',
 1512:                       movie => '',
 1513:                      );
 1514:     my $p;
 1515:     if ($content) {
 1516:         $p = HTML::LCParser->new($content);
 1517:     } else {
 1518:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1519:     }
 1520:     while (my $t=$p->get_token()) {
 1521: 	if ($t->[0] eq 'S') {
 1522: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1523: 	    push (@state, $tagname);
 1524:             if (lc($tagname) eq 'allow') {
 1525:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1526:             }
 1527: 	    if (lc($tagname) eq 'img') {
 1528: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1529: 	    }
 1530:             if (lc($tagname) eq 'script') {
 1531:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1532:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1533:                 } else {
 1534:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1535:                 }
 1536:             }
 1537:             if (lc($tagname) eq 'link') {
 1538:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1539:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1540:                 }
 1541:             }
 1542: 	    if (lc($tagname) eq 'object' ||
 1543: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1544: 		foreach my $item (keys(%javafiles)) {
 1545: 		    $javafiles{$item} = '';
 1546: 		}
 1547: 	    }
 1548: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1549: 		my $name = lc($attr->{'name'});
 1550: 		foreach my $item (keys(%javafiles)) {
 1551: 		    if ($name eq $item) {
 1552: 			$javafiles{$item} = $attr->{'value'};
 1553: 			last;
 1554: 		    }
 1555: 		}
 1556: 		foreach my $item (keys(%mediafiles)) {
 1557: 		    if ($name eq $item) {
 1558: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1559: 			last;
 1560: 		    }
 1561: 		}
 1562: 	    }
 1563: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1564: 		foreach my $item (keys(%javafiles)) {
 1565: 		    if ($attr->{$item}) {
 1566: 			$javafiles{$item} = $attr->{$item};
 1567: 			last;
 1568: 		    }
 1569: 		}
 1570: 		foreach my $item (keys(%mediafiles)) {
 1571: 		    if ($attr->{$item}) {
 1572: 			&add_filetype($allfiles,$attr->{$item},$item);
 1573: 			last;
 1574: 		    }
 1575: 		}
 1576: 	    }
 1577: 	} elsif ($t->[0] eq 'E') {
 1578: 	    my ($tagname) = ($t->[1]);
 1579: 	    if ($javafiles{'codebase'} ne '') {
 1580: 		$javafiles{'codebase'} .= '/';
 1581: 	    }  
 1582: 	    if (lc($tagname) eq 'applet' ||
 1583: 		lc($tagname) eq 'object' ||
 1584: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1585: 		) {
 1586: 		foreach my $item (keys(%javafiles)) {
 1587: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1588: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1589: 			&add_filetype($allfiles,$file,$item);
 1590: 		    }
 1591: 		}
 1592: 	    } 
 1593: 	    pop @state;
 1594: 	}
 1595:     }
 1596:     return 'ok';
 1597: }
 1598: 
 1599: sub add_filetype {
 1600:     my ($allfiles,$file,$type)=@_;
 1601:     if (exists($allfiles->{$file})) {
 1602: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1603: 	    push(@{$allfiles->{$file}}, &escape($type));
 1604: 	}
 1605:     } else {
 1606: 	@{$allfiles->{$file}} = (&escape($type));
 1607:     }
 1608: }
 1609: 
 1610: sub removeuploadedurl {
 1611:     my ($url)=@_;
 1612:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1613:     return &removeuserfile($uname,$udom,$fname);
 1614: }
 1615: 
 1616: sub removeuserfile {
 1617:     my ($docuname,$docudom,$fname)=@_;
 1618:     my $home=&homeserver($docuname,$docudom);
 1619:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1620: }
 1621: 
 1622: sub mkdiruserfile {
 1623:     my ($docuname,$docudom,$dir)=@_;
 1624:     my $home=&homeserver($docuname,$docudom);
 1625:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1626: }
 1627: 
 1628: sub renameuserfile {
 1629:     my ($docuname,$docudom,$old,$new)=@_;
 1630:     my $home=&homeserver($docuname,$docudom);
 1631:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1632: 		  &escape("$new"),$home);
 1633: }
 1634: 
 1635: # ------------------------------------------------------------------------- Log
 1636: 
 1637: sub log {
 1638:     my ($dom,$nam,$hom,$what)=@_;
 1639:     return critical("log:$dom:$nam:$what",$hom);
 1640: }
 1641: 
 1642: # ------------------------------------------------------------------ Course Log
 1643: #
 1644: # This routine flushes several buffers of non-mission-critical nature
 1645: #
 1646: 
 1647: sub flushcourselogs {
 1648:     &logthis('Flushing log buffers');
 1649: #
 1650: # course logs
 1651: # This is a log of all transactions in a course, which can be used
 1652: # for data mining purposes
 1653: #
 1654: # It also collects the courseid database, which lists last transaction
 1655: # times and course titles for all courseids
 1656: #
 1657:     my %courseidbuffer=();
 1658:     foreach (keys %courselogs) {
 1659:         my $crsid=$_;
 1660:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1661: 		          &escape($courselogs{$crsid}),
 1662: 		          $coursehombuf{$crsid}) eq 'ok') {
 1663: 	    delete $courselogs{$crsid};
 1664:         } else {
 1665:             &logthis('Failed to flush log buffer for '.$crsid);
 1666:             if (length($courselogs{$crsid})>40000) {
 1667:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1668:                         " exceeded maximum size, deleting.</font>");
 1669:                delete $courselogs{$crsid};
 1670:             }
 1671:         }
 1672:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1673:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1674: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1675:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1676:         } else {
 1677:            $courseidbuffer{$coursehombuf{$crsid}}=
 1678: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1679:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1680:         }
 1681:     }
 1682: #
 1683: # Write course id database (reverse lookup) to homeserver of courses 
 1684: # Is used in pickcourse
 1685: #
 1686:     foreach (keys %courseidbuffer) {
 1687:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1688:     }
 1689: #
 1690: # File accesses
 1691: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1692: #
 1693:     foreach my $entry (keys(%accesshash)) {
 1694:         if ($entry =~ /___count$/) {
 1695:             my ($dom,$name);
 1696:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1697:             if (! defined($dom) || $dom eq '' || 
 1698:                 ! defined($name) || $name eq '') {
 1699:                 my $cid = $env{'request.course.id'};
 1700:                 $dom  = $env{'request.'.$cid.'.domain'};
 1701:                 $name = $env{'request.'.$cid.'.num'};
 1702:             }
 1703:             my $value = $accesshash{$entry};
 1704:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1705:             my %temphash=($url => $value);
 1706:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1707:             if ($result eq 'ok') {
 1708:                 delete $accesshash{$entry};
 1709:             } elsif ($result eq 'unknown_cmd') {
 1710:                 # Target server has old code running on it.
 1711:                 my %temphash=($entry => $value);
 1712:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1713:                     delete $accesshash{$entry};
 1714:                 }
 1715:             }
 1716:         } else {
 1717:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1718:             my %temphash=($entry => $accesshash{$entry});
 1719:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1720:                 delete $accesshash{$entry};
 1721:             }
 1722:         }
 1723:     }
 1724: #
 1725: # Roles
 1726: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1727: #
 1728:     foreach (keys %userrolehash) {
 1729:         my $entry=$_;
 1730:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1731: 	    split(/\:/,$entry);
 1732:         if (&Apache::lonnet::put('nohist_userroles',
 1733:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1734:                 $rudom,$runame) eq 'ok') {
 1735: 	    delete $userrolehash{$entry};
 1736:         }
 1737:     }
 1738: #
 1739: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1740: #
 1741:     my %domrolebuffer = ();
 1742:     foreach my $entry (keys %domainrolehash) {
 1743:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1744:         if ($domrolebuffer{$rudom}) {
 1745:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1746:                       '='.&escape($domainrolehash{$entry});
 1747:         } else {
 1748:             $domrolebuffer{$rudom}.=&escape($entry).
 1749:                       '='.&escape($domainrolehash{$entry});
 1750:         }
 1751:         delete $domainrolehash{$entry};
 1752:     }
 1753:     foreach my $dom (keys(%domrolebuffer)) {
 1754:         foreach my $tryserver (keys %libserv) {
 1755:             if ($hostdom{$tryserver} eq $dom) {
 1756:                 unless (&reply('domroleput:'.$dom.':'.
 1757:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1758:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1759:                 }
 1760:             }
 1761:         }
 1762:     }
 1763:     $dumpcount++;
 1764: }
 1765: 
 1766: sub courselog {
 1767:     my $what=shift;
 1768:     $what=time.':'.$what;
 1769:     unless ($env{'request.course.id'}) { return ''; }
 1770:     $coursedombuf{$env{'request.course.id'}}=
 1771:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1772:     $coursenumbuf{$env{'request.course.id'}}=
 1773:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1774:     $coursehombuf{$env{'request.course.id'}}=
 1775:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1776:     $coursedescrbuf{$env{'request.course.id'}}=
 1777:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1778:     $courseinstcodebuf{$env{'request.course.id'}}=
 1779:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1780:     $courseownerbuf{$env{'request.course.id'}}=
 1781:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1782:     $coursetypebuf{$env{'request.course.id'}}=
 1783:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1784:     if (defined $courselogs{$env{'request.course.id'}}) {
 1785: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1786:     } else {
 1787: 	$courselogs{$env{'request.course.id'}}.=$what;
 1788:     }
 1789:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1790: 	&flushcourselogs();
 1791:     }
 1792: }
 1793: 
 1794: sub courseacclog {
 1795:     my $fnsymb=shift;
 1796:     unless ($env{'request.course.id'}) { return ''; }
 1797:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1798:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1799:         $what.=':POST';
 1800:         # FIXME: Probably ought to escape things....
 1801: 	foreach (keys %env) {
 1802:             if ($_=~/^form\.(.*)/) {
 1803: 		$what.=':'.$1.'='.$env{$_};
 1804:             }
 1805:         }
 1806:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1807:         # FIXME: We should not be depending on a form parameter that someone
 1808:         # editing lonsearchcat.pm might change in the future.
 1809:         if ($env{'form.phase'} eq 'course_search') {
 1810:             $what.= ':POST';
 1811:             # FIXME: Probably ought to escape things....
 1812:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1813:                                  'crsdiscuss') {
 1814:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1815:             }
 1816:         }
 1817:     }
 1818:     &courselog($what);
 1819: }
 1820: 
 1821: sub countacc {
 1822:     my $url=&declutter(shift);
 1823:     return if (! defined($url) || $url eq '');
 1824:     unless ($env{'request.course.id'}) { return ''; }
 1825:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1826:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1827:     $accesshash{$key}++;
 1828: }
 1829: 
 1830: sub linklog {
 1831:     my ($from,$to)=@_;
 1832:     $from=&declutter($from);
 1833:     $to=&declutter($to);
 1834:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1835:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1836: }
 1837:   
 1838: sub userrolelog {
 1839:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1840:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1841:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1842:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1843:         ($trole=~/^ta/)) {
 1844:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1845:        $userrolehash
 1846:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1847:                     =$tend.':'.$tstart;
 1848:     }
 1849:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1850:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1851:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1852:         ($trole=~/^sc/)) {
 1853:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1854:        $domainrolehash
 1855:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1856:                     = $tend.':'.$tstart;
 1857:     }
 1858: }
 1859: 
 1860: sub get_course_adv_roles {
 1861:     my $cid=shift;
 1862:     $cid=$env{'request.course.id'} unless (defined($cid));
 1863:     my %coursehash=&coursedescription($cid);
 1864:     my %nothide=();
 1865:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1866: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1867:     }
 1868:     my %returnhash=();
 1869:     my %dumphash=
 1870:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1871:     my $now=time;
 1872:     foreach (keys %dumphash) {
 1873: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1874:         if (($tstart) && ($tstart<0)) { next; }
 1875:         if (($tend) && ($tend<$now)) { next; }
 1876:         if (($tstart) && ($now<$tstart)) { next; }
 1877:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1878: 	if ($username eq '' || $domain eq '') { next; }
 1879: 	if ((&privileged($username,$domain)) && 
 1880: 	    (!$nothide{$username.':'.$domain})) { next; }
 1881: 	if ($role eq 'cr') { next; }
 1882:         my $key=&plaintext($role);
 1883:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1884:         if ($returnhash{$key}) {
 1885: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1886:         } else {
 1887:             $returnhash{$key}=$username.':'.$domain;
 1888:         }
 1889:      }
 1890:     return %returnhash;
 1891: }
 1892: 
 1893: sub get_my_roles {
 1894:     my ($uname,$udom)=@_;
 1895:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1896:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1897:     my %dumphash=
 1898:             &dump('nohist_userroles',$udom,$uname);
 1899:     my %returnhash=();
 1900:     my $now=time;
 1901:     foreach (keys %dumphash) {
 1902: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1903:         if (($tstart) && ($tstart<0)) { next; }
 1904:         if (($tend) && ($tend<$now)) { next; }
 1905:         if (($tstart) && ($now<$tstart)) { next; }
 1906:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1907: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1908:      }
 1909:     return %returnhash;
 1910: }
 1911: 
 1912: # ----------------------------------------------------- Frontpage Announcements
 1913: #
 1914: #
 1915: 
 1916: sub postannounce {
 1917:     my ($server,$text)=@_;
 1918:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1919:     unless ($text=~/\w/) { $text=''; }
 1920:     return &reply('setannounce:'.&escape($text),$server);
 1921: }
 1922: 
 1923: sub getannounce {
 1924: 
 1925:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1926: 	my $announcement='';
 1927: 	while (<$fh>) { $announcement .=$_; }
 1928: 	close($fh);
 1929: 	if ($announcement=~/\w/) { 
 1930: 	    return 
 1931:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1932:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1933: 	} else {
 1934: 	    return '';
 1935: 	}
 1936:     } else {
 1937: 	return '';
 1938:     }
 1939: }
 1940: 
 1941: # ---------------------------------------------------------- Course ID routines
 1942: # Deal with domain's nohist_courseid.db files
 1943: #
 1944: 
 1945: sub courseidput {
 1946:     my ($domain,$what,$coursehome)=@_;
 1947:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1948: }
 1949: 
 1950: sub courseiddump {
 1951:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
 1952:     my %returnhash=();
 1953:     unless ($domfilter) { $domfilter=''; }
 1954:     foreach my $tryserver (keys %libserv) {
 1955:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1956: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1957: 	        foreach (
 1958:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1959: 			       $sincefilter.':'.&escape($descfilter).':'.
 1960:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
 1961:                                $tryserver))) {
 1962: 		    my ($key,$value)=split(/\=/,$_);
 1963:                     if (($key) && ($value)) {
 1964: 		        $returnhash{&unescape($key)}=$value;
 1965:                     }
 1966:                 }
 1967:             }
 1968:         }
 1969:     }
 1970:     return %returnhash;
 1971: }
 1972: 
 1973: # ---------------------------------------------------------- DC e-mail
 1974: 
 1975: sub dcmailput {
 1976:     my ($domain,$msgid,$message,$server)=@_;
 1977:     my $status = &Apache::lonnet::critical(
 1978:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 1979:        &escape($message),$server);
 1980:     return $status;
 1981: }
 1982: 
 1983: sub dcmaildump {
 1984:     my ($dom,$startdate,$enddate,$senders) = @_;
 1985:     my %returnhash=();
 1986:     if (exists($domain_primary{$dom})) {
 1987:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 1988:                                                          &escape($enddate).':';
 1989: 	my @esc_senders=map { &escape($_)} @$senders;
 1990: 	$cmd.=&escape(join('&',@esc_senders));
 1991: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 1992:             my ($key,$value) = split(/\=/,$_);
 1993:             if (($key) && ($value)) {
 1994:                 $returnhash{&unescape($key)} = &unescape($value);
 1995:             }
 1996:         }
 1997:     }
 1998:     return %returnhash;
 1999: }
 2000: # ---------------------------------------------------------- Domain roles
 2001: 
 2002: sub get_domain_roles {
 2003:     my ($dom,$roles,$startdate,$enddate)=@_;
 2004:     if (undef($startdate) || $startdate eq '') {
 2005:         $startdate = '.';
 2006:     }
 2007:     if (undef($enddate) || $enddate eq '') {
 2008:         $enddate = '.';
 2009:     }
 2010:     my $rolelist = join(':',@{$roles});
 2011:     my %personnel = ();
 2012:     foreach my $tryserver (keys(%libserv)) {
 2013:         if ($hostdom{$tryserver} eq $dom) {
 2014:             %{$personnel{$tryserver}}=();
 2015:             foreach (
 2016:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2017:                    &escape($startdate).':'.&escape($enddate).':'.
 2018:                    &escape($rolelist), $tryserver))) {
 2019:                 my($key,$value) = split(/\=/,$_);
 2020:                 if (($key) && ($value)) {
 2021:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2022:                 }
 2023:             }
 2024:         }
 2025:     }
 2026:     return %personnel;
 2027: }
 2028: 
 2029: # ----------------------------------------------------------- Check out an item
 2030: 
 2031: sub get_first_access {
 2032:     my ($type,$argsymb)=@_;
 2033:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2034:     if ($argsymb) { $symb=$argsymb; }
 2035:     my ($map,$id,$res)=&decode_symb($symb);
 2036:     if ($type eq 'map') {
 2037: 	$res=&symbread($map);
 2038:     } else {
 2039: 	$res=$symb;
 2040:     }
 2041:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2042:     return $times{"$courseid\0$res"};
 2043: }
 2044: 
 2045: sub set_first_access {
 2046:     my ($type)=@_;
 2047:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2048:     my ($map,$id,$res)=&decode_symb($symb);
 2049:     if ($type eq 'map') {
 2050: 	$res=&symbread($map);
 2051:     } else {
 2052: 	$res=$symb;
 2053:     }
 2054:     my $firstaccess=&get_first_access($type,$symb);
 2055:     if (!$firstaccess) {
 2056: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2057:     }
 2058:     return 'already_set';
 2059: }
 2060: 
 2061: sub checkout {
 2062:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2063:     my $now=time;
 2064:     my $lonhost=$perlvar{'lonHostID'};
 2065:     my $infostr=&escape(
 2066:                  'CHECKOUTTOKEN&'.
 2067:                  $tuname.'&'.
 2068:                  $tudom.'&'.
 2069:                  $tcrsid.'&'.
 2070:                  $symb.'&'.
 2071: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2072:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2073:     if ($token=~/^error\:/) { 
 2074:         &logthis("<font color=\"blue\">WARNING: ".
 2075:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2076:                  "</font>");
 2077:         return ''; 
 2078:     }
 2079: 
 2080:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2081:     $token=~tr/a-z/A-Z/;
 2082: 
 2083:     my %infohash=('resource.0.outtoken' => $token,
 2084:                   'resource.0.checkouttime' => $now,
 2085:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2086: 
 2087:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2088:        return '';
 2089:     } else {
 2090:         &logthis("<font color=\"blue\">WARNING: ".
 2091:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2092:                  "</font>");
 2093:     }    
 2094: 
 2095:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2096:                          &escape('Checkout '.$infostr.' - '.
 2097:                                                  $token)) ne 'ok') {
 2098: 	return '';
 2099:     } else {
 2100:         &logthis("<font color=\"blue\">WARNING: ".
 2101:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2102:                  "</font>");
 2103:     }
 2104:     return $token;
 2105: }
 2106: 
 2107: # ------------------------------------------------------------ Check in an item
 2108: 
 2109: sub checkin {
 2110:     my $token=shift;
 2111:     my $now=time;
 2112:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2113:     $lonhost=~tr/A-Z/a-z/;
 2114:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2115:     $dtoken=~s/\W/\_/g;
 2116:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2117:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2118: 
 2119:     unless (($tuname) && ($tudom)) {
 2120:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2121:         return '';
 2122:     }
 2123:     
 2124:     unless (&allowed('mgr',$tcrsid)) {
 2125:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2126:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2127:         return '';
 2128:     }
 2129: 
 2130:     my %infohash=('resource.0.intoken' => $token,
 2131:                   'resource.0.checkintime' => $now,
 2132:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2133: 
 2134:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2135:        return '';
 2136:     }    
 2137: 
 2138:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2139:                          &escape('Checkin - '.$token)) ne 'ok') {
 2140: 	return '';
 2141:     }
 2142: 
 2143:     return ($symb,$tuname,$tudom,$tcrsid);    
 2144: }
 2145: 
 2146: # --------------------------------------------- Set Expire Date for Spreadsheet
 2147: 
 2148: sub expirespread {
 2149:     my ($uname,$udom,$stype,$usymb)=@_;
 2150:     my $cid=$env{'request.course.id'}; 
 2151:     if ($cid) {
 2152:        my $now=time;
 2153:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2154:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2155:                             $env{'course.'.$cid.'.num'}.
 2156: 	        	    ':nohist_expirationdates:'.
 2157:                             &escape($key).'='.$now,
 2158:                             $env{'course.'.$cid.'.home'})
 2159:     }
 2160:     return 'ok';
 2161: }
 2162: 
 2163: # ----------------------------------------------------- Devalidate Spreadsheets
 2164: 
 2165: sub devalidate {
 2166:     my ($symb,$uname,$udom)=@_;
 2167:     my $cid=$env{'request.course.id'}; 
 2168:     if ($cid) {
 2169:         # delete the stored spreadsheets for
 2170:         # - the student level sheet of this user in course's homespace
 2171:         # - the assessment level sheet for this resource 
 2172:         #   for this user in user's homespace
 2173: 	# - current conditional state info
 2174: 	my $key=$uname.':'.$udom.':';
 2175:         my $status=
 2176: 	    &del('nohist_calculatedsheets',
 2177: 		 [$key.'studentcalc:'],
 2178: 		 $env{'course.'.$cid.'.domain'},
 2179: 		 $env{'course.'.$cid.'.num'})
 2180: 		.' '.
 2181: 	    &del('nohist_calculatedsheets_'.$cid,
 2182: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2183:         unless ($status eq 'ok ok') {
 2184:            &logthis('Could not devalidate spreadsheet '.
 2185:                     $uname.' at '.$udom.' for '.
 2186: 		    $symb.': '.$status);
 2187:         }
 2188: 	&delenv('user.state.'.$cid);
 2189:     }
 2190: }
 2191: 
 2192: sub get_scalar {
 2193:     my ($string,$end) = @_;
 2194:     my $value;
 2195:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2196: 	$value = $1;
 2197:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2198: 	$value = $1;
 2199:     }
 2200:     return &unescape($value);
 2201: }
 2202: 
 2203: sub array2str {
 2204:   my (@array) = @_;
 2205:   my $result=&arrayref2str(\@array);
 2206:   $result=~s/^__ARRAY_REF__//;
 2207:   $result=~s/__END_ARRAY_REF__$//;
 2208:   return $result;
 2209: }
 2210: 
 2211: sub arrayref2str {
 2212:   my ($arrayref) = @_;
 2213:   my $result='__ARRAY_REF__';
 2214:   foreach my $elem (@$arrayref) {
 2215:     if(ref($elem) eq 'ARRAY') {
 2216:       $result.=&arrayref2str($elem).'&';
 2217:     } elsif(ref($elem) eq 'HASH') {
 2218:       $result.=&hashref2str($elem).'&';
 2219:     } elsif(ref($elem)) {
 2220:       #print("Got a ref of ".(ref($elem))." skipping.");
 2221:     } else {
 2222:       $result.=&escape($elem).'&';
 2223:     }
 2224:   }
 2225:   $result=~s/\&$//;
 2226:   $result .= '__END_ARRAY_REF__';
 2227:   return $result;
 2228: }
 2229: 
 2230: sub hash2str {
 2231:   my (%hash) = @_;
 2232:   my $result=&hashref2str(\%hash);
 2233:   $result=~s/^__HASH_REF__//;
 2234:   $result=~s/__END_HASH_REF__$//;
 2235:   return $result;
 2236: }
 2237: 
 2238: sub hashref2str {
 2239:   my ($hashref)=@_;
 2240:   my $result='__HASH_REF__';
 2241:   foreach (sort(keys(%$hashref))) {
 2242:     if (ref($_) eq 'ARRAY') {
 2243:       $result.=&arrayref2str($_).'=';
 2244:     } elsif (ref($_) eq 'HASH') {
 2245:       $result.=&hashref2str($_).'=';
 2246:     } elsif (ref($_)) {
 2247:       $result.='=';
 2248:       #print("Got a ref of ".(ref($_))." skipping.");
 2249:     } else {
 2250: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2251:     }
 2252: 
 2253:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2254:       $result.=&arrayref2str($hashref->{$_}).'&';
 2255:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2256:       $result.=&hashref2str($hashref->{$_}).'&';
 2257:     } elsif(ref($hashref->{$_})) {
 2258:        $result.='&';
 2259:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2260:     } else {
 2261:       $result.=&escape($hashref->{$_}).'&';
 2262:     }
 2263:   }
 2264:   $result=~s/\&$//;
 2265:   $result .= '__END_HASH_REF__';
 2266:   return $result;
 2267: }
 2268: 
 2269: sub str2hash {
 2270:     my ($string)=@_;
 2271:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2272:     return %$hash;
 2273: }
 2274: 
 2275: sub str2hashref {
 2276:   my ($string) = @_;
 2277: 
 2278:   my %hash;
 2279: 
 2280:   if($string !~ /^__HASH_REF__/) {
 2281:       if (! ($string eq '' || !defined($string))) {
 2282: 	  $hash{'error'}='Not hash reference';
 2283:       }
 2284:       return (\%hash, $string);
 2285:   }
 2286: 
 2287:   $string =~ s/^__HASH_REF__//;
 2288: 
 2289:   while($string !~ /^__END_HASH_REF__/) {
 2290:       #key
 2291:       my $key='';
 2292:       if($string =~ /^__HASH_REF__/) {
 2293:           ($key, $string)=&str2hashref($string);
 2294:           if(defined($key->{'error'})) {
 2295:               $hash{'error'}='Bad data';
 2296:               return (\%hash, $string);
 2297:           }
 2298:       } elsif($string =~ /^__ARRAY_REF__/) {
 2299:           ($key, $string)=&str2arrayref($string);
 2300:           if($key->[0] eq 'Array reference error') {
 2301:               $hash{'error'}='Bad data';
 2302:               return (\%hash, $string);
 2303:           }
 2304:       } else {
 2305:           $string =~ s/^(.*?)=//;
 2306: 	  $key=&unescape($1);
 2307:       }
 2308:       $string =~ s/^=//;
 2309: 
 2310:       #value
 2311:       my $value='';
 2312:       if($string =~ /^__HASH_REF__/) {
 2313:           ($value, $string)=&str2hashref($string);
 2314:           if(defined($value->{'error'})) {
 2315:               $hash{'error'}='Bad data';
 2316:               return (\%hash, $string);
 2317:           }
 2318:       } elsif($string =~ /^__ARRAY_REF__/) {
 2319:           ($value, $string)=&str2arrayref($string);
 2320:           if($value->[0] eq 'Array reference error') {
 2321:               $hash{'error'}='Bad data';
 2322:               return (\%hash, $string);
 2323:           }
 2324:       } else {
 2325: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2326:       }
 2327:       $string =~ s/^&//;
 2328: 
 2329:       $hash{$key}=$value;
 2330:   }
 2331: 
 2332:   $string =~ s/^__END_HASH_REF__//;
 2333: 
 2334:   return (\%hash, $string);
 2335: }
 2336: 
 2337: sub str2array {
 2338:     my ($string)=@_;
 2339:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2340:     return @$array;
 2341: }
 2342: 
 2343: sub str2arrayref {
 2344:   my ($string) = @_;
 2345:   my @array;
 2346: 
 2347:   if($string !~ /^__ARRAY_REF__/) {
 2348:       if (! ($string eq '' || !defined($string))) {
 2349: 	  $array[0]='Array reference error';
 2350:       }
 2351:       return (\@array, $string);
 2352:   }
 2353: 
 2354:   $string =~ s/^__ARRAY_REF__//;
 2355: 
 2356:   while($string !~ /^__END_ARRAY_REF__/) {
 2357:       my $value='';
 2358:       if($string =~ /^__HASH_REF__/) {
 2359:           ($value, $string)=&str2hashref($string);
 2360:           if(defined($value->{'error'})) {
 2361:               $array[0] ='Array reference error';
 2362:               return (\@array, $string);
 2363:           }
 2364:       } elsif($string =~ /^__ARRAY_REF__/) {
 2365:           ($value, $string)=&str2arrayref($string);
 2366:           if($value->[0] eq 'Array reference error') {
 2367:               $array[0] ='Array reference error';
 2368:               return (\@array, $string);
 2369:           }
 2370:       } else {
 2371: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2372:       }
 2373:       $string =~ s/^&//;
 2374: 
 2375:       push(@array, $value);
 2376:   }
 2377: 
 2378:   $string =~ s/^__END_ARRAY_REF__//;
 2379: 
 2380:   return (\@array, $string);
 2381: }
 2382: 
 2383: # -------------------------------------------------------------------Temp Store
 2384: 
 2385: sub tmpreset {
 2386:   my ($symb,$namespace,$domain,$stuname) = @_;
 2387:   if (!$symb) {
 2388:     $symb=&symbread();
 2389:     if (!$symb) { $symb= $env{'request.url'}; }
 2390:   }
 2391:   $symb=escape($symb);
 2392: 
 2393:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2394:   $namespace=~s/\//\_/g;
 2395:   $namespace=~s/\W//g;
 2396: 
 2397:   if (!$domain) { $domain=$env{'user.domain'}; }
 2398:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2399:   if ($domain eq 'public' && $stuname eq 'public') {
 2400:       $stuname=$ENV{'REMOTE_ADDR'};
 2401:   }
 2402:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2403:   my %hash;
 2404:   if (tie(%hash,'GDBM_File',
 2405: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2406: 	  &GDBM_WRCREAT(),0640)) {
 2407:     foreach my $key (keys %hash) {
 2408:       if ($key=~ /:$symb/) {
 2409: 	delete($hash{$key});
 2410:       }
 2411:     }
 2412:   }
 2413: }
 2414: 
 2415: sub tmpstore {
 2416:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2417: 
 2418:   if (!$symb) {
 2419:     $symb=&symbread();
 2420:     if (!$symb) { $symb= $env{'request.url'}; }
 2421:   }
 2422:   $symb=escape($symb);
 2423: 
 2424:   if (!$namespace) {
 2425:     # I don't think we would ever want to store this for a course.
 2426:     # it seems this will only be used if we don't have a course.
 2427:     #$namespace=$env{'request.course.id'};
 2428:     #if (!$namespace) {
 2429:       $namespace=$env{'request.state'};
 2430:     #}
 2431:   }
 2432:   $namespace=~s/\//\_/g;
 2433:   $namespace=~s/\W//g;
 2434:   if (!$domain) { $domain=$env{'user.domain'}; }
 2435:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2436:   if ($domain eq 'public' && $stuname eq 'public') {
 2437:       $stuname=$ENV{'REMOTE_ADDR'};
 2438:   }
 2439:   my $now=time;
 2440:   my %hash;
 2441:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2442:   if (tie(%hash,'GDBM_File',
 2443: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2444: 	  &GDBM_WRCREAT(),0640)) {
 2445:     $hash{"version:$symb"}++;
 2446:     my $version=$hash{"version:$symb"};
 2447:     my $allkeys=''; 
 2448:     foreach my $key (keys(%$storehash)) {
 2449:       $allkeys.=$key.':';
 2450:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2451:     }
 2452:     $hash{"$version:$symb:timestamp"}=$now;
 2453:     $allkeys.='timestamp';
 2454:     $hash{"$version:keys:$symb"}=$allkeys;
 2455:     if (untie(%hash)) {
 2456:       return 'ok';
 2457:     } else {
 2458:       return "error:$!";
 2459:     }
 2460:   } else {
 2461:     return "error:$!";
 2462:   }
 2463: }
 2464: 
 2465: # -----------------------------------------------------------------Temp Restore
 2466: 
 2467: sub tmprestore {
 2468:   my ($symb,$namespace,$domain,$stuname) = @_;
 2469: 
 2470:   if (!$symb) {
 2471:     $symb=&symbread();
 2472:     if (!$symb) { $symb= $env{'request.url'}; }
 2473:   }
 2474:   $symb=escape($symb);
 2475: 
 2476:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2477: 
 2478:   if (!$domain) { $domain=$env{'user.domain'}; }
 2479:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2480:   if ($domain eq 'public' && $stuname eq 'public') {
 2481:       $stuname=$ENV{'REMOTE_ADDR'};
 2482:   }
 2483:   my %returnhash;
 2484:   $namespace=~s/\//\_/g;
 2485:   $namespace=~s/\W//g;
 2486:   my %hash;
 2487:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2488:   if (tie(%hash,'GDBM_File',
 2489: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2490: 	  &GDBM_READER(),0640)) {
 2491:     my $version=$hash{"version:$symb"};
 2492:     $returnhash{'version'}=$version;
 2493:     my $scope;
 2494:     for ($scope=1;$scope<=$version;$scope++) {
 2495:       my $vkeys=$hash{"$scope:keys:$symb"};
 2496:       my @keys=split(/:/,$vkeys);
 2497:       my $key;
 2498:       $returnhash{"$scope:keys"}=$vkeys;
 2499:       foreach $key (@keys) {
 2500: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2501: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2502:       }
 2503:     }
 2504:     if (!(untie(%hash))) {
 2505:       return "error:$!";
 2506:     }
 2507:   } else {
 2508:     return "error:$!";
 2509:   }
 2510:   return %returnhash;
 2511: }
 2512: 
 2513: # ----------------------------------------------------------------------- Store
 2514: 
 2515: sub store {
 2516:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2517:     my $home='';
 2518: 
 2519:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2520: 
 2521:     $symb=&symbclean($symb);
 2522:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2523: 
 2524:     if (!$domain) { $domain=$env{'user.domain'}; }
 2525:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2526: 
 2527:     &devalidate($symb,$stuname,$domain);
 2528: 
 2529:     $symb=escape($symb);
 2530:     if (!$namespace) { 
 2531:        unless ($namespace=$env{'request.course.id'}) { 
 2532:           return ''; 
 2533:        } 
 2534:     }
 2535:     if (!$home) { $home=$env{'user.home'}; }
 2536: 
 2537:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2538:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2539: 
 2540:     my $namevalue='';
 2541:     foreach (keys %$storehash) {
 2542:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2543:     }
 2544:     $namevalue=~s/\&$//;
 2545:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2546:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2547: }
 2548: 
 2549: # -------------------------------------------------------------- Critical Store
 2550: 
 2551: sub cstore {
 2552:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2553:     my $home='';
 2554: 
 2555:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2556: 
 2557:     $symb=&symbclean($symb);
 2558:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2559: 
 2560:     if (!$domain) { $domain=$env{'user.domain'}; }
 2561:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2562: 
 2563:     &devalidate($symb,$stuname,$domain);
 2564: 
 2565:     $symb=escape($symb);
 2566:     if (!$namespace) { 
 2567:        unless ($namespace=$env{'request.course.id'}) { 
 2568:           return ''; 
 2569:        } 
 2570:     }
 2571:     if (!$home) { $home=$env{'user.home'}; }
 2572: 
 2573:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2574:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2575: 
 2576:     my $namevalue='';
 2577:     foreach (keys %$storehash) {
 2578:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2579:     }
 2580:     $namevalue=~s/\&$//;
 2581:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2582:     return critical
 2583:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2584: }
 2585: 
 2586: # --------------------------------------------------------------------- Restore
 2587: 
 2588: sub restore {
 2589:     my ($symb,$namespace,$domain,$stuname) = @_;
 2590:     my $home='';
 2591: 
 2592:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2593: 
 2594:     if (!$symb) {
 2595:       unless ($symb=escape(&symbread())) { return ''; }
 2596:     } else {
 2597:       $symb=&escape(&symbclean($symb));
 2598:     }
 2599:     if (!$namespace) { 
 2600:        unless ($namespace=$env{'request.course.id'}) { 
 2601:           return ''; 
 2602:        } 
 2603:     }
 2604:     if (!$domain) { $domain=$env{'user.domain'}; }
 2605:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2606:     if (!$home) { $home=$env{'user.home'}; }
 2607:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2608: 
 2609:     my %returnhash=();
 2610:     foreach (split(/\&/,$answer)) {
 2611: 	my ($name,$value)=split(/\=/,$_);
 2612:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2613:     }
 2614:     my $version;
 2615:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2616:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2617:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2618:        }
 2619:     }
 2620:     return %returnhash;
 2621: }
 2622: 
 2623: # ---------------------------------------------------------- Course Description
 2624: 
 2625: sub coursedescription {
 2626:     my ($courseid,$args)=@_;
 2627:     $courseid=~s/^\///;
 2628:     $courseid=~s/\_/\//g;
 2629:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2630:     my $chome=&homeserver($cnum,$cdomain);
 2631:     my $normalid=$cdomain.'_'.$cnum;
 2632:     # need to always cache even if we get errors otherwise we keep 
 2633:     # trying and trying and trying to get the course description.
 2634:     my %envhash=();
 2635:     my %returnhash=();
 2636:     
 2637:     my $expiretime=600;
 2638:     if ($env{'request.course.id'} eq $normalid) {
 2639: 	$expiretime=120;
 2640:     }
 2641: 
 2642:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2643:     if (!$args->{'freshen_cache'}
 2644: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2645: 	foreach my $key (keys(%env)) {
 2646: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2647: 	    my ($setting) = $1;
 2648: 	    $returnhash{$setting} = $env{$key};
 2649: 	}
 2650: 	return %returnhash;
 2651:     }
 2652: 
 2653:     # get the data agin
 2654:     if (!$args->{'one_time'}) {
 2655: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2656:     }
 2657:     if ($chome ne 'no_host') {
 2658:        %returnhash=&dump('environment',$cdomain,$cnum);
 2659:        if (!exists($returnhash{'con_lost'})) {
 2660:            $returnhash{'home'}= $chome;
 2661: 	   $returnhash{'domain'} = $cdomain;
 2662: 	   $returnhash{'num'} = $cnum;
 2663:            if (!defined($returnhash{'type'})) {
 2664:                $returnhash{'type'} = 'Course';
 2665:            }
 2666:            while (my ($name,$value) = each %returnhash) {
 2667:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2668:            }
 2669:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2670:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2671: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2672:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2673:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2674:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2675:        }
 2676:     }
 2677:     if (!$args->{'one_time'}) {
 2678: 	&appenv(%envhash);
 2679:     }
 2680:     return %returnhash;
 2681: }
 2682: 
 2683: # -------------------------------------------------See if a user is privileged
 2684: 
 2685: sub privileged {
 2686:     my ($username,$domain)=@_;
 2687:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2688: 			&homeserver($username,$domain));
 2689:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2690:     my $now=time;
 2691:     if ($rolesdump ne '') {
 2692:         foreach (split(/&/,$rolesdump)) {
 2693: 	    if ($_!~/^rolesdef_/) {
 2694: 		my ($area,$role)=split(/=/,$_);
 2695: 		$area=~s/\_\w\w$//;
 2696: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2697: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2698: 		    my $active=1;
 2699: 		    if ($tend) {
 2700: 			if ($tend<$now) { $active=0; }
 2701: 		    }
 2702: 		    if ($tstart) {
 2703: 			if ($tstart>$now) { $active=0; }
 2704: 		    }
 2705: 		    if ($active) { return 1; }
 2706: 		}
 2707: 	    }
 2708: 	}
 2709:     }
 2710:     return 0;
 2711: }
 2712: 
 2713: # -------------------------------------------------------- Get user privileges
 2714: 
 2715: sub rolesinit {
 2716:     my ($domain,$username,$authhost)=@_;
 2717:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2718:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2719:     my %allroles=();
 2720:     my %allgroups=();   
 2721:     my $now=time;
 2722:     my %userroles = ('user.login.time' => $now);
 2723:     my $group_privs;
 2724: 
 2725:     if ($rolesdump ne '') {
 2726:         foreach (split(/&/,$rolesdump)) {
 2727: 	  if ($_!~/^rolesdef_/) {
 2728:             my ($area,$role)=split(/=/,$_);
 2729: 	    $area=~s/\_\w\w$//;
 2730:             my ($trole,$tend,$tstart,$group_privs);
 2731: 	    if ($role=~/^cr/) { 
 2732: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2733: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2734: 		    ($tend,$tstart)=split('_',$trest);
 2735: 		} else {
 2736: 		    $trole=$role;
 2737: 		}
 2738:             } elsif ($role =~ m|^gr/|) {
 2739:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2740:                 ($trole,$group_privs) = split(/\//,$trole);
 2741:                 $group_privs = &unescape($group_privs);
 2742: 	    } else {
 2743: 		($trole,$tend,$tstart)=split(/_/,$role);
 2744: 	    }
 2745: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2746: 					 $username);
 2747: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2748:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2749:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2750:             if (($area ne '') && ($trole ne '')) {
 2751: 		my $spec=$trole.'.'.$area;
 2752: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2753: 		if ($trole =~ /^cr\//) {
 2754:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2755:                 } elsif ($trole eq 'gr') {
 2756:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2757: 		} else {
 2758:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2759: 		}
 2760:             }
 2761:           }
 2762:         }
 2763:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2764:         $userroles{'user.adv'}    = $adv;
 2765: 	$userroles{'user.author'} = $author;
 2766:         $env{'user.adv'}=$adv;
 2767:     }
 2768:     return \%userroles;  
 2769: }
 2770: 
 2771: sub set_arearole {
 2772:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2773: # log the associated role with the area
 2774:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2775:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2776: }
 2777: 
 2778: sub custom_roleprivs {
 2779:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2780:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2781:     my $homsvr=homeserver($rauthor,$rdomain);
 2782:     if ($hostname{$homsvr} ne '') {
 2783:         my ($rdummy,$roledef)=
 2784:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2785:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2786:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2787:             if (defined($syspriv)) {
 2788:                 $$allroles{'cm./'}.=':'.$syspriv;
 2789:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2790:             }
 2791:             if ($tdomain ne '') {
 2792:                 if (defined($dompriv)) {
 2793:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2794:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2795:                 }
 2796:                 if (($trest ne '') && (defined($coursepriv))) {
 2797:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2798:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2799:                 }
 2800:             }
 2801:         }
 2802:     }
 2803: }
 2804: 
 2805: sub group_roleprivs {
 2806:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2807:     my $access = 1;
 2808:     my $now = time;
 2809:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2810:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2811:     if ($access) {
 2812:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2813:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2814:     }
 2815: }
 2816: 
 2817: sub standard_roleprivs {
 2818:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2819:     if (defined($pr{$trole.':s'})) {
 2820:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2821:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2822:     }
 2823:     if ($tdomain ne '') {
 2824:         if (defined($pr{$trole.':d'})) {
 2825:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2826:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2827:         }
 2828:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2829:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2830:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2831:         }
 2832:     }
 2833: }
 2834: 
 2835: sub set_userprivs {
 2836:     my ($userroles,$allroles,$allgroups) = @_; 
 2837:     my $author=0;
 2838:     my $adv=0;
 2839:     my %grouproles = ();
 2840:     if (keys(%{$allgroups}) > 0) {
 2841:         foreach my $role (keys %{$allroles}) {
 2842:             my ($trole,$area,$sec,$extendedarea);
 2843:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
 2844:                 $trole = $1;
 2845:                 $area = $2;
 2846:                 $sec = $3;
 2847:                 $extendedarea = $area.$sec;
 2848:                 if (exists($$allgroups{$area})) {
 2849:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2850:                         my $spec = $trole.'.'.$extendedarea;
 2851:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2852:                                                 $$allgroups{$area}{$group};
 2853:                     }
 2854:                 }
 2855:             }
 2856:         }
 2857:     }
 2858:     foreach (keys(%grouproles)) {
 2859:         $$allroles{$_} = $grouproles{$_};
 2860:     }
 2861:     foreach (keys %{$allroles}) {
 2862:         my %thesepriv=();
 2863:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2864:         foreach (split(/:/,$$allroles{$_})) {
 2865:             if ($_ ne '') {
 2866:                 my ($privilege,$restrictions)=split(/&/,$_);
 2867:                 if ($restrictions eq '') {
 2868:                     $thesepriv{$privilege}='F';
 2869:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2870:                     $thesepriv{$privilege}.=$restrictions;
 2871:                 }
 2872:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2873:             }
 2874:         }
 2875:         my $thesestr='';
 2876:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2877:         $userroles->{'user.priv.'.$_} = $thesestr;
 2878:     }
 2879:     return ($author,$adv);
 2880: }
 2881: 
 2882: # --------------------------------------------------------------- get interface
 2883: 
 2884: sub get {
 2885:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2886:    my $items='';
 2887:    foreach (@$storearr) {
 2888:        $items.=escape($_).'&';
 2889:    }
 2890:    $items=~s/\&$//;
 2891:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2892:    if (!$uname) { $uname=$env{'user.name'}; }
 2893:    my $uhome=&homeserver($uname,$udomain);
 2894: 
 2895:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2896:    my @pairs=split(/\&/,$rep);
 2897:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2898:      return @pairs;
 2899:    }
 2900:    my %returnhash=();
 2901:    my $i=0;
 2902:    foreach (@$storearr) {
 2903:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2904:       $i++;
 2905:    }
 2906:    return %returnhash;
 2907: }
 2908: 
 2909: # --------------------------------------------------------------- del interface
 2910: 
 2911: sub del {
 2912:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2913:    my $items='';
 2914:    foreach (@$storearr) {
 2915:        $items.=escape($_).'&';
 2916:    }
 2917:    $items=~s/\&$//;
 2918:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2919:    if (!$uname) { $uname=$env{'user.name'}; }
 2920:    my $uhome=&homeserver($uname,$udomain);
 2921: 
 2922:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2923: }
 2924: 
 2925: # -------------------------------------------------------------- dump interface
 2926: 
 2927: sub dump {
 2928:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2929:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2930:     if (!$uname) { $uname=$env{'user.name'}; }
 2931:     my $uhome=&homeserver($uname,$udomain);
 2932:     if ($regexp) {
 2933: 	$regexp=&escape($regexp);
 2934:     } else {
 2935: 	$regexp='.';
 2936:     }
 2937:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2938:     my @pairs=split(/\&/,$rep);
 2939:     my %returnhash=();
 2940:     foreach my $item (@pairs) {
 2941: 	my ($key,$value)=split(/=/,$item,2);
 2942: 	$key = &unescape($key);
 2943: 	next if ($key =~ /^error: 2 /);
 2944: 	$returnhash{$key}=&thaw_unescape($value);
 2945:     }
 2946:     return %returnhash;
 2947: }
 2948: 
 2949: # --------------------------------------------------------- dumpstore interface
 2950: 
 2951: sub dumpstore {
 2952:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2953:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2954: }
 2955: 
 2956: # -------------------------------------------------------------- keys interface
 2957: 
 2958: sub getkeys {
 2959:    my ($namespace,$udomain,$uname)=@_;
 2960:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2961:    if (!$uname) { $uname=$env{'user.name'}; }
 2962:    my $uhome=&homeserver($uname,$udomain);
 2963:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2964:    my @keyarray=();
 2965:    foreach (split(/\&/,$rep)) {
 2966:       push (@keyarray,&unescape($_));
 2967:    }
 2968:    return @keyarray;
 2969: }
 2970: 
 2971: # --------------------------------------------------------------- currentdump
 2972: sub currentdump {
 2973:    my ($courseid,$sdom,$sname)=@_;
 2974:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2975:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2976:    $sname    = $env{'user.name'}         if (! defined($sname));
 2977:    my $uhome = &homeserver($sname,$sdom);
 2978:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2979:    return if ($rep =~ /^(error:|no_such_host)/);
 2980:    #
 2981:    my %returnhash=();
 2982:    #
 2983:    if ($rep eq "unknown_cmd") { 
 2984:        # an old lond will not know currentdump
 2985:        # Do a dump and make it look like a currentdump
 2986:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2987:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2988:        my %hash = @tmp;
 2989:        @tmp=();
 2990:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2991:    } else {
 2992:        my @pairs=split(/\&/,$rep);
 2993:        foreach (@pairs) {
 2994:            my ($key,$value)=split(/=/,$_);
 2995:            my ($symb,$param) = split(/:/,$key);
 2996:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2997:                                                         &thaw_unescape($value);
 2998:        }
 2999:    }
 3000:    return %returnhash;
 3001: }
 3002: 
 3003: sub convert_dump_to_currentdump{
 3004:     my %hash = %{shift()};
 3005:     my %returnhash;
 3006:     # Code ripped from lond, essentially.  The only difference
 3007:     # here is the unescaping done by lonnet::dump().  Conceivably
 3008:     # we might run in to problems with parameter names =~ /^v\./
 3009:     while (my ($key,$value) = each(%hash)) {
 3010:         my ($v,$symb,$param) = split(/:/,$key);
 3011:         next if ($v eq 'version' || $symb eq 'keys');
 3012:         next if (exists($returnhash{$symb}) &&
 3013:                  exists($returnhash{$symb}->{$param}) &&
 3014:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3015:         $returnhash{$symb}->{$param}=$value;
 3016:         $returnhash{$symb}->{'v.'.$param}=$v;
 3017:     }
 3018:     #
 3019:     # Remove all of the keys in the hashes which keep track of
 3020:     # the version of the parameter.
 3021:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3022:         # use a foreach because we are going to delete from the hash.
 3023:         foreach my $key (keys(%$param_hash)) {
 3024:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3025:         }
 3026:     }
 3027:     return \%returnhash;
 3028: }
 3029: 
 3030: # ------------------------------------------------------ critical inc interface
 3031: 
 3032: sub cinc {
 3033:     return &inc(@_,'critical');
 3034: }
 3035: 
 3036: # --------------------------------------------------------------- inc interface
 3037: 
 3038: sub inc {
 3039:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3040:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3041:     if (!$uname) { $uname=$env{'user.name'}; }
 3042:     my $uhome=&homeserver($uname,$udomain);
 3043:     my $items='';
 3044:     if (! ref($store)) {
 3045:         # got a single value, so use that instead
 3046:         $items = &escape($store).'=&';
 3047:     } elsif (ref($store) eq 'SCALAR') {
 3048:         $items = &escape($$store).'=&';        
 3049:     } elsif (ref($store) eq 'ARRAY') {
 3050:         $items = join('=&',map {&escape($_);} @{$store});
 3051:     } elsif (ref($store) eq 'HASH') {
 3052:         while (my($key,$value) = each(%{$store})) {
 3053:             $items.= &escape($key).'='.&escape($value).'&';
 3054:         }
 3055:     }
 3056:     $items=~s/\&$//;
 3057:     if ($critical) {
 3058: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3059:     } else {
 3060: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3061:     }
 3062: }
 3063: 
 3064: # --------------------------------------------------------------- put interface
 3065: 
 3066: sub put {
 3067:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3068:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3069:    if (!$uname) { $uname=$env{'user.name'}; }
 3070:    my $uhome=&homeserver($uname,$udomain);
 3071:    my $items='';
 3072:    foreach (keys %$storehash) {
 3073:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3074:    }
 3075:    $items=~s/\&$//;
 3076:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3077: }
 3078: 
 3079: # ------------------------------------------------------------ newput interface
 3080: 
 3081: sub newput {
 3082:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3083:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3084:    if (!$uname) { $uname=$env{'user.name'}; }
 3085:    my $uhome=&homeserver($uname,$udomain);
 3086:    my $items='';
 3087:    foreach my $key (keys(%$storehash)) {
 3088:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3089:    }
 3090:    $items=~s/\&$//;
 3091:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3092: }
 3093: 
 3094: # ---------------------------------------------------------  putstore interface
 3095: 
 3096: sub putstore {
 3097:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3099:    if (!$uname) { $uname=$env{'user.name'}; }
 3100:    my $uhome=&homeserver($uname,$udomain);
 3101:    my $items='';
 3102:    foreach my $key (keys(%$storehash)) {
 3103:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3104:    }
 3105:    $items=~s/\&$//;
 3106:    my $esc_symb=&escape($symb);
 3107:    my $esc_v=&escape($version);
 3108:    my $reply =
 3109:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3110: 	      $uhome);
 3111:    if ($reply eq 'unknown_cmd') {
 3112:        # gfall back to way things use to be done
 3113:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3114: 			    $uname);
 3115:    }
 3116:    return $reply;
 3117: }
 3118: 
 3119: sub old_putstore {
 3120:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3121:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3122:     if (!$uname) { $uname=$env{'user.name'}; }
 3123:     my $uhome=&homeserver($uname,$udomain);
 3124:     my %newstorehash;
 3125:     foreach (keys %$storehash) {
 3126: 	my $key = $version.':'.&escape($symb).':'.$_;
 3127: 	$newstorehash{$key} = $storehash->{$_};
 3128:     }
 3129:     my $items='';
 3130:     my %allitems = ();
 3131:     foreach (keys %newstorehash) {
 3132: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3133: 	    my $key = $1.':keys:'.$2;
 3134: 	    $allitems{$key} .= $3.':';
 3135: 	}
 3136: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3137:     }
 3138:     foreach (keys %allitems) {
 3139: 	$allitems{$_} =~ s/\:$//;
 3140: 	$items.= $_.'='.$allitems{$_}.'&';
 3141:     }
 3142:     $items=~s/\&$//;
 3143:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3144: }
 3145: 
 3146: # ------------------------------------------------------ critical put interface
 3147: 
 3148: sub cput {
 3149:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3150:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3151:    if (!$uname) { $uname=$env{'user.name'}; }
 3152:    my $uhome=&homeserver($uname,$udomain);
 3153:    my $items='';
 3154:    foreach (keys %$storehash) {
 3155:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3156:    }
 3157:    $items=~s/\&$//;
 3158:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3159: }
 3160: 
 3161: # -------------------------------------------------------------- eget interface
 3162: 
 3163: sub eget {
 3164:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3165:    my $items='';
 3166:    foreach (@$storearr) {
 3167:        $items.=escape($_).'&';
 3168:    }
 3169:    $items=~s/\&$//;
 3170:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3171:    if (!$uname) { $uname=$env{'user.name'}; }
 3172:    my $uhome=&homeserver($uname,$udomain);
 3173:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3174:    my @pairs=split(/\&/,$rep);
 3175:    my %returnhash=();
 3176:    my $i=0;
 3177:    foreach (@$storearr) {
 3178:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3179:       $i++;
 3180:    }
 3181:    return %returnhash;
 3182: }
 3183: 
 3184: # ------------------------------------------------------------ tmpput interface
 3185: sub tmpput {
 3186:     my ($storehash,$server)=@_;
 3187:     my $items='';
 3188:     foreach (keys(%$storehash)) {
 3189: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3190:     }
 3191:     $items=~s/\&$//;
 3192:     return &reply("tmpput:$items",$server);
 3193: }
 3194: 
 3195: # ------------------------------------------------------------ tmpget interface
 3196: sub tmpget {
 3197:     my ($token,$server)=@_;
 3198:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3199:     my $rep=&reply("tmpget:$token",$server);
 3200:     my %returnhash;
 3201:     foreach my $item (split(/\&/,$rep)) {
 3202: 	my ($key,$value)=split(/=/,$item);
 3203: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3204:     }
 3205:     return %returnhash;
 3206: }
 3207: 
 3208: # ------------------------------------------------------------ tmpget interface
 3209: sub tmpdel {
 3210:     my ($token,$server)=@_;
 3211:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3212:     return &reply("tmpdel:$token",$server);
 3213: }
 3214: 
 3215: # -------------------------------------------------- portfolio access checking
 3216: 
 3217: sub portfolio_access {
 3218:     my ($requrl) = @_;
 3219:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3220:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3221:     if ($result eq 'ok') {
 3222:        return 'F';
 3223:     } elsif ($result =~ /^[^:]+:guest_/) {
 3224:        return 'A';
 3225:     }
 3226:     return '';
 3227: }
 3228: 
 3229: sub get_portfolio_access {
 3230:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3231: 
 3232:     if (!ref($access_hash)) {
 3233: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3234: 	my %access_controls = &get_access_controls($current_perms,$group,
 3235: 						   $file_name);
 3236: 	$access_hash = $access_controls{$file_name};
 3237:     }
 3238: 
 3239:     my ($public,$guest,@domains,@users,@courses,@groups);
 3240:     my $now = time;
 3241:     if (ref($access_hash) eq 'HASH') {
 3242:         foreach my $key (keys(%{$access_hash})) {
 3243:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3244:             if ($start > $now) {
 3245:                 next;
 3246:             }
 3247:             if ($end && $end<$now) {
 3248:                 next;
 3249:             }
 3250:             if ($scope eq 'public') {
 3251:                 $public = $key;
 3252:                 last;
 3253:             } elsif ($scope eq 'guest') {
 3254:                 $guest = $key;
 3255:             } elsif ($scope eq 'domains') {
 3256:                 push(@domains,$key);
 3257:             } elsif ($scope eq 'users') {
 3258:                 push(@users,$key);
 3259:             } elsif ($scope eq 'course') {
 3260:                 push(@courses,$key);
 3261:             } elsif ($scope eq 'group') {
 3262:                 push(@groups,$key);
 3263:             }
 3264:         }
 3265:         if ($public) {
 3266:             return 'ok';
 3267:         }
 3268:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3269:             if ($guest) {
 3270:                 return $guest;
 3271:             }
 3272:         } else {
 3273:             if (@domains > 0) {
 3274:                 foreach my $domkey (@domains) {
 3275:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3276:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3277:                             return 'ok';
 3278:                         }
 3279:                     }
 3280:                 }
 3281:             }
 3282:             if (@users > 0) {
 3283:                 foreach my $userkey (@users) {
 3284:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3285:                         return 'ok';
 3286:                     }
 3287:                 }
 3288:             }
 3289:             my %roleshash;
 3290:             my @courses_and_groups = @courses;
 3291:             push(@courses_and_groups,@groups); 
 3292:             if (@courses_and_groups > 0) {
 3293:                 my (%allgroups,%allroles); 
 3294:                 my ($start,$end,$role,$sec,$group);
 3295:                 foreach my $envkey (%env) {
 3296:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
 3297:                         my $cid = $2.'_'.$3; 
 3298:                         if ($1 eq 'gr') {
 3299:                             $group = $4;
 3300:                             $allgroups{$cid}{$group} = $env{$envkey};
 3301:                         } else {
 3302:                             if ($4 eq '') {
 3303:                                 $sec = 'none';
 3304:                             } else {
 3305:                                 $sec = $4;
 3306:                             }
 3307:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3308:                         }
 3309:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
 3310:                         my $cid = $2.'_'.$3;
 3311:                         if ($4 eq '') {
 3312:                             $sec = 'none';
 3313:                         } else {
 3314:                             $sec = $4;
 3315:                         }
 3316:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3317:                     }
 3318:                 }
 3319:                 if (keys(%allroles) == 0) {
 3320:                     return;
 3321:                 }
 3322:                 foreach my $key (@courses_and_groups) {
 3323:                     my %content = %{$$access_hash{$key}};
 3324:                     my $cnum = $content{'number'};
 3325:                     my $cdom = $content{'domain'};
 3326:                     my $cid = $cdom.'_'.$cnum;
 3327:                     if (!exists($allroles{$cid})) {
 3328:                         next;
 3329:                     }    
 3330:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3331:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3332:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3333:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3334:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3335:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3336:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3337:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3338:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3339:                                         if (grep/^all$/,@sections) {
 3340:                                             return 'ok';
 3341:                                         } else {
 3342:                                             if (grep/^$sec$/,@sections) {
 3343:                                                 return 'ok';
 3344:                                             }
 3345:                                         }
 3346:                                     }
 3347:                                 }
 3348:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3349:                                     if (grep/^none$/,@groups) {
 3350:                                         return 'ok';
 3351:                                     }
 3352:                                 } else {
 3353:                                     if (grep/^all$/,@groups) {
 3354:                                         return 'ok';
 3355:                                     } 
 3356:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3357:                                         if (grep/^$group$/,@groups) {
 3358:                                             return 'ok';
 3359:                                         }
 3360:                                     }
 3361:                                 } 
 3362:                             }
 3363:                         }
 3364:                     }
 3365:                 }
 3366:             }
 3367:             if ($guest) {
 3368:                 return $guest;
 3369:             }
 3370:         }
 3371:     }
 3372:     return;
 3373: }
 3374: 
 3375: sub course_group_datechecker {
 3376:     my ($dates,$now,$status) = @_;
 3377:     my ($start,$end) = split(/\./,$dates);
 3378:     if (!$start && !$end) {
 3379:         return 'ok';
 3380:     }
 3381:     if (grep/^active$/,@{$status}) {
 3382:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3383:             return 'ok';
 3384:         }
 3385:     }
 3386:     if (grep/^previous$/,@{$status}) {
 3387:         if ($end > $now ) {
 3388:             return 'ok';
 3389:         }
 3390:     }
 3391:     if (grep/^future$/,@{$status}) {
 3392:         if ($start > $now) {
 3393:             return 'ok';
 3394:         }
 3395:     }
 3396:     return; 
 3397: }
 3398: 
 3399: sub parse_portfolio_url {
 3400:     my ($url) = @_;
 3401: 
 3402:     my ($type,$udom,$unum,$group,$file_name);
 3403:     
 3404:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
 3405: 	$type = 1;
 3406:         $udom = $1;
 3407:         $unum = $2;
 3408:         $file_name = $3;
 3409:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
 3410: 	$type = 2;
 3411:         $udom = $1;
 3412:         $unum = $2;
 3413:         $group = $3;
 3414:         $file_name = $3.'/'.$4;
 3415:     }
 3416:     if (wantarray) {
 3417: 	return ($type,$udom,$unum,$file_name,$group);
 3418:     }
 3419:     return $type;
 3420: }
 3421: 
 3422: sub is_portfolio_url {
 3423:     my ($url) = @_;
 3424:     return scalar(&parse_portfolio_url($url));
 3425: }
 3426: 
 3427: # ---------------------------------------------- Custom access rule evaluation
 3428: 
 3429: sub customaccess {
 3430:     my ($priv,$uri)=@_;
 3431:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3432:     $urealm=~s/^\W//;
 3433:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3434:     my $access=0;
 3435:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3436: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3437:         if ($role) {
 3438: 	   if ($role ne $urole) { next; }
 3439:         }
 3440:         foreach (split(/\s*\,\s*/,$realm)) {
 3441:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3442:             if ($tdom) {
 3443: 		if ($tdom ne $udom) { next; }
 3444:             }
 3445:             if ($tcrs) {
 3446: 		if ($tcrs ne $ucrs) { next; }
 3447:             }
 3448:             if ($tsec) {
 3449: 		if ($tsec ne $usec) { next; }
 3450:             }
 3451:             $access=($effect eq 'allow');
 3452:             last;
 3453:         }
 3454: 	if ($realm eq '' && $role eq '') {
 3455:             $access=($effect eq 'allow');
 3456: 	}
 3457:     }
 3458:     return $access;
 3459: }
 3460: 
 3461: # ------------------------------------------------- Check for a user privilege
 3462: 
 3463: sub allowed {
 3464:     my ($priv,$uri,$symb)=@_;
 3465:     my $ver_orguri=$uri;
 3466:     $uri=&deversion($uri);
 3467:     my $orguri=$uri;
 3468:     $uri=&declutter($uri);
 3469:     
 3470:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3471: # Free bre access to adm and meta resources
 3472:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3473: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3474: 	&& ($priv eq 'bre')) {
 3475: 	return 'F';
 3476:     }
 3477: 
 3478: # Free bre access to user's own portfolio contents
 3479:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3480:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3481: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3482:         return 'F';
 3483:     }
 3484: 
 3485: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3486:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3487:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3488:         if (exists($env{'request.course.id'})) {
 3489:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3490:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3491:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3492:                 my $courseprivid=$env{'request.course.id'};
 3493:                 $courseprivid=~s/\_/\//;
 3494:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3495:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3496:                     return $1; 
 3497:                 } else {
 3498:                     if ($env{'request.course.sec'}) {
 3499:                         $courseprivid.='/'.$env{'request.course.sec'};
 3500:                     }
 3501:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3502:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3503:                         return $2;
 3504:                     }
 3505:                 }
 3506:             }
 3507:         }
 3508:     }
 3509: 
 3510: # Free bre to public access
 3511: 
 3512:     if ($priv eq 'bre') {
 3513:         my $copyright=&metadata($uri,'copyright');
 3514: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3515:            return 'F'; 
 3516:         }
 3517:         if ($copyright eq 'priv') {
 3518:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3519: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3520: 		return '';
 3521:             }
 3522:         }
 3523:         if ($copyright eq 'domain') {
 3524:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3525: 	    unless (($env{'user.domain'} eq $1) ||
 3526:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3527: 		return '';
 3528:             }
 3529:         }
 3530:         if ($env{'request.role'}=~ /li\.\//) {
 3531:             # Library role, so allow browsing of resources in this domain.
 3532:             return 'F';
 3533:         }
 3534:         if ($copyright eq 'custom') {
 3535: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3536:         }
 3537:     }
 3538:     # Domain coordinator is trying to create a course
 3539:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3540:         # uri is the requested domain in this case.
 3541:         # comparison to 'request.role.domain' shows if the user has selected
 3542:         # a role of dc for the domain in question.
 3543:         return 'F' if ($uri eq $env{'request.role.domain'});
 3544:     }
 3545: 
 3546:     my $thisallowed='';
 3547:     my $statecond=0;
 3548:     my $courseprivid='';
 3549: 
 3550: # Course
 3551: 
 3552:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3553:        $thisallowed.=$1;
 3554:     }
 3555: 
 3556: # Domain
 3557: 
 3558:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3559:        =~/\Q$priv\E\&([^\:]*)/) {
 3560:        $thisallowed.=$1;
 3561:     }
 3562: 
 3563: # Course: uri itself is a course
 3564:     my $courseuri=$uri;
 3565:     $courseuri=~s/\_(\d)/\/$1/;
 3566:     $courseuri=~s/^([^\/])/\/$1/;
 3567: 
 3568:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3569:        =~/\Q$priv\E\&([^\:]*)/) {
 3570:        $thisallowed.=$1;
 3571:     }
 3572: 
 3573: # URI is an uploaded document for this course, default permissions don't matter
 3574: # not allowing 'edit' access (editupload) to uploaded course docs
 3575:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3576: 	$thisallowed='';
 3577:         my ($match)=&is_on_map($uri);
 3578:         if ($match) {
 3579:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3580:                   =~/\Q$priv\E\&([^\:]*)/) {
 3581:                 $thisallowed.=$1;
 3582:             }
 3583:         } else {
 3584:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3585:             if ($refuri) {
 3586:                 if ($refuri =~ m|^/adm/|) {
 3587:                     $thisallowed='F';
 3588:                 } else {
 3589:                     $refuri=&declutter($refuri);
 3590:                     my ($match) = &is_on_map($refuri);
 3591:                     if ($match) {
 3592:                         $thisallowed='F';
 3593:                     }
 3594:                 }
 3595:             }
 3596:         }
 3597:     }
 3598: 
 3599:     if ($priv eq 'bre'
 3600: 	&& $thisallowed ne 'F' 
 3601: 	&& $thisallowed ne '2'
 3602: 	&& &is_portfolio_url($uri)) {
 3603: 	$thisallowed = &portfolio_access($uri);
 3604:     }
 3605:     
 3606: # Full access at system, domain or course-wide level? Exit.
 3607: 
 3608:     if ($thisallowed=~/F/) {
 3609: 	return 'F';
 3610:     }
 3611: 
 3612: # If this is generating or modifying users, exit with special codes
 3613: 
 3614:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3615: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3616: 	    my ($audom,$auname)=split('/',$uri);
 3617: # no author name given, so this just checks on the general right to make a co-author in this domain
 3618: 	    unless ($auname) { return $thisallowed; }
 3619: # an author name is given, so we are about to actually make a co-author for a certain account
 3620: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3621: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3622: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3623: 	}
 3624: 	return $thisallowed;
 3625:     }
 3626: #
 3627: # Gathered so far: system, domain and course wide privileges
 3628: #
 3629: # Course: See if uri or referer is an individual resource that is part of 
 3630: # the course
 3631: 
 3632:     if ($env{'request.course.id'}) {
 3633: 
 3634:        $courseprivid=$env{'request.course.id'};
 3635:        if ($env{'request.course.sec'}) {
 3636:           $courseprivid.='/'.$env{'request.course.sec'};
 3637:        }
 3638:        $courseprivid=~s/\_/\//;
 3639:        my $checkreferer=1;
 3640:        my ($match,$cond)=&is_on_map($uri);
 3641:        if ($match) {
 3642:            $statecond=$cond;
 3643:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3644:                =~/\Q$priv\E\&([^\:]*)/) {
 3645:                $thisallowed.=$1;
 3646:                $checkreferer=0;
 3647:            }
 3648:        }
 3649:        
 3650:        if ($checkreferer) {
 3651: 	  my $refuri=$env{'httpref.'.$orguri};
 3652:             unless ($refuri) {
 3653:                 foreach (keys %env) {
 3654: 		    if ($_=~/^httpref\..*\*/) {
 3655: 			my $pattern=$_;
 3656:                         $pattern=~s/^httpref\.\/res\///;
 3657:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3658:                         $pattern=~s/\//\\\//g;
 3659:                         if ($orguri=~/$pattern/) {
 3660: 			    $refuri=$env{$_};
 3661:                         }
 3662:                     }
 3663:                 }
 3664:             }
 3665: 
 3666:          if ($refuri) { 
 3667: 	  $refuri=&declutter($refuri);
 3668:           my ($match,$cond)=&is_on_map($refuri);
 3669:             if ($match) {
 3670:               my $refstatecond=$cond;
 3671:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3672:                   =~/\Q$priv\E\&([^\:]*)/) {
 3673:                   $thisallowed.=$1;
 3674:                   $uri=$refuri;
 3675:                   $statecond=$refstatecond;
 3676:               }
 3677:           }
 3678:         }
 3679:        }
 3680:    }
 3681: 
 3682: #
 3683: # Gathered now: all privileges that could apply, and condition number
 3684: # 
 3685: #
 3686: # Full or no access?
 3687: #
 3688: 
 3689:     if ($thisallowed=~/F/) {
 3690: 	return 'F';
 3691:     }
 3692: 
 3693:     unless ($thisallowed) {
 3694:         return '';
 3695:     }
 3696: 
 3697: # Restrictions exist, deal with them
 3698: #
 3699: #   C:according to course preferences
 3700: #   R:according to resource settings
 3701: #   L:unless locked
 3702: #   X:according to user session state
 3703: #
 3704: 
 3705: # Possibly locked functionality, check all courses
 3706: # Locks might take effect only after 10 minutes cache expiration for other
 3707: # courses, and 2 minutes for current course
 3708: 
 3709:     my $envkey;
 3710:     if ($thisallowed=~/L/) {
 3711:         foreach $envkey (keys %env) {
 3712:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3713:                my $courseid=$2;
 3714:                my $roleid=$1.'.'.$2;
 3715:                $courseid=~s/^\///;
 3716:                my $expiretime=600;
 3717:                if ($env{'request.role'} eq $roleid) {
 3718: 		  $expiretime=120;
 3719:                }
 3720: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3721:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3722:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3723: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3724:                }
 3725:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3726:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3727: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3728:                        &log($env{'user.domain'},$env{'user.name'},
 3729:                             $env{'user.home'},
 3730:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3731:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3732:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3733: 		       return '';
 3734:                    }
 3735:                }
 3736:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3737:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3738: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3739:                        &log($env{'user.domain'},$env{'user.name'},
 3740:                             $env{'user.home'},
 3741:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3742:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3743:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3744: 		       return '';
 3745:                    }
 3746:                }
 3747: 	   }
 3748:        }
 3749:     }
 3750:    
 3751: #
 3752: # Rest of the restrictions depend on selected course
 3753: #
 3754: 
 3755:     unless ($env{'request.course.id'}) {
 3756: 	if ($thisallowed eq 'A') {
 3757: 	    return 'A';
 3758: 	} else {
 3759: 	    return '1';
 3760: 	}
 3761:     }
 3762: 
 3763: #
 3764: # Now user is definitely in a course
 3765: #
 3766: 
 3767: 
 3768: # Course preferences
 3769: 
 3770:    if ($thisallowed=~/C/) {
 3771:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3772:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3773:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3774: 	   =~/\Q$rolecode\E/) {
 3775: 	   if ($priv ne 'pch') { 
 3776: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3777: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3778: 			$env{'request.course.id'});
 3779: 	   }
 3780:            return '';
 3781:        }
 3782: 
 3783:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3784: 	   =~/\Q$unamedom\E/) {
 3785: 	   if ($priv ne 'pch') { 
 3786: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3787: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3788: 			$env{'request.course.id'});
 3789: 	   }
 3790:            return '';
 3791:        }
 3792:    }
 3793: 
 3794: # Resource preferences
 3795: 
 3796:    if ($thisallowed=~/R/) {
 3797:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3798:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3799: 	   if ($priv ne 'pch') { 
 3800: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3801: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3802: 	   }
 3803: 	   return '';
 3804:        }
 3805:    }
 3806: 
 3807: # Restricted by state or randomout?
 3808: 
 3809:    if ($thisallowed=~/X/) {
 3810:       if ($env{'acc.randomout'}) {
 3811: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3812:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3813:             return ''; 
 3814:          }
 3815:       }
 3816:       if (&condval($statecond)) {
 3817: 	 return '2';
 3818:       } else {
 3819:          return '';
 3820:       }
 3821:    }
 3822: 
 3823:     if ($thisallowed eq 'A') {
 3824: 	return 'A';
 3825:     }
 3826:    return 'F';
 3827: }
 3828: 
 3829: sub split_uri_for_cond {
 3830:     my $uri=&deversion(&declutter(shift));
 3831:     my @uriparts=split(/\//,$uri);
 3832:     my $filename=pop(@uriparts);
 3833:     my $pathname=join('/',@uriparts);
 3834:     return ($pathname,$filename);
 3835: }
 3836: # --------------------------------------------------- Is a resource on the map?
 3837: 
 3838: sub is_on_map {
 3839:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3840:     #Trying to find the conditional for the file
 3841:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3842: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3843:     if ($match) {
 3844: 	return (1,$1);
 3845:     } else {
 3846: 	return (0,0);
 3847:     }
 3848: }
 3849: 
 3850: # --------------------------------------------------------- Get symb from alias
 3851: 
 3852: sub get_symb_from_alias {
 3853:     my $symb=shift;
 3854:     my ($map,$resid,$url)=&decode_symb($symb);
 3855: # Already is a symb
 3856:     if ($url) { return $symb; }
 3857: # Must be an alias
 3858:     my $aliassymb='';
 3859:     my %bighash;
 3860:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3861:                             &GDBM_READER(),0640)) {
 3862:         my $rid=$bighash{'mapalias_'.$symb};
 3863: 	if ($rid) {
 3864: 	    my ($mapid,$resid)=split(/\./,$rid);
 3865: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3866: 				    $resid,$bighash{'src_'.$rid});
 3867: 	}
 3868:         untie %bighash;
 3869:     }
 3870:     return $aliassymb;
 3871: }
 3872: 
 3873: # ----------------------------------------------------------------- Define Role
 3874: 
 3875: sub definerole {
 3876:   if (allowed('mcr','/')) {
 3877:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3878:     foreach (split(':',$sysrole)) {
 3879: 	my ($crole,$cqual)=split(/\&/,$_);
 3880:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3881:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3882: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3883:                return "refused:s:$crole&$cqual"; 
 3884:             }
 3885:         }
 3886:     }
 3887:     foreach (split(':',$domrole)) {
 3888: 	my ($crole,$cqual)=split(/\&/,$_);
 3889:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3890:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3891: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3892:                return "refused:d:$crole&$cqual"; 
 3893:             }
 3894:         }
 3895:     }
 3896:     foreach (split(':',$courole)) {
 3897: 	my ($crole,$cqual)=split(/\&/,$_);
 3898:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3899:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3900: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3901:                return "refused:c:$crole&$cqual"; 
 3902:             }
 3903:         }
 3904:     }
 3905:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3906:                 "$env{'user.domain'}:$env{'user.name'}:".
 3907: 	        "rolesdef_$rolename=".
 3908:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3909:     return reply($command,$env{'user.home'});
 3910:   } else {
 3911:     return 'refused';
 3912:   }
 3913: }
 3914: 
 3915: # ---------------- Make a metadata query against the network of library servers
 3916: 
 3917: sub metadata_query {
 3918:     my ($query,$custom,$customshow,$server_array)=@_;
 3919:     my %rhash;
 3920:     my @server_list = (defined($server_array) ? @$server_array
 3921:                                               : keys(%libserv) );
 3922:     for my $server (@server_list) {
 3923: 	unless ($custom or $customshow) {
 3924: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3925: 	    $rhash{$server}=$reply;
 3926: 	}
 3927: 	else {
 3928: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3929: 			     &escape($custom).':'.&escape($customshow),
 3930: 			     $server);
 3931: 	    $rhash{$server}=$reply;
 3932: 	}
 3933:     }
 3934:     return \%rhash;
 3935: }
 3936: 
 3937: # ----------------------------------------- Send log queries and wait for reply
 3938: 
 3939: sub log_query {
 3940:     my ($uname,$udom,$query,%filters)=@_;
 3941:     my $uhome=&homeserver($uname,$udom);
 3942:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3943:     my $uhost=$hostname{$uhome};
 3944:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3945:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3946:                        $uhome);
 3947:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3948:     return get_query_reply($queryid);
 3949: }
 3950: 
 3951: # ------- Request retrieval of institutional classlists for course(s)
 3952: 
 3953: sub fetch_enrollment_query {
 3954:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3955:     my $homeserver;
 3956:     my $maxtries = 1;
 3957:     if ($context eq 'automated') {
 3958:         $homeserver = $perlvar{'lonHostID'};
 3959:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3960:     } else {
 3961:         $homeserver = &homeserver($cnum,$dom);
 3962:     }
 3963:     my $host=$hostname{$homeserver};
 3964:     my $cmd = '';
 3965:     foreach (keys %{$affiliatesref}) {
 3966:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3967:     }
 3968:     $cmd =~ s/%%$//;
 3969:     $cmd = &escape($cmd);
 3970:     my $query = 'fetchenrollment';
 3971:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3972:     unless ($queryid=~/^\Q$host\E\_/) { 
 3973:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3974:         return 'error: '.$queryid;
 3975:     }
 3976:     my $reply = &get_query_reply($queryid);
 3977:     my $tries = 1;
 3978:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3979:         $reply = &get_query_reply($queryid);
 3980:         $tries ++;
 3981:     }
 3982:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3983:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3984:     } else {
 3985:         my @responses = split/:/,$reply;
 3986:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3987:             foreach (@responses) {
 3988:                 my ($key,$value) = split/=/,$_;
 3989:                 $$replyref{$key} = $value;
 3990:             }
 3991:         } else {
 3992:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3993:             foreach (@responses) {
 3994:                 my ($key,$value) = split/=/,$_;
 3995:                 $$replyref{$key} = $value;
 3996:                 if ($value > 0) {
 3997:                     foreach (@{$$affiliatesref{$key}}) {
 3998:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3999:                         my $destname = $pathname.'/'.$filename;
 4000:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4001:                         if ($xml_classlist =~ /^error/) {
 4002:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4003:                         } else {
 4004:                             if ( open(FILE,">$destname") ) {
 4005:                                 print FILE &unescape($xml_classlist);
 4006:                                 close(FILE);
 4007:                             } else {
 4008:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4009:                             }
 4010:                         }
 4011:                     }
 4012:                 }
 4013:             }
 4014:         }
 4015:         return 'ok';
 4016:     }
 4017:     return 'error';
 4018: }
 4019: 
 4020: sub get_query_reply {
 4021:     my $queryid=shift;
 4022:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4023:     my $reply='';
 4024:     for (1..100) {
 4025: 	sleep 2;
 4026:         if (-e $replyfile.'.end') {
 4027: 	    if (open(my $fh,$replyfile)) {
 4028:                $reply.=<$fh>;
 4029:                close($fh);
 4030: 	   } else { return 'error: reply_file_error'; }
 4031:            return &unescape($reply);
 4032: 	}
 4033:     }
 4034:     return 'timeout:'.$queryid;
 4035: }
 4036: 
 4037: sub courselog_query {
 4038: #
 4039: # possible filters:
 4040: # url: url or symb
 4041: # username
 4042: # domain
 4043: # action: view, submit, grade
 4044: # start: timestamp
 4045: # end: timestamp
 4046: #
 4047:     my (%filters)=@_;
 4048:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4049:     if ($filters{'url'}) {
 4050: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4051:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4052:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4053:     }
 4054:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4055:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4056:     return &log_query($cname,$cdom,'courselog',%filters);
 4057: }
 4058: 
 4059: sub userlog_query {
 4060:     my ($uname,$udom,%filters)=@_;
 4061:     return &log_query($uname,$udom,'userlog',%filters);
 4062: }
 4063: 
 4064: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4065: 
 4066: sub auto_run {
 4067:     my ($cnum,$cdom) = @_;
 4068:     my $homeserver = &homeserver($cnum,$cdom);
 4069:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4070:     return $response;
 4071: }
 4072: 
 4073: sub auto_get_sections {
 4074:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4075:     my $homeserver = &homeserver($cnum,$cdom);
 4076:     my @secs = ();
 4077:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4078:     unless ($response eq 'refused') {
 4079:         @secs = split/:/,$response;
 4080:     }
 4081:     return @secs;
 4082: }
 4083: 
 4084: sub auto_new_course {
 4085:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4086:     my $homeserver = &homeserver($cnum,$cdom);
 4087:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4088:     return $response;
 4089: }
 4090: 
 4091: sub auto_validate_courseID {
 4092:     my ($cnum,$cdom,$inst_course_id) = @_;
 4093:     my $homeserver = &homeserver($cnum,$cdom);
 4094:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4095:     return $response;
 4096: }
 4097: 
 4098: sub auto_create_password {
 4099:     my ($cnum,$cdom,$authparam) = @_;
 4100:     my $homeserver = &homeserver($cnum,$cdom); 
 4101:     my $create_passwd = 0;
 4102:     my $authchk = '';
 4103:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4104:     if ($response eq 'refused') {
 4105:         $authchk = 'refused';
 4106:     } else {
 4107:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4108:     }
 4109:     return ($authparam,$create_passwd,$authchk);
 4110: }
 4111: 
 4112: sub auto_photo_permission {
 4113:     my ($cnum,$cdom,$students) = @_;
 4114:     my $homeserver = &homeserver($cnum,$cdom);
 4115:     my ($outcome,$perm_reqd,$conditions) = 
 4116: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4117:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4118: 	return (undef,undef);
 4119:     }
 4120:     return ($outcome,$perm_reqd,$conditions);
 4121: }
 4122: 
 4123: sub auto_checkphotos {
 4124:     my ($uname,$udom,$pid) = @_;
 4125:     my $homeserver = &homeserver($uname,$udom);
 4126:     my ($result,$resulttype);
 4127:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4128: 				   &escape($uname).':'.&escape($pid),
 4129: 				   $homeserver));
 4130:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4131: 	return (undef,undef);
 4132:     }
 4133:     if ($outcome) {
 4134:         ($result,$resulttype) = split(/:/,$outcome);
 4135:     } 
 4136:     return ($result,$resulttype);
 4137: }
 4138: 
 4139: sub auto_photochoice {
 4140:     my ($cnum,$cdom) = @_;
 4141:     my $homeserver = &homeserver($cnum,$cdom);
 4142:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4143: 						       &escape($cdom),
 4144: 						       $homeserver)));
 4145:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4146: 	return (undef,undef);
 4147:     }
 4148:     return ($update,$comment);
 4149: }
 4150: 
 4151: sub auto_photoupdate {
 4152:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4153:     my $homeserver = &homeserver($cnum,$dom);
 4154:     my $host=$hostname{$homeserver};
 4155:     my $cmd = '';
 4156:     my $maxtries = 1;
 4157:     foreach (keys %{$affiliatesref}) {
 4158:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 4159:     }
 4160:     $cmd =~ s/%%$//;
 4161:     $cmd = &escape($cmd);
 4162:     my $query = 'institutionalphotos';
 4163:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4164:     unless ($queryid=~/^\Q$host\E\_/) {
 4165:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4166:         return 'error: '.$queryid;
 4167:     }
 4168:     my $reply = &get_query_reply($queryid);
 4169:     my $tries = 1;
 4170:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4171:         $reply = &get_query_reply($queryid);
 4172:         $tries ++;
 4173:     }
 4174:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4175:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4176:     } else {
 4177:         my @responses = split(/:/,$reply);
 4178:         my $outcome = shift(@responses); 
 4179:         foreach my $item (@responses) {
 4180:             my ($key,$value) = split(/=/,$item);
 4181:             $$photo{$key} = $value;
 4182:         }
 4183:         return $outcome;
 4184:     }
 4185:     return 'error';
 4186: }
 4187: 
 4188: sub auto_instcode_format {
 4189:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 4190:     my $courses = '';
 4191:     my @homeservers;
 4192:     if ($caller eq 'global') {
 4193:         foreach my $tryserver (keys %libserv) {
 4194:             if ($hostdom{$tryserver} eq $codedom) {
 4195:                 if (!grep/^\Q$tryserver\E$/,@homeservers) {
 4196:                     push(@homeservers,$tryserver);
 4197:                 }
 4198:             }
 4199:         }
 4200:     } else {
 4201:         push(@homeservers,&homeserver($caller,$codedom));
 4202:     }
 4203:     foreach (keys %{$instcodes}) {
 4204:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 4205:     }
 4206:     chop($courses);
 4207:     my $ok_response = 0;
 4208:     my $response;
 4209:     while (@homeservers > 0 && $ok_response == 0) {
 4210:         my $server = shift(@homeservers); 
 4211:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4212:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4213:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4214:                                                             split/:/,$response;
 4215:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4216:             push(@{$codetitles},&str2array($codetitles_str));
 4217:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4218:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4219:             $ok_response = 1;
 4220:         }
 4221:     }
 4222:     if ($ok_response) {
 4223:         return 'ok';
 4224:     } else {
 4225:         return $response;
 4226:     }
 4227: }
 4228: 
 4229: sub auto_validate_class_sec {
 4230:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4231:     my $homeserver = &homeserver($cnum,$cdom);
 4232:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4233:                         &escape($owner).':'.$cdom,$homeserver);
 4234:     return $response;
 4235: }
 4236: 
 4237: # ------------------------------------------------------- Course Group routines
 4238: 
 4239: sub get_coursegroups {
 4240:     my ($cdom,$cnum,$group) = @_;
 4241:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4242: }
 4243: 
 4244: sub modify_coursegroup {
 4245:     my ($cdom,$cnum,$groupsettings) = @_;
 4246:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4247: }
 4248: 
 4249: sub modify_group_roles {
 4250:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4251:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4252:     my $role = 'gr/'.&escape($userprivs);
 4253:     my ($uname,$udom) = split(/:/,$user);
 4254:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4255:     if ($result eq 'ok') {
 4256:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4257:     }
 4258:     return $result;
 4259: }
 4260: 
 4261: sub modify_coursegroup_membership {
 4262:     my ($cdom,$cnum,$membership) = @_;
 4263:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4264:     return $result;
 4265: }
 4266: 
 4267: sub get_active_groups {
 4268:     my ($udom,$uname,$cdom,$cnum) = @_;
 4269:     my $now = time;
 4270:     my %groups = ();
 4271:     foreach my $key (keys(%env)) {
 4272:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4273:             my ($start,$end) = split(/\./,$env{$key});
 4274:             if (($end!=0) && ($end<$now)) { next; }
 4275:             if (($start!=0) && ($start>$now)) { next; }
 4276:             if ($1 eq $cdom && $2 eq $cnum) {
 4277:                 $groups{$3} = $env{$key} ;
 4278:             }
 4279:         }
 4280:     }
 4281:     return %groups;
 4282: }
 4283: 
 4284: sub get_group_membership {
 4285:     my ($cdom,$cnum,$group) = @_;
 4286:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4287: }
 4288: 
 4289: sub get_users_groups {
 4290:     my ($udom,$uname,$courseid) = @_;
 4291:     my @usersgroups;
 4292:     my $cachetime=1800;
 4293:     $courseid=~s/\_/\//g;
 4294:     $courseid=~s/^(\w)/\/$1/;
 4295: 
 4296:     my $hashid="$udom:$uname:$courseid";
 4297:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4298:     if (defined($cached)) {
 4299:         @usersgroups = split(/:/,$grouplist);
 4300:     } else {  
 4301:         $grouplist = '';
 4302:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4303:         my ($tmp) = keys(%roleshash);
 4304:         if ($tmp=~/^error:/) {
 4305:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4306:         } else {
 4307:             my $access_end = $env{'course.'.$courseid.
 4308:                                   '.default_enrollment_end_date'};
 4309:             my $now = time;
 4310:             foreach my $key (keys(%roleshash)) {
 4311:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4312:                     my $group = $1;
 4313:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4314:                         my $start = $2;
 4315:                         my $end = $1;
 4316:                         if ($start == -1) { next; } # deleted from group
 4317:                         if (($start!=0) && ($start>$now)) { next; }
 4318:                         if (($end!=0) && ($end<$now)) {
 4319:                             if ($access_end && $access_end < $now) {
 4320:                                 if ($access_end - $end < 86400) {
 4321:                                     push(@usersgroups,$group);
 4322:                                 }
 4323:                             }
 4324:                             next;
 4325:                         }
 4326:                         push(@usersgroups,$group);
 4327:                     }
 4328:                 }
 4329:             }
 4330:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4331:             $grouplist = join(':',@usersgroups);
 4332:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4333:         }
 4334:     }
 4335:     return @usersgroups;
 4336: }
 4337: 
 4338: sub devalidate_getgroups_cache {
 4339:     my ($udom,$uname,$cdom,$cnum)=@_;
 4340:     my $courseid = $cdom.'_'.$cnum;
 4341:     $courseid=~s/\_/\//g;
 4342:     $courseid=~s/^(\w)/\/$1/;
 4343:     my $hashid="$udom:$uname:$courseid";
 4344:     &devalidate_cache_new('getgroups',$hashid);
 4345: }
 4346: 
 4347: # ------------------------------------------------------------------ Plain Text
 4348: 
 4349: sub plaintext {
 4350:     my ($short,$type,$cid) = @_;
 4351:     if ($short =~ /^cr/) {
 4352: 	return (split('/',$short))[-1];
 4353:     }
 4354:     if (!defined($cid)) {
 4355:         $cid = $env{'request.course.id'};
 4356:     }
 4357:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4358:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4359:                                           '.plaintext'});
 4360:     }
 4361:     my %rolenames = (
 4362:                       Course => 'std',
 4363:                       Group => 'alt1',
 4364:                     );
 4365:     if (defined($type) && 
 4366:          defined($rolenames{$type}) && 
 4367:          defined($prp{$short}{$rolenames{$type}})) {
 4368:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4369:     } else {
 4370:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4371:     }
 4372: }
 4373: 
 4374: # ----------------------------------------------------------------- Assign Role
 4375: 
 4376: sub assignrole {
 4377:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4378:     my $mrole;
 4379:     if ($role =~ /^cr\//) {
 4380:         my $cwosec=$url;
 4381:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4382: 	unless (&allowed('ccr',$cwosec)) {
 4383:            &logthis('Refused custom assignrole: '.
 4384:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4385: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4386:            return 'refused'; 
 4387:         }
 4388:         $mrole='cr';
 4389:     } elsif ($role =~ /^gr\//) {
 4390:         my $cwogrp=$url;
 4391:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4392:         unless (&allowed('mdg',$cwogrp)) {
 4393:             &logthis('Refused group assignrole: '.
 4394:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4395:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4396:             return 'refused';
 4397:         }
 4398:         $mrole='gr';
 4399:     } else {
 4400:         my $cwosec=$url;
 4401:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4402:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4403:            &logthis('Refused assignrole: '.
 4404:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4405: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4406:            return 'refused'; 
 4407:         }
 4408:         $mrole=$role;
 4409:     }
 4410:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4411:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4412:     if ($end) { $command.='_'.$end; }
 4413:     if ($start) {
 4414: 	if ($end) { 
 4415:            $command.='_'.$start; 
 4416:         } else {
 4417:            $command.='_0_'.$start;
 4418:         }
 4419:     }
 4420:     my $origstart = $start;
 4421:     my $origend = $end;
 4422: # actually delete
 4423:     if ($deleteflag) {
 4424: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4425: # modify command to delete the role
 4426:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4427:                 "$udom:$uname:$url".'_'."$mrole";
 4428: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4429: # set start and finish to negative values for userrolelog
 4430:            $start=-1;
 4431:            $end=-1;
 4432:         }
 4433:     }
 4434: # send command
 4435:     my $answer=&reply($command,&homeserver($uname,$udom));
 4436: # log new user role if status is ok
 4437:     if ($answer eq 'ok') {
 4438: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4439: # for course roles, perform group memberships changes triggered by role change.
 4440:         unless ($role =~ /^gr/) {
 4441:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4442:                                              $origstart);
 4443:         }
 4444:     }
 4445:     return $answer;
 4446: }
 4447: 
 4448: # -------------------------------------------------- Modify user authentication
 4449: # Overrides without validation
 4450: 
 4451: sub modifyuserauth {
 4452:     my ($udom,$uname,$umode,$upass)=@_;
 4453:     my $uhome=&homeserver($uname,$udom);
 4454:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4455:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4456:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4457:              ' in domain '.$env{'request.role.domain'});  
 4458:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4459: 		     &escape($upass),$uhome);
 4460:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4461:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4462:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4463:     &log($udom,,$uname,$uhome,
 4464:         'Authentication changed by '.$env{'user.domain'}.', '.
 4465:                                      $env{'user.name'}.', '.$umode.
 4466:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4467:     unless ($reply eq 'ok') {
 4468:         &logthis('Authentication mode error: '.$reply);
 4469: 	return 'error: '.$reply;
 4470:     }   
 4471:     return 'ok';
 4472: }
 4473: 
 4474: # --------------------------------------------------------------- Modify a user
 4475: 
 4476: sub modifyuser {
 4477:     my ($udom,    $uname, $uid,
 4478:         $umode,   $upass, $first,
 4479:         $middle,  $last,  $gene,
 4480:         $forceid, $desiredhome, $email)=@_;
 4481:     $udom=~s/\W//g;
 4482:     $uname=~s/\W//g;
 4483:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4484:              $umode.', '.$first.', '.$middle.', '.
 4485: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4486:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4487:                                      ' desiredhome not specified'). 
 4488:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4489:              ' in domain '.$env{'request.role.domain'});
 4490:     my $uhome=&homeserver($uname,$udom,'true');
 4491: # ----------------------------------------------------------------- Create User
 4492:     if (($uhome eq 'no_host') && 
 4493: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4494:         my $unhome='';
 4495:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4496:             $unhome = $desiredhome;
 4497: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4498: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4499:         } else { # load balancing routine for determining $unhome
 4500:             my $tryserver;
 4501:             my $loadm=10000000;
 4502:             foreach $tryserver (keys %libserv) {
 4503: 	       if ($hostdom{$tryserver} eq $udom) {
 4504:                   my $answer=reply('load',$tryserver);
 4505:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4506: 		      $loadm=$answer;
 4507:                       $unhome=$tryserver;
 4508:                   }
 4509: 	       }
 4510: 	    }
 4511:         }
 4512:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4513: 	    return 'error: unable to find a home server for '.$uname.
 4514:                    ' in domain '.$udom;
 4515:         }
 4516:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4517:                          &escape($upass),$unhome);
 4518: 	unless ($reply eq 'ok') {
 4519:             return 'error: '.$reply;
 4520:         }   
 4521:         $uhome=&homeserver($uname,$udom,'true');
 4522:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4523: 	    return 'error: unable verify users home machine.';
 4524:         }
 4525:     }   # End of creation of new user
 4526: # ---------------------------------------------------------------------- Add ID
 4527:     if ($uid) {
 4528:        $uid=~tr/A-Z/a-z/;
 4529:        my %uidhash=&idrget($udom,$uname);
 4530:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4531:          && (!$forceid)) {
 4532: 	  unless ($uid eq $uidhash{$uname}) {
 4533: 	      return 'error: user id "'.$uid.'" does not match '.
 4534:                   'current user id "'.$uidhash{$uname}.'".';
 4535:           }
 4536:        } else {
 4537: 	  &idput($udom,($uname => $uid));
 4538:        }
 4539:     }
 4540: # -------------------------------------------------------------- Add names, etc
 4541:     my @tmp=&get('environment',
 4542: 		   ['firstname','middlename','lastname','generation'],
 4543: 		   $udom,$uname);
 4544:     my %names;
 4545:     if ($tmp[0] =~ m/^error:.*/) { 
 4546:         %names=(); 
 4547:     } else {
 4548:         %names = @tmp;
 4549:     }
 4550: #
 4551: # Make sure to not trash student environment if instructor does not bother
 4552: # to supply name and email information
 4553: #
 4554:     if ($first)  { $names{'firstname'}  = $first; }
 4555:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4556:     if ($last)   { $names{'lastname'}   = $last; }
 4557:     if (defined($gene))   { $names{'generation'} = $gene; }
 4558:     if ($email) {
 4559:        $email=~s/[^\w\@\.\-\,]//gs;
 4560:        if ($email=~/\@/) { $names{'notification'} = $email;
 4561: 			   $names{'critnotification'} = $email;
 4562: 			   $names{'permanentemail'} = $email; }
 4563:     }
 4564:     my $reply = &put('environment', \%names, $udom,$uname);
 4565:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4566:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4567:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4568:              $umode.', '.$first.', '.$middle.', '.
 4569: 	     $last.', '.$gene.' by '.
 4570:              $env{'user.name'}.' at '.$env{'user.domain'});
 4571:     return 'ok';
 4572: }
 4573: 
 4574: # -------------------------------------------------------------- Modify student
 4575: 
 4576: sub modifystudent {
 4577:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4578:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4579:     if (!$cid) {
 4580: 	unless ($cid=$env{'request.course.id'}) {
 4581: 	    return 'not_in_class';
 4582: 	}
 4583:     }
 4584: # --------------------------------------------------------------- Make the user
 4585:     my $reply=&modifyuser
 4586: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4587:          $desiredhome,$email);
 4588:     unless ($reply eq 'ok') { return $reply; }
 4589:     # This will cause &modify_student_enrollment to get the uid from the
 4590:     # students environment
 4591:     $uid = undef if (!$forceid);
 4592:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4593: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4594:     return $reply;
 4595: }
 4596: 
 4597: sub modify_student_enrollment {
 4598:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4599:     my ($cdom,$cnum,$chome);
 4600:     if (!$cid) {
 4601: 	unless ($cid=$env{'request.course.id'}) {
 4602: 	    return 'not_in_class';
 4603: 	}
 4604: 	$cdom=$env{'course.'.$cid.'.domain'};
 4605: 	$cnum=$env{'course.'.$cid.'.num'};
 4606:     } else {
 4607: 	($cdom,$cnum)=split(/_/,$cid);
 4608:     }
 4609:     $chome=$env{'course.'.$cid.'.home'};
 4610:     if (!$chome) {
 4611: 	$chome=&homeserver($cnum,$cdom);
 4612:     }
 4613:     if (!$chome) { return 'unknown_course'; }
 4614:     # Make sure the user exists
 4615:     my $uhome=&homeserver($uname,$udom);
 4616:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4617: 	return 'error: no such user';
 4618:     }
 4619:     # Get student data if we were not given enough information
 4620:     if (!defined($first)  || $first  eq '' || 
 4621:         !defined($last)   || $last   eq '' || 
 4622:         !defined($uid)    || $uid    eq '' || 
 4623:         !defined($middle) || $middle eq '' || 
 4624:         !defined($gene)   || $gene   eq '') {
 4625:         # They did not supply us with enough data to enroll the student, so
 4626:         # we need to pick up more information.
 4627:         my %tmp = &get('environment',
 4628:                        ['firstname','middlename','lastname', 'generation','id']
 4629:                        ,$udom,$uname);
 4630: 
 4631:         #foreach (keys(%tmp)) {
 4632:         #    &logthis("key $_ = ".$tmp{$_});
 4633:         #}
 4634:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4635:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4636:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4637:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4638:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4639:     }
 4640:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4641:     my $reply=cput('classlist',
 4642: 		   {"$uname:$udom" => 
 4643: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4644: 		   $cdom,$cnum);
 4645:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4646: 	return 'error: '.$reply;
 4647:     } else {
 4648: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4649:     }
 4650:     # Add student role to user
 4651:     my $uurl='/'.$cid;
 4652:     $uurl=~s/\_/\//g;
 4653:     if ($usec) {
 4654: 	$uurl.='/'.$usec;
 4655:     }
 4656:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4657: }
 4658: 
 4659: sub format_name {
 4660:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4661:     my $name;
 4662:     if ($first ne 'lastname') {
 4663: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4664:     } else {
 4665: 	if ($lastname=~/\S/) {
 4666: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4667: 	    $name=~s/\s+,/,/;
 4668: 	} else {
 4669: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4670: 	}
 4671:     }
 4672:     $name=~s/^\s+//;
 4673:     $name=~s/\s+$//;
 4674:     $name=~s/\s+/ /g;
 4675:     return $name;
 4676: }
 4677: 
 4678: # ------------------------------------------------- Write to course preferences
 4679: 
 4680: sub writecoursepref {
 4681:     my ($courseid,%prefs)=@_;
 4682:     $courseid=~s/^\///;
 4683:     $courseid=~s/\_/\//g;
 4684:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4685:     my $chome=homeserver($cnum,$cdomain);
 4686:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4687: 	return 'error: no such course';
 4688:     }
 4689:     my $cstring='';
 4690:     foreach (keys %prefs) {
 4691: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4692:     }
 4693:     $cstring=~s/\&$//;
 4694:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4695: }
 4696: 
 4697: # ---------------------------------------------------------- Make/modify course
 4698: 
 4699: sub createcourse {
 4700:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4701:         $course_owner,$crstype)=@_;
 4702:     $url=&declutter($url);
 4703:     my $cid='';
 4704:     unless (&allowed('ccc',$udom)) {
 4705:         return 'refused';
 4706:     }
 4707: # ------------------------------------------------------------------- Create ID
 4708:    my $uname=int(1+rand(9)).
 4709:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4710:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4711:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4712: # ----------------------------------------------- Make sure that does not exist
 4713:    my $uhome=&homeserver($uname,$udom,'true');
 4714:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4715:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4716:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4717:        $uhome=&homeserver($uname,$udom,'true');       
 4718:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4719:            return 'error: unable to generate unique course-ID';
 4720:        } 
 4721:    }
 4722: # ------------------------------------------------ Check supplied server name
 4723:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4724:     if (! exists($libserv{$course_server})) {
 4725:         return 'error:bad server name '.$course_server;
 4726:     }
 4727: # ------------------------------------------------------------- Make the course
 4728:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4729:                       $course_server);
 4730:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4731:     $uhome=&homeserver($uname,$udom,'true');
 4732:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4733: 	return 'error: no such course';
 4734:     }
 4735: # ----------------------------------------------------------------- Course made
 4736: # log existence
 4737:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4738:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4739:                   &escape($crstype),$uhome);
 4740:     &flushcourselogs();
 4741: # set toplevel url
 4742:     my $topurl=$url;
 4743:     unless ($nonstandard) {
 4744: # ------------------------------------------ For standard courses, make top url
 4745:         my $mapurl=&clutter($url);
 4746:         if ($mapurl eq '/res/') { $mapurl=''; }
 4747:         $env{'form.initmap'}=(<<ENDINITMAP);
 4748: <map>
 4749: <resource id="1" type="start"></resource>
 4750: <resource id="2" src="$mapurl"></resource>
 4751: <resource id="3" type="finish"></resource>
 4752: <link index="1" from="1" to="2"></link>
 4753: <link index="2" from="2" to="3"></link>
 4754: </map>
 4755: ENDINITMAP
 4756:         $topurl=&declutter(
 4757:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4758:                           );
 4759:     }
 4760: # ----------------------------------------------------------- Write preferences
 4761:     &writecoursepref($udom.'_'.$uname,
 4762:                      ('description' => $description,
 4763:                       'url'         => $topurl));
 4764:     return '/'.$udom.'/'.$uname;
 4765: }
 4766: 
 4767: # ---------------------------------------------------------- Assign Custom Role
 4768: 
 4769: sub assigncustomrole {
 4770:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4771:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4772:                        $end,$start,$deleteflag);
 4773: }
 4774: 
 4775: # ----------------------------------------------------------------- Revoke Role
 4776: 
 4777: sub revokerole {
 4778:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4779:     my $now=time;
 4780:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4781: }
 4782: 
 4783: # ---------------------------------------------------------- Revoke Custom Role
 4784: 
 4785: sub revokecustomrole {
 4786:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4787:     my $now=time;
 4788:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4789:            $deleteflag);
 4790: }
 4791: 
 4792: # ------------------------------------------------------------ Disk usage
 4793: sub diskusage {
 4794:     my ($udom,$uname,$directoryRoot)=@_;
 4795:     $directoryRoot =~ s/\/$//;
 4796:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4797:     return $listing;
 4798: }
 4799: 
 4800: sub is_locked {
 4801:     my ($file_name, $domain, $user) = @_;
 4802:     my @check;
 4803:     my $is_locked;
 4804:     push @check, $file_name;
 4805:     my %locked = &get('file_permissions',\@check,
 4806: 		      $env{'user.domain'},$env{'user.name'});
 4807:     my ($tmp)=keys(%locked);
 4808:     if ($tmp=~/^error:/) { undef(%locked); }
 4809:     
 4810:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4811:         $is_locked = 'false';
 4812:         foreach my $entry (@{$locked{$file_name}}) {
 4813:            if (ref($entry) eq 'ARRAY') { 
 4814:                $is_locked = 'true';
 4815:                last;
 4816:            }
 4817:        }
 4818:     } else {
 4819:         $is_locked = 'false';
 4820:     }
 4821: }
 4822: 
 4823: sub declutter_portfile {
 4824:     my ($file) = @_;
 4825:     &logthis("got $file");
 4826:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 4827:     &logthis("ret $file");
 4828:     return $file;
 4829: }
 4830: 
 4831: # ------------------------------------------------------------- Mark as Read Only
 4832: 
 4833: sub mark_as_readonly {
 4834:     my ($domain,$user,$files,$what) = @_;
 4835:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4836:     my ($tmp)=keys(%current_permissions);
 4837:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4838:     foreach my $file (@{$files}) {
 4839: 	$file = &declutter_portfile($file);
 4840:         push(@{$current_permissions{$file}},$what);
 4841:     }
 4842:     &put('file_permissions',\%current_permissions,$domain,$user);
 4843:     return;
 4844: }
 4845: 
 4846: # ------------------------------------------------------------Save Selected Files
 4847: 
 4848: sub save_selected_files {
 4849:     my ($user, $path, @files) = @_;
 4850:     my $filename = $user."savedfiles";
 4851:     my @other_files = &files_not_in_path($user, $path);
 4852:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4853:     foreach my $file (@files) {
 4854:         print (OUT $env{'form.currentpath'}.$file."\n");
 4855:     }
 4856:     foreach my $file (@other_files) {
 4857:         print (OUT $file."\n");
 4858:     }
 4859:     close (OUT);
 4860:     return 'ok';
 4861: }
 4862: 
 4863: sub clear_selected_files {
 4864:     my ($user) = @_;
 4865:     my $filename = $user."savedfiles";
 4866:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4867:     print (OUT undef);
 4868:     close (OUT);
 4869:     return ("ok");    
 4870: }
 4871: 
 4872: sub files_in_path {
 4873:     my ($user, $path) = @_;
 4874:     my $filename = $user."savedfiles";
 4875:     my %return_files;
 4876:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4877:     while (my $line_in = <IN>) {
 4878:         chomp ($line_in);
 4879:         my @paths_and_file = split (m!/!, $line_in);
 4880:         my $file_part = pop (@paths_and_file);
 4881:         my $path_part = join ('/', @paths_and_file);
 4882:         $path_part.='/';
 4883:         my $path_and_file = $path_part.$file_part;
 4884:         if ($path_part eq $path) {
 4885:             $return_files{$file_part}= 'selected';
 4886:         }
 4887:     }
 4888:     close (IN);
 4889:     return (\%return_files);
 4890: }
 4891: 
 4892: # called in portfolio select mode, to show files selected NOT in current directory
 4893: sub files_not_in_path {
 4894:     my ($user, $path) = @_;
 4895:     my $filename = $user."savedfiles";
 4896:     my @return_files;
 4897:     my $path_part;
 4898:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4899:     while (<IN>) {
 4900:         #ok, I know it's clunky, but I want it to work
 4901:         my @paths_and_file = split m!/!, $_;
 4902:         my $file_part = pop (@paths_and_file);
 4903:         chomp ($file_part);
 4904:         my $path_part = join ('/', @paths_and_file);
 4905:         $path_part .= '/';
 4906:         my $path_and_file = $path_part.$file_part;
 4907:         if ($path_part ne $path) {
 4908:             push (@return_files, ($path_and_file));
 4909:         }
 4910:     }
 4911:     close (OUT);
 4912:     return (@return_files);
 4913: }
 4914: 
 4915: #----------------------------------------------Get portfolio file permissions
 4916: 
 4917: sub get_portfile_permissions {
 4918:     my ($domain,$user) = @_;
 4919:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4920:     my ($tmp)=keys(%current_permissions);
 4921:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4922:     return \%current_permissions;
 4923: }
 4924: 
 4925: #---------------------------------------------Get portfolio file access controls
 4926: 
 4927: sub get_access_controls {
 4928:     my ($current_permissions,$group,$file) = @_;
 4929:     my %access;
 4930:     my $real_file = $file;
 4931:     $file =~ s/\.meta$//;
 4932:     if (defined($file)) {
 4933:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 4934:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 4935:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 4936:             }
 4937:         }
 4938:     } else {
 4939:         foreach my $key (keys(%{$current_permissions})) {
 4940:             if ($key =~ /\0accesscontrol$/) {
 4941:                 if (defined($group)) {
 4942:                     if ($key !~ m-^\Q$group\E/-) {
 4943:                         next;
 4944:                     }
 4945:                 }
 4946:                 my ($fullpath) = split(/\0/,$key);
 4947:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 4948:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 4949:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 4950:                     }
 4951:                 }
 4952:             }
 4953:         }
 4954:     }
 4955:     return %access;
 4956: }
 4957: 
 4958: sub modify_access_controls {
 4959:     my ($file_name,$changes,$domain,$user)=@_;
 4960:     my ($outcome,$deloutcome);
 4961:     my %store_permissions;
 4962:     my %new_values;
 4963:     my %new_control;
 4964:     my %translation;
 4965:     my @deletions = ();
 4966:     my $now = time;
 4967:     if (exists($$changes{'activate'})) {
 4968:         if (ref($$changes{'activate'}) eq 'HASH') {
 4969:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 4970:             my $numnew = scalar(@newitems);
 4971:             for (my $i=0; $i<$numnew; $i++) {
 4972:                 my $newkey = $newitems[$i];
 4973:                 my $newid = &Apache::loncommon::get_cgi_id();
 4974:                 $newkey =~ s/^(\d+)/$newid/;
 4975:                 $translation{$1} = $newid;
 4976:                 $new_values{$file_name."\0".$newkey} = 
 4977:                                           $$changes{'activate'}{$newitems[$i]};
 4978:                 $new_control{$newkey} = $now;
 4979:             }
 4980:         }
 4981:     }
 4982:     my %todelete;
 4983:     my %changed_items;
 4984:     foreach my $action ('delete','update') {
 4985:         if (exists($$changes{$action})) {
 4986:             if (ref($$changes{$action}) eq 'HASH') {
 4987:                 foreach my $key (keys(%{$$changes{$action}})) {
 4988:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 4989:                     if ($action eq 'delete') { 
 4990:                         $todelete{$itemnum} = 1;
 4991:                     } else {
 4992:                         $changed_items{$itemnum} = $key;
 4993:                     }
 4994:                 }
 4995:             }
 4996:         }
 4997:     }
 4998:     # get lock on access controls for file.
 4999:     my $lockhash = {
 5000:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5001:                                                        ':'.$env{'user.domain'},
 5002:                    }; 
 5003:     my $tries = 0;
 5004:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5005:    
 5006:     while (($gotlock ne 'ok') && $tries <3) {
 5007:         $tries ++;
 5008:         sleep 1;
 5009:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5010:     }
 5011:     if ($gotlock eq 'ok') {
 5012:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5013:         my ($tmp)=keys(%curr_permissions);
 5014:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5015:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5016:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5017:             if (ref($curr_controls) eq 'HASH') {
 5018:                 foreach my $control_item (keys(%{$curr_controls})) {
 5019:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5020:                     if (defined($todelete{$itemnum})) {
 5021:                         push(@deletions,$file_name."\0".$control_item);
 5022:                     } else {
 5023:                         if (defined($changed_items{$itemnum})) {
 5024:                             $new_control{$changed_items{$itemnum}} = $now;
 5025:                             push(@deletions,$file_name."\0".$control_item);
 5026:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5027:                         } else {
 5028:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5029:                         }
 5030:                     }
 5031:                 }
 5032:             }
 5033:         }
 5034:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5035:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5036:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5037:         #  remove lock
 5038:         my @del_lock = ($file_name."\0".'locked_access_records');
 5039:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5040:     } else {
 5041:         $outcome = "error: could not obtain lockfile\n";  
 5042:     }
 5043:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5044: }
 5045: 
 5046: #------------------------------------------------------Get Marked as Read Only
 5047: 
 5048: sub get_marked_as_readonly {
 5049:     my ($domain,$user,$what,$group) = @_;
 5050:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5051:     my @readonly_files;
 5052:     my $cmp1=$what;
 5053:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5054:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5055:         if (defined($group)) {
 5056:             if ($file_name !~ m-^\Q$group\E/-) {
 5057:                 next;
 5058:             }
 5059:         }
 5060:         if (ref($value) eq "ARRAY"){
 5061:             foreach my $stored_what (@{$value}) {
 5062:                 my $cmp2=$stored_what;
 5063:                 if (ref($stored_what) eq 'ARRAY') {
 5064:                     $cmp2=join('',@{$stored_what});
 5065:                 }
 5066:                 if ($cmp1 eq $cmp2) {
 5067:                     push(@readonly_files, $file_name);
 5068:                     last;
 5069:                 } elsif (!defined($what)) {
 5070:                     push(@readonly_files, $file_name);
 5071:                     last;
 5072:                 }
 5073:             }
 5074:         }
 5075:     }
 5076:     return @readonly_files;
 5077: }
 5078: #-----------------------------------------------------------Get Marked as Read Only Hash
 5079: 
 5080: sub get_marked_as_readonly_hash {
 5081:     my ($current_permissions,$group,$what) = @_;
 5082:     my %readonly_files;
 5083:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5084:         if (defined($group)) {
 5085:             if ($file_name !~ m-^\Q$group\E/-) {
 5086:                 next;
 5087:             }
 5088:         }
 5089:         if (ref($value) eq "ARRAY"){
 5090:             foreach my $stored_what (@{$value}) {
 5091:                 if (ref($stored_what) eq 'ARRAY') {
 5092:                     foreach my $lock_descriptor(@{$stored_what}) {
 5093:                         if ($lock_descriptor eq 'graded') {
 5094:                             $readonly_files{$file_name} = 'graded';
 5095:                         } elsif ($lock_descriptor eq 'handback') {
 5096:                             $readonly_files{$file_name} = 'handback';
 5097:                         } else {
 5098:                             if (!exists($readonly_files{$file_name})) {
 5099:                                 $readonly_files{$file_name} = 'locked';
 5100:                             }
 5101:                         }
 5102:                     }
 5103:                 } 
 5104:             }
 5105:         } 
 5106:     }
 5107:     return %readonly_files;
 5108: }
 5109: # ------------------------------------------------------------ Unmark as Read Only
 5110: 
 5111: sub unmark_as_readonly {
 5112:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5113:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5114:     my ($domain,$user,$what,$file_name,$group) = @_;
 5115:     $file_name = &declutter_portfile($file_name);
 5116:     my $symb_crs = $what;
 5117:     if (ref($what)) { $symb_crs=join('',@$what); }
 5118:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5119:     my ($tmp)=keys(%current_permissions);
 5120:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5121:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5122:     foreach my $file (@readonly_files) {
 5123: 	my $clean_file = &declutter_portfile($file);
 5124: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5125: 	my $current_locks = $current_permissions{$file};
 5126:         my @new_locks;
 5127:         my @del_keys;
 5128:         if (ref($current_locks) eq "ARRAY"){
 5129:             foreach my $locker (@{$current_locks}) {
 5130:                 my $compare=$locker;
 5131:                 if (ref($locker) eq 'ARRAY') {
 5132:                     $compare=join('',@{$locker});
 5133:                     if ($compare ne $symb_crs) {
 5134:                         push(@new_locks, $locker);
 5135:                     }
 5136:                 }
 5137:             }
 5138:             if (scalar(@new_locks) > 0) {
 5139:                 $current_permissions{$file} = \@new_locks;
 5140:             } else {
 5141:                 push(@del_keys, $file);
 5142:                 &del('file_permissions',\@del_keys, $domain, $user);
 5143:                 delete($current_permissions{$file});
 5144:             }
 5145:         }
 5146:     }
 5147:     &put('file_permissions',\%current_permissions,$domain,$user);
 5148:     return;
 5149: }
 5150: 
 5151: # ------------------------------------------------------------ Directory lister
 5152: 
 5153: sub dirlist {
 5154:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5155: 
 5156:     $uri=~s/^\///;
 5157:     $uri=~s/\/$//;
 5158:     my ($udom, $uname);
 5159:     (undef,$udom,$uname)=split(/\//,$uri);
 5160:     if(defined($userdomain)) {
 5161:         $udom = $userdomain;
 5162:     }
 5163:     if(defined($username)) {
 5164:         $uname = $username;
 5165:     }
 5166: 
 5167:     my $dirRoot = $perlvar{'lonDocRoot'};
 5168:     if(defined($alternateDirectoryRoot)) {
 5169:         $dirRoot = $alternateDirectoryRoot;
 5170:         $dirRoot =~ s/\/$//;
 5171:     }
 5172: 
 5173:     if($udom) {
 5174:         if($uname) {
 5175:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 5176:                               homeserver($uname,$udom));
 5177:             my @listing_results;
 5178:             if ($listing eq 'unknown_cmd') {
 5179:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 5180:                                homeserver($uname,$udom));
 5181:                 @listing_results = split(/:/,$listing);
 5182:             } else {
 5183:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5184:             }
 5185:             return @listing_results;
 5186:         } elsif(!defined($alternateDirectoryRoot)) {
 5187:             my $tryserver;
 5188:             my %allusers=();
 5189:             foreach $tryserver (keys %libserv) {
 5190:                 if($hostdom{$tryserver} eq $udom) {
 5191:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5192:                                       $udom, $tryserver);
 5193:                     my @listing_results;
 5194:                     if ($listing eq 'unknown_cmd') {
 5195:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5196:                                        $udom, $tryserver);
 5197:                         @listing_results = split(/:/,$listing);
 5198:                     } else {
 5199:                         @listing_results =
 5200:                             map { &unescape($_); } split(/:/,$listing);
 5201:                     }
 5202:                     if ($listing_results[0] ne 'no_such_dir' && 
 5203:                         $listing_results[0] ne 'empty'       &&
 5204:                         $listing_results[0] ne 'con_lost') {
 5205:                         foreach (@listing_results) {
 5206:                             my ($entry,@stat)=split(/&/,$_);
 5207:                             $allusers{$entry}=1;
 5208:                         }
 5209:                     }
 5210:                 }
 5211:             }
 5212:             my $alluserstr='';
 5213:             foreach (sort keys %allusers) {
 5214:                 $alluserstr.=$_.'&user:';
 5215:             }
 5216:             $alluserstr=~s/:$//;
 5217:             return split(/:/,$alluserstr);
 5218:         } else {
 5219:             my @emptyResults = ();
 5220:             push(@emptyResults, 'missing user name');
 5221:             return split(':',@emptyResults);
 5222:         }
 5223:     } elsif(!defined($alternateDirectoryRoot)) {
 5224:         my $tryserver;
 5225:         my %alldom=();
 5226:         foreach $tryserver (keys %libserv) {
 5227:             $alldom{$hostdom{$tryserver}}=1;
 5228:         }
 5229:         my $alldomstr='';
 5230:         foreach (sort keys %alldom) {
 5231:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 5232:         }
 5233:         $alldomstr=~s/:$//;
 5234:         return split(/:/,$alldomstr);       
 5235:     } else {
 5236:         my @emptyResults = ();
 5237:         push(@emptyResults, 'missing domain');
 5238:         return split(':',@emptyResults);
 5239:     }
 5240: }
 5241: 
 5242: # --------------------------------------------- GetFileTimestamp
 5243: # This function utilizes dirlist and returns the date stamp for
 5244: # when it was last modified.  It will also return an error of -1
 5245: # if an error occurs
 5246: 
 5247: ##
 5248: ## FIXME: This subroutine assumes its caller knows something about the
 5249: ## directory structure of the home server for the student ($root).
 5250: ## Not a good assumption to make.  Since this is for looking up files
 5251: ## in user directories, the full path should be constructed by lond, not
 5252: ## whatever machine we request data from.
 5253: ##
 5254: sub GetFileTimestamp {
 5255:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5256:     $studentDomain=~s/\W//g;
 5257:     $studentName=~s/\W//g;
 5258:     my $subdir=$studentName.'__';
 5259:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5260:     my $proname="$studentDomain/$subdir/$studentName";
 5261:     $proname .= '/'.$filename;
 5262:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5263:                                               $studentName, $root);
 5264:     my @stats = split('&', $fileStat);
 5265:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5266:         # @stats contains first the filename, then the stat output
 5267:         return $stats[10]; # so this is 10 instead of 9.
 5268:     } else {
 5269:         return -1;
 5270:     }
 5271: }
 5272: 
 5273: sub stat_file {
 5274:     my ($uri) = @_;
 5275:     $uri = &clutter($uri);
 5276: 
 5277:     # we want just the url part without the unneeded accessor url bits
 5278:     if ($uri =~ m-^/adm/-) {
 5279: 	$uri=~s-^/adm/wrapper/-/-;
 5280: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 5281:     }
 5282:     my ($udom,$uname,$file,$dir);
 5283:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5284: 	($udom,$uname,$file) =
 5285: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5286: 	$file = 'userfiles/'.$file;
 5287: 	$dir = &propath($udom,$uname);
 5288:     }
 5289:     if ($uri =~ m-^/res/-) {
 5290: 	($udom,$uname) = 
 5291: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5292: 	$file = $uri;
 5293:     }
 5294: 
 5295:     if (!$udom || !$uname || !$file) {
 5296: 	# unable to handle the uri
 5297: 	return ();
 5298:     }
 5299: 
 5300:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5301:     my @stats = split('&', $result);
 5302:     
 5303:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5304: 	shift(@stats); #filename is first
 5305: 	return @stats;
 5306:     }
 5307:     return ();
 5308: }
 5309: 
 5310: # -------------------------------------------------------- Value of a Condition
 5311: 
 5312: # gets the value of a specific preevaluated condition
 5313: #    stored in the string  $env{user.state.<cid>}
 5314: # or looks up a condition reference in the bighash and if if hasn't
 5315: # already been evaluated recurses into docondval to get the value of
 5316: # the condition, then memoizing it to 
 5317: #   $env{user.state.<cid>.<condition>}
 5318: sub directcondval {
 5319:     my $number=shift;
 5320:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5321: 	&Apache::lonuserstate::evalstate();
 5322:     }
 5323:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5324: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5325:     } elsif ($number =~ /^_/) {
 5326: 	my $sub_condition;
 5327: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5328: 		&GDBM_READER(),0640)) {
 5329: 	    $sub_condition=$bighash{'conditions'.$number};
 5330: 	    untie(%bighash);
 5331: 	}
 5332: 	my $value = &docondval($sub_condition);
 5333: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5334: 	return $value;
 5335:     }
 5336:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5337:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5338:     } else {
 5339:        return 2;
 5340:     }
 5341: }
 5342: 
 5343: # get the collection of conditions for this resource
 5344: sub condval {
 5345:     my $condidx=shift;
 5346:     my $allpathcond='';
 5347:     foreach my $cond (split(/\|/,$condidx)) {
 5348: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5349: 	    $allpathcond.=
 5350: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5351: 	}
 5352:     }
 5353:     $allpathcond=~s/\|$//;
 5354:     return &docondval($allpathcond);
 5355: }
 5356: 
 5357: #evaluates an expression of conditions
 5358: sub docondval {
 5359:     my ($allpathcond) = @_;
 5360:     my $result=0;
 5361:     if ($env{'request.course.id'}
 5362: 	&& defined($allpathcond)) {
 5363: 	my $operand='|';
 5364: 	my @stack;
 5365: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5366: 	    if ($chunk eq '(') {
 5367: 		push @stack,($operand,$result);
 5368: 	    } elsif ($chunk eq ')') {
 5369: 		my $before=pop @stack;
 5370: 		if (pop @stack eq '&') {
 5371: 		    $result=$result>$before?$before:$result;
 5372: 		} else {
 5373: 		    $result=$result>$before?$result:$before;
 5374: 		}
 5375: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5376: 		$operand=$chunk;
 5377: 	    } else {
 5378: 		my $new=directcondval($chunk);
 5379: 		if ($operand eq '&') {
 5380: 		    $result=$result>$new?$new:$result;
 5381: 		} else {
 5382: 		    $result=$result>$new?$result:$new;
 5383: 		}
 5384: 	    }
 5385: 	}
 5386:     }
 5387:     return $result;
 5388: }
 5389: 
 5390: # ---------------------------------------------------- Devalidate courseresdata
 5391: 
 5392: sub devalidatecourseresdata {
 5393:     my ($coursenum,$coursedomain)=@_;
 5394:     my $hashid=$coursenum.':'.$coursedomain;
 5395:     &devalidate_cache_new('courseres',$hashid);
 5396: }
 5397: 
 5398: 
 5399: # --------------------------------------------------- Course Resourcedata Query
 5400: 
 5401: sub get_courseresdata {
 5402:     my ($coursenum,$coursedomain)=@_;
 5403:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5404:     my $hashid=$coursenum.':'.$coursedomain;
 5405:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5406:     my %dumpreply;
 5407:     unless (defined($cached)) {
 5408: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5409: 	$result=\%dumpreply;
 5410: 	my ($tmp) = keys(%dumpreply);
 5411: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5412: 	    &do_cache_new('courseres',$hashid,$result,600);
 5413: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5414: 	    return $tmp;
 5415: 	} elsif ($tmp =~ /^(error)/) {
 5416: 	    $result=undef;
 5417: 	    &do_cache_new('courseres',$hashid,$result,600);
 5418: 	}
 5419:     }
 5420:     return $result;
 5421: }
 5422: 
 5423: sub devalidateuserresdata {
 5424:     my ($uname,$udom)=@_;
 5425:     my $hashid="$udom:$uname";
 5426:     &devalidate_cache_new('userres',$hashid);
 5427: }
 5428: 
 5429: sub get_userresdata {
 5430:     my ($uname,$udom)=@_;
 5431:     #most student don\'t have any data set, check if there is some data
 5432:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5433: 
 5434:     my $hashid="$udom:$uname";
 5435:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5436:     if (!defined($cached)) {
 5437: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5438: 	$result=\%resourcedata;
 5439: 	&do_cache_new('userres',$hashid,$result,600);
 5440:     }
 5441:     my ($tmp)=keys(%$result);
 5442:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5443: 	return $result;
 5444:     }
 5445:     #error 2 occurs when the .db doesn't exist
 5446:     if ($tmp!~/error: 2 /) {
 5447: 	&logthis("<font color=\"blue\">WARNING:".
 5448: 		 " Trying to get resource data for ".
 5449: 		 $uname." at ".$udom.": ".
 5450: 		 $tmp."</font>");
 5451:     } elsif ($tmp=~/error: 2 /) {
 5452: 	#&EXT_cache_set($udom,$uname);
 5453: 	&do_cache_new('userres',$hashid,undef,600);
 5454: 	undef($tmp); # not really an error so don't send it back
 5455:     }
 5456:     return $tmp;
 5457: }
 5458: 
 5459: sub resdata {
 5460:     my ($name,$domain,$type,@which)=@_;
 5461:     my $result;
 5462:     if ($type eq 'course') {
 5463: 	$result=&get_courseresdata($name,$domain);
 5464:     } elsif ($type eq 'user') {
 5465: 	$result=&get_userresdata($name,$domain);
 5466:     }
 5467:     if (!ref($result)) { return $result; }    
 5468:     foreach my $item (@which) {
 5469: 	if (defined($result->{$item})) {
 5470: 	    return $result->{$item};
 5471: 	}
 5472:     }
 5473:     return undef;
 5474: }
 5475: 
 5476: #
 5477: # EXT resource caching routines
 5478: #
 5479: 
 5480: sub clear_EXT_cache_status {
 5481:     &delenv('cache.EXT.');
 5482: }
 5483: 
 5484: sub EXT_cache_status {
 5485:     my ($target_domain,$target_user) = @_;
 5486:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5487:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5488:         # We know already the user has no data
 5489:         return 1;
 5490:     } else {
 5491:         return 0;
 5492:     }
 5493: }
 5494: 
 5495: sub EXT_cache_set {
 5496:     my ($target_domain,$target_user) = @_;
 5497:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5498:     #&appenv($cachename => time);
 5499: }
 5500: 
 5501: # --------------------------------------------------------- Value of a Variable
 5502: sub EXT {
 5503: 
 5504:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5505:     unless ($varname) { return ''; }
 5506:     #get real user name/domain, courseid and symb
 5507:     my $courseid;
 5508:     my $publicuser;
 5509:     if ($symbparm) {
 5510: 	$symbparm=&get_symb_from_alias($symbparm);
 5511:     }
 5512:     if (!($uname && $udom)) {
 5513:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5514: 	  &Apache::lonxml::whichuser($symbparm);
 5515:       if (!$symbparm) {	$symbparm=$cursymb; }
 5516:     } else {
 5517: 	$courseid=$env{'request.course.id'};
 5518:     }
 5519:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5520:     my $rest;
 5521:     if (defined($therest[0])) {
 5522:        $rest=join('.',@therest);
 5523:     } else {
 5524:        $rest='';
 5525:     }
 5526: 
 5527:     my $qualifierrest=$qualifier;
 5528:     if ($rest) { $qualifierrest.='.'.$rest; }
 5529:     my $spacequalifierrest=$space;
 5530:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5531:     if ($realm eq 'user') {
 5532: # --------------------------------------------------------------- user.resource
 5533: 	if ($space eq 'resource') {
 5534: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5535: 		  || defined($Apache::lonhomework::parsing_a_task))
 5536: 		 &&
 5537: 		 ($symbparm eq &symbread()) ) {	
 5538: 		# if we are in the middle of processing the resource the
 5539: 		# get the value we are planning on committing
 5540:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5541:                     return $Apache::lonhomework::results{$qualifierrest};
 5542:                 } else {
 5543:                     return $Apache::lonhomework::history{$qualifierrest};
 5544:                 }
 5545: 	    } else {
 5546: 		my %restored;
 5547: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5548: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5549: 		} else {
 5550: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5551: 		}
 5552: 		return $restored{$qualifierrest};
 5553: 	    }
 5554: # ----------------------------------------------------------------- user.access
 5555:         } elsif ($space eq 'access') {
 5556: 	    # FIXME - not supporting calls for a specific user
 5557:             return &allowed($qualifier,$rest);
 5558: # ------------------------------------------ user.preferences, user.environment
 5559:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5560: 	    if (($uname eq $env{'user.name'}) &&
 5561: 		($udom eq $env{'user.domain'})) {
 5562: 		return $env{join('.',('environment',$qualifierrest))};
 5563: 	    } else {
 5564: 		my %returnhash;
 5565: 		if (!$publicuser) {
 5566: 		    %returnhash=&userenvironment($udom,$uname,
 5567: 						 $qualifierrest);
 5568: 		}
 5569: 		return $returnhash{$qualifierrest};
 5570: 	    }
 5571: # ----------------------------------------------------------------- user.course
 5572:         } elsif ($space eq 'course') {
 5573: 	    # FIXME - not supporting calls for a specific user
 5574:             return $env{join('.',('request.course',$qualifier))};
 5575: # ------------------------------------------------------------------- user.role
 5576:         } elsif ($space eq 'role') {
 5577: 	    # FIXME - not supporting calls for a specific user
 5578:             my ($role,$where)=split(/\./,$env{'request.role'});
 5579:             if ($qualifier eq 'value') {
 5580: 		return $role;
 5581:             } elsif ($qualifier eq 'extent') {
 5582:                 return $where;
 5583:             }
 5584: # ----------------------------------------------------------------- user.domain
 5585:         } elsif ($space eq 'domain') {
 5586:             return $udom;
 5587: # ------------------------------------------------------------------- user.name
 5588:         } elsif ($space eq 'name') {
 5589:             return $uname;
 5590: # ---------------------------------------------------- Any other user namespace
 5591:         } else {
 5592: 	    my %reply;
 5593: 	    if (!$publicuser) {
 5594: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5595: 	    }
 5596: 	    return $reply{$qualifierrest};
 5597:         }
 5598:     } elsif ($realm eq 'query') {
 5599: # ---------------------------------------------- pull stuff out of query string
 5600:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5601: 						[$spacequalifierrest]);
 5602: 	return $env{'form.'.$spacequalifierrest}; 
 5603:    } elsif ($realm eq 'request') {
 5604: # ------------------------------------------------------------- request.browser
 5605:         if ($space eq 'browser') {
 5606: 	    if ($qualifier eq 'textremote') {
 5607: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5608: 		    return 1;
 5609: 		} else {
 5610: 		    return 0;
 5611: 		}
 5612: 	    } else {
 5613: 		return $env{'browser.'.$qualifier};
 5614: 	    }
 5615: # ------------------------------------------------------------ request.filename
 5616:         } else {
 5617:             return $env{'request.'.$spacequalifierrest};
 5618:         }
 5619:     } elsif ($realm eq 'course') {
 5620: # ---------------------------------------------------------- course.description
 5621:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5622:     } elsif ($realm eq 'resource') {
 5623: 
 5624: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5625: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5626: 	}
 5627: 
 5628: 	if ($space eq 'title') {
 5629: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5630: 	    return &gettitle($symbparm);
 5631: 	}
 5632: 	
 5633: 	if ($space eq 'map') {
 5634: 	    my ($map) = &decode_symb($symbparm);
 5635: 	    return &symbread($map);
 5636: 	}
 5637: 
 5638: 	my ($section, $group, @groups);
 5639: 	my ($courselevelm,$courselevel);
 5640: 	if ($symbparm && defined($courseid) && 
 5641: 	    $courseid eq $env{'request.course.id'}) {
 5642: 
 5643: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5644: 
 5645: # ----------------------------------------------------- Cascading lookup scheme
 5646: 	    my $symbp=$symbparm;
 5647: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5648: 
 5649: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5650: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5651: 
 5652: 	    if (($env{'user.name'} eq $uname) &&
 5653: 		($env{'user.domain'} eq $udom)) {
 5654: 		$section=$env{'request.course.sec'};
 5655:                 @groups = split(/:/,$env{'request.course.groups'});  
 5656:                 @groups=&sort_course_groups($courseid,@groups); 
 5657: 	    } else {
 5658: 		if (! defined($usection)) {
 5659: 		    $section=&getsection($udom,$uname,$courseid);
 5660: 		} else {
 5661: 		    $section = $usection;
 5662: 		}
 5663:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5664: 	    }
 5665: 
 5666: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5667: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5668: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5669: 
 5670: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5671: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5672: 	    $courselevelm=$courseid.'.'.$mapparm;
 5673: 
 5674: # ----------------------------------------------------------- first, check user
 5675: 
 5676: 	    my $userreply=&resdata($uname,$udom,'user',
 5677: 				       ($courselevelr,$courselevelm,
 5678: 					$courselevel));
 5679: 	    if (defined($userreply)) { return $userreply; }
 5680: 
 5681: # ------------------------------------------------ second, check some of course
 5682:             my $coursereply;
 5683:             if (@groups > 0) {
 5684:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5685:                                        $mapparm,$spacequalifierrest);
 5686:                 if (defined($coursereply)) { return $coursereply; }
 5687:             }
 5688: 
 5689: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5690: 				     $env{'course.'.$courseid.'.domain'},
 5691: 				     'course',
 5692: 				     ($seclevelr,$seclevelm,$seclevel,
 5693: 				      $courselevelr));
 5694: 	    if (defined($coursereply)) { return $coursereply; }
 5695: 
 5696: # ------------------------------------------------------ third, check map parms
 5697: 	    my %parmhash=();
 5698: 	    my $thisparm='';
 5699: 	    if (tie(%parmhash,'GDBM_File',
 5700: 		    $env{'request.course.fn'}.'_parms.db',
 5701: 		    &GDBM_READER(),0640)) {
 5702: 		$thisparm=$parmhash{$symbparm};
 5703: 		untie(%parmhash);
 5704: 	    }
 5705: 	    if ($thisparm) { return $thisparm; }
 5706: 	}
 5707: # ------------------------------------------ fourth, look in resource metadata
 5708: 
 5709: 	$spacequalifierrest=~s/\./\_/;
 5710: 	my $filename;
 5711: 	if (!$symbparm) { $symbparm=&symbread(); }
 5712: 	if ($symbparm) {
 5713: 	    $filename=(&decode_symb($symbparm))[2];
 5714: 	} else {
 5715: 	    $filename=$env{'request.filename'};
 5716: 	}
 5717: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5718: 	if (defined($metadata)) { return $metadata; }
 5719: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5720: 	if (defined($metadata)) { return $metadata; }
 5721: 
 5722: # ---------------------------------------------- fourth, look in rest pf course
 5723: 	if ($symbparm && defined($courseid) && 
 5724: 	    $courseid eq $env{'request.course.id'}) {
 5725: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5726: 				     $env{'course.'.$courseid.'.domain'},
 5727: 				     'course',
 5728: 				     ($courselevelm,$courselevel));
 5729: 	    if (defined($coursereply)) { return $coursereply; }
 5730: 	}
 5731: # ------------------------------------------------------------------ Cascade up
 5732: 	unless ($space eq '0') {
 5733: 	    my @parts=split(/_/,$space);
 5734: 	    my $id=pop(@parts);
 5735: 	    my $part=join('_',@parts);
 5736: 	    if ($part eq '') { $part='0'; }
 5737: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5738: 				 $symbparm,$udom,$uname,$section,1);
 5739: 	    if (defined($partgeneral)) { return $partgeneral; }
 5740: 	}
 5741: 	if ($recurse) { return undef; }
 5742: 	my $pack_def=&packages_tab_default($filename,$varname);
 5743: 	if (defined($pack_def)) { return $pack_def; }
 5744: 
 5745: # ---------------------------------------------------- Any other user namespace
 5746:     } elsif ($realm eq 'environment') {
 5747: # ----------------------------------------------------------------- environment
 5748: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5749: 	    return $env{'environment.'.$spacequalifierrest};
 5750: 	} else {
 5751: 	    if ($uname eq 'anonymous' && $udom eq '') {
 5752: 		return '';
 5753: 	    }
 5754: 	    my %returnhash=&userenvironment($udom,$uname,
 5755: 					    $spacequalifierrest);
 5756: 	    return $returnhash{$spacequalifierrest};
 5757: 	}
 5758:     } elsif ($realm eq 'system') {
 5759: # ----------------------------------------------------------------- system.time
 5760: 	if ($space eq 'time') {
 5761: 	    return time;
 5762:         }
 5763:     } elsif ($realm eq 'server') {
 5764: # ----------------------------------------------------------------- system.time
 5765: 	if ($space eq 'name') {
 5766: 	    return $ENV{'SERVER_NAME'};
 5767:         }
 5768:     }
 5769:     return '';
 5770: }
 5771: 
 5772: sub check_group_parms {
 5773:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5774:     my @groupitems = ();
 5775:     my $resultitem;
 5776:     my @levels = ($symbparm,$mapparm,$what);
 5777:     foreach my $group (@{$groups}) {
 5778:         foreach my $level (@levels) {
 5779:              my $item = $courseid.'.['.$group.'].'.$level;
 5780:              push(@groupitems,$item);
 5781:         }
 5782:     }
 5783:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5784:                             $env{'course.'.$courseid.'.domain'},
 5785:                                      'course',@groupitems);
 5786:     return $coursereply;
 5787: }
 5788: 
 5789: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5790:     my ($courseid,@groups) = @_;
 5791:     @groups = sort(@groups);
 5792:     return @groups;
 5793: }
 5794: 
 5795: sub packages_tab_default {
 5796:     my ($uri,$varname)=@_;
 5797:     my (undef,$part,$name)=split(/\./,$varname);
 5798: 
 5799:     my (@extension,@specifics,$do_default);
 5800:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5801: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5802: 	if ($pack_type eq 'default') {
 5803: 	    $do_default=1;
 5804: 	} elsif ($pack_type eq 'extension') {
 5805: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5806: 	} else {
 5807: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5808: 	}
 5809:     }
 5810:     # first look for a package that matches the requested part id
 5811:     foreach my $package (@specifics) {
 5812: 	my (undef,$pack_type,$pack_part)=@{$package};
 5813: 	next if ($pack_part ne $part);
 5814: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5815: 	    return $packagetab{"$pack_type&$name&default"};
 5816: 	}
 5817:     }
 5818:     # look for any possible matching non extension_ package
 5819:     foreach my $package (@specifics) {
 5820: 	my (undef,$pack_type,$pack_part)=@{$package};
 5821: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5822: 	    return $packagetab{"$pack_type&$name&default"};
 5823: 	}
 5824: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5825: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5826: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5827: 	}
 5828:     }
 5829:     # look for any posible extension_ match
 5830:     foreach my $package (@extension) {
 5831: 	my ($package,$pack_type)=@{$package};
 5832: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5833: 	    return $packagetab{"$pack_type&$name&default"};
 5834: 	}
 5835: 	if (defined($packagetab{$package."&$name&default"})) {
 5836: 	    return $packagetab{$package."&$name&default"};
 5837: 	}
 5838:     }
 5839:     # look for a global default setting
 5840:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5841: 	return $packagetab{"default&$name&default"};
 5842:     }
 5843:     return undef;
 5844: }
 5845: 
 5846: sub add_prefix_and_part {
 5847:     my ($prefix,$part)=@_;
 5848:     my $keyroot;
 5849:     if (defined($prefix) && $prefix !~ /^__/) {
 5850: 	# prefix that has a part already
 5851: 	$keyroot=$prefix;
 5852:     } elsif (defined($prefix)) {
 5853: 	# prefix that is missing a part
 5854: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5855:     } else {
 5856: 	# no prefix at all
 5857: 	if (defined($part)) { $keyroot='_'.$part; }
 5858:     }
 5859:     return $keyroot;
 5860: }
 5861: 
 5862: # ---------------------------------------------------------------- Get metadata
 5863: 
 5864: my %metaentry;
 5865: sub metadata {
 5866:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5867:     $uri=&declutter($uri);
 5868:     # if it is a non metadata possible uri return quickly
 5869:     if (($uri eq '') || 
 5870: 	(($uri =~ m|^/*adm/|) && 
 5871: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5872:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5873: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5874: 	return undef;
 5875:     }
 5876:     my $filename=$uri;
 5877:     $uri=~s/\.meta$//;
 5878: #
 5879: # Is the metadata already cached?
 5880: # Look at timestamp of caching
 5881: # Everything is cached by the main uri, libraries are never directly cached
 5882: #
 5883:     if (!defined($liburi)) {
 5884: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5885: 	if (defined($cached)) { return $result->{':'.$what}; }
 5886:     }
 5887:     {
 5888: #
 5889: # Is this a recursive call for a library?
 5890: #
 5891: #	if (! exists($metacache{$uri})) {
 5892: #	    $metacache{$uri}={};
 5893: #	}
 5894:         if ($liburi) {
 5895: 	    $liburi=&declutter($liburi);
 5896:             $filename=$liburi;
 5897:         } else {
 5898: 	    &devalidate_cache_new('meta',$uri);
 5899: 	    undef(%metaentry);
 5900: 	}
 5901:         my %metathesekeys=();
 5902:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5903: 	my $metastring;
 5904: 	if ($uri !~ m -^(editupload)/-) {
 5905: 	    my $file=&filelocation('',&clutter($filename));
 5906: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5907: 	    $metastring=&getfile($file);
 5908: 	}
 5909:         my $parser=HTML::LCParser->new(\$metastring);
 5910:         my $token;
 5911:         undef %metathesekeys;
 5912:         while ($token=$parser->get_token) {
 5913: 	    if ($token->[0] eq 'S') {
 5914: 		if (defined($token->[2]->{'package'})) {
 5915: #
 5916: # This is a package - get package info
 5917: #
 5918: 		    my $package=$token->[2]->{'package'};
 5919: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5920: 		    if (defined($token->[2]->{'id'})) { 
 5921: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5922: 		    }
 5923: 		    if ($metaentry{':packages'}) {
 5924: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5925: 		    } else {
 5926: 			$metaentry{':packages'}=$package.$keyroot;
 5927: 		    }
 5928: 		    foreach my $pack_entry (keys(%packagetab)) {
 5929: 			my $part=$keyroot;
 5930: 			$part=~s/^\_//;
 5931: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 5932: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 5933: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 5934: 			    # ignore package.tab specified default values
 5935:                             # here &package_tab_default() will fetch those
 5936: 			    if ($subp eq 'default') { next; }
 5937: 			    my $value=$packagetab{$pack_entry};
 5938: 			    my $unikey;
 5939: 			    if ($pack =~ /_0$/) {
 5940: 				$unikey='parameter_0_'.$name;
 5941: 				$part=0;
 5942: 			    } else {
 5943: 				$unikey='parameter'.$keyroot.'_'.$name;
 5944: 			    }
 5945: 			    if ($subp eq 'display') {
 5946: 				$value.=' [Part: '.$part.']';
 5947: 			    }
 5948: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5949: 			    $metathesekeys{$unikey}=1;
 5950: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5951: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5952: 			    }
 5953: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5954: 				$metaentry{':'.$unikey}=
 5955: 				    $metaentry{':'.$unikey.'.default'};
 5956: 			    }
 5957: 			}
 5958: 		    }
 5959: 		} else {
 5960: #
 5961: # This is not a package - some other kind of start tag
 5962: #
 5963: 		    my $entry=$token->[1];
 5964: 		    my $unikey;
 5965: 		    if ($entry eq 'import') {
 5966: 			$unikey='';
 5967: 		    } else {
 5968: 			$unikey=$entry;
 5969: 		    }
 5970: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5971: 
 5972: 		    if (defined($token->[2]->{'id'})) { 
 5973: 			$unikey.='_'.$token->[2]->{'id'}; 
 5974: 		    }
 5975: 
 5976: 		    if ($entry eq 'import') {
 5977: #
 5978: # Importing a library here
 5979: #
 5980: 			if ($depthcount<20) {
 5981: 			    my $location=$parser->get_text('/import');
 5982: 			    my $dir=$filename;
 5983: 			    $dir=~s|[^/]*$||;
 5984: 			    $location=&filelocation($dir,$location);
 5985: 			    my $metadata = 
 5986: 				&metadata($uri,'keys', $location,$unikey,
 5987: 					  $depthcount+1);
 5988: 			    foreach my $meta (split(',',$metadata)) {
 5989: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 5990: 				$metathesekeys{$meta}=1;
 5991: 			    }
 5992: 			}
 5993: 		    } else { 
 5994: 			
 5995: 			if (defined($token->[2]->{'name'})) { 
 5996: 			    $unikey.='_'.$token->[2]->{'name'}; 
 5997: 			}
 5998: 			$metathesekeys{$unikey}=1;
 5999: 			foreach my $param (@{$token->[3]}) {
 6000: 			    $metaentry{':'.$unikey.'.'.$param} =
 6001: 				$token->[2]->{$param};
 6002: 			}
 6003: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6004: 			my $default=$metaentry{':'.$unikey.'.default'};
 6005: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6006: 		 # only ws inside the tag, and not in default, so use default
 6007: 		 # as value
 6008: 			    $metaentry{':'.$unikey}=$default;
 6009: 			} else {
 6010: 		  # either something interesting inside the tag or default
 6011:                   # uninteresting
 6012: 			    $metaentry{':'.$unikey}=$internaltext;
 6013: 			}
 6014: # end of not-a-package not-a-library import
 6015: 		    }
 6016: # end of not-a-package start tag
 6017: 		}
 6018: # the next is the end of "start tag"
 6019: 	    }
 6020: 	}
 6021: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6022: 	foreach my $key (keys(%packagetab)) {
 6023: 	    #no specific packages #how's our extension
 6024: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6025: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6026: 					 \%metathesekeys);
 6027: 	}
 6028: 	if (!exists($metaentry{':packages'})) {
 6029: 	    foreach my $key (keys(%packagetab)) {
 6030: 		#no specific packages well let's get default then
 6031: 		if ($key!~/^default&/) { next; }
 6032: 		&metadata_create_package_def($uri,$key,'default',
 6033: 					     \%metathesekeys);
 6034: 	    }
 6035: 	}
 6036: # are there custom rights to evaluate
 6037: 	if ($metaentry{':copyright'} eq 'custom') {
 6038: 
 6039:     #
 6040:     # Importing a rights file here
 6041:     #
 6042: 	    unless ($depthcount) {
 6043: 		my $location=$metaentry{':customdistributionfile'};
 6044: 		my $dir=$filename;
 6045: 		$dir=~s|[^/]*$||;
 6046: 		$location=&filelocation($dir,$location);
 6047: 		my $rights_metadata =
 6048: 		    &metadata($uri,'keys',$location,'_rights',
 6049: 			      $depthcount+1);
 6050: 		foreach my $rights (split(',',$rights_metadata)) {
 6051: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6052: 		    $metathesekeys{$rights}=1;
 6053: 		}
 6054: 	    }
 6055: 	}
 6056: 	# uniqifiy package listing
 6057: 	my %seen;
 6058: 	my @uniq_packages =
 6059: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6060: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6061: 
 6062: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6063: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6064: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6065: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6066: # this is the end of "was not already recently cached
 6067:     }
 6068:     return $metaentry{':'.$what};
 6069: }
 6070: 
 6071: sub metadata_create_package_def {
 6072:     my ($uri,$key,$package,$metathesekeys)=@_;
 6073:     my ($pack,$name,$subp)=split(/\&/,$key);
 6074:     if ($subp eq 'default') { next; }
 6075:     
 6076:     if (defined($metaentry{':packages'})) {
 6077: 	$metaentry{':packages'}.=','.$package;
 6078:     } else {
 6079: 	$metaentry{':packages'}=$package;
 6080:     }
 6081:     my $value=$packagetab{$key};
 6082:     my $unikey;
 6083:     $unikey='parameter_0_'.$name;
 6084:     $metaentry{':'.$unikey.'.part'}=0;
 6085:     $$metathesekeys{$unikey}=1;
 6086:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6087: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6088:     }
 6089:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6090: 	$metaentry{':'.$unikey}=
 6091: 	    $metaentry{':'.$unikey.'.default'};
 6092:     }
 6093: }
 6094: 
 6095: sub metadata_generate_part0 {
 6096:     my ($metadata,$metacache,$uri) = @_;
 6097:     my %allnames;
 6098:     foreach my $metakey (keys(%$metadata)) {
 6099: 	if ($metakey=~/^parameter\_(.*)/) {
 6100: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6101: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6102: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6103: 	    $allnames{$name}=$part;
 6104: 	  }
 6105: 	}
 6106:     }
 6107:     foreach my $name (keys(%allnames)) {
 6108:       $$metadata{"parameter_0_$name"}=1;
 6109:       my $key=":parameter_0_$name";
 6110:       $$metacache{"$key.part"}='0';
 6111:       $$metacache{"$key.name"}=$name;
 6112:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6113: 					   $allnames{$name}.'_'.$name.
 6114: 					   '.type'};
 6115:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6116: 			     '.display'};
 6117:       my $expr='[Part: '.$allnames{$name}.']';
 6118:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6119:       $$metacache{"$key.display"}=$olddis;
 6120:     }
 6121: }
 6122: 
 6123: # ------------------------------------------------------ Devalidate title cache
 6124: 
 6125: sub devalidate_title_cache {
 6126:     my ($url)=@_;
 6127:     if (!$env{'request.course.id'}) { return; }
 6128:     my $symb=&symbread($url);
 6129:     if (!$symb) { return; }
 6130:     my $key=$env{'request.course.id'}."\0".$symb;
 6131:     &devalidate_cache_new('title',$key);
 6132: }
 6133: 
 6134: # ------------------------------------------------- Get the title of a resource
 6135: 
 6136: sub gettitle {
 6137:     my $urlsymb=shift;
 6138:     my $symb=&symbread($urlsymb);
 6139:     if ($symb) {
 6140: 	my $key=$env{'request.course.id'}."\0".$symb;
 6141: 	my ($result,$cached)=&is_cached_new('title',$key);
 6142: 	if (defined($cached)) { 
 6143: 	    return $result;
 6144: 	}
 6145: 	my ($map,$resid,$url)=&decode_symb($symb);
 6146: 	my $title='';
 6147: 	my %bighash;
 6148: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6149: 		&GDBM_READER(),0640)) {
 6150: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6151: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6152: 	    untie %bighash;
 6153: 	}
 6154: 	$title=~s/\&colon\;/\:/gs;
 6155: 	if ($title) {
 6156: 	    return &do_cache_new('title',$key,$title,600);
 6157: 	}
 6158: 	$urlsymb=$url;
 6159:     }
 6160:     my $title=&metadata($urlsymb,'title');
 6161:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6162:     return $title;
 6163: }
 6164: 
 6165: sub get_slot {
 6166:     my ($which,$cnum,$cdom)=@_;
 6167:     if (!$cnum || !$cdom) {
 6168: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 6169: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6170: 	$cnum=$env{'course.'.$courseid.'.num'};
 6171:     }
 6172:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6173:     my %slotinfo;
 6174:     if (exists($remembered{$key})) {
 6175: 	$slotinfo{$which} = $remembered{$key};
 6176:     } else {
 6177: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6178: 	&Apache::lonhomework::showhash(%slotinfo);
 6179: 	my ($tmp)=keys(%slotinfo);
 6180: 	if ($tmp=~/^error:/) { return (); }
 6181: 	$remembered{$key} = $slotinfo{$which};
 6182:     }
 6183:     if (ref($slotinfo{$which}) eq 'HASH') {
 6184: 	return %{$slotinfo{$which}};
 6185:     }
 6186:     return $slotinfo{$which};
 6187: }
 6188: # ------------------------------------------------- Update symbolic store links
 6189: 
 6190: sub symblist {
 6191:     my ($mapname,%newhash)=@_;
 6192:     $mapname=&deversion(&declutter($mapname));
 6193:     my %hash;
 6194:     if (($env{'request.course.fn'}) && (%newhash)) {
 6195:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6196:                       &GDBM_WRCREAT(),0640)) {
 6197: 	    foreach my $url (keys %newhash) {
 6198: 		next if ($url eq 'last_known'
 6199: 			 && $env{'form.no_update_last_known'});
 6200: 		$hash{declutter($url)}=&encode_symb($mapname,
 6201: 						    $newhash{$url}->[1],
 6202: 						    $newhash{$url}->[0]);
 6203:             }
 6204:             if (untie(%hash)) {
 6205: 		return 'ok';
 6206:             }
 6207:         }
 6208:     }
 6209:     return 'error';
 6210: }
 6211: 
 6212: # --------------------------------------------------------------- Verify a symb
 6213: 
 6214: sub symbverify {
 6215:     my ($symb,$thisurl)=@_;
 6216:     my $thisfn=$thisurl;
 6217: # wrapper not part of symbs
 6218:     $thisfn=~s/^\/adm\/wrapper//;
 6219:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 6220:     $thisfn=&declutter($thisfn);
 6221: # direct jump to resource in page or to a sequence - will construct own symbs
 6222:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6223: # check URL part
 6224:     my ($map,$resid,$url)=&decode_symb($symb);
 6225: 
 6226:     unless ($url eq $thisfn) { return 0; }
 6227: 
 6228:     $symb=&symbclean($symb);
 6229:     $thisurl=&deversion($thisurl);
 6230:     $thisfn=&deversion($thisfn);
 6231: 
 6232:     my %bighash;
 6233:     my $okay=0;
 6234: 
 6235:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6236:                             &GDBM_READER(),0640)) {
 6237:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6238:         unless ($ids) { 
 6239:            $ids=$bighash{'ids_/'.$thisurl};
 6240:         }
 6241:         if ($ids) {
 6242: # ------------------------------------------------------------------- Has ID(s)
 6243: 	    foreach (split(/\,/,$ids)) {
 6244: 	       my ($mapid,$resid)=split(/\./,$_);
 6245:                if (
 6246:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6247:    eq $symb) { 
 6248: 		   if (($env{'request.role.adv'}) ||
 6249: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 6250: 		       $okay=1; 
 6251: 		   }
 6252: 	       }
 6253: 	   }
 6254:         }
 6255: 	untie(%bighash);
 6256:     }
 6257:     return $okay;
 6258: }
 6259: 
 6260: # --------------------------------------------------------------- Clean-up symb
 6261: 
 6262: sub symbclean {
 6263:     my $symb=shift;
 6264:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6265: # remove version from map
 6266:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6267: 
 6268: # remove version from URL
 6269:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6270: 
 6271: # remove wrapper
 6272: 
 6273:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6274:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6275:     return $symb;
 6276: }
 6277: 
 6278: # ---------------------------------------------- Split symb to find map and url
 6279: 
 6280: sub encode_symb {
 6281:     my ($map,$resid,$url)=@_;
 6282:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6283: }
 6284: 
 6285: sub decode_symb {
 6286:     my $symb=shift;
 6287:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6288:     my ($map,$resid,$url)=split(/___/,$symb);
 6289:     return (&fixversion($map),$resid,&fixversion($url));
 6290: }
 6291: 
 6292: sub fixversion {
 6293:     my $fn=shift;
 6294:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6295:     my %bighash;
 6296:     my $uri=&clutter($fn);
 6297:     my $key=$env{'request.course.id'}.'_'.$uri;
 6298: # is this cached?
 6299:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6300:     if (defined($cached)) { return $result; }
 6301: # unfortunately not cached, or expired
 6302:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6303: 	    &GDBM_READER(),0640)) {
 6304:  	if ($bighash{'version_'.$uri}) {
 6305:  	    my $version=$bighash{'version_'.$uri};
 6306:  	    unless (($version eq 'mostrecent') || 
 6307: 		    ($version==&getversion($uri))) {
 6308:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6309:  	    }
 6310:  	}
 6311:  	untie %bighash;
 6312:     }
 6313:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6314: }
 6315: 
 6316: sub deversion {
 6317:     my $url=shift;
 6318:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6319:     return $url;
 6320: }
 6321: 
 6322: # ------------------------------------------------------ Return symb list entry
 6323: 
 6324: sub symbread {
 6325:     my ($thisfn,$donotrecurse)=@_;
 6326:     my $cache_str='request.symbread.cached.'.$thisfn;
 6327:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6328: # no filename provided? try from environment
 6329:     unless ($thisfn) {
 6330:         if ($env{'request.symb'}) {
 6331: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6332: 	}
 6333: 	$thisfn=$env{'request.filename'};
 6334:     }
 6335:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6336: # is that filename actually a symb? Verify, clean, and return
 6337:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6338: 	if (&symbverify($thisfn,$1)) {
 6339: 	    return $env{$cache_str}=&symbclean($thisfn);
 6340: 	}
 6341:     }
 6342:     $thisfn=declutter($thisfn);
 6343:     my %hash;
 6344:     my %bighash;
 6345:     my $syval='';
 6346:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6347:         my $targetfn = $thisfn;
 6348:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6349:             $targetfn = 'adm/wrapper/'.$thisfn;
 6350:         }
 6351: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6352: 	    $targetfn=$1;
 6353: 	}
 6354:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6355:                       &GDBM_READER(),0640)) {
 6356: 	    $syval=$hash{$targetfn};
 6357:             untie(%hash);
 6358:         }
 6359: # ---------------------------------------------------------- There was an entry
 6360:         if ($syval) {
 6361: 	    #unless ($syval=~/\_\d+$/) {
 6362: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6363: 		    #&appenv('request.ambiguous' => $thisfn);
 6364: 		    #return $env{$cache_str}='';
 6365: 		#}    
 6366: 		#$syval.=$1;
 6367: 	    #}
 6368:         } else {
 6369: # ------------------------------------------------------- Was not in symb table
 6370:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6371:                             &GDBM_READER(),0640)) {
 6372: # ---------------------------------------------- Get ID(s) for current resource
 6373:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6374:               unless ($ids) { 
 6375:                  $ids=$bighash{'ids_/'.$thisfn};
 6376:               }
 6377:               unless ($ids) {
 6378: # alias?
 6379: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6380:               }
 6381:               if ($ids) {
 6382: # ------------------------------------------------------------------- Has ID(s)
 6383:                  my @possibilities=split(/\,/,$ids);
 6384:                  if ($#possibilities==0) {
 6385: # ----------------------------------------------- There is only one possibility
 6386: 		     my ($mapid,$resid)=split(/\./,$ids);
 6387: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6388: 						    $resid,$thisfn);
 6389:                  } elsif (!$donotrecurse) {
 6390: # ------------------------------------------ There is more than one possibility
 6391:                      my $realpossible=0;
 6392:                      foreach (@possibilities) {
 6393: 			 my $file=$bighash{'src_'.$_};
 6394:                          if (&allowed('bre',$file)) {
 6395:          		    my ($mapid,$resid)=split(/\./,$_);
 6396:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6397: 				$realpossible++;
 6398:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6399: 						    $resid,$thisfn);
 6400:                             }
 6401: 			 }
 6402:                      }
 6403: 		     if ($realpossible!=1) { $syval=''; }
 6404:                  } else {
 6405:                      $syval='';
 6406:                  }
 6407: 	      }
 6408:               untie(%bighash)
 6409:            }
 6410:         }
 6411:         if ($syval) {
 6412: 	    return $env{$cache_str}=$syval;
 6413:         }
 6414:     }
 6415:     &appenv('request.ambiguous' => $thisfn);
 6416:     return $env{$cache_str}='';
 6417: }
 6418: 
 6419: # ---------------------------------------------------------- Return random seed
 6420: 
 6421: sub numval {
 6422:     my $txt=shift;
 6423:     $txt=~tr/A-J/0-9/;
 6424:     $txt=~tr/a-j/0-9/;
 6425:     $txt=~tr/K-T/0-9/;
 6426:     $txt=~tr/k-t/0-9/;
 6427:     $txt=~tr/U-Z/0-5/;
 6428:     $txt=~tr/u-z/0-5/;
 6429:     $txt=~s/\D//g;
 6430:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6431:     return int($txt);
 6432: }
 6433: 
 6434: sub numval2 {
 6435:     my $txt=shift;
 6436:     $txt=~tr/A-J/0-9/;
 6437:     $txt=~tr/a-j/0-9/;
 6438:     $txt=~tr/K-T/0-9/;
 6439:     $txt=~tr/k-t/0-9/;
 6440:     $txt=~tr/U-Z/0-5/;
 6441:     $txt=~tr/u-z/0-5/;
 6442:     $txt=~s/\D//g;
 6443:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6444:     my $total;
 6445:     foreach my $val (@txts) { $total+=$val; }
 6446:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6447:     return int($total);
 6448: }
 6449: 
 6450: sub numval3 {
 6451:     use integer;
 6452:     my $txt=shift;
 6453:     $txt=~tr/A-J/0-9/;
 6454:     $txt=~tr/a-j/0-9/;
 6455:     $txt=~tr/K-T/0-9/;
 6456:     $txt=~tr/k-t/0-9/;
 6457:     $txt=~tr/U-Z/0-5/;
 6458:     $txt=~tr/u-z/0-5/;
 6459:     $txt=~s/\D//g;
 6460:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6461:     my $total;
 6462:     foreach my $val (@txts) { $total+=$val; }
 6463:     if ($_64bit) { $total=(($total<<32)>>32); }
 6464:     return $total;
 6465: }
 6466: 
 6467: sub digest {
 6468:     my ($data)=@_;
 6469:     my $digest=&Digest::MD5::md5($data);
 6470:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6471:     my ($e,$f);
 6472:     {
 6473:         use integer;
 6474:         $e=($a+$b);
 6475:         $f=($c+$d);
 6476:         if ($_64bit) {
 6477:             $e=(($e<<32)>>32);
 6478:             $f=(($f<<32)>>32);
 6479:         }
 6480:     }
 6481:     if (wantarray) {
 6482: 	return ($e,$f);
 6483:     } else {
 6484: 	my $g;
 6485: 	{
 6486: 	    use integer;
 6487: 	    $g=($e+$f);
 6488: 	    if ($_64bit) {
 6489: 		$g=(($g<<32)>>32);
 6490: 	    }
 6491: 	}
 6492: 	return $g;
 6493:     }
 6494: }
 6495: 
 6496: sub latest_rnd_algorithm_id {
 6497:     return '64bit5';
 6498: }
 6499: 
 6500: sub get_rand_alg {
 6501:     my ($courseid)=@_;
 6502:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 6503:     if ($courseid) {
 6504: 	return $env{"course.$courseid.rndseed"};
 6505:     }
 6506:     return &latest_rnd_algorithm_id();
 6507: }
 6508: 
 6509: sub validCODE {
 6510:     my ($CODE)=@_;
 6511:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6512:     return 0;
 6513: }
 6514: 
 6515: sub getCODE {
 6516:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6517:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6518: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6519: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6520: 	return $Apache::lonhomework::history{'resource.CODE'};
 6521:     }
 6522:     return undef;
 6523: }
 6524: 
 6525: sub rndseed {
 6526:     my ($symb,$courseid,$domain,$username)=@_;
 6527: 
 6528:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 6529:     if (!$symb) {
 6530: 	unless ($symb=$wsymb) { return time; }
 6531:     }
 6532:     if (!$courseid) { $courseid=$wcourseid; }
 6533:     if (!$domain) { $domain=$wdomain; }
 6534:     if (!$username) { $username=$wusername }
 6535:     my $which=&get_rand_alg();
 6536:     if (defined(&getCODE())) {
 6537: 	if ($which eq '64bit5') {
 6538: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6539: 	} elsif ($which eq '64bit4') {
 6540: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6541: 	} else {
 6542: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6543: 	}
 6544:     } elsif ($which eq '64bit5') {
 6545: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6546:     } elsif ($which eq '64bit4') {
 6547: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6548:     } elsif ($which eq '64bit3') {
 6549: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6550:     } elsif ($which eq '64bit2') {
 6551: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6552:     } elsif ($which eq '64bit') {
 6553: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6554:     }
 6555:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6556: }
 6557: 
 6558: sub rndseed_32bit {
 6559:     my ($symb,$courseid,$domain,$username)=@_;
 6560:     {
 6561: 	use integer;
 6562: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6563: 	my $symbseed=numval($symb) << 22;
 6564: 	my $namechck=unpack("%32C*",$username) << 17;
 6565: 	my $nameseed=numval($username) << 12;
 6566: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6567: 	my $courseseed=unpack("%32C*",$courseid);
 6568: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6569: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6570: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6571: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6572: 	return $num;
 6573:     }
 6574: }
 6575: 
 6576: sub rndseed_64bit {
 6577:     my ($symb,$courseid,$domain,$username)=@_;
 6578:     {
 6579: 	use integer;
 6580: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6581: 	my $symbseed=numval($symb) << 10;
 6582: 	my $namechck=unpack("%32S*",$username);
 6583: 	
 6584: 	my $nameseed=numval($username) << 21;
 6585: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6586: 	my $courseseed=unpack("%32S*",$courseid);
 6587: 	
 6588: 	my $num1=$symbchck+$symbseed+$namechck;
 6589: 	my $num2=$nameseed+$domainseed+$courseseed;
 6590: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6591: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6592: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6593: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6594: 	return "$num1,$num2";
 6595:     }
 6596: }
 6597: 
 6598: sub rndseed_64bit2 {
 6599:     my ($symb,$courseid,$domain,$username)=@_;
 6600:     {
 6601: 	use integer;
 6602: 	# strings need to be an even # of cahracters long, it it is odd the
 6603:         # last characters gets thrown away
 6604: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6605: 	my $symbseed=numval($symb) << 10;
 6606: 	my $namechck=unpack("%32S*",$username.' ');
 6607: 	
 6608: 	my $nameseed=numval($username) << 21;
 6609: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6610: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6611: 	
 6612: 	my $num1=$symbchck+$symbseed+$namechck;
 6613: 	my $num2=$nameseed+$domainseed+$courseseed;
 6614: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6615: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6616: 	return "$num1,$num2";
 6617:     }
 6618: }
 6619: 
 6620: sub rndseed_64bit3 {
 6621:     my ($symb,$courseid,$domain,$username)=@_;
 6622:     {
 6623: 	use integer;
 6624: 	# strings need to be an even # of cahracters long, it it is odd the
 6625:         # last characters gets thrown away
 6626: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6627: 	my $symbseed=numval2($symb) << 10;
 6628: 	my $namechck=unpack("%32S*",$username.' ');
 6629: 	
 6630: 	my $nameseed=numval2($username) << 21;
 6631: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6632: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6633: 	
 6634: 	my $num1=$symbchck+$symbseed+$namechck;
 6635: 	my $num2=$nameseed+$domainseed+$courseseed;
 6636: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6637: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6638: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6639: 	
 6640: 	return "$num1:$num2";
 6641:     }
 6642: }
 6643: 
 6644: sub rndseed_64bit4 {
 6645:     my ($symb,$courseid,$domain,$username)=@_;
 6646:     {
 6647: 	use integer;
 6648: 	# strings need to be an even # of cahracters long, it it is odd the
 6649:         # last characters gets thrown away
 6650: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6651: 	my $symbseed=numval3($symb) << 10;
 6652: 	my $namechck=unpack("%32S*",$username.' ');
 6653: 	
 6654: 	my $nameseed=numval3($username) << 21;
 6655: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6656: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6657: 	
 6658: 	my $num1=$symbchck+$symbseed+$namechck;
 6659: 	my $num2=$nameseed+$domainseed+$courseseed;
 6660: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6661: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6662: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6663: 	
 6664: 	return "$num1:$num2";
 6665:     }
 6666: }
 6667: 
 6668: sub rndseed_64bit5 {
 6669:     my ($symb,$courseid,$domain,$username)=@_;
 6670:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6671:     return "$num1:$num2";
 6672: }
 6673: 
 6674: sub rndseed_CODE_64bit {
 6675:     my ($symb,$courseid,$domain,$username)=@_;
 6676:     {
 6677: 	use integer;
 6678: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6679: 	my $symbseed=numval2($symb);
 6680: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6681: 	my $CODEseed=numval(&getCODE());
 6682: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6683: 	my $num1=$symbseed+$CODEchck;
 6684: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6685: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6686: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6687: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6688: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6689: 	return "$num1:$num2";
 6690:     }
 6691: }
 6692: 
 6693: sub rndseed_CODE_64bit4 {
 6694:     my ($symb,$courseid,$domain,$username)=@_;
 6695:     {
 6696: 	use integer;
 6697: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6698: 	my $symbseed=numval3($symb);
 6699: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6700: 	my $CODEseed=numval3(&getCODE());
 6701: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6702: 	my $num1=$symbseed+$CODEchck;
 6703: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6704: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6705: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6706: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6707: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6708: 	return "$num1:$num2";
 6709:     }
 6710: }
 6711: 
 6712: sub rndseed_CODE_64bit5 {
 6713:     my ($symb,$courseid,$domain,$username)=@_;
 6714:     my $code = &getCODE();
 6715:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6716:     return "$num1:$num2";
 6717: }
 6718: 
 6719: sub setup_random_from_rndseed {
 6720:     my ($rndseed)=@_;
 6721:     if ($rndseed =~/([,:])/) {
 6722: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6723: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6724:     } else {
 6725: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6726:     }
 6727: }
 6728: 
 6729: sub latest_receipt_algorithm_id {
 6730:     return 'receipt2';
 6731: }
 6732: 
 6733: sub recunique {
 6734:     my $fucourseid=shift;
 6735:     my $unique;
 6736:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6737: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6738:     } else {
 6739: 	$unique=$perlvar{'lonReceipt'};
 6740:     }
 6741:     return unpack("%32C*",$unique);
 6742: }
 6743: 
 6744: sub recprefix {
 6745:     my $fucourseid=shift;
 6746:     my $prefix;
 6747:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6748: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6749:     } else {
 6750: 	$prefix=$perlvar{'lonHostID'};
 6751:     }
 6752:     return unpack("%32C*",$prefix);
 6753: }
 6754: 
 6755: sub ireceipt {
 6756:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6757:     my $cuname=unpack("%32C*",$funame);
 6758:     my $cudom=unpack("%32C*",$fudom);
 6759:     my $cucourseid=unpack("%32C*",$fucourseid);
 6760:     my $cusymb=unpack("%32C*",$fusymb);
 6761:     my $cunique=&recunique($fucourseid);
 6762:     my $cpart=unpack("%32S*",$part);
 6763:     my $return =&recprefix($fucourseid).'-';
 6764:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6765: 	$env{'request.state'} eq 'construct') {
 6766: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6767: 			       " and ".($cpart%$cudom));
 6768: 			       
 6769: 	$return.= ($cunique%$cuname+
 6770: 		   $cunique%$cudom+
 6771: 		   $cusymb%$cuname+
 6772: 		   $cusymb%$cudom+
 6773: 		   $cucourseid%$cuname+
 6774: 		   $cucourseid%$cudom+
 6775: 		   $cpart%$cuname+
 6776: 		   $cpart%$cudom);
 6777:     } else {
 6778: 	$return.= ($cunique%$cuname+
 6779: 		   $cunique%$cudom+
 6780: 		   $cusymb%$cuname+
 6781: 		   $cusymb%$cudom+
 6782: 		   $cucourseid%$cuname+
 6783: 		   $cucourseid%$cudom);
 6784:     }
 6785:     return $return;
 6786: }
 6787: 
 6788: sub receipt {
 6789:     my ($part)=@_;
 6790:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6791:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6792: }
 6793: 
 6794: # ------------------------------------------------------------ Serves up a file
 6795: # returns either the contents of the file or 
 6796: # -1 if the file doesn't exist
 6797: #
 6798: # if the target is a file that was uploaded via DOCS, 
 6799: # a check will be made to see if a current copy exists on the local server,
 6800: # if it does this will be served, otherwise a copy will be retrieved from
 6801: # the home server for the course and stored in /home/httpd/html/userfiles on
 6802: # the local server.   
 6803: 
 6804: sub getfile {
 6805:     my ($file) = @_;
 6806:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6807:     &repcopy($file);
 6808:     return &readfile($file);
 6809: }
 6810: 
 6811: sub repcopy_userfile {
 6812:     my ($file)=@_;
 6813:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6814:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6815:     my ($cdom,$cnum,$filename) = 
 6816: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6817:     my ($info,$rtncode);
 6818:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6819:     if (-e "$file") {
 6820: 	my @fileinfo = stat($file);
 6821: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6822: 	if ($lwpresp ne 'ok') {
 6823: 	    if ($rtncode eq '404') {
 6824: 		unlink($file);
 6825: 	    }
 6826: 	    #my $ua=new LWP::UserAgent;
 6827: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6828: 	    #my $response=$ua->request($request);
 6829: 	    #if ($response->is_success()) {
 6830: 	#	return $response->content;
 6831: 	#    } else {
 6832: 	#	return -1;
 6833: 	#    }
 6834: 	    return -1;
 6835: 	}
 6836: 	if ($info < $fileinfo[9]) {
 6837: 	    return 'ok';
 6838: 	}
 6839: 	$info = '';
 6840: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6841: 	if ($lwpresp ne 'ok') {
 6842: 	    return -1;
 6843: 	}
 6844:     } else {
 6845: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6846: 	if ($lwpresp ne 'ok') {
 6847: 	    my $ua=new LWP::UserAgent;
 6848: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6849: 	    my $response=$ua->request($request);
 6850: 	    if ($response->is_success()) {
 6851: 		$info=$response->content;
 6852: 	    } else {
 6853: 		return -1;
 6854: 	    }
 6855: 	}
 6856: 	my @parts = ($cdom,$cnum); 
 6857: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6858: 	    push @parts, split(/\//,$1);
 6859: 	}
 6860: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6861: 	foreach my $part (@parts) {
 6862: 	    $path .= '/'.$part;
 6863: 	    if (!-e $path) {
 6864: 		mkdir($path,0770);
 6865: 	    }
 6866: 	}
 6867:     }
 6868:     open(FILE,">$file");
 6869:     print FILE $info;
 6870:     close(FILE);
 6871:     return 'ok';
 6872: }
 6873: 
 6874: sub tokenwrapper {
 6875:     my $uri=shift;
 6876:     $uri=~s|^http\://([^/]+)||;
 6877:     $uri=~s|^/||;
 6878:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6879:     my $token=$1;
 6880:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6881:     if ($udom && $uname && $file) {
 6882: 	$file=~s|(\?\.*)*$||;
 6883:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6884:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6885:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6886:                                '&tokenissued='.$perlvar{'lonHostID'};
 6887:     } else {
 6888:         return '/adm/notfound.html';
 6889:     }
 6890: }
 6891: 
 6892: sub getuploaded {
 6893:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6894:     $uri=~s/^\///;
 6895:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6896:     my $ua=new LWP::UserAgent;
 6897:     my $request=new HTTP::Request($reqtype,$uri);
 6898:     my $response=$ua->request($request);
 6899:     $$rtncode = $response->code;
 6900:     if (! $response->is_success()) {
 6901: 	return 'failed';
 6902:     }      
 6903:     if ($reqtype eq 'HEAD') {
 6904: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6905:     } elsif ($reqtype eq 'GET') {
 6906: 	$$info = $response->content;
 6907:     }
 6908:     return 'ok';
 6909: }
 6910: 
 6911: sub readfile {
 6912:     my $file = shift;
 6913:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6914:     my $fh;
 6915:     open($fh,"<$file");
 6916:     my $a='';
 6917:     while (<$fh>) { $a .=$_; }
 6918:     return $a;
 6919: }
 6920: 
 6921: sub filelocation {
 6922:     my ($dir,$file) = @_;
 6923:     my $location;
 6924:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6925: 
 6926:     if ($file =~ m-^/adm/-) {
 6927: 	$file=~s-^/adm/wrapper/-/-;
 6928: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6929:     }
 6930:     if ($file=~m:^/~:) { # is a contruction space reference
 6931:         $location = $file;
 6932:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6933:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6934: 	# is a correct contruction space reference
 6935:         $location = $file;
 6936:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6937:         my ($udom,$uname,$filename)=
 6938:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6939:         my $home=&homeserver($uname,$udom);
 6940:         my $is_me=0;
 6941:         my @ids=&current_machine_ids();
 6942:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6943:         if ($is_me) {
 6944:   	    $location=&propath($udom,$uname).
 6945:   	      '/userfiles/'.$filename;
 6946:         } else {
 6947:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6948:   	      $udom.'/'.$uname.'/'.$filename;
 6949:         }
 6950:     } else {
 6951:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6952:         $file=~s:^/res/:/:;
 6953:         if ( !( $file =~ m:^/:) ) {
 6954:             $location = $dir. '/'.$file;
 6955:         } else {
 6956:             $location = '/home/httpd/html/res'.$file;
 6957:         }
 6958:     }
 6959:     $location=~s://+:/:g; # remove duplicate /
 6960:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6961:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6962:     return $location;
 6963: }
 6964: 
 6965: sub hreflocation {
 6966:     my ($dir,$file)=@_;
 6967:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6968: 	$file=filelocation($dir,$file);
 6969:     } elsif ($file=~m-^/adm/-) {
 6970: 	$file=~s-^/adm/wrapper/-/-;
 6971: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6972:     }
 6973:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6974: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6975:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6976: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6977:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6978: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6979: 	    -/uploaded/$1/$2/-x;
 6980:     }
 6981:     return $file;
 6982: }
 6983: 
 6984: sub current_machine_domains {
 6985:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6986:     my @domains;
 6987:     while( my($id, $name) = each(%hostname)) {
 6988: #	&logthis("-$id-$name-$hostname-");
 6989: 	if ($hostname eq $name) {
 6990: 	    push(@domains,$hostdom{$id});
 6991: 	}
 6992:     }
 6993:     return @domains;
 6994: }
 6995: 
 6996: sub current_machine_ids {
 6997:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6998:     my @ids;
 6999:     while( my($id, $name) = each(%hostname)) {
 7000: #	&logthis("-$id-$name-$hostname-");
 7001: 	if ($hostname eq $name) {
 7002: 	    push(@ids,$id);
 7003: 	}
 7004:     }
 7005:     return @ids;
 7006: }
 7007: 
 7008: # ------------------------------------------------------------- Declutters URLs
 7009: 
 7010: sub declutter {
 7011:     my $thisfn=shift;
 7012:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7013:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7014:     $thisfn=~s/^\///;
 7015:     $thisfn=~s|^adm/wrapper/||;
 7016:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7017:     $thisfn=~s/^res\///;
 7018:     $thisfn=~s/\?.+$//;
 7019:     return $thisfn;
 7020: }
 7021: 
 7022: # ------------------------------------------------------------- Clutter up URLs
 7023: 
 7024: sub clutter {
 7025:     my $thisfn='/'.&declutter(shift);
 7026:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7027:        $thisfn='/res'.$thisfn; 
 7028:     }
 7029:     if ($thisfn !~m|/adm|) {
 7030: 	if ($thisfn =~ m|/ext/|) {
 7031: 	    $thisfn='/adm/wrapper'.$thisfn;
 7032: 	} else {
 7033: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7034: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7035: 	    if ($embstyle eq 'ssi'
 7036: 		|| ($embstyle eq 'hdn')
 7037: 		|| ($embstyle eq 'rat')
 7038: 		|| ($embstyle eq 'prv')
 7039: 		|| ($embstyle eq 'ign')) {
 7040: 		#do nothing with these
 7041: 	    } elsif (($embstyle eq 'img') 
 7042: 		|| ($embstyle eq 'emb')
 7043: 		|| ($embstyle eq 'wrp')) {
 7044: 		$thisfn='/adm/wrapper'.$thisfn;
 7045: 	    } elsif ($embstyle eq 'unk'
 7046: 		     && $thisfn!~/\.(sequence|page)$/) {
 7047: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7048: 	    } else {
 7049: #		&logthis("Got a blank emb style");
 7050: 	    }
 7051: 	}
 7052:     }
 7053:     return $thisfn;
 7054: }
 7055: 
 7056: sub freeze_escape {
 7057:     my ($value)=@_;
 7058:     if (ref($value)) {
 7059: 	$value=&nfreeze($value);
 7060: 	return '__FROZEN__'.&escape($value);
 7061:     }
 7062:     return &escape($value);
 7063: }
 7064: 
 7065: 
 7066: sub thaw_unescape {
 7067:     my ($value)=@_;
 7068:     if ($value =~ /^__FROZEN__/) {
 7069: 	substr($value,0,10,undef);
 7070: 	$value=&unescape($value);
 7071: 	return &thaw($value);
 7072:     }
 7073:     return &unescape($value);
 7074: }
 7075: 
 7076: sub correct_line_ends {
 7077:     my ($result)=@_;
 7078:     $$result =~s/\r\n/\n/mg;
 7079:     $$result =~s/\r/\n/mg;
 7080: }
 7081: # ================================================================ Main Program
 7082: 
 7083: sub goodbye {
 7084:    &logthis("Starting Shut down");
 7085: #not converted to using infrastruture and probably shouldn't be
 7086:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7087: #converted
 7088: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7089:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7090: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7091: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7092: #1.1 only
 7093: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7094: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7095: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7096: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7097:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7098:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7099:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7100:    &flushcourselogs();
 7101:    &logthis("Shutting down");
 7102: }
 7103: 
 7104: BEGIN {
 7105: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7106:     unless ($readit) {
 7107: {
 7108:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7109:     %perlvar = (%perlvar,%{$configvars});
 7110: }
 7111: 
 7112: # ------------------------------------------------------------ Read domain file
 7113: {
 7114:     %domaindescription = ();
 7115:     %domain_auth_def = ();
 7116:     %domain_auth_arg_def = ();
 7117:     my $fh;
 7118:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7119:        while (<$fh>) {
 7120:            next if (/^(\#|\s*$)/);
 7121: #           next if /^\#/;
 7122:            chomp;
 7123:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7124: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 7125: 	   $domain_auth_def{$domain}=$def_auth;
 7126:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7127: 	   $domaindescription{$domain}=$domain_description;
 7128: 	   $domain_lang_def{$domain}=$def_lang;
 7129: 	   $domain_city{$domain}=$city;
 7130: 	   $domain_longi{$domain}=$longi;
 7131: 	   $domain_lati{$domain}=$lati;
 7132:            $domain_primary{$domain}=$primary;
 7133: 
 7134:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7135: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7136: 	}
 7137:     }
 7138:     close ($fh);
 7139: }
 7140: 
 7141: 
 7142: # ------------------------------------------------------------- Read hosts file
 7143: {
 7144:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7145: 
 7146:     while (my $configline=<$config>) {
 7147:        next if ($configline =~ /^(\#|\s*$)/);
 7148:        chomp($configline);
 7149:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7150:        $name=~s/\s//g;
 7151:        if ($id && $domain && $role && $name) {
 7152: 	 $hostname{$id}=$name;
 7153: 	 $hostdom{$id}=$domain;
 7154: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7155:        }
 7156:     }
 7157:     close($config);
 7158:     # FIXME: dev server don't want this, production servers _do_ want this
 7159:     #&get_iphost();
 7160: }
 7161: 
 7162: sub get_iphost {
 7163:     if (%iphost) { return %iphost; }
 7164:     my %name_to_ip;
 7165:     foreach my $id (keys(%hostname)) {
 7166: 	my $name=$hostname{$id};
 7167: 	my $ip;
 7168: 	if (!exists($name_to_ip{$name})) {
 7169: 	    $ip = gethostbyname($name);
 7170: 	    if (!$ip || length($ip) ne 4) {
 7171: 		&logthis("Skipping host $id name $name no IP found\n");
 7172: 		next;
 7173: 	    }
 7174: 	    $ip=inet_ntoa($ip);
 7175: 	    $name_to_ip{$name} = $ip;
 7176: 	} else {
 7177: 	    $ip = $name_to_ip{$name};
 7178: 	}
 7179: 	push(@{$iphost{$ip}},$id);
 7180:     }
 7181:     return %iphost;
 7182: }
 7183: 
 7184: # ------------------------------------------------------ Read spare server file
 7185: {
 7186:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7187: 
 7188:     while (my $configline=<$config>) {
 7189:        chomp($configline);
 7190:        if ($configline) {
 7191: 	   my ($host,$type) = split(':',$configline,2);
 7192: 	   if ($type eq '') { $type = 'default' };
 7193: 	   push(@{ $spareid{$type} }, $host);
 7194:        }
 7195:     }
 7196:     close($config);
 7197: }
 7198: # ------------------------------------------------------------ Read permissions
 7199: {
 7200:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7201: 
 7202:     while (my $configline=<$config>) {
 7203: 	chomp($configline);
 7204: 	if ($configline) {
 7205: 	    my ($role,$perm)=split(/ /,$configline);
 7206: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7207: 	}
 7208:     }
 7209:     close($config);
 7210: }
 7211: 
 7212: # -------------------------------------------- Read plain texts for permissions
 7213: {
 7214:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7215: 
 7216:     while (my $configline=<$config>) {
 7217: 	chomp($configline);
 7218: 	if ($configline) {
 7219: 	    my ($short,@plain)=split(/:/,$configline);
 7220:             %{$prp{$short}} = ();
 7221: 	    if (@plain > 0) {
 7222:                 $prp{$short}{'std'} = $plain[0];
 7223:                 for (my $i=1; $i<@plain; $i++) {
 7224:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7225:                 }
 7226:             }
 7227: 	}
 7228:     }
 7229:     close($config);
 7230: }
 7231: 
 7232: # ---------------------------------------------------------- Read package table
 7233: {
 7234:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7235: 
 7236:     while (my $configline=<$config>) {
 7237: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7238: 	chomp($configline);
 7239: 	my ($short,$plain)=split(/:/,$configline);
 7240: 	my ($pack,$name)=split(/\&/,$short);
 7241: 	if ($plain ne '') {
 7242: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7243: 	    $packagetab{$short}=$plain; 
 7244: 	}
 7245:     }
 7246:     close($config);
 7247: }
 7248: 
 7249: # ------------- set up temporary directory
 7250: {
 7251:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7252: 
 7253: }
 7254: 
 7255: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 7256: 
 7257: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7258: $dumpcount=0;
 7259: 
 7260: &logtouch();
 7261: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7262: $readit=1;
 7263:     {
 7264: 	use integer;
 7265: 	my $test=(2**32)+1;
 7266: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7267: 	&logthis(" Detected 64bit platform ($_64bit)");
 7268:     }
 7269: }
 7270: }
 7271: 
 7272: 1;
 7273: __END__
 7274: 
 7275: =pod
 7276: 
 7277: =head1 NAME
 7278: 
 7279: Apache::lonnet - Subroutines to ask questions about things in the network.
 7280: 
 7281: =head1 SYNOPSIS
 7282: 
 7283: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7284: 
 7285:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7286: 
 7287: Common parameters:
 7288: 
 7289: =over 4
 7290: 
 7291: =item *
 7292: 
 7293: $uname : an internal username (if $cname expecting a course Id specifically)
 7294: 
 7295: =item *
 7296: 
 7297: $udom : a domain (if $cdom expecting a course's domain specifically)
 7298: 
 7299: =item *
 7300: 
 7301: $symb : a resource instance identifier
 7302: 
 7303: =item *
 7304: 
 7305: $namespace : the name of a .db file that contains the data needed or
 7306: being set.
 7307: 
 7308: =back
 7309: 
 7310: =head1 OVERVIEW
 7311: 
 7312: lonnet provides subroutines which interact with the
 7313: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7314: about classes, users, and resources.
 7315: 
 7316: For many of these objects you can also use this to store data about
 7317: them or modify them in various ways.
 7318: 
 7319: =head2 Symbs
 7320: 
 7321: To identify a specific instance of a resource, LON-CAPA uses symbols
 7322: or "symbs"X<symb>. These identifiers are built from the URL of the
 7323: map, the resource number of the resource in the map, and the URL of
 7324: the resource itself. The latter is somewhat redundant, but might help
 7325: if maps change.
 7326: 
 7327: An example is
 7328: 
 7329:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7330: 
 7331: The respective map entry is
 7332: 
 7333:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7334:   title="Problem 2">
 7335:  </resource>
 7336: 
 7337: Symbs are used by the random number generator, as well as to store and
 7338: restore data specific to a certain instance of for example a problem.
 7339: 
 7340: =head2 Storing And Retrieving Data
 7341: 
 7342: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7343: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7344: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7345: is is the non-critical message twin of cstore. These functions are for
 7346: handlers to store a perl hash to a user's permanent data space in an
 7347: easy manner, and to retrieve it again on another call. It is expected
 7348: that a handler would use this once at the beginning to retrieve data,
 7349: and then again once at the end to send only the new data back.
 7350: 
 7351: The data is stored in the user's data directory on the user's
 7352: homeserver under the ID of the course.
 7353: 
 7354: The hash that is returned by restore will have all of the previous
 7355: value for all of the elements of the hash.
 7356: 
 7357: Example:
 7358: 
 7359:  #creating a hash
 7360:  my %hash;
 7361:  $hash{'foo'}='bar';
 7362: 
 7363:  #storing it
 7364:  &Apache::lonnet::cstore(\%hash);
 7365: 
 7366:  #changing a value
 7367:  $hash{'foo'}='notbar';
 7368: 
 7369:  #adding a new value
 7370:  $hash{'bar'}='foo';
 7371:  &Apache::lonnet::cstore(\%hash);
 7372: 
 7373:  #retrieving the hash
 7374:  my %history=&Apache::lonnet::restore();
 7375: 
 7376:  #print the hash
 7377:  foreach my $key (sort(keys(%history))) {
 7378:    print("\%history{$key} = $history{$key}");
 7379:  }
 7380: 
 7381: Will print out:
 7382: 
 7383:  %history{1:foo} = bar
 7384:  %history{1:keys} = foo:timestamp
 7385:  %history{1:timestamp} = 990455579
 7386:  %history{2:bar} = foo
 7387:  %history{2:foo} = notbar
 7388:  %history{2:keys} = foo:bar:timestamp
 7389:  %history{2:timestamp} = 990455580
 7390:  %history{bar} = foo
 7391:  %history{foo} = notbar
 7392:  %history{timestamp} = 990455580
 7393:  %history{version} = 2
 7394: 
 7395: Note that the special hash entries C<keys>, C<version> and
 7396: C<timestamp> were added to the hash. C<version> will be equal to the
 7397: total number of versions of the data that have been stored. The
 7398: C<timestamp> attribute will be the UNIX time the hash was
 7399: stored. C<keys> is available in every historical section to list which
 7400: keys were added or changed at a specific historical revision of a
 7401: hash.
 7402: 
 7403: B<Warning>: do not store the hash that restore returns directly. This
 7404: will cause a mess since it will restore the historical keys as if the
 7405: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7406: 
 7407: Calling convention:
 7408: 
 7409:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7410:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7411: 
 7412: For more detailed information, see lonnet specific documentation.
 7413: 
 7414: =head1 RETURN MESSAGES
 7415: 
 7416: =over 4
 7417: 
 7418: =item * B<con_lost>: unable to contact remote host
 7419: 
 7420: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7421: when the connection is brought back up
 7422: 
 7423: =item * B<con_failed>: unable to contact remote host and unable to save message
 7424: for later delivery
 7425: 
 7426: =item * B<error:>: an error a occured, a description of the error follows the :
 7427: 
 7428: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7429: that was requested
 7430: 
 7431: =back
 7432: 
 7433: =head1 PUBLIC SUBROUTINES
 7434: 
 7435: =head2 Session Environment Functions
 7436: 
 7437: =over 4
 7438: 
 7439: =item * 
 7440: X<appenv()>
 7441: B<appenv(%hash)>: the value of %hash is written to
 7442: the user envirnoment file, and will be restored for each access this
 7443: user makes during this session, also modifies the %env for the current
 7444: process
 7445: 
 7446: =item *
 7447: X<delenv()>
 7448: B<delenv($regexp)>: removes all items from the session
 7449: environment file that matches the regular expression in $regexp. The
 7450: values are also delted from the current processes %env.
 7451: 
 7452: =back
 7453: 
 7454: =head2 User Information
 7455: 
 7456: =over 4
 7457: 
 7458: =item *
 7459: X<queryauthenticate()>
 7460: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7461: authentication scheme
 7462: 
 7463: =item *
 7464: X<authenticate()>
 7465: B<authenticate($uname,$upass,$udom)>: try to
 7466: authenticate user from domain's lib servers (first use the current
 7467: one). C<$upass> should be the users password.
 7468: 
 7469: =item *
 7470: X<homeserver()>
 7471: B<homeserver($uname,$udom)>: find the server which has
 7472: the user's directory and files (there must be only one), this caches
 7473: the answer, and also caches if there is a borken connection.
 7474: 
 7475: =item *
 7476: X<idget()>
 7477: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7478: (IDs are a unique resource in a domain, there must be only 1 ID per
 7479: username, and only 1 username per ID in a specific domain) (returns
 7480: hash: id=>name,id=>name)
 7481: 
 7482: =item *
 7483: X<idrget()>
 7484: B<idrget($udom,@unames)>: find the IDs behind a list of
 7485: usernames (returns hash: name=>id,name=>id)
 7486: 
 7487: =item *
 7488: X<idput()>
 7489: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7490: 
 7491: =item *
 7492: X<rolesinit()>
 7493: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7494: 
 7495: =item *
 7496: X<getsection()>
 7497: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7498: course $cname, return section name/number or '' for "not in course"
 7499: and '-1' for "no section"
 7500: 
 7501: =item *
 7502: X<userenvironment()>
 7503: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7504: passed in @what from the requested user's environment, returns a hash
 7505: 
 7506: =back
 7507: 
 7508: =head2 User Roles
 7509: 
 7510: =over 4
 7511: 
 7512: =item *
 7513: 
 7514: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7515: actions
 7516:  F: full access
 7517:  U,I,K: authentication modes (cxx only)
 7518:  '': forbidden
 7519:  1: user needs to choose course
 7520:  2: browse allowed
 7521:  A: passphrase authentication needed
 7522: 
 7523: =item *
 7524: 
 7525: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7526: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7527: and course level
 7528: 
 7529: =item *
 7530: 
 7531: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7532: explanation of a user role term
 7533: 
 7534: =back
 7535: 
 7536: =head2 User Modification
 7537: 
 7538: =over 4
 7539: 
 7540: =item *
 7541: 
 7542: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7543: user for the level given by URL.  Optional start and end dates (leave empty
 7544: string or zero for "no date")
 7545: 
 7546: =item *
 7547: 
 7548: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7549: change a users, password, possible return values are: ok,
 7550: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7551: refused
 7552: 
 7553: =item *
 7554: 
 7555: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7556: 
 7557: =item *
 7558: 
 7559: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7560: modify user
 7561: 
 7562: =item *
 7563: 
 7564: modifystudent
 7565: 
 7566: modify a students enrollment and identification information.
 7567: The course id is resolved based on the current users environment.  
 7568: This means the envoking user must be a course coordinator or otherwise
 7569: associated with a course.
 7570: 
 7571: This call is essentially a wrapper for lonnet::modifyuser and
 7572: lonnet::modify_student_enrollment
 7573: 
 7574: Inputs: 
 7575: 
 7576: =over 4
 7577: 
 7578: =item B<$udom> Students loncapa domain
 7579: 
 7580: =item B<$uname> Students loncapa login name
 7581: 
 7582: =item B<$uid> Students id/student number
 7583: 
 7584: =item B<$umode> Students authentication mode
 7585: 
 7586: =item B<$upass> Students password
 7587: 
 7588: =item B<$first> Students first name
 7589: 
 7590: =item B<$middle> Students middle name
 7591: 
 7592: =item B<$last> Students last name
 7593: 
 7594: =item B<$gene> Students generation
 7595: 
 7596: =item B<$usec> Students section in course
 7597: 
 7598: =item B<$end> Unix time of the roles expiration
 7599: 
 7600: =item B<$start> Unix time of the roles start date
 7601: 
 7602: =item B<$forceid> If defined, allow $uid to be changed
 7603: 
 7604: =item B<$desiredhome> server to use as home server for student
 7605: 
 7606: =back
 7607: 
 7608: =item *
 7609: 
 7610: modify_student_enrollment
 7611: 
 7612: Change a students enrollment status in a class.  The environment variable
 7613: 'role.request.course' must be defined for this function to proceed.
 7614: 
 7615: Inputs:
 7616: 
 7617: =over 4
 7618: 
 7619: =item $udom, students domain
 7620: 
 7621: =item $uname, students name
 7622: 
 7623: =item $uid, students user id
 7624: 
 7625: =item $first, students first name
 7626: 
 7627: =item $middle
 7628: 
 7629: =item $last
 7630: 
 7631: =item $gene
 7632: 
 7633: =item $usec
 7634: 
 7635: =item $end
 7636: 
 7637: =item $start
 7638: 
 7639: =back
 7640: 
 7641: 
 7642: =item *
 7643: 
 7644: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7645: custom role; give a custom role to a user for the level given by URL.  Specify
 7646: name and domain of role author, and role name
 7647: 
 7648: =item *
 7649: 
 7650: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7651: 
 7652: =item *
 7653: 
 7654: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7655: 
 7656: =back
 7657: 
 7658: =head2 Course Infomation
 7659: 
 7660: =over 4
 7661: 
 7662: =item *
 7663: 
 7664: coursedescription($courseid) : returns a hash of information about the
 7665: specified course id, including all environment settings for the
 7666: course, the description of the course will be in the hash under the
 7667: key 'description'
 7668: 
 7669: =item *
 7670: 
 7671: resdata($name,$domain,$type,@which) : request for current parameter
 7672: setting for a specific $type, where $type is either 'course' or 'user',
 7673: @what should be a list of parameters to ask about. This routine caches
 7674: answers for 5 minutes.
 7675: 
 7676: =back
 7677: 
 7678: =head2 Course Modification
 7679: 
 7680: =over 4
 7681: 
 7682: =item *
 7683: 
 7684: writecoursepref($courseid,%prefs) : write preferences (environment
 7685: database) for a course
 7686: 
 7687: =item *
 7688: 
 7689: createcourse($udom,$description,$url) : make/modify course
 7690: 
 7691: =back
 7692: 
 7693: =head2 Resource Subroutines
 7694: 
 7695: =over 4
 7696: 
 7697: =item *
 7698: 
 7699: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7700: 
 7701: =item *
 7702: 
 7703: repcopy($filename) : subscribes to the requested file, and attempts to
 7704: replicate from the owning library server, Might return
 7705: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7706: 'bad_request', also attempts to grab the metadata for the
 7707: resource. Expects the local filesystem pathname
 7708: (/home/httpd/html/res/....)
 7709: 
 7710: =back
 7711: 
 7712: =head2 Resource Information
 7713: 
 7714: =over 4
 7715: 
 7716: =item *
 7717: 
 7718: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7719: a vairety of different possible values, $varname should be a request
 7720: string, and the other parameters can be used to specify who and what
 7721: one is asking about.
 7722: 
 7723: Possible values for $varname are environment.lastname (or other item
 7724: from the envirnment hash), user.name (or someother aspect about the
 7725: user), resource.0.maxtries (or some other part and parameter of a
 7726: resource)
 7727: 
 7728: =item *
 7729: 
 7730: directcondval($number) : get current value of a condition; reads from a state
 7731: string
 7732: 
 7733: =item *
 7734: 
 7735: condval($condidx) : value of condition index based on state
 7736: 
 7737: =item *
 7738: 
 7739: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7740: resource's metadata, $what should be either a specific key, or either
 7741: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7742: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7743: 
 7744: this function automatically caches all requests
 7745: 
 7746: =item *
 7747: 
 7748: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7749: network of library servers; returns file handle of where SQL and regex results
 7750: will be stored for query
 7751: 
 7752: =item *
 7753: 
 7754: symbread($filename) : return symbolic list entry (filename argument optional);
 7755: returns the data handle
 7756: 
 7757: =item *
 7758: 
 7759: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7760: a possible symb for the URL in $thisfn, and if is an encryypted
 7761: resource that the user accessed using /enc/ returns a 1 on success, 0
 7762: on failure, user must be in a course, as it assumes the existance of
 7763: the course initial hash, and uses $env('request.course.id'}
 7764: 
 7765: 
 7766: =item *
 7767: 
 7768: symbclean($symb) : removes versions numbers from a symb, returns the
 7769: cleaned symb
 7770: 
 7771: =item *
 7772: 
 7773: is_on_map($uri) : checks if the $uri is somewhere on the current
 7774: course map, user must be in a course for it to work.
 7775: 
 7776: =item *
 7777: 
 7778: numval($salt) : return random seed value (addend for rndseed)
 7779: 
 7780: =item *
 7781: 
 7782: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7783: a random seed, all arguments are optional, if they aren't sent it uses the
 7784: environment to derive them. Note: if symb isn't sent and it can't get one
 7785: from &symbread it will use the current time as its return value
 7786: 
 7787: =item *
 7788: 
 7789: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7790: unfakeable, receipt
 7791: 
 7792: =item *
 7793: 
 7794: receipt() : API to ireceipt working off of env values; given out to users
 7795: 
 7796: =item *
 7797: 
 7798: countacc($url) : count the number of accesses to a given URL
 7799: 
 7800: =item *
 7801: 
 7802: 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
 7803: 
 7804: =item *
 7805: 
 7806: 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)
 7807: 
 7808: =item *
 7809: 
 7810: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7811: 
 7812: =item *
 7813: 
 7814: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7815: forcing spreadsheet to reevaluate the resource scores next time.
 7816: 
 7817: =back
 7818: 
 7819: =head2 Storing/Retreiving Data
 7820: 
 7821: =over 4
 7822: 
 7823: =item *
 7824: 
 7825: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7826: for this url; hashref needs to be given and should be a \%hashname; the
 7827: remaining args aren't required and if they aren't passed or are '' they will
 7828: be derived from the env
 7829: 
 7830: =item *
 7831: 
 7832: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7833: uses critical subroutine
 7834: 
 7835: =item *
 7836: 
 7837: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7838: all args are optional
 7839: 
 7840: =item *
 7841: 
 7842: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7843: dumps the complete (or key matching regexp) namespace into a hash
 7844: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7845: normally &store()ed into
 7846: 
 7847: $range should be either an integer '100' (give me the first 100
 7848:                                            matching records)
 7849:               or be  two integers sperated by a - with no spaces
 7850:                  '30-50' (give me the 30th through the 50th matching
 7851:                           records)
 7852: 
 7853: 
 7854: =item *
 7855: 
 7856: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7857: replaces a &store() version of data with a replacement set of data
 7858: for a particular resource in a namespace passed in the $storehash hash 
 7859: reference
 7860: 
 7861: =item *
 7862: 
 7863: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7864: works very similar to store/cstore, but all data is stored in a
 7865: temporary location and can be reset using tmpreset, $storehash should
 7866: be a hash reference, returns nothing on success
 7867: 
 7868: =item *
 7869: 
 7870: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7871: similar to restore, but all data is stored in a temporary location and
 7872: can be reset using tmpreset. Returns a hash of values on success,
 7873: error string otherwise.
 7874: 
 7875: =item *
 7876: 
 7877: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7878: deltes all keys for $symb form the temporary storage hash.
 7879: 
 7880: =item *
 7881: 
 7882: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7883: reference filled in from namesp ($udom and $uname are optional)
 7884: 
 7885: =item *
 7886: 
 7887: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7888: namesp ($udom and $uname are optional)
 7889: 
 7890: =item *
 7891: 
 7892: dump($namespace,$udom,$uname,$regexp,$range) : 
 7893: dumps the complete (or key matching regexp) namespace into a hash
 7894: ($udom, $uname, $regexp, $range are optional)
 7895: 
 7896: $range should be either an integer '100' (give me the first 100
 7897:                                            matching records)
 7898:               or be  two integers sperated by a - with no spaces
 7899:                  '30-50' (give me the 30th through the 50th matching
 7900:                           records)
 7901: =item *
 7902: 
 7903: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7904: $store can be a scalar, an array reference, or if the amount to be 
 7905: incremented is > 1, a hash reference.
 7906: 
 7907: ($udom and $uname are optional)
 7908: 
 7909: =item *
 7910: 
 7911: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7912: ($udom and $uname are optional)
 7913: 
 7914: =item *
 7915: 
 7916: cput($namespace,$storehash,$udom,$uname) : critical put
 7917: ($udom and $uname are optional)
 7918: 
 7919: =item *
 7920: 
 7921: newput($namespace,$storehash,$udom,$uname) :
 7922: 
 7923: Attempts to store the items in the $storehash, but only if they don't
 7924: currently exist, if this succeeds you can be certain that you have 
 7925: successfully created a new key value pair in the $namespace db.
 7926: 
 7927: 
 7928: Args:
 7929:  $namespace: name of database to store values to
 7930:  $storehash: hashref to store to the db
 7931:  $udom: (optional) domain of user containing the db
 7932:  $uname: (optional) name of user caontaining the db
 7933: 
 7934: Returns:
 7935:  'ok' -> succeeded in storing all keys of $storehash
 7936:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 7937:                         least <key> already existed in the db (other
 7938:                         requested keys may also already exist)
 7939:  'error: <msg>' -> unable to tie the DB or other erorr occured
 7940:  'con_lost' -> unable to contact request server
 7941:  'refused' -> action was not allowed by remote machine
 7942: 
 7943: 
 7944: =item *
 7945: 
 7946: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7947: reference filled in from namesp (encrypts the return communication)
 7948: ($udom and $uname are optional)
 7949: 
 7950: =item *
 7951: 
 7952: log($udom,$name,$home,$message) : write to permanent log for user; use
 7953: critical subroutine
 7954: 
 7955: =back
 7956: 
 7957: =head2 Network Status Functions
 7958: 
 7959: =over 4
 7960: 
 7961: =item *
 7962: 
 7963: dirlist($uri) : return directory list based on URI
 7964: 
 7965: =item *
 7966: 
 7967: spareserver() : find server with least workload from spare.tab
 7968: 
 7969: =back
 7970: 
 7971: =head2 Apache Request
 7972: 
 7973: =over 4
 7974: 
 7975: =item *
 7976: 
 7977: ssi($url,%hash) : server side include, does a complete request cycle on url to
 7978: localhost, posts hash
 7979: 
 7980: =back
 7981: 
 7982: =head2 Data to String to Data
 7983: 
 7984: =over 4
 7985: 
 7986: =item *
 7987: 
 7988: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 7989: and '&' separators, supports elements that are arrayrefs and hashrefs
 7990: 
 7991: =item *
 7992: 
 7993: hashref2str($hashref) : convert a hashref into a string complete with
 7994: escaping and '=' and '&' separators, supports elements that are
 7995: arrayrefs and hashrefs
 7996: 
 7997: =item *
 7998: 
 7999: arrayref2str($arrayref) : convert an arrayref into a string complete
 8000: with escaping and '&' separators, supports elements that are arrayrefs
 8001: and hashrefs
 8002: 
 8003: =item *
 8004: 
 8005: str2hash($string) : convert string to hash using unescaping and
 8006: splitting on '=' and '&', supports elements that are arrayrefs and
 8007: hashrefs
 8008: 
 8009: =item *
 8010: 
 8011: str2array($string) : convert string to hash using unescaping and
 8012: splitting on '&', supports elements that are arrayrefs and hashrefs
 8013: 
 8014: =back
 8015: 
 8016: =head2 Logging Routines
 8017: 
 8018: =over 4
 8019: 
 8020: These routines allow one to make log messages in the lonnet.log and
 8021: lonnet.perm logfiles.
 8022: 
 8023: =item *
 8024: 
 8025: logtouch() : make sure the logfile, lonnet.log, exists
 8026: 
 8027: =item *
 8028: 
 8029: logthis() : append message to the normal lonnet.log file, it gets
 8030: preiodically rolled over and deleted.
 8031: 
 8032: =item *
 8033: 
 8034: logperm() : append a permanent message to lonnet.perm.log, this log
 8035: file never gets deleted by any automated portion of the system, only
 8036: messages of critical importance should go in here.
 8037: 
 8038: =back
 8039: 
 8040: =head2 General File Helper Routines
 8041: 
 8042: =over 4
 8043: 
 8044: =item *
 8045: 
 8046: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8047: (a) files in /uploaded
 8048:   (i) If a local copy of the file exists - 
 8049:       compares modification date of local copy with last-modified date for 
 8050:       definitive version stored on home server for course. If local copy is 
 8051:       stale, requests a new version from the home server and stores it. 
 8052:       If the original has been removed from the home server, then local copy 
 8053:       is unlinked.
 8054:   (ii) If local copy does not exist -
 8055:       requests the file from the home server and stores it. 
 8056:   
 8057:   If $caller is 'uploadrep':  
 8058:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8059:     for request for files originally uploaded via DOCS. 
 8060:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8061:   
 8062:   Otherwise:
 8063:      This indicates a call from the content generation phase of the request.
 8064:      -  returns the entire contents of the file or -1.
 8065:      
 8066: (b) files in /res
 8067:    - returns the entire contents of a file or -1; 
 8068:    it properly subscribes to and replicates the file if neccessary.
 8069: 
 8070: 
 8071: =item *
 8072: 
 8073: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8074:                   reference
 8075: 
 8076: returns either a stat() list of data about the file or an empty list
 8077: if the file doesn't exist or couldn't find out about it (connection
 8078: problems or user unknown)
 8079: 
 8080: =item *
 8081: 
 8082: filelocation($dir,$file) : returns file system location of a file
 8083: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8084: directory that relative $file lookups are to looked in ($dir of /a/dir
 8085: and a file of ../bob will become /a/bob)
 8086: 
 8087: =item *
 8088: 
 8089: hreflocation($dir,$file) : returns file system location or a URL; same as
 8090: filelocation except for hrefs
 8091: 
 8092: =item *
 8093: 
 8094: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8095: 
 8096: =back
 8097: 
 8098: =head2 Usererfile file routines (/uploaded*)
 8099: 
 8100: =over 4
 8101: 
 8102: =item *
 8103: 
 8104: userfileupload(): main rotine for putting a file in a user or course's
 8105:                   filespace, arguments are,
 8106: 
 8107:  formname - required - this is the name of the element in $env where the
 8108:            filename, and the contents of the file to create/modifed exist
 8109:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8110:            contents of the file is located in $env{'form.'.$formname}
 8111:  coursedoc - if true, store the file in the course of the active role
 8112:              of the current user
 8113:  subdir - required - subdirectory to put the file in under ../userfiles/
 8114:          if undefined, it will be placed in "unknown"
 8115: 
 8116:  (This routine calls clean_filename() to remove any dangerous
 8117:  characters from the filename, and then calls finuserfileupload() to
 8118:  complete the transaction)
 8119: 
 8120:  returns either the url of the uploaded file (/uploaded/....) if successful
 8121:  and /adm/notfound.html if unsuccessful
 8122: 
 8123: =item *
 8124: 
 8125: clean_filename(): routine for cleaing a filename up for storage in
 8126:                  userfile space, argument is:
 8127: 
 8128:  filename - proposed filename
 8129: 
 8130: returns: the new clean filename
 8131: 
 8132: =item *
 8133: 
 8134: finishuserfileupload(): routine that creaes and sends the file to
 8135: userspace, probably shouldn't be called directly
 8136: 
 8137:   docuname: username or courseid of destination for the file
 8138:   docudom: domain of user/course of destination for the file
 8139:   formname: same as for userfileupload()
 8140:   fname: filename (inculding subdirectories) for the file
 8141: 
 8142:  returns either the url of the uploaded file (/uploaded/....) if successful
 8143:  and /adm/notfound.html if unsuccessful
 8144: 
 8145: =item *
 8146: 
 8147: renameuserfile(): renames an existing userfile to a new name
 8148: 
 8149:   Args:
 8150:    docuname: username or courseid of destination for the file
 8151:    docudom: domain of user/course of destination for the file
 8152:    old: current file name (including any subdirs under userfiles)
 8153:    new: desired file name (including any subdirs under userfiles)
 8154: 
 8155: =item *
 8156: 
 8157: mkdiruserfile(): creates a directory is a userfiles dir
 8158: 
 8159:   Args:
 8160:    docuname: username or courseid of destination for the file
 8161:    docudom: domain of user/course of destination for the file
 8162:    dir: dir to create (including any subdirs under userfiles)
 8163: 
 8164: =item *
 8165: 
 8166: removeuserfile(): removes a file that exists in userfiles
 8167: 
 8168:   Args:
 8169:    docuname: username or courseid of destination for the file
 8170:    docudom: domain of user/course of destination for the file
 8171:    fname: filname to delete (including any subdirs under userfiles)
 8172: 
 8173: =item *
 8174: 
 8175: removeuploadedurl(): convience function for removeuserfile()
 8176: 
 8177:   Args:
 8178:    url:  a full /uploaded/... url to delete
 8179: 
 8180: =item * 
 8181: 
 8182: get_portfile_permissions():
 8183:   Args:
 8184:     domain: domain of user or course contain the portfolio files
 8185:     user: name of user or num of course contain the portfolio files
 8186:   Returns:
 8187:     hashref of a dump of the proper file_permissions.db
 8188:    
 8189: 
 8190: =item * 
 8191: 
 8192: get_access_controls():
 8193: 
 8194: Args:
 8195:   current_permissions: the hash ref returned from get_portfile_permissions()
 8196:   group: (optional) the group you want the files associated with
 8197:   file: (optional) the file you want access info on
 8198: 
 8199: Returns:
 8200:     a hash (keys are file names) of hashes containing
 8201:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8202:         values are XML containing access control settings (see below) 
 8203: 
 8204: Internal notes:
 8205: 
 8206:  access controls are stored in file_permissions.db as key=value pairs.
 8207:     key -> path to file/file_name\0uniqueID:scope_end_start
 8208:         where scope -> public,guest,course,group,domains or users.
 8209:               end -> UNIX time for end of access (0 -> no end date)
 8210:               start -> UNIX time for start of access
 8211: 
 8212:     value -> XML description of access control
 8213:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8214:             <start></start>
 8215:             <end></end>
 8216: 
 8217:             <password></password>  for scope type = guest
 8218: 
 8219:             <domain></domain>     for scope type = course or group
 8220:             <number></number>
 8221:             <roles id="">
 8222:              <role></role>
 8223:              <access></access>
 8224:              <section></section>
 8225:              <group></group>
 8226:             </roles>
 8227: 
 8228:             <dom></dom>         for scope type = domains
 8229: 
 8230:             <users>             for scope type = users
 8231:              <user>
 8232:               <uname></uname>
 8233:               <udom></udom>
 8234:              </user>
 8235:             </users>
 8236:            </scope> 
 8237:               
 8238:  Access data is also aggregated for each file in an additional key=value pair:
 8239:  key -> path to file/file_name\0accesscontrol 
 8240:  value -> reference to hash
 8241:           hash contains key = value pairs
 8242:           where key = uniqueID:scope_end_start
 8243:                 value = UNIX time record was last updated
 8244: 
 8245:           Used to improve speed of look-ups of access controls for each file.  
 8246:  
 8247:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8248: 
 8249: modify_access_controls():
 8250: 
 8251: Modifies access controls for a portfolio file
 8252: Args
 8253: 1. file name
 8254: 2. reference to hash of required changes,
 8255: 3. domain
 8256: 4. username
 8257:   where domain,username are the domain of the portfolio owner 
 8258:   (either a user or a course) 
 8259: 
 8260: Returns:
 8261: 1. result of additions or updates ('ok' or 'error', with error message). 
 8262: 2. result of deletions ('ok' or 'error', with error message).
 8263: 3. reference to hash of any new or updated access controls.
 8264: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8265:    key = integer (inbound ID)
 8266:    value = uniqueID  
 8267: 
 8268: =back
 8269: 
 8270: =head2 HTTP Helper Routines
 8271: 
 8272: =over 4
 8273: 
 8274: =item *
 8275: 
 8276: escape() : unpack non-word characters into CGI-compatible hex codes
 8277: 
 8278: =item *
 8279: 
 8280: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8281: 
 8282: =back
 8283: 
 8284: =head1 PRIVATE SUBROUTINES
 8285: 
 8286: =head2 Underlying communication routines (Shouldn't call)
 8287: 
 8288: =over 4
 8289: 
 8290: =item *
 8291: 
 8292: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8293: 
 8294: =item *
 8295: 
 8296: reply() : uses subreply to send a message to remote machine, logs all failures
 8297: 
 8298: =item *
 8299: 
 8300: critical() : passes a critical message to another server; if cannot
 8301: get through then place message in connection buffer directory and
 8302: returns con_delayed, if incapable of saving message, returns
 8303: con_failed
 8304: 
 8305: =item *
 8306: 
 8307: reconlonc() : tries to reconnect lonc client processes.
 8308: 
 8309: =back
 8310: 
 8311: =head2 Resource Access Logging
 8312: 
 8313: =over 4
 8314: 
 8315: =item *
 8316: 
 8317: flushcourselogs() : flush (save) buffer logs and access logs
 8318: 
 8319: =item *
 8320: 
 8321: courselog($what) : save message for course in hash
 8322: 
 8323: =item *
 8324: 
 8325: courseacclog($what) : save message for course using &courselog().  Perform
 8326: special processing for specific resource types (problems, exams, quizzes, etc).
 8327: 
 8328: =item *
 8329: 
 8330: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8331: as a PerlChildExitHandler
 8332: 
 8333: =back
 8334: 
 8335: =head2 Other
 8336: 
 8337: =over 4
 8338: 
 8339: =item *
 8340: 
 8341: symblist($mapname,%newhash) : update symbolic storage links
 8342: 
 8343: =back
 8344: 
 8345: =cut

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