File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.783: download - view: text, annotated - select for diffs
Tue Sep 19 21:36:41 2006 UTC (17 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- change sesion env into a .db file
  (simplifies the appenv/delenv process)

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

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