File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.645: download - view: text, annotated - select for diffs
Wed Jul 13 20:30:20 2005 UTC (18 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_1_99_2, HEAD
Will now prompt for embedded .css and .js files in uploaded HTML documents.

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

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