File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.667: download - view: text, annotated - select for diffs
Tue Oct 25 19:14:33 2005 UTC (18 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- migrateuser checks the input data more carefully
- tmpput and tmpget now have lonnet implementations

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

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