File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.640: download - view: text, annotated - select for diffs
Fri Jun 17 16:53:07 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Change to use pull style parser rather than the callback style

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

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