File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.549: download - view: text, annotated - select for diffs
Tue Oct 5 11:24:34 2004 UTC (19 years, 9 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
If necessary, wait for the unix socket lock file to disappear before
connecting to lonc.  Needed to support process trimming in loncnew and
harmless in pre process trimming implementations of lonc/loncnew since
those implementations won't ever create the lock file in the first place.

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

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