File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.651.2.2: download - view: text, annotated - select for diffs
Thu Sep 1 06:48:05 2005 UTC (18 years, 10 months ago) by albertel
Branches: version_2_0_X
CVS tags: version_2_0_1
- backport 1.652

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

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