File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.554: download - view: text, annotated - select for diffs
Tue Oct 26 17:20:09 2004 UTC (19 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #3501: actually catch overload errors and tell people to come back
later.

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

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