File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.550: download - view: text, annotated - select for diffs
Wed Oct 6 09:48:39 2004 UTC (19 years, 9 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add connection retries to lonc for up to 10 seconds/10 times (1 retry/sec).
This may compensate for short lonc outages, but probably is not strictly needed.
The retry count can be tuned via $max_connection_retries at the top of the file.
I'm not sure this warrants a configuration entry in loncapa's config files,
if so, by all means go for it.

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

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