File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.668: download - view: text, annotated - select for diffs
Thu Oct 27 17:01:35 2005 UTC (18 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Scope.

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

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