File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.565: download - view: text, annotated - select for diffs
Mon Nov 8 23:08:46 2004 UTC (19 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- ssi_body works with html comments script blocks  (and non)

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

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