File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.764.2.1: download - view: text, annotated - select for diffs
Fri Jul 21 08:40:54 2006 UTC (17 years, 11 months ago) by albertel
CVS tags: version_2_1_99_1
- turn on get_ipHost during server startup for production machines

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

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