File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.755: download - view: text, annotated - select for diffs
Thu Jun 22 14:30:14 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- adding an easy to use network error detector
- dump internally detect the error: 2 case and no longer returns it

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.755 2006/06/22 14:30:14 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: use lib '/home/httpd/lib/perl';
   56: use LONCAPA;
   57: use LONCAPA::Configuration;
   58: 
   59: my $readit;
   60: my $max_connection_retries = 10;     # Or some such value.
   61: 
   62: require Exporter;
   63: 
   64: our @ISA = qw (Exporter);
   65: our @EXPORT = qw(%env);
   66: 
   67: =pod
   68: 
   69: =head1 Package Variables
   70: 
   71: These are largely undocumented, so if you decipher one please note it here.
   72: 
   73: =over 4
   74: 
   75: =item $processmarker
   76: 
   77: Contains the time this process was started and this servers host id.
   78: 
   79: =item $dumpcount
   80: 
   81: Counts the number of times a message log flush has been attempted (regardless
   82: of success) by this process.  Used as part of the filename when messages are
   83: delayed.
   84: 
   85: =back
   86: 
   87: =cut
   88: 
   89: 
   90: # --------------------------------------------------------------------- Logging
   91: {
   92:     my $logid;
   93:     sub instructor_log {
   94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   95: 	$logid++;
   96: 	my $id=time().'00000'.$$.'00000'.$logid;
   97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   98: 				    { $id => {
   99: 					'exe_uname' => $env{'user.name'},
  100: 					'exe_udom'  => $env{'user.domain'},
  101: 					'exe_time'  => time(),
  102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  103: 					'delflag'   => $delflag,
  104: 					'logentry'  => $storehash,
  105: 					'uname'     => $uname,
  106: 					'udom'      => $udom,
  107: 				    }
  108: 				  },
  109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  111: 				    );
  112:     }
  113: }
  114: 
  115: sub logtouch {
  116:     my $execdir=$perlvar{'lonDaemons'};
  117:     unless (-e "$execdir/logs/lonnet.log") {	
  118: 	open(my $fh,">>$execdir/logs/lonnet.log");
  119: 	close $fh;
  120:     }
  121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  123: }
  124: 
  125: sub logthis {
  126:     my $message=shift;
  127:     my $execdir=$perlvar{'lonDaemons'};
  128:     my $now=time;
  129:     my $local=localtime($now);
  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  131: 	print $fh "$local ($$): $message\n";
  132: 	close($fh);
  133:     }
  134:     return 1;
  135: }
  136: 
  137: sub logperm {
  138:     my $message=shift;
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     my $now=time;
  141:     my $local=localtime($now);
  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  143: 	print $fh "$now:$message:$local\n";
  144: 	close($fh);
  145:     }
  146:     return 1;
  147: }
  148: 
  149: # -------------------------------------------------- Non-critical communication
  150: sub subreply {
  151:     my ($cmd,$server)=@_;
  152:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
  153:     #
  154:     #  With loncnew process trimming, there's a timing hole between lonc server
  155:     #  process exit and the master server picking up the listen on the AF_UNIX
  156:     #  socket.  In that time interval, a lock file will exist:
  157: 
  158:     my $lockfile=$peerfile.".lock";
  159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  160: 	sleep(1);
  161:     }
  162:     # At this point, either a loncnew parent is listening or an old lonc
  163:     # or loncnew child is listening so we can connect or everything's dead.
  164:     #
  165:     #   We'll give the connection a few tries before abandoning it.  If
  166:     #   connection is not possible, we'll con_lost back to the client.
  167:     #   
  168:     my $client;
  169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  171: 				      Type    => SOCK_STREAM,
  172: 				      Timeout => 10);
  173: 	if($client) {
  174: 	    last;		# Connected!
  175: 	}
  176: 	sleep(1);		# Try again later if failed connection.
  177:     }
  178:     my $answer;
  179:     if ($client) {
  180: 	print $client "sethost:$server:$cmd\n";
  181: 	$answer=<$client>;
  182: 	if (!$answer) { $answer="con_lost"; }
  183: 	chomp($answer);
  184:     } else {
  185: 	$answer = 'con_lost';	# Failed connection.
  186:     }
  187:     return $answer;
  188: }
  189: 
  190: sub reply {
  191:     my ($cmd,$server)=@_;
  192:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  193:     my $answer=subreply($cmd,$server);
  194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  195:        &logthis("<font color=\"blue\">WARNING:".
  196:                 " $cmd to $server returned $answer</font>");
  197:     }
  198:     return $answer;
  199: }
  200: 
  201: # ----------------------------------------------------------- Send USR1 to lonc
  202: 
  203: sub reconlonc {
  204:     my $peerfile=shift;
  205:     &logthis("Trying to reconnect for $peerfile");
  206:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  207:     if (open(my $fh,"<$loncfile")) {
  208: 	my $loncpid=<$fh>;
  209:         chomp($loncpid);
  210:         if (kill 0 => $loncpid) {
  211: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  212:             kill USR1 => $loncpid;
  213:             sleep 1;
  214:             if (-e "$peerfile") { return; }
  215:             &logthis("$peerfile still not there, give it another try");
  216:             sleep 5;
  217:             if (-e "$peerfile") { return; }
  218:             &logthis(
  219:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
  220:         } else {
  221: 	    &logthis(
  222:                "<font color=\"blue\">WARNING:".
  223:                " lonc at pid $loncpid not responding, giving up</font>");
  224:         }
  225:     } else {
  226:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  227:     }
  228: }
  229: 
  230: # ------------------------------------------------------ Critical communication
  231: 
  232: sub critical {
  233:     my ($cmd,$server)=@_;
  234:     unless ($hostname{$server}) {
  235:         &logthis("<font color=\"blue\">WARNING:".
  236:                " Critical message to unknown server ($server)</font>");
  237:         return 'no_such_host';
  238:     }
  239:     my $answer=reply($cmd,$server);
  240:     if ($answer eq 'con_lost') {
  241: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  242: 	my $answer=reply($cmd,$server);
  243:         if ($answer eq 'con_lost') {
  244:             my $now=time;
  245:             my $middlename=$cmd;
  246:             $middlename=substr($middlename,0,16);
  247:             $middlename=~s/\W//g;
  248:             my $dfilename=
  249:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  250:             $dumpcount++;
  251:             {
  252: 		my $dfh;
  253: 		if (open($dfh,">$dfilename")) {
  254: 		    print $dfh "$cmd\n"; 
  255: 		    close($dfh);
  256: 		}
  257:             }
  258:             sleep 2;
  259:             my $wcmd='';
  260:             {
  261: 		my $dfh;
  262: 		if (open($dfh,"<$dfilename")) {
  263: 		    $wcmd=<$dfh>; 
  264: 		    close($dfh);
  265: 		}
  266:             }
  267:             chomp($wcmd);
  268:             if ($wcmd eq $cmd) {
  269: 		&logthis("<font color=\"blue\">WARNING: ".
  270:                          "Connection buffer $dfilename: $cmd</font>");
  271:                 &logperm("D:$server:$cmd");
  272: 	        return 'con_delayed';
  273:             } else {
  274:                 &logthis("<font color=\"red\">CRITICAL:"
  275:                         ." Critical connection failed: $server $cmd</font>");
  276:                 &logperm("F:$server:$cmd");
  277:                 return 'con_failed';
  278:             }
  279:         }
  280:     }
  281:     return $answer;
  282: }
  283: 
  284: # ------------------------------------------- check if return value is an error
  285: 
  286: sub error {
  287:     my ($result) = @_;
  288:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) )/) {
  289: 	if ($2 == 2) { return undef; }
  290: 	return $1;
  291:     }
  292:     &logthis("accepting $result");
  293:     return undef;
  294: }
  295: 
  296: # ------------------------------------------- Transfer profile into environment
  297: 
  298: sub transfer_profile_to_env {
  299:     my ($lonidsdir,$handle)=@_;
  300:     if (!defined($lonidsdir)) {
  301: 	$lonidsdir = $perlvar{'lonIDsDir'};
  302:     }
  303:     if (!defined($handle)) {
  304:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  305:     }
  306: 
  307:     my @profile;
  308:     {
  309: 	open(my $idf,"$lonidsdir/$handle.id");
  310: 	flock($idf,LOCK_SH);
  311: 	@profile=<$idf>;
  312: 	close($idf);
  313:     }
  314:     my $envi;
  315:     my %Remove;
  316:     for ($envi=0;$envi<=$#profile;$envi++) {
  317: 	chomp($profile[$envi]);
  318: 	my ($envname,$envvalue)=split(/=/,$profile[$envi],2);
  319: 	$envname=&unescape($envname);
  320: 	$envvalue=&unescape($envvalue);
  321: 	$env{$envname} = $envvalue;
  322:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  323:             if ($time < time-300) {
  324:                 $Remove{$key}++;
  325:             }
  326:         }
  327:     }
  328:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  329:     foreach my $expired_key (keys(%Remove)) {
  330:         &delenv($expired_key);
  331:     }
  332: }
  333: 
  334: # ---------------------------------------------------------- Append Environment
  335: 
  336: sub appenv {
  337:     my %newenv=@_;
  338:     foreach my $key (keys(%newenv)) {
  339: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  340:             &logthis("<font color=\"blue\">WARNING: ".
  341:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  342:                 .'</font>');
  343: 	    delete($newenv{$key});
  344:         } else {
  345:             $env{$key}=$newenv{$key};
  346:         }
  347:     }
  348: 
  349:     my $lockfh;
  350:     unless (open($lockfh,"$env{'user.environment'}")) {
  351: 	return 'error: '.$!;
  352:     }
  353:     unless (flock($lockfh,LOCK_EX)) {
  354:          &logthis("<font color=\"blue\">WARNING: ".
  355:                   'Could not obtain exclusive lock in appenv: '.$!);
  356:          close($lockfh);
  357:          return 'error: '.$!;
  358:     }
  359: 
  360:     my @oldenv;
  361:     {
  362: 	my $fh;
  363: 	unless (open($fh,"$env{'user.environment'}")) {
  364: 	    return 'error: '.$!;
  365: 	}
  366: 	@oldenv=<$fh>;
  367: 	close($fh);
  368:     }
  369:     for (my $i=0; $i<=$#oldenv; $i++) {
  370:         chomp($oldenv[$i]);
  371:         if ($oldenv[$i] ne '') {
  372: 	    my ($name,$value)=split(/=/,$oldenv[$i],2);
  373: 	    $name=&unescape($name);
  374: 	    $value=&unescape($value);
  375: 	    unless (defined($newenv{$name})) {
  376: 		$newenv{$name}=$value;
  377: 	    }
  378:         }
  379:     }
  380:     {
  381: 	my $fh;
  382: 	unless (open($fh,">$env{'user.environment'}")) {
  383: 	    return 'error';
  384: 	}
  385: 	my $newname;
  386: 	foreach $newname (keys %newenv) {
  387: 	    print $fh &escape($newname).'='.&escape($newenv{$newname})."\n";
  388: 	}
  389: 	close($fh);
  390:     }
  391: 	
  392:     close($lockfh);
  393:     return 'ok';
  394: }
  395: # ----------------------------------------------------- Delete from Environment
  396: 
  397: sub delenv {
  398:     my $delthis=shift;
  399:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  400:         &logthis("<font color=\"blue\">WARNING: ".
  401:                 "Attempt to delete from environment ".$delthis);
  402:         return 'error';
  403:     }
  404:     my @oldenv;
  405:     {
  406: 	my $fh;
  407: 	unless (open($fh,"$env{'user.environment'}")) {
  408: 	    return 'error';
  409: 	}
  410: 	unless (flock($fh,LOCK_SH)) {
  411: 	    &logthis("<font color=\"blue\">WARNING: ".
  412: 		     'Could not obtain shared lock in delenv: '.$!);
  413: 	    close($fh);
  414: 	    return 'error: '.$!;
  415: 	}
  416: 	@oldenv=<$fh>;
  417: 	close($fh);
  418:     }
  419:     {
  420: 	my $fh;
  421: 	unless (open($fh,">$env{'user.environment'}")) {
  422: 	    return 'error';
  423: 	}
  424: 	unless (flock($fh,LOCK_EX)) {
  425: 	    &logthis("<font color=\"blue\">WARNING: ".
  426: 		     'Could not obtain exclusive lock in delenv: '.$!);
  427: 	    close($fh);
  428: 	    return 'error: '.$!;
  429: 	}
  430: 	foreach my $cur_key (@oldenv) {
  431: 	    my $unescaped_cur_key = &unescape($cur_key);
  432: 	    if ($unescaped_cur_key=~/^$delthis/) { 
  433:                 my ($key) = split('=',$cur_key,2);
  434: 		$key = &unescape($key);
  435:                 delete($env{$key});
  436:             } else {
  437:                 print $fh $cur_key; 
  438:             }
  439: 	}
  440: 	close($fh);
  441:     }
  442:     return 'ok';
  443: }
  444: 
  445: # ------------------------------------------ Find out current server userload
  446: # there is a copy in lond
  447: sub userload {
  448:     my $numusers=0;
  449:     {
  450: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  451: 	my $filename;
  452: 	my $curtime=time;
  453: 	while ($filename=readdir(LONIDS)) {
  454: 	    if ($filename eq '.' || $filename eq '..') {next;}
  455: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  456: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  457: 	}
  458: 	closedir(LONIDS);
  459:     }
  460:     my $userloadpercent=0;
  461:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  462:     if ($maxuserload) {
  463: 	$userloadpercent=100*$numusers/$maxuserload;
  464:     }
  465:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  466:     return $userloadpercent;
  467: }
  468: 
  469: # ------------------------------------------ Fight off request when overloaded
  470: 
  471: sub overloaderror {
  472:     my ($r,$checkserver)=@_;
  473:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  474:     my $loadavg;
  475:     if ($checkserver eq $perlvar{'lonHostID'}) {
  476:        open(my $loadfile,'/proc/loadavg');
  477:        $loadavg=<$loadfile>;
  478:        $loadavg =~ s/\s.*//g;
  479:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  480:        close($loadfile);
  481:     } else {
  482:        $loadavg=&reply('load',$checkserver);
  483:     }
  484:     my $overload=$loadavg-100;
  485:     if ($overload>0) {
  486: 	$r->err_headers_out->{'Retry-After'}=$overload;
  487:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  488:         return 413;
  489:     }    
  490:     return '';
  491: }
  492: 
  493: # ------------------------------ Find server with least workload from spare.tab
  494: 
  495: sub spareserver {
  496:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  497:     my $tryserver;
  498:     my $spareserver='';
  499:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  500:     my $lowestserver=$loadpercent > $userloadpercent?
  501: 	             $loadpercent :  $userloadpercent;
  502:     foreach $tryserver (keys(%spareid)) {
  503: 	my $loadans=&reply('load',$tryserver);
  504: 	my $userloadans=&reply('userload',$tryserver);
  505: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  506: 	    next; #didn't get a number from the server
  507: 	}
  508: 	my $answer;
  509: 	if ($loadans =~ /\d/) {
  510: 	    if ($userloadans =~ /\d/) {
  511: 		#both are numbers, pick the bigger one
  512: 		$answer=$loadans > $userloadans?
  513: 		    $loadans :  $userloadans;
  514: 	    } else {
  515: 		$answer = $loadans;
  516: 	    }
  517: 	} else {
  518: 	    $answer = $userloadans;
  519: 	}
  520: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  521: 	    if ($want_server_name) {
  522: 		$spareserver=$tryserver;
  523: 	    } else {
  524: 		$spareserver="http://$hostname{$tryserver}";
  525: 	    }
  526: 	    $lowestserver=$answer;
  527: 	}
  528:     }
  529:     return $spareserver;
  530: }
  531: 
  532: # --------------------------------------------- Try to change a user's password
  533: 
  534: sub changepass {
  535:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  536:     $currentpass = &escape($currentpass);
  537:     $newpass     = &escape($newpass);
  538:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  539: 		       $server);
  540:     if (! $answer) {
  541: 	&logthis("No reply on password change request to $server ".
  542: 		 "by $uname in domain $udom.");
  543:     } elsif ($answer =~ "^ok") {
  544:         &logthis("$uname in $udom successfully changed their password ".
  545: 		 "on $server.");
  546:     } elsif ($answer =~ "^pwchange_failure") {
  547: 	&logthis("$uname in $udom was unable to change their password ".
  548: 		 "on $server.  The action was blocked by either lcpasswd ".
  549: 		 "or pwchange");
  550:     } elsif ($answer =~ "^non_authorized") {
  551:         &logthis("$uname in $udom did not get their password correct when ".
  552: 		 "attempting to change it on $server.");
  553:     } elsif ($answer =~ "^auth_mode_error") {
  554:         &logthis("$uname in $udom attempted to change their password despite ".
  555: 		 "not being locally or internally authenticated on $server.");
  556:     } elsif ($answer =~ "^unknown_user") {
  557:         &logthis("$uname in $udom attempted to change their password ".
  558: 		 "on $server but were unable to because $server is not ".
  559: 		 "their home server.");
  560:     } elsif ($answer =~ "^refused") {
  561: 	&logthis("$server refused to change $uname in $udom password because ".
  562: 		 "it was sent an unencrypted request to change the password.");
  563:     }
  564:     return $answer;
  565: }
  566: 
  567: # ----------------------- Try to determine user's current authentication scheme
  568: 
  569: sub queryauthenticate {
  570:     my ($uname,$udom)=@_;
  571:     my $uhome=&homeserver($uname,$udom);
  572:     if (!$uhome) {
  573: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  574: 	return 'no_host';
  575:     }
  576:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  577:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  578: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  579:     }
  580:     return $answer;
  581: }
  582: 
  583: # --------- Try to authenticate user from domain's lib servers (first this one)
  584: 
  585: sub authenticate {
  586:     my ($uname,$upass,$udom)=@_;
  587:     $upass=escape($upass);
  588:     $uname=~s/\W//g;
  589:     my $uhome=&homeserver($uname,$udom);
  590:     if (!$uhome) {
  591: 	&logthis("User $uname at $udom is unknown in authenticate");
  592: 	return 'no_host';
  593:     }
  594:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  595:     if ($answer eq 'authorized') {
  596: 	&logthis("User $uname at $udom authorized by $uhome"); 
  597: 	return $uhome; 
  598:     }
  599:     if ($answer eq 'non_authorized') {
  600: 	&logthis("User $uname at $udom rejected by $uhome");
  601: 	return 'no_host'; 
  602:     }
  603:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  604:     return 'no_host';
  605: }
  606: 
  607: # ---------------------- Find the homebase for a user from domain's lib servers
  608: 
  609: my %homecache;
  610: sub homeserver {
  611:     my ($uname,$udom,$ignoreBadCache)=@_;
  612:     my $index="$uname:$udom";
  613: 
  614:     if (exists($homecache{$index})) { return $homecache{$index}; }
  615:     my $tryserver;
  616:     foreach $tryserver (keys %libserv) {
  617:         next if ($ignoreBadCache ne 'true' && 
  618: 		 exists($badServerCache{$tryserver}));
  619: 	if ($hostdom{$tryserver} eq $udom) {
  620:            my $answer=reply("home:$udom:$uname",$tryserver);
  621:            if ($answer eq 'found') { 
  622: 	       return $homecache{$index}=$tryserver;
  623:            } elsif ($answer eq 'no_host') {
  624: 	       $badServerCache{$tryserver}=1;
  625:            }
  626:        }
  627:     }    
  628:     return 'no_host';
  629: }
  630: 
  631: # ------------------------------------- Find the usernames behind a list of IDs
  632: 
  633: sub idget {
  634:     my ($udom,@ids)=@_;
  635:     my %returnhash=();
  636:     
  637:     my $tryserver;
  638:     foreach $tryserver (keys %libserv) {
  639:        if ($hostdom{$tryserver} eq $udom) {
  640: 	  my $idlist=join('&',@ids);
  641:           $idlist=~tr/A-Z/a-z/; 
  642: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  643:           my @answer=();
  644:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  645: 	      @answer=split(/\&/,$reply);
  646:           }                    ;
  647:           my $i;
  648:           for ($i=0;$i<=$#ids;$i++) {
  649:               if ($answer[$i]) {
  650: 		  $returnhash{$ids[$i]}=$answer[$i];
  651:               } 
  652:           }
  653:        }
  654:     }    
  655:     return %returnhash;
  656: }
  657: 
  658: # ------------------------------------- Find the IDs behind a list of usernames
  659: 
  660: sub idrget {
  661:     my ($udom,@unames)=@_;
  662:     my %returnhash=();
  663:     foreach (@unames) {
  664:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  665:     }
  666:     return %returnhash;
  667: }
  668: 
  669: # ------------------------------- Store away a list of names and associated IDs
  670: 
  671: sub idput {
  672:     my ($udom,%ids)=@_;
  673:     my %servers=();
  674:     foreach (keys %ids) {
  675: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  676:         my $uhom=&homeserver($_,$udom);
  677:         if ($uhom ne 'no_host') {
  678:             my $id=&escape($ids{$_});
  679:             $id=~tr/A-Z/a-z/;
  680:             my $unam=&escape($_);
  681: 	    if ($servers{$uhom}) {
  682: 		$servers{$uhom}.='&'.$id.'='.$unam;
  683:             } else {
  684:                 $servers{$uhom}=$id.'='.$unam;
  685:             }
  686:         }
  687:     }
  688:     foreach (keys %servers) {
  689:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  690:     }
  691: }
  692: 
  693: # --------------------------------------------------- Assign a key to a student
  694: 
  695: sub assign_access_key {
  696: #
  697: # a valid key looks like uname:udom#comments
  698: # comments are being appended
  699: #
  700:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  701:     $kdom=
  702:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  703:     $knum=
  704:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  705:     $cdom=
  706:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  707:     $cnum=
  708:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  709:     $udom=$env{'user.name'} unless (defined($udom));
  710:     $uname=$env{'user.domain'} unless (defined($uname));
  711:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  712:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  713:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  714:                                                   # assigned to this person
  715:                                                   # - this should not happen,
  716:                                                   # unless something went wrong
  717:                                                   # the first time around
  718: # ready to assign
  719:         $logentry=$1.'; '.$logentry;
  720:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  721:                                                  $kdom,$knum) eq 'ok') {
  722: # key now belongs to user
  723: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  724:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  725:                 &appenv('environment.'.$envkey => $ckey);
  726:                 return 'ok';
  727:             } else {
  728:                 return 
  729:   'error: Count not permanently assign key, will need to be re-entered later.';
  730: 	    }
  731:         } else {
  732:             return 'error: Could not assign key, try again later.';
  733:         }
  734:     } elsif (!$existing{$ckey}) {
  735: # the key does not exist
  736: 	return 'error: The key does not exist';
  737:     } else {
  738: # the key is somebody else's
  739: 	return 'error: The key is already in use';
  740:     }
  741: }
  742: 
  743: # ------------------------------------------ put an additional comment on a key
  744: 
  745: sub comment_access_key {
  746: #
  747: # a valid key looks like uname:udom#comments
  748: # comments are being appended
  749: #
  750:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  751:     $cdom=
  752:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  753:     $cnum=
  754:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  755:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  756:     if ($existing{$ckey}) {
  757:         $existing{$ckey}.='; '.$logentry;
  758: # ready to assign
  759:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  760:                                                  $cdom,$cnum) eq 'ok') {
  761: 	    return 'ok';
  762:         } else {
  763: 	    return 'error: Count not store comment.';
  764:         }
  765:     } else {
  766: # the key does not exist
  767: 	return 'error: The key does not exist';
  768:     }
  769: }
  770: 
  771: # ------------------------------------------------------ Generate a set of keys
  772: 
  773: sub generate_access_keys {
  774:     my ($number,$cdom,$cnum,$logentry)=@_;
  775:     $cdom=
  776:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  777:     $cnum=
  778:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  779:     unless (&allowed('mky',$cdom)) { return 0; }
  780:     unless (($cdom) && ($cnum)) { return 0; }
  781:     if ($number>10000) { return 0; }
  782:     sleep(2); # make sure don't get same seed twice
  783:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  784:     my $total=0;
  785:     for (my $i=1;$i<=$number;$i++) {
  786:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  787:                   sprintf("%lx",int(100000*rand)).'-'.
  788:                   sprintf("%lx",int(100000*rand));
  789:        $newkey=~s/1/g/g; # folks mix up 1 and l
  790:        $newkey=~s/0/h/g; # and also 0 and O
  791:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  792:        if ($existing{$newkey}) {
  793:            $i--;
  794:        } else {
  795: 	  if (&put('accesskeys',
  796:               { $newkey => '# generated '.localtime().
  797:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  798:                            '; '.$logentry },
  799: 		   $cdom,$cnum) eq 'ok') {
  800:               $total++;
  801: 	  }
  802:        }
  803:     }
  804:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  805:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  806:     return $total;
  807: }
  808: 
  809: # ------------------------------------------------------- Validate an accesskey
  810: 
  811: sub validate_access_key {
  812:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  813:     $cdom=
  814:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  815:     $cnum=
  816:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  817:     $udom=$env{'user.domain'} unless (defined($udom));
  818:     $uname=$env{'user.name'} unless (defined($uname));
  819:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  820:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  821: }
  822: 
  823: # ------------------------------------- Find the section of student in a course
  824: sub devalidate_getsection_cache {
  825:     my ($udom,$unam,$courseid)=@_;
  826:     $courseid=~s/\_/\//g;
  827:     $courseid=~s/^(\w)/\/$1/;
  828:     my $hashid="$udom:$unam:$courseid";
  829:     &devalidate_cache_new('getsection',$hashid);
  830: }
  831: 
  832: sub getsection {
  833:     my ($udom,$unam,$courseid)=@_;
  834:     my $cachetime=1800;
  835:     $courseid=~s/\_/\//g;
  836:     $courseid=~s/^(\w)/\/$1/;
  837: 
  838:     my $hashid="$udom:$unam:$courseid";
  839:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  840:     if (defined($cached)) { return $result; }
  841: 
  842:     my %Pending; 
  843:     my %Expired;
  844:     #
  845:     # Each role can either have not started yet (pending), be active, 
  846:     #    or have expired.
  847:     #
  848:     # If there is an active role, we are done.
  849:     #
  850:     # If there is more than one role which has not started yet, 
  851:     #     choose the one which will start sooner
  852:     # If there is one role which has not started yet, return it.
  853:     #
  854:     # If there is more than one expired role, choose the one which ended last.
  855:     # If there is a role which has expired, return it.
  856:     #
  857:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  858:                         &homeserver($unam,$udom)))) {
  859:         my ($key,$value)=split(/\=/,$_);
  860:         $key=&unescape($key);
  861:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  862:         my $section=$1;
  863:         if ($key eq $courseid.'_st') { $section=''; }
  864:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  865:         my $now=time;
  866:         if (defined($end) && $end && ($now > $end)) {
  867:             $Expired{$end}=$section;
  868:             next;
  869:         }
  870:         if (defined($start) && $start && ($now < $start)) {
  871:             $Pending{$start}=$section;
  872:             next;
  873:         }
  874:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  875:     }
  876:     #
  877:     # Presumedly there will be few matching roles from the above
  878:     # loop and the sorting time will be negligible.
  879:     if (scalar(keys(%Pending))) {
  880:         my ($time) = sort {$a <=> $b} keys(%Pending);
  881:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  882:     } 
  883:     if (scalar(keys(%Expired))) {
  884:         my @sorted = sort {$a <=> $b} keys(%Expired);
  885:         my $time = pop(@sorted);
  886:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  887:     }
  888:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  889: }
  890: 
  891: sub save_cache {
  892:     &purge_remembered();
  893:     #&Apache::loncommon::validate_page();
  894:     undef(%env);
  895: }
  896: 
  897: my $to_remember=-1;
  898: my %remembered;
  899: my %accessed;
  900: my $kicks=0;
  901: my $hits=0;
  902: sub devalidate_cache_new {
  903:     my ($name,$id,$debug) = @_;
  904:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  905:     $id=&escape($name.':'.$id);
  906:     $memcache->delete($id);
  907:     delete($remembered{$id});
  908:     delete($accessed{$id});
  909: }
  910: 
  911: sub is_cached_new {
  912:     my ($name,$id,$debug) = @_;
  913:     $id=&escape($name.':'.$id);
  914:     if (exists($remembered{$id})) {
  915: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  916: 	$accessed{$id}=[&gettimeofday()];
  917: 	$hits++;
  918: 	return ($remembered{$id},1);
  919:     }
  920:     my $value = $memcache->get($id);
  921:     if (!(defined($value))) {
  922: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  923: 	return (undef,undef);
  924:     }
  925:     if ($value eq '__undef__') {
  926: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  927: 	$value=undef;
  928:     }
  929:     &make_room($id,$value,$debug);
  930:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  931:     return ($value,1);
  932: }
  933: 
  934: sub do_cache_new {
  935:     my ($name,$id,$value,$time,$debug) = @_;
  936:     $id=&escape($name.':'.$id);
  937:     my $setvalue=$value;
  938:     if (!defined($setvalue)) {
  939: 	$setvalue='__undef__';
  940:     }
  941:     if (!defined($time) ) {
  942: 	$time=600;
  943:     }
  944:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  945:     $memcache->set($id,$setvalue,$time);
  946:     # need to make a copy of $value
  947:     #&make_room($id,$value,$debug);
  948:     return $value;
  949: }
  950: 
  951: sub make_room {
  952:     my ($id,$value,$debug)=@_;
  953:     $remembered{$id}=$value;
  954:     if ($to_remember<0) { return; }
  955:     $accessed{$id}=[&gettimeofday()];
  956:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  957:     my $to_kick;
  958:     my $max_time=0;
  959:     foreach my $other (keys(%accessed)) {
  960: 	if (&tv_interval($accessed{$other}) > $max_time) {
  961: 	    $to_kick=$other;
  962: 	    $max_time=&tv_interval($accessed{$other});
  963: 	}
  964:     }
  965:     delete($remembered{$to_kick});
  966:     delete($accessed{$to_kick});
  967:     $kicks++;
  968:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  969:     return;
  970: }
  971: 
  972: sub purge_remembered {
  973:     #&logthis("Tossing ".scalar(keys(%remembered)));
  974:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  975:     undef(%remembered);
  976:     undef(%accessed);
  977: }
  978: # ------------------------------------- Read an entry from a user's environment
  979: 
  980: sub userenvironment {
  981:     my ($udom,$unam,@what)=@_;
  982:     my %returnhash=();
  983:     my @answer=split(/\&/,
  984:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  985:                       &homeserver($unam,$udom)));
  986:     my $i;
  987:     for ($i=0;$i<=$#what;$i++) {
  988: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  989:     }
  990:     return %returnhash;
  991: }
  992: 
  993: # ---------------------------------------------------------- Get a studentphoto
  994: sub studentphoto {
  995:     my ($udom,$unam,$ext) = @_;
  996:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  997:     if (defined($env{'request.course.id'})) {
  998:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
  999:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1000:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1001:             } else {
 1002:                 my ($result,$perm_reqd)=
 1003: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1004:                 if ($result eq 'ok') {
 1005:                     if (!($perm_reqd eq 'yes')) {
 1006:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1007:                     }
 1008:                 }
 1009:             }
 1010:         }
 1011:     } else {
 1012:         my ($result,$perm_reqd) = 
 1013: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1014:         if ($result eq 'ok') {
 1015:             if (!($perm_reqd eq 'yes')) {
 1016:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1017:             }
 1018:         }
 1019:     }
 1020:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1021: }
 1022: 
 1023: sub retrievestudentphoto {
 1024:     my ($udom,$unam,$ext,$type) = @_;
 1025:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1026:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1027:     if ($ret eq 'ok') {
 1028:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1029:         if ($type eq 'thumbnail') {
 1030:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1031:         }
 1032:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1033:         return $tokenurl;
 1034:     } else {
 1035:         if ($type eq 'thumbnail') {
 1036:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1037:         } else { 
 1038:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1039:         }
 1040:     }
 1041: }
 1042: 
 1043: # -------------------------------------------------------------------- New chat
 1044: 
 1045: sub chatsend {
 1046:     my ($newentry,$anon,$group)=@_;
 1047:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1048:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1049:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1050:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1051: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1052: 		   &escape($newentry)).':'.$group,$chome);
 1053: }
 1054: 
 1055: # ------------------------------------------ Find current version of a resource
 1056: 
 1057: sub getversion {
 1058:     my $fname=&clutter(shift);
 1059:     unless ($fname=~/^\/res\//) { return -1; }
 1060:     return &currentversion(&filelocation('',$fname));
 1061: }
 1062: 
 1063: sub currentversion {
 1064:     my $fname=shift;
 1065:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1066:     if (defined($cached)) { return $result; }
 1067:     my $author=$fname;
 1068:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1069:     my ($udom,$uname)=split(/\//,$author);
 1070:     my $home=homeserver($uname,$udom);
 1071:     if ($home eq 'no_host') { 
 1072:         return -1; 
 1073:     }
 1074:     my $answer=reply("currentversion:$fname",$home);
 1075:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1076: 	return -1;
 1077:     }
 1078:     return &do_cache_new('resversion',$fname,$answer,600);
 1079: }
 1080: 
 1081: # ----------------------------- Subscribe to a resource, return URL if possible
 1082: 
 1083: sub subscribe {
 1084:     my $fname=shift;
 1085:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1086:     $fname=~s/[\n\r]//g;
 1087:     my $author=$fname;
 1088:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1089:     my ($udom,$uname)=split(/\//,$author);
 1090:     my $home=homeserver($uname,$udom);
 1091:     if ($home eq 'no_host') {
 1092:         return 'not_found';
 1093:     }
 1094:     my $answer=reply("sub:$fname",$home);
 1095:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1096: 	$answer.=' by '.$home;
 1097:     }
 1098:     return $answer;
 1099: }
 1100:     
 1101: # -------------------------------------------------------------- Replicate file
 1102: 
 1103: sub repcopy {
 1104:     my $filename=shift;
 1105:     $filename=~s/\/+/\//g;
 1106:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1107:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1108:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1109: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1110: 	return &repcopy_userfile($filename);
 1111:     }
 1112:     $filename=~s/[\n\r]//g;
 1113:     my $transname="$filename.in.transfer";
 1114:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1115:     my $remoteurl=subscribe($filename);
 1116:     if ($remoteurl =~ /^con_lost by/) {
 1117: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1118:            return 'unavailable';
 1119:     } elsif ($remoteurl eq 'not_found') {
 1120: 	   #&logthis("Subscribe returned not_found: $filename");
 1121: 	   return 'not_found';
 1122:     } elsif ($remoteurl =~ /^rejected by/) {
 1123: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1124:            return 'forbidden';
 1125:     } elsif ($remoteurl eq 'directory') {
 1126:            return 'ok';
 1127:     } else {
 1128:         my $author=$filename;
 1129:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1130:         my ($udom,$uname)=split(/\//,$author);
 1131:         my $home=homeserver($uname,$udom);
 1132:         unless ($home eq $perlvar{'lonHostID'}) {
 1133:            my @parts=split(/\//,$filename);
 1134:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1135:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1136:                &logthis("Malconfiguration for replication: $filename");
 1137: 	       return 'bad_request';
 1138:            }
 1139:            my $count;
 1140:            for ($count=5;$count<$#parts;$count++) {
 1141:                $path.="/$parts[$count]";
 1142:                if ((-e $path)!=1) {
 1143: 		   mkdir($path,0777);
 1144:                }
 1145:            }
 1146:            my $ua=new LWP::UserAgent;
 1147:            my $request=new HTTP::Request('GET',"$remoteurl");
 1148:            my $response=$ua->request($request,$transname);
 1149:            if ($response->is_error()) {
 1150: 	       unlink($transname);
 1151:                my $message=$response->status_line;
 1152:                &logthis("<font color=\"blue\">WARNING:"
 1153:                        ." LWP get: $message: $filename</font>");
 1154:                return 'unavailable';
 1155:            } else {
 1156: 	       if ($remoteurl!~/\.meta$/) {
 1157:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1158:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1159:                   if ($mresponse->is_error()) {
 1160: 		      unlink($filename.'.meta');
 1161:                       &logthis(
 1162:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1163:                   }
 1164: 	       }
 1165:                rename($transname,$filename);
 1166:                return 'ok';
 1167:            }
 1168:        }
 1169:     }
 1170: }
 1171: 
 1172: # ------------------------------------------------ Get server side include body
 1173: sub ssi_body {
 1174:     my ($filelink,%form)=@_;
 1175:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1176:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1177:     }
 1178:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1179:                                      &ssi($filelink,%form));
 1180:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
 1181:     $output=~s/^.*?\<body[^\>]*\>//si;
 1182:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1183:     return $output;
 1184: }
 1185: 
 1186: # --------------------------------------------------------- Server Side Include
 1187: 
 1188: sub ssi {
 1189: 
 1190:     my ($fn,%form)=@_;
 1191: 
 1192:     my $ua=new LWP::UserAgent;
 1193:     
 1194:     my $request;
 1195: 
 1196:     $form{'no_update_last_known'}=1;
 1197: 
 1198:     if (%form) {
 1199:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1200:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1201:     } else {
 1202:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1203:     }
 1204: 
 1205:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1206:     my $response=$ua->request($request);
 1207: 
 1208:     return $response->content;
 1209: }
 1210: 
 1211: sub externalssi {
 1212:     my ($url)=@_;
 1213:     my $ua=new LWP::UserAgent;
 1214:     my $request=new HTTP::Request('GET',$url);
 1215:     my $response=$ua->request($request);
 1216:     return $response->content;
 1217: }
 1218: 
 1219: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1220: 
 1221: sub allowuploaded {
 1222:     my ($srcurl,$url)=@_;
 1223:     $url=&clutter(&declutter($url));
 1224:     my $dir=$url;
 1225:     $dir=~s/\/[^\/]+$//;
 1226:     my %httpref=();
 1227:     my $httpurl=&hreflocation('',$url);
 1228:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1229:     &Apache::lonnet::appenv(%httpref);
 1230: }
 1231: 
 1232: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1233: # input: action, courseID, current domain, intended
 1234: #        path to file, source of file, instruction to parse file for objects,
 1235: #        ref to hash for embedded objects,
 1236: #        ref to hash for codebase of java objects.
 1237: #
 1238: # output: url to file (if action was uploaddoc), 
 1239: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1240: #
 1241: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1242: # course.
 1243: #
 1244: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1245: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1246: #          course's home server.
 1247: #
 1248: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1249: #          be copied from $source (current location) to 
 1250: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1251: #         and will then be copied to
 1252: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1253: #         course's home server.
 1254: #
 1255: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1256: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1257: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1258: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1259: #         in course's home server.
 1260: #
 1261: 
 1262: sub process_coursefile {
 1263:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1264:     my $fetchresult;
 1265:     my $home=&homeserver($docuname,$docudom);
 1266:     if ($action eq 'propagate') {
 1267:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1268: 			     $home);
 1269:     } else {
 1270:         my $fpath = '';
 1271:         my $fname = $file;
 1272:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1273:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1274:         my $filepath = &build_filepath($fpath);
 1275:         if ($action eq 'copy') {
 1276:             if ($source eq '') {
 1277:                 $fetchresult = 'no source file';
 1278:                 return $fetchresult;
 1279:             } else {
 1280:                 my $destination = $filepath.'/'.$fname;
 1281:                 rename($source,$destination);
 1282:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1283:                                  $home);
 1284:             }
 1285:         } elsif ($action eq 'uploaddoc') {
 1286:             open(my $fh,'>'.$filepath.'/'.$fname);
 1287:             print $fh $env{'form.'.$source};
 1288:             close($fh);
 1289:             if ($parser eq 'parse') {
 1290:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1291:                 unless ($parse_result eq 'ok') {
 1292:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1293:                 }
 1294:             }
 1295:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1296:                                  $home);
 1297:             if ($fetchresult eq 'ok') {
 1298:                 return '/uploaded/'.$fpath.'/'.$fname;
 1299:             } else {
 1300:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1301:                         ' to host '.$home.': '.$fetchresult);
 1302:                 return '/adm/notfound.html';
 1303:             }
 1304:         }
 1305:     }
 1306:     unless ( $fetchresult eq 'ok') {
 1307:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1308:              ' to host '.$home.': '.$fetchresult);
 1309:     }
 1310:     return $fetchresult;
 1311: }
 1312: 
 1313: sub build_filepath {
 1314:     my ($fpath) = @_;
 1315:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1316:     unless ($fpath eq '') {
 1317:         my @parts=split('/',$fpath);
 1318:         foreach my $part (@parts) {
 1319:             $filepath.= '/'.$part;
 1320:             if ((-e $filepath)!=1) {
 1321:                 mkdir($filepath,0777);
 1322:             }
 1323:         }
 1324:     }
 1325:     return $filepath;
 1326: }
 1327: 
 1328: sub store_edited_file {
 1329:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1330:     my $file = $primary_url;
 1331:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1332:     my $fpath = '';
 1333:     my $fname = $file;
 1334:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1335:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1336:     my $filepath = &build_filepath($fpath);
 1337:     open(my $fh,'>'.$filepath.'/'.$fname);
 1338:     print $fh $content;
 1339:     close($fh);
 1340:     my $home=&homeserver($docuname,$docudom);
 1341:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1342: 			  $home);
 1343:     if ($$fetchresult eq 'ok') {
 1344:         return '/uploaded/'.$fpath.'/'.$fname;
 1345:     } else {
 1346:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1347: 		 ' to host '.$home.': '.$$fetchresult);
 1348:         return '/adm/notfound.html';
 1349:     }
 1350: }
 1351: 
 1352: sub clean_filename {
 1353:     my ($fname)=@_;
 1354: # Replace Windows backslashes by forward slashes
 1355:     $fname=~s/\\/\//g;
 1356: # Get rid of everything but the actual filename
 1357:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1358: # Replace spaces by underscores
 1359:     $fname=~s/\s+/\_/g;
 1360: # Replace all other weird characters by nothing
 1361:     $fname=~s/[^\w\.\-]//g;
 1362: # Replace all .\d. sequences with _\d. so they no longer look like version
 1363: # numbers
 1364:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1365:     return $fname;
 1366: }
 1367: 
 1368: # --------------- Take an uploaded file and put it into the userfiles directory
 1369: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1370: #                    the desired filenam is in $env{"form.$formname.filename"}
 1371: #        $coursedoc - if true up to the current course
 1372: #                     if false
 1373: #        $subdir - directory in userfile to store the file into
 1374: #        $parser, $allfiles, $codebase - unknown
 1375: #
 1376: # output: url of file in userspace, or error: <message> 
 1377: #             or /adm/notfound.html if failure to upload occurse
 1378: 
 1379: 
 1380: sub userfileupload {
 1381:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1382:     if (!defined($subdir)) { $subdir='unknown'; }
 1383:     my $fname=$env{'form.'.$formname.'.filename'};
 1384:     $fname=&clean_filename($fname);
 1385: # See if there is anything left
 1386:     unless ($fname) { return 'error: no uploaded file'; }
 1387:     chop($env{'form.'.$formname});
 1388:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1389:         my $now = time;
 1390:         my $filepath = 'tmp/helprequests/'.$now;
 1391:         my @parts=split(/\//,$filepath);
 1392:         my $fullpath = $perlvar{'lonDaemons'};
 1393:         for (my $i=0;$i<@parts;$i++) {
 1394:             $fullpath .= '/'.$parts[$i];
 1395:             if ((-e $fullpath)!=1) {
 1396:                 mkdir($fullpath,0777);
 1397:             }
 1398:         }
 1399:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1400:         print $fh $env{'form.'.$formname};
 1401:         close($fh);
 1402:         return $fullpath.'/'.$fname;
 1403:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1404:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1405:                        '_'.$env{'user.domain'}.'/pending';
 1406:         my @parts=split(/\//,$filepath);
 1407:         my $fullpath = $perlvar{'lonDaemons'};
 1408:         for (my $i=0;$i<@parts;$i++) {
 1409:             $fullpath .= '/'.$parts[$i];
 1410:             if ((-e $fullpath)!=1) {
 1411:                 mkdir($fullpath,0777);
 1412:             }
 1413:         }
 1414:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1415:         print $fh $env{'form.'.$formname};
 1416:         close($fh);
 1417:         return $fullpath.'/'.$fname;
 1418:     }
 1419:     
 1420: # Create the directory if not present
 1421:     $fname="$subdir/$fname";
 1422:     if ($coursedoc) {
 1423: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1424: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1425:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1426:             return &finishuserfileupload($docuname,$docudom,
 1427: 					 $formname,$fname,$parser,$allfiles,
 1428: 					 $codebase);
 1429:         } else {
 1430:             $fname=$env{'form.folder'}.'/'.$fname;
 1431:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1432: 				       $fname,$formname,$parser,
 1433: 				       $allfiles,$codebase);
 1434:         }
 1435:     } elsif (defined($destuname)) {
 1436:         my $docuname=$destuname;
 1437:         my $docudom=$destudom;
 1438: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1439: 				     $fname,$parser,$allfiles,$codebase);
 1440:         
 1441:     } else {
 1442:         my $docuname=$env{'user.name'};
 1443:         my $docudom=$env{'user.domain'};
 1444:         if (exists($env{'form.group'})) {
 1445:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1446:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1447:         }
 1448: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1449: 				     $fname,$parser,$allfiles,$codebase);
 1450:     }
 1451: }
 1452: 
 1453: sub finishuserfileupload {
 1454:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1455:     my $path=$docudom.'/'.$docuname.'/';
 1456:     my $filepath=$perlvar{'lonDocRoot'};
 1457:     my ($fnamepath,$file);
 1458:     $file=$fname;
 1459:     if ($fname=~m|/|) {
 1460:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1461: 	$path.=$fnamepath.'/';
 1462:     }
 1463:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1464:     my $count;
 1465:     for ($count=4;$count<=$#parts;$count++) {
 1466:         $filepath.="/$parts[$count]";
 1467:         if ((-e $filepath)!=1) {
 1468: 	    mkdir($filepath,0777);
 1469:         }
 1470:     }
 1471: # Save the file
 1472:     {
 1473: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1474: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1475: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1476: 	    return '/adm/notfound.html';
 1477: 	}
 1478: 	if (!print FH ($env{'form.'.$formname})) {
 1479: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1480: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1481: 	    return '/adm/notfound.html';
 1482: 	}
 1483: 	close(FH);
 1484:     }
 1485:     if ($parser eq 'parse') {
 1486:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1487: 						   $codebase);
 1488:         unless ($parse_result eq 'ok') {
 1489:             &logthis('Failed to parse '.$filepath.$file.
 1490: 		     ' for embedded media: '.$parse_result); 
 1491:         }
 1492:     }
 1493: # Notify homeserver to grep it
 1494: #
 1495:     my $docuhome=&homeserver($docuname,$docudom);
 1496:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1497:     if ($fetchresult eq 'ok') {
 1498: #
 1499: # Return the URL to it
 1500:         return '/uploaded/'.$path.$file;
 1501:     } else {
 1502:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1503: 		 ': '.$fetchresult);
 1504:         return '/adm/notfound.html';
 1505:     }    
 1506: }
 1507: 
 1508: sub extract_embedded_items {
 1509:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1510:     my @state = ();
 1511:     my %javafiles = (
 1512:                       codebase => '',
 1513:                       code => '',
 1514:                       archive => ''
 1515:                     );
 1516:     my %mediafiles = (
 1517:                       src => '',
 1518:                       movie => '',
 1519:                      );
 1520:     my $p;
 1521:     if ($content) {
 1522:         $p = HTML::LCParser->new($content);
 1523:     } else {
 1524:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1525:     }
 1526:     while (my $t=$p->get_token()) {
 1527: 	if ($t->[0] eq 'S') {
 1528: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1529: 	    push (@state, $tagname);
 1530:             if (lc($tagname) eq 'allow') {
 1531:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1532:             }
 1533: 	    if (lc($tagname) eq 'img') {
 1534: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1535: 	    }
 1536:             if (lc($tagname) eq 'script') {
 1537:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1538:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1539:                 } else {
 1540:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1541:                 }
 1542:             }
 1543:             if (lc($tagname) eq 'link') {
 1544:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1545:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1546:                 }
 1547:             }
 1548: 	    if (lc($tagname) eq 'object' ||
 1549: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1550: 		foreach my $item (keys(%javafiles)) {
 1551: 		    $javafiles{$item} = '';
 1552: 		}
 1553: 	    }
 1554: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1555: 		my $name = lc($attr->{'name'});
 1556: 		foreach my $item (keys(%javafiles)) {
 1557: 		    if ($name eq $item) {
 1558: 			$javafiles{$item} = $attr->{'value'};
 1559: 			last;
 1560: 		    }
 1561: 		}
 1562: 		foreach my $item (keys(%mediafiles)) {
 1563: 		    if ($name eq $item) {
 1564: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1565: 			last;
 1566: 		    }
 1567: 		}
 1568: 	    }
 1569: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1570: 		foreach my $item (keys(%javafiles)) {
 1571: 		    if ($attr->{$item}) {
 1572: 			$javafiles{$item} = $attr->{$item};
 1573: 			last;
 1574: 		    }
 1575: 		}
 1576: 		foreach my $item (keys(%mediafiles)) {
 1577: 		    if ($attr->{$item}) {
 1578: 			&add_filetype($allfiles,$attr->{$item},$item);
 1579: 			last;
 1580: 		    }
 1581: 		}
 1582: 	    }
 1583: 	} elsif ($t->[0] eq 'E') {
 1584: 	    my ($tagname) = ($t->[1]);
 1585: 	    if ($javafiles{'codebase'} ne '') {
 1586: 		$javafiles{'codebase'} .= '/';
 1587: 	    }  
 1588: 	    if (lc($tagname) eq 'applet' ||
 1589: 		lc($tagname) eq 'object' ||
 1590: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1591: 		) {
 1592: 		foreach my $item (keys(%javafiles)) {
 1593: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1594: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1595: 			&add_filetype($allfiles,$file,$item);
 1596: 		    }
 1597: 		}
 1598: 	    } 
 1599: 	    pop @state;
 1600: 	}
 1601:     }
 1602:     return 'ok';
 1603: }
 1604: 
 1605: sub add_filetype {
 1606:     my ($allfiles,$file,$type)=@_;
 1607:     if (exists($allfiles->{$file})) {
 1608: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1609: 	    push(@{$allfiles->{$file}}, &escape($type));
 1610: 	}
 1611:     } else {
 1612: 	@{$allfiles->{$file}} = (&escape($type));
 1613:     }
 1614: }
 1615: 
 1616: sub removeuploadedurl {
 1617:     my ($url)=@_;
 1618:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1619:     return &removeuserfile($uname,$udom,$fname);
 1620: }
 1621: 
 1622: sub removeuserfile {
 1623:     my ($docuname,$docudom,$fname)=@_;
 1624:     my $home=&homeserver($docuname,$docudom);
 1625:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1626: }
 1627: 
 1628: sub mkdiruserfile {
 1629:     my ($docuname,$docudom,$dir)=@_;
 1630:     my $home=&homeserver($docuname,$docudom);
 1631:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1632: }
 1633: 
 1634: sub renameuserfile {
 1635:     my ($docuname,$docudom,$old,$new)=@_;
 1636:     my $home=&homeserver($docuname,$docudom);
 1637:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1638: 		  &escape("$new"),$home);
 1639: }
 1640: 
 1641: # ------------------------------------------------------------------------- Log
 1642: 
 1643: sub log {
 1644:     my ($dom,$nam,$hom,$what)=@_;
 1645:     return critical("log:$dom:$nam:$what",$hom);
 1646: }
 1647: 
 1648: # ------------------------------------------------------------------ Course Log
 1649: #
 1650: # This routine flushes several buffers of non-mission-critical nature
 1651: #
 1652: 
 1653: sub flushcourselogs {
 1654:     &logthis('Flushing log buffers');
 1655: #
 1656: # course logs
 1657: # This is a log of all transactions in a course, which can be used
 1658: # for data mining purposes
 1659: #
 1660: # It also collects the courseid database, which lists last transaction
 1661: # times and course titles for all courseids
 1662: #
 1663:     my %courseidbuffer=();
 1664:     foreach (keys %courselogs) {
 1665:         my $crsid=$_;
 1666:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1667: 		          &escape($courselogs{$crsid}),
 1668: 		          $coursehombuf{$crsid}) eq 'ok') {
 1669: 	    delete $courselogs{$crsid};
 1670:         } else {
 1671:             &logthis('Failed to flush log buffer for '.$crsid);
 1672:             if (length($courselogs{$crsid})>40000) {
 1673:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1674:                         " exceeded maximum size, deleting.</font>");
 1675:                delete $courselogs{$crsid};
 1676:             }
 1677:         }
 1678:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1679:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1680: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1681:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1682:         } else {
 1683:            $courseidbuffer{$coursehombuf{$crsid}}=
 1684: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1685:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1686:         }
 1687:     }
 1688: #
 1689: # Write course id database (reverse lookup) to homeserver of courses 
 1690: # Is used in pickcourse
 1691: #
 1692:     foreach (keys %courseidbuffer) {
 1693:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1694:     }
 1695: #
 1696: # File accesses
 1697: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1698: #
 1699:     foreach my $entry (keys(%accesshash)) {
 1700:         if ($entry =~ /___count$/) {
 1701:             my ($dom,$name);
 1702:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1703:             if (! defined($dom) || $dom eq '' || 
 1704:                 ! defined($name) || $name eq '') {
 1705:                 my $cid = $env{'request.course.id'};
 1706:                 $dom  = $env{'request.'.$cid.'.domain'};
 1707:                 $name = $env{'request.'.$cid.'.num'};
 1708:             }
 1709:             my $value = $accesshash{$entry};
 1710:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1711:             my %temphash=($url => $value);
 1712:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1713:             if ($result eq 'ok') {
 1714:                 delete $accesshash{$entry};
 1715:             } elsif ($result eq 'unknown_cmd') {
 1716:                 # Target server has old code running on it.
 1717:                 my %temphash=($entry => $value);
 1718:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1719:                     delete $accesshash{$entry};
 1720:                 }
 1721:             }
 1722:         } else {
 1723:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1724:             my %temphash=($entry => $accesshash{$entry});
 1725:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1726:                 delete $accesshash{$entry};
 1727:             }
 1728:         }
 1729:     }
 1730: #
 1731: # Roles
 1732: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1733: #
 1734:     foreach (keys %userrolehash) {
 1735:         my $entry=$_;
 1736:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1737: 	    split(/\:/,$entry);
 1738:         if (&Apache::lonnet::put('nohist_userroles',
 1739:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1740:                 $rudom,$runame) eq 'ok') {
 1741: 	    delete $userrolehash{$entry};
 1742:         }
 1743:     }
 1744: #
 1745: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1746: #
 1747:     my %domrolebuffer = ();
 1748:     foreach my $entry (keys %domainrolehash) {
 1749:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1750:         if ($domrolebuffer{$rudom}) {
 1751:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1752:                       '='.&escape($domainrolehash{$entry});
 1753:         } else {
 1754:             $domrolebuffer{$rudom}.=&escape($entry).
 1755:                       '='.&escape($domainrolehash{$entry});
 1756:         }
 1757:         delete $domainrolehash{$entry};
 1758:     }
 1759:     foreach my $dom (keys(%domrolebuffer)) {
 1760:         foreach my $tryserver (keys %libserv) {
 1761:             if ($hostdom{$tryserver} eq $dom) {
 1762:                 unless (&reply('domroleput:'.$dom.':'.
 1763:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1764:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1765:                 }
 1766:             }
 1767:         }
 1768:     }
 1769:     $dumpcount++;
 1770: }
 1771: 
 1772: sub courselog {
 1773:     my $what=shift;
 1774:     $what=time.':'.$what;
 1775:     unless ($env{'request.course.id'}) { return ''; }
 1776:     $coursedombuf{$env{'request.course.id'}}=
 1777:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1778:     $coursenumbuf{$env{'request.course.id'}}=
 1779:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1780:     $coursehombuf{$env{'request.course.id'}}=
 1781:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1782:     $coursedescrbuf{$env{'request.course.id'}}=
 1783:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1784:     $courseinstcodebuf{$env{'request.course.id'}}=
 1785:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1786:     $courseownerbuf{$env{'request.course.id'}}=
 1787:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1788:     $coursetypebuf{$env{'request.course.id'}}=
 1789:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1790:     if (defined $courselogs{$env{'request.course.id'}}) {
 1791: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1792:     } else {
 1793: 	$courselogs{$env{'request.course.id'}}.=$what;
 1794:     }
 1795:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1796: 	&flushcourselogs();
 1797:     }
 1798: }
 1799: 
 1800: sub courseacclog {
 1801:     my $fnsymb=shift;
 1802:     unless ($env{'request.course.id'}) { return ''; }
 1803:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1804:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1805:         $what.=':POST';
 1806:         # FIXME: Probably ought to escape things....
 1807: 	foreach (keys %env) {
 1808:             if ($_=~/^form\.(.*)/) {
 1809: 		$what.=':'.$1.'='.$env{$_};
 1810:             }
 1811:         }
 1812:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1813:         # FIXME: We should not be depending on a form parameter that someone
 1814:         # editing lonsearchcat.pm might change in the future.
 1815:         if ($env{'form.phase'} eq 'course_search') {
 1816:             $what.= ':POST';
 1817:             # FIXME: Probably ought to escape things....
 1818:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1819:                                  'crsdiscuss') {
 1820:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1821:             }
 1822:         }
 1823:     }
 1824:     &courselog($what);
 1825: }
 1826: 
 1827: sub countacc {
 1828:     my $url=&declutter(shift);
 1829:     return if (! defined($url) || $url eq '');
 1830:     unless ($env{'request.course.id'}) { return ''; }
 1831:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1832:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1833:     $accesshash{$key}++;
 1834: }
 1835: 
 1836: sub linklog {
 1837:     my ($from,$to)=@_;
 1838:     $from=&declutter($from);
 1839:     $to=&declutter($to);
 1840:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1841:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1842: }
 1843:   
 1844: sub userrolelog {
 1845:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1846:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1847:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1848:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1849:         ($trole=~/^ta/)) {
 1850:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1851:        $userrolehash
 1852:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1853:                     =$tend.':'.$tstart;
 1854:     }
 1855:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1856:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1857:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1858:         ($trole=~/^sc/)) {
 1859:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1860:        $domainrolehash
 1861:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1862:                     = $tend.':'.$tstart;
 1863:     }
 1864: }
 1865: 
 1866: sub get_course_adv_roles {
 1867:     my $cid=shift;
 1868:     $cid=$env{'request.course.id'} unless (defined($cid));
 1869:     my %coursehash=&coursedescription($cid);
 1870:     my %nothide=();
 1871:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1872: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1873:     }
 1874:     my %returnhash=();
 1875:     my %dumphash=
 1876:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1877:     my $now=time;
 1878:     foreach (keys %dumphash) {
 1879: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1880:         if (($tstart) && ($tstart<0)) { next; }
 1881:         if (($tend) && ($tend<$now)) { next; }
 1882:         if (($tstart) && ($now<$tstart)) { next; }
 1883:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1884: 	if ($username eq '' || $domain eq '') { next; }
 1885: 	if ((&privileged($username,$domain)) && 
 1886: 	    (!$nothide{$username.':'.$domain})) { next; }
 1887: 	if ($role eq 'cr') { next; }
 1888:         my $key=&plaintext($role);
 1889: 	if ($role =~ /^cr/) {
 1890: 	    $key=(split('/',$role))[3];
 1891: 	}
 1892:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1893:         if ($returnhash{$key}) {
 1894: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1895:         } else {
 1896:             $returnhash{$key}=$username.':'.$domain;
 1897:         }
 1898:      }
 1899:     return %returnhash;
 1900: }
 1901: 
 1902: sub get_my_roles {
 1903:     my ($uname,$udom)=@_;
 1904:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1905:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1906:     my %dumphash=
 1907:             &dump('nohist_userroles',$udom,$uname);
 1908:     my %returnhash=();
 1909:     my $now=time;
 1910:     foreach (keys %dumphash) {
 1911: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1912:         if (($tstart) && ($tstart<0)) { next; }
 1913:         if (($tend) && ($tend<$now)) { next; }
 1914:         if (($tstart) && ($now<$tstart)) { next; }
 1915:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1916: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1917:      }
 1918:     return %returnhash;
 1919: }
 1920: 
 1921: # ----------------------------------------------------- Frontpage Announcements
 1922: #
 1923: #
 1924: 
 1925: sub postannounce {
 1926:     my ($server,$text)=@_;
 1927:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1928:     unless ($text=~/\w/) { $text=''; }
 1929:     return &reply('setannounce:'.&escape($text),$server);
 1930: }
 1931: 
 1932: sub getannounce {
 1933: 
 1934:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1935: 	my $announcement='';
 1936: 	while (<$fh>) { $announcement .=$_; }
 1937: 	close($fh);
 1938: 	if ($announcement=~/\w/) { 
 1939: 	    return 
 1940:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1941:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1942: 	} else {
 1943: 	    return '';
 1944: 	}
 1945:     } else {
 1946: 	return '';
 1947:     }
 1948: }
 1949: 
 1950: # ---------------------------------------------------------- Course ID routines
 1951: # Deal with domain's nohist_courseid.db files
 1952: #
 1953: 
 1954: sub courseidput {
 1955:     my ($domain,$what,$coursehome)=@_;
 1956:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1957: }
 1958: 
 1959: sub courseiddump {
 1960:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter)=@_;
 1961:     my %returnhash=();
 1962:     unless ($domfilter) { $domfilter=''; }
 1963:     foreach my $tryserver (keys %libserv) {
 1964:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1965: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1966: 	        foreach (
 1967:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1968: 			       $sincefilter.':'.&escape($descfilter).':'.
 1969:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter),
 1970:                                $tryserver))) {
 1971: 		    my ($key,$value)=split(/\=/,$_);
 1972:                     if (($key) && ($value)) {
 1973: 		        $returnhash{&unescape($key)}=$value;
 1974:                     }
 1975:                 }
 1976:             }
 1977:         }
 1978:     }
 1979:     return %returnhash;
 1980: }
 1981: 
 1982: # ---------------------------------------------------------- DC e-mail
 1983: 
 1984: sub dcmailput {
 1985:     my ($domain,$msgid,$message,$server)=@_;
 1986:     my $status = &Apache::lonnet::critical(
 1987:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 1988:        &escape($message),$server);
 1989:     return $status;
 1990: }
 1991: 
 1992: sub dcmaildump {
 1993:     my ($dom,$startdate,$enddate,$senders) = @_;
 1994:     my %returnhash=();
 1995:     if (exists($domain_primary{$dom})) {
 1996:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 1997:                                                          &escape($enddate).':';
 1998: 	my @esc_senders=map { &escape($_)} @$senders;
 1999: 	$cmd.=&escape(join('&',@esc_senders));
 2000: 	foreach (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2001:             my ($key,$value) = split(/\=/,$_);
 2002:             if (($key) && ($value)) {
 2003:                 $returnhash{&unescape($key)} = &unescape($value);
 2004:             }
 2005:         }
 2006:     }
 2007:     return %returnhash;
 2008: }
 2009: # ---------------------------------------------------------- Domain roles
 2010: 
 2011: sub get_domain_roles {
 2012:     my ($dom,$roles,$startdate,$enddate)=@_;
 2013:     if (undef($startdate) || $startdate eq '') {
 2014:         $startdate = '.';
 2015:     }
 2016:     if (undef($enddate) || $enddate eq '') {
 2017:         $enddate = '.';
 2018:     }
 2019:     my $rolelist = join(':',@{$roles});
 2020:     my %personnel = ();
 2021:     foreach my $tryserver (keys(%libserv)) {
 2022:         if ($hostdom{$tryserver} eq $dom) {
 2023:             %{$personnel{$tryserver}}=();
 2024:             foreach (
 2025:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2026:                    &escape($startdate).':'.&escape($enddate).':'.
 2027:                    &escape($rolelist), $tryserver))) {
 2028:                 my($key,$value) = split(/\=/,$_);
 2029:                 if (($key) && ($value)) {
 2030:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2031:                 }
 2032:             }
 2033:         }
 2034:     }
 2035:     return %personnel;
 2036: }
 2037: 
 2038: # ----------------------------------------------------------- Check out an item
 2039: 
 2040: sub get_first_access {
 2041:     my ($type,$argsymb)=@_;
 2042:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2043:     if ($argsymb) { $symb=$argsymb; }
 2044:     my ($map,$id,$res)=&decode_symb($symb);
 2045:     if ($type eq 'map') {
 2046: 	$res=&symbread($map);
 2047:     } else {
 2048: 	$res=$symb;
 2049:     }
 2050:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2051:     return $times{"$courseid\0$res"};
 2052: }
 2053: 
 2054: sub set_first_access {
 2055:     my ($type)=@_;
 2056:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 2057:     my ($map,$id,$res)=&decode_symb($symb);
 2058:     if ($type eq 'map') {
 2059: 	$res=&symbread($map);
 2060:     } else {
 2061: 	$res=$symb;
 2062:     }
 2063:     my $firstaccess=&get_first_access($type,$symb);
 2064:     if (!$firstaccess) {
 2065: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2066:     }
 2067:     return 'already_set';
 2068: }
 2069: 
 2070: sub checkout {
 2071:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2072:     my $now=time;
 2073:     my $lonhost=$perlvar{'lonHostID'};
 2074:     my $infostr=&escape(
 2075:                  'CHECKOUTTOKEN&'.
 2076:                  $tuname.'&'.
 2077:                  $tudom.'&'.
 2078:                  $tcrsid.'&'.
 2079:                  $symb.'&'.
 2080: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2081:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2082:     if ($token=~/^error\:/) { 
 2083:         &logthis("<font color=\"blue\">WARNING: ".
 2084:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2085:                  "</font>");
 2086:         return ''; 
 2087:     }
 2088: 
 2089:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2090:     $token=~tr/a-z/A-Z/;
 2091: 
 2092:     my %infohash=('resource.0.outtoken' => $token,
 2093:                   'resource.0.checkouttime' => $now,
 2094:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2095: 
 2096:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2097:        return '';
 2098:     } else {
 2099:         &logthis("<font color=\"blue\">WARNING: ".
 2100:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2101:                  "</font>");
 2102:     }    
 2103: 
 2104:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2105:                          &escape('Checkout '.$infostr.' - '.
 2106:                                                  $token)) ne 'ok') {
 2107: 	return '';
 2108:     } else {
 2109:         &logthis("<font color=\"blue\">WARNING: ".
 2110:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2111:                  "</font>");
 2112:     }
 2113:     return $token;
 2114: }
 2115: 
 2116: # ------------------------------------------------------------ Check in an item
 2117: 
 2118: sub checkin {
 2119:     my $token=shift;
 2120:     my $now=time;
 2121:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2122:     $lonhost=~tr/A-Z/a-z/;
 2123:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2124:     $dtoken=~s/\W/\_/g;
 2125:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2126:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2127: 
 2128:     unless (($tuname) && ($tudom)) {
 2129:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2130:         return '';
 2131:     }
 2132:     
 2133:     unless (&allowed('mgr',$tcrsid)) {
 2134:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2135:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2136:         return '';
 2137:     }
 2138: 
 2139:     my %infohash=('resource.0.intoken' => $token,
 2140:                   'resource.0.checkintime' => $now,
 2141:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2142: 
 2143:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2144:        return '';
 2145:     }    
 2146: 
 2147:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2148:                          &escape('Checkin - '.$token)) ne 'ok') {
 2149: 	return '';
 2150:     }
 2151: 
 2152:     return ($symb,$tuname,$tudom,$tcrsid);    
 2153: }
 2154: 
 2155: # --------------------------------------------- Set Expire Date for Spreadsheet
 2156: 
 2157: sub expirespread {
 2158:     my ($uname,$udom,$stype,$usymb)=@_;
 2159:     my $cid=$env{'request.course.id'}; 
 2160:     if ($cid) {
 2161:        my $now=time;
 2162:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2163:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2164:                             $env{'course.'.$cid.'.num'}.
 2165: 	        	    ':nohist_expirationdates:'.
 2166:                             &escape($key).'='.$now,
 2167:                             $env{'course.'.$cid.'.home'})
 2168:     }
 2169:     return 'ok';
 2170: }
 2171: 
 2172: # ----------------------------------------------------- Devalidate Spreadsheets
 2173: 
 2174: sub devalidate {
 2175:     my ($symb,$uname,$udom)=@_;
 2176:     my $cid=$env{'request.course.id'}; 
 2177:     if ($cid) {
 2178:         # delete the stored spreadsheets for
 2179:         # - the student level sheet of this user in course's homespace
 2180:         # - the assessment level sheet for this resource 
 2181:         #   for this user in user's homespace
 2182: 	# - current conditional state info
 2183: 	my $key=$uname.':'.$udom.':';
 2184:         my $status=
 2185: 	    &del('nohist_calculatedsheets',
 2186: 		 [$key.'studentcalc:'],
 2187: 		 $env{'course.'.$cid.'.domain'},
 2188: 		 $env{'course.'.$cid.'.num'})
 2189: 		.' '.
 2190: 	    &del('nohist_calculatedsheets_'.$cid,
 2191: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2192:         unless ($status eq 'ok ok') {
 2193:            &logthis('Could not devalidate spreadsheet '.
 2194:                     $uname.' at '.$udom.' for '.
 2195: 		    $symb.': '.$status);
 2196:         }
 2197: 	&delenv('user.state.'.$cid);
 2198:     }
 2199: }
 2200: 
 2201: sub get_scalar {
 2202:     my ($string,$end) = @_;
 2203:     my $value;
 2204:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2205: 	$value = $1;
 2206:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2207: 	$value = $1;
 2208:     }
 2209:     return &unescape($value);
 2210: }
 2211: 
 2212: sub array2str {
 2213:   my (@array) = @_;
 2214:   my $result=&arrayref2str(\@array);
 2215:   $result=~s/^__ARRAY_REF__//;
 2216:   $result=~s/__END_ARRAY_REF__$//;
 2217:   return $result;
 2218: }
 2219: 
 2220: sub arrayref2str {
 2221:   my ($arrayref) = @_;
 2222:   my $result='__ARRAY_REF__';
 2223:   foreach my $elem (@$arrayref) {
 2224:     if(ref($elem) eq 'ARRAY') {
 2225:       $result.=&arrayref2str($elem).'&';
 2226:     } elsif(ref($elem) eq 'HASH') {
 2227:       $result.=&hashref2str($elem).'&';
 2228:     } elsif(ref($elem)) {
 2229:       #print("Got a ref of ".(ref($elem))." skipping.");
 2230:     } else {
 2231:       $result.=&escape($elem).'&';
 2232:     }
 2233:   }
 2234:   $result=~s/\&$//;
 2235:   $result .= '__END_ARRAY_REF__';
 2236:   return $result;
 2237: }
 2238: 
 2239: sub hash2str {
 2240:   my (%hash) = @_;
 2241:   my $result=&hashref2str(\%hash);
 2242:   $result=~s/^__HASH_REF__//;
 2243:   $result=~s/__END_HASH_REF__$//;
 2244:   return $result;
 2245: }
 2246: 
 2247: sub hashref2str {
 2248:   my ($hashref)=@_;
 2249:   my $result='__HASH_REF__';
 2250:   foreach (sort(keys(%$hashref))) {
 2251:     if (ref($_) eq 'ARRAY') {
 2252:       $result.=&arrayref2str($_).'=';
 2253:     } elsif (ref($_) eq 'HASH') {
 2254:       $result.=&hashref2str($_).'=';
 2255:     } elsif (ref($_)) {
 2256:       $result.='=';
 2257:       #print("Got a ref of ".(ref($_))." skipping.");
 2258:     } else {
 2259: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2260:     }
 2261: 
 2262:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2263:       $result.=&arrayref2str($hashref->{$_}).'&';
 2264:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2265:       $result.=&hashref2str($hashref->{$_}).'&';
 2266:     } elsif(ref($hashref->{$_})) {
 2267:        $result.='&';
 2268:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2269:     } else {
 2270:       $result.=&escape($hashref->{$_}).'&';
 2271:     }
 2272:   }
 2273:   $result=~s/\&$//;
 2274:   $result .= '__END_HASH_REF__';
 2275:   return $result;
 2276: }
 2277: 
 2278: sub str2hash {
 2279:     my ($string)=@_;
 2280:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2281:     return %$hash;
 2282: }
 2283: 
 2284: sub str2hashref {
 2285:   my ($string) = @_;
 2286: 
 2287:   my %hash;
 2288: 
 2289:   if($string !~ /^__HASH_REF__/) {
 2290:       if (! ($string eq '' || !defined($string))) {
 2291: 	  $hash{'error'}='Not hash reference';
 2292:       }
 2293:       return (\%hash, $string);
 2294:   }
 2295: 
 2296:   $string =~ s/^__HASH_REF__//;
 2297: 
 2298:   while($string !~ /^__END_HASH_REF__/) {
 2299:       #key
 2300:       my $key='';
 2301:       if($string =~ /^__HASH_REF__/) {
 2302:           ($key, $string)=&str2hashref($string);
 2303:           if(defined($key->{'error'})) {
 2304:               $hash{'error'}='Bad data';
 2305:               return (\%hash, $string);
 2306:           }
 2307:       } elsif($string =~ /^__ARRAY_REF__/) {
 2308:           ($key, $string)=&str2arrayref($string);
 2309:           if($key->[0] eq 'Array reference error') {
 2310:               $hash{'error'}='Bad data';
 2311:               return (\%hash, $string);
 2312:           }
 2313:       } else {
 2314:           $string =~ s/^(.*?)=//;
 2315: 	  $key=&unescape($1);
 2316:       }
 2317:       $string =~ s/^=//;
 2318: 
 2319:       #value
 2320:       my $value='';
 2321:       if($string =~ /^__HASH_REF__/) {
 2322:           ($value, $string)=&str2hashref($string);
 2323:           if(defined($value->{'error'})) {
 2324:               $hash{'error'}='Bad data';
 2325:               return (\%hash, $string);
 2326:           }
 2327:       } elsif($string =~ /^__ARRAY_REF__/) {
 2328:           ($value, $string)=&str2arrayref($string);
 2329:           if($value->[0] eq 'Array reference error') {
 2330:               $hash{'error'}='Bad data';
 2331:               return (\%hash, $string);
 2332:           }
 2333:       } else {
 2334: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2335:       }
 2336:       $string =~ s/^&//;
 2337: 
 2338:       $hash{$key}=$value;
 2339:   }
 2340: 
 2341:   $string =~ s/^__END_HASH_REF__//;
 2342: 
 2343:   return (\%hash, $string);
 2344: }
 2345: 
 2346: sub str2array {
 2347:     my ($string)=@_;
 2348:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2349:     return @$array;
 2350: }
 2351: 
 2352: sub str2arrayref {
 2353:   my ($string) = @_;
 2354:   my @array;
 2355: 
 2356:   if($string !~ /^__ARRAY_REF__/) {
 2357:       if (! ($string eq '' || !defined($string))) {
 2358: 	  $array[0]='Array reference error';
 2359:       }
 2360:       return (\@array, $string);
 2361:   }
 2362: 
 2363:   $string =~ s/^__ARRAY_REF__//;
 2364: 
 2365:   while($string !~ /^__END_ARRAY_REF__/) {
 2366:       my $value='';
 2367:       if($string =~ /^__HASH_REF__/) {
 2368:           ($value, $string)=&str2hashref($string);
 2369:           if(defined($value->{'error'})) {
 2370:               $array[0] ='Array reference error';
 2371:               return (\@array, $string);
 2372:           }
 2373:       } elsif($string =~ /^__ARRAY_REF__/) {
 2374:           ($value, $string)=&str2arrayref($string);
 2375:           if($value->[0] eq 'Array reference error') {
 2376:               $array[0] ='Array reference error';
 2377:               return (\@array, $string);
 2378:           }
 2379:       } else {
 2380: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2381:       }
 2382:       $string =~ s/^&//;
 2383: 
 2384:       push(@array, $value);
 2385:   }
 2386: 
 2387:   $string =~ s/^__END_ARRAY_REF__//;
 2388: 
 2389:   return (\@array, $string);
 2390: }
 2391: 
 2392: # -------------------------------------------------------------------Temp Store
 2393: 
 2394: sub tmpreset {
 2395:   my ($symb,$namespace,$domain,$stuname) = @_;
 2396:   if (!$symb) {
 2397:     $symb=&symbread();
 2398:     if (!$symb) { $symb= $env{'request.url'}; }
 2399:   }
 2400:   $symb=escape($symb);
 2401: 
 2402:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2403:   $namespace=~s/\//\_/g;
 2404:   $namespace=~s/\W//g;
 2405: 
 2406:   if (!$domain) { $domain=$env{'user.domain'}; }
 2407:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2408:   if ($domain eq 'public' && $stuname eq 'public') {
 2409:       $stuname=$ENV{'REMOTE_ADDR'};
 2410:   }
 2411:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2412:   my %hash;
 2413:   if (tie(%hash,'GDBM_File',
 2414: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2415: 	  &GDBM_WRCREAT(),0640)) {
 2416:     foreach my $key (keys %hash) {
 2417:       if ($key=~ /:$symb/) {
 2418: 	delete($hash{$key});
 2419:       }
 2420:     }
 2421:   }
 2422: }
 2423: 
 2424: sub tmpstore {
 2425:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2426: 
 2427:   if (!$symb) {
 2428:     $symb=&symbread();
 2429:     if (!$symb) { $symb= $env{'request.url'}; }
 2430:   }
 2431:   $symb=escape($symb);
 2432: 
 2433:   if (!$namespace) {
 2434:     # I don't think we would ever want to store this for a course.
 2435:     # it seems this will only be used if we don't have a course.
 2436:     #$namespace=$env{'request.course.id'};
 2437:     #if (!$namespace) {
 2438:       $namespace=$env{'request.state'};
 2439:     #}
 2440:   }
 2441:   $namespace=~s/\//\_/g;
 2442:   $namespace=~s/\W//g;
 2443:   if (!$domain) { $domain=$env{'user.domain'}; }
 2444:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2445:   if ($domain eq 'public' && $stuname eq 'public') {
 2446:       $stuname=$ENV{'REMOTE_ADDR'};
 2447:   }
 2448:   my $now=time;
 2449:   my %hash;
 2450:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2451:   if (tie(%hash,'GDBM_File',
 2452: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2453: 	  &GDBM_WRCREAT(),0640)) {
 2454:     $hash{"version:$symb"}++;
 2455:     my $version=$hash{"version:$symb"};
 2456:     my $allkeys=''; 
 2457:     foreach my $key (keys(%$storehash)) {
 2458:       $allkeys.=$key.':';
 2459:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2460:     }
 2461:     $hash{"$version:$symb:timestamp"}=$now;
 2462:     $allkeys.='timestamp';
 2463:     $hash{"$version:keys:$symb"}=$allkeys;
 2464:     if (untie(%hash)) {
 2465:       return 'ok';
 2466:     } else {
 2467:       return "error:$!";
 2468:     }
 2469:   } else {
 2470:     return "error:$!";
 2471:   }
 2472: }
 2473: 
 2474: # -----------------------------------------------------------------Temp Restore
 2475: 
 2476: sub tmprestore {
 2477:   my ($symb,$namespace,$domain,$stuname) = @_;
 2478: 
 2479:   if (!$symb) {
 2480:     $symb=&symbread();
 2481:     if (!$symb) { $symb= $env{'request.url'}; }
 2482:   }
 2483:   $symb=escape($symb);
 2484: 
 2485:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2486: 
 2487:   if (!$domain) { $domain=$env{'user.domain'}; }
 2488:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2489:   if ($domain eq 'public' && $stuname eq 'public') {
 2490:       $stuname=$ENV{'REMOTE_ADDR'};
 2491:   }
 2492:   my %returnhash;
 2493:   $namespace=~s/\//\_/g;
 2494:   $namespace=~s/\W//g;
 2495:   my %hash;
 2496:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2497:   if (tie(%hash,'GDBM_File',
 2498: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2499: 	  &GDBM_READER(),0640)) {
 2500:     my $version=$hash{"version:$symb"};
 2501:     $returnhash{'version'}=$version;
 2502:     my $scope;
 2503:     for ($scope=1;$scope<=$version;$scope++) {
 2504:       my $vkeys=$hash{"$scope:keys:$symb"};
 2505:       my @keys=split(/:/,$vkeys);
 2506:       my $key;
 2507:       $returnhash{"$scope:keys"}=$vkeys;
 2508:       foreach $key (@keys) {
 2509: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2510: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2511:       }
 2512:     }
 2513:     if (!(untie(%hash))) {
 2514:       return "error:$!";
 2515:     }
 2516:   } else {
 2517:     return "error:$!";
 2518:   }
 2519:   return %returnhash;
 2520: }
 2521: 
 2522: # ----------------------------------------------------------------------- Store
 2523: 
 2524: sub store {
 2525:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2526:     my $home='';
 2527: 
 2528:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2529: 
 2530:     $symb=&symbclean($symb);
 2531:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2532: 
 2533:     if (!$domain) { $domain=$env{'user.domain'}; }
 2534:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2535: 
 2536:     &devalidate($symb,$stuname,$domain);
 2537: 
 2538:     $symb=escape($symb);
 2539:     if (!$namespace) { 
 2540:        unless ($namespace=$env{'request.course.id'}) { 
 2541:           return ''; 
 2542:        } 
 2543:     }
 2544:     if (!$home) { $home=$env{'user.home'}; }
 2545: 
 2546:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2547:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2548: 
 2549:     my $namevalue='';
 2550:     foreach (keys %$storehash) {
 2551:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2552:     }
 2553:     $namevalue=~s/\&$//;
 2554:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2555:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2556: }
 2557: 
 2558: # -------------------------------------------------------------- Critical Store
 2559: 
 2560: sub cstore {
 2561:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2562:     my $home='';
 2563: 
 2564:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2565: 
 2566:     $symb=&symbclean($symb);
 2567:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2568: 
 2569:     if (!$domain) { $domain=$env{'user.domain'}; }
 2570:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2571: 
 2572:     &devalidate($symb,$stuname,$domain);
 2573: 
 2574:     $symb=escape($symb);
 2575:     if (!$namespace) { 
 2576:        unless ($namespace=$env{'request.course.id'}) { 
 2577:           return ''; 
 2578:        } 
 2579:     }
 2580:     if (!$home) { $home=$env{'user.home'}; }
 2581: 
 2582:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2583:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2584: 
 2585:     my $namevalue='';
 2586:     foreach (keys %$storehash) {
 2587:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2588:     }
 2589:     $namevalue=~s/\&$//;
 2590:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2591:     return critical
 2592:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2593: }
 2594: 
 2595: # --------------------------------------------------------------------- Restore
 2596: 
 2597: sub restore {
 2598:     my ($symb,$namespace,$domain,$stuname) = @_;
 2599:     my $home='';
 2600: 
 2601:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2602: 
 2603:     if (!$symb) {
 2604:       unless ($symb=escape(&symbread())) { return ''; }
 2605:     } else {
 2606:       $symb=&escape(&symbclean($symb));
 2607:     }
 2608:     if (!$namespace) { 
 2609:        unless ($namespace=$env{'request.course.id'}) { 
 2610:           return ''; 
 2611:        } 
 2612:     }
 2613:     if (!$domain) { $domain=$env{'user.domain'}; }
 2614:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2615:     if (!$home) { $home=$env{'user.home'}; }
 2616:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2617: 
 2618:     my %returnhash=();
 2619:     foreach (split(/\&/,$answer)) {
 2620: 	my ($name,$value)=split(/\=/,$_);
 2621:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2622:     }
 2623:     my $version;
 2624:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2625:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2626:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2627:        }
 2628:     }
 2629:     return %returnhash;
 2630: }
 2631: 
 2632: # ---------------------------------------------------------- Course Description
 2633: 
 2634: sub coursedescription {
 2635:     my ($courseid,$args)=@_;
 2636:     $courseid=~s/^\///;
 2637:     $courseid=~s/\_/\//g;
 2638:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2639:     my $chome=&homeserver($cnum,$cdomain);
 2640:     my $normalid=$cdomain.'_'.$cnum;
 2641:     # need to always cache even if we get errors otherwise we keep 
 2642:     # trying and trying and trying to get the course description.
 2643:     my %envhash=();
 2644:     my %returnhash=();
 2645:     
 2646:     my $expiretime=600;
 2647:     if ($env{'request.course.id'} eq $normalid) {
 2648: 	$expiretime=120;
 2649:     }
 2650: 
 2651:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2652:     if (!$args->{'freshen_cache'}
 2653: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2654: 	foreach my $key (keys(%env)) {
 2655: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2656: 	    my ($setting) = $1;
 2657: 	    $returnhash{$setting} = $env{$key};
 2658: 	}
 2659: 	return %returnhash;
 2660:     }
 2661: 
 2662:     # get the data agin
 2663:     if (!$args->{'one_time'}) {
 2664: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2665:     }
 2666:     if ($chome ne 'no_host') {
 2667:        %returnhash=&dump('environment',$cdomain,$cnum);
 2668:        if (!exists($returnhash{'con_lost'})) {
 2669:            $returnhash{'home'}= $chome;
 2670: 	   $returnhash{'domain'} = $cdomain;
 2671: 	   $returnhash{'num'} = $cnum;
 2672:            if (!defined($returnhash{'type'})) {
 2673:                $returnhash{'type'} = 'Course';
 2674:            }
 2675:            while (my ($name,$value) = each %returnhash) {
 2676:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2677:            }
 2678:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2679:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2680: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2681:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2682:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2683:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2684:        }
 2685:     }
 2686:     if (!$args->{'one_time'}) {
 2687: 	&appenv(%envhash);
 2688:     }
 2689:     return %returnhash;
 2690: }
 2691: 
 2692: # -------------------------------------------------See if a user is privileged
 2693: 
 2694: sub privileged {
 2695:     my ($username,$domain)=@_;
 2696:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2697: 			&homeserver($username,$domain));
 2698:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2699:     my $now=time;
 2700:     if ($rolesdump ne '') {
 2701:         foreach (split(/&/,$rolesdump)) {
 2702: 	    if ($_!~/^rolesdef_/) {
 2703: 		my ($area,$role)=split(/=/,$_);
 2704: 		$area=~s/\_\w\w$//;
 2705: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2706: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2707: 		    my $active=1;
 2708: 		    if ($tend) {
 2709: 			if ($tend<$now) { $active=0; }
 2710: 		    }
 2711: 		    if ($tstart) {
 2712: 			if ($tstart>$now) { $active=0; }
 2713: 		    }
 2714: 		    if ($active) { return 1; }
 2715: 		}
 2716: 	    }
 2717: 	}
 2718:     }
 2719:     return 0;
 2720: }
 2721: 
 2722: # -------------------------------------------------------- Get user privileges
 2723: 
 2724: sub rolesinit {
 2725:     my ($domain,$username,$authhost)=@_;
 2726:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2727:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2728:     my %allroles=();
 2729:     my %allgroups=();   
 2730:     my $now=time;
 2731:     my %userroles = ('user.login.time' => $now);
 2732:     my $group_privs;
 2733: 
 2734:     if ($rolesdump ne '') {
 2735:         foreach (split(/&/,$rolesdump)) {
 2736: 	  if ($_!~/^rolesdef_/) {
 2737:             my ($area,$role)=split(/=/,$_);
 2738: 	    $area=~s/\_\w\w$//;
 2739:             my ($trole,$tend,$tstart,$group_privs);
 2740: 	    if ($role=~/^cr/) { 
 2741: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2742: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2743: 		    ($tend,$tstart)=split('_',$trest);
 2744: 		} else {
 2745: 		    $trole=$role;
 2746: 		}
 2747:             } elsif ($role =~ m|^gr/|) {
 2748:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2749:                 ($trole,$group_privs) = split(/\//,$trole);
 2750:                 $group_privs = &unescape($group_privs);
 2751: 	    } else {
 2752: 		($trole,$tend,$tstart)=split(/_/,$role);
 2753: 	    }
 2754: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2755: 					 $username);
 2756: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2757:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2758:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2759:             if (($area ne '') && ($trole ne '')) {
 2760: 		my $spec=$trole.'.'.$area;
 2761: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2762: 		if ($trole =~ /^cr\//) {
 2763:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2764:                 } elsif ($trole eq 'gr') {
 2765:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2766: 		} else {
 2767:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2768: 		}
 2769:             }
 2770:           }
 2771:         }
 2772:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2773:         $userroles{'user.adv'}    = $adv;
 2774: 	$userroles{'user.author'} = $author;
 2775:         $env{'user.adv'}=$adv;
 2776:     }
 2777:     return \%userroles;  
 2778: }
 2779: 
 2780: sub set_arearole {
 2781:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2782: # log the associated role with the area
 2783:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2784:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2785: }
 2786: 
 2787: sub custom_roleprivs {
 2788:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2789:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2790:     my $homsvr=homeserver($rauthor,$rdomain);
 2791:     if ($hostname{$homsvr} ne '') {
 2792:         my ($rdummy,$roledef)=
 2793:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2794:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2795:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2796:             if (defined($syspriv)) {
 2797:                 $$allroles{'cm./'}.=':'.$syspriv;
 2798:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2799:             }
 2800:             if ($tdomain ne '') {
 2801:                 if (defined($dompriv)) {
 2802:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2803:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2804:                 }
 2805:                 if (($trest ne '') && (defined($coursepriv))) {
 2806:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2807:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2808:                 }
 2809:             }
 2810:         }
 2811:     }
 2812: }
 2813: 
 2814: sub group_roleprivs {
 2815:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2816:     my $access = 1;
 2817:     my $now = time;
 2818:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2819:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2820:     if ($access) {
 2821:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2822:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2823:     }
 2824: }
 2825: 
 2826: sub standard_roleprivs {
 2827:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2828:     if (defined($pr{$trole.':s'})) {
 2829:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2830:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2831:     }
 2832:     if ($tdomain ne '') {
 2833:         if (defined($pr{$trole.':d'})) {
 2834:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2835:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2836:         }
 2837:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2838:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2839:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2840:         }
 2841:     }
 2842: }
 2843: 
 2844: sub set_userprivs {
 2845:     my ($userroles,$allroles,$allgroups) = @_; 
 2846:     my $author=0;
 2847:     my $adv=0;
 2848:     my %grouproles = ();
 2849:     if (keys(%{$allgroups}) > 0) {
 2850:         foreach my $role (keys %{$allroles}) {
 2851:             my ($trole,$area,$sec,$extendedarea);
 2852:             if ($role =~ m|^(\w+)\.(/\w+/\w+)(/?\w*)|) {
 2853:                 $trole = $1;
 2854:                 $area = $2;
 2855:                 $sec = $3;
 2856:                 $extendedarea = $area.$sec;
 2857:                 if (exists($$allgroups{$area})) {
 2858:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2859:                         my $spec = $trole.'.'.$extendedarea;
 2860:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2861:                                                 $$allgroups{$area}{$group};
 2862:                     }
 2863:                 }
 2864:             }
 2865:         }
 2866:     }
 2867:     foreach (keys(%grouproles)) {
 2868:         $$allroles{$_} = $grouproles{$_};
 2869:     }
 2870:     foreach (keys %{$allroles}) {
 2871:         my %thesepriv=();
 2872:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2873:         foreach (split(/:/,$$allroles{$_})) {
 2874:             if ($_ ne '') {
 2875:                 my ($privilege,$restrictions)=split(/&/,$_);
 2876:                 if ($restrictions eq '') {
 2877:                     $thesepriv{$privilege}='F';
 2878:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2879:                     $thesepriv{$privilege}.=$restrictions;
 2880:                 }
 2881:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2882:             }
 2883:         }
 2884:         my $thesestr='';
 2885:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2886:         $userroles->{'user.priv.'.$_} = $thesestr;
 2887:     }
 2888:     return ($author,$adv);
 2889: }
 2890: 
 2891: # --------------------------------------------------------------- get interface
 2892: 
 2893: sub get {
 2894:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2895:    my $items='';
 2896:    foreach (@$storearr) {
 2897:        $items.=escape($_).'&';
 2898:    }
 2899:    $items=~s/\&$//;
 2900:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2901:    if (!$uname) { $uname=$env{'user.name'}; }
 2902:    my $uhome=&homeserver($uname,$udomain);
 2903: 
 2904:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2905:    my @pairs=split(/\&/,$rep);
 2906:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2907:      return @pairs;
 2908:    }
 2909:    my %returnhash=();
 2910:    my $i=0;
 2911:    foreach (@$storearr) {
 2912:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2913:       $i++;
 2914:    }
 2915:    return %returnhash;
 2916: }
 2917: 
 2918: # --------------------------------------------------------------- del interface
 2919: 
 2920: sub del {
 2921:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2922:    my $items='';
 2923:    foreach (@$storearr) {
 2924:        $items.=escape($_).'&';
 2925:    }
 2926:    $items=~s/\&$//;
 2927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2928:    if (!$uname) { $uname=$env{'user.name'}; }
 2929:    my $uhome=&homeserver($uname,$udomain);
 2930: 
 2931:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2932: }
 2933: 
 2934: # -------------------------------------------------------------- dump interface
 2935: 
 2936: sub dump {
 2937:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2938:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2939:     if (!$uname) { $uname=$env{'user.name'}; }
 2940:     my $uhome=&homeserver($uname,$udomain);
 2941:     if ($regexp) {
 2942: 	$regexp=&escape($regexp);
 2943:     } else {
 2944: 	$regexp='.';
 2945:     }
 2946:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2947:     my @pairs=split(/\&/,$rep);
 2948:     my %returnhash=();
 2949:     foreach my $item (@pairs) {
 2950: 	my ($key,$value)=split(/=/,$item,2);
 2951: 	$key = &unescape($key);
 2952: 	next if ($key =~ /^error: 2 /);
 2953: 	$returnhash{$key}=&thaw_unescape($value);
 2954:     }
 2955:     return %returnhash;
 2956: }
 2957: 
 2958: # --------------------------------------------------------- dumpstore interface
 2959: 
 2960: sub dumpstore {
 2961:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2962:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2963: }
 2964: 
 2965: # -------------------------------------------------------------- keys interface
 2966: 
 2967: sub getkeys {
 2968:    my ($namespace,$udomain,$uname)=@_;
 2969:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2970:    if (!$uname) { $uname=$env{'user.name'}; }
 2971:    my $uhome=&homeserver($uname,$udomain);
 2972:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2973:    my @keyarray=();
 2974:    foreach (split(/\&/,$rep)) {
 2975:       push (@keyarray,&unescape($_));
 2976:    }
 2977:    return @keyarray;
 2978: }
 2979: 
 2980: # --------------------------------------------------------------- currentdump
 2981: sub currentdump {
 2982:    my ($courseid,$sdom,$sname)=@_;
 2983:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2984:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2985:    $sname    = $env{'user.name'}         if (! defined($sname));
 2986:    my $uhome = &homeserver($sname,$sdom);
 2987:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2988:    return if ($rep =~ /^(error:|no_such_host)/);
 2989:    #
 2990:    my %returnhash=();
 2991:    #
 2992:    if ($rep eq "unknown_cmd") { 
 2993:        # an old lond will not know currentdump
 2994:        # Do a dump and make it look like a currentdump
 2995:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2996:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2997:        my %hash = @tmp;
 2998:        @tmp=();
 2999:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3000:    } else {
 3001:        my @pairs=split(/\&/,$rep);
 3002:        foreach (@pairs) {
 3003:            my ($key,$value)=split(/=/,$_);
 3004:            my ($symb,$param) = split(/:/,$key);
 3005:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3006:                                                         &thaw_unescape($value);
 3007:        }
 3008:    }
 3009:    return %returnhash;
 3010: }
 3011: 
 3012: sub convert_dump_to_currentdump{
 3013:     my %hash = %{shift()};
 3014:     my %returnhash;
 3015:     # Code ripped from lond, essentially.  The only difference
 3016:     # here is the unescaping done by lonnet::dump().  Conceivably
 3017:     # we might run in to problems with parameter names =~ /^v\./
 3018:     while (my ($key,$value) = each(%hash)) {
 3019:         my ($v,$symb,$param) = split(/:/,$key);
 3020:         next if ($v eq 'version' || $symb eq 'keys');
 3021:         next if (exists($returnhash{$symb}) &&
 3022:                  exists($returnhash{$symb}->{$param}) &&
 3023:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3024:         $returnhash{$symb}->{$param}=$value;
 3025:         $returnhash{$symb}->{'v.'.$param}=$v;
 3026:     }
 3027:     #
 3028:     # Remove all of the keys in the hashes which keep track of
 3029:     # the version of the parameter.
 3030:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3031:         # use a foreach because we are going to delete from the hash.
 3032:         foreach my $key (keys(%$param_hash)) {
 3033:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3034:         }
 3035:     }
 3036:     return \%returnhash;
 3037: }
 3038: 
 3039: # ------------------------------------------------------ critical inc interface
 3040: 
 3041: sub cinc {
 3042:     return &inc(@_,'critical');
 3043: }
 3044: 
 3045: # --------------------------------------------------------------- inc interface
 3046: 
 3047: sub inc {
 3048:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3049:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3050:     if (!$uname) { $uname=$env{'user.name'}; }
 3051:     my $uhome=&homeserver($uname,$udomain);
 3052:     my $items='';
 3053:     if (! ref($store)) {
 3054:         # got a single value, so use that instead
 3055:         $items = &escape($store).'=&';
 3056:     } elsif (ref($store) eq 'SCALAR') {
 3057:         $items = &escape($$store).'=&';        
 3058:     } elsif (ref($store) eq 'ARRAY') {
 3059:         $items = join('=&',map {&escape($_);} @{$store});
 3060:     } elsif (ref($store) eq 'HASH') {
 3061:         while (my($key,$value) = each(%{$store})) {
 3062:             $items.= &escape($key).'='.&escape($value).'&';
 3063:         }
 3064:     }
 3065:     $items=~s/\&$//;
 3066:     if ($critical) {
 3067: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3068:     } else {
 3069: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3070:     }
 3071: }
 3072: 
 3073: # --------------------------------------------------------------- put interface
 3074: 
 3075: sub put {
 3076:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3077:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3078:    if (!$uname) { $uname=$env{'user.name'}; }
 3079:    my $uhome=&homeserver($uname,$udomain);
 3080:    my $items='';
 3081:    foreach (keys %$storehash) {
 3082:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3083:    }
 3084:    $items=~s/\&$//;
 3085:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3086: }
 3087: 
 3088: # ------------------------------------------------------------ newput interface
 3089: 
 3090: sub newput {
 3091:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3092:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3093:    if (!$uname) { $uname=$env{'user.name'}; }
 3094:    my $uhome=&homeserver($uname,$udomain);
 3095:    my $items='';
 3096:    foreach my $key (keys(%$storehash)) {
 3097:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3098:    }
 3099:    $items=~s/\&$//;
 3100:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3101: }
 3102: 
 3103: # ---------------------------------------------------------  putstore interface
 3104: 
 3105: sub putstore {
 3106:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3107:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3108:    if (!$uname) { $uname=$env{'user.name'}; }
 3109:    my $uhome=&homeserver($uname,$udomain);
 3110:    my $items='';
 3111:    foreach my $key (keys(%$storehash)) {
 3112:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3113:    }
 3114:    $items=~s/\&$//;
 3115:    my $esc_symb=&escape($symb);
 3116:    my $esc_v=&escape($version);
 3117:    my $reply =
 3118:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3119: 	      $uhome);
 3120:    if ($reply eq 'unknown_cmd') {
 3121:        # gfall back to way things use to be done
 3122:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3123: 			    $uname);
 3124:    }
 3125:    return $reply;
 3126: }
 3127: 
 3128: sub old_putstore {
 3129:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3130:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3131:     if (!$uname) { $uname=$env{'user.name'}; }
 3132:     my $uhome=&homeserver($uname,$udomain);
 3133:     my %newstorehash;
 3134:     foreach (keys %$storehash) {
 3135: 	my $key = $version.':'.&escape($symb).':'.$_;
 3136: 	$newstorehash{$key} = $storehash->{$_};
 3137:     }
 3138:     my $items='';
 3139:     my %allitems = ();
 3140:     foreach (keys %newstorehash) {
 3141: 	if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3142: 	    my $key = $1.':keys:'.$2;
 3143: 	    $allitems{$key} .= $3.':';
 3144: 	}
 3145: 	$items.=$_.'='.&freeze_escape($newstorehash{$_}).'&';
 3146:     }
 3147:     foreach (keys %allitems) {
 3148: 	$allitems{$_} =~ s/\:$//;
 3149: 	$items.= $_.'='.$allitems{$_}.'&';
 3150:     }
 3151:     $items=~s/\&$//;
 3152:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3153: }
 3154: 
 3155: # ------------------------------------------------------ critical put interface
 3156: 
 3157: sub cput {
 3158:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3160:    if (!$uname) { $uname=$env{'user.name'}; }
 3161:    my $uhome=&homeserver($uname,$udomain);
 3162:    my $items='';
 3163:    foreach (keys %$storehash) {
 3164:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3165:    }
 3166:    $items=~s/\&$//;
 3167:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3168: }
 3169: 
 3170: # -------------------------------------------------------------- eget interface
 3171: 
 3172: sub eget {
 3173:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3174:    my $items='';
 3175:    foreach (@$storearr) {
 3176:        $items.=escape($_).'&';
 3177:    }
 3178:    $items=~s/\&$//;
 3179:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3180:    if (!$uname) { $uname=$env{'user.name'}; }
 3181:    my $uhome=&homeserver($uname,$udomain);
 3182:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3183:    my @pairs=split(/\&/,$rep);
 3184:    my %returnhash=();
 3185:    my $i=0;
 3186:    foreach (@$storearr) {
 3187:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 3188:       $i++;
 3189:    }
 3190:    return %returnhash;
 3191: }
 3192: 
 3193: # ------------------------------------------------------------ tmpput interface
 3194: sub tmpput {
 3195:     my ($storehash,$server)=@_;
 3196:     my $items='';
 3197:     foreach (keys(%$storehash)) {
 3198: 	$items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 3199:     }
 3200:     $items=~s/\&$//;
 3201:     return &reply("tmpput:$items",$server);
 3202: }
 3203: 
 3204: # ------------------------------------------------------------ tmpget interface
 3205: sub tmpget {
 3206:     my ($token,$server)=@_;
 3207:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3208:     my $rep=&reply("tmpget:$token",$server);
 3209:     my %returnhash;
 3210:     foreach my $item (split(/\&/,$rep)) {
 3211: 	my ($key,$value)=split(/=/,$item);
 3212: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3213:     }
 3214:     return %returnhash;
 3215: }
 3216: 
 3217: # ------------------------------------------------------------ tmpget interface
 3218: sub tmpdel {
 3219:     my ($token,$server)=@_;
 3220:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3221:     return &reply("tmpdel:$token",$server);
 3222: }
 3223: 
 3224: # ---------------------------------------------- Custom access rule evaluation
 3225: 
 3226: sub customaccess {
 3227:     my ($priv,$uri)=@_;
 3228:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3229:     $urealm=~s/^\W//;
 3230:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3231:     my $access=0;
 3232:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3233: 	my ($effect,$realm,$role)=split(/\:/,$_);
 3234:         if ($role) {
 3235: 	   if ($role ne $urole) { next; }
 3236:         }
 3237:         foreach (split(/\s*\,\s*/,$realm)) {
 3238:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 3239:             if ($tdom) {
 3240: 		if ($tdom ne $udom) { next; }
 3241:             }
 3242:             if ($tcrs) {
 3243: 		if ($tcrs ne $ucrs) { next; }
 3244:             }
 3245:             if ($tsec) {
 3246: 		if ($tsec ne $usec) { next; }
 3247:             }
 3248:             $access=($effect eq 'allow');
 3249:             last;
 3250:         }
 3251: 	if ($realm eq '' && $role eq '') {
 3252:             $access=($effect eq 'allow');
 3253: 	}
 3254:     }
 3255:     return $access;
 3256: }
 3257: 
 3258: # ------------------------------------------------- Check for a user privilege
 3259: 
 3260: sub allowed {
 3261:     my ($priv,$uri,$symb)=@_;
 3262:     my $ver_orguri=$uri;
 3263:     $uri=&deversion($uri);
 3264:     my $orguri=$uri;
 3265:     $uri=&declutter($uri);
 3266:     
 3267:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3268: # Free bre access to adm and meta resources
 3269:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 3270: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 3271: 	return 'F';
 3272:     }
 3273: 
 3274: # Free bre access to user's own portfolio contents
 3275:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3276:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3277: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3278:         return 'F';
 3279:     }
 3280: 
 3281: # bre access to group if user has rgf priv for this group and course.
 3282:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3283:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3284:         if (exists($env{'request.course.id'})) {
 3285:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3286:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3287:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3288:                 my $courseprivid=$env{'request.course.id'};
 3289:                 $courseprivid=~s/\_/\//;
 3290:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3291:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3292:                     return $1; 
 3293:                 }
 3294:             }
 3295:         }
 3296:     }
 3297: 
 3298: # Free bre to public access
 3299: 
 3300:     if ($priv eq 'bre') {
 3301:         my $copyright=&metadata($uri,'copyright');
 3302: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3303:            return 'F'; 
 3304:         }
 3305:         if ($copyright eq 'priv') {
 3306:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3307: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3308: 		return '';
 3309:             }
 3310:         }
 3311:         if ($copyright eq 'domain') {
 3312:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3313: 	    unless (($env{'user.domain'} eq $1) ||
 3314:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3315: 		return '';
 3316:             }
 3317:         }
 3318:         if ($env{'request.role'}=~ /li\.\//) {
 3319:             # Library role, so allow browsing of resources in this domain.
 3320:             return 'F';
 3321:         }
 3322:         if ($copyright eq 'custom') {
 3323: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3324:         }
 3325:     }
 3326:     # Domain coordinator is trying to create a course
 3327:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3328:         # uri is the requested domain in this case.
 3329:         # comparison to 'request.role.domain' shows if the user has selected
 3330:         # a role of dc for the domain in question.
 3331:         return 'F' if ($uri eq $env{'request.role.domain'});
 3332:     }
 3333: 
 3334:     my $thisallowed='';
 3335:     my $statecond=0;
 3336:     my $courseprivid='';
 3337: 
 3338: # Course
 3339: 
 3340:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3341:        $thisallowed.=$1;
 3342:     }
 3343: 
 3344: # Domain
 3345: 
 3346:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3347:        =~/\Q$priv\E\&([^\:]*)/) {
 3348:        $thisallowed.=$1;
 3349:     }
 3350: 
 3351: # Course: uri itself is a course
 3352:     my $courseuri=$uri;
 3353:     $courseuri=~s/\_(\d)/\/$1/;
 3354:     $courseuri=~s/^([^\/])/\/$1/;
 3355: 
 3356:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3357:        =~/\Q$priv\E\&([^\:]*)/) {
 3358:        $thisallowed.=$1;
 3359:     }
 3360: 
 3361: # Group: uri itself is a group
 3362:     my $groupuri=$uri;
 3363:     $groupuri=~s/^([^\/])/\/$1/;
 3364:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$groupuri}
 3365:        =~/\Q$priv\E\&([^\:]*)/) {
 3366:        $thisallowed.=$1;
 3367:     }
 3368: 
 3369: # URI is an uploaded document for this course, default permissions don't matter
 3370: # not allowing 'edit' access (editupload) to uploaded course docs
 3371:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3372: 	$thisallowed='';
 3373:         my ($match)=&is_on_map($uri);
 3374:         if ($match) {
 3375:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3376:                   =~/\Q$priv\E\&([^\:]*)/) {
 3377:                 $thisallowed.=$1;
 3378:             }
 3379:         } else {
 3380:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3381:             if ($refuri) {
 3382:                 if ($refuri =~ m|^/adm/|) {
 3383:                     $thisallowed='F';
 3384:                 } else {
 3385:                     $refuri=&declutter($refuri);
 3386:                     my ($match) = &is_on_map($refuri);
 3387:                     if ($match) {
 3388:                         $thisallowed='F';
 3389:                     }
 3390:                 }
 3391:             }
 3392:         }
 3393:     }
 3394: 
 3395: # Full access at system, domain or course-wide level? Exit.
 3396: 
 3397:     if ($thisallowed=~/F/) {
 3398: 	return 'F';
 3399:     }
 3400: 
 3401: # If this is generating or modifying users, exit with special codes
 3402: 
 3403:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3404: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3405: 	    my ($audom,$auname)=split('/',$uri);
 3406: # no author name given, so this just checks on the general right to make a co-author in this domain
 3407: 	    unless ($auname) { return $thisallowed; }
 3408: # an author name is given, so we are about to actually make a co-author for a certain account
 3409: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3410: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3411: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3412: 	}
 3413: 	return $thisallowed;
 3414:     }
 3415: #
 3416: # Gathered so far: system, domain and course wide privileges
 3417: #
 3418: # Course: See if uri or referer is an individual resource that is part of 
 3419: # the course
 3420: 
 3421:     if ($env{'request.course.id'}) {
 3422: 
 3423:        $courseprivid=$env{'request.course.id'};
 3424:        if ($env{'request.course.sec'}) {
 3425:           $courseprivid.='/'.$env{'request.course.sec'};
 3426:        }
 3427:        $courseprivid=~s/\_/\//;
 3428:        my $checkreferer=1;
 3429:        my ($match,$cond)=&is_on_map($uri);
 3430:        if ($match) {
 3431:            $statecond=$cond;
 3432:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3433:                =~/\Q$priv\E\&([^\:]*)/) {
 3434:                $thisallowed.=$1;
 3435:                $checkreferer=0;
 3436:            }
 3437:        }
 3438:        
 3439:        if ($checkreferer) {
 3440: 	  my $refuri=$env{'httpref.'.$orguri};
 3441:             unless ($refuri) {
 3442:                 foreach (keys %env) {
 3443: 		    if ($_=~/^httpref\..*\*/) {
 3444: 			my $pattern=$_;
 3445:                         $pattern=~s/^httpref\.\/res\///;
 3446:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3447:                         $pattern=~s/\//\\\//g;
 3448:                         if ($orguri=~/$pattern/) {
 3449: 			    $refuri=$env{$_};
 3450:                         }
 3451:                     }
 3452:                 }
 3453:             }
 3454: 
 3455:          if ($refuri) { 
 3456: 	  $refuri=&declutter($refuri);
 3457:           my ($match,$cond)=&is_on_map($refuri);
 3458:             if ($match) {
 3459:               my $refstatecond=$cond;
 3460:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3461:                   =~/\Q$priv\E\&([^\:]*)/) {
 3462:                   $thisallowed.=$1;
 3463:                   $uri=$refuri;
 3464:                   $statecond=$refstatecond;
 3465:               }
 3466:           }
 3467:         }
 3468:        }
 3469:    }
 3470: 
 3471: #
 3472: # Gathered now: all privileges that could apply, and condition number
 3473: # 
 3474: #
 3475: # Full or no access?
 3476: #
 3477: 
 3478:     if ($thisallowed=~/F/) {
 3479: 	return 'F';
 3480:     }
 3481: 
 3482:     unless ($thisallowed) {
 3483:         return '';
 3484:     }
 3485: 
 3486: # Restrictions exist, deal with them
 3487: #
 3488: #   C:according to course preferences
 3489: #   R:according to resource settings
 3490: #   L:unless locked
 3491: #   X:according to user session state
 3492: #
 3493: 
 3494: # Possibly locked functionality, check all courses
 3495: # Locks might take effect only after 10 minutes cache expiration for other
 3496: # courses, and 2 minutes for current course
 3497: 
 3498:     my $envkey;
 3499:     if ($thisallowed=~/L/) {
 3500:         foreach $envkey (keys %env) {
 3501:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3502:                my $courseid=$2;
 3503:                my $roleid=$1.'.'.$2;
 3504:                $courseid=~s/^\///;
 3505:                my $expiretime=600;
 3506:                if ($env{'request.role'} eq $roleid) {
 3507: 		  $expiretime=120;
 3508:                }
 3509: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3510:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3511:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3512: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3513:                }
 3514:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3515:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3516: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3517:                        &log($env{'user.domain'},$env{'user.name'},
 3518:                             $env{'user.home'},
 3519:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3520:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3521:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3522: 		       return '';
 3523:                    }
 3524:                }
 3525:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3526:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3527: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3528:                        &log($env{'user.domain'},$env{'user.name'},
 3529:                             $env{'user.home'},
 3530:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3531:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3532:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3533: 		       return '';
 3534:                    }
 3535:                }
 3536: 	   }
 3537:        }
 3538:     }
 3539:    
 3540: #
 3541: # Rest of the restrictions depend on selected course
 3542: #
 3543: 
 3544:     unless ($env{'request.course.id'}) {
 3545:        return '1';
 3546:     }
 3547: 
 3548: #
 3549: # Now user is definitely in a course
 3550: #
 3551: 
 3552: 
 3553: # Course preferences
 3554: 
 3555:    if ($thisallowed=~/C/) {
 3556:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3557:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3558:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3559: 	   =~/\Q$rolecode\E/) {
 3560: 	   if ($priv ne 'pch') { 
 3561: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3562: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3563: 			$env{'request.course.id'});
 3564: 	   }
 3565:            return '';
 3566:        }
 3567: 
 3568:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3569: 	   =~/\Q$unamedom\E/) {
 3570: 	   if ($priv ne 'pch') { 
 3571: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3572: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3573: 			$env{'request.course.id'});
 3574: 	   }
 3575:            return '';
 3576:        }
 3577:    }
 3578: 
 3579: # Resource preferences
 3580: 
 3581:    if ($thisallowed=~/R/) {
 3582:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3583:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3584: 	   if ($priv ne 'pch') { 
 3585: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3586: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3587: 	   }
 3588: 	   return '';
 3589:        }
 3590:    }
 3591: 
 3592: # Restricted by state or randomout?
 3593: 
 3594:    if ($thisallowed=~/X/) {
 3595:       if ($env{'acc.randomout'}) {
 3596: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3597:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3598:             return ''; 
 3599:          }
 3600:       }
 3601:       if (&condval($statecond)) {
 3602: 	 return '2';
 3603:       } else {
 3604:          return '';
 3605:       }
 3606:    }
 3607: 
 3608:    return 'F';
 3609: }
 3610: 
 3611: sub split_uri_for_cond {
 3612:     my $uri=&deversion(&declutter(shift));
 3613:     my @uriparts=split(/\//,$uri);
 3614:     my $filename=pop(@uriparts);
 3615:     my $pathname=join('/',@uriparts);
 3616:     return ($pathname,$filename);
 3617: }
 3618: # --------------------------------------------------- Is a resource on the map?
 3619: 
 3620: sub is_on_map {
 3621:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3622:     #Trying to find the conditional for the file
 3623:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3624: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3625:     if ($match) {
 3626: 	return (1,$1);
 3627:     } else {
 3628: 	return (0,0);
 3629:     }
 3630: }
 3631: 
 3632: # --------------------------------------------------------- Get symb from alias
 3633: 
 3634: sub get_symb_from_alias {
 3635:     my $symb=shift;
 3636:     my ($map,$resid,$url)=&decode_symb($symb);
 3637: # Already is a symb
 3638:     if ($url) { return $symb; }
 3639: # Must be an alias
 3640:     my $aliassymb='';
 3641:     my %bighash;
 3642:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3643:                             &GDBM_READER(),0640)) {
 3644:         my $rid=$bighash{'mapalias_'.$symb};
 3645: 	if ($rid) {
 3646: 	    my ($mapid,$resid)=split(/\./,$rid);
 3647: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3648: 				    $resid,$bighash{'src_'.$rid});
 3649: 	}
 3650:         untie %bighash;
 3651:     }
 3652:     return $aliassymb;
 3653: }
 3654: 
 3655: # ----------------------------------------------------------------- Define Role
 3656: 
 3657: sub definerole {
 3658:   if (allowed('mcr','/')) {
 3659:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3660:     foreach (split(':',$sysrole)) {
 3661: 	my ($crole,$cqual)=split(/\&/,$_);
 3662:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3663:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3664: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3665:                return "refused:s:$crole&$cqual"; 
 3666:             }
 3667:         }
 3668:     }
 3669:     foreach (split(':',$domrole)) {
 3670: 	my ($crole,$cqual)=split(/\&/,$_);
 3671:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3672:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3673: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3674:                return "refused:d:$crole&$cqual"; 
 3675:             }
 3676:         }
 3677:     }
 3678:     foreach (split(':',$courole)) {
 3679: 	my ($crole,$cqual)=split(/\&/,$_);
 3680:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3681:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3682: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3683:                return "refused:c:$crole&$cqual"; 
 3684:             }
 3685:         }
 3686:     }
 3687:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3688:                 "$env{'user.domain'}:$env{'user.name'}:".
 3689: 	        "rolesdef_$rolename=".
 3690:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3691:     return reply($command,$env{'user.home'});
 3692:   } else {
 3693:     return 'refused';
 3694:   }
 3695: }
 3696: 
 3697: # ---------------- Make a metadata query against the network of library servers
 3698: 
 3699: sub metadata_query {
 3700:     my ($query,$custom,$customshow,$server_array)=@_;
 3701:     my %rhash;
 3702:     my @server_list = (defined($server_array) ? @$server_array
 3703:                                               : keys(%libserv) );
 3704:     for my $server (@server_list) {
 3705: 	unless ($custom or $customshow) {
 3706: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3707: 	    $rhash{$server}=$reply;
 3708: 	}
 3709: 	else {
 3710: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3711: 			     &escape($custom).':'.&escape($customshow),
 3712: 			     $server);
 3713: 	    $rhash{$server}=$reply;
 3714: 	}
 3715:     }
 3716:     return \%rhash;
 3717: }
 3718: 
 3719: # ----------------------------------------- Send log queries and wait for reply
 3720: 
 3721: sub log_query {
 3722:     my ($uname,$udom,$query,%filters)=@_;
 3723:     my $uhome=&homeserver($uname,$udom);
 3724:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3725:     my $uhost=$hostname{$uhome};
 3726:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3727:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3728:                        $uhome);
 3729:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3730:     return get_query_reply($queryid);
 3731: }
 3732: 
 3733: # ------- Request retrieval of institutional classlists for course(s)
 3734: 
 3735: sub fetch_enrollment_query {
 3736:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3737:     my $homeserver;
 3738:     my $maxtries = 1;
 3739:     if ($context eq 'automated') {
 3740:         $homeserver = $perlvar{'lonHostID'};
 3741:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3742:     } else {
 3743:         $homeserver = &homeserver($cnum,$dom);
 3744:     }
 3745:     my $host=$hostname{$homeserver};
 3746:     my $cmd = '';
 3747:     foreach (keys %{$affiliatesref}) {
 3748:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3749:     }
 3750:     $cmd =~ s/%%$//;
 3751:     $cmd = &escape($cmd);
 3752:     my $query = 'fetchenrollment';
 3753:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3754:     unless ($queryid=~/^\Q$host\E\_/) { 
 3755:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3756:         return 'error: '.$queryid;
 3757:     }
 3758:     my $reply = &get_query_reply($queryid);
 3759:     my $tries = 1;
 3760:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3761:         $reply = &get_query_reply($queryid);
 3762:         $tries ++;
 3763:     }
 3764:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3765:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3766:     } else {
 3767:         my @responses = split/:/,$reply;
 3768:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3769:             foreach (@responses) {
 3770:                 my ($key,$value) = split/=/,$_;
 3771:                 $$replyref{$key} = $value;
 3772:             }
 3773:         } else {
 3774:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3775:             foreach (@responses) {
 3776:                 my ($key,$value) = split/=/,$_;
 3777:                 $$replyref{$key} = $value;
 3778:                 if ($value > 0) {
 3779:                     foreach (@{$$affiliatesref{$key}}) {
 3780:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3781:                         my $destname = $pathname.'/'.$filename;
 3782:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3783:                         if ($xml_classlist =~ /^error/) {
 3784:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3785:                         } else {
 3786:                             if ( open(FILE,">$destname") ) {
 3787:                                 print FILE &unescape($xml_classlist);
 3788:                                 close(FILE);
 3789:                             } else {
 3790:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3791:                             }
 3792:                         }
 3793:                     }
 3794:                 }
 3795:             }
 3796:         }
 3797:         return 'ok';
 3798:     }
 3799:     return 'error';
 3800: }
 3801: 
 3802: sub get_query_reply {
 3803:     my $queryid=shift;
 3804:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3805:     my $reply='';
 3806:     for (1..100) {
 3807: 	sleep 2;
 3808:         if (-e $replyfile.'.end') {
 3809: 	    if (open(my $fh,$replyfile)) {
 3810:                $reply.=<$fh>;
 3811:                close($fh);
 3812: 	   } else { return 'error: reply_file_error'; }
 3813:            return &unescape($reply);
 3814: 	}
 3815:     }
 3816:     return 'timeout:'.$queryid;
 3817: }
 3818: 
 3819: sub courselog_query {
 3820: #
 3821: # possible filters:
 3822: # url: url or symb
 3823: # username
 3824: # domain
 3825: # action: view, submit, grade
 3826: # start: timestamp
 3827: # end: timestamp
 3828: #
 3829:     my (%filters)=@_;
 3830:     unless ($env{'request.course.id'}) { return 'no_course'; }
 3831:     if ($filters{'url'}) {
 3832: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3833:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3834:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3835:     }
 3836:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3837:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3838:     return &log_query($cname,$cdom,'courselog',%filters);
 3839: }
 3840: 
 3841: sub userlog_query {
 3842:     my ($uname,$udom,%filters)=@_;
 3843:     return &log_query($uname,$udom,'userlog',%filters);
 3844: }
 3845: 
 3846: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3847: 
 3848: sub auto_run {
 3849:     my ($cnum,$cdom) = @_;
 3850:     my $homeserver = &homeserver($cnum,$cdom);
 3851:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3852:     return $response;
 3853: }
 3854:                                                                                    
 3855: sub auto_get_sections {
 3856:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3857:     my $homeserver = &homeserver($cnum,$cdom);
 3858:     my @secs = ();
 3859:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3860:     unless ($response eq 'refused') {
 3861:         @secs = split/:/,$response;
 3862:     }
 3863:     return @secs;
 3864: }
 3865:                                                                                    
 3866: sub auto_new_course {
 3867:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3868:     my $homeserver = &homeserver($cnum,$cdom);
 3869:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3870:     return $response;
 3871: }
 3872:                                                                                    
 3873: sub auto_validate_courseID {
 3874:     my ($cnum,$cdom,$inst_course_id) = @_;
 3875:     my $homeserver = &homeserver($cnum,$cdom);
 3876:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3877:     return $response;
 3878: }
 3879:                                                                                    
 3880: sub auto_create_password {
 3881:     my ($cnum,$cdom,$authparam) = @_;
 3882:     my $homeserver = &homeserver($cnum,$cdom); 
 3883:     my $create_passwd = 0;
 3884:     my $authchk = '';
 3885:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3886:     if ($response eq 'refused') {
 3887:         $authchk = 'refused';
 3888:     } else {
 3889:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3890:     }
 3891:     return ($authparam,$create_passwd,$authchk);
 3892: }
 3893: 
 3894: sub auto_photo_permission {
 3895:     my ($cnum,$cdom,$students) = @_;
 3896:     my $homeserver = &homeserver($cnum,$cdom);
 3897:     my ($outcome,$perm_reqd,$conditions) = 
 3898: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 3899:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3900: 	return (undef,undef);
 3901:     }
 3902:     return ($outcome,$perm_reqd,$conditions);
 3903: }
 3904: 
 3905: sub auto_checkphotos {
 3906:     my ($uname,$udom,$pid) = @_;
 3907:     my $homeserver = &homeserver($uname,$udom);
 3908:     my ($result,$resulttype);
 3909:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 3910: 				   &escape($uname).':'.&escape($pid),
 3911: 				   $homeserver));
 3912:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3913: 	return (undef,undef);
 3914:     }
 3915:     if ($outcome) {
 3916:         ($result,$resulttype) = split(/:/,$outcome);
 3917:     } 
 3918:     return ($result,$resulttype);
 3919: }
 3920: 
 3921: sub auto_photochoice {
 3922:     my ($cnum,$cdom) = @_;
 3923:     my $homeserver = &homeserver($cnum,$cdom);
 3924:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 3925: 						       &escape($cdom),
 3926: 						       $homeserver)));
 3927:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 3928: 	return (undef,undef);
 3929:     }
 3930:     return ($update,$comment);
 3931: }
 3932: 
 3933: sub auto_photoupdate {
 3934:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 3935:     my $homeserver = &homeserver($cnum,$dom);
 3936:     my $host=$hostname{$homeserver};
 3937:     my $cmd = '';
 3938:     my $maxtries = 1;
 3939:     foreach (keys %{$affiliatesref}) {
 3940:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3941:     }
 3942:     $cmd =~ s/%%$//;
 3943:     $cmd = &escape($cmd);
 3944:     my $query = 'institutionalphotos';
 3945:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 3946:     unless ($queryid=~/^\Q$host\E\_/) {
 3947:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 3948:         return 'error: '.$queryid;
 3949:     }
 3950:     my $reply = &get_query_reply($queryid);
 3951:     my $tries = 1;
 3952:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3953:         $reply = &get_query_reply($queryid);
 3954:         $tries ++;
 3955:     }
 3956:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3957:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3958:     } else {
 3959:         my @responses = split(/:/,$reply);
 3960:         my $outcome = shift(@responses); 
 3961:         foreach my $item (@responses) {
 3962:             my ($key,$value) = split(/=/,$item);
 3963:             $$photo{$key} = $value;
 3964:         }
 3965:         return $outcome;
 3966:     }
 3967:     return 'error';
 3968: }
 3969: 
 3970: sub auto_instcode_format {
 3971:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3972:     my $courses = '';
 3973:     my $homeserver;
 3974:     if ($caller eq 'global') {
 3975:         foreach my $tryserver (keys %libserv) {
 3976:             if ($hostdom{$tryserver} eq $codedom) {
 3977:                 $homeserver = $tryserver;
 3978:                 last;
 3979:             }
 3980:         }
 3981:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
 3982:             $homeserver = &homeserver($env{'user.name'},$codedom);
 3983:         }
 3984:     } else {
 3985:         $homeserver = &homeserver($caller,$codedom);
 3986:     }
 3987:     foreach (keys %{$instcodes}) {
 3988:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3989:     }
 3990:     chop($courses);
 3991:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3992:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3993:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3994:         %{$codes} = &str2hash($codes_str);
 3995:         @{$codetitles} = &str2array($codetitles_str);
 3996:         %{$cat_titles} = &str2hash($cat_titles_str);
 3997:         %{$cat_order} = &str2hash($cat_order_str);
 3998:         return 'ok';
 3999:     }
 4000:     return $response;
 4001: }
 4002: 
 4003: # ------------------------------------------------------- Course Group routines
 4004: 
 4005: sub get_coursegroups {
 4006:     my ($cdom,$cnum,$group) = @_;
 4007:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4008: }
 4009: 
 4010: sub modify_coursegroup {
 4011:     my ($cdom,$cnum,$groupsettings) = @_;
 4012:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4013: }
 4014: 
 4015: sub modify_group_roles {
 4016:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4017:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4018:     my $role = 'gr/'.&escape($userprivs);
 4019:     my ($uname,$udom) = split(/:/,$user);
 4020:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4021:     if ($result eq 'ok') {
 4022:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4023:     }
 4024:     return $result;
 4025: }
 4026: 
 4027: sub modify_coursegroup_membership {
 4028:     my ($cdom,$cnum,$membership) = @_;
 4029:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4030:     return $result;
 4031: }
 4032: 
 4033: sub get_active_groups {
 4034:     my ($udom,$uname,$cdom,$cnum) = @_;
 4035:     my $now = time;
 4036:     my %groups = ();
 4037:     foreach my $key (keys(%env)) {
 4038:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4039:             my ($start,$end) = split(/\./,$env{$key});
 4040:             if (($end!=0) && ($end<$now)) { next; }
 4041:             if (($start!=0) && ($start>$now)) { next; }
 4042:             if ($1 eq $cdom && $2 eq $cnum) {
 4043:                 $groups{$3} = $env{$key} ;
 4044:             }
 4045:         }
 4046:     }
 4047:     return %groups;
 4048: }
 4049: 
 4050: sub get_group_membership {
 4051:     my ($cdom,$cnum,$group) = @_;
 4052:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4053: }
 4054: 
 4055: sub get_users_groups {
 4056:     my ($udom,$uname,$courseid) = @_;
 4057:     my @usersgroups;
 4058:     my $cachetime=1800;
 4059:     $courseid=~s/\_/\//g;
 4060:     $courseid=~s/^(\w)/\/$1/;
 4061: 
 4062:     my $hashid="$udom:$uname:$courseid";
 4063:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4064:     if (defined($cached)) {
 4065:         @usersgroups = split(/:/,$grouplist);
 4066:     } else {  
 4067:         $grouplist = '';
 4068:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4069:         my ($tmp) = keys(%roleshash);
 4070:         if ($tmp=~/^error:/) {
 4071:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4072:         } else {
 4073:             my $access_end = $env{'course.'.$courseid.
 4074:                                   '.default_enrollment_end_date'};
 4075:             my $now = time;
 4076:             foreach my $key (keys(%roleshash)) {
 4077:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4078:                     my $group = $1;
 4079:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4080:                         my $start = $2;
 4081:                         my $end = $1;
 4082:                         if ($start == -1) { next; } # deleted from group
 4083:                         if (($start!=0) && ($start>$now)) { next; }
 4084:                         if (($end!=0) && ($end<$now)) {
 4085:                             if ($access_end && $access_end < $now) {
 4086:                                 if ($access_end - $end < 86400) {
 4087:                                     push(@usersgroups,$group);
 4088:                                 }
 4089:                             }
 4090:                             next;
 4091:                         }
 4092:                         push(@usersgroups,$group);
 4093:                     }
 4094:                 }
 4095:             }
 4096:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4097:             $grouplist = join(':',@usersgroups);
 4098:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4099:         }
 4100:     }
 4101:     return @usersgroups;
 4102: }
 4103: 
 4104: sub devalidate_getgroups_cache {
 4105:     my ($udom,$uname,$cdom,$cnum)=@_;
 4106:     my $courseid = $cdom.'_'.$cnum;
 4107:     $courseid=~s/\_/\//g;
 4108:     $courseid=~s/^(\w)/\/$1/;
 4109:     my $hashid="$udom:$uname:$courseid";
 4110:     &devalidate_cache_new('getgroups',$hashid);
 4111: }
 4112: 
 4113: # ------------------------------------------------------------------ Plain Text
 4114: 
 4115: sub plaintext {
 4116:     my ($short,$type,$cid) = @_;
 4117:     if (!defined($cid)) {
 4118:         $cid = $env{'request.course.id'};
 4119:     }
 4120:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4121:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4122:                                           '.plaintext'});
 4123:     }
 4124:     my %rolenames = (
 4125:                       Course => 'std',
 4126:                       Group => 'alt1',
 4127:                     );
 4128:     if (defined($type) && 
 4129:          defined($rolenames{$type}) && 
 4130:          defined($prp{$short}{$rolenames{$type}})) {
 4131:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4132:     } else {
 4133:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4134:     }
 4135: }
 4136: 
 4137: # ----------------------------------------------------------------- Assign Role
 4138: 
 4139: sub assignrole {
 4140:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4141:     my $mrole;
 4142:     if ($role =~ /^cr\//) {
 4143:         my $cwosec=$url;
 4144:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4145: 	unless (&allowed('ccr',$cwosec)) {
 4146:            &logthis('Refused custom assignrole: '.
 4147:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4148: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4149:            return 'refused'; 
 4150:         }
 4151:         $mrole='cr';
 4152:     } elsif ($role =~ /^gr\//) {
 4153:         my $cwogrp=$url;
 4154:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4155:         unless (&allowed('mdg',$cwogrp)) {
 4156:             &logthis('Refused group assignrole: '.
 4157:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4158:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4159:             return 'refused';
 4160:         }
 4161:         $mrole='gr';
 4162:     } else {
 4163:         my $cwosec=$url;
 4164:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4165:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4166:            &logthis('Refused assignrole: '.
 4167:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4168: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4169:            return 'refused'; 
 4170:         }
 4171:         $mrole=$role;
 4172:     }
 4173:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4174:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4175:     if ($end) { $command.='_'.$end; }
 4176:     if ($start) {
 4177: 	if ($end) { 
 4178:            $command.='_'.$start; 
 4179:         } else {
 4180:            $command.='_0_'.$start;
 4181:         }
 4182:     }
 4183:     my $origstart = $start;
 4184:     my $origend = $end;
 4185: # actually delete
 4186:     if ($deleteflag) {
 4187: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4188: # modify command to delete the role
 4189:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4190:                 "$udom:$uname:$url".'_'."$mrole";
 4191: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4192: # set start and finish to negative values for userrolelog
 4193:            $start=-1;
 4194:            $end=-1;
 4195:         }
 4196:     }
 4197: # send command
 4198:     my $answer=&reply($command,&homeserver($uname,$udom));
 4199: # log new user role if status is ok
 4200:     if ($answer eq 'ok') {
 4201: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4202: # for course roles, perform group memberships changes triggered by role change.
 4203:         unless ($role =~ /^gr/) {
 4204:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4205:                                              $origstart);
 4206:         }
 4207:     }
 4208:     return $answer;
 4209: }
 4210: 
 4211: # -------------------------------------------------- Modify user authentication
 4212: # Overrides without validation
 4213: 
 4214: sub modifyuserauth {
 4215:     my ($udom,$uname,$umode,$upass)=@_;
 4216:     my $uhome=&homeserver($uname,$udom);
 4217:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4218:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4219:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4220:              ' in domain '.$env{'request.role.domain'});  
 4221:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4222: 		     &escape($upass),$uhome);
 4223:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4224:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4225:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4226:     &log($udom,,$uname,$uhome,
 4227:         'Authentication changed by '.$env{'user.domain'}.', '.
 4228:                                      $env{'user.name'}.', '.$umode.
 4229:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4230:     unless ($reply eq 'ok') {
 4231:         &logthis('Authentication mode error: '.$reply);
 4232: 	return 'error: '.$reply;
 4233:     }   
 4234:     return 'ok';
 4235: }
 4236: 
 4237: # --------------------------------------------------------------- Modify a user
 4238: 
 4239: sub modifyuser {
 4240:     my ($udom,    $uname, $uid,
 4241:         $umode,   $upass, $first,
 4242:         $middle,  $last,  $gene,
 4243:         $forceid, $desiredhome, $email)=@_;
 4244:     $udom=~s/\W//g;
 4245:     $uname=~s/\W//g;
 4246:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4247:              $umode.', '.$first.', '.$middle.', '.
 4248: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4249:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4250:                                      ' desiredhome not specified'). 
 4251:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4252:              ' in domain '.$env{'request.role.domain'});
 4253:     my $uhome=&homeserver($uname,$udom,'true');
 4254: # ----------------------------------------------------------------- Create User
 4255:     if (($uhome eq 'no_host') && 
 4256: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4257:         my $unhome='';
 4258:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4259:             $unhome = $desiredhome;
 4260: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4261: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4262:         } else { # load balancing routine for determining $unhome
 4263:             my $tryserver;
 4264:             my $loadm=10000000;
 4265:             foreach $tryserver (keys %libserv) {
 4266: 	       if ($hostdom{$tryserver} eq $udom) {
 4267:                   my $answer=reply('load',$tryserver);
 4268:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4269: 		      $loadm=$answer;
 4270:                       $unhome=$tryserver;
 4271:                   }
 4272: 	       }
 4273: 	    }
 4274:         }
 4275:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4276: 	    return 'error: unable to find a home server for '.$uname.
 4277:                    ' in domain '.$udom;
 4278:         }
 4279:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4280:                          &escape($upass),$unhome);
 4281: 	unless ($reply eq 'ok') {
 4282:             return 'error: '.$reply;
 4283:         }   
 4284:         $uhome=&homeserver($uname,$udom,'true');
 4285:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4286: 	    return 'error: unable verify users home machine.';
 4287:         }
 4288:     }   # End of creation of new user
 4289: # ---------------------------------------------------------------------- Add ID
 4290:     if ($uid) {
 4291:        $uid=~tr/A-Z/a-z/;
 4292:        my %uidhash=&idrget($udom,$uname);
 4293:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4294:          && (!$forceid)) {
 4295: 	  unless ($uid eq $uidhash{$uname}) {
 4296: 	      return 'error: user id "'.$uid.'" does not match '.
 4297:                   'current user id "'.$uidhash{$uname}.'".';
 4298:           }
 4299:        } else {
 4300: 	  &idput($udom,($uname => $uid));
 4301:        }
 4302:     }
 4303: # -------------------------------------------------------------- Add names, etc
 4304:     my @tmp=&get('environment',
 4305: 		   ['firstname','middlename','lastname','generation'],
 4306: 		   $udom,$uname);
 4307:     my %names;
 4308:     if ($tmp[0] =~ m/^error:.*/) { 
 4309:         %names=(); 
 4310:     } else {
 4311:         %names = @tmp;
 4312:     }
 4313: #
 4314: # Make sure to not trash student environment if instructor does not bother
 4315: # to supply name and email information
 4316: #
 4317:     if ($first)  { $names{'firstname'}  = $first; }
 4318:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4319:     if ($last)   { $names{'lastname'}   = $last; }
 4320:     if (defined($gene))   { $names{'generation'} = $gene; }
 4321:     if ($email) {
 4322:        $email=~s/[^\w\@\.\-\,]//gs;
 4323:        if ($email=~/\@/) { $names{'notification'} = $email;
 4324: 			   $names{'critnotification'} = $email;
 4325: 			   $names{'permanentemail'} = $email; }
 4326:     }
 4327:     my $reply = &put('environment', \%names, $udom,$uname);
 4328:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4329:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4330:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4331:              $umode.', '.$first.', '.$middle.', '.
 4332: 	     $last.', '.$gene.' by '.
 4333:              $env{'user.name'}.' at '.$env{'user.domain'});
 4334:     return 'ok';
 4335: }
 4336: 
 4337: # -------------------------------------------------------------- Modify student
 4338: 
 4339: sub modifystudent {
 4340:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4341:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4342:     if (!$cid) {
 4343: 	unless ($cid=$env{'request.course.id'}) {
 4344: 	    return 'not_in_class';
 4345: 	}
 4346:     }
 4347: # --------------------------------------------------------------- Make the user
 4348:     my $reply=&modifyuser
 4349: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4350:          $desiredhome,$email);
 4351:     unless ($reply eq 'ok') { return $reply; }
 4352:     # This will cause &modify_student_enrollment to get the uid from the
 4353:     # students environment
 4354:     $uid = undef if (!$forceid);
 4355:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4356: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4357:     return $reply;
 4358: }
 4359: 
 4360: sub modify_student_enrollment {
 4361:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4362:     my ($cdom,$cnum,$chome);
 4363:     if (!$cid) {
 4364: 	unless ($cid=$env{'request.course.id'}) {
 4365: 	    return 'not_in_class';
 4366: 	}
 4367: 	$cdom=$env{'course.'.$cid.'.domain'};
 4368: 	$cnum=$env{'course.'.$cid.'.num'};
 4369:     } else {
 4370: 	($cdom,$cnum)=split(/_/,$cid);
 4371:     }
 4372:     $chome=$env{'course.'.$cid.'.home'};
 4373:     if (!$chome) {
 4374: 	$chome=&homeserver($cnum,$cdom);
 4375:     }
 4376:     if (!$chome) { return 'unknown_course'; }
 4377:     # Make sure the user exists
 4378:     my $uhome=&homeserver($uname,$udom);
 4379:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4380: 	return 'error: no such user';
 4381:     }
 4382:     # Get student data if we were not given enough information
 4383:     if (!defined($first)  || $first  eq '' || 
 4384:         !defined($last)   || $last   eq '' || 
 4385:         !defined($uid)    || $uid    eq '' || 
 4386:         !defined($middle) || $middle eq '' || 
 4387:         !defined($gene)   || $gene   eq '') {
 4388:         # They did not supply us with enough data to enroll the student, so
 4389:         # we need to pick up more information.
 4390:         my %tmp = &get('environment',
 4391:                        ['firstname','middlename','lastname', 'generation','id']
 4392:                        ,$udom,$uname);
 4393: 
 4394:         #foreach (keys(%tmp)) {
 4395:         #    &logthis("key $_ = ".$tmp{$_});
 4396:         #}
 4397:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4398:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4399:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4400:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4401:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4402:     }
 4403:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4404:     my $reply=cput('classlist',
 4405: 		   {"$uname:$udom" => 
 4406: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4407: 		   $cdom,$cnum);
 4408:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4409: 	return 'error: '.$reply;
 4410:     } else {
 4411: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4412:     }
 4413:     # Add student role to user
 4414:     my $uurl='/'.$cid;
 4415:     $uurl=~s/\_/\//g;
 4416:     if ($usec) {
 4417: 	$uurl.='/'.$usec;
 4418:     }
 4419:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4420: }
 4421: 
 4422: sub format_name {
 4423:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4424:     my $name;
 4425:     if ($first ne 'lastname') {
 4426: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4427:     } else {
 4428: 	if ($lastname=~/\S/) {
 4429: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4430: 	    $name=~s/\s+,/,/;
 4431: 	} else {
 4432: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4433: 	}
 4434:     }
 4435:     $name=~s/^\s+//;
 4436:     $name=~s/\s+$//;
 4437:     $name=~s/\s+/ /g;
 4438:     return $name;
 4439: }
 4440: 
 4441: # ------------------------------------------------- Write to course preferences
 4442: 
 4443: sub writecoursepref {
 4444:     my ($courseid,%prefs)=@_;
 4445:     $courseid=~s/^\///;
 4446:     $courseid=~s/\_/\//g;
 4447:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4448:     my $chome=homeserver($cnum,$cdomain);
 4449:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4450: 	return 'error: no such course';
 4451:     }
 4452:     my $cstring='';
 4453:     foreach (keys %prefs) {
 4454: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 4455:     }
 4456:     $cstring=~s/\&$//;
 4457:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4458: }
 4459: 
 4460: # ---------------------------------------------------------- Make/modify course
 4461: 
 4462: sub createcourse {
 4463:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4464:         $course_owner,$crstype)=@_;
 4465:     $url=&declutter($url);
 4466:     my $cid='';
 4467:     unless (&allowed('ccc',$udom)) {
 4468:         return 'refused';
 4469:     }
 4470: # ------------------------------------------------------------------- Create ID
 4471:    my $uname=int(1+rand(9)).
 4472:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4473:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4474:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4475: # ----------------------------------------------- Make sure that does not exist
 4476:    my $uhome=&homeserver($uname,$udom,'true');
 4477:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4478:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4479:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4480:        $uhome=&homeserver($uname,$udom,'true');       
 4481:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4482:            return 'error: unable to generate unique course-ID';
 4483:        } 
 4484:    }
 4485: # ------------------------------------------------ Check supplied server name
 4486:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4487:     if (! exists($libserv{$course_server})) {
 4488:         return 'error:bad server name '.$course_server;
 4489:     }
 4490: # ------------------------------------------------------------- Make the course
 4491:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4492:                       $course_server);
 4493:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4494:     $uhome=&homeserver($uname,$udom,'true');
 4495:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4496: 	return 'error: no such course';
 4497:     }
 4498: # ----------------------------------------------------------------- Course made
 4499: # log existence
 4500:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4501:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4502:                   &escape($crstype),$uhome);
 4503:     &flushcourselogs();
 4504: # set toplevel url
 4505:     my $topurl=$url;
 4506:     unless ($nonstandard) {
 4507: # ------------------------------------------ For standard courses, make top url
 4508:         my $mapurl=&clutter($url);
 4509:         if ($mapurl eq '/res/') { $mapurl=''; }
 4510:         $env{'form.initmap'}=(<<ENDINITMAP);
 4511: <map>
 4512: <resource id="1" type="start"></resource>
 4513: <resource id="2" src="$mapurl"></resource>
 4514: <resource id="3" type="finish"></resource>
 4515: <link index="1" from="1" to="2"></link>
 4516: <link index="2" from="2" to="3"></link>
 4517: </map>
 4518: ENDINITMAP
 4519:         $topurl=&declutter(
 4520:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4521:                           );
 4522:     }
 4523: # ----------------------------------------------------------- Write preferences
 4524:     &writecoursepref($udom.'_'.$uname,
 4525:                      ('description' => $description,
 4526:                       'url'         => $topurl));
 4527:     return '/'.$udom.'/'.$uname;
 4528: }
 4529: 
 4530: # ---------------------------------------------------------- Assign Custom Role
 4531: 
 4532: sub assigncustomrole {
 4533:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4534:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4535:                        $end,$start,$deleteflag);
 4536: }
 4537: 
 4538: # ----------------------------------------------------------------- Revoke Role
 4539: 
 4540: sub revokerole {
 4541:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4542:     my $now=time;
 4543:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4544: }
 4545: 
 4546: # ---------------------------------------------------------- Revoke Custom Role
 4547: 
 4548: sub revokecustomrole {
 4549:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4550:     my $now=time;
 4551:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4552:            $deleteflag);
 4553: }
 4554: 
 4555: # ------------------------------------------------------------ Disk usage
 4556: sub diskusage {
 4557:     my ($udom,$uname,$directoryRoot)=@_;
 4558:     $directoryRoot =~ s/\/$//;
 4559:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4560:     return $listing;
 4561: }
 4562: 
 4563: sub is_locked {
 4564:     my ($file_name, $domain, $user) = @_;
 4565:     my @check;
 4566:     my $is_locked;
 4567:     push @check, $file_name;
 4568:     my %locked = &get('file_permissions',\@check,
 4569: 		      $env{'user.domain'},$env{'user.name'});
 4570:     my ($tmp)=keys(%locked);
 4571:     if ($tmp=~/^error:/) { undef(%locked); }
 4572:     
 4573:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4574:         $is_locked = 'false';
 4575:         foreach my $entry (@{$locked{$file_name}}) {
 4576:            if (ref($entry) eq 'ARRAY') { 
 4577:                $is_locked = 'true';
 4578:                last;
 4579:            }
 4580:        }
 4581:     } else {
 4582:         $is_locked = 'false';
 4583:     }
 4584: }
 4585: 
 4586: # ------------------------------------------------------------- Mark as Read Only
 4587: 
 4588: sub mark_as_readonly {
 4589:     my ($domain,$user,$files,$what) = @_;
 4590:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4591:     my ($tmp)=keys(%current_permissions);
 4592:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4593:     foreach my $file (@{$files}) {
 4594:         push(@{$current_permissions{$file}},$what);
 4595:     }
 4596:     &put('file_permissions',\%current_permissions,$domain,$user);
 4597:     return;
 4598: }
 4599: 
 4600: # ------------------------------------------------------------Save Selected Files
 4601: 
 4602: sub save_selected_files {
 4603:     my ($user, $path, @files) = @_;
 4604:     my $filename = $user."savedfiles";
 4605:     my @other_files = &files_not_in_path($user, $path);
 4606:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4607:     foreach my $file (@files) {
 4608:         print (OUT $env{'form.currentpath'}.$file."\n");
 4609:     }
 4610:     foreach my $file (@other_files) {
 4611:         print (OUT $file."\n");
 4612:     }
 4613:     close (OUT);
 4614:     return 'ok';
 4615: }
 4616: 
 4617: sub clear_selected_files {
 4618:     my ($user) = @_;
 4619:     my $filename = $user."savedfiles";
 4620:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4621:     print (OUT undef);
 4622:     close (OUT);
 4623:     return ("ok");    
 4624: }
 4625: 
 4626: sub files_in_path {
 4627:     my ($user, $path) = @_;
 4628:     my $filename = $user."savedfiles";
 4629:     my %return_files;
 4630:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4631:     while (my $line_in = <IN>) {
 4632:         chomp ($line_in);
 4633:         my @paths_and_file = split (m!/!, $line_in);
 4634:         my $file_part = pop (@paths_and_file);
 4635:         my $path_part = join ('/', @paths_and_file);
 4636:         $path_part.='/';
 4637:         my $path_and_file = $path_part.$file_part;
 4638:         if ($path_part eq $path) {
 4639:             $return_files{$file_part}= 'selected';
 4640:         }
 4641:     }
 4642:     close (IN);
 4643:     return (\%return_files);
 4644: }
 4645: 
 4646: # called in portfolio select mode, to show files selected NOT in current directory
 4647: sub files_not_in_path {
 4648:     my ($user, $path) = @_;
 4649:     my $filename = $user."savedfiles";
 4650:     my @return_files;
 4651:     my $path_part;
 4652:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4653:     while (<IN>) {
 4654:         #ok, I know it's clunky, but I want it to work
 4655:         my @paths_and_file = split m!/!, $_;
 4656:         my $file_part = pop (@paths_and_file);
 4657:         chomp ($file_part);
 4658:         my $path_part = join ('/', @paths_and_file);
 4659:         $path_part .= '/';
 4660:         my $path_and_file = $path_part.$file_part;
 4661:         if ($path_part ne $path) {
 4662:             push (@return_files, ($path_and_file));
 4663:         }
 4664:     }
 4665:     close (OUT);
 4666:     return (@return_files);
 4667: }
 4668: 
 4669: #----------------------------------------------Get portfolio file permissions
 4670: 
 4671: sub get_portfile_permissions {
 4672:     my ($domain,$user) = @_;
 4673:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4674:     my ($tmp)=keys(%current_permissions);
 4675:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4676:     return \%current_permissions;
 4677: }
 4678: 
 4679: #---------------------------------------------Get portfolio file access controls
 4680: 
 4681: sub get_access_controls {
 4682:     my ($current_permissions,$group,$file) = @_;
 4683:     my %access; 
 4684:     if (defined($file)) {
 4685:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 4686:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 4687:                 $access{$file}{$control} = $$current_permissions{$file."\0".$control};
 4688:             }
 4689:         }
 4690:     } else {
 4691:         foreach my $key (keys(%{$current_permissions})) {
 4692:             if ($key =~ /\0accesscontrol$/) {
 4693:                 if (defined($group)) {
 4694:                     if ($key !~ m-^\Q$group\E/-) {
 4695:                         next;
 4696:                     }
 4697:                 }
 4698:                 my ($fullpath) = split(/\0/,$key);
 4699:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 4700:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 4701:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 4702:                     }
 4703:                 }
 4704:             }
 4705:         }
 4706:     }
 4707:     return %access;
 4708: }
 4709: 
 4710: sub parse_access_controls {
 4711:     my ($access_item) = @_;
 4712:     my %content;
 4713:     my $role_id;
 4714:     my $user;
 4715:     my $usercount;
 4716:     my $token;
 4717:     my $parser=HTML::TokeParser->new(\$access_item);
 4718:     while ($token=$parser->get_token) {
 4719:         if ($token->[0] eq 'S')  {
 4720:             my $entry=$token->[1];
 4721:             if ($entry eq 'scope') {
 4722:                 my $type = $token->[2]{'type'};
 4723:                 if (($type eq 'course') || ($type eq 'group')) {
 4724:                     $content{'roles'} = {};
 4725:                 }
 4726:             } elsif ($entry eq 'roles') {
 4727:                 $role_id = $token->[2]{id};
 4728: 		$content{$entry}{$role_id} = {
 4729: 		                                 role => [],
 4730:                                                  access => [],
 4731:                                                  section => [],
 4732:                                                  group => [],
 4733:                                              };
 4734:             } elsif ($entry eq 'users') {
 4735:                 $content{'users'} = {};
 4736:                 $usercount = 0;
 4737:             } elsif ($entry eq 'user') {
 4738:                 $user = '';
 4739:             } else {
 4740:                 my $value=$parser->get_text('/'.$entry);
 4741:                 if ($entry eq 'uname') {
 4742:                     $user = $value;
 4743:                 } elsif ($entry eq 'udom') {
 4744:                     $user .= ':'.$value;
 4745:                     $content{'users'}{$user} = $usercount;
 4746:                 } elsif ($entry eq 'role' ||
 4747:                     $entry eq 'access' ||
 4748:                     $entry eq 'section' ||
 4749:                     $entry eq 'group') {
 4750:                     if ($role_id ne '') {
 4751:                         push(@{$content{'roles'}{$role_id}{$entry}},$value);
 4752:                     }
 4753:                 } elsif ($entry eq 'dom') {
 4754:                     push(@{$content{$entry}},$value);
 4755:                 } else {
 4756:                     $content{$entry}=$value;
 4757:                 }
 4758:             }
 4759:         } elsif ($token->[0] eq 'E') {
 4760:             if ($token->[1] eq 'user') {
 4761:                 $user = '';
 4762:                 $usercount ++;
 4763:             } elsif ($token->[1] eq 'roles') {
 4764:                 $role_id = '';
 4765:             }
 4766:         }
 4767:     }
 4768:     return %content;
 4769: }
 4770: 
 4771: sub modify_access_controls {
 4772:     my ($file_name,$changes,$domain,$user)=@_;
 4773:     my ($outcome,$deloutcome);
 4774:     my %store_permissions;
 4775:     my %new_values;
 4776:     my %new_control;
 4777:     my %translation;
 4778:     my @deletions = ();
 4779:     my $now = time;
 4780:     if (exists($$changes{'activate'})) {
 4781:         if (ref($$changes{'activate'}) eq 'HASH') {
 4782:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 4783:             my $numnew = scalar(@newitems);
 4784:             for (my $i=0; $i<$numnew; $i++) {
 4785:                 my $newkey = $newitems[$i];
 4786:                 my $newid = &Apache::loncommon::get_cgi_id();
 4787:                 $newkey =~ s/^(\d+)/$newid/;
 4788:                 $translation{$1} = $newid;
 4789:                 $new_values{$file_name."\0".$newkey} = 
 4790:                                           $$changes{'activate'}{$newitems[$i]};
 4791:                 $new_control{$newkey} = $now;
 4792:             }
 4793:         }
 4794:     }
 4795:     my %todelete;
 4796:     my %changed_items;
 4797:     foreach my $action ('delete','update') {
 4798:         if (exists($$changes{$action})) {
 4799:             if (ref($$changes{$action}) eq 'HASH') {
 4800:                 foreach my $key (keys(%{$$changes{$action}})) {
 4801:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 4802:                     if ($action eq 'delete') { 
 4803:                         $todelete{$itemnum} = 1;
 4804:                     } else {
 4805:                         $changed_items{$itemnum} = $key;
 4806:                     }
 4807:                 }
 4808:             }
 4809:         }
 4810:     }
 4811:     # get lock on access controls for file.
 4812:     my $lockhash = {
 4813:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 4814:                                                        ':'.$env{'user.domain'},
 4815:                    }; 
 4816:     my $tries = 0;
 4817:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 4818:    
 4819:     while (($gotlock ne 'ok') && $tries <3) {
 4820:         $tries ++;
 4821:         sleep 1;
 4822:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 4823:     }
 4824:     if ($gotlock eq 'ok') {
 4825:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 4826:         my ($tmp)=keys(%curr_permissions);
 4827:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 4828:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 4829:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 4830:             if (ref($curr_controls) eq 'HASH') {
 4831:                 foreach my $control_item (keys(%{$curr_controls})) {
 4832:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 4833:                     if (defined($todelete{$itemnum})) {
 4834:                         push(@deletions,$file_name."\0".$control_item);
 4835:                     } else {
 4836:                         if (defined($changed_items{$itemnum})) {
 4837:                             $new_control{$changed_items{$itemnum}} = $now;
 4838:                             push(@deletions,$file_name."\0".$control_item);
 4839:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 4840:                         } else {
 4841:                             $new_control{$control_item} = $$curr_controls{$control_item};
 4842:                         }
 4843:                     }
 4844:                 }
 4845:             }
 4846:         }
 4847:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 4848:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 4849:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 4850:         #  remove lock
 4851:         my @del_lock = ($file_name."\0".'locked_access_records');
 4852:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 4853:     } else {
 4854:         $outcome = "error: could not obtain lockfile\n";  
 4855:     }
 4856:     return ($outcome,$deloutcome,\%new_values,\%translation);
 4857: }
 4858: 
 4859: #------------------------------------------------------Get Marked as Read Only
 4860: 
 4861: sub get_marked_as_readonly {
 4862:     my ($domain,$user,$what,$group) = @_;
 4863:     my $current_permissions = &get_portfile_permissions($domain,$user);
 4864:     my @readonly_files;
 4865:     my $cmp1=$what;
 4866:     if (ref($what)) { $cmp1=join('',@{$what}) };
 4867:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 4868:         if (defined($group)) {
 4869:             if ($file_name !~ m-^\Q$group\E/-) {
 4870:                 next;
 4871:             }
 4872:         }
 4873:         if (ref($value) eq "ARRAY"){
 4874:             foreach my $stored_what (@{$value}) {
 4875:                 my $cmp2=$stored_what;
 4876:                 if (ref($stored_what eq 'ARRAY')) {
 4877:                     $cmp2=join('',@{$stored_what});
 4878:                 }
 4879:                 if ($cmp1 eq $cmp2) {
 4880:                     push(@readonly_files, $file_name);
 4881:                     last;
 4882:                 } elsif (!defined($what)) {
 4883:                     push(@readonly_files, $file_name);
 4884:                     last;
 4885:                 }
 4886:             }
 4887:         }
 4888:     }
 4889:     return @readonly_files;
 4890: }
 4891: #-----------------------------------------------------------Get Marked as Read Only Hash
 4892: 
 4893: sub get_marked_as_readonly_hash {
 4894:     my ($current_permissions,$group,$what) = @_;
 4895:     my %readonly_files;
 4896:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 4897:         if (defined($group)) {
 4898:             if ($file_name !~ m-^\Q$group\E/-) {
 4899:                 next;
 4900:             }
 4901:         }
 4902:         if (ref($value) eq "ARRAY"){
 4903:             foreach my $stored_what (@{$value}) {
 4904:                 if (ref($stored_what) eq 'ARRAY') {
 4905:                     foreach my $lock_descriptor(@{$stored_what}) {
 4906:                         if ($lock_descriptor eq 'graded') {
 4907:                             $readonly_files{$file_name} = 'graded';
 4908:                         } elsif ($lock_descriptor eq 'handback') {
 4909:                             $readonly_files{$file_name} = 'handback';
 4910:                         } else {
 4911:                             if (!exists($readonly_files{$file_name})) {
 4912:                                 $readonly_files{$file_name} = 'locked';
 4913:                             }
 4914:                         }
 4915:                     }
 4916:                 } 
 4917:             }
 4918:         } 
 4919:     }
 4920:     return %readonly_files;
 4921: }
 4922: # ------------------------------------------------------------ Unmark as Read Only
 4923: 
 4924: sub unmark_as_readonly {
 4925:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 4926:     # for portfolio submissions, $what contains [$symb,$crsid] 
 4927:     my ($domain,$user,$what,$file_name,$group) = @_;
 4928:     my $symb_crs = $what;
 4929:     if (ref($what)) { $symb_crs=join('',@$what); }
 4930:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 4931:     my ($tmp)=keys(%current_permissions);
 4932:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4933:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 4934:     foreach my $file (@readonly_files) {
 4935: 	if (defined($file_name) && ($file_name ne $file)) { next; }
 4936: 	my $current_locks = $current_permissions{$file};
 4937:         my @new_locks;
 4938:         my @del_keys;
 4939:         if (ref($current_locks) eq "ARRAY"){
 4940:             foreach my $locker (@{$current_locks}) {
 4941:                 my $compare=$locker;
 4942:                 if (ref($locker) eq 'ARRAY') {
 4943:                     $compare=join('',@{$locker});
 4944:                     if ($compare ne $symb_crs) {
 4945:                         push(@new_locks, $locker);
 4946:                     }
 4947:                 }
 4948:             }
 4949:             if (scalar(@new_locks) > 0) {
 4950:                 $current_permissions{$file} = \@new_locks;
 4951:             } else {
 4952:                 push(@del_keys, $file);
 4953:                 &del('file_permissions',\@del_keys, $domain, $user);
 4954:                 delete($current_permissions{$file});
 4955:             }
 4956:         }
 4957:     }
 4958:     &put('file_permissions',\%current_permissions,$domain,$user);
 4959:     return;
 4960: }
 4961: 
 4962: # ------------------------------------------------------------ Directory lister
 4963: 
 4964: sub dirlist {
 4965:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 4966: 
 4967:     $uri=~s/^\///;
 4968:     $uri=~s/\/$//;
 4969:     my ($udom, $uname);
 4970:     (undef,$udom,$uname)=split(/\//,$uri);
 4971:     if(defined($userdomain)) {
 4972:         $udom = $userdomain;
 4973:     }
 4974:     if(defined($username)) {
 4975:         $uname = $username;
 4976:     }
 4977: 
 4978:     my $dirRoot = $perlvar{'lonDocRoot'};
 4979:     if(defined($alternateDirectoryRoot)) {
 4980:         $dirRoot = $alternateDirectoryRoot;
 4981:         $dirRoot =~ s/\/$//;
 4982:     }
 4983: 
 4984:     if($udom) {
 4985:         if($uname) {
 4986:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 4987:                               homeserver($uname,$udom));
 4988:             my @listing_results;
 4989:             if ($listing eq 'unknown_cmd') {
 4990:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4991:                                homeserver($uname,$udom));
 4992:                 @listing_results = split(/:/,$listing);
 4993:             } else {
 4994:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 4995:             }
 4996:             return @listing_results;
 4997:         } elsif(!defined($alternateDirectoryRoot)) {
 4998:             my $tryserver;
 4999:             my %allusers=();
 5000:             foreach $tryserver (keys %libserv) {
 5001:                 if($hostdom{$tryserver} eq $udom) {
 5002:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5003:                                       $udom, $tryserver);
 5004:                     my @listing_results;
 5005:                     if ($listing eq 'unknown_cmd') {
 5006:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5007:                                        $udom, $tryserver);
 5008:                         @listing_results = split(/:/,$listing);
 5009:                     } else {
 5010:                         @listing_results =
 5011:                             map { &unescape($_); } split(/:/,$listing);
 5012:                     }
 5013:                     if ($listing_results[0] ne 'no_such_dir' && 
 5014:                         $listing_results[0] ne 'empty'       &&
 5015:                         $listing_results[0] ne 'con_lost') {
 5016:                         foreach (@listing_results) {
 5017:                             my ($entry,@stat)=split(/&/,$_);
 5018:                             $allusers{$entry}=1;
 5019:                         }
 5020:                     }
 5021:                 }
 5022:             }
 5023:             my $alluserstr='';
 5024:             foreach (sort keys %allusers) {
 5025:                 $alluserstr.=$_.'&user:';
 5026:             }
 5027:             $alluserstr=~s/:$//;
 5028:             return split(/:/,$alluserstr);
 5029:         } else {
 5030:             my @emptyResults = ();
 5031:             push(@emptyResults, 'missing user name');
 5032:             return split(':',@emptyResults);
 5033:         }
 5034:     } elsif(!defined($alternateDirectoryRoot)) {
 5035:         my $tryserver;
 5036:         my %alldom=();
 5037:         foreach $tryserver (keys %libserv) {
 5038:             $alldom{$hostdom{$tryserver}}=1;
 5039:         }
 5040:         my $alldomstr='';
 5041:         foreach (sort keys %alldom) {
 5042:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 5043:         }
 5044:         $alldomstr=~s/:$//;
 5045:         return split(/:/,$alldomstr);       
 5046:     } else {
 5047:         my @emptyResults = ();
 5048:         push(@emptyResults, 'missing domain');
 5049:         return split(':',@emptyResults);
 5050:     }
 5051: }
 5052: 
 5053: # --------------------------------------------- GetFileTimestamp
 5054: # This function utilizes dirlist and returns the date stamp for
 5055: # when it was last modified.  It will also return an error of -1
 5056: # if an error occurs
 5057: 
 5058: ##
 5059: ## FIXME: This subroutine assumes its caller knows something about the
 5060: ## directory structure of the home server for the student ($root).
 5061: ## Not a good assumption to make.  Since this is for looking up files
 5062: ## in user directories, the full path should be constructed by lond, not
 5063: ## whatever machine we request data from.
 5064: ##
 5065: sub GetFileTimestamp {
 5066:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5067:     $studentDomain=~s/\W//g;
 5068:     $studentName=~s/\W//g;
 5069:     my $subdir=$studentName.'__';
 5070:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5071:     my $proname="$studentDomain/$subdir/$studentName";
 5072:     $proname .= '/'.$filename;
 5073:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5074:                                               $studentName, $root);
 5075:     my @stats = split('&', $fileStat);
 5076:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5077:         # @stats contains first the filename, then the stat output
 5078:         return $stats[10]; # so this is 10 instead of 9.
 5079:     } else {
 5080:         return -1;
 5081:     }
 5082: }
 5083: 
 5084: sub stat_file {
 5085:     my ($uri) = @_;
 5086:     $uri = &clutter($uri);
 5087: 
 5088:     # we want just the url part without the unneeded accessor url bits
 5089:     if ($uri =~ m-^/adm/-) {
 5090: 	$uri=~s-^/adm/wrapper/-/-;
 5091: 	$uri=~s-^/adm/coursedocs/showdoc/-/-;
 5092:     }
 5093:     my ($udom,$uname,$file,$dir);
 5094:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5095: 	($udom,$uname,$file) =
 5096: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5097: 	$file = 'userfiles/'.$file;
 5098: 	$dir = &propath($udom,$uname);
 5099:     }
 5100:     if ($uri =~ m-^/res/-) {
 5101: 	($udom,$uname) = 
 5102: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5103: 	$file = $uri;
 5104:     }
 5105: 
 5106:     if (!$udom || !$uname || !$file) {
 5107: 	# unable to handle the uri
 5108: 	return ();
 5109:     }
 5110: 
 5111:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5112:     my @stats = split('&', $result);
 5113:     
 5114:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5115: 	shift(@stats); #filename is first
 5116: 	return @stats;
 5117:     }
 5118:     return ();
 5119: }
 5120: 
 5121: # -------------------------------------------------------- Value of a Condition
 5122: 
 5123: # gets the value of a specific preevaluated condition
 5124: #    stored in the string  $env{user.state.<cid>}
 5125: # or looks up a condition reference in the bighash and if if hasn't
 5126: # already been evaluated recurses into docondval to get the value of
 5127: # the condition, then memoizing it to 
 5128: #   $env{user.state.<cid>.<condition>}
 5129: sub directcondval {
 5130:     my $number=shift;
 5131:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5132: 	&Apache::lonuserstate::evalstate();
 5133:     }
 5134:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5135: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5136:     } elsif ($number =~ /^_/) {
 5137: 	my $sub_condition;
 5138: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5139: 		&GDBM_READER(),0640)) {
 5140: 	    $sub_condition=$bighash{'conditions'.$number};
 5141: 	    untie(%bighash);
 5142: 	}
 5143: 	my $value = &docondval($sub_condition);
 5144: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5145: 	return $value;
 5146:     }
 5147:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5148:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5149:     } else {
 5150:        return 2;
 5151:     }
 5152: }
 5153: 
 5154: # get the collection of conditions for this resource
 5155: sub condval {
 5156:     my $condidx=shift;
 5157:     my $allpathcond='';
 5158:     foreach my $cond (split(/\|/,$condidx)) {
 5159: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5160: 	    $allpathcond.=
 5161: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5162: 	}
 5163:     }
 5164:     $allpathcond=~s/\|$//;
 5165:     return &docondval($allpathcond);
 5166: }
 5167: 
 5168: #evaluates an expression of conditions
 5169: sub docondval {
 5170:     my ($allpathcond) = @_;
 5171:     my $result=0;
 5172:     if ($env{'request.course.id'}
 5173: 	&& defined($allpathcond)) {
 5174: 	my $operand='|';
 5175: 	my @stack;
 5176: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5177: 	    if ($chunk eq '(') {
 5178: 		push @stack,($operand,$result);
 5179: 	    } elsif ($chunk eq ')') {
 5180: 		my $before=pop @stack;
 5181: 		if (pop @stack eq '&') {
 5182: 		    $result=$result>$before?$before:$result;
 5183: 		} else {
 5184: 		    $result=$result>$before?$result:$before;
 5185: 		}
 5186: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5187: 		$operand=$chunk;
 5188: 	    } else {
 5189: 		my $new=directcondval($chunk);
 5190: 		if ($operand eq '&') {
 5191: 		    $result=$result>$new?$new:$result;
 5192: 		} else {
 5193: 		    $result=$result>$new?$result:$new;
 5194: 		}
 5195: 	    }
 5196: 	}
 5197:     }
 5198:     return $result;
 5199: }
 5200: 
 5201: # ---------------------------------------------------- Devalidate courseresdata
 5202: 
 5203: sub devalidatecourseresdata {
 5204:     my ($coursenum,$coursedomain)=@_;
 5205:     my $hashid=$coursenum.':'.$coursedomain;
 5206:     &devalidate_cache_new('courseres',$hashid);
 5207: }
 5208: 
 5209: # --------------------------------------------------- Course Resourcedata Query
 5210: 
 5211: sub get_courseresdata {
 5212:     my ($coursenum,$coursedomain)=@_;
 5213:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5214:     my $hashid=$coursenum.':'.$coursedomain;
 5215:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5216:     my %dumpreply;
 5217:     unless (defined($cached)) {
 5218: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5219: 	$result=\%dumpreply;
 5220: 	my ($tmp) = keys(%dumpreply);
 5221: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5222: 	    &do_cache_new('courseres',$hashid,$result,600);
 5223: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5224: 	    return $tmp;
 5225: 	} elsif ($tmp =~ /^(error)/) {
 5226: 	    $result=undef;
 5227: 	    &do_cache_new('courseres',$hashid,$result,600);
 5228: 	}
 5229:     }
 5230:     return $result;
 5231: }
 5232: 
 5233: sub devalidateuserresdata {
 5234:     my ($uname,$udom)=@_;
 5235:     my $hashid="$udom:$uname";
 5236:     &devalidate_cache_new('userres',$hashid);
 5237: }
 5238: 
 5239: sub get_userresdata {
 5240:     my ($uname,$udom)=@_;
 5241:     #most student don\'t have any data set, check if there is some data
 5242:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5243: 
 5244:     my $hashid="$udom:$uname";
 5245:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5246:     if (!defined($cached)) {
 5247: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5248: 	$result=\%resourcedata;
 5249: 	&do_cache_new('userres',$hashid,$result,600);
 5250:     }
 5251:     my ($tmp)=keys(%$result);
 5252:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5253: 	return $result;
 5254:     }
 5255:     #error 2 occurs when the .db doesn't exist
 5256:     if ($tmp!~/error: 2 /) {
 5257: 	&logthis("<font color=\"blue\">WARNING:".
 5258: 		 " Trying to get resource data for ".
 5259: 		 $uname." at ".$udom.": ".
 5260: 		 $tmp."</font>");
 5261:     } elsif ($tmp=~/error: 2 /) {
 5262: 	#&EXT_cache_set($udom,$uname);
 5263: 	&do_cache_new('userres',$hashid,undef,600);
 5264: 	undef($tmp); # not really an error so don't send it back
 5265:     }
 5266:     return $tmp;
 5267: }
 5268: 
 5269: sub resdata {
 5270:     my ($name,$domain,$type,@which)=@_;
 5271:     my $result;
 5272:     if ($type eq 'course') {
 5273: 	$result=&get_courseresdata($name,$domain);
 5274:     } elsif ($type eq 'user') {
 5275: 	$result=&get_userresdata($name,$domain);
 5276:     }
 5277:     if (!ref($result)) { return $result; }    
 5278:     foreach my $item (@which) {
 5279: 	if (defined($result->{$item})) {
 5280: 	    return $result->{$item};
 5281: 	}
 5282:     }
 5283:     return undef;
 5284: }
 5285: 
 5286: #
 5287: # EXT resource caching routines
 5288: #
 5289: 
 5290: sub clear_EXT_cache_status {
 5291:     &delenv('cache.EXT.');
 5292: }
 5293: 
 5294: sub EXT_cache_status {
 5295:     my ($target_domain,$target_user) = @_;
 5296:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5297:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5298:         # We know already the user has no data
 5299:         return 1;
 5300:     } else {
 5301:         return 0;
 5302:     }
 5303: }
 5304: 
 5305: sub EXT_cache_set {
 5306:     my ($target_domain,$target_user) = @_;
 5307:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5308:     #&appenv($cachename => time);
 5309: }
 5310: 
 5311: # --------------------------------------------------------- Value of a Variable
 5312: sub EXT {
 5313: 
 5314:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5315:     unless ($varname) { return ''; }
 5316:     #get real user name/domain, courseid and symb
 5317:     my $courseid;
 5318:     my $publicuser;
 5319:     if ($symbparm) {
 5320: 	$symbparm=&get_symb_from_alias($symbparm);
 5321:     }
 5322:     if (!($uname && $udom)) {
 5323:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 5324: 	  &Apache::lonxml::whichuser($symbparm);
 5325:       if (!$symbparm) {	$symbparm=$cursymb; }
 5326:     } else {
 5327: 	$courseid=$env{'request.course.id'};
 5328:     }
 5329:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5330:     my $rest;
 5331:     if (defined($therest[0])) {
 5332:        $rest=join('.',@therest);
 5333:     } else {
 5334:        $rest='';
 5335:     }
 5336: 
 5337:     my $qualifierrest=$qualifier;
 5338:     if ($rest) { $qualifierrest.='.'.$rest; }
 5339:     my $spacequalifierrest=$space;
 5340:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5341:     if ($realm eq 'user') {
 5342: # --------------------------------------------------------------- user.resource
 5343: 	if ($space eq 'resource') {
 5344: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5345: 		  || defined($Apache::lonhomework::parsing_a_task))
 5346: 		 &&
 5347: 		 ($symbparm eq &symbread()) ) {	
 5348: 		# if we are in the middle of processing the resource the
 5349: 		# get the value we are planning on committing
 5350:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5351:                     return $Apache::lonhomework::results{$qualifierrest};
 5352:                 } else {
 5353:                     return $Apache::lonhomework::history{$qualifierrest};
 5354:                 }
 5355: 	    } else {
 5356: 		my %restored;
 5357: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5358: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5359: 		} else {
 5360: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5361: 		}
 5362: 		return $restored{$qualifierrest};
 5363: 	    }
 5364: # ----------------------------------------------------------------- user.access
 5365:         } elsif ($space eq 'access') {
 5366: 	    # FIXME - not supporting calls for a specific user
 5367:             return &allowed($qualifier,$rest);
 5368: # ------------------------------------------ user.preferences, user.environment
 5369:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5370: 	    if (($uname eq $env{'user.name'}) &&
 5371: 		($udom eq $env{'user.domain'})) {
 5372: 		return $env{join('.',('environment',$qualifierrest))};
 5373: 	    } else {
 5374: 		my %returnhash;
 5375: 		if (!$publicuser) {
 5376: 		    %returnhash=&userenvironment($udom,$uname,
 5377: 						 $qualifierrest);
 5378: 		}
 5379: 		return $returnhash{$qualifierrest};
 5380: 	    }
 5381: # ----------------------------------------------------------------- user.course
 5382:         } elsif ($space eq 'course') {
 5383: 	    # FIXME - not supporting calls for a specific user
 5384:             return $env{join('.',('request.course',$qualifier))};
 5385: # ------------------------------------------------------------------- user.role
 5386:         } elsif ($space eq 'role') {
 5387: 	    # FIXME - not supporting calls for a specific user
 5388:             my ($role,$where)=split(/\./,$env{'request.role'});
 5389:             if ($qualifier eq 'value') {
 5390: 		return $role;
 5391:             } elsif ($qualifier eq 'extent') {
 5392:                 return $where;
 5393:             }
 5394: # ----------------------------------------------------------------- user.domain
 5395:         } elsif ($space eq 'domain') {
 5396:             return $udom;
 5397: # ------------------------------------------------------------------- user.name
 5398:         } elsif ($space eq 'name') {
 5399:             return $uname;
 5400: # ---------------------------------------------------- Any other user namespace
 5401:         } else {
 5402: 	    my %reply;
 5403: 	    if (!$publicuser) {
 5404: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5405: 	    }
 5406: 	    return $reply{$qualifierrest};
 5407:         }
 5408:     } elsif ($realm eq 'query') {
 5409: # ---------------------------------------------- pull stuff out of query string
 5410:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5411: 						[$spacequalifierrest]);
 5412: 	return $env{'form.'.$spacequalifierrest}; 
 5413:    } elsif ($realm eq 'request') {
 5414: # ------------------------------------------------------------- request.browser
 5415:         if ($space eq 'browser') {
 5416: 	    if ($qualifier eq 'textremote') {
 5417: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5418: 		    return 1;
 5419: 		} else {
 5420: 		    return 0;
 5421: 		}
 5422: 	    } else {
 5423: 		return $env{'browser.'.$qualifier};
 5424: 	    }
 5425: # ------------------------------------------------------------ request.filename
 5426:         } else {
 5427:             return $env{'request.'.$spacequalifierrest};
 5428:         }
 5429:     } elsif ($realm eq 'course') {
 5430: # ---------------------------------------------------------- course.description
 5431:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5432:     } elsif ($realm eq 'resource') {
 5433: 
 5434: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5435: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5436: 	}
 5437: 
 5438: 	if ($space eq 'title') {
 5439: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5440: 	    return &gettitle($symbparm);
 5441: 	}
 5442: 	
 5443: 	if ($space eq 'map') {
 5444: 	    my ($map) = &decode_symb($symbparm);
 5445: 	    return &symbread($map);
 5446: 	}
 5447: 
 5448: 	my ($section, $group, @groups);
 5449: 	my ($courselevelm,$courselevel);
 5450: 	if ($symbparm && defined($courseid) && 
 5451: 	    $courseid eq $env{'request.course.id'}) {
 5452: 
 5453: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5454: 
 5455: # ----------------------------------------------------- Cascading lookup scheme
 5456: 	    my $symbp=$symbparm;
 5457: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5458: 
 5459: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5460: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5461: 
 5462: 	    if (($env{'user.name'} eq $uname) &&
 5463: 		($env{'user.domain'} eq $udom)) {
 5464: 		$section=$env{'request.course.sec'};
 5465:                 @groups = split(/:/,$env{'request.course.groups'});  
 5466:                 @groups=&sort_course_groups($courseid,@groups); 
 5467: 	    } else {
 5468: 		if (! defined($usection)) {
 5469: 		    $section=&getsection($udom,$uname,$courseid);
 5470: 		} else {
 5471: 		    $section = $usection;
 5472: 		}
 5473:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5474: 	    }
 5475: 
 5476: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5477: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5478: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5479: 
 5480: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5481: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5482: 	    $courselevelm=$courseid.'.'.$mapparm;
 5483: 
 5484: # ----------------------------------------------------------- first, check user
 5485: 
 5486: 	    my $userreply=&resdata($uname,$udom,'user',
 5487: 				       ($courselevelr,$courselevelm,
 5488: 					$courselevel));
 5489: 	    if (defined($userreply)) { return $userreply; }
 5490: 
 5491: # ------------------------------------------------ second, check some of course
 5492:             my $coursereply;
 5493:             if (@groups > 0) {
 5494:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5495:                                        $mapparm,$spacequalifierrest);
 5496:                 if (defined($coursereply)) { return $coursereply; }
 5497:             }
 5498: 
 5499: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5500: 				     $env{'course.'.$courseid.'.domain'},
 5501: 				     'course',
 5502: 				     ($seclevelr,$seclevelm,$seclevel,
 5503: 				      $courselevelr));
 5504: 	    if (defined($coursereply)) { return $coursereply; }
 5505: 
 5506: # ------------------------------------------------------ third, check map parms
 5507: 	    my %parmhash=();
 5508: 	    my $thisparm='';
 5509: 	    if (tie(%parmhash,'GDBM_File',
 5510: 		    $env{'request.course.fn'}.'_parms.db',
 5511: 		    &GDBM_READER(),0640)) {
 5512: 		$thisparm=$parmhash{$symbparm};
 5513: 		untie(%parmhash);
 5514: 	    }
 5515: 	    if ($thisparm) { return $thisparm; }
 5516: 	}
 5517: # ------------------------------------------ fourth, look in resource metadata
 5518: 
 5519: 	$spacequalifierrest=~s/\./\_/;
 5520: 	my $filename;
 5521: 	if (!$symbparm) { $symbparm=&symbread(); }
 5522: 	if ($symbparm) {
 5523: 	    $filename=(&decode_symb($symbparm))[2];
 5524: 	} else {
 5525: 	    $filename=$env{'request.filename'};
 5526: 	}
 5527: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5528: 	if (defined($metadata)) { return $metadata; }
 5529: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5530: 	if (defined($metadata)) { return $metadata; }
 5531: 
 5532: # ---------------------------------------------- fourth, look in rest pf course
 5533: 	if ($symbparm && defined($courseid) && 
 5534: 	    $courseid eq $env{'request.course.id'}) {
 5535: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5536: 				     $env{'course.'.$courseid.'.domain'},
 5537: 				     'course',
 5538: 				     ($courselevelm,$courselevel));
 5539: 	    if (defined($coursereply)) { return $coursereply; }
 5540: 	}
 5541: # ------------------------------------------------------------------ Cascade up
 5542: 	unless ($space eq '0') {
 5543: 	    my @parts=split(/_/,$space);
 5544: 	    my $id=pop(@parts);
 5545: 	    my $part=join('_',@parts);
 5546: 	    if ($part eq '') { $part='0'; }
 5547: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5548: 				 $symbparm,$udom,$uname,$section,1);
 5549: 	    if (defined($partgeneral)) { return $partgeneral; }
 5550: 	}
 5551: 	if ($recurse) { return undef; }
 5552: 	my $pack_def=&packages_tab_default($filename,$varname);
 5553: 	if (defined($pack_def)) { return $pack_def; }
 5554: 
 5555: # ---------------------------------------------------- Any other user namespace
 5556:     } elsif ($realm eq 'environment') {
 5557: # ----------------------------------------------------------------- environment
 5558: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5559: 	    return $env{'environment.'.$spacequalifierrest};
 5560: 	} else {
 5561: 	    my %returnhash=&userenvironment($udom,$uname,
 5562: 					    $spacequalifierrest);
 5563: 	    return $returnhash{$spacequalifierrest};
 5564: 	}
 5565:     } elsif ($realm eq 'system') {
 5566: # ----------------------------------------------------------------- system.time
 5567: 	if ($space eq 'time') {
 5568: 	    return time;
 5569:         }
 5570:     } elsif ($realm eq 'server') {
 5571: # ----------------------------------------------------------------- system.time
 5572: 	if ($space eq 'name') {
 5573: 	    return $ENV{'SERVER_NAME'};
 5574:         }
 5575:     }
 5576:     return '';
 5577: }
 5578: 
 5579: sub check_group_parms {
 5580:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5581:     my @groupitems = ();
 5582:     my $resultitem;
 5583:     my @levels = ($symbparm,$mapparm,$what);
 5584:     foreach my $group (@{$groups}) {
 5585:         foreach my $level (@levels) {
 5586:              my $item = $courseid.'.['.$group.'].'.$level;
 5587:              push(@groupitems,$item);
 5588:         }
 5589:     }
 5590:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5591:                             $env{'course.'.$courseid.'.domain'},
 5592:                                      'course',@groupitems);
 5593:     return $coursereply;
 5594: }
 5595: 
 5596: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5597:     my ($courseid,@groups) = @_;
 5598:     @groups = sort(@groups);
 5599:     return @groups;
 5600: }
 5601: 
 5602: sub packages_tab_default {
 5603:     my ($uri,$varname)=@_;
 5604:     my (undef,$part,$name)=split(/\./,$varname);
 5605: 
 5606:     my (@extension,@specifics,$do_default);
 5607:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5608: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5609: 	if ($pack_type eq 'default') {
 5610: 	    $do_default=1;
 5611: 	} elsif ($pack_type eq 'extension') {
 5612: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5613: 	} else {
 5614: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5615: 	}
 5616:     }
 5617:     # first look for a package that matches the requested part id
 5618:     foreach my $package (@specifics) {
 5619: 	my (undef,$pack_type,$pack_part)=@{$package};
 5620: 	next if ($pack_part ne $part);
 5621: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5622: 	    return $packagetab{"$pack_type&$name&default"};
 5623: 	}
 5624:     }
 5625:     # look for any possible matching non extension_ package
 5626:     foreach my $package (@specifics) {
 5627: 	my (undef,$pack_type,$pack_part)=@{$package};
 5628: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5629: 	    return $packagetab{"$pack_type&$name&default"};
 5630: 	}
 5631: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5632: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5633: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5634: 	}
 5635:     }
 5636:     # look for any posible extension_ match
 5637:     foreach my $package (@extension) {
 5638: 	my ($package,$pack_type)=@{$package};
 5639: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5640: 	    return $packagetab{"$pack_type&$name&default"};
 5641: 	}
 5642: 	if (defined($packagetab{$package."&$name&default"})) {
 5643: 	    return $packagetab{$package."&$name&default"};
 5644: 	}
 5645:     }
 5646:     # look for a global default setting
 5647:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5648: 	return $packagetab{"default&$name&default"};
 5649:     }
 5650:     return undef;
 5651: }
 5652: 
 5653: sub add_prefix_and_part {
 5654:     my ($prefix,$part)=@_;
 5655:     my $keyroot;
 5656:     if (defined($prefix) && $prefix !~ /^__/) {
 5657: 	# prefix that has a part already
 5658: 	$keyroot=$prefix;
 5659:     } elsif (defined($prefix)) {
 5660: 	# prefix that is missing a part
 5661: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5662:     } else {
 5663: 	# no prefix at all
 5664: 	if (defined($part)) { $keyroot='_'.$part; }
 5665:     }
 5666:     return $keyroot;
 5667: }
 5668: 
 5669: # ---------------------------------------------------------------- Get metadata
 5670: 
 5671: my %metaentry;
 5672: sub metadata {
 5673:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5674:     $uri=&declutter($uri);
 5675:     # if it is a non metadata possible uri return quickly
 5676:     if (($uri eq '') || 
 5677: 	(($uri =~ m|^/*adm/|) && 
 5678: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5679:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5680: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5681: 	return undef;
 5682:     }
 5683:     my $filename=$uri;
 5684:     $uri=~s/\.meta$//;
 5685: #
 5686: # Is the metadata already cached?
 5687: # Look at timestamp of caching
 5688: # Everything is cached by the main uri, libraries are never directly cached
 5689: #
 5690:     if (!defined($liburi)) {
 5691: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5692: 	if (defined($cached)) { return $result->{':'.$what}; }
 5693:     }
 5694:     {
 5695: #
 5696: # Is this a recursive call for a library?
 5697: #
 5698: #	if (! exists($metacache{$uri})) {
 5699: #	    $metacache{$uri}={};
 5700: #	}
 5701:         if ($liburi) {
 5702: 	    $liburi=&declutter($liburi);
 5703:             $filename=$liburi;
 5704:         } else {
 5705: 	    &devalidate_cache_new('meta',$uri);
 5706: 	    undef(%metaentry);
 5707: 	}
 5708:         my %metathesekeys=();
 5709:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5710: 	my $metastring;
 5711: 	if ($uri !~ m -^(uploaded|editupload)/-) {
 5712: 	    my $file=&filelocation('',&clutter($filename));
 5713: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5714: 	    $metastring=&getfile($file);
 5715: 	}
 5716:         my $parser=HTML::LCParser->new(\$metastring);
 5717:         my $token;
 5718:         undef %metathesekeys;
 5719:         while ($token=$parser->get_token) {
 5720: 	    if ($token->[0] eq 'S') {
 5721: 		if (defined($token->[2]->{'package'})) {
 5722: #
 5723: # This is a package - get package info
 5724: #
 5725: 		    my $package=$token->[2]->{'package'};
 5726: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5727: 		    if (defined($token->[2]->{'id'})) { 
 5728: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5729: 		    }
 5730: 		    if ($metaentry{':packages'}) {
 5731: 			$metaentry{':packages'}.=','.$package.$keyroot;
 5732: 		    } else {
 5733: 			$metaentry{':packages'}=$package.$keyroot;
 5734: 		    }
 5735: 		    foreach my $pack_entry (keys(%packagetab)) {
 5736: 			my $part=$keyroot;
 5737: 			$part=~s/^\_//;
 5738: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 5739: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 5740: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 5741: 			    # ignore package.tab specified default values
 5742:                             # here &package_tab_default() will fetch those
 5743: 			    if ($subp eq 'default') { next; }
 5744: 			    my $value=$packagetab{$pack_entry};
 5745: 			    my $unikey;
 5746: 			    if ($pack =~ /_0$/) {
 5747: 				$unikey='parameter_0_'.$name;
 5748: 				$part=0;
 5749: 			    } else {
 5750: 				$unikey='parameter'.$keyroot.'_'.$name;
 5751: 			    }
 5752: 			    if ($subp eq 'display') {
 5753: 				$value.=' [Part: '.$part.']';
 5754: 			    }
 5755: 			    $metaentry{':'.$unikey.'.part'}=$part;
 5756: 			    $metathesekeys{$unikey}=1;
 5757: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5758: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 5759: 			    }
 5760: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 5761: 				$metaentry{':'.$unikey}=
 5762: 				    $metaentry{':'.$unikey.'.default'};
 5763: 			    }
 5764: 			}
 5765: 		    }
 5766: 		} else {
 5767: #
 5768: # This is not a package - some other kind of start tag
 5769: #
 5770: 		    my $entry=$token->[1];
 5771: 		    my $unikey;
 5772: 		    if ($entry eq 'import') {
 5773: 			$unikey='';
 5774: 		    } else {
 5775: 			$unikey=$entry;
 5776: 		    }
 5777: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5778: 
 5779: 		    if (defined($token->[2]->{'id'})) { 
 5780: 			$unikey.='_'.$token->[2]->{'id'}; 
 5781: 		    }
 5782: 
 5783: 		    if ($entry eq 'import') {
 5784: #
 5785: # Importing a library here
 5786: #
 5787: 			if ($depthcount<20) {
 5788: 			    my $location=$parser->get_text('/import');
 5789: 			    my $dir=$filename;
 5790: 			    $dir=~s|[^/]*$||;
 5791: 			    $location=&filelocation($dir,$location);
 5792: 			    my $metadata = 
 5793: 				&metadata($uri,'keys', $location,$unikey,
 5794: 					  $depthcount+1);
 5795: 			    foreach my $meta (split(',',$metadata)) {
 5796: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 5797: 				$metathesekeys{$meta}=1;
 5798: 			    }
 5799: 			}
 5800: 		    } else { 
 5801: 			
 5802: 			if (defined($token->[2]->{'name'})) { 
 5803: 			    $unikey.='_'.$token->[2]->{'name'}; 
 5804: 			}
 5805: 			$metathesekeys{$unikey}=1;
 5806: 			foreach my $param (@{$token->[3]}) {
 5807: 			    $metaentry{':'.$unikey.'.'.$param} =
 5808: 				$token->[2]->{$param};
 5809: 			}
 5810: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 5811: 			my $default=$metaentry{':'.$unikey.'.default'};
 5812: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 5813: 		 # only ws inside the tag, and not in default, so use default
 5814: 		 # as value
 5815: 			    $metaentry{':'.$unikey}=$default;
 5816: 			} else {
 5817: 		  # either something interesting inside the tag or default
 5818:                   # uninteresting
 5819: 			    $metaentry{':'.$unikey}=$internaltext;
 5820: 			}
 5821: # end of not-a-package not-a-library import
 5822: 		    }
 5823: # end of not-a-package start tag
 5824: 		}
 5825: # the next is the end of "start tag"
 5826: 	    }
 5827: 	}
 5828: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 5829: 	foreach my $key (keys(%packagetab)) {
 5830: 	    #no specific packages #how's our extension
 5831: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 5832: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 5833: 					 \%metathesekeys);
 5834: 	}
 5835: 	if (!exists($metaentry{':packages'})) {
 5836: 	    foreach my $key (keys(%packagetab)) {
 5837: 		#no specific packages well let's get default then
 5838: 		if ($key!~/^default&/) { next; }
 5839: 		&metadata_create_package_def($uri,$key,'default',
 5840: 					     \%metathesekeys);
 5841: 	    }
 5842: 	}
 5843: # are there custom rights to evaluate
 5844: 	if ($metaentry{':copyright'} eq 'custom') {
 5845: 
 5846:     #
 5847:     # Importing a rights file here
 5848:     #
 5849: 	    unless ($depthcount) {
 5850: 		my $location=$metaentry{':customdistributionfile'};
 5851: 		my $dir=$filename;
 5852: 		$dir=~s|[^/]*$||;
 5853: 		$location=&filelocation($dir,$location);
 5854: 		my $rights_metadata =
 5855: 		    &metadata($uri,'keys',$location,'_rights',
 5856: 			      $depthcount+1);
 5857: 		foreach my $rights (split(',',$rights_metadata)) {
 5858: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 5859: 		    $metathesekeys{$rights}=1;
 5860: 		}
 5861: 	    }
 5862: 	}
 5863: 	# uniqifiy package listing
 5864: 	my %seen;
 5865: 	my @uniq_packages =
 5866: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 5867: 	$metaentry{':packages'} = join(',',@uniq_packages);
 5868: 
 5869: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 5870: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 5871: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 5872: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 5873: # this is the end of "was not already recently cached
 5874:     }
 5875:     return $metaentry{':'.$what};
 5876: }
 5877: 
 5878: sub metadata_create_package_def {
 5879:     my ($uri,$key,$package,$metathesekeys)=@_;
 5880:     my ($pack,$name,$subp)=split(/\&/,$key);
 5881:     if ($subp eq 'default') { next; }
 5882:     
 5883:     if (defined($metaentry{':packages'})) {
 5884: 	$metaentry{':packages'}.=','.$package;
 5885:     } else {
 5886: 	$metaentry{':packages'}=$package;
 5887:     }
 5888:     my $value=$packagetab{$key};
 5889:     my $unikey;
 5890:     $unikey='parameter_0_'.$name;
 5891:     $metaentry{':'.$unikey.'.part'}=0;
 5892:     $$metathesekeys{$unikey}=1;
 5893:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 5894: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 5895:     }
 5896:     if (defined($metaentry{':'.$unikey.'.default'})) {
 5897: 	$metaentry{':'.$unikey}=
 5898: 	    $metaentry{':'.$unikey.'.default'};
 5899:     }
 5900: }
 5901: 
 5902: sub metadata_generate_part0 {
 5903:     my ($metadata,$metacache,$uri) = @_;
 5904:     my %allnames;
 5905:     foreach my $metakey (keys(%$metadata)) {
 5906: 	if ($metakey=~/^parameter\_(.*)/) {
 5907: 	  my $part=$$metacache{':'.$metakey.'.part'};
 5908: 	  my $name=$$metacache{':'.$metakey.'.name'};
 5909: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 5910: 	    $allnames{$name}=$part;
 5911: 	  }
 5912: 	}
 5913:     }
 5914:     foreach my $name (keys(%allnames)) {
 5915:       $$metadata{"parameter_0_$name"}=1;
 5916:       my $key=":parameter_0_$name";
 5917:       $$metacache{"$key.part"}='0';
 5918:       $$metacache{"$key.name"}=$name;
 5919:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 5920: 					   $allnames{$name}.'_'.$name.
 5921: 					   '.type'};
 5922:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 5923: 			     '.display'};
 5924:       my $expr='[Part: '.$allnames{$name}.']';
 5925:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 5926:       $$metacache{"$key.display"}=$olddis;
 5927:     }
 5928: }
 5929: 
 5930: # ------------------------------------------------- Get the title of a resource
 5931: 
 5932: sub gettitle {
 5933:     my $urlsymb=shift;
 5934:     my $symb=&symbread($urlsymb);
 5935:     if ($symb) {
 5936: 	my $key=$env{'request.course.id'}."\0".$symb;
 5937: 	my ($result,$cached)=&is_cached_new('title',$key);
 5938: 	if (defined($cached)) { 
 5939: 	    return $result;
 5940: 	}
 5941: 	my ($map,$resid,$url)=&decode_symb($symb);
 5942: 	my $title='';
 5943: 	my %bighash;
 5944: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5945: 		&GDBM_READER(),0640)) {
 5946: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 5947: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 5948: 	    untie %bighash;
 5949: 	}
 5950: 	$title=~s/\&colon\;/\:/gs;
 5951: 	if ($title) {
 5952: 	    return &do_cache_new('title',$key,$title,600);
 5953: 	}
 5954: 	$urlsymb=$url;
 5955:     }
 5956:     my $title=&metadata($urlsymb,'title');
 5957:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 5958:     return $title;
 5959: }
 5960: 
 5961: sub get_slot {
 5962:     my ($which,$cnum,$cdom)=@_;
 5963:     if (!$cnum || !$cdom) {
 5964: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 5965: 	$cdom=$env{'course.'.$courseid.'.domain'};
 5966: 	$cnum=$env{'course.'.$courseid.'.num'};
 5967:     }
 5968:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 5969:     my %slotinfo;
 5970:     if (exists($remembered{$key})) {
 5971: 	$slotinfo{$which} = $remembered{$key};
 5972:     } else {
 5973: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 5974: 	&Apache::lonhomework::showhash(%slotinfo);
 5975: 	my ($tmp)=keys(%slotinfo);
 5976: 	if ($tmp=~/^error:/) { return (); }
 5977: 	$remembered{$key} = $slotinfo{$which};
 5978:     }
 5979:     if (ref($slotinfo{$which}) eq 'HASH') {
 5980: 	return %{$slotinfo{$which}};
 5981:     }
 5982:     return $slotinfo{$which};
 5983: }
 5984: # ------------------------------------------------- Update symbolic store links
 5985: 
 5986: sub symblist {
 5987:     my ($mapname,%newhash)=@_;
 5988:     $mapname=&deversion(&declutter($mapname));
 5989:     my %hash;
 5990:     if (($env{'request.course.fn'}) && (%newhash)) {
 5991:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5992:                       &GDBM_WRCREAT(),0640)) {
 5993: 	    foreach my $url (keys %newhash) {
 5994: 		next if ($url eq 'last_known'
 5995: 			 && $env{'form.no_update_last_known'});
 5996: 		$hash{declutter($url)}=&encode_symb($mapname,
 5997: 						    $newhash{$url}->[1],
 5998: 						    $newhash{$url}->[0]);
 5999:             }
 6000:             if (untie(%hash)) {
 6001: 		return 'ok';
 6002:             }
 6003:         }
 6004:     }
 6005:     return 'error';
 6006: }
 6007: 
 6008: # --------------------------------------------------------------- Verify a symb
 6009: 
 6010: sub symbverify {
 6011:     my ($symb,$thisurl)=@_;
 6012:     my $thisfn=$thisurl;
 6013: # wrapper not part of symbs
 6014:     $thisfn=~s/^\/adm\/wrapper//;
 6015:     $thisfn=~s/^\/adm\/coursedocs\/showdoc\///;
 6016:     $thisfn=&declutter($thisfn);
 6017: # direct jump to resource in page or to a sequence - will construct own symbs
 6018:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6019: # check URL part
 6020:     my ($map,$resid,$url)=&decode_symb($symb);
 6021: 
 6022:     unless ($url eq $thisfn) { return 0; }
 6023: 
 6024:     $symb=&symbclean($symb);
 6025:     $thisurl=&deversion($thisurl);
 6026:     $thisfn=&deversion($thisfn);
 6027: 
 6028:     my %bighash;
 6029:     my $okay=0;
 6030: 
 6031:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6032:                             &GDBM_READER(),0640)) {
 6033:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6034:         unless ($ids) { 
 6035:            $ids=$bighash{'ids_/'.$thisurl};
 6036:         }
 6037:         if ($ids) {
 6038: # ------------------------------------------------------------------- Has ID(s)
 6039: 	    foreach (split(/\,/,$ids)) {
 6040: 	       my ($mapid,$resid)=split(/\./,$_);
 6041:                if (
 6042:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6043:    eq $symb) { 
 6044: 		   if (($env{'request.role.adv'}) ||
 6045: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 6046: 		       $okay=1; 
 6047: 		   }
 6048: 	       }
 6049: 	   }
 6050:         }
 6051: 	untie(%bighash);
 6052:     }
 6053:     return $okay;
 6054: }
 6055: 
 6056: # --------------------------------------------------------------- Clean-up symb
 6057: 
 6058: sub symbclean {
 6059:     my $symb=shift;
 6060:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6061: # remove version from map
 6062:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6063: 
 6064: # remove version from URL
 6065:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6066: 
 6067: # remove wrapper
 6068: 
 6069:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6070:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6071:     return $symb;
 6072: }
 6073: 
 6074: # ---------------------------------------------- Split symb to find map and url
 6075: 
 6076: sub encode_symb {
 6077:     my ($map,$resid,$url)=@_;
 6078:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6079: }
 6080: 
 6081: sub decode_symb {
 6082:     my $symb=shift;
 6083:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6084:     my ($map,$resid,$url)=split(/___/,$symb);
 6085:     return (&fixversion($map),$resid,&fixversion($url));
 6086: }
 6087: 
 6088: sub fixversion {
 6089:     my $fn=shift;
 6090:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6091:     my %bighash;
 6092:     my $uri=&clutter($fn);
 6093:     my $key=$env{'request.course.id'}.'_'.$uri;
 6094: # is this cached?
 6095:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6096:     if (defined($cached)) { return $result; }
 6097: # unfortunately not cached, or expired
 6098:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6099: 	    &GDBM_READER(),0640)) {
 6100:  	if ($bighash{'version_'.$uri}) {
 6101:  	    my $version=$bighash{'version_'.$uri};
 6102:  	    unless (($version eq 'mostrecent') || 
 6103: 		    ($version==&getversion($uri))) {
 6104:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6105:  	    }
 6106:  	}
 6107:  	untie %bighash;
 6108:     }
 6109:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6110: }
 6111: 
 6112: sub deversion {
 6113:     my $url=shift;
 6114:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6115:     return $url;
 6116: }
 6117: 
 6118: # ------------------------------------------------------ Return symb list entry
 6119: 
 6120: sub symbread {
 6121:     my ($thisfn,$donotrecurse)=@_;
 6122:     my $cache_str='request.symbread.cached.'.$thisfn;
 6123:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6124: # no filename provided? try from environment
 6125:     unless ($thisfn) {
 6126:         if ($env{'request.symb'}) {
 6127: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6128: 	}
 6129: 	$thisfn=$env{'request.filename'};
 6130:     }
 6131:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6132: # is that filename actually a symb? Verify, clean, and return
 6133:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6134: 	if (&symbverify($thisfn,$1)) {
 6135: 	    return $env{$cache_str}=&symbclean($thisfn);
 6136: 	}
 6137:     }
 6138:     $thisfn=declutter($thisfn);
 6139:     my %hash;
 6140:     my %bighash;
 6141:     my $syval='';
 6142:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6143:         my $targetfn = $thisfn;
 6144:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6145:             $targetfn = 'adm/wrapper/'.$thisfn;
 6146:         }
 6147: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6148: 	    $targetfn=$1;
 6149: 	}
 6150:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6151:                       &GDBM_READER(),0640)) {
 6152: 	    $syval=$hash{$targetfn};
 6153:             untie(%hash);
 6154:         }
 6155: # ---------------------------------------------------------- There was an entry
 6156:         if ($syval) {
 6157: 	    #unless ($syval=~/\_\d+$/) {
 6158: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6159: 		    #&appenv('request.ambiguous' => $thisfn);
 6160: 		    #return $env{$cache_str}='';
 6161: 		#}    
 6162: 		#$syval.=$1;
 6163: 	    #}
 6164:         } else {
 6165: # ------------------------------------------------------- Was not in symb table
 6166:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6167:                             &GDBM_READER(),0640)) {
 6168: # ---------------------------------------------- Get ID(s) for current resource
 6169:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6170:               unless ($ids) { 
 6171:                  $ids=$bighash{'ids_/'.$thisfn};
 6172:               }
 6173:               unless ($ids) {
 6174: # alias?
 6175: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6176:               }
 6177:               if ($ids) {
 6178: # ------------------------------------------------------------------- Has ID(s)
 6179:                  my @possibilities=split(/\,/,$ids);
 6180:                  if ($#possibilities==0) {
 6181: # ----------------------------------------------- There is only one possibility
 6182: 		     my ($mapid,$resid)=split(/\./,$ids);
 6183: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6184: 						    $resid,$thisfn);
 6185:                  } elsif (!$donotrecurse) {
 6186: # ------------------------------------------ There is more than one possibility
 6187:                      my $realpossible=0;
 6188:                      foreach (@possibilities) {
 6189: 			 my $file=$bighash{'src_'.$_};
 6190:                          if (&allowed('bre',$file)) {
 6191:          		    my ($mapid,$resid)=split(/\./,$_);
 6192:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6193: 				$realpossible++;
 6194:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6195: 						    $resid,$thisfn);
 6196:                             }
 6197: 			 }
 6198:                      }
 6199: 		     if ($realpossible!=1) { $syval=''; }
 6200:                  } else {
 6201:                      $syval='';
 6202:                  }
 6203: 	      }
 6204:               untie(%bighash)
 6205:            }
 6206:         }
 6207:         if ($syval) {
 6208: 	    return $env{$cache_str}=$syval;
 6209:         }
 6210:     }
 6211:     &appenv('request.ambiguous' => $thisfn);
 6212:     return $env{$cache_str}='';
 6213: }
 6214: 
 6215: # ---------------------------------------------------------- Return random seed
 6216: 
 6217: sub numval {
 6218:     my $txt=shift;
 6219:     $txt=~tr/A-J/0-9/;
 6220:     $txt=~tr/a-j/0-9/;
 6221:     $txt=~tr/K-T/0-9/;
 6222:     $txt=~tr/k-t/0-9/;
 6223:     $txt=~tr/U-Z/0-5/;
 6224:     $txt=~tr/u-z/0-5/;
 6225:     $txt=~s/\D//g;
 6226:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6227:     return int($txt);
 6228: }
 6229: 
 6230: sub numval2 {
 6231:     my $txt=shift;
 6232:     $txt=~tr/A-J/0-9/;
 6233:     $txt=~tr/a-j/0-9/;
 6234:     $txt=~tr/K-T/0-9/;
 6235:     $txt=~tr/k-t/0-9/;
 6236:     $txt=~tr/U-Z/0-5/;
 6237:     $txt=~tr/u-z/0-5/;
 6238:     $txt=~s/\D//g;
 6239:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6240:     my $total;
 6241:     foreach my $val (@txts) { $total+=$val; }
 6242:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6243:     return int($total);
 6244: }
 6245: 
 6246: sub numval3 {
 6247:     use integer;
 6248:     my $txt=shift;
 6249:     $txt=~tr/A-J/0-9/;
 6250:     $txt=~tr/a-j/0-9/;
 6251:     $txt=~tr/K-T/0-9/;
 6252:     $txt=~tr/k-t/0-9/;
 6253:     $txt=~tr/U-Z/0-5/;
 6254:     $txt=~tr/u-z/0-5/;
 6255:     $txt=~s/\D//g;
 6256:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6257:     my $total;
 6258:     foreach my $val (@txts) { $total+=$val; }
 6259:     if ($_64bit) { $total=(($total<<32)>>32); }
 6260:     return $total;
 6261: }
 6262: 
 6263: sub digest {
 6264:     my ($data)=@_;
 6265:     my $digest=&Digest::MD5::md5($data);
 6266:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6267:     my ($e,$f);
 6268:     {
 6269:         use integer;
 6270:         $e=($a+$b);
 6271:         $f=($c+$d);
 6272:         if ($_64bit) {
 6273:             $e=(($e<<32)>>32);
 6274:             $f=(($f<<32)>>32);
 6275:         }
 6276:     }
 6277:     if (wantarray) {
 6278: 	return ($e,$f);
 6279:     } else {
 6280: 	my $g;
 6281: 	{
 6282: 	    use integer;
 6283: 	    $g=($e+$f);
 6284: 	    if ($_64bit) {
 6285: 		$g=(($g<<32)>>32);
 6286: 	    }
 6287: 	}
 6288: 	return $g;
 6289:     }
 6290: }
 6291: 
 6292: sub latest_rnd_algorithm_id {
 6293:     return '64bit5';
 6294: }
 6295: 
 6296: sub get_rand_alg {
 6297:     my ($courseid)=@_;
 6298:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 6299:     if ($courseid) {
 6300: 	return $env{"course.$courseid.rndseed"};
 6301:     }
 6302:     return &latest_rnd_algorithm_id();
 6303: }
 6304: 
 6305: sub validCODE {
 6306:     my ($CODE)=@_;
 6307:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6308:     return 0;
 6309: }
 6310: 
 6311: sub getCODE {
 6312:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6313:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6314: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6315: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6316: 	return $Apache::lonhomework::history{'resource.CODE'};
 6317:     }
 6318:     return undef;
 6319: }
 6320: 
 6321: sub rndseed {
 6322:     my ($symb,$courseid,$domain,$username)=@_;
 6323: 
 6324:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 6325:     if (!$symb) {
 6326: 	unless ($symb=$wsymb) { return time; }
 6327:     }
 6328:     if (!$courseid) { $courseid=$wcourseid; }
 6329:     if (!$domain) { $domain=$wdomain; }
 6330:     if (!$username) { $username=$wusername }
 6331:     my $which=&get_rand_alg();
 6332:     if (defined(&getCODE())) {
 6333: 	if ($which eq '64bit5') {
 6334: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6335: 	} elsif ($which eq '64bit4') {
 6336: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6337: 	} else {
 6338: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6339: 	}
 6340:     } elsif ($which eq '64bit5') {
 6341: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6342:     } elsif ($which eq '64bit4') {
 6343: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6344:     } elsif ($which eq '64bit3') {
 6345: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6346:     } elsif ($which eq '64bit2') {
 6347: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6348:     } elsif ($which eq '64bit') {
 6349: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6350:     }
 6351:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6352: }
 6353: 
 6354: sub rndseed_32bit {
 6355:     my ($symb,$courseid,$domain,$username)=@_;
 6356:     {
 6357: 	use integer;
 6358: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6359: 	my $symbseed=numval($symb) << 22;
 6360: 	my $namechck=unpack("%32C*",$username) << 17;
 6361: 	my $nameseed=numval($username) << 12;
 6362: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6363: 	my $courseseed=unpack("%32C*",$courseid);
 6364: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6365: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6366: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6367: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6368: 	return $num;
 6369:     }
 6370: }
 6371: 
 6372: sub rndseed_64bit {
 6373:     my ($symb,$courseid,$domain,$username)=@_;
 6374:     {
 6375: 	use integer;
 6376: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6377: 	my $symbseed=numval($symb) << 10;
 6378: 	my $namechck=unpack("%32S*",$username);
 6379: 	
 6380: 	my $nameseed=numval($username) << 21;
 6381: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6382: 	my $courseseed=unpack("%32S*",$courseid);
 6383: 	
 6384: 	my $num1=$symbchck+$symbseed+$namechck;
 6385: 	my $num2=$nameseed+$domainseed+$courseseed;
 6386: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6387: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6388: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6389: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6390: 	return "$num1,$num2";
 6391:     }
 6392: }
 6393: 
 6394: sub rndseed_64bit2 {
 6395:     my ($symb,$courseid,$domain,$username)=@_;
 6396:     {
 6397: 	use integer;
 6398: 	# strings need to be an even # of cahracters long, it it is odd the
 6399:         # last characters gets thrown away
 6400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6401: 	my $symbseed=numval($symb) << 10;
 6402: 	my $namechck=unpack("%32S*",$username.' ');
 6403: 	
 6404: 	my $nameseed=numval($username) << 21;
 6405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6406: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6407: 	
 6408: 	my $num1=$symbchck+$symbseed+$namechck;
 6409: 	my $num2=$nameseed+$domainseed+$courseseed;
 6410: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6411: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 6412: 	return "$num1,$num2";
 6413:     }
 6414: }
 6415: 
 6416: sub rndseed_64bit3 {
 6417:     my ($symb,$courseid,$domain,$username)=@_;
 6418:     {
 6419: 	use integer;
 6420: 	# strings need to be an even # of cahracters long, it it is odd the
 6421:         # last characters gets thrown away
 6422: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6423: 	my $symbseed=numval2($symb) << 10;
 6424: 	my $namechck=unpack("%32S*",$username.' ');
 6425: 	
 6426: 	my $nameseed=numval2($username) << 21;
 6427: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6428: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6429: 	
 6430: 	my $num1=$symbchck+$symbseed+$namechck;
 6431: 	my $num2=$nameseed+$domainseed+$courseseed;
 6432: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6433: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6434: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6435: 	
 6436: 	return "$num1:$num2";
 6437:     }
 6438: }
 6439: 
 6440: sub rndseed_64bit4 {
 6441:     my ($symb,$courseid,$domain,$username)=@_;
 6442:     {
 6443: 	use integer;
 6444: 	# strings need to be an even # of cahracters long, it it is odd the
 6445:         # last characters gets thrown away
 6446: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6447: 	my $symbseed=numval3($symb) << 10;
 6448: 	my $namechck=unpack("%32S*",$username.' ');
 6449: 	
 6450: 	my $nameseed=numval3($username) << 21;
 6451: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6452: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6453: 	
 6454: 	my $num1=$symbchck+$symbseed+$namechck;
 6455: 	my $num2=$nameseed+$domainseed+$courseseed;
 6456: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6457: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 6458: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6459: 	
 6460: 	return "$num1:$num2";
 6461:     }
 6462: }
 6463: 
 6464: sub rndseed_64bit5 {
 6465:     my ($symb,$courseid,$domain,$username)=@_;
 6466:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6467:     return "$num1:$num2";
 6468: }
 6469: 
 6470: sub rndseed_CODE_64bit {
 6471:     my ($symb,$courseid,$domain,$username)=@_;
 6472:     {
 6473: 	use integer;
 6474: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6475: 	my $symbseed=numval2($symb);
 6476: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6477: 	my $CODEseed=numval(&getCODE());
 6478: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6479: 	my $num1=$symbseed+$CODEchck;
 6480: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6481: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6482: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6483: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6484: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6485: 	return "$num1:$num2";
 6486:     }
 6487: }
 6488: 
 6489: sub rndseed_CODE_64bit4 {
 6490:     my ($symb,$courseid,$domain,$username)=@_;
 6491:     {
 6492: 	use integer;
 6493: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6494: 	my $symbseed=numval3($symb);
 6495: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6496: 	my $CODEseed=numval3(&getCODE());
 6497: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6498: 	my $num1=$symbseed+$CODEchck;
 6499: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6500: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6501: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 6502: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6503: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6504: 	return "$num1:$num2";
 6505:     }
 6506: }
 6507: 
 6508: sub rndseed_CODE_64bit5 {
 6509:     my ($symb,$courseid,$domain,$username)=@_;
 6510:     my $code = &getCODE();
 6511:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6512:     return "$num1:$num2";
 6513: }
 6514: 
 6515: sub setup_random_from_rndseed {
 6516:     my ($rndseed)=@_;
 6517:     if ($rndseed =~/([,:])/) {
 6518: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6519: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6520:     } else {
 6521: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6522:     }
 6523: }
 6524: 
 6525: sub latest_receipt_algorithm_id {
 6526:     return 'receipt2';
 6527: }
 6528: 
 6529: sub recunique {
 6530:     my $fucourseid=shift;
 6531:     my $unique;
 6532:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6533: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6534:     } else {
 6535: 	$unique=$perlvar{'lonReceipt'};
 6536:     }
 6537:     return unpack("%32C*",$unique);
 6538: }
 6539: 
 6540: sub recprefix {
 6541:     my $fucourseid=shift;
 6542:     my $prefix;
 6543:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6544: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6545:     } else {
 6546: 	$prefix=$perlvar{'lonHostID'};
 6547:     }
 6548:     return unpack("%32C*",$prefix);
 6549: }
 6550: 
 6551: sub ireceipt {
 6552:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6553:     my $cuname=unpack("%32C*",$funame);
 6554:     my $cudom=unpack("%32C*",$fudom);
 6555:     my $cucourseid=unpack("%32C*",$fucourseid);
 6556:     my $cusymb=unpack("%32C*",$fusymb);
 6557:     my $cunique=&recunique($fucourseid);
 6558:     my $cpart=unpack("%32S*",$part);
 6559:     my $return =&recprefix($fucourseid).'-';
 6560:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6561: 	$env{'request.state'} eq 'construct') {
 6562: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 6563: 			       " and ".($cpart%$cudom));
 6564: 			       
 6565: 	$return.= ($cunique%$cuname+
 6566: 		   $cunique%$cudom+
 6567: 		   $cusymb%$cuname+
 6568: 		   $cusymb%$cudom+
 6569: 		   $cucourseid%$cuname+
 6570: 		   $cucourseid%$cudom+
 6571: 		   $cpart%$cuname+
 6572: 		   $cpart%$cudom);
 6573:     } else {
 6574: 	$return.= ($cunique%$cuname+
 6575: 		   $cunique%$cudom+
 6576: 		   $cusymb%$cuname+
 6577: 		   $cusymb%$cudom+
 6578: 		   $cucourseid%$cuname+
 6579: 		   $cucourseid%$cudom);
 6580:     }
 6581:     return $return;
 6582: }
 6583: 
 6584: sub receipt {
 6585:     my ($part)=@_;
 6586:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 6587:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6588: }
 6589: 
 6590: # ------------------------------------------------------------ Serves up a file
 6591: # returns either the contents of the file or 
 6592: # -1 if the file doesn't exist
 6593: #
 6594: # if the target is a file that was uploaded via DOCS, 
 6595: # a check will be made to see if a current copy exists on the local server,
 6596: # if it does this will be served, otherwise a copy will be retrieved from
 6597: # the home server for the course and stored in /home/httpd/html/userfiles on
 6598: # the local server.   
 6599: 
 6600: sub getfile {
 6601:     my ($file) = @_;
 6602:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6603:     &repcopy($file);
 6604:     return &readfile($file);
 6605: }
 6606: 
 6607: sub repcopy_userfile {
 6608:     my ($file)=@_;
 6609:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6610:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6611:     my ($cdom,$cnum,$filename) = 
 6612: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6613:     my ($info,$rtncode);
 6614:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6615:     if (-e "$file") {
 6616: 	my @fileinfo = stat($file);
 6617: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6618: 	if ($lwpresp ne 'ok') {
 6619: 	    if ($rtncode eq '404') {
 6620: 		unlink($file);
 6621: 	    }
 6622: 	    #my $ua=new LWP::UserAgent;
 6623: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6624: 	    #my $response=$ua->request($request);
 6625: 	    #if ($response->is_success()) {
 6626: 	#	return $response->content;
 6627: 	#    } else {
 6628: 	#	return -1;
 6629: 	#    }
 6630: 	    return -1;
 6631: 	}
 6632: 	if ($info < $fileinfo[9]) {
 6633: 	    return 'ok';
 6634: 	}
 6635: 	$info = '';
 6636: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6637: 	if ($lwpresp ne 'ok') {
 6638: 	    return -1;
 6639: 	}
 6640:     } else {
 6641: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6642: 	if ($lwpresp ne 'ok') {
 6643: 	    my $ua=new LWP::UserAgent;
 6644: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6645: 	    my $response=$ua->request($request);
 6646: 	    if ($response->is_success()) {
 6647: 		$info=$response->content;
 6648: 	    } else {
 6649: 		return -1;
 6650: 	    }
 6651: 	}
 6652: 	my @parts = ($cdom,$cnum); 
 6653: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6654: 	    push @parts, split(/\//,$1);
 6655: 	}
 6656: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6657: 	foreach my $part (@parts) {
 6658: 	    $path .= '/'.$part;
 6659: 	    if (!-e $path) {
 6660: 		mkdir($path,0770);
 6661: 	    }
 6662: 	}
 6663:     }
 6664:     open(FILE,">$file");
 6665:     print FILE $info;
 6666:     close(FILE);
 6667:     return 'ok';
 6668: }
 6669: 
 6670: sub tokenwrapper {
 6671:     my $uri=shift;
 6672:     $uri=~s|^http\://([^/]+)||;
 6673:     $uri=~s|^/||;
 6674:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6675:     my $token=$1;
 6676:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6677:     if ($udom && $uname && $file) {
 6678: 	$file=~s|(\?\.*)*$||;
 6679:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6680:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6681:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6682:                                '&tokenissued='.$perlvar{'lonHostID'};
 6683:     } else {
 6684:         return '/adm/notfound.html';
 6685:     }
 6686: }
 6687: 
 6688: sub getuploaded {
 6689:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 6690:     $uri=~s/^\///;
 6691:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 6692:     my $ua=new LWP::UserAgent;
 6693:     my $request=new HTTP::Request($reqtype,$uri);
 6694:     my $response=$ua->request($request);
 6695:     $$rtncode = $response->code;
 6696:     if (! $response->is_success()) {
 6697: 	return 'failed';
 6698:     }      
 6699:     if ($reqtype eq 'HEAD') {
 6700: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 6701:     } elsif ($reqtype eq 'GET') {
 6702: 	$$info = $response->content;
 6703:     }
 6704:     return 'ok';
 6705: }
 6706: 
 6707: sub readfile {
 6708:     my $file = shift;
 6709:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 6710:     my $fh;
 6711:     open($fh,"<$file");
 6712:     my $a='';
 6713:     while (<$fh>) { $a .=$_; }
 6714:     return $a;
 6715: }
 6716: 
 6717: sub filelocation {
 6718:     my ($dir,$file) = @_;
 6719:     my $location;
 6720:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 6721: 
 6722:     if ($file =~ m-^/adm/-) {
 6723: 	$file=~s-^/adm/wrapper/-/-;
 6724: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6725:     }
 6726:     if ($file=~m:^/~:) { # is a contruction space reference
 6727:         $location = $file;
 6728:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 6729:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 6730: 	# is a correct contruction space reference
 6731:         $location = $file;
 6732:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 6733:         my ($udom,$uname,$filename)=
 6734:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 6735:         my $home=&homeserver($uname,$udom);
 6736:         my $is_me=0;
 6737:         my @ids=&current_machine_ids();
 6738:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 6739:         if ($is_me) {
 6740:   	    $location=&propath($udom,$uname).
 6741:   	      '/userfiles/'.$filename;
 6742:         } else {
 6743:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 6744:   	      $udom.'/'.$uname.'/'.$filename;
 6745:         }
 6746:     } else {
 6747:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6748:         $file=~s:^/res/:/:;
 6749:         if ( !( $file =~ m:^/:) ) {
 6750:             $location = $dir. '/'.$file;
 6751:         } else {
 6752:             $location = '/home/httpd/html/res'.$file;
 6753:         }
 6754:     }
 6755:     $location=~s://+:/:g; # remove duplicate /
 6756:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 6757:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 6758:     return $location;
 6759: }
 6760: 
 6761: sub hreflocation {
 6762:     my ($dir,$file)=@_;
 6763:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 6764: 	$file=filelocation($dir,$file);
 6765:     } elsif ($file=~m-^/adm/-) {
 6766: 	$file=~s-^/adm/wrapper/-/-;
 6767: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 6768:     }
 6769:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 6770: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 6771:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 6772: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 6773:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 6774: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 6775: 	    -/uploaded/$1/$2/-x;
 6776:     }
 6777:     return $file;
 6778: }
 6779: 
 6780: sub current_machine_domains {
 6781:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6782:     my @domains;
 6783:     while( my($id, $name) = each(%hostname)) {
 6784: #	&logthis("-$id-$name-$hostname-");
 6785: 	if ($hostname eq $name) {
 6786: 	    push(@domains,$hostdom{$id});
 6787: 	}
 6788:     }
 6789:     return @domains;
 6790: }
 6791: 
 6792: sub current_machine_ids {
 6793:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 6794:     my @ids;
 6795:     while( my($id, $name) = each(%hostname)) {
 6796: #	&logthis("-$id-$name-$hostname-");
 6797: 	if ($hostname eq $name) {
 6798: 	    push(@ids,$id);
 6799: 	}
 6800:     }
 6801:     return @ids;
 6802: }
 6803: 
 6804: # ------------------------------------------------------------- Declutters URLs
 6805: 
 6806: sub declutter {
 6807:     my $thisfn=shift;
 6808:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6809:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 6810:     $thisfn=~s/^\///;
 6811:     $thisfn=~s|^adm/wrapper/||;
 6812:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 6813:     $thisfn=~s/^res\///;
 6814:     $thisfn=~s/\?.+$//;
 6815:     return $thisfn;
 6816: }
 6817: 
 6818: # ------------------------------------------------------------- Clutter up URLs
 6819: 
 6820: sub clutter {
 6821:     my $thisfn='/'.&declutter(shift);
 6822:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 6823:        $thisfn='/res'.$thisfn; 
 6824:     }
 6825:     if ($thisfn !~m|/adm|) {
 6826: 	if ($thisfn =~ m|/ext/|) {
 6827: 	    $thisfn='/adm/wrapper'.$thisfn;
 6828: 	} else {
 6829: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 6830: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 6831: 	    if ($embstyle eq 'ssi'
 6832: 		|| ($embstyle eq 'hdn')
 6833: 		|| ($embstyle eq 'rat')
 6834: 		|| ($embstyle eq 'prv')
 6835: 		|| ($embstyle eq 'ign')) {
 6836: 		#do nothing with these
 6837: 	    } elsif (($embstyle eq 'img') 
 6838: 		|| ($embstyle eq 'emb')
 6839: 		|| ($embstyle eq 'wrp')) {
 6840: 		$thisfn='/adm/wrapper'.$thisfn;
 6841: 	    } elsif ($embstyle eq 'unk'
 6842: 		     && $thisfn!~/\.(sequence|page)$/) {
 6843: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 6844: 	    } else {
 6845: #		&logthis("Got a blank emb style");
 6846: 	    }
 6847: 	}
 6848:     }
 6849:     return $thisfn;
 6850: }
 6851: 
 6852: sub freeze_escape {
 6853:     my ($value)=@_;
 6854:     if (ref($value)) {
 6855: 	$value=&nfreeze($value);
 6856: 	return '__FROZEN__'.&escape($value);
 6857:     }
 6858:     return &escape($value);
 6859: }
 6860: 
 6861: 
 6862: sub thaw_unescape {
 6863:     my ($value)=@_;
 6864:     if ($value =~ /^__FROZEN__/) {
 6865: 	substr($value,0,10,undef);
 6866: 	$value=&unescape($value);
 6867: 	return &thaw($value);
 6868:     }
 6869:     return &unescape($value);
 6870: }
 6871: 
 6872: sub correct_line_ends {
 6873:     my ($result)=@_;
 6874:     $$result =~s/\r\n/\n/mg;
 6875:     $$result =~s/\r/\n/mg;
 6876: }
 6877: # ================================================================ Main Program
 6878: 
 6879: sub goodbye {
 6880:    &logthis("Starting Shut down");
 6881: #not converted to using infrastruture and probably shouldn't be
 6882:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 6883: #converted
 6884: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 6885:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 6886: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 6887: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 6888: #1.1 only
 6889: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 6890: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 6891: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 6892: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 6893:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 6894:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 6895:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 6896:    &flushcourselogs();
 6897:    &logthis("Shutting down");
 6898: }
 6899: 
 6900: BEGIN {
 6901: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 6902:     unless ($readit) {
 6903: {
 6904:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 6905:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 6906: 
 6907:     while (my $configline=<$config>) {
 6908:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 6909: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6910:            chomp($varvalue);
 6911:            $perlvar{$varname}=$varvalue;
 6912:         }
 6913:     }
 6914:     close($config);
 6915: }
 6916: {
 6917:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 6918: 
 6919:     while (my $configline=<$config>) {
 6920:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 6921: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 6922:            chomp($varvalue);
 6923:            $perlvar{$varname}=$varvalue;
 6924:         }
 6925:     }
 6926:     close($config);
 6927: }
 6928: 
 6929: # ------------------------------------------------------------ Read domain file
 6930: {
 6931:     %domaindescription = ();
 6932:     %domain_auth_def = ();
 6933:     %domain_auth_arg_def = ();
 6934:     my $fh;
 6935:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 6936:        while (<$fh>) {
 6937:            next if (/^(\#|\s*$)/);
 6938: #           next if /^\#/;
 6939:            chomp;
 6940:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 6941: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$_);
 6942: 	   $domain_auth_def{$domain}=$def_auth;
 6943:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 6944: 	   $domaindescription{$domain}=$domain_description;
 6945: 	   $domain_lang_def{$domain}=$def_lang;
 6946: 	   $domain_city{$domain}=$city;
 6947: 	   $domain_longi{$domain}=$longi;
 6948: 	   $domain_lati{$domain}=$lati;
 6949:            $domain_primary{$domain}=$primary;
 6950: 
 6951:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 6952: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 6953: 	}
 6954:     }
 6955:     close ($fh);
 6956: }
 6957: 
 6958: 
 6959: # ------------------------------------------------------------- Read hosts file
 6960: {
 6961:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 6962: 
 6963:     while (my $configline=<$config>) {
 6964:        next if ($configline =~ /^(\#|\s*$)/);
 6965:        chomp($configline);
 6966:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 6967:        $name=~s/\s//g;
 6968:        if ($id && $domain && $role && $name) {
 6969: 	 $hostname{$id}=$name;
 6970: 	 $hostdom{$id}=$domain;
 6971: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 6972:        }
 6973:     }
 6974:     close($config);
 6975:     # FIXME: dev server don't want this, production servers _do_ want this
 6976:     #&get_iphost();
 6977: }
 6978: 
 6979: sub get_iphost {
 6980:     if (%iphost) { return %iphost; }
 6981:     my %name_to_ip;
 6982:     foreach my $id (keys(%hostname)) {
 6983: 	my $name=$hostname{$id};
 6984: 	my $ip;
 6985: 	if (!exists($name_to_ip{$name})) {
 6986: 	    $ip = gethostbyname($name);
 6987: 	    if (!$ip || length($ip) ne 4) {
 6988: 		&logthis("Skipping host $id name $name no IP found\n");
 6989: 		next;
 6990: 	    }
 6991: 	    $ip=inet_ntoa($ip);
 6992: 	    $name_to_ip{$name} = $ip;
 6993: 	} else {
 6994: 	    $ip = $name_to_ip{$name};
 6995: 	}
 6996: 	push(@{$iphost{$ip}},$id);
 6997:     }
 6998:     return %iphost;
 6999: }
 7000: 
 7001: # ------------------------------------------------------ Read spare server file
 7002: {
 7003:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7004: 
 7005:     while (my $configline=<$config>) {
 7006:        chomp($configline);
 7007:        if ($configline) {
 7008:           $spareid{$configline}=1;
 7009:        }
 7010:     }
 7011:     close($config);
 7012: }
 7013: # ------------------------------------------------------------ Read permissions
 7014: {
 7015:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7016: 
 7017:     while (my $configline=<$config>) {
 7018: 	chomp($configline);
 7019: 	if ($configline) {
 7020: 	    my ($role,$perm)=split(/ /,$configline);
 7021: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7022: 	}
 7023:     }
 7024:     close($config);
 7025: }
 7026: 
 7027: # -------------------------------------------- Read plain texts for permissions
 7028: {
 7029:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7030: 
 7031:     while (my $configline=<$config>) {
 7032: 	chomp($configline);
 7033: 	if ($configline) {
 7034: 	    my ($short,@plain)=split(/:/,$configline);
 7035:             %{$prp{$short}} = ();
 7036: 	    if (@plain > 0) {
 7037:                 $prp{$short}{'std'} = $plain[0];
 7038:                 for (my $i=1; $i<@plain; $i++) {
 7039:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7040:                 }
 7041:             }
 7042: 	}
 7043:     }
 7044:     close($config);
 7045: }
 7046: 
 7047: # ---------------------------------------------------------- Read package table
 7048: {
 7049:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7050: 
 7051:     while (my $configline=<$config>) {
 7052: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7053: 	chomp($configline);
 7054: 	my ($short,$plain)=split(/:/,$configline);
 7055: 	my ($pack,$name)=split(/\&/,$short);
 7056: 	if ($plain ne '') {
 7057: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7058: 	    $packagetab{$short}=$plain; 
 7059: 	}
 7060:     }
 7061:     close($config);
 7062: }
 7063: 
 7064: # ------------- set up temporary directory
 7065: {
 7066:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7067: 
 7068: }
 7069: 
 7070: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 7071: 
 7072: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7073: $dumpcount=0;
 7074: 
 7075: &logtouch();
 7076: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7077: $readit=1;
 7078:     {
 7079: 	use integer;
 7080: 	my $test=(2**32)+1;
 7081: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7082: 	&logthis(" Detected 64bit platform ($_64bit)");
 7083:     }
 7084: }
 7085: }
 7086: 
 7087: 1;
 7088: __END__
 7089: 
 7090: =pod
 7091: 
 7092: =head1 NAME
 7093: 
 7094: Apache::lonnet - Subroutines to ask questions about things in the network.
 7095: 
 7096: =head1 SYNOPSIS
 7097: 
 7098: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7099: 
 7100:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7101: 
 7102: Common parameters:
 7103: 
 7104: =over 4
 7105: 
 7106: =item *
 7107: 
 7108: $uname : an internal username (if $cname expecting a course Id specifically)
 7109: 
 7110: =item *
 7111: 
 7112: $udom : a domain (if $cdom expecting a course's domain specifically)
 7113: 
 7114: =item *
 7115: 
 7116: $symb : a resource instance identifier
 7117: 
 7118: =item *
 7119: 
 7120: $namespace : the name of a .db file that contains the data needed or
 7121: being set.
 7122: 
 7123: =back
 7124: 
 7125: =head1 OVERVIEW
 7126: 
 7127: lonnet provides subroutines which interact with the
 7128: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7129: about classes, users, and resources.
 7130: 
 7131: For many of these objects you can also use this to store data about
 7132: them or modify them in various ways.
 7133: 
 7134: =head2 Symbs
 7135: 
 7136: To identify a specific instance of a resource, LON-CAPA uses symbols
 7137: or "symbs"X<symb>. These identifiers are built from the URL of the
 7138: map, the resource number of the resource in the map, and the URL of
 7139: the resource itself. The latter is somewhat redundant, but might help
 7140: if maps change.
 7141: 
 7142: An example is
 7143: 
 7144:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7145: 
 7146: The respective map entry is
 7147: 
 7148:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7149:   title="Problem 2">
 7150:  </resource>
 7151: 
 7152: Symbs are used by the random number generator, as well as to store and
 7153: restore data specific to a certain instance of for example a problem.
 7154: 
 7155: =head2 Storing And Retrieving Data
 7156: 
 7157: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7158: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7159: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7160: is is the non-critical message twin of cstore. These functions are for
 7161: handlers to store a perl hash to a user's permanent data space in an
 7162: easy manner, and to retrieve it again on another call. It is expected
 7163: that a handler would use this once at the beginning to retrieve data,
 7164: and then again once at the end to send only the new data back.
 7165: 
 7166: The data is stored in the user's data directory on the user's
 7167: homeserver under the ID of the course.
 7168: 
 7169: The hash that is returned by restore will have all of the previous
 7170: value for all of the elements of the hash.
 7171: 
 7172: Example:
 7173: 
 7174:  #creating a hash
 7175:  my %hash;
 7176:  $hash{'foo'}='bar';
 7177: 
 7178:  #storing it
 7179:  &Apache::lonnet::cstore(\%hash);
 7180: 
 7181:  #changing a value
 7182:  $hash{'foo'}='notbar';
 7183: 
 7184:  #adding a new value
 7185:  $hash{'bar'}='foo';
 7186:  &Apache::lonnet::cstore(\%hash);
 7187: 
 7188:  #retrieving the hash
 7189:  my %history=&Apache::lonnet::restore();
 7190: 
 7191:  #print the hash
 7192:  foreach my $key (sort(keys(%history))) {
 7193:    print("\%history{$key} = $history{$key}");
 7194:  }
 7195: 
 7196: Will print out:
 7197: 
 7198:  %history{1:foo} = bar
 7199:  %history{1:keys} = foo:timestamp
 7200:  %history{1:timestamp} = 990455579
 7201:  %history{2:bar} = foo
 7202:  %history{2:foo} = notbar
 7203:  %history{2:keys} = foo:bar:timestamp
 7204:  %history{2:timestamp} = 990455580
 7205:  %history{bar} = foo
 7206:  %history{foo} = notbar
 7207:  %history{timestamp} = 990455580
 7208:  %history{version} = 2
 7209: 
 7210: Note that the special hash entries C<keys>, C<version> and
 7211: C<timestamp> were added to the hash. C<version> will be equal to the
 7212: total number of versions of the data that have been stored. The
 7213: C<timestamp> attribute will be the UNIX time the hash was
 7214: stored. C<keys> is available in every historical section to list which
 7215: keys were added or changed at a specific historical revision of a
 7216: hash.
 7217: 
 7218: B<Warning>: do not store the hash that restore returns directly. This
 7219: will cause a mess since it will restore the historical keys as if the
 7220: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7221: 
 7222: Calling convention:
 7223: 
 7224:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7225:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7226: 
 7227: For more detailed information, see lonnet specific documentation.
 7228: 
 7229: =head1 RETURN MESSAGES
 7230: 
 7231: =over 4
 7232: 
 7233: =item * B<con_lost>: unable to contact remote host
 7234: 
 7235: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7236: when the connection is brought back up
 7237: 
 7238: =item * B<con_failed>: unable to contact remote host and unable to save message
 7239: for later delivery
 7240: 
 7241: =item * B<error:>: an error a occured, a description of the error follows the :
 7242: 
 7243: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7244: that was requested
 7245: 
 7246: =back
 7247: 
 7248: =head1 PUBLIC SUBROUTINES
 7249: 
 7250: =head2 Session Environment Functions
 7251: 
 7252: =over 4
 7253: 
 7254: =item * 
 7255: X<appenv()>
 7256: B<appenv(%hash)>: the value of %hash is written to
 7257: the user envirnoment file, and will be restored for each access this
 7258: user makes during this session, also modifies the %env for the current
 7259: process
 7260: 
 7261: =item *
 7262: X<delenv()>
 7263: B<delenv($regexp)>: removes all items from the session
 7264: environment file that matches the regular expression in $regexp. The
 7265: values are also delted from the current processes %env.
 7266: 
 7267: =back
 7268: 
 7269: =head2 User Information
 7270: 
 7271: =over 4
 7272: 
 7273: =item *
 7274: X<queryauthenticate()>
 7275: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7276: authentication scheme
 7277: 
 7278: =item *
 7279: X<authenticate()>
 7280: B<authenticate($uname,$upass,$udom)>: try to
 7281: authenticate user from domain's lib servers (first use the current
 7282: one). C<$upass> should be the users password.
 7283: 
 7284: =item *
 7285: X<homeserver()>
 7286: B<homeserver($uname,$udom)>: find the server which has
 7287: the user's directory and files (there must be only one), this caches
 7288: the answer, and also caches if there is a borken connection.
 7289: 
 7290: =item *
 7291: X<idget()>
 7292: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7293: (IDs are a unique resource in a domain, there must be only 1 ID per
 7294: username, and only 1 username per ID in a specific domain) (returns
 7295: hash: id=>name,id=>name)
 7296: 
 7297: =item *
 7298: X<idrget()>
 7299: B<idrget($udom,@unames)>: find the IDs behind a list of
 7300: usernames (returns hash: name=>id,name=>id)
 7301: 
 7302: =item *
 7303: X<idput()>
 7304: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7305: 
 7306: =item *
 7307: X<rolesinit()>
 7308: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7309: 
 7310: =item *
 7311: X<getsection()>
 7312: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7313: course $cname, return section name/number or '' for "not in course"
 7314: and '-1' for "no section"
 7315: 
 7316: =item *
 7317: X<userenvironment()>
 7318: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7319: passed in @what from the requested user's environment, returns a hash
 7320: 
 7321: =back
 7322: 
 7323: =head2 User Roles
 7324: 
 7325: =over 4
 7326: 
 7327: =item *
 7328: 
 7329: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7330: actions
 7331:  F: full access
 7332:  U,I,K: authentication modes (cxx only)
 7333:  '': forbidden
 7334:  1: user needs to choose course
 7335:  2: browse allowed
 7336: 
 7337: =item *
 7338: 
 7339: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7340: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7341: and course level
 7342: 
 7343: =item *
 7344: 
 7345: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7346: explanation of a user role term
 7347: 
 7348: =back
 7349: 
 7350: =head2 User Modification
 7351: 
 7352: =over 4
 7353: 
 7354: =item *
 7355: 
 7356: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7357: user for the level given by URL.  Optional start and end dates (leave empty
 7358: string or zero for "no date")
 7359: 
 7360: =item *
 7361: 
 7362: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7363: change a users, password, possible return values are: ok,
 7364: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7365: refused
 7366: 
 7367: =item *
 7368: 
 7369: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7370: 
 7371: =item *
 7372: 
 7373: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7374: modify user
 7375: 
 7376: =item *
 7377: 
 7378: modifystudent
 7379: 
 7380: modify a students enrollment and identification information.
 7381: The course id is resolved based on the current users environment.  
 7382: This means the envoking user must be a course coordinator or otherwise
 7383: associated with a course.
 7384: 
 7385: This call is essentially a wrapper for lonnet::modifyuser and
 7386: lonnet::modify_student_enrollment
 7387: 
 7388: Inputs: 
 7389: 
 7390: =over 4
 7391: 
 7392: =item B<$udom> Students loncapa domain
 7393: 
 7394: =item B<$uname> Students loncapa login name
 7395: 
 7396: =item B<$uid> Students id/student number
 7397: 
 7398: =item B<$umode> Students authentication mode
 7399: 
 7400: =item B<$upass> Students password
 7401: 
 7402: =item B<$first> Students first name
 7403: 
 7404: =item B<$middle> Students middle name
 7405: 
 7406: =item B<$last> Students last name
 7407: 
 7408: =item B<$gene> Students generation
 7409: 
 7410: =item B<$usec> Students section in course
 7411: 
 7412: =item B<$end> Unix time of the roles expiration
 7413: 
 7414: =item B<$start> Unix time of the roles start date
 7415: 
 7416: =item B<$forceid> If defined, allow $uid to be changed
 7417: 
 7418: =item B<$desiredhome> server to use as home server for student
 7419: 
 7420: =back
 7421: 
 7422: =item *
 7423: 
 7424: modify_student_enrollment
 7425: 
 7426: Change a students enrollment status in a class.  The environment variable
 7427: 'role.request.course' must be defined for this function to proceed.
 7428: 
 7429: Inputs:
 7430: 
 7431: =over 4
 7432: 
 7433: =item $udom, students domain
 7434: 
 7435: =item $uname, students name
 7436: 
 7437: =item $uid, students user id
 7438: 
 7439: =item $first, students first name
 7440: 
 7441: =item $middle
 7442: 
 7443: =item $last
 7444: 
 7445: =item $gene
 7446: 
 7447: =item $usec
 7448: 
 7449: =item $end
 7450: 
 7451: =item $start
 7452: 
 7453: =back
 7454: 
 7455: 
 7456: =item *
 7457: 
 7458: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7459: custom role; give a custom role to a user for the level given by URL.  Specify
 7460: name and domain of role author, and role name
 7461: 
 7462: =item *
 7463: 
 7464: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7465: 
 7466: =item *
 7467: 
 7468: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7469: 
 7470: =back
 7471: 
 7472: =head2 Course Infomation
 7473: 
 7474: =over 4
 7475: 
 7476: =item *
 7477: 
 7478: coursedescription($courseid) : returns a hash of information about the
 7479: specified course id, including all environment settings for the
 7480: course, the description of the course will be in the hash under the
 7481: key 'description'
 7482: 
 7483: =item *
 7484: 
 7485: resdata($name,$domain,$type,@which) : request for current parameter
 7486: setting for a specific $type, where $type is either 'course' or 'user',
 7487: @what should be a list of parameters to ask about. This routine caches
 7488: answers for 5 minutes.
 7489: 
 7490: =back
 7491: 
 7492: =head2 Course Modification
 7493: 
 7494: =over 4
 7495: 
 7496: =item *
 7497: 
 7498: writecoursepref($courseid,%prefs) : write preferences (environment
 7499: database) for a course
 7500: 
 7501: =item *
 7502: 
 7503: createcourse($udom,$description,$url) : make/modify course
 7504: 
 7505: =back
 7506: 
 7507: =head2 Resource Subroutines
 7508: 
 7509: =over 4
 7510: 
 7511: =item *
 7512: 
 7513: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7514: 
 7515: =item *
 7516: 
 7517: repcopy($filename) : subscribes to the requested file, and attempts to
 7518: replicate from the owning library server, Might return
 7519: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7520: 'bad_request', also attempts to grab the metadata for the
 7521: resource. Expects the local filesystem pathname
 7522: (/home/httpd/html/res/....)
 7523: 
 7524: =back
 7525: 
 7526: =head2 Resource Information
 7527: 
 7528: =over 4
 7529: 
 7530: =item *
 7531: 
 7532: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7533: a vairety of different possible values, $varname should be a request
 7534: string, and the other parameters can be used to specify who and what
 7535: one is asking about.
 7536: 
 7537: Possible values for $varname are environment.lastname (or other item
 7538: from the envirnment hash), user.name (or someother aspect about the
 7539: user), resource.0.maxtries (or some other part and parameter of a
 7540: resource)
 7541: 
 7542: =item *
 7543: 
 7544: directcondval($number) : get current value of a condition; reads from a state
 7545: string
 7546: 
 7547: =item *
 7548: 
 7549: condval($condidx) : value of condition index based on state
 7550: 
 7551: =item *
 7552: 
 7553: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7554: resource's metadata, $what should be either a specific key, or either
 7555: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7556: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7557: 
 7558: this function automatically caches all requests
 7559: 
 7560: =item *
 7561: 
 7562: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7563: network of library servers; returns file handle of where SQL and regex results
 7564: will be stored for query
 7565: 
 7566: =item *
 7567: 
 7568: symbread($filename) : return symbolic list entry (filename argument optional);
 7569: returns the data handle
 7570: 
 7571: =item *
 7572: 
 7573: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7574: a possible symb for the URL in $thisfn, and if is an encryypted
 7575: resource that the user accessed using /enc/ returns a 1 on success, 0
 7576: on failure, user must be in a course, as it assumes the existance of
 7577: the course initial hash, and uses $env('request.course.id'}
 7578: 
 7579: 
 7580: =item *
 7581: 
 7582: symbclean($symb) : removes versions numbers from a symb, returns the
 7583: cleaned symb
 7584: 
 7585: =item *
 7586: 
 7587: is_on_map($uri) : checks if the $uri is somewhere on the current
 7588: course map, user must be in a course for it to work.
 7589: 
 7590: =item *
 7591: 
 7592: numval($salt) : return random seed value (addend for rndseed)
 7593: 
 7594: =item *
 7595: 
 7596: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7597: a random seed, all arguments are optional, if they aren't sent it uses the
 7598: environment to derive them. Note: if symb isn't sent and it can't get one
 7599: from &symbread it will use the current time as its return value
 7600: 
 7601: =item *
 7602: 
 7603: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7604: unfakeable, receipt
 7605: 
 7606: =item *
 7607: 
 7608: receipt() : API to ireceipt working off of env values; given out to users
 7609: 
 7610: =item *
 7611: 
 7612: countacc($url) : count the number of accesses to a given URL
 7613: 
 7614: =item *
 7615: 
 7616: 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
 7617: 
 7618: =item *
 7619: 
 7620: 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)
 7621: 
 7622: =item *
 7623: 
 7624: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7625: 
 7626: =item *
 7627: 
 7628: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7629: forcing spreadsheet to reevaluate the resource scores next time.
 7630: 
 7631: =back
 7632: 
 7633: =head2 Storing/Retreiving Data
 7634: 
 7635: =over 4
 7636: 
 7637: =item *
 7638: 
 7639: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7640: for this url; hashref needs to be given and should be a \%hashname; the
 7641: remaining args aren't required and if they aren't passed or are '' they will
 7642: be derived from the env
 7643: 
 7644: =item *
 7645: 
 7646: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7647: uses critical subroutine
 7648: 
 7649: =item *
 7650: 
 7651: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7652: all args are optional
 7653: 
 7654: =item *
 7655: 
 7656: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7657: dumps the complete (or key matching regexp) namespace into a hash
 7658: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7659: normally &store()ed into
 7660: 
 7661: $range should be either an integer '100' (give me the first 100
 7662:                                            matching records)
 7663:               or be  two integers sperated by a - with no spaces
 7664:                  '30-50' (give me the 30th through the 50th matching
 7665:                           records)
 7666: 
 7667: 
 7668: =item *
 7669: 
 7670: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7671: replaces a &store() version of data with a replacement set of data
 7672: for a particular resource in a namespace passed in the $storehash hash 
 7673: reference
 7674: 
 7675: =item *
 7676: 
 7677: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7678: works very similar to store/cstore, but all data is stored in a
 7679: temporary location and can be reset using tmpreset, $storehash should
 7680: be a hash reference, returns nothing on success
 7681: 
 7682: =item *
 7683: 
 7684: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 7685: similar to restore, but all data is stored in a temporary location and
 7686: can be reset using tmpreset. Returns a hash of values on success,
 7687: error string otherwise.
 7688: 
 7689: =item *
 7690: 
 7691: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 7692: deltes all keys for $symb form the temporary storage hash.
 7693: 
 7694: =item *
 7695: 
 7696: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7697: reference filled in from namesp ($udom and $uname are optional)
 7698: 
 7699: =item *
 7700: 
 7701: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 7702: namesp ($udom and $uname are optional)
 7703: 
 7704: =item *
 7705: 
 7706: dump($namespace,$udom,$uname,$regexp,$range) : 
 7707: dumps the complete (or key matching regexp) namespace into a hash
 7708: ($udom, $uname, $regexp, $range are optional)
 7709: 
 7710: $range should be either an integer '100' (give me the first 100
 7711:                                            matching records)
 7712:               or be  two integers sperated by a - with no spaces
 7713:                  '30-50' (give me the 30th through the 50th matching
 7714:                           records)
 7715: =item *
 7716: 
 7717: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 7718: $store can be a scalar, an array reference, or if the amount to be 
 7719: incremented is > 1, a hash reference.
 7720: 
 7721: ($udom and $uname are optional)
 7722: 
 7723: =item *
 7724: 
 7725: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 7726: ($udom and $uname are optional)
 7727: 
 7728: =item *
 7729: 
 7730: cput($namespace,$storehash,$udom,$uname) : critical put
 7731: ($udom and $uname are optional)
 7732: 
 7733: =item *
 7734: 
 7735: newput($namespace,$storehash,$udom,$uname) :
 7736: 
 7737: Attempts to store the items in the $storehash, but only if they don't
 7738: currently exist, if this succeeds you can be certain that you have 
 7739: successfully created a new key value pair in the $namespace db.
 7740: 
 7741: 
 7742: Args:
 7743:  $namespace: name of database to store values to
 7744:  $storehash: hashref to store to the db
 7745:  $udom: (optional) domain of user containing the db
 7746:  $uname: (optional) name of user caontaining the db
 7747: 
 7748: Returns:
 7749:  'ok' -> succeeded in storing all keys of $storehash
 7750:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 7751:                         least <key> already existed in the db (other
 7752:                         requested keys may also already exist)
 7753:  'error: <msg>' -> unable to tie the DB or other erorr occured
 7754:  'con_lost' -> unable to contact request server
 7755:  'refused' -> action was not allowed by remote machine
 7756: 
 7757: 
 7758: =item *
 7759: 
 7760: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 7761: reference filled in from namesp (encrypts the return communication)
 7762: ($udom and $uname are optional)
 7763: 
 7764: =item *
 7765: 
 7766: log($udom,$name,$home,$message) : write to permanent log for user; use
 7767: critical subroutine
 7768: 
 7769: =back
 7770: 
 7771: =head2 Network Status Functions
 7772: 
 7773: =over 4
 7774: 
 7775: =item *
 7776: 
 7777: dirlist($uri) : return directory list based on URI
 7778: 
 7779: =item *
 7780: 
 7781: spareserver() : find server with least workload from spare.tab
 7782: 
 7783: =back
 7784: 
 7785: =head2 Apache Request
 7786: 
 7787: =over 4
 7788: 
 7789: =item *
 7790: 
 7791: ssi($url,%hash) : server side include, does a complete request cycle on url to
 7792: localhost, posts hash
 7793: 
 7794: =back
 7795: 
 7796: =head2 Data to String to Data
 7797: 
 7798: =over 4
 7799: 
 7800: =item *
 7801: 
 7802: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 7803: and '&' separators, supports elements that are arrayrefs and hashrefs
 7804: 
 7805: =item *
 7806: 
 7807: hashref2str($hashref) : convert a hashref into a string complete with
 7808: escaping and '=' and '&' separators, supports elements that are
 7809: arrayrefs and hashrefs
 7810: 
 7811: =item *
 7812: 
 7813: arrayref2str($arrayref) : convert an arrayref into a string complete
 7814: with escaping and '&' separators, supports elements that are arrayrefs
 7815: and hashrefs
 7816: 
 7817: =item *
 7818: 
 7819: str2hash($string) : convert string to hash using unescaping and
 7820: splitting on '=' and '&', supports elements that are arrayrefs and
 7821: hashrefs
 7822: 
 7823: =item *
 7824: 
 7825: str2array($string) : convert string to hash using unescaping and
 7826: splitting on '&', supports elements that are arrayrefs and hashrefs
 7827: 
 7828: =back
 7829: 
 7830: =head2 Logging Routines
 7831: 
 7832: =over 4
 7833: 
 7834: These routines allow one to make log messages in the lonnet.log and
 7835: lonnet.perm logfiles.
 7836: 
 7837: =item *
 7838: 
 7839: logtouch() : make sure the logfile, lonnet.log, exists
 7840: 
 7841: =item *
 7842: 
 7843: logthis() : append message to the normal lonnet.log file, it gets
 7844: preiodically rolled over and deleted.
 7845: 
 7846: =item *
 7847: 
 7848: logperm() : append a permanent message to lonnet.perm.log, this log
 7849: file never gets deleted by any automated portion of the system, only
 7850: messages of critical importance should go in here.
 7851: 
 7852: =back
 7853: 
 7854: =head2 General File Helper Routines
 7855: 
 7856: =over 4
 7857: 
 7858: =item *
 7859: 
 7860: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 7861: (a) files in /uploaded
 7862:   (i) If a local copy of the file exists - 
 7863:       compares modification date of local copy with last-modified date for 
 7864:       definitive version stored on home server for course. If local copy is 
 7865:       stale, requests a new version from the home server and stores it. 
 7866:       If the original has been removed from the home server, then local copy 
 7867:       is unlinked.
 7868:   (ii) If local copy does not exist -
 7869:       requests the file from the home server and stores it. 
 7870:   
 7871:   If $caller is 'uploadrep':  
 7872:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 7873:     for request for files originally uploaded via DOCS. 
 7874:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 7875:   
 7876:   Otherwise:
 7877:      This indicates a call from the content generation phase of the request.
 7878:      -  returns the entire contents of the file or -1.
 7879:      
 7880: (b) files in /res
 7881:    - returns the entire contents of a file or -1; 
 7882:    it properly subscribes to and replicates the file if neccessary.
 7883: 
 7884: 
 7885: =item *
 7886: 
 7887: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 7888:                   reference
 7889: 
 7890: returns either a stat() list of data about the file or an empty list
 7891: if the file doesn't exist or couldn't find out about it (connection
 7892: problems or user unknown)
 7893: 
 7894: =item *
 7895: 
 7896: filelocation($dir,$file) : returns file system location of a file
 7897: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 7898: directory that relative $file lookups are to looked in ($dir of /a/dir
 7899: and a file of ../bob will become /a/bob)
 7900: 
 7901: =item *
 7902: 
 7903: hreflocation($dir,$file) : returns file system location or a URL; same as
 7904: filelocation except for hrefs
 7905: 
 7906: =item *
 7907: 
 7908: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 7909: 
 7910: =back
 7911: 
 7912: =head2 Usererfile file routines (/uploaded*)
 7913: 
 7914: =over 4
 7915: 
 7916: =item *
 7917: 
 7918: userfileupload(): main rotine for putting a file in a user or course's
 7919:                   filespace, arguments are,
 7920: 
 7921:  formname - required - this is the name of the element in $env where the
 7922:            filename, and the contents of the file to create/modifed exist
 7923:            the filename is in $env{'form.'.$formname.'.filename'} and the
 7924:            contents of the file is located in $env{'form.'.$formname}
 7925:  coursedoc - if true, store the file in the course of the active role
 7926:              of the current user
 7927:  subdir - required - subdirectory to put the file in under ../userfiles/
 7928:          if undefined, it will be placed in "unknown"
 7929: 
 7930:  (This routine calls clean_filename() to remove any dangerous
 7931:  characters from the filename, and then calls finuserfileupload() to
 7932:  complete the transaction)
 7933: 
 7934:  returns either the url of the uploaded file (/uploaded/....) if successful
 7935:  and /adm/notfound.html if unsuccessful
 7936: 
 7937: =item *
 7938: 
 7939: clean_filename(): routine for cleaing a filename up for storage in
 7940:                  userfile space, argument is:
 7941: 
 7942:  filename - proposed filename
 7943: 
 7944: returns: the new clean filename
 7945: 
 7946: =item *
 7947: 
 7948: finishuserfileupload(): routine that creaes and sends the file to
 7949: userspace, probably shouldn't be called directly
 7950: 
 7951:   docuname: username or courseid of destination for the file
 7952:   docudom: domain of user/course of destination for the file
 7953:   formname: same as for userfileupload()
 7954:   fname: filename (inculding subdirectories) for the file
 7955: 
 7956:  returns either the url of the uploaded file (/uploaded/....) if successful
 7957:  and /adm/notfound.html if unsuccessful
 7958: 
 7959: =item *
 7960: 
 7961: renameuserfile(): renames an existing userfile to a new name
 7962: 
 7963:   Args:
 7964:    docuname: username or courseid of destination for the file
 7965:    docudom: domain of user/course of destination for the file
 7966:    old: current file name (including any subdirs under userfiles)
 7967:    new: desired file name (including any subdirs under userfiles)
 7968: 
 7969: =item *
 7970: 
 7971: mkdiruserfile(): creates a directory is a userfiles dir
 7972: 
 7973:   Args:
 7974:    docuname: username or courseid of destination for the file
 7975:    docudom: domain of user/course of destination for the file
 7976:    dir: dir to create (including any subdirs under userfiles)
 7977: 
 7978: =item *
 7979: 
 7980: removeuserfile(): removes a file that exists in userfiles
 7981: 
 7982:   Args:
 7983:    docuname: username or courseid of destination for the file
 7984:    docudom: domain of user/course of destination for the file
 7985:    fname: filname to delete (including any subdirs under userfiles)
 7986: 
 7987: =item *
 7988: 
 7989: removeuploadedurl(): convience function for removeuserfile()
 7990: 
 7991:   Args:
 7992:    url:  a full /uploaded/... url to delete
 7993: 
 7994: =item * 
 7995: 
 7996: get_portfile_permissions():
 7997:   Args:
 7998:     domain: domain of user or course contain the portfolio files
 7999:     user: name of user or num of course contain the portfolio files
 8000:   Returns:
 8001:     hashref of a dump of the proper file_permissions.db
 8002:    
 8003: 
 8004: =item * 
 8005: 
 8006: get_access_controls():
 8007: 
 8008: Args:
 8009:   current_permissions: the hash ref returned from get_portfile_permissions()
 8010:   group: (optional) the group you want the files associated with
 8011:   file: (optional) the file you want access info on
 8012: 
 8013: Returns:
 8014:     a hash (keys are file names) of hashes containing
 8015:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8016:         values are XML containing access control settings (see below) 
 8017: 
 8018: Internal notes:
 8019: 
 8020:  access controls are stored in file_permissions.db as key=value pairs.
 8021:     key -> path to file/file_name\0uniqueID:scope_end_start
 8022:         where scope -> public,guest,course,group,domains or users.
 8023:               end -> UNIX time for end of access (0 -> no end date)
 8024:               start -> UNIX time for start of access
 8025: 
 8026:     value -> XML description of access control
 8027:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8028:             <start></start>
 8029:             <end></end>
 8030: 
 8031:             <password></password>  for scope type = guest
 8032: 
 8033:             <domain></domain>     for scope type = course or group
 8034:             <number></number>
 8035:             <roles id="">
 8036:              <role></role>
 8037:              <access></access>
 8038:              <section></section>
 8039:              <group></group>
 8040:             </roles>
 8041: 
 8042:             <dom></dom>         for scope type = domains
 8043: 
 8044:             <users>             for scope type = users
 8045:              <user>
 8046:               <uname></uname>
 8047:               <udom></udom>
 8048:              </user>
 8049:             </users>
 8050:            </scope> 
 8051:               
 8052:  Access data is also aggregated for each file in an additional key=value pair:
 8053:  key -> path to file/file_name\0accesscontrol 
 8054:  value -> reference to hash
 8055:           hash contains key = value pairs
 8056:           where key = uniqueID:scope_end_start
 8057:                 value = UNIX time record was last updated
 8058: 
 8059:           Used to improve speed of look-ups of access controls for each file.  
 8060:  
 8061:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8062: 
 8063: parse_access_controls():
 8064: 
 8065: Parses XML of an access control record
 8066: Args
 8067: 1. Text string (XML) of access comtrol record
 8068: 
 8069: Returns:
 8070: 1. Hash of access control settings. 
 8071: 
 8072: modify_access_controls():
 8073: 
 8074: Modifies access controls for a portfolio file
 8075: Args
 8076: 1. file name
 8077: 2. reference to hash of required changes,
 8078: 3. domain
 8079: 4. username
 8080:   where domain,username are the domain of the portfolio owner 
 8081:   (either a user or a course) 
 8082: 
 8083: Returns:
 8084: 1. result of additions or updates ('ok' or 'error', with error message). 
 8085: 2. result of deletions ('ok' or 'error', with error message).
 8086: 3. reference to hash of any new or updated access controls.
 8087: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8088:    key = integer (inbound ID)
 8089:    value = uniqueID  
 8090: 
 8091: =back
 8092: 
 8093: =head2 HTTP Helper Routines
 8094: 
 8095: =over 4
 8096: 
 8097: =item *
 8098: 
 8099: escape() : unpack non-word characters into CGI-compatible hex codes
 8100: 
 8101: =item *
 8102: 
 8103: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8104: 
 8105: =back
 8106: 
 8107: =head1 PRIVATE SUBROUTINES
 8108: 
 8109: =head2 Underlying communication routines (Shouldn't call)
 8110: 
 8111: =over 4
 8112: 
 8113: =item *
 8114: 
 8115: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8116: 
 8117: =item *
 8118: 
 8119: reply() : uses subreply to send a message to remote machine, logs all failures
 8120: 
 8121: =item *
 8122: 
 8123: critical() : passes a critical message to another server; if cannot
 8124: get through then place message in connection buffer directory and
 8125: returns con_delayed, if incapable of saving message, returns
 8126: con_failed
 8127: 
 8128: =item *
 8129: 
 8130: reconlonc() : tries to reconnect lonc client processes.
 8131: 
 8132: =back
 8133: 
 8134: =head2 Resource Access Logging
 8135: 
 8136: =over 4
 8137: 
 8138: =item *
 8139: 
 8140: flushcourselogs() : flush (save) buffer logs and access logs
 8141: 
 8142: =item *
 8143: 
 8144: courselog($what) : save message for course in hash
 8145: 
 8146: =item *
 8147: 
 8148: courseacclog($what) : save message for course using &courselog().  Perform
 8149: special processing for specific resource types (problems, exams, quizzes, etc).
 8150: 
 8151: =item *
 8152: 
 8153: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8154: as a PerlChildExitHandler
 8155: 
 8156: =back
 8157: 
 8158: =head2 Other
 8159: 
 8160: =over 4
 8161: 
 8162: =item *
 8163: 
 8164: symblist($mapname,%newhash) : update symbolic storage links
 8165: 
 8166: =back
 8167: 
 8168: =cut

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