File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.824.2.5: download - view: text, annotated - select for diffs
Wed May 2 22:01:32 2007 UTC (17 years, 3 months ago) by albertel
Branches: version_2_3_X
Diff to branchpoint 1.824: preferred, unified
- backport 1.872

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.824.2.5 2007/05/02 22:01:32 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 Math::Random;
   56: use LONCAPA qw(:DEFAULT :match);
   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: sub convert_and_load_session_env {
  296:     my ($lonidsdir,$handle)=@_;
  297:     my @profile;
  298:     {
  299: 	open(my $idf,"$lonidsdir/$handle.id");
  300: 	flock($idf,LOCK_SH);
  301: 	@profile=<$idf>;
  302: 	close($idf);
  303:     }
  304:     my %temp_env;
  305:     foreach my $line (@profile) {
  306: 	if ($line !~ m/=/) {
  307: 	    return 0;
  308: 	}
  309: 	chomp($line);
  310: 	my ($envname,$envvalue)=split(/=/,$line,2);
  311: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  312:     }
  313:     unlink("$lonidsdir/$handle.id");
  314:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  315: 	    0640)) {
  316: 	%disk_env = %temp_env;
  317: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  318: 	untie(%disk_env);
  319:     }
  320:     return 1;
  321: }
  322: 
  323: # ------------------------------------------- Transfer profile into environment
  324: my $env_loaded;
  325: sub transfer_profile_to_env {
  326:     my ($lonidsdir,$handle,$force_transfer) = @_;
  327:     if (!$force_transfer && $env_loaded) { return; } 
  328: 
  329:     if (!defined($lonidsdir)) {
  330: 	$lonidsdir = $perlvar{'lonIDsDir'};
  331:     }
  332:     if (!defined($handle)) {
  333:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  334:     }
  335: 
  336:     my $convert;
  337:     {
  338:     	open(my $idf,"$lonidsdir/$handle.id");
  339: 	flock($idf,LOCK_SH);
  340: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  341: 		&GDBM_READER(),0640)) {
  342: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  343: 	    untie(%disk_env);
  344: 	} else {
  345: 	    $convert = 1;
  346: 	}
  347:     }
  348:     if ($convert) {
  349: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  350: 	    &logthis("Failed to load session, or convert session.");
  351: 	}
  352:     }
  353: 
  354:     my %remove;
  355:     while ( my $envname = each(%env) ) {
  356:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  357:             if ($time < time-300) {
  358:                 $remove{$key}++;
  359:             }
  360:         }
  361:     }
  362: 
  363:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  364:     $env_loaded=1;
  365:     foreach my $expired_key (keys(%remove)) {
  366:         &delenv($expired_key);
  367:     }
  368: }
  369: 
  370: sub timed_flock {
  371:     my ($file,$lock_type) = @_;
  372:     my $failed=0;
  373:     eval {
  374: 	local $SIG{__DIE__}='DEFAULT';
  375: 	local $SIG{ALRM}=sub {
  376: 	    $failed=1;
  377: 	    die("failed lock");
  378: 	};
  379: 	alarm(13);
  380: 	flock($file,$lock_type);
  381: 	alarm(0);
  382:     };
  383:     if ($failed) {
  384: 	return undef;
  385:     } else {
  386: 	return 1;
  387:     }
  388: }
  389: 
  390: # ---------------------------------------------------------- Append Environment
  391: 
  392: sub appenv {
  393:     my %newenv=@_;
  394:     foreach my $key (keys(%newenv)) {
  395: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  396:             &logthis("<font color=\"blue\">WARNING: ".
  397:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  398:                 .'</font>');
  399: 	    delete($newenv{$key});
  400:         } else {
  401:             $env{$key}=$newenv{$key};
  402:         }
  403:     }
  404:     open(my $env_file,$env{'user.environment'});
  405:     if (&timed_flock($env_file,LOCK_EX)
  406: 	&&
  407: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  408: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  409: 	while (my ($key,$value) = each(%newenv)) {
  410: 	    $disk_env{$key} = $value;
  411: 	}
  412: 	untie(%disk_env);
  413:     }
  414:     return 'ok';
  415: }
  416: # ----------------------------------------------------- Delete from Environment
  417: 
  418: sub delenv {
  419:     my $delthis=shift;
  420:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  421:         &logthis("<font color=\"blue\">WARNING: ".
  422:                 "Attempt to delete from environment ".$delthis);
  423:         return 'error';
  424:     }
  425:     open(my $env_file,$env{'user.environment'});
  426:     if (&timed_flock($env_file,LOCK_EX)
  427: 	&&
  428: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  429: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  430: 	foreach my $key (keys(%disk_env)) {
  431: 	    if ($key=~/^$delthis/) { 
  432:                 delete($env{$key});
  433:                 delete($disk_env{$key});
  434:             }
  435: 	}
  436: 	untie(%disk_env);
  437:     }
  438:     return 'ok';
  439: }
  440: 
  441: sub get_env_multiple {
  442:     my ($name) = @_;
  443:     my @values;
  444:     if (defined($env{$name})) {
  445:         # exists is it an array
  446:         if (ref($env{$name})) {
  447:             @values=@{ $env{$name} };
  448:         } else {
  449:             $values[0]=$env{$name};
  450:         }
  451:     }
  452:     return(@values);
  453: }
  454: 
  455: # ------------------------------------------ Find out current server userload
  456: # there is a copy in lond
  457: sub userload {
  458:     my $numusers=0;
  459:     {
  460: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  461: 	my $filename;
  462: 	my $curtime=time;
  463: 	while ($filename=readdir(LONIDS)) {
  464: 	    if ($filename eq '.' || $filename eq '..') {next;}
  465: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  466: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  467: 	}
  468: 	closedir(LONIDS);
  469:     }
  470:     my $userloadpercent=0;
  471:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  472:     if ($maxuserload) {
  473: 	$userloadpercent=100*$numusers/$maxuserload;
  474:     }
  475:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  476:     return $userloadpercent;
  477: }
  478: 
  479: # ------------------------------------------ Fight off request when overloaded
  480: 
  481: sub overloaderror {
  482:     my ($r,$checkserver)=@_;
  483:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  484:     my $loadavg;
  485:     if ($checkserver eq $perlvar{'lonHostID'}) {
  486:        open(my $loadfile,'/proc/loadavg');
  487:        $loadavg=<$loadfile>;
  488:        $loadavg =~ s/\s.*//g;
  489:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  490:        close($loadfile);
  491:     } else {
  492:        $loadavg=&reply('load',$checkserver);
  493:     }
  494:     my $overload=$loadavg-100;
  495:     if ($overload>0) {
  496: 	$r->err_headers_out->{'Retry-After'}=$overload;
  497:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  498:         return 413;
  499:     }    
  500:     return '';
  501: }
  502: 
  503: # ------------------------------ Find server with least workload from spare.tab
  504: 
  505: sub spareserver {
  506:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  507:     my $spare_server;
  508:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  509:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  510:                                                      :  $userloadpercent;
  511:     
  512:     foreach my $try_server (@{ $spareid{'primary'} }) {
  513: 	($spare_server, $lowest_load) =
  514: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  515:     }
  516: 
  517:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  518: 
  519:     if (!$found_server) {
  520: 	foreach my $try_server (@{ $spareid{'default'} }) {
  521: 	    ($spare_server, $lowest_load) =
  522: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  523: 	}
  524:     }
  525: 
  526:     if (!$want_server_name) {
  527: 	$spare_server="http://$hostname{$spare_server}";
  528:     }
  529:     return $spare_server;
  530: }
  531: 
  532: sub compare_server_load {
  533:     my ($try_server, $spare_server, $lowest_load) = @_;
  534: 
  535:     my $loadans     = &reply('load',    $try_server);
  536:     my $userloadans = &reply('userload',$try_server);
  537: 
  538:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  539: 	next; #didn't get a number from the server
  540:     }
  541: 
  542:     my $load;
  543:     if ($loadans =~ /\d/) {
  544: 	if ($userloadans =~ /\d/) {
  545: 	    #both are numbers, pick the bigger one
  546: 	    $load = ($loadans > $userloadans) ? $loadans 
  547: 		                              : $userloadans;
  548: 	} else {
  549: 	    $load = $loadans;
  550: 	}
  551:     } else {
  552: 	$load = $userloadans;
  553:     }
  554: 
  555:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  556: 	$spare_server = $try_server;
  557: 	$lowest_load  = $load;
  558:     }
  559:     return ($spare_server,$lowest_load);
  560: }
  561: # --------------------------------------------- Try to change a user's password
  562: 
  563: sub changepass {
  564:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  565:     $currentpass = &escape($currentpass);
  566:     $newpass     = &escape($newpass);
  567:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  568: 		       $server);
  569:     if (! $answer) {
  570: 	&logthis("No reply on password change request to $server ".
  571: 		 "by $uname in domain $udom.");
  572:     } elsif ($answer =~ "^ok") {
  573:         &logthis("$uname in $udom successfully changed their password ".
  574: 		 "on $server.");
  575:     } elsif ($answer =~ "^pwchange_failure") {
  576: 	&logthis("$uname in $udom was unable to change their password ".
  577: 		 "on $server.  The action was blocked by either lcpasswd ".
  578: 		 "or pwchange");
  579:     } elsif ($answer =~ "^non_authorized") {
  580:         &logthis("$uname in $udom did not get their password correct when ".
  581: 		 "attempting to change it on $server.");
  582:     } elsif ($answer =~ "^auth_mode_error") {
  583:         &logthis("$uname in $udom attempted to change their password despite ".
  584: 		 "not being locally or internally authenticated on $server.");
  585:     } elsif ($answer =~ "^unknown_user") {
  586:         &logthis("$uname in $udom attempted to change their password ".
  587: 		 "on $server but were unable to because $server is not ".
  588: 		 "their home server.");
  589:     } elsif ($answer =~ "^refused") {
  590: 	&logthis("$server refused to change $uname in $udom password because ".
  591: 		 "it was sent an unencrypted request to change the password.");
  592:     }
  593:     return $answer;
  594: }
  595: 
  596: # ----------------------- Try to determine user's current authentication scheme
  597: 
  598: sub queryauthenticate {
  599:     my ($uname,$udom)=@_;
  600:     my $uhome=&homeserver($uname,$udom);
  601:     if (!$uhome) {
  602: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  603: 	return 'no_host';
  604:     }
  605:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  606:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  607: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  608:     }
  609:     return $answer;
  610: }
  611: 
  612: # --------- Try to authenticate user from domain's lib servers (first this one)
  613: 
  614: sub authenticate {
  615:     my ($uname,$upass,$udom)=@_;
  616:     $upass=&escape($upass);
  617:     $uname= &LONCAPA::clean_username($uname);
  618:     my $uhome=&homeserver($uname,$udom);
  619:     if (!$uhome) {
  620: 	&logthis("User $uname at $udom is unknown in authenticate");
  621: 	return 'no_host';
  622:     }
  623:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  624:     if ($answer eq 'authorized') {
  625: 	&logthis("User $uname at $udom authorized by $uhome"); 
  626: 	return $uhome; 
  627:     }
  628:     if ($answer eq 'non_authorized') {
  629: 	&logthis("User $uname at $udom rejected by $uhome");
  630: 	return 'no_host'; 
  631:     }
  632:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  633:     return 'no_host';
  634: }
  635: 
  636: # ---------------------- Find the homebase for a user from domain's lib servers
  637: 
  638: my %homecache;
  639: sub homeserver {
  640:     my ($uname,$udom,$ignoreBadCache)=@_;
  641:     my $index="$uname:$udom";
  642: 
  643:     if (exists($homecache{$index})) { return $homecache{$index}; }
  644:     my $tryserver;
  645:     foreach $tryserver (keys %libserv) {
  646:         next if ($ignoreBadCache ne 'true' && 
  647: 		 exists($badServerCache{$tryserver}));
  648: 	if ($hostdom{$tryserver} eq $udom) {
  649:            my $answer=reply("home:$udom:$uname",$tryserver);
  650:            if ($answer eq 'found') { 
  651: 	       return $homecache{$index}=$tryserver;
  652:            } elsif ($answer eq 'no_host') {
  653: 	       $badServerCache{$tryserver}=1;
  654:            }
  655:        }
  656:     }    
  657:     return 'no_host';
  658: }
  659: 
  660: # ------------------------------------- Find the usernames behind a list of IDs
  661: 
  662: sub idget {
  663:     my ($udom,@ids)=@_;
  664:     my %returnhash=();
  665:     
  666:     my $tryserver;
  667:     foreach $tryserver (keys %libserv) {
  668:        if ($hostdom{$tryserver} eq $udom) {
  669: 	  my $idlist=join('&',@ids);
  670:           $idlist=~tr/A-Z/a-z/; 
  671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  672:           my @answer=();
  673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  674: 	      @answer=split(/\&/,$reply);
  675:           }                    ;
  676:           my $i;
  677:           for ($i=0;$i<=$#ids;$i++) {
  678:               if ($answer[$i]) {
  679: 		  $returnhash{$ids[$i]}=$answer[$i];
  680:               } 
  681:           }
  682:        }
  683:     }    
  684:     return %returnhash;
  685: }
  686: 
  687: # ------------------------------------- Find the IDs behind a list of usernames
  688: 
  689: sub idrget {
  690:     my ($udom,@unames)=@_;
  691:     my %returnhash=();
  692:     foreach my $uname (@unames) {
  693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  694:     }
  695:     return %returnhash;
  696: }
  697: 
  698: # ------------------------------- Store away a list of names and associated IDs
  699: 
  700: sub idput {
  701:     my ($udom,%ids)=@_;
  702:     my %servers=();
  703:     foreach my $uname (keys(%ids)) {
  704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  705:         my $uhom=&homeserver($uname,$udom);
  706:         if ($uhom ne 'no_host') {
  707:             my $id=&escape($ids{$uname});
  708:             $id=~tr/A-Z/a-z/;
  709:             my $esc_unam=&escape($uname);
  710: 	    if ($servers{$uhom}) {
  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  712:             } else {
  713:                 $servers{$uhom}=$id.'='.$esc_unam;
  714:             }
  715:         }
  716:     }
  717:     foreach my $server (keys(%servers)) {
  718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  719:     }
  720: }
  721: 
  722: # ------------------------------------------- get items from domain db files   
  723: 
  724: sub get_dom {
  725:     my ($namespace,$storearr,$udom)=@_;
  726:     my $items='';
  727:     foreach my $item (@$storearr) {
  728:         $items.=&escape($item).'&';
  729:     }
  730:     $items=~s/\&$//;
  731:     if (!$udom) { $udom=$env{'user.domain'}; }
  732:     if (exists($domain_primary{$udom})) {
  733:         my $uhome=$domain_primary{$udom};
  734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  735:         my @pairs=split(/\&/,$rep);
  736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  737:             return @pairs;
  738:         }
  739:         my %returnhash=();
  740:         my $i=0;
  741:         foreach my $item (@$storearr) {
  742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  743:             $i++;
  744:         }
  745:         return %returnhash;
  746:     } else {
  747:         &logthis("get_dom failed - no primary domain server for $udom");
  748:     }
  749: }
  750: 
  751: # -------------------------------------------- put items in domain db files 
  752: 
  753: sub put_dom {
  754:     my ($namespace,$storehash,$udom)=@_;
  755:     if (!$udom) { $udom=$env{'user.domain'}; }
  756:     if (exists($domain_primary{$udom})) {
  757:         my $uhome=$domain_primary{$udom};
  758:         my $items='';
  759:         foreach my $item (keys(%$storehash)) {
  760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  761:         }
  762:         $items=~s/\&$//;
  763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  764:     } else {
  765:         &logthis("put_dom failed - no primary domain server for $udom");
  766:     }
  767: }
  768: 
  769: # --------------------------------------------------- Assign a key to a student
  770: 
  771: sub assign_access_key {
  772: #
  773: # a valid key looks like uname:udom#comments
  774: # comments are being appended
  775: #
  776:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  777:     $kdom=
  778:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  779:     $knum=
  780:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  781:     $cdom=
  782:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  783:     $cnum=
  784:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  785:     $udom=$env{'user.name'} unless (defined($udom));
  786:     $uname=$env{'user.domain'} unless (defined($uname));
  787:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  788:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  789:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  790:                                                   # assigned to this person
  791:                                                   # - this should not happen,
  792:                                                   # unless something went wrong
  793:                                                   # the first time around
  794: # ready to assign
  795:         $logentry=$1.'; '.$logentry;
  796:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  797:                                                  $kdom,$knum) eq 'ok') {
  798: # key now belongs to user
  799: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  800:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  801:                 &appenv('environment.'.$envkey => $ckey);
  802:                 return 'ok';
  803:             } else {
  804:                 return 
  805:   'error: Count not permanently assign key, will need to be re-entered later.';
  806: 	    }
  807:         } else {
  808:             return 'error: Could not assign key, try again later.';
  809:         }
  810:     } elsif (!$existing{$ckey}) {
  811: # the key does not exist
  812: 	return 'error: The key does not exist';
  813:     } else {
  814: # the key is somebody else's
  815: 	return 'error: The key is already in use';
  816:     }
  817: }
  818: 
  819: # ------------------------------------------ put an additional comment on a key
  820: 
  821: sub comment_access_key {
  822: #
  823: # a valid key looks like uname:udom#comments
  824: # comments are being appended
  825: #
  826:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  827:     $cdom=
  828:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  829:     $cnum=
  830:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  831:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  832:     if ($existing{$ckey}) {
  833:         $existing{$ckey}.='; '.$logentry;
  834: # ready to assign
  835:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  836:                                                  $cdom,$cnum) eq 'ok') {
  837: 	    return 'ok';
  838:         } else {
  839: 	    return 'error: Count not store comment.';
  840:         }
  841:     } else {
  842: # the key does not exist
  843: 	return 'error: The key does not exist';
  844:     }
  845: }
  846: 
  847: # ------------------------------------------------------ Generate a set of keys
  848: 
  849: sub generate_access_keys {
  850:     my ($number,$cdom,$cnum,$logentry)=@_;
  851:     $cdom=
  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  853:     $cnum=
  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  855:     unless (&allowed('mky',$cdom)) { return 0; }
  856:     unless (($cdom) && ($cnum)) { return 0; }
  857:     if ($number>10000) { return 0; }
  858:     sleep(2); # make sure don't get same seed twice
  859:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  860:     my $total=0;
  861:     for (my $i=1;$i<=$number;$i++) {
  862:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  863:                   sprintf("%lx",int(100000*rand)).'-'.
  864:                   sprintf("%lx",int(100000*rand));
  865:        $newkey=~s/1/g/g; # folks mix up 1 and l
  866:        $newkey=~s/0/h/g; # and also 0 and O
  867:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  868:        if ($existing{$newkey}) {
  869:            $i--;
  870:        } else {
  871: 	  if (&put('accesskeys',
  872:               { $newkey => '# generated '.localtime().
  873:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  874:                            '; '.$logentry },
  875: 		   $cdom,$cnum) eq 'ok') {
  876:               $total++;
  877: 	  }
  878:        }
  879:     }
  880:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  881:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  882:     return $total;
  883: }
  884: 
  885: # ------------------------------------------------------- Validate an accesskey
  886: 
  887: sub validate_access_key {
  888:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  889:     $cdom=
  890:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  891:     $cnum=
  892:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  893:     $udom=$env{'user.domain'} unless (defined($udom));
  894:     $uname=$env{'user.name'} unless (defined($uname));
  895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  896:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  897: }
  898: 
  899: # ------------------------------------- Find the section of student in a course
  900: sub devalidate_getsection_cache {
  901:     my ($udom,$unam,$courseid)=@_;
  902:     my $hashid="$udom:$unam:$courseid";
  903:     &devalidate_cache_new('getsection',$hashid);
  904: }
  905: 
  906: sub courseid_to_courseurl {
  907:     my ($courseid) = @_;
  908:     #already url style courseid
  909:     return $courseid if ($courseid =~ m{^/});
  910: 
  911:     if (exists($env{'course.'.$courseid.'.num'})) {
  912: 	my $cnum = $env{'course.'.$courseid.'.num'};
  913: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  914: 	return "/$cdom/$cnum";
  915:     }
  916: 
  917:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  918:     if (exists($courseinfo{'num'})) {
  919: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  920:     }
  921: 
  922:     return undef;
  923: }
  924: 
  925: sub getsection {
  926:     my ($udom,$unam,$courseid)=@_;
  927:     my $cachetime=1800;
  928: 
  929:     my $hashid="$udom:$unam:$courseid";
  930:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  931:     if (defined($cached)) { return $result; }
  932: 
  933:     my %Pending; 
  934:     my %Expired;
  935:     #
  936:     # Each role can either have not started yet (pending), be active, 
  937:     #    or have expired.
  938:     #
  939:     # If there is an active role, we are done.
  940:     #
  941:     # If there is more than one role which has not started yet, 
  942:     #     choose the one which will start sooner
  943:     # If there is one role which has not started yet, return it.
  944:     #
  945:     # If there is more than one expired role, choose the one which ended last.
  946:     # If there is a role which has expired, return it.
  947:     #
  948:     $courseid = &courseid_to_courseurl($courseid);
  949:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
  950:     foreach my $key (keys(%roleshash)) {
  951:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  952:         my $section=$1;
  953:         if ($key eq $courseid.'_st') { $section=''; }
  954:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
  955:         my $now=time;
  956:         if (defined($end) && $end && ($now > $end)) {
  957:             $Expired{$end}=$section;
  958:             next;
  959:         }
  960:         if (defined($start) && $start && ($now < $start)) {
  961:             $Pending{$start}=$section;
  962:             next;
  963:         }
  964:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  965:     }
  966:     #
  967:     # Presumedly there will be few matching roles from the above
  968:     # loop and the sorting time will be negligible.
  969:     if (scalar(keys(%Pending))) {
  970:         my ($time) = sort {$a <=> $b} keys(%Pending);
  971:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  972:     } 
  973:     if (scalar(keys(%Expired))) {
  974:         my @sorted = sort {$a <=> $b} keys(%Expired);
  975:         my $time = pop(@sorted);
  976:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  977:     }
  978:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  979: }
  980: 
  981: sub save_cache {
  982:     &purge_remembered();
  983:     #&Apache::loncommon::validate_page();
  984:     undef(%env);
  985:     undef($env_loaded);
  986: }
  987: 
  988: my $to_remember=-1;
  989: my %remembered;
  990: my %accessed;
  991: my $kicks=0;
  992: my $hits=0;
  993: sub make_key {
  994:     my ($name,$id) = @_;
  995:     if (length($id) > 65 
  996: 	&& length(&escape($id)) > 200) {
  997: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
  998:     }
  999:     return &escape($name.':'.$id);
 1000: }
 1001: 
 1002: sub devalidate_cache_new {
 1003:     my ($name,$id,$debug) = @_;
 1004:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1005:     $id=&make_key($name,$id);
 1006:     $memcache->delete($id);
 1007:     delete($remembered{$id});
 1008:     delete($accessed{$id});
 1009: }
 1010: 
 1011: sub is_cached_new {
 1012:     my ($name,$id,$debug) = @_;
 1013:     $id=&make_key($name,$id);
 1014:     if (exists($remembered{$id})) {
 1015: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1016: 	$accessed{$id}=[&gettimeofday()];
 1017: 	$hits++;
 1018: 	return ($remembered{$id},1);
 1019:     }
 1020:     my $value = $memcache->get($id);
 1021:     if (!(defined($value))) {
 1022: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1023: 	return (undef,undef);
 1024:     }
 1025:     if ($value eq '__undef__') {
 1026: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1027: 	$value=undef;
 1028:     }
 1029:     &make_room($id,$value,$debug);
 1030:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1031:     return ($value,1);
 1032: }
 1033: 
 1034: sub do_cache_new {
 1035:     my ($name,$id,$value,$time,$debug) = @_;
 1036:     $id=&make_key($name,$id);
 1037:     my $setvalue=$value;
 1038:     if (!defined($setvalue)) {
 1039: 	$setvalue='__undef__';
 1040:     }
 1041:     if (!defined($time) ) {
 1042: 	$time=600;
 1043:     }
 1044:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1045:     if (!($memcache->set($id,$setvalue,$time))) {
 1046: 	&logthis("caching of id -> $id  failed");
 1047:     }
 1048:     # need to make a copy of $value
 1049:     #&make_room($id,$value,$debug);
 1050:     return $value;
 1051: }
 1052: 
 1053: sub make_room {
 1054:     my ($id,$value,$debug)=@_;
 1055:     $remembered{$id}=$value;
 1056:     if ($to_remember<0) { return; }
 1057:     $accessed{$id}=[&gettimeofday()];
 1058:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1059:     my $to_kick;
 1060:     my $max_time=0;
 1061:     foreach my $other (keys(%accessed)) {
 1062: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1063: 	    $to_kick=$other;
 1064: 	    $max_time=&tv_interval($accessed{$other});
 1065: 	}
 1066:     }
 1067:     delete($remembered{$to_kick});
 1068:     delete($accessed{$to_kick});
 1069:     $kicks++;
 1070:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1071:     return;
 1072: }
 1073: 
 1074: sub purge_remembered {
 1075:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1076:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1077:     undef(%remembered);
 1078:     undef(%accessed);
 1079: }
 1080: # ------------------------------------- Read an entry from a user's environment
 1081: 
 1082: sub userenvironment {
 1083:     my ($udom,$unam,@what)=@_;
 1084:     my %returnhash=();
 1085:     my @answer=split(/\&/,
 1086:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1087:                       &homeserver($unam,$udom)));
 1088:     my $i;
 1089:     for ($i=0;$i<=$#what;$i++) {
 1090: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1091:     }
 1092:     return %returnhash;
 1093: }
 1094: 
 1095: # ---------------------------------------------------------- Get a studentphoto
 1096: sub studentphoto {
 1097:     my ($udom,$unam,$ext) = @_;
 1098:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1099:     if (defined($env{'request.course.id'})) {
 1100:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1101:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1102:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1103:             } else {
 1104:                 my ($result,$perm_reqd)=
 1105: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1106:                 if ($result eq 'ok') {
 1107:                     if (!($perm_reqd eq 'yes')) {
 1108:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1109:                     }
 1110:                 }
 1111:             }
 1112:         }
 1113:     } else {
 1114:         my ($result,$perm_reqd) = 
 1115: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1116:         if ($result eq 'ok') {
 1117:             if (!($perm_reqd eq 'yes')) {
 1118:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1119:             }
 1120:         }
 1121:     }
 1122:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1123: }
 1124: 
 1125: sub retrievestudentphoto {
 1126:     my ($udom,$unam,$ext,$type) = @_;
 1127:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1128:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1129:     if ($ret eq 'ok') {
 1130:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1131:         if ($type eq 'thumbnail') {
 1132:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1133:         }
 1134:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1135:         return $tokenurl;
 1136:     } else {
 1137:         if ($type eq 'thumbnail') {
 1138:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1139:         } else { 
 1140:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1141:         }
 1142:     }
 1143: }
 1144: 
 1145: # -------------------------------------------------------------------- New chat
 1146: 
 1147: sub chatsend {
 1148:     my ($newentry,$anon,$group)=@_;
 1149:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1150:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1151:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1152:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1153: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1154: 		   &escape($newentry)).':'.$group,$chome);
 1155: }
 1156: 
 1157: # ------------------------------------------ Find current version of a resource
 1158: 
 1159: sub getversion {
 1160:     my $fname=&clutter(shift);
 1161:     unless ($fname=~/^\/res\//) { return -1; }
 1162:     return &currentversion(&filelocation('',$fname));
 1163: }
 1164: 
 1165: sub currentversion {
 1166:     my $fname=shift;
 1167:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1168:     if (defined($cached)) { return $result; }
 1169:     my $author=$fname;
 1170:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1171:     my ($udom,$uname)=split(/\//,$author);
 1172:     my $home=homeserver($uname,$udom);
 1173:     if ($home eq 'no_host') { 
 1174:         return -1; 
 1175:     }
 1176:     my $answer=reply("currentversion:$fname",$home);
 1177:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1178: 	return -1;
 1179:     }
 1180:     return &do_cache_new('resversion',$fname,$answer,600);
 1181: }
 1182: 
 1183: # ----------------------------- Subscribe to a resource, return URL if possible
 1184: 
 1185: sub subscribe {
 1186:     my $fname=shift;
 1187:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1188:     $fname=~s/[\n\r]//g;
 1189:     my $author=$fname;
 1190:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1191:     my ($udom,$uname)=split(/\//,$author);
 1192:     my $home=homeserver($uname,$udom);
 1193:     if ($home eq 'no_host') {
 1194:         return 'not_found';
 1195:     }
 1196:     my $answer=reply("sub:$fname",$home);
 1197:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1198: 	$answer.=' by '.$home;
 1199:     }
 1200:     return $answer;
 1201: }
 1202:     
 1203: # -------------------------------------------------------------- Replicate file
 1204: 
 1205: sub repcopy {
 1206:     my $filename=shift;
 1207:     $filename=~s/\/+/\//g;
 1208:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1209:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1210:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1211: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1212: 	return &repcopy_userfile($filename);
 1213:     }
 1214:     $filename=~s/[\n\r]//g;
 1215:     my $transname="$filename.in.transfer";
 1216:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1217:     my $remoteurl=subscribe($filename);
 1218:     if ($remoteurl =~ /^con_lost by/) {
 1219: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1220:            return 'unavailable';
 1221:     } elsif ($remoteurl eq 'not_found') {
 1222: 	   #&logthis("Subscribe returned not_found: $filename");
 1223: 	   return 'not_found';
 1224:     } elsif ($remoteurl =~ /^rejected by/) {
 1225: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1226:            return 'forbidden';
 1227:     } elsif ($remoteurl eq 'directory') {
 1228:            return 'ok';
 1229:     } else {
 1230:         my $author=$filename;
 1231:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1232:         my ($udom,$uname)=split(/\//,$author);
 1233:         my $home=homeserver($uname,$udom);
 1234:         unless ($home eq $perlvar{'lonHostID'}) {
 1235:            my @parts=split(/\//,$filename);
 1236:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1237:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1238:                &logthis("Malconfiguration for replication: $filename");
 1239: 	       return 'bad_request';
 1240:            }
 1241:            my $count;
 1242:            for ($count=5;$count<$#parts;$count++) {
 1243:                $path.="/$parts[$count]";
 1244:                if ((-e $path)!=1) {
 1245: 		   mkdir($path,0777);
 1246:                }
 1247:            }
 1248:            my $ua=new LWP::UserAgent;
 1249:            my $request=new HTTP::Request('GET',"$remoteurl");
 1250:            my $response=$ua->request($request,$transname);
 1251:            if ($response->is_error()) {
 1252: 	       unlink($transname);
 1253:                my $message=$response->status_line;
 1254:                &logthis("<font color=\"blue\">WARNING:"
 1255:                        ." LWP get: $message: $filename</font>");
 1256:                return 'unavailable';
 1257:            } else {
 1258: 	       if ($remoteurl!~/\.meta$/) {
 1259:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1260:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1261:                   if ($mresponse->is_error()) {
 1262: 		      unlink($filename.'.meta');
 1263:                       &logthis(
 1264:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1265:                   }
 1266: 	       }
 1267:                rename($transname,$filename);
 1268:                return 'ok';
 1269:            }
 1270:        }
 1271:     }
 1272: }
 1273: 
 1274: # ------------------------------------------------ Get server side include body
 1275: sub ssi_body {
 1276:     my ($filelink,%form)=@_;
 1277:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1278:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1279:     }
 1280:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1281:                                      &ssi($filelink,%form));
 1282:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1283:     $output=~s/^.*?\<body[^\>]*\>//si;
 1284:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1285:     return $output;
 1286: }
 1287: 
 1288: # --------------------------------------------------------- Server Side Include
 1289: 
 1290: sub absolute_url {
 1291:     my ($host_name) = @_;
 1292:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1293:     if ($host_name eq '') {
 1294: 	$host_name = $ENV{'SERVER_NAME'};
 1295:     }
 1296:     return $protocol.$host_name;
 1297: }
 1298: 
 1299: sub ssi {
 1300: 
 1301:     my ($fn,%form)=@_;
 1302: 
 1303:     my $ua=new LWP::UserAgent;
 1304:     
 1305:     my $request;
 1306: 
 1307:     $form{'no_update_last_known'}=1;
 1308: 
 1309:     if (%form) {
 1310:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1311:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1312:     } else {
 1313:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1314:     }
 1315: 
 1316:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1317:     my $response=$ua->request($request);
 1318: 
 1319:     return $response->content;
 1320: }
 1321: 
 1322: sub externalssi {
 1323:     my ($url)=@_;
 1324:     my $ua=new LWP::UserAgent;
 1325:     my $request=new HTTP::Request('GET',$url);
 1326:     my $response=$ua->request($request);
 1327:     return $response->content;
 1328: }
 1329: 
 1330: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1331: 
 1332: sub allowuploaded {
 1333:     my ($srcurl,$url)=@_;
 1334:     $url=&clutter(&declutter($url));
 1335:     my $dir=$url;
 1336:     $dir=~s/\/[^\/]+$//;
 1337:     my %httpref=();
 1338:     my $httpurl=&hreflocation('',$url);
 1339:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1340:     &Apache::lonnet::appenv(%httpref);
 1341: }
 1342: 
 1343: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1344: # input: action, courseID, current domain, intended
 1345: #        path to file, source of file, instruction to parse file for objects,
 1346: #        ref to hash for embedded objects,
 1347: #        ref to hash for codebase of java objects.
 1348: #
 1349: # output: url to file (if action was uploaddoc), 
 1350: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1351: #
 1352: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1353: # course.
 1354: #
 1355: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1356: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1357: #          course's home server.
 1358: #
 1359: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1360: #          be copied from $source (current location) to 
 1361: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1362: #         and will then be copied to
 1363: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1364: #         course's home server.
 1365: #
 1366: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1367: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1368: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1369: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1370: #         in course's home server.
 1371: #
 1372: 
 1373: sub process_coursefile {
 1374:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1375:     my $fetchresult;
 1376:     my $home=&homeserver($docuname,$docudom);
 1377:     if ($action eq 'propagate') {
 1378:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1379: 			     $home);
 1380:     } else {
 1381:         my $fpath = '';
 1382:         my $fname = $file;
 1383:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1384:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1385:         my $filepath = &build_filepath($fpath);
 1386:         if ($action eq 'copy') {
 1387:             if ($source eq '') {
 1388:                 $fetchresult = 'no source file';
 1389:                 return $fetchresult;
 1390:             } else {
 1391:                 my $destination = $filepath.'/'.$fname;
 1392:                 rename($source,$destination);
 1393:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1394:                                  $home);
 1395:             }
 1396:         } elsif ($action eq 'uploaddoc') {
 1397:             open(my $fh,'>'.$filepath.'/'.$fname);
 1398:             print $fh $env{'form.'.$source};
 1399:             close($fh);
 1400:             if ($parser eq 'parse') {
 1401:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1402:                 unless ($parse_result eq 'ok') {
 1403:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1404:                 }
 1405:             }
 1406:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1407:                                  $home);
 1408:             if ($fetchresult eq 'ok') {
 1409:                 return '/uploaded/'.$fpath.'/'.$fname;
 1410:             } else {
 1411:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1412:                         ' to host '.$home.': '.$fetchresult);
 1413:                 return '/adm/notfound.html';
 1414:             }
 1415:         }
 1416:     }
 1417:     unless ( $fetchresult eq 'ok') {
 1418:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1419:              ' to host '.$home.': '.$fetchresult);
 1420:     }
 1421:     return $fetchresult;
 1422: }
 1423: 
 1424: sub build_filepath {
 1425:     my ($fpath) = @_;
 1426:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1427:     unless ($fpath eq '') {
 1428:         my @parts=split('/',$fpath);
 1429:         foreach my $part (@parts) {
 1430:             $filepath.= '/'.$part;
 1431:             if ((-e $filepath)!=1) {
 1432:                 mkdir($filepath,0777);
 1433:             }
 1434:         }
 1435:     }
 1436:     return $filepath;
 1437: }
 1438: 
 1439: sub store_edited_file {
 1440:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1441:     my $file = $primary_url;
 1442:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1443:     my $fpath = '';
 1444:     my $fname = $file;
 1445:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1446:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1447:     my $filepath = &build_filepath($fpath);
 1448:     open(my $fh,'>'.$filepath.'/'.$fname);
 1449:     print $fh $content;
 1450:     close($fh);
 1451:     my $home=&homeserver($docuname,$docudom);
 1452:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1453: 			  $home);
 1454:     if ($$fetchresult eq 'ok') {
 1455:         return '/uploaded/'.$fpath.'/'.$fname;
 1456:     } else {
 1457:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1458: 		 ' to host '.$home.': '.$$fetchresult);
 1459:         return '/adm/notfound.html';
 1460:     }
 1461: }
 1462: 
 1463: sub clean_filename {
 1464:     my ($fname)=@_;
 1465: # Replace Windows backslashes by forward slashes
 1466:     $fname=~s/\\/\//g;
 1467: # Get rid of everything but the actual filename
 1468:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1469: # Replace spaces by underscores
 1470:     $fname=~s/\s+/\_/g;
 1471: # Replace all other weird characters by nothing
 1472:     $fname=~s/[^\w\.\-]//g;
 1473: # Replace all .\d. sequences with _\d. so they no longer look like version
 1474: # numbers
 1475:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1476:     return $fname;
 1477: }
 1478: 
 1479: # --------------- Take an uploaded file and put it into the userfiles directory
 1480: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1481: #                    the desired filenam is in $env{"form.$formname.filename"}
 1482: #        $coursedoc - if true up to the current course
 1483: #                     if false
 1484: #        $subdir - directory in userfile to store the file into
 1485: #        $parser, $allfiles, $codebase - unknown
 1486: #
 1487: # output: url of file in userspace, or error: <message> 
 1488: #             or /adm/notfound.html if failure to upload occurse
 1489: 
 1490: 
 1491: sub userfileupload {
 1492:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1493:     if (!defined($subdir)) { $subdir='unknown'; }
 1494:     my $fname=$env{'form.'.$formname.'.filename'};
 1495:     $fname=&clean_filename($fname);
 1496: # See if there is anything left
 1497:     unless ($fname) { return 'error: no uploaded file'; }
 1498:     chop($env{'form.'.$formname});
 1499:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1500:         my $now = time;
 1501:         my $filepath = 'tmp/helprequests/'.$now;
 1502:         my @parts=split(/\//,$filepath);
 1503:         my $fullpath = $perlvar{'lonDaemons'};
 1504:         for (my $i=0;$i<@parts;$i++) {
 1505:             $fullpath .= '/'.$parts[$i];
 1506:             if ((-e $fullpath)!=1) {
 1507:                 mkdir($fullpath,0777);
 1508:             }
 1509:         }
 1510:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1511:         print $fh $env{'form.'.$formname};
 1512:         close($fh);
 1513:         return $fullpath.'/'.$fname;
 1514:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1515:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1516:                        '_'.$env{'user.domain'}.'/pending';
 1517:         my @parts=split(/\//,$filepath);
 1518:         my $fullpath = $perlvar{'lonDaemons'};
 1519:         for (my $i=0;$i<@parts;$i++) {
 1520:             $fullpath .= '/'.$parts[$i];
 1521:             if ((-e $fullpath)!=1) {
 1522:                 mkdir($fullpath,0777);
 1523:             }
 1524:         }
 1525:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1526:         print $fh $env{'form.'.$formname};
 1527:         close($fh);
 1528:         return $fullpath.'/'.$fname;
 1529:     }
 1530:     
 1531: # Create the directory if not present
 1532:     $fname="$subdir/$fname";
 1533:     if ($coursedoc) {
 1534: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1535: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1536:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1537:             return &finishuserfileupload($docuname,$docudom,
 1538: 					 $formname,$fname,$parser,$allfiles,
 1539: 					 $codebase);
 1540:         } else {
 1541:             $fname=$env{'form.folder'}.'/'.$fname;
 1542:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1543: 				       $fname,$formname,$parser,
 1544: 				       $allfiles,$codebase);
 1545:         }
 1546:     } elsif (defined($destuname)) {
 1547:         my $docuname=$destuname;
 1548:         my $docudom=$destudom;
 1549: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1550: 				     $fname,$parser,$allfiles,$codebase);
 1551:         
 1552:     } else {
 1553:         my $docuname=$env{'user.name'};
 1554:         my $docudom=$env{'user.domain'};
 1555:         if (exists($env{'form.group'})) {
 1556:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1557:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1558:         }
 1559: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1560: 				     $fname,$parser,$allfiles,$codebase);
 1561:     }
 1562: }
 1563: 
 1564: sub finishuserfileupload {
 1565:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1566:     my $path=$docudom.'/'.$docuname.'/';
 1567:     my $filepath=$perlvar{'lonDocRoot'};
 1568:     my ($fnamepath,$file);
 1569:     $file=$fname;
 1570:     if ($fname=~m|/|) {
 1571:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1572: 	$path.=$fnamepath.'/';
 1573:     }
 1574:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1575:     my $count;
 1576:     for ($count=4;$count<=$#parts;$count++) {
 1577:         $filepath.="/$parts[$count]";
 1578:         if ((-e $filepath)!=1) {
 1579: 	    mkdir($filepath,0777);
 1580:         }
 1581:     }
 1582: # Save the file
 1583:     {
 1584: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1585: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1586: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1587: 	    return '/adm/notfound.html';
 1588: 	}
 1589: 	if (!print FH ($env{'form.'.$formname})) {
 1590: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1591: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1592: 	    return '/adm/notfound.html';
 1593: 	}
 1594: 	close(FH);
 1595:     }
 1596:     if ($parser eq 'parse') {
 1597:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1598: 						   $codebase);
 1599:         unless ($parse_result eq 'ok') {
 1600:             &logthis('Failed to parse '.$filepath.$file.
 1601: 		     ' for embedded media: '.$parse_result); 
 1602:         }
 1603:     }
 1604: # Notify homeserver to grep it
 1605: #
 1606:     my $docuhome=&homeserver($docuname,$docudom);
 1607:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1608:     if ($fetchresult eq 'ok') {
 1609: #
 1610: # Return the URL to it
 1611:         return '/uploaded/'.$path.$file;
 1612:     } else {
 1613:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1614: 		 ': '.$fetchresult);
 1615:         return '/adm/notfound.html';
 1616:     }    
 1617: }
 1618: 
 1619: sub extract_embedded_items {
 1620:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1621:     my @state = ();
 1622:     my %javafiles = (
 1623:                       codebase => '',
 1624:                       code => '',
 1625:                       archive => ''
 1626:                     );
 1627:     my %mediafiles = (
 1628:                       src => '',
 1629:                       movie => '',
 1630:                      );
 1631:     my $p;
 1632:     if ($content) {
 1633:         $p = HTML::LCParser->new($content);
 1634:     } else {
 1635:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1636:     }
 1637:     while (my $t=$p->get_token()) {
 1638: 	if ($t->[0] eq 'S') {
 1639: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1640: 	    push (@state, $tagname);
 1641:             if (lc($tagname) eq 'allow') {
 1642:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1643:             }
 1644: 	    if (lc($tagname) eq 'img') {
 1645: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1646: 	    }
 1647:             if (lc($tagname) eq 'script') {
 1648:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1649:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1650:                 } else {
 1651:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1652:                 }
 1653:             }
 1654:             if (lc($tagname) eq 'link') {
 1655:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1656:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1657:                 }
 1658:             }
 1659: 	    if (lc($tagname) eq 'object' ||
 1660: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1661: 		foreach my $item (keys(%javafiles)) {
 1662: 		    $javafiles{$item} = '';
 1663: 		}
 1664: 	    }
 1665: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1666: 		my $name = lc($attr->{'name'});
 1667: 		foreach my $item (keys(%javafiles)) {
 1668: 		    if ($name eq $item) {
 1669: 			$javafiles{$item} = $attr->{'value'};
 1670: 			last;
 1671: 		    }
 1672: 		}
 1673: 		foreach my $item (keys(%mediafiles)) {
 1674: 		    if ($name eq $item) {
 1675: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1676: 			last;
 1677: 		    }
 1678: 		}
 1679: 	    }
 1680: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1681: 		foreach my $item (keys(%javafiles)) {
 1682: 		    if ($attr->{$item}) {
 1683: 			$javafiles{$item} = $attr->{$item};
 1684: 			last;
 1685: 		    }
 1686: 		}
 1687: 		foreach my $item (keys(%mediafiles)) {
 1688: 		    if ($attr->{$item}) {
 1689: 			&add_filetype($allfiles,$attr->{$item},$item);
 1690: 			last;
 1691: 		    }
 1692: 		}
 1693: 	    }
 1694: 	} elsif ($t->[0] eq 'E') {
 1695: 	    my ($tagname) = ($t->[1]);
 1696: 	    if ($javafiles{'codebase'} ne '') {
 1697: 		$javafiles{'codebase'} .= '/';
 1698: 	    }  
 1699: 	    if (lc($tagname) eq 'applet' ||
 1700: 		lc($tagname) eq 'object' ||
 1701: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1702: 		) {
 1703: 		foreach my $item (keys(%javafiles)) {
 1704: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1705: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1706: 			&add_filetype($allfiles,$file,$item);
 1707: 		    }
 1708: 		}
 1709: 	    } 
 1710: 	    pop @state;
 1711: 	}
 1712:     }
 1713:     return 'ok';
 1714: }
 1715: 
 1716: sub add_filetype {
 1717:     my ($allfiles,$file,$type)=@_;
 1718:     if (exists($allfiles->{$file})) {
 1719: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1720: 	    push(@{$allfiles->{$file}}, &escape($type));
 1721: 	}
 1722:     } else {
 1723: 	@{$allfiles->{$file}} = (&escape($type));
 1724:     }
 1725: }
 1726: 
 1727: sub removeuploadedurl {
 1728:     my ($url)=@_;
 1729:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1730:     return &removeuserfile($uname,$udom,$fname);
 1731: }
 1732: 
 1733: sub removeuserfile {
 1734:     my ($docuname,$docudom,$fname)=@_;
 1735:     my $home=&homeserver($docuname,$docudom);
 1736:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1737:     if ($result eq 'ok') {
 1738:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1739:             my $metafile = $fname.'.meta';
 1740:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1741: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1742:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1743:             my $sqlresult = 
 1744:                 &update_portfolio_table($docuname,$docudom,$file,
 1745:                                         'portfolio_metadata',$group,
 1746:                                         'delete');
 1747:         }
 1748:     }
 1749:     return $result;
 1750: }
 1751: 
 1752: sub mkdiruserfile {
 1753:     my ($docuname,$docudom,$dir)=@_;
 1754:     my $home=&homeserver($docuname,$docudom);
 1755:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1756: }
 1757: 
 1758: sub renameuserfile {
 1759:     my ($docuname,$docudom,$old,$new)=@_;
 1760:     my $home=&homeserver($docuname,$docudom);
 1761:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1762:                         &escape("$old").':'.&escape("$new"),$home);
 1763:     if ($result eq 'ok') {
 1764:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1765:             my $oldmeta = $old.'.meta';
 1766:             my $newmeta = $new.'.meta';
 1767:             my $metaresult = 
 1768:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1769: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1770:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1771:             my $sqlresult = 
 1772:                 &update_portfolio_table($docuname,$docudom,$file,
 1773:                                         'portfolio_metadata',$group,
 1774:                                         'delete');
 1775:         }
 1776:     }
 1777:     return $result;
 1778: }
 1779: 
 1780: # ------------------------------------------------------------------------- Log
 1781: 
 1782: sub log {
 1783:     my ($dom,$nam,$hom,$what)=@_;
 1784:     return critical("log:$dom:$nam:$what",$hom);
 1785: }
 1786: 
 1787: # ------------------------------------------------------------------ Course Log
 1788: #
 1789: # This routine flushes several buffers of non-mission-critical nature
 1790: #
 1791: 
 1792: sub flushcourselogs {
 1793:     &logthis('Flushing log buffers');
 1794: #
 1795: # course logs
 1796: # This is a log of all transactions in a course, which can be used
 1797: # for data mining purposes
 1798: #
 1799: # It also collects the courseid database, which lists last transaction
 1800: # times and course titles for all courseids
 1801: #
 1802:     my %courseidbuffer=();
 1803:     foreach my $crsid (keys %courselogs) {
 1804:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1805: 		          &escape($courselogs{$crsid}),
 1806: 		          $coursehombuf{$crsid}) eq 'ok') {
 1807: 	    delete $courselogs{$crsid};
 1808:         } else {
 1809:             &logthis('Failed to flush log buffer for '.$crsid);
 1810:             if (length($courselogs{$crsid})>40000) {
 1811:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1812:                         " exceeded maximum size, deleting.</font>");
 1813:                delete $courselogs{$crsid};
 1814:             }
 1815:         }
 1816:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1817:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1818: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1819:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1820:         } else {
 1821:            $courseidbuffer{$coursehombuf{$crsid}}=
 1822: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1823:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1824:         }
 1825:     }
 1826: #
 1827: # Write course id database (reverse lookup) to homeserver of courses 
 1828: # Is used in pickcourse
 1829: #
 1830:     foreach my $crsid (keys(%courseidbuffer)) {
 1831:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
 1832:     }
 1833: #
 1834: # File accesses
 1835: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1836: #
 1837:     foreach my $entry (keys(%accesshash)) {
 1838:         if ($entry =~ /___count$/) {
 1839:             my ($dom,$name);
 1840:             ($dom,$name,undef)=
 1841: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1842:             if (! defined($dom) || $dom eq '' || 
 1843:                 ! defined($name) || $name eq '') {
 1844:                 my $cid = $env{'request.course.id'};
 1845:                 $dom  = $env{'request.'.$cid.'.domain'};
 1846:                 $name = $env{'request.'.$cid.'.num'};
 1847:             }
 1848:             my $value = $accesshash{$entry};
 1849:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1850:             my %temphash=($url => $value);
 1851:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1852:             if ($result eq 'ok') {
 1853:                 delete $accesshash{$entry};
 1854:             } elsif ($result eq 'unknown_cmd') {
 1855:                 # Target server has old code running on it.
 1856:                 my %temphash=($entry => $value);
 1857:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1858:                     delete $accesshash{$entry};
 1859:                 }
 1860:             }
 1861:         } else {
 1862:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1863:             my %temphash=($entry => $accesshash{$entry});
 1864:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1865:                 delete $accesshash{$entry};
 1866:             }
 1867:         }
 1868:     }
 1869: #
 1870: # Roles
 1871: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1872: #
 1873:     foreach my $entry (keys(%userrolehash)) {
 1874:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1875: 	    split(/\:/,$entry);
 1876:         if (&Apache::lonnet::put('nohist_userroles',
 1877:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1878:                 $rudom,$runame) eq 'ok') {
 1879: 	    delete $userrolehash{$entry};
 1880:         }
 1881:     }
 1882: #
 1883: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1884: #
 1885:     my %domrolebuffer = ();
 1886:     foreach my $entry (keys %domainrolehash) {
 1887:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1888:         if ($domrolebuffer{$rudom}) {
 1889:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1890:                       '='.&escape($domainrolehash{$entry});
 1891:         } else {
 1892:             $domrolebuffer{$rudom}.=&escape($entry).
 1893:                       '='.&escape($domainrolehash{$entry});
 1894:         }
 1895:         delete $domainrolehash{$entry};
 1896:     }
 1897:     foreach my $dom (keys(%domrolebuffer)) {
 1898:         foreach my $tryserver (keys %libserv) {
 1899:             if ($hostdom{$tryserver} eq $dom) {
 1900:                 unless (&reply('domroleput:'.$dom.':'.
 1901:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1902:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1903:                 }
 1904:             }
 1905:         }
 1906:     }
 1907:     $dumpcount++;
 1908: }
 1909: 
 1910: sub courselog {
 1911:     my $what=shift;
 1912:     $what=time.':'.$what;
 1913:     unless ($env{'request.course.id'}) { return ''; }
 1914:     $coursedombuf{$env{'request.course.id'}}=
 1915:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1916:     $coursenumbuf{$env{'request.course.id'}}=
 1917:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1918:     $coursehombuf{$env{'request.course.id'}}=
 1919:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1920:     $coursedescrbuf{$env{'request.course.id'}}=
 1921:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1922:     $courseinstcodebuf{$env{'request.course.id'}}=
 1923:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1924:     $courseownerbuf{$env{'request.course.id'}}=
 1925:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1926:     $coursetypebuf{$env{'request.course.id'}}=
 1927:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1928:     if (defined $courselogs{$env{'request.course.id'}}) {
 1929: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1930:     } else {
 1931: 	$courselogs{$env{'request.course.id'}}.=$what;
 1932:     }
 1933:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1934: 	&flushcourselogs();
 1935:     }
 1936: }
 1937: 
 1938: sub courseacclog {
 1939:     my $fnsymb=shift;
 1940:     unless ($env{'request.course.id'}) { return ''; }
 1941:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1942:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1943:         $what.=':POST';
 1944:         # FIXME: Probably ought to escape things....
 1945: 	foreach my $key (keys(%env)) {
 1946:             if ($key=~/^form\.(.*)/) {
 1947: 		$what.=':'.$1.'='.$env{$key};
 1948:             }
 1949:         }
 1950:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1951:         # FIXME: We should not be depending on a form parameter that someone
 1952:         # editing lonsearchcat.pm might change in the future.
 1953:         if ($env{'form.phase'} eq 'course_search') {
 1954:             $what.= ':POST';
 1955:             # FIXME: Probably ought to escape things....
 1956:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1957:                                  'crsdiscuss') {
 1958:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1959:             }
 1960:         }
 1961:     }
 1962:     &courselog($what);
 1963: }
 1964: 
 1965: sub countacc {
 1966:     my $url=&declutter(shift);
 1967:     return if (! defined($url) || $url eq '');
 1968:     unless ($env{'request.course.id'}) { return ''; }
 1969:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1970:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1971:     $accesshash{$key}++;
 1972: }
 1973: 
 1974: sub linklog {
 1975:     my ($from,$to)=@_;
 1976:     $from=&declutter($from);
 1977:     $to=&declutter($to);
 1978:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1979:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1980: }
 1981:   
 1982: sub userrolelog {
 1983:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1984:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1985:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1986:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1987:         ($trole=~/^ta/)) {
 1988:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1989:        $userrolehash
 1990:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1991:                     =$tend.':'.$tstart;
 1992:     }
 1993:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1994:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1995:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1996:         ($trole=~/^sc/)) {
 1997:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1998:        $domainrolehash
 1999:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2000:                     = $tend.':'.$tstart;
 2001:     }
 2002: }
 2003: 
 2004: sub get_course_adv_roles {
 2005:     my $cid=shift;
 2006:     $cid=$env{'request.course.id'} unless (defined($cid));
 2007:     my %coursehash=&coursedescription($cid);
 2008:     my %nothide=();
 2009:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2010: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2011:     }
 2012:     my %returnhash=();
 2013:     my %dumphash=
 2014:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2015:     my $now=time;
 2016:     foreach my $entry (keys %dumphash) {
 2017: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2018:         if (($tstart) && ($tstart<0)) { next; }
 2019:         if (($tend) && ($tend<$now)) { next; }
 2020:         if (($tstart) && ($now<$tstart)) { next; }
 2021:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2022: 	if ($username eq '' || $domain eq '') { next; }
 2023: 	if ((&privileged($username,$domain)) && 
 2024: 	    (!$nothide{$username.':'.$domain})) { next; }
 2025: 	if ($role eq 'cr') { next; }
 2026:         my $key=&plaintext($role);
 2027:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2028:         if ($returnhash{$key}) {
 2029: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2030:         } else {
 2031:             $returnhash{$key}=$username.':'.$domain;
 2032:         }
 2033:      }
 2034:     return %returnhash;
 2035: }
 2036: 
 2037: sub get_my_roles {
 2038:     my ($uname,$udom)=@_;
 2039:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2040:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2041:     my %dumphash=
 2042:             &dump('nohist_userroles',$udom,$uname);
 2043:     my %returnhash=();
 2044:     my $now=time;
 2045:     foreach my $entry (keys(%dumphash)) {
 2046: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2047:         if (($tstart) && ($tstart<0)) { next; }
 2048:         if (($tend) && ($tend<$now)) { next; }
 2049:         if (($tstart) && ($now<$tstart)) { next; }
 2050:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2051: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2052:      }
 2053:     return %returnhash;
 2054: }
 2055: 
 2056: # ----------------------------------------------------- Frontpage Announcements
 2057: #
 2058: #
 2059: 
 2060: sub postannounce {
 2061:     my ($server,$text)=@_;
 2062:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 2063:     unless ($text=~/\w/) { $text=''; }
 2064:     return &reply('setannounce:'.&escape($text),$server);
 2065: }
 2066: 
 2067: sub getannounce {
 2068: 
 2069:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2070: 	my $announcement='';
 2071: 	while (my $line = <$fh>) { $announcement .= $line; }
 2072: 	close($fh);
 2073: 	if ($announcement=~/\w/) { 
 2074: 	    return 
 2075:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2076:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2077: 	} else {
 2078: 	    return '';
 2079: 	}
 2080:     } else {
 2081: 	return '';
 2082:     }
 2083: }
 2084: 
 2085: # ---------------------------------------------------------- Course ID routines
 2086: # Deal with domain's nohist_courseid.db files
 2087: #
 2088: 
 2089: sub courseidput {
 2090:     my ($domain,$what,$coursehome)=@_;
 2091:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2092: }
 2093: 
 2094: sub courseiddump {
 2095:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2096:     my %returnhash=();
 2097:     unless ($domfilter) { $domfilter=''; }
 2098:     foreach my $tryserver (keys %libserv) {
 2099:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 2100: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 2101: 	        foreach my $line (
 2102:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 2103: 			       $sincefilter.':'.&escape($descfilter).':'.
 2104:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2105:                                $tryserver))) {
 2106: 		    my ($key,$value)=split(/\=/,$line,2);
 2107:                     if (($key) && ($value)) {
 2108: 		        $returnhash{&unescape($key)}=$value;
 2109:                     }
 2110:                 }
 2111:             }
 2112:         }
 2113:     }
 2114:     return %returnhash;
 2115: }
 2116: 
 2117: # ---------------------------------------------------------- DC e-mail
 2118: 
 2119: sub dcmailput {
 2120:     my ($domain,$msgid,$message,$server)=@_;
 2121:     my $status = &Apache::lonnet::critical(
 2122:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2123:        &escape($message),$server);
 2124:     return $status;
 2125: }
 2126: 
 2127: sub dcmaildump {
 2128:     my ($dom,$startdate,$enddate,$senders) = @_;
 2129:     my %returnhash=();
 2130:     if (exists($domain_primary{$dom})) {
 2131:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2132:                                                          &escape($enddate).':';
 2133: 	my @esc_senders=map { &escape($_)} @$senders;
 2134: 	$cmd.=&escape(join('&',@esc_senders));
 2135: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2136:             my ($key,$value) = split(/\=/,$line,2);
 2137:             if (($key) && ($value)) {
 2138:                 $returnhash{&unescape($key)} = &unescape($value);
 2139:             }
 2140:         }
 2141:     }
 2142:     return %returnhash;
 2143: }
 2144: # ---------------------------------------------------------- Domain roles
 2145: 
 2146: sub get_domain_roles {
 2147:     my ($dom,$roles,$startdate,$enddate)=@_;
 2148:     if (undef($startdate) || $startdate eq '') {
 2149:         $startdate = '.';
 2150:     }
 2151:     if (undef($enddate) || $enddate eq '') {
 2152:         $enddate = '.';
 2153:     }
 2154:     my $rolelist = join(':',@{$roles});
 2155:     my %personnel = ();
 2156:     foreach my $tryserver (keys(%libserv)) {
 2157:         if ($hostdom{$tryserver} eq $dom) {
 2158:             %{$personnel{$tryserver}}=();
 2159:             foreach my $line (
 2160:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2161:                    &escape($startdate).':'.&escape($enddate).':'.
 2162:                    &escape($rolelist), $tryserver))) {
 2163:                 my ($key,$value) = split(/\=/,$line,2);
 2164:                 if (($key) && ($value)) {
 2165:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2166:                 }
 2167:             }
 2168:         }
 2169:     }
 2170:     return %personnel;
 2171: }
 2172: 
 2173: # ----------------------------------------------------------- Check out an item
 2174: 
 2175: sub get_first_access {
 2176:     my ($type,$argsymb)=@_;
 2177:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2178:     if ($argsymb) { $symb=$argsymb; }
 2179:     my ($map,$id,$res)=&decode_symb($symb);
 2180:     if ($type eq 'map') {
 2181: 	$res=&symbread($map);
 2182:     } else {
 2183: 	$res=$symb;
 2184:     }
 2185:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2186:     return $times{"$courseid\0$res"};
 2187: }
 2188: 
 2189: sub set_first_access {
 2190:     my ($type)=@_;
 2191:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2192:     my ($map,$id,$res)=&decode_symb($symb);
 2193:     if ($type eq 'map') {
 2194: 	$res=&symbread($map);
 2195:     } else {
 2196: 	$res=$symb;
 2197:     }
 2198:     my $firstaccess=&get_first_access($type,$symb);
 2199:     if (!$firstaccess) {
 2200: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2201:     }
 2202:     return 'already_set';
 2203: }
 2204: 
 2205: sub checkout {
 2206:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2207:     my $now=time;
 2208:     my $lonhost=$perlvar{'lonHostID'};
 2209:     my $infostr=&escape(
 2210:                  'CHECKOUTTOKEN&'.
 2211:                  $tuname.'&'.
 2212:                  $tudom.'&'.
 2213:                  $tcrsid.'&'.
 2214:                  $symb.'&'.
 2215: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2216:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2217:     if ($token=~/^error\:/) { 
 2218:         &logthis("<font color=\"blue\">WARNING: ".
 2219:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2220:                  "</font>");
 2221:         return ''; 
 2222:     }
 2223: 
 2224:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2225:     $token=~tr/a-z/A-Z/;
 2226: 
 2227:     my %infohash=('resource.0.outtoken' => $token,
 2228:                   'resource.0.checkouttime' => $now,
 2229:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2230: 
 2231:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2232:        return '';
 2233:     } else {
 2234:         &logthis("<font color=\"blue\">WARNING: ".
 2235:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2236:                  "</font>");
 2237:     }    
 2238: 
 2239:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2240:                          &escape('Checkout '.$infostr.' - '.
 2241:                                                  $token)) ne 'ok') {
 2242: 	return '';
 2243:     } else {
 2244:         &logthis("<font color=\"blue\">WARNING: ".
 2245:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2246:                  "</font>");
 2247:     }
 2248:     return $token;
 2249: }
 2250: 
 2251: # ------------------------------------------------------------ Check in an item
 2252: 
 2253: sub checkin {
 2254:     my $token=shift;
 2255:     my $now=time;
 2256:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2257:     $lonhost=~tr/A-Z/a-z/;
 2258:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2259:     $dtoken=~s/\W/\_/g;
 2260:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2261:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2262: 
 2263:     unless (($tuname) && ($tudom)) {
 2264:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2265:         return '';
 2266:     }
 2267:     
 2268:     unless (&allowed('mgr',$tcrsid)) {
 2269:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2270:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2271:         return '';
 2272:     }
 2273: 
 2274:     my %infohash=('resource.0.intoken' => $token,
 2275:                   'resource.0.checkintime' => $now,
 2276:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2277: 
 2278:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2279:        return '';
 2280:     }    
 2281: 
 2282:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2283:                          &escape('Checkin - '.$token)) ne 'ok') {
 2284: 	return '';
 2285:     }
 2286: 
 2287:     return ($symb,$tuname,$tudom,$tcrsid);    
 2288: }
 2289: 
 2290: # --------------------------------------------- Set Expire Date for Spreadsheet
 2291: 
 2292: sub expirespread {
 2293:     my ($uname,$udom,$stype,$usymb)=@_;
 2294:     my $cid=$env{'request.course.id'}; 
 2295:     if ($cid) {
 2296:        my $now=time;
 2297:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2298:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2299:                             $env{'course.'.$cid.'.num'}.
 2300: 	        	    ':nohist_expirationdates:'.
 2301:                             &escape($key).'='.$now,
 2302:                             $env{'course.'.$cid.'.home'})
 2303:     }
 2304:     return 'ok';
 2305: }
 2306: 
 2307: # ----------------------------------------------------- Devalidate Spreadsheets
 2308: 
 2309: sub devalidate {
 2310:     my ($symb,$uname,$udom)=@_;
 2311:     my $cid=$env{'request.course.id'}; 
 2312:     if ($cid) {
 2313:         # delete the stored spreadsheets for
 2314:         # - the student level sheet of this user in course's homespace
 2315:         # - the assessment level sheet for this resource 
 2316:         #   for this user in user's homespace
 2317: 	# - current conditional state info
 2318: 	my $key=$uname.':'.$udom.':';
 2319:         my $status=
 2320: 	    &del('nohist_calculatedsheets',
 2321: 		 [$key.'studentcalc:'],
 2322: 		 $env{'course.'.$cid.'.domain'},
 2323: 		 $env{'course.'.$cid.'.num'})
 2324: 		.' '.
 2325: 	    &del('nohist_calculatedsheets_'.$cid,
 2326: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2327:         unless ($status eq 'ok ok') {
 2328:            &logthis('Could not devalidate spreadsheet '.
 2329:                     $uname.' at '.$udom.' for '.
 2330: 		    $symb.': '.$status);
 2331:         }
 2332: 	&delenv('user.state.'.$cid);
 2333:     }
 2334: }
 2335: 
 2336: sub get_scalar {
 2337:     my ($string,$end) = @_;
 2338:     my $value;
 2339:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2340: 	$value = $1;
 2341:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2342: 	$value = $1;
 2343:     }
 2344:     return &unescape($value);
 2345: }
 2346: 
 2347: sub array2str {
 2348:   my (@array) = @_;
 2349:   my $result=&arrayref2str(\@array);
 2350:   $result=~s/^__ARRAY_REF__//;
 2351:   $result=~s/__END_ARRAY_REF__$//;
 2352:   return $result;
 2353: }
 2354: 
 2355: sub arrayref2str {
 2356:   my ($arrayref) = @_;
 2357:   my $result='__ARRAY_REF__';
 2358:   foreach my $elem (@$arrayref) {
 2359:     if(ref($elem) eq 'ARRAY') {
 2360:       $result.=&arrayref2str($elem).'&';
 2361:     } elsif(ref($elem) eq 'HASH') {
 2362:       $result.=&hashref2str($elem).'&';
 2363:     } elsif(ref($elem)) {
 2364:       #print("Got a ref of ".(ref($elem))." skipping.");
 2365:     } else {
 2366:       $result.=&escape($elem).'&';
 2367:     }
 2368:   }
 2369:   $result=~s/\&$//;
 2370:   $result .= '__END_ARRAY_REF__';
 2371:   return $result;
 2372: }
 2373: 
 2374: sub hash2str {
 2375:   my (%hash) = @_;
 2376:   my $result=&hashref2str(\%hash);
 2377:   $result=~s/^__HASH_REF__//;
 2378:   $result=~s/__END_HASH_REF__$//;
 2379:   return $result;
 2380: }
 2381: 
 2382: sub hashref2str {
 2383:   my ($hashref)=@_;
 2384:   my $result='__HASH_REF__';
 2385:   foreach my $key (sort(keys(%$hashref))) {
 2386:     if (ref($key) eq 'ARRAY') {
 2387:       $result.=&arrayref2str($key).'=';
 2388:     } elsif (ref($key) eq 'HASH') {
 2389:       $result.=&hashref2str($key).'=';
 2390:     } elsif (ref($key)) {
 2391:       $result.='=';
 2392:       #print("Got a ref of ".(ref($key))." skipping.");
 2393:     } else {
 2394: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2395:     }
 2396: 
 2397:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2398:       $result.=&arrayref2str($hashref->{$key}).'&';
 2399:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2400:       $result.=&hashref2str($hashref->{$key}).'&';
 2401:     } elsif(ref($hashref->{$key})) {
 2402:        $result.='&';
 2403:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2404:     } else {
 2405:       $result.=&escape($hashref->{$key}).'&';
 2406:     }
 2407:   }
 2408:   $result=~s/\&$//;
 2409:   $result .= '__END_HASH_REF__';
 2410:   return $result;
 2411: }
 2412: 
 2413: sub str2hash {
 2414:     my ($string)=@_;
 2415:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2416:     return %$hash;
 2417: }
 2418: 
 2419: sub str2hashref {
 2420:   my ($string) = @_;
 2421: 
 2422:   my %hash;
 2423: 
 2424:   if($string !~ /^__HASH_REF__/) {
 2425:       if (! ($string eq '' || !defined($string))) {
 2426: 	  $hash{'error'}='Not hash reference';
 2427:       }
 2428:       return (\%hash, $string);
 2429:   }
 2430: 
 2431:   $string =~ s/^__HASH_REF__//;
 2432: 
 2433:   while($string !~ /^__END_HASH_REF__/) {
 2434:       #key
 2435:       my $key='';
 2436:       if($string =~ /^__HASH_REF__/) {
 2437:           ($key, $string)=&str2hashref($string);
 2438:           if(defined($key->{'error'})) {
 2439:               $hash{'error'}='Bad data';
 2440:               return (\%hash, $string);
 2441:           }
 2442:       } elsif($string =~ /^__ARRAY_REF__/) {
 2443:           ($key, $string)=&str2arrayref($string);
 2444:           if($key->[0] eq 'Array reference error') {
 2445:               $hash{'error'}='Bad data';
 2446:               return (\%hash, $string);
 2447:           }
 2448:       } else {
 2449:           $string =~ s/^(.*?)=//;
 2450: 	  $key=&unescape($1);
 2451:       }
 2452:       $string =~ s/^=//;
 2453: 
 2454:       #value
 2455:       my $value='';
 2456:       if($string =~ /^__HASH_REF__/) {
 2457:           ($value, $string)=&str2hashref($string);
 2458:           if(defined($value->{'error'})) {
 2459:               $hash{'error'}='Bad data';
 2460:               return (\%hash, $string);
 2461:           }
 2462:       } elsif($string =~ /^__ARRAY_REF__/) {
 2463:           ($value, $string)=&str2arrayref($string);
 2464:           if($value->[0] eq 'Array reference error') {
 2465:               $hash{'error'}='Bad data';
 2466:               return (\%hash, $string);
 2467:           }
 2468:       } else {
 2469: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2470:       }
 2471:       $string =~ s/^&//;
 2472: 
 2473:       $hash{$key}=$value;
 2474:   }
 2475: 
 2476:   $string =~ s/^__END_HASH_REF__//;
 2477: 
 2478:   return (\%hash, $string);
 2479: }
 2480: 
 2481: sub str2array {
 2482:     my ($string)=@_;
 2483:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2484:     return @$array;
 2485: }
 2486: 
 2487: sub str2arrayref {
 2488:   my ($string) = @_;
 2489:   my @array;
 2490: 
 2491:   if($string !~ /^__ARRAY_REF__/) {
 2492:       if (! ($string eq '' || !defined($string))) {
 2493: 	  $array[0]='Array reference error';
 2494:       }
 2495:       return (\@array, $string);
 2496:   }
 2497: 
 2498:   $string =~ s/^__ARRAY_REF__//;
 2499: 
 2500:   while($string !~ /^__END_ARRAY_REF__/) {
 2501:       my $value='';
 2502:       if($string =~ /^__HASH_REF__/) {
 2503:           ($value, $string)=&str2hashref($string);
 2504:           if(defined($value->{'error'})) {
 2505:               $array[0] ='Array reference error';
 2506:               return (\@array, $string);
 2507:           }
 2508:       } elsif($string =~ /^__ARRAY_REF__/) {
 2509:           ($value, $string)=&str2arrayref($string);
 2510:           if($value->[0] eq 'Array reference error') {
 2511:               $array[0] ='Array reference error';
 2512:               return (\@array, $string);
 2513:           }
 2514:       } else {
 2515: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2516:       }
 2517:       $string =~ s/^&//;
 2518: 
 2519:       push(@array, $value);
 2520:   }
 2521: 
 2522:   $string =~ s/^__END_ARRAY_REF__//;
 2523: 
 2524:   return (\@array, $string);
 2525: }
 2526: 
 2527: # -------------------------------------------------------------------Temp Store
 2528: 
 2529: sub tmpreset {
 2530:   my ($symb,$namespace,$domain,$stuname) = @_;
 2531:   if (!$symb) {
 2532:     $symb=&symbread();
 2533:     if (!$symb) { $symb= $env{'request.url'}; }
 2534:   }
 2535:   $symb=escape($symb);
 2536: 
 2537:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2538:   $namespace=~s/\//\_/g;
 2539:   $namespace=~s/\W//g;
 2540: 
 2541:   if (!$domain) { $domain=$env{'user.domain'}; }
 2542:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2543:   if ($domain eq 'public' && $stuname eq 'public') {
 2544:       $stuname=$ENV{'REMOTE_ADDR'};
 2545:   }
 2546:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2547:   my %hash;
 2548:   if (tie(%hash,'GDBM_File',
 2549: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2550: 	  &GDBM_WRCREAT(),0640)) {
 2551:     foreach my $key (keys %hash) {
 2552:       if ($key=~ /:$symb/) {
 2553: 	delete($hash{$key});
 2554:       }
 2555:     }
 2556:   }
 2557: }
 2558: 
 2559: sub tmpstore {
 2560:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2561: 
 2562:   if (!$symb) {
 2563:     $symb=&symbread();
 2564:     if (!$symb) { $symb= $env{'request.url'}; }
 2565:   }
 2566:   $symb=escape($symb);
 2567: 
 2568:   if (!$namespace) {
 2569:     # I don't think we would ever want to store this for a course.
 2570:     # it seems this will only be used if we don't have a course.
 2571:     #$namespace=$env{'request.course.id'};
 2572:     #if (!$namespace) {
 2573:       $namespace=$env{'request.state'};
 2574:     #}
 2575:   }
 2576:   $namespace=~s/\//\_/g;
 2577:   $namespace=~s/\W//g;
 2578:   if (!$domain) { $domain=$env{'user.domain'}; }
 2579:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2580:   if ($domain eq 'public' && $stuname eq 'public') {
 2581:       $stuname=$ENV{'REMOTE_ADDR'};
 2582:   }
 2583:   my $now=time;
 2584:   my %hash;
 2585:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2586:   if (tie(%hash,'GDBM_File',
 2587: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2588: 	  &GDBM_WRCREAT(),0640)) {
 2589:     $hash{"version:$symb"}++;
 2590:     my $version=$hash{"version:$symb"};
 2591:     my $allkeys=''; 
 2592:     foreach my $key (keys(%$storehash)) {
 2593:       $allkeys.=$key.':';
 2594:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2595:     }
 2596:     $hash{"$version:$symb:timestamp"}=$now;
 2597:     $allkeys.='timestamp';
 2598:     $hash{"$version:keys:$symb"}=$allkeys;
 2599:     if (untie(%hash)) {
 2600:       return 'ok';
 2601:     } else {
 2602:       return "error:$!";
 2603:     }
 2604:   } else {
 2605:     return "error:$!";
 2606:   }
 2607: }
 2608: 
 2609: # -----------------------------------------------------------------Temp Restore
 2610: 
 2611: sub tmprestore {
 2612:   my ($symb,$namespace,$domain,$stuname) = @_;
 2613: 
 2614:   if (!$symb) {
 2615:     $symb=&symbread();
 2616:     if (!$symb) { $symb= $env{'request.url'}; }
 2617:   }
 2618:   $symb=escape($symb);
 2619: 
 2620:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2621: 
 2622:   if (!$domain) { $domain=$env{'user.domain'}; }
 2623:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2624:   if ($domain eq 'public' && $stuname eq 'public') {
 2625:       $stuname=$ENV{'REMOTE_ADDR'};
 2626:   }
 2627:   my %returnhash;
 2628:   $namespace=~s/\//\_/g;
 2629:   $namespace=~s/\W//g;
 2630:   my %hash;
 2631:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2632:   if (tie(%hash,'GDBM_File',
 2633: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2634: 	  &GDBM_READER(),0640)) {
 2635:     my $version=$hash{"version:$symb"};
 2636:     $returnhash{'version'}=$version;
 2637:     my $scope;
 2638:     for ($scope=1;$scope<=$version;$scope++) {
 2639:       my $vkeys=$hash{"$scope:keys:$symb"};
 2640:       my @keys=split(/:/,$vkeys);
 2641:       my $key;
 2642:       $returnhash{"$scope:keys"}=$vkeys;
 2643:       foreach $key (@keys) {
 2644: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2645: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2646:       }
 2647:     }
 2648:     if (!(untie(%hash))) {
 2649:       return "error:$!";
 2650:     }
 2651:   } else {
 2652:     return "error:$!";
 2653:   }
 2654:   return %returnhash;
 2655: }
 2656: 
 2657: # ----------------------------------------------------------------------- Store
 2658: 
 2659: sub store {
 2660:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2661:     my $home='';
 2662: 
 2663:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2664: 
 2665:     $symb=&symbclean($symb);
 2666:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2667: 
 2668:     if (!$domain) { $domain=$env{'user.domain'}; }
 2669:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2670: 
 2671:     &devalidate($symb,$stuname,$domain);
 2672: 
 2673:     $symb=escape($symb);
 2674:     if (!$namespace) { 
 2675:        unless ($namespace=$env{'request.course.id'}) { 
 2676:           return ''; 
 2677:        } 
 2678:     }
 2679:     if (!$home) { $home=$env{'user.home'}; }
 2680: 
 2681:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2682:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2683: 
 2684:     my $namevalue='';
 2685:     foreach my $key (keys(%$storehash)) {
 2686:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2687:     }
 2688:     $namevalue=~s/\&$//;
 2689:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2690:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2691: }
 2692: 
 2693: # -------------------------------------------------------------- Critical Store
 2694: 
 2695: sub cstore {
 2696:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2697:     my $home='';
 2698: 
 2699:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2700: 
 2701:     $symb=&symbclean($symb);
 2702:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2703: 
 2704:     if (!$domain) { $domain=$env{'user.domain'}; }
 2705:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2706: 
 2707:     &devalidate($symb,$stuname,$domain);
 2708: 
 2709:     $symb=escape($symb);
 2710:     if (!$namespace) { 
 2711:        unless ($namespace=$env{'request.course.id'}) { 
 2712:           return ''; 
 2713:        } 
 2714:     }
 2715:     if (!$home) { $home=$env{'user.home'}; }
 2716: 
 2717:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2718:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2719: 
 2720:     my $namevalue='';
 2721:     foreach my $key (keys(%$storehash)) {
 2722:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2723:     }
 2724:     $namevalue=~s/\&$//;
 2725:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2726:     return critical
 2727:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2728: }
 2729: 
 2730: # --------------------------------------------------------------------- Restore
 2731: 
 2732: sub restore {
 2733:     my ($symb,$namespace,$domain,$stuname) = @_;
 2734:     my $home='';
 2735: 
 2736:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2737: 
 2738:     if (!$symb) {
 2739:       unless ($symb=escape(&symbread())) { return ''; }
 2740:     } else {
 2741:       $symb=&escape(&symbclean($symb));
 2742:     }
 2743:     if (!$namespace) { 
 2744:        unless ($namespace=$env{'request.course.id'}) { 
 2745:           return ''; 
 2746:        } 
 2747:     }
 2748:     if (!$domain) { $domain=$env{'user.domain'}; }
 2749:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2750:     if (!$home) { $home=$env{'user.home'}; }
 2751:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2752: 
 2753:     my %returnhash=();
 2754:     foreach my $line (split(/\&/,$answer)) {
 2755: 	my ($name,$value)=split(/\=/,$line);
 2756:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2757:     }
 2758:     my $version;
 2759:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2760:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2761:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2762:        }
 2763:     }
 2764:     return %returnhash;
 2765: }
 2766: 
 2767: # ---------------------------------------------------------- Course Description
 2768: 
 2769: sub coursedescription {
 2770:     my ($courseid,$args)=@_;
 2771:     $courseid=~s/^\///;
 2772:     $courseid=~s/\_/\//g;
 2773:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2774:     my $chome=&homeserver($cnum,$cdomain);
 2775:     my $normalid=$cdomain.'_'.$cnum;
 2776:     # need to always cache even if we get errors otherwise we keep 
 2777:     # trying and trying and trying to get the course description.
 2778:     my %envhash=();
 2779:     my %returnhash=();
 2780:     
 2781:     my $expiretime=600;
 2782:     if ($env{'request.course.id'} eq $normalid) {
 2783: 	$expiretime=120;
 2784:     }
 2785: 
 2786:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2787:     if (!$args->{'freshen_cache'}
 2788: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2789: 	foreach my $key (keys(%env)) {
 2790: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2791: 	    my ($setting) = $1;
 2792: 	    $returnhash{$setting} = $env{$key};
 2793: 	}
 2794: 	return %returnhash;
 2795:     }
 2796: 
 2797:     # get the data agin
 2798:     if (!$args->{'one_time'}) {
 2799: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2800:     }
 2801: 
 2802:     if ($chome ne 'no_host') {
 2803:        %returnhash=&dump('environment',$cdomain,$cnum);
 2804:        if (!exists($returnhash{'con_lost'})) {
 2805:            $returnhash{'home'}= $chome;
 2806: 	   $returnhash{'domain'} = $cdomain;
 2807: 	   $returnhash{'num'} = $cnum;
 2808:            if (!defined($returnhash{'type'})) {
 2809:                $returnhash{'type'} = 'Course';
 2810:            }
 2811:            while (my ($name,$value) = each %returnhash) {
 2812:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2813:            }
 2814:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2815:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2816: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2817:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2818:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2819:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2820:        }
 2821:     }
 2822:     if (!$args->{'one_time'}) {
 2823: 	&appenv(%envhash);
 2824:     }
 2825:     return %returnhash;
 2826: }
 2827: 
 2828: # -------------------------------------------------See if a user is privileged
 2829: 
 2830: sub privileged {
 2831:     my ($username,$domain)=@_;
 2832:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2833: 			&homeserver($username,$domain));
 2834:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2835:     my $now=time;
 2836:     if ($rolesdump ne '') {
 2837:         foreach my $entry (split(/&/,$rolesdump)) {
 2838: 	    if ($entry!~/^rolesdef_/) {
 2839: 		my ($area,$role)=split(/=/,$entry);
 2840: 		$area=~s/\_\w\w$//;
 2841: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2842: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2843: 		    my $active=1;
 2844: 		    if ($tend) {
 2845: 			if ($tend<$now) { $active=0; }
 2846: 		    }
 2847: 		    if ($tstart) {
 2848: 			if ($tstart>$now) { $active=0; }
 2849: 		    }
 2850: 		    if ($active) { return 1; }
 2851: 		}
 2852: 	    }
 2853: 	}
 2854:     }
 2855:     return 0;
 2856: }
 2857: 
 2858: # -------------------------------------------------------- Get user privileges
 2859: 
 2860: sub rolesinit {
 2861:     my ($domain,$username,$authhost)=@_;
 2862:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2863:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2864:     my %allroles=();
 2865:     my %allgroups=();   
 2866:     my $now=time;
 2867:     my %userroles = ('user.login.time' => $now);
 2868:     my $group_privs;
 2869: 
 2870:     if ($rolesdump ne '') {
 2871:         foreach my $entry (split(/&/,$rolesdump)) {
 2872: 	  if ($entry!~/^rolesdef_/) {
 2873:             my ($area,$role)=split(/=/,$entry);
 2874: 	    $area=~s/\_\w\w$//;
 2875:             my ($trole,$tend,$tstart,$group_privs);
 2876: 	    if ($role=~/^cr/) { 
 2877: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 2878: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 2879: 		    ($tend,$tstart)=split('_',$trest);
 2880: 		} else {
 2881: 		    $trole=$role;
 2882: 		}
 2883:             } elsif ($role =~ m|^gr/|) {
 2884:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2885:                 ($trole,$group_privs) = split(/\//,$trole);
 2886:                 $group_privs = &unescape($group_privs);
 2887: 	    } else {
 2888: 		($trole,$tend,$tstart)=split(/_/,$role);
 2889: 	    }
 2890: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2891: 					 $username);
 2892: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2893:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2894:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2895:             if (($area ne '') && ($trole ne '')) {
 2896: 		my $spec=$trole.'.'.$area;
 2897: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2898: 		if ($trole =~ /^cr\//) {
 2899:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2900:                 } elsif ($trole eq 'gr') {
 2901:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2902: 		} else {
 2903:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2904: 		}
 2905:             }
 2906:           }
 2907:         }
 2908:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2909:         $userroles{'user.adv'}    = $adv;
 2910: 	$userroles{'user.author'} = $author;
 2911:         $env{'user.adv'}=$adv;
 2912:     }
 2913:     return \%userroles;  
 2914: }
 2915: 
 2916: sub set_arearole {
 2917:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2918: # log the associated role with the area
 2919:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2920:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2921: }
 2922: 
 2923: sub custom_roleprivs {
 2924:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2925:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2926:     my $homsvr=homeserver($rauthor,$rdomain);
 2927:     if ($hostname{$homsvr} ne '') {
 2928:         my ($rdummy,$roledef)=
 2929:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2930:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2931:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2932:             if (defined($syspriv)) {
 2933:                 $$allroles{'cm./'}.=':'.$syspriv;
 2934:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2935:             }
 2936:             if ($tdomain ne '') {
 2937:                 if (defined($dompriv)) {
 2938:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2939:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2940:                 }
 2941:                 if (($trest ne '') && (defined($coursepriv))) {
 2942:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2943:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2944:                 }
 2945:             }
 2946:         }
 2947:     }
 2948: }
 2949: 
 2950: sub group_roleprivs {
 2951:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2952:     my $access = 1;
 2953:     my $now = time;
 2954:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2955:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2956:     if ($access) {
 2957:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 2958:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2959:     }
 2960: }
 2961: 
 2962: sub standard_roleprivs {
 2963:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2964:     if (defined($pr{$trole.':s'})) {
 2965:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2966:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2967:     }
 2968:     if ($tdomain ne '') {
 2969:         if (defined($pr{$trole.':d'})) {
 2970:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2971:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2972:         }
 2973:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2974:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2975:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2976:         }
 2977:     }
 2978: }
 2979: 
 2980: sub set_userprivs {
 2981:     my ($userroles,$allroles,$allgroups) = @_; 
 2982:     my $author=0;
 2983:     my $adv=0;
 2984:     my %grouproles = ();
 2985:     if (keys(%{$allgroups}) > 0) {
 2986:         foreach my $role (keys %{$allroles}) {
 2987:             my ($trole,$area,$sec,$extendedarea);
 2988:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 2989:                 $trole = $1;
 2990:                 $area = $2;
 2991:                 $sec = $3;
 2992:                 $extendedarea = $area.$sec;
 2993:                 if (exists($$allgroups{$area})) {
 2994:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2995:                         my $spec = $trole.'.'.$extendedarea;
 2996:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2997:                                                 $$allgroups{$area}{$group};
 2998:                     }
 2999:                 }
 3000:             }
 3001:         }
 3002:     }
 3003:     foreach my $group (keys(%grouproles)) {
 3004:         $$allroles{$group} = $grouproles{$group};
 3005:     }
 3006:     foreach my $role (keys(%{$allroles})) {
 3007:         my %thesepriv;
 3008:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3009:         foreach my $item (split(/:/,$$allroles{$role})) {
 3010:             if ($item ne '') {
 3011:                 my ($privilege,$restrictions)=split(/&/,$item);
 3012:                 if ($restrictions eq '') {
 3013:                     $thesepriv{$privilege}='F';
 3014:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3015:                     $thesepriv{$privilege}.=$restrictions;
 3016:                 }
 3017:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3018:             }
 3019:         }
 3020:         my $thesestr='';
 3021:         foreach my $priv (keys(%thesepriv)) {
 3022: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3023: 	}
 3024:         $userroles->{'user.priv.'.$role} = $thesestr;
 3025:     }
 3026:     return ($author,$adv);
 3027: }
 3028: 
 3029: # --------------------------------------------------------------- get interface
 3030: 
 3031: sub get {
 3032:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3033:    my $items='';
 3034:    foreach my $item (@$storearr) {
 3035:        $items.=&escape($item).'&';
 3036:    }
 3037:    $items=~s/\&$//;
 3038:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3039:    if (!$uname) { $uname=$env{'user.name'}; }
 3040:    my $uhome=&homeserver($uname,$udomain);
 3041: 
 3042:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3043:    my @pairs=split(/\&/,$rep);
 3044:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3045:      return @pairs;
 3046:    }
 3047:    my %returnhash=();
 3048:    my $i=0;
 3049:    foreach my $item (@$storearr) {
 3050:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3051:       $i++;
 3052:    }
 3053:    return %returnhash;
 3054: }
 3055: 
 3056: # --------------------------------------------------------------- del interface
 3057: 
 3058: sub del {
 3059:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3060:    my $items='';
 3061:    foreach my $item (@$storearr) {
 3062:        $items.=&escape($item).'&';
 3063:    }
 3064:    $items=~s/\&$//;
 3065:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3066:    if (!$uname) { $uname=$env{'user.name'}; }
 3067:    my $uhome=&homeserver($uname,$udomain);
 3068: 
 3069:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3070: }
 3071: 
 3072: # -------------------------------------------------------------- dump interface
 3073: 
 3074: sub dump {
 3075:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3077:     if (!$uname) { $uname=$env{'user.name'}; }
 3078:     my $uhome=&homeserver($uname,$udomain);
 3079:     if ($regexp) {
 3080: 	$regexp=&escape($regexp);
 3081:     } else {
 3082: 	$regexp='.';
 3083:     }
 3084:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3085:     my @pairs=split(/\&/,$rep);
 3086:     my %returnhash=();
 3087:     foreach my $item (@pairs) {
 3088: 	my ($key,$value)=split(/=/,$item,2);
 3089: 	$key = &unescape($key);
 3090: 	next if ($key =~ /^error: 2 /);
 3091: 	$returnhash{$key}=&thaw_unescape($value);
 3092:     }
 3093:     return %returnhash;
 3094: }
 3095: 
 3096: # --------------------------------------------------------- dumpstore interface
 3097: 
 3098: sub dumpstore {
 3099:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3101:    if (!$uname) { $uname=$env{'user.name'}; }
 3102:    my $uhome=&homeserver($uname,$udomain);
 3103:    if ($regexp) {
 3104:        $regexp=&escape($regexp);
 3105:    } else {
 3106:        $regexp='.';
 3107:    }
 3108:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3109:    my @pairs=split(/\&/,$rep);
 3110:    my %returnhash=();
 3111:    foreach my $item (@pairs) {
 3112:        my ($key,$value)=split(/=/,$item,2);
 3113:        next if ($key =~ /^error: 2 /);
 3114:        $returnhash{$key}=&thaw_unescape($value);
 3115:    }
 3116:    return %returnhash;
 3117: }
 3118: 
 3119: # -------------------------------------------------------------- keys interface
 3120: 
 3121: sub getkeys {
 3122:    my ($namespace,$udomain,$uname)=@_;
 3123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3124:    if (!$uname) { $uname=$env{'user.name'}; }
 3125:    my $uhome=&homeserver($uname,$udomain);
 3126:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3127:    my @keyarray=();
 3128:    foreach my $key (split(/\&/,$rep)) {
 3129:       next if ($key =~ /^error: 2 /);
 3130:       push(@keyarray,&unescape($key));
 3131:    }
 3132:    return @keyarray;
 3133: }
 3134: 
 3135: # --------------------------------------------------------------- currentdump
 3136: sub currentdump {
 3137:    my ($courseid,$sdom,$sname)=@_;
 3138:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3139:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3140:    $sname    = $env{'user.name'}         if (! defined($sname));
 3141:    my $uhome = &homeserver($sname,$sdom);
 3142:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3143:    return if ($rep =~ /^(error:|no_such_host)/);
 3144:    #
 3145:    my %returnhash=();
 3146:    #
 3147:    if ($rep eq "unknown_cmd") { 
 3148:        # an old lond will not know currentdump
 3149:        # Do a dump and make it look like a currentdump
 3150:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3151:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3152:        my %hash = @tmp;
 3153:        @tmp=();
 3154:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3155:    } else {
 3156:        my @pairs=split(/\&/,$rep);
 3157:        foreach my $pair (@pairs) {
 3158:            my ($key,$value)=split(/=/,$pair,2);
 3159:            my ($symb,$param) = split(/:/,$key);
 3160:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3161:                                                         &thaw_unescape($value);
 3162:        }
 3163:    }
 3164:    return %returnhash;
 3165: }
 3166: 
 3167: sub convert_dump_to_currentdump{
 3168:     my %hash = %{shift()};
 3169:     my %returnhash;
 3170:     # Code ripped from lond, essentially.  The only difference
 3171:     # here is the unescaping done by lonnet::dump().  Conceivably
 3172:     # we might run in to problems with parameter names =~ /^v\./
 3173:     while (my ($key,$value) = each(%hash)) {
 3174:         my ($v,$symb,$param) = split(/:/,$key);
 3175: 	$symb  = &unescape($symb);
 3176: 	$param = &unescape($param);
 3177:         next if ($v eq 'version' || $symb eq 'keys');
 3178:         next if (exists($returnhash{$symb}) &&
 3179:                  exists($returnhash{$symb}->{$param}) &&
 3180:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3181:         $returnhash{$symb}->{$param}=$value;
 3182:         $returnhash{$symb}->{'v.'.$param}=$v;
 3183:     }
 3184:     #
 3185:     # Remove all of the keys in the hashes which keep track of
 3186:     # the version of the parameter.
 3187:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3188:         # use a foreach because we are going to delete from the hash.
 3189:         foreach my $key (keys(%$param_hash)) {
 3190:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3191:         }
 3192:     }
 3193:     return \%returnhash;
 3194: }
 3195: 
 3196: # ------------------------------------------------------ critical inc interface
 3197: 
 3198: sub cinc {
 3199:     return &inc(@_,'critical');
 3200: }
 3201: 
 3202: # --------------------------------------------------------------- inc interface
 3203: 
 3204: sub inc {
 3205:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3206:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3207:     if (!$uname) { $uname=$env{'user.name'}; }
 3208:     my $uhome=&homeserver($uname,$udomain);
 3209:     my $items='';
 3210:     if (! ref($store)) {
 3211:         # got a single value, so use that instead
 3212:         $items = &escape($store).'=&';
 3213:     } elsif (ref($store) eq 'SCALAR') {
 3214:         $items = &escape($$store).'=&';        
 3215:     } elsif (ref($store) eq 'ARRAY') {
 3216:         $items = join('=&',map {&escape($_);} @{$store});
 3217:     } elsif (ref($store) eq 'HASH') {
 3218:         while (my($key,$value) = each(%{$store})) {
 3219:             $items.= &escape($key).'='.&escape($value).'&';
 3220:         }
 3221:     }
 3222:     $items=~s/\&$//;
 3223:     if ($critical) {
 3224: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3225:     } else {
 3226: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3227:     }
 3228: }
 3229: 
 3230: # --------------------------------------------------------------- put interface
 3231: 
 3232: sub put {
 3233:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3235:    if (!$uname) { $uname=$env{'user.name'}; }
 3236:    my $uhome=&homeserver($uname,$udomain);
 3237:    my $items='';
 3238:    foreach my $item (keys(%$storehash)) {
 3239:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3240:    }
 3241:    $items=~s/\&$//;
 3242:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3243: }
 3244: 
 3245: # ------------------------------------------------------------ newput interface
 3246: 
 3247: sub newput {
 3248:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3250:    if (!$uname) { $uname=$env{'user.name'}; }
 3251:    my $uhome=&homeserver($uname,$udomain);
 3252:    my $items='';
 3253:    foreach my $key (keys(%$storehash)) {
 3254:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3255:    }
 3256:    $items=~s/\&$//;
 3257:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3258: }
 3259: 
 3260: # ---------------------------------------------------------  putstore interface
 3261: 
 3262: sub putstore {
 3263:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3264:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3265:    if (!$uname) { $uname=$env{'user.name'}; }
 3266:    my $uhome=&homeserver($uname,$udomain);
 3267:    my $items='';
 3268:    foreach my $key (keys(%$storehash)) {
 3269:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3270:    }
 3271:    $items=~s/\&$//;
 3272:    my $esc_symb=&escape($symb);
 3273:    my $esc_v=&escape($version);
 3274:    my $reply =
 3275:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3276: 	      $uhome);
 3277:    if ($reply eq 'unknown_cmd') {
 3278:        # gfall back to way things use to be done
 3279:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3280: 			    $uname);
 3281:    }
 3282:    return $reply;
 3283: }
 3284: 
 3285: sub old_putstore {
 3286:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3287:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3288:     if (!$uname) { $uname=$env{'user.name'}; }
 3289:     my $uhome=&homeserver($uname,$udomain);
 3290:     my %newstorehash;
 3291:     foreach my $item (keys(%$storehash)) {
 3292: 	my $key = $version.':'.&escape($symb).':'.$item;
 3293: 	$newstorehash{$key} = $storehash->{$item};
 3294:     }
 3295:     my $items='';
 3296:     my %allitems = ();
 3297:     foreach my $item (keys(%newstorehash)) {
 3298: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3299: 	    my $key = $1.':keys:'.$2;
 3300: 	    $allitems{$key} .= $3.':';
 3301: 	}
 3302: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3303:     }
 3304:     foreach my $item (keys(%allitems)) {
 3305: 	$allitems{$item} =~ s/\:$//;
 3306: 	$items.= $item.'='.$allitems{$item}.'&';
 3307:     }
 3308:     $items=~s/\&$//;
 3309:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3310: }
 3311: 
 3312: # ------------------------------------------------------ critical put interface
 3313: 
 3314: sub cput {
 3315:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3317:    if (!$uname) { $uname=$env{'user.name'}; }
 3318:    my $uhome=&homeserver($uname,$udomain);
 3319:    my $items='';
 3320:    foreach my $item (keys(%$storehash)) {
 3321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3322:    }
 3323:    $items=~s/\&$//;
 3324:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3325: }
 3326: 
 3327: # -------------------------------------------------------------- eget interface
 3328: 
 3329: sub eget {
 3330:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3331:    my $items='';
 3332:    foreach my $item (@$storearr) {
 3333:        $items.=&escape($item).'&';
 3334:    }
 3335:    $items=~s/\&$//;
 3336:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3337:    if (!$uname) { $uname=$env{'user.name'}; }
 3338:    my $uhome=&homeserver($uname,$udomain);
 3339:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3340:    my @pairs=split(/\&/,$rep);
 3341:    my %returnhash=();
 3342:    my $i=0;
 3343:    foreach my $item (@$storearr) {
 3344:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3345:       $i++;
 3346:    }
 3347:    return %returnhash;
 3348: }
 3349: 
 3350: # ------------------------------------------------------------ tmpput interface
 3351: sub tmpput {
 3352:     my ($storehash,$server,$context)=@_;
 3353:     my $items='';
 3354:     foreach my $item (keys(%$storehash)) {
 3355: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3356:     }
 3357:     $items=~s/\&$//;
 3358:     if (defined($context)) {
 3359:         $items .= ':'.&escape($context);
 3360:     }
 3361:     return &reply("tmpput:$items",$server);
 3362: }
 3363: 
 3364: # ------------------------------------------------------------ tmpget interface
 3365: sub tmpget {
 3366:     my ($token,$server)=@_;
 3367:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3368:     my $rep=&reply("tmpget:$token",$server);
 3369:     my %returnhash;
 3370:     foreach my $item (split(/\&/,$rep)) {
 3371: 	my ($key,$value)=split(/=/,$item);
 3372: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3373:     }
 3374:     return %returnhash;
 3375: }
 3376: 
 3377: # ------------------------------------------------------------ tmpget interface
 3378: sub tmpdel {
 3379:     my ($token,$server)=@_;
 3380:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3381:     return &reply("tmpdel:$token",$server);
 3382: }
 3383: 
 3384: # -------------------------------------------------- portfolio access checking
 3385: 
 3386: sub portfolio_access {
 3387:     my ($requrl) = @_;
 3388:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3389:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3390:     if ($result) {
 3391:         my %setters;
 3392:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3393:             my ($startblock,$endblock) =
 3394:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3395:             if ($startblock && $endblock) {
 3396:                 return 'B';
 3397:             }
 3398:         } else {
 3399:             my ($startblock,$endblock) =
 3400:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3401:             if ($startblock && $endblock) {
 3402:                 return 'B';
 3403:             }
 3404:         }
 3405:     }
 3406:     if ($result eq 'ok') {
 3407:        return 'F';
 3408:     } elsif ($result =~ /^[^:]+:guest_/) {
 3409:        return 'A';
 3410:     }
 3411:     return '';
 3412: }
 3413: 
 3414: sub get_portfolio_access {
 3415:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3416: 
 3417:     if (!ref($access_hash)) {
 3418: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3419: 	my %access_controls = &get_access_controls($current_perms,$group,
 3420: 						   $file_name);
 3421: 	$access_hash = $access_controls{$file_name};
 3422:     }
 3423: 
 3424:     my ($public,$guest,@domains,@users,@courses,@groups);
 3425:     my $now = time;
 3426:     if (ref($access_hash) eq 'HASH') {
 3427:         foreach my $key (keys(%{$access_hash})) {
 3428:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3429:             if ($start > $now) {
 3430:                 next;
 3431:             }
 3432:             if ($end && $end<$now) {
 3433:                 next;
 3434:             }
 3435:             if ($scope eq 'public') {
 3436:                 $public = $key;
 3437:                 last;
 3438:             } elsif ($scope eq 'guest') {
 3439:                 $guest = $key;
 3440:             } elsif ($scope eq 'domains') {
 3441:                 push(@domains,$key);
 3442:             } elsif ($scope eq 'users') {
 3443:                 push(@users,$key);
 3444:             } elsif ($scope eq 'course') {
 3445:                 push(@courses,$key);
 3446:             } elsif ($scope eq 'group') {
 3447:                 push(@groups,$key);
 3448:             }
 3449:         }
 3450:         if ($public) {
 3451:             return 'ok';
 3452:         }
 3453:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3454:             if ($guest) {
 3455:                 return $guest;
 3456:             }
 3457:         } else {
 3458:             if (@domains > 0) {
 3459:                 foreach my $domkey (@domains) {
 3460:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3461:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3462:                             return 'ok';
 3463:                         }
 3464:                     }
 3465:                 }
 3466:             }
 3467:             if (@users > 0) {
 3468:                 foreach my $userkey (@users) {
 3469:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3470:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3471:                             if (ref($item) eq 'HASH') {
 3472:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3473:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3474:                                     return 'ok';
 3475:                                 }
 3476:                             }
 3477:                         }
 3478:                     } 
 3479:                 }
 3480:             }
 3481:             my %roleshash;
 3482:             my @courses_and_groups = @courses;
 3483:             push(@courses_and_groups,@groups); 
 3484:             if (@courses_and_groups > 0) {
 3485:                 my (%allgroups,%allroles); 
 3486:                 my ($start,$end,$role,$sec,$group);
 3487:                 foreach my $envkey (%env) {
 3488:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3489:                         my $cid = $2.'_'.$3; 
 3490:                         if ($1 eq 'gr') {
 3491:                             $group = $4;
 3492:                             $allgroups{$cid}{$group} = $env{$envkey};
 3493:                         } else {
 3494:                             if ($4 eq '') {
 3495:                                 $sec = 'none';
 3496:                             } else {
 3497:                                 $sec = $4;
 3498:                             }
 3499:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3500:                         }
 3501:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3502:                         my $cid = $2.'_'.$3;
 3503:                         if ($4 eq '') {
 3504:                             $sec = 'none';
 3505:                         } else {
 3506:                             $sec = $4;
 3507:                         }
 3508:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3509:                     }
 3510:                 }
 3511:                 if (keys(%allroles) == 0) {
 3512:                     return;
 3513:                 }
 3514:                 foreach my $key (@courses_and_groups) {
 3515:                     my %content = %{$$access_hash{$key}};
 3516:                     my $cnum = $content{'number'};
 3517:                     my $cdom = $content{'domain'};
 3518:                     my $cid = $cdom.'_'.$cnum;
 3519:                     if (!exists($allroles{$cid})) {
 3520:                         next;
 3521:                     }    
 3522:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3523:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3524:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3525:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3526:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3527:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3528:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3529:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3530:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3531:                                         if (grep/^all$/,@sections) {
 3532:                                             return 'ok';
 3533:                                         } else {
 3534:                                             if (grep/^$sec$/,@sections) {
 3535:                                                 return 'ok';
 3536:                                             }
 3537:                                         }
 3538:                                     }
 3539:                                 }
 3540:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3541:                                     if (grep/^none$/,@groups) {
 3542:                                         return 'ok';
 3543:                                     }
 3544:                                 } else {
 3545:                                     if (grep/^all$/,@groups) {
 3546:                                         return 'ok';
 3547:                                     } 
 3548:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3549:                                         if (grep/^$group$/,@groups) {
 3550:                                             return 'ok';
 3551:                                         }
 3552:                                     }
 3553:                                 } 
 3554:                             }
 3555:                         }
 3556:                     }
 3557:                 }
 3558:             }
 3559:             if ($guest) {
 3560:                 return $guest;
 3561:             }
 3562:         }
 3563:     }
 3564:     return;
 3565: }
 3566: 
 3567: sub course_group_datechecker {
 3568:     my ($dates,$now,$status) = @_;
 3569:     my ($start,$end) = split(/\./,$dates);
 3570:     if (!$start && !$end) {
 3571:         return 'ok';
 3572:     }
 3573:     if (grep/^active$/,@{$status}) {
 3574:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3575:             return 'ok';
 3576:         }
 3577:     }
 3578:     if (grep/^previous$/,@{$status}) {
 3579:         if ($end > $now ) {
 3580:             return 'ok';
 3581:         }
 3582:     }
 3583:     if (grep/^future$/,@{$status}) {
 3584:         if ($start > $now) {
 3585:             return 'ok';
 3586:         }
 3587:     }
 3588:     return; 
 3589: }
 3590: 
 3591: sub parse_portfolio_url {
 3592:     my ($url) = @_;
 3593: 
 3594:     my ($type,$udom,$unum,$group,$file_name);
 3595:     
 3596:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3597: 	$type = 1;
 3598:         $udom = $1;
 3599:         $unum = $2;
 3600:         $file_name = $3;
 3601:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3602: 	$type = 2;
 3603:         $udom = $1;
 3604:         $unum = $2;
 3605:         $group = $3;
 3606:         $file_name = $3.'/'.$4;
 3607:     }
 3608:     if (wantarray) {
 3609: 	return ($type,$udom,$unum,$file_name,$group);
 3610:     }
 3611:     return $type;
 3612: }
 3613: 
 3614: sub is_portfolio_url {
 3615:     my ($url) = @_;
 3616:     return scalar(&parse_portfolio_url($url));
 3617: }
 3618: 
 3619: sub is_portfolio_file {
 3620:     my ($file) = @_;
 3621:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3622:         return 1;
 3623:     }
 3624:     return;
 3625: }
 3626: 
 3627: 
 3628: # ---------------------------------------------- Custom access rule evaluation
 3629: 
 3630: sub customaccess {
 3631:     my ($priv,$uri)=@_;
 3632:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3633:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3634:     $udom = &LONCAPA::clean_domain($udom);
 3635:     $ucrs = &LONCAPA::clean_username($ucrs);
 3636:     my $access=0;
 3637:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3638: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3639:         if ($role) {
 3640: 	   if ($role ne $urole) { next; }
 3641:         }
 3642:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3643:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3644:             if ($tdom) {
 3645: 		if ($tdom ne $udom) { next; }
 3646:             }
 3647:             if ($tcrs) {
 3648: 		if ($tcrs ne $ucrs) { next; }
 3649:             }
 3650:             if ($tsec) {
 3651: 		if ($tsec ne $usec) { next; }
 3652:             }
 3653:             $access=($effect eq 'allow');
 3654:             last;
 3655:         }
 3656: 	if ($realm eq '' && $role eq '') {
 3657:             $access=($effect eq 'allow');
 3658: 	}
 3659:     }
 3660:     return $access;
 3661: }
 3662: 
 3663: # ------------------------------------------------- Check for a user privilege
 3664: 
 3665: sub allowed {
 3666:     my ($priv,$uri,$symb,$role)=@_;
 3667:     my $ver_orguri=$uri;
 3668:     $uri=&deversion($uri);
 3669:     my $orguri=$uri;
 3670:     $uri=&declutter($uri);
 3671: 
 3672:     if ($priv eq 'evb') {
 3673: # Evade communication block restrictions for specified role in a course
 3674:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3675:             return $1;
 3676:         } else {
 3677:             return;
 3678:         }
 3679:     }
 3680: 
 3681:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3682: # Free bre access to adm and meta resources
 3683:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3684: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3685: 	&& ($priv eq 'bre')) {
 3686: 	return 'F';
 3687:     }
 3688: 
 3689: # Free bre access to user's own portfolio contents
 3690:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3691:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3692: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3693:         my %setters;
 3694:         my ($startblock,$endblock) = 
 3695:             &Apache::loncommon::blockcheck(\%setters,'port');
 3696:         if ($startblock && $endblock) {
 3697:             return 'B';
 3698:         } else {
 3699:             return 'F';
 3700:         }
 3701:     }
 3702: 
 3703: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3704:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3705:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3706:         if (exists($env{'request.course.id'})) {
 3707:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3708:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3709:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3710:                 my $courseprivid=$env{'request.course.id'};
 3711:                 $courseprivid=~s/\_/\//;
 3712:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3713:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3714:                     return $1; 
 3715:                 } else {
 3716:                     if ($env{'request.course.sec'}) {
 3717:                         $courseprivid.='/'.$env{'request.course.sec'};
 3718:                     }
 3719:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3720:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3721:                         return $2;
 3722:                     }
 3723:                 }
 3724:             }
 3725:         }
 3726:     }
 3727: 
 3728: # Free bre to public access
 3729: 
 3730:     if ($priv eq 'bre') {
 3731:         my $copyright=&metadata($uri,'copyright');
 3732: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3733:            return 'F'; 
 3734:         }
 3735:         if ($copyright eq 'priv') {
 3736:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3737: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3738: 		return '';
 3739:             }
 3740:         }
 3741:         if ($copyright eq 'domain') {
 3742:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3743: 	    unless (($env{'user.domain'} eq $1) ||
 3744:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3745: 		return '';
 3746:             }
 3747:         }
 3748:         if ($env{'request.role'}=~ /li\.\//) {
 3749:             # Library role, so allow browsing of resources in this domain.
 3750:             return 'F';
 3751:         }
 3752:         if ($copyright eq 'custom') {
 3753: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3754:         }
 3755:     }
 3756:     # Domain coordinator is trying to create a course
 3757:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3758:         # uri is the requested domain in this case.
 3759:         # comparison to 'request.role.domain' shows if the user has selected
 3760:         # a role of dc for the domain in question.
 3761:         return 'F' if ($uri eq $env{'request.role.domain'});
 3762:     }
 3763: 
 3764:     my $thisallowed='';
 3765:     my $statecond=0;
 3766:     my $courseprivid='';
 3767: 
 3768: # Course
 3769: 
 3770:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3771:        $thisallowed.=$1;
 3772:     }
 3773: 
 3774: # Domain
 3775: 
 3776:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3777:        =~/\Q$priv\E\&([^\:]*)/) {
 3778:        $thisallowed.=$1;
 3779:     }
 3780: 
 3781: # Course: uri itself is a course
 3782:     my $courseuri=$uri;
 3783:     $courseuri=~s/\_(\d)/\/$1/;
 3784:     $courseuri=~s/^([^\/])/\/$1/;
 3785: 
 3786:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3787:        =~/\Q$priv\E\&([^\:]*)/) {
 3788:        $thisallowed.=$1;
 3789:     }
 3790: 
 3791: # URI is an uploaded document for this course, default permissions don't matter
 3792: # not allowing 'edit' access (editupload) to uploaded course docs
 3793:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3794: 	$thisallowed='';
 3795:         my ($match)=&is_on_map($uri);
 3796:         if ($match) {
 3797:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3798:                   =~/\Q$priv\E\&([^\:]*)/) {
 3799:                 $thisallowed.=$1;
 3800:             }
 3801:         } else {
 3802:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3803:             if ($refuri) {
 3804:                 if ($refuri =~ m|^/adm/|) {
 3805:                     $thisallowed='F';
 3806:                 } else {
 3807:                     $refuri=&declutter($refuri);
 3808:                     my ($match) = &is_on_map($refuri);
 3809:                     if ($match) {
 3810:                         $thisallowed='F';
 3811:                     }
 3812:                 }
 3813:             }
 3814:         }
 3815:     }
 3816: 
 3817:     if ($priv eq 'bre'
 3818: 	&& $thisallowed ne 'F' 
 3819: 	&& $thisallowed ne '2'
 3820: 	&& &is_portfolio_url($uri)) {
 3821: 	$thisallowed = &portfolio_access($uri);
 3822:     }
 3823:     
 3824: # Full access at system, domain or course-wide level? Exit.
 3825: 
 3826:     if ($thisallowed=~/F/) {
 3827: 	return 'F';
 3828:     }
 3829: 
 3830: # If this is generating or modifying users, exit with special codes
 3831: 
 3832:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3833: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3834: 	    my ($audom,$auname)=split('/',$uri);
 3835: # no author name given, so this just checks on the general right to make a co-author in this domain
 3836: 	    unless ($auname) { return $thisallowed; }
 3837: # an author name is given, so we are about to actually make a co-author for a certain account
 3838: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3839: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3840: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3841: 	}
 3842: 	return $thisallowed;
 3843:     }
 3844: #
 3845: # Gathered so far: system, domain and course wide privileges
 3846: #
 3847: # Course: See if uri or referer is an individual resource that is part of 
 3848: # the course
 3849: 
 3850:     if ($env{'request.course.id'}) {
 3851: 
 3852:        $courseprivid=$env{'request.course.id'};
 3853:        if ($env{'request.course.sec'}) {
 3854:           $courseprivid.='/'.$env{'request.course.sec'};
 3855:        }
 3856:        $courseprivid=~s/\_/\//;
 3857:        my $checkreferer=1;
 3858:        my ($match,$cond)=&is_on_map($uri);
 3859:        if ($match) {
 3860:            $statecond=$cond;
 3861:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3862:                =~/\Q$priv\E\&([^\:]*)/) {
 3863:                $thisallowed.=$1;
 3864:                $checkreferer=0;
 3865:            }
 3866:        }
 3867:        
 3868:        if ($checkreferer) {
 3869: 	  my $refuri=$env{'httpref.'.$orguri};
 3870:             unless ($refuri) {
 3871:                 foreach my $key (keys(%env)) {
 3872: 		    if ($key=~/^httpref\..*\*/) {
 3873: 			my $pattern=$key;
 3874:                         $pattern=~s/^httpref\.\/res\///;
 3875:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3876:                         $pattern=~s/\//\\\//g;
 3877:                         if ($orguri=~/$pattern/) {
 3878: 			    $refuri=$env{$key};
 3879:                         }
 3880:                     }
 3881:                 }
 3882:             }
 3883: 
 3884:          if ($refuri) { 
 3885: 	  $refuri=&declutter($refuri);
 3886:           my ($match,$cond)=&is_on_map($refuri);
 3887:             if ($match) {
 3888:               my $refstatecond=$cond;
 3889:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3890:                   =~/\Q$priv\E\&([^\:]*)/) {
 3891:                   $thisallowed.=$1;
 3892:                   $uri=$refuri;
 3893:                   $statecond=$refstatecond;
 3894:               }
 3895:           }
 3896:         }
 3897:        }
 3898:    }
 3899: 
 3900: #
 3901: # Gathered now: all privileges that could apply, and condition number
 3902: # 
 3903: #
 3904: # Full or no access?
 3905: #
 3906: 
 3907:     if ($thisallowed=~/F/) {
 3908: 	return 'F';
 3909:     }
 3910: 
 3911:     unless ($thisallowed) {
 3912:         return '';
 3913:     }
 3914: 
 3915: # Restrictions exist, deal with them
 3916: #
 3917: #   C:according to course preferences
 3918: #   R:according to resource settings
 3919: #   L:unless locked
 3920: #   X:according to user session state
 3921: #
 3922: 
 3923: # Possibly locked functionality, check all courses
 3924: # Locks might take effect only after 10 minutes cache expiration for other
 3925: # courses, and 2 minutes for current course
 3926: 
 3927:     my $envkey;
 3928:     if ($thisallowed=~/L/) {
 3929:         foreach $envkey (keys %env) {
 3930:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3931:                my $courseid=$2;
 3932:                my $roleid=$1.'.'.$2;
 3933:                $courseid=~s/^\///;
 3934:                my $expiretime=600;
 3935:                if ($env{'request.role'} eq $roleid) {
 3936: 		  $expiretime=120;
 3937:                }
 3938: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3939:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3940:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3941: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3942:                }
 3943:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3944:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3945: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3946:                        &log($env{'user.domain'},$env{'user.name'},
 3947:                             $env{'user.home'},
 3948:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3949:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3950:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3951: 		       return '';
 3952:                    }
 3953:                }
 3954:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3955:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3956: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3957:                        &log($env{'user.domain'},$env{'user.name'},
 3958:                             $env{'user.home'},
 3959:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3960:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3961:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3962: 		       return '';
 3963:                    }
 3964:                }
 3965: 	   }
 3966:        }
 3967:     }
 3968:    
 3969: #
 3970: # Rest of the restrictions depend on selected course
 3971: #
 3972: 
 3973:     unless ($env{'request.course.id'}) {
 3974: 	if ($thisallowed eq 'A') {
 3975: 	    return 'A';
 3976:         } elsif ($thisallowed eq 'B') {
 3977:             return 'B';
 3978: 	} else {
 3979: 	    return '1';
 3980: 	}
 3981:     }
 3982: 
 3983: #
 3984: # Now user is definitely in a course
 3985: #
 3986: 
 3987: 
 3988: # Course preferences
 3989: 
 3990:    if ($thisallowed=~/C/) {
 3991:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3992:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3993:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3994: 	   =~/\Q$rolecode\E/) {
 3995: 	   if ($priv ne 'pch') { 
 3996: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3997: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3998: 			$env{'request.course.id'});
 3999: 	   }
 4000:            return '';
 4001:        }
 4002: 
 4003:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4004: 	   =~/\Q$unamedom\E/) {
 4005: 	   if ($priv ne 'pch') { 
 4006: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4007: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4008: 			$env{'request.course.id'});
 4009: 	   }
 4010:            return '';
 4011:        }
 4012:    }
 4013: 
 4014: # Resource preferences
 4015: 
 4016:    if ($thisallowed=~/R/) {
 4017:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4018:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4019: 	   if ($priv ne 'pch') { 
 4020: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4021: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4022: 	   }
 4023: 	   return '';
 4024:        }
 4025:    }
 4026: 
 4027: # Restricted by state or randomout?
 4028: 
 4029:    if ($thisallowed=~/X/) {
 4030:       if ($env{'acc.randomout'}) {
 4031: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4032:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4033:             return ''; 
 4034:          }
 4035:       }
 4036:       if (&condval($statecond)) {
 4037: 	 return '2';
 4038:       } else {
 4039:          return '';
 4040:       }
 4041:    }
 4042: 
 4043:     if ($thisallowed eq 'A') {
 4044: 	return 'A';
 4045:     } elsif ($thisallowed eq 'B') {
 4046:         return 'B';
 4047:     }
 4048:    return 'F';
 4049: }
 4050: 
 4051: sub split_uri_for_cond {
 4052:     my $uri=&deversion(&declutter(shift));
 4053:     my @uriparts=split(/\//,$uri);
 4054:     my $filename=pop(@uriparts);
 4055:     my $pathname=join('/',@uriparts);
 4056:     return ($pathname,$filename);
 4057: }
 4058: # --------------------------------------------------- Is a resource on the map?
 4059: 
 4060: sub is_on_map {
 4061:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4062:     #Trying to find the conditional for the file
 4063:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4064: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4065:     if ($match) {
 4066: 	return (1,$1);
 4067:     } else {
 4068: 	return (0,0);
 4069:     }
 4070: }
 4071: 
 4072: # --------------------------------------------------------- Get symb from alias
 4073: 
 4074: sub get_symb_from_alias {
 4075:     my $symb=shift;
 4076:     my ($map,$resid,$url)=&decode_symb($symb);
 4077: # Already is a symb
 4078:     if ($url) { return $symb; }
 4079: # Must be an alias
 4080:     my $aliassymb='';
 4081:     my %bighash;
 4082:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4083:                             &GDBM_READER(),0640)) {
 4084:         my $rid=$bighash{'mapalias_'.$symb};
 4085: 	if ($rid) {
 4086: 	    my ($mapid,$resid)=split(/\./,$rid);
 4087: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4088: 				    $resid,$bighash{'src_'.$rid});
 4089: 	}
 4090:         untie %bighash;
 4091:     }
 4092:     return $aliassymb;
 4093: }
 4094: 
 4095: # ----------------------------------------------------------------- Define Role
 4096: 
 4097: sub definerole {
 4098:   if (allowed('mcr','/')) {
 4099:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4100:     foreach my $role (split(':',$sysrole)) {
 4101: 	my ($crole,$cqual)=split(/\&/,$role);
 4102:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4103:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4104: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4105:                return "refused:s:$crole&$cqual"; 
 4106:             }
 4107:         }
 4108:     }
 4109:     foreach my $role (split(':',$domrole)) {
 4110: 	my ($crole,$cqual)=split(/\&/,$role);
 4111:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4112:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4113: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4114:                return "refused:d:$crole&$cqual"; 
 4115:             }
 4116:         }
 4117:     }
 4118:     foreach my $role (split(':',$courole)) {
 4119: 	my ($crole,$cqual)=split(/\&/,$role);
 4120:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4121:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4122: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4123:                return "refused:c:$crole&$cqual"; 
 4124:             }
 4125:         }
 4126:     }
 4127:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4128:                 "$env{'user.domain'}:$env{'user.name'}:".
 4129: 	        "rolesdef_$rolename=".
 4130:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4131:     return reply($command,$env{'user.home'});
 4132:   } else {
 4133:     return 'refused';
 4134:   }
 4135: }
 4136: 
 4137: # ---------------- Make a metadata query against the network of library servers
 4138: 
 4139: sub metadata_query {
 4140:     my ($query,$custom,$customshow,$server_array)=@_;
 4141:     my %rhash;
 4142:     my @server_list = (defined($server_array) ? @$server_array
 4143:                                               : keys(%libserv) );
 4144:     for my $server (@server_list) {
 4145: 	unless ($custom or $customshow) {
 4146: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4147: 	    $rhash{$server}=$reply;
 4148: 	}
 4149: 	else {
 4150: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4151: 			     &escape($custom).':'.&escape($customshow),
 4152: 			     $server);
 4153: 	    $rhash{$server}=$reply;
 4154: 	}
 4155:     }
 4156:     return \%rhash;
 4157: }
 4158: 
 4159: # ----------------------------------------- Send log queries and wait for reply
 4160: 
 4161: sub log_query {
 4162:     my ($uname,$udom,$query,%filters)=@_;
 4163:     my $uhome=&homeserver($uname,$udom);
 4164:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4165:     my $uhost=$hostname{$uhome};
 4166:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4167:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4168:                        $uhome);
 4169:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4170:     return get_query_reply($queryid);
 4171: }
 4172: 
 4173: # -------------------------- Update MySQL table for portfolio file
 4174: 
 4175: sub update_portfolio_table {
 4176:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4177:     my $homeserver = &homeserver($uname,$udom);
 4178:     my $queryid=
 4179:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4180:                ':'.&escape($file_name).':'.$action,$homeserver);
 4181:     my $reply = &get_query_reply($queryid);
 4182:     return $reply;
 4183: }
 4184: 
 4185: # ------- Request retrieval of institutional classlists for course(s)
 4186: 
 4187: sub fetch_enrollment_query {
 4188:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4189:     my $homeserver;
 4190:     my $maxtries = 1;
 4191:     if ($context eq 'automated') {
 4192:         $homeserver = $perlvar{'lonHostID'};
 4193:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4194:     } else {
 4195:         $homeserver = &homeserver($cnum,$dom);
 4196:     }
 4197:     my $host=$hostname{$homeserver};
 4198:     my $cmd = '';
 4199:     foreach my $affiliate (keys %{$affiliatesref}) {
 4200:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4201:     }
 4202:     $cmd =~ s/%%$//;
 4203:     $cmd = &escape($cmd);
 4204:     my $query = 'fetchenrollment';
 4205:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4206:     unless ($queryid=~/^\Q$host\E\_/) { 
 4207:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4208:         return 'error: '.$queryid;
 4209:     }
 4210:     my $reply = &get_query_reply($queryid);
 4211:     my $tries = 1;
 4212:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4213:         $reply = &get_query_reply($queryid);
 4214:         $tries ++;
 4215:     }
 4216:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4217:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4218:     } else {
 4219:         my @responses = split/:/,$reply;
 4220:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4221:             foreach my $line (@responses) {
 4222:                 my ($key,$value) = split(/=/,$line,2);
 4223:                 $$replyref{$key} = $value;
 4224:             }
 4225:         } else {
 4226:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4227:             foreach my $line (@responses) {
 4228:                 my ($key,$value) = split(/=/,$line);
 4229:                 $$replyref{$key} = $value;
 4230:                 if ($value > 0) {
 4231:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4232:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4233:                         my $destname = $pathname.'/'.$filename;
 4234:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4235:                         if ($xml_classlist =~ /^error/) {
 4236:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4237:                         } else {
 4238:                             if ( open(FILE,">$destname") ) {
 4239:                                 print FILE &unescape($xml_classlist);
 4240:                                 close(FILE);
 4241:                             } else {
 4242:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4243:                             }
 4244:                         }
 4245:                     }
 4246:                 }
 4247:             }
 4248:         }
 4249:         return 'ok';
 4250:     }
 4251:     return 'error';
 4252: }
 4253: 
 4254: sub get_query_reply {
 4255:     my $queryid=shift;
 4256:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4257:     my $reply='';
 4258:     for (1..100) {
 4259: 	sleep 2;
 4260:         if (-e $replyfile.'.end') {
 4261: 	    if (open(my $fh,$replyfile)) {
 4262:                $reply.=<$fh>;
 4263:                close($fh);
 4264: 	   } else { return 'error: reply_file_error'; }
 4265:            return &unescape($reply);
 4266: 	}
 4267:     }
 4268:     return 'timeout:'.$queryid;
 4269: }
 4270: 
 4271: sub courselog_query {
 4272: #
 4273: # possible filters:
 4274: # url: url or symb
 4275: # username
 4276: # domain
 4277: # action: view, submit, grade
 4278: # start: timestamp
 4279: # end: timestamp
 4280: #
 4281:     my (%filters)=@_;
 4282:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4283:     if ($filters{'url'}) {
 4284: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4285:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4286:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4287:     }
 4288:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4289:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4290:     return &log_query($cname,$cdom,'courselog',%filters);
 4291: }
 4292: 
 4293: sub userlog_query {
 4294:     my ($uname,$udom,%filters)=@_;
 4295:     return &log_query($uname,$udom,'userlog',%filters);
 4296: }
 4297: 
 4298: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4299: 
 4300: sub auto_run {
 4301:     my ($cnum,$cdom) = @_;
 4302:     my $homeserver = &homeserver($cnum,$cdom);
 4303:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4304:     return $response;
 4305: }
 4306: 
 4307: sub auto_get_sections {
 4308:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4309:     my $homeserver = &homeserver($cnum,$cdom);
 4310:     my @secs = ();
 4311:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4312:     unless ($response eq 'refused') {
 4313:         @secs = split/:/,$response;
 4314:     }
 4315:     return @secs;
 4316: }
 4317: 
 4318: sub auto_new_course {
 4319:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4320:     my $homeserver = &homeserver($cnum,$cdom);
 4321:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4322:     return $response;
 4323: }
 4324: 
 4325: sub auto_validate_courseID {
 4326:     my ($cnum,$cdom,$inst_course_id) = @_;
 4327:     my $homeserver = &homeserver($cnum,$cdom);
 4328:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4329:     return $response;
 4330: }
 4331: 
 4332: sub auto_create_password {
 4333:     my ($cnum,$cdom,$authparam) = @_;
 4334:     my $homeserver = &homeserver($cnum,$cdom); 
 4335:     my $create_passwd = 0;
 4336:     my $authchk = '';
 4337:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4338:     if ($response eq 'refused') {
 4339:         $authchk = 'refused';
 4340:     } else {
 4341:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4342:     }
 4343:     return ($authparam,$create_passwd,$authchk);
 4344: }
 4345: 
 4346: sub auto_photo_permission {
 4347:     my ($cnum,$cdom,$students) = @_;
 4348:     my $homeserver = &homeserver($cnum,$cdom);
 4349:     my ($outcome,$perm_reqd,$conditions) = 
 4350: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4351:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4352: 	return (undef,undef);
 4353:     }
 4354:     return ($outcome,$perm_reqd,$conditions);
 4355: }
 4356: 
 4357: sub auto_checkphotos {
 4358:     my ($uname,$udom,$pid) = @_;
 4359:     my $homeserver = &homeserver($uname,$udom);
 4360:     my ($result,$resulttype);
 4361:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4362: 				   &escape($uname).':'.&escape($pid),
 4363: 				   $homeserver));
 4364:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4365: 	return (undef,undef);
 4366:     }
 4367:     if ($outcome) {
 4368:         ($result,$resulttype) = split(/:/,$outcome);
 4369:     } 
 4370:     return ($result,$resulttype);
 4371: }
 4372: 
 4373: sub auto_photochoice {
 4374:     my ($cnum,$cdom) = @_;
 4375:     my $homeserver = &homeserver($cnum,$cdom);
 4376:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4377: 						       &escape($cdom),
 4378: 						       $homeserver)));
 4379:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4380: 	return (undef,undef);
 4381:     }
 4382:     return ($update,$comment);
 4383: }
 4384: 
 4385: sub auto_photoupdate {
 4386:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4387:     my $homeserver = &homeserver($cnum,$dom);
 4388:     my $host=$hostname{$homeserver};
 4389:     my $cmd = '';
 4390:     my $maxtries = 1;
 4391:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4392:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4393:     }
 4394:     $cmd =~ s/%%$//;
 4395:     $cmd = &escape($cmd);
 4396:     my $query = 'institutionalphotos';
 4397:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4398:     unless ($queryid=~/^\Q$host\E\_/) {
 4399:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4400:         return 'error: '.$queryid;
 4401:     }
 4402:     my $reply = &get_query_reply($queryid);
 4403:     my $tries = 1;
 4404:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4405:         $reply = &get_query_reply($queryid);
 4406:         $tries ++;
 4407:     }
 4408:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4409:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4410:     } else {
 4411:         my @responses = split(/:/,$reply);
 4412:         my $outcome = shift(@responses); 
 4413:         foreach my $item (@responses) {
 4414:             my ($key,$value) = split(/=/,$item);
 4415:             $$photo{$key} = $value;
 4416:         }
 4417:         return $outcome;
 4418:     }
 4419:     return 'error';
 4420: }
 4421: 
 4422: sub auto_instcode_format {
 4423:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4424: 	$cat_order) = @_;
 4425:     my $courses = '';
 4426:     my @homeservers;
 4427:     if ($caller eq 'global') {
 4428:         foreach my $tryserver (keys(%libserv)) {
 4429:             if ($hostdom{$tryserver} eq $codedom) {
 4430:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4431:                     push(@homeservers,$tryserver);
 4432:                 }
 4433:             }
 4434:         }
 4435:     } else {
 4436:         push(@homeservers,&homeserver($caller,$codedom));
 4437:     }
 4438:     foreach my $code (keys(%{$instcodes})) {
 4439:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4440:     }
 4441:     chop($courses);
 4442:     my $ok_response = 0;
 4443:     my $response;
 4444:     while (@homeservers > 0 && $ok_response == 0) {
 4445:         my $server = shift(@homeservers); 
 4446:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4447:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4448:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4449: 		split/:/,$response;
 4450:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4451:             push(@{$codetitles},&str2array($codetitles_str));
 4452:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4453:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4454:             $ok_response = 1;
 4455:         }
 4456:     }
 4457:     if ($ok_response) {
 4458:         return 'ok';
 4459:     } else {
 4460:         return $response;
 4461:     }
 4462: }
 4463: 
 4464: sub auto_instcode_defaults {
 4465:     my ($domain,$returnhash,$code_order) = @_;
 4466:     my @homeservers;
 4467:     foreach my $tryserver (keys(%libserv)) {
 4468:         if ($hostdom{$tryserver} eq $domain) {
 4469:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4470:                 push(@homeservers,$tryserver);
 4471:             }
 4472:         }
 4473:     }
 4474:     my $ok_response = 0;
 4475:     my $response;
 4476:     while (@homeservers > 0 && $ok_response == 0) {
 4477:         my $server = shift(@homeservers);
 4478:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4479:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4480:             foreach my $pair (split(/\&/,$response)) {
 4481:                 my ($name,$value)=split(/\=/,$pair);
 4482:                 if ($name eq 'code_order') {
 4483:                     @{$code_order} = split(/\&/,&unescape($value));
 4484:                 } else {
 4485:                     $returnhash->{&unescape($name)}=&unescape($value);
 4486:                 }
 4487:             }
 4488:             $ok_response = 1;
 4489:         }
 4490:     }
 4491:     if ($ok_response) {
 4492:         return 'ok';
 4493:     } else {
 4494:         return $response;
 4495:     }
 4496: } 
 4497: 
 4498: sub auto_validate_class_sec {
 4499:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4500:     my $homeserver = &homeserver($cnum,$cdom);
 4501:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4502:                         &escape($owner).':'.$cdom,$homeserver);
 4503:     return $response;
 4504: }
 4505: 
 4506: # ------------------------------------------------------- Course Group routines
 4507: 
 4508: sub get_coursegroups {
 4509:     my ($cdom,$cnum,$group,$namespace) = @_;
 4510:     return(&dump($namespace,$cdom,$cnum,$group));
 4511: }
 4512: 
 4513: sub modify_coursegroup {
 4514:     my ($cdom,$cnum,$groupsettings) = @_;
 4515:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4516: }
 4517: 
 4518: sub toggle_coursegroup_status {
 4519:     my ($cdom,$cnum,$group,$action) = @_;
 4520:     my ($from_namespace,$to_namespace);
 4521:     if ($action eq 'delete') {
 4522:         $from_namespace = 'coursegroups';
 4523:         $to_namespace = 'deleted_groups';
 4524:     } else {
 4525:         $from_namespace = 'deleted_groups';
 4526:         $to_namespace = 'coursegroups';
 4527:     }
 4528:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4529:     if (my $tmp = &error(%curr_group)) {
 4530:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4531:         return ('read error',$tmp);
 4532:     } else {
 4533:         my %savedsettings = %curr_group; 
 4534:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4535:         my $deloutcome;
 4536:         if ($result eq 'ok') {
 4537:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4538:         } else {
 4539:             return ('write error',$result);
 4540:         }
 4541:         if ($deloutcome eq 'ok') {
 4542:             return 'ok';
 4543:         } else {
 4544:             return ('delete error',$deloutcome);
 4545:         }
 4546:     }
 4547: }
 4548: 
 4549: sub modify_group_roles {
 4550:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4551:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4552:     my $role = 'gr/'.&escape($userprivs);
 4553:     my ($uname,$udom) = split(/:/,$user);
 4554:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4555:     if ($result eq 'ok') {
 4556:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4557:     }
 4558:     return $result;
 4559: }
 4560: 
 4561: sub modify_coursegroup_membership {
 4562:     my ($cdom,$cnum,$membership) = @_;
 4563:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4564:     return $result;
 4565: }
 4566: 
 4567: sub get_active_groups {
 4568:     my ($udom,$uname,$cdom,$cnum) = @_;
 4569:     my $now = time;
 4570:     my %groups = ();
 4571:     foreach my $key (keys(%env)) {
 4572:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4573:             my ($start,$end) = split(/\./,$env{$key});
 4574:             if (($end!=0) && ($end<$now)) { next; }
 4575:             if (($start!=0) && ($start>$now)) { next; }
 4576:             if ($1 eq $cdom && $2 eq $cnum) {
 4577:                 $groups{$3} = $env{$key} ;
 4578:             }
 4579:         }
 4580:     }
 4581:     return %groups;
 4582: }
 4583: 
 4584: sub get_group_membership {
 4585:     my ($cdom,$cnum,$group) = @_;
 4586:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4587: }
 4588: 
 4589: sub get_users_groups {
 4590:     my ($udom,$uname,$courseid) = @_;
 4591:     my @usersgroups;
 4592:     my $cachetime=1800;
 4593: 
 4594:     my $hashid="$udom:$uname:$courseid";
 4595:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4596:     if (defined($cached)) {
 4597:         @usersgroups = split(/:/,$grouplist);
 4598:     } else {  
 4599:         $grouplist = '';
 4600:         my $courseurl = &courseid_to_courseurl($courseid);
 4601:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4602:         my $access_end = $env{'course.'.$courseid.
 4603:                               '.default_enrollment_end_date'};
 4604:         my $now = time;
 4605:         foreach my $key (keys(%roleshash)) {
 4606:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4607:                 my $group = $1;
 4608:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4609:                     my $start = $2;
 4610:                     my $end = $1;
 4611:                     if ($start == -1) { next; } # deleted from group
 4612:                     if (($start!=0) && ($start>$now)) { next; }
 4613:                     if (($end!=0) && ($end<$now)) {
 4614:                         if ($access_end && $access_end < $now) {
 4615:                             if ($access_end - $end < 86400) {
 4616:                                 push(@usersgroups,$group);
 4617:                             }
 4618:                         }
 4619:                         next;
 4620:                     }
 4621:                     push(@usersgroups,$group);
 4622:                 }
 4623:             }
 4624:         }
 4625:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4626:         $grouplist = join(':',@usersgroups);
 4627:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4628:     }
 4629:     return @usersgroups;
 4630: }
 4631: 
 4632: sub devalidate_getgroups_cache {
 4633:     my ($udom,$uname,$cdom,$cnum)=@_;
 4634:     my $courseid = $cdom.'_'.$cnum;
 4635: 
 4636:     my $hashid="$udom:$uname:$courseid";
 4637:     &devalidate_cache_new('getgroups',$hashid);
 4638: }
 4639: 
 4640: # ------------------------------------------------------------------ Plain Text
 4641: 
 4642: sub plaintext {
 4643:     my ($short,$type,$cid) = @_;
 4644:     if ($short =~ /^cr/) {
 4645: 	return (split('/',$short))[-1];
 4646:     }
 4647:     if (!defined($cid)) {
 4648:         $cid = $env{'request.course.id'};
 4649:     }
 4650:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4651:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4652:                                           '.plaintext'});
 4653:     }
 4654:     my %rolenames = (
 4655:                       Course => 'std',
 4656:                       Group => 'alt1',
 4657:                     );
 4658:     if (defined($type) && 
 4659:          defined($rolenames{$type}) && 
 4660:          defined($prp{$short}{$rolenames{$type}})) {
 4661:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4662:     } else {
 4663:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4664:     }
 4665: }
 4666: 
 4667: # ----------------------------------------------------------------- Assign Role
 4668: 
 4669: sub assignrole {
 4670:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4671:     my $mrole;
 4672:     if ($role =~ /^cr\//) {
 4673:         my $cwosec=$url;
 4674:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4675: 	unless (&allowed('ccr',$cwosec)) {
 4676:            &logthis('Refused custom assignrole: '.
 4677:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4678: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4679:            return 'refused'; 
 4680:         }
 4681:         $mrole='cr';
 4682:     } elsif ($role =~ /^gr\//) {
 4683:         my $cwogrp=$url;
 4684:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4685:         unless (&allowed('mdg',$cwogrp)) {
 4686:             &logthis('Refused group assignrole: '.
 4687:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4688:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4689:             return 'refused';
 4690:         }
 4691:         $mrole='gr';
 4692:     } else {
 4693:         my $cwosec=$url;
 4694:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4695:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4696:            &logthis('Refused assignrole: '.
 4697:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4698: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4699:            return 'refused'; 
 4700:         }
 4701:         $mrole=$role;
 4702:     }
 4703:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4704:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4705:     if ($end) { $command.='_'.$end; }
 4706:     if ($start) {
 4707: 	if ($end) { 
 4708:            $command.='_'.$start; 
 4709:         } else {
 4710:            $command.='_0_'.$start;
 4711:         }
 4712:     }
 4713:     my $origstart = $start;
 4714:     my $origend = $end;
 4715: # actually delete
 4716:     if ($deleteflag) {
 4717: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4718: # modify command to delete the role
 4719:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4720:                 "$udom:$uname:$url".'_'."$mrole";
 4721: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4722: # set start and finish to negative values for userrolelog
 4723:            $start=-1;
 4724:            $end=-1;
 4725:         }
 4726:     }
 4727: # send command
 4728:     my $answer=&reply($command,&homeserver($uname,$udom));
 4729: # log new user role if status is ok
 4730:     if ($answer eq 'ok') {
 4731: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4732: # for course roles, perform group memberships changes triggered by role change.
 4733:         unless ($role =~ /^gr/) {
 4734:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4735:                                              $origstart);
 4736:         }
 4737:     }
 4738:     return $answer;
 4739: }
 4740: 
 4741: # -------------------------------------------------- Modify user authentication
 4742: # Overrides without validation
 4743: 
 4744: sub modifyuserauth {
 4745:     my ($udom,$uname,$umode,$upass)=@_;
 4746:     my $uhome=&homeserver($uname,$udom);
 4747:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4748:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4749:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4750:              ' in domain '.$env{'request.role.domain'});  
 4751:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4752: 		     &escape($upass),$uhome);
 4753:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4754:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4755:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4756:     &log($udom,,$uname,$uhome,
 4757:         'Authentication changed by '.$env{'user.domain'}.', '.
 4758:                                      $env{'user.name'}.', '.$umode.
 4759:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4760:     unless ($reply eq 'ok') {
 4761:         &logthis('Authentication mode error: '.$reply);
 4762: 	return 'error: '.$reply;
 4763:     }   
 4764:     return 'ok';
 4765: }
 4766: 
 4767: # --------------------------------------------------------------- Modify a user
 4768: 
 4769: sub modifyuser {
 4770:     my ($udom,    $uname, $uid,
 4771:         $umode,   $upass, $first,
 4772:         $middle,  $last,  $gene,
 4773:         $forceid, $desiredhome, $email)=@_;
 4774:     $udom= &LONCAPA::clean_domain($udom);
 4775:     $uname=&LONCAPA::clean_username($uname);
 4776:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4777:              $umode.', '.$first.', '.$middle.', '.
 4778: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4779:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4780:                                      ' desiredhome not specified'). 
 4781:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4782:              ' in domain '.$env{'request.role.domain'});
 4783:     my $uhome=&homeserver($uname,$udom,'true');
 4784: # ----------------------------------------------------------------- Create User
 4785:     if (($uhome eq 'no_host') && 
 4786: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4787:         my $unhome='';
 4788:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4789:             $unhome = $desiredhome;
 4790: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4791: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4792:         } else { # load balancing routine for determining $unhome
 4793:             my $tryserver;
 4794:             my $loadm=10000000;
 4795:             foreach $tryserver (keys %libserv) {
 4796: 	       if ($hostdom{$tryserver} eq $udom) {
 4797:                   my $answer=reply('load',$tryserver);
 4798:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4799: 		      $loadm=$answer;
 4800:                       $unhome=$tryserver;
 4801:                   }
 4802: 	       }
 4803: 	    }
 4804:         }
 4805:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4806: 	    return 'error: unable to find a home server for '.$uname.
 4807:                    ' in domain '.$udom;
 4808:         }
 4809:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4810:                          &escape($upass),$unhome);
 4811: 	unless ($reply eq 'ok') {
 4812:             return 'error: '.$reply;
 4813:         }   
 4814:         $uhome=&homeserver($uname,$udom,'true');
 4815:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4816: 	    return 'error: unable verify users home machine.';
 4817:         }
 4818:     }   # End of creation of new user
 4819: # ---------------------------------------------------------------------- Add ID
 4820:     if ($uid) {
 4821:        $uid=~tr/A-Z/a-z/;
 4822:        my %uidhash=&idrget($udom,$uname);
 4823:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4824:          && (!$forceid)) {
 4825: 	  unless ($uid eq $uidhash{$uname}) {
 4826: 	      return 'error: user id "'.$uid.'" does not match '.
 4827:                   'current user id "'.$uidhash{$uname}.'".';
 4828:           }
 4829:        } else {
 4830: 	  &idput($udom,($uname => $uid));
 4831:        }
 4832:     }
 4833: # -------------------------------------------------------------- Add names, etc
 4834:     my @tmp=&get('environment',
 4835: 		   ['firstname','middlename','lastname','generation'],
 4836: 		   $udom,$uname);
 4837:     my %names;
 4838:     if ($tmp[0] =~ m/^error:.*/) { 
 4839:         %names=(); 
 4840:     } else {
 4841:         %names = @tmp;
 4842:     }
 4843: #
 4844: # Make sure to not trash student environment if instructor does not bother
 4845: # to supply name and email information
 4846: #
 4847:     if ($first)  { $names{'firstname'}  = $first; }
 4848:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4849:     if ($last)   { $names{'lastname'}   = $last; }
 4850:     if (defined($gene))   { $names{'generation'} = $gene; }
 4851:     if ($email) {
 4852:        $email=~s/[^\w\@\.\-\,]//gs;
 4853:        if ($email=~/\@/) { $names{'notification'} = $email;
 4854: 			   $names{'critnotification'} = $email;
 4855: 			   $names{'permanentemail'} = $email; }
 4856:     }
 4857:     my $reply = &put('environment', \%names, $udom,$uname);
 4858:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4859:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4860:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4861:              $umode.', '.$first.', '.$middle.', '.
 4862: 	     $last.', '.$gene.' by '.
 4863:              $env{'user.name'}.' at '.$env{'user.domain'});
 4864:     return 'ok';
 4865: }
 4866: 
 4867: # -------------------------------------------------------------- Modify student
 4868: 
 4869: sub modifystudent {
 4870:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4871:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4872:     if (!$cid) {
 4873: 	unless ($cid=$env{'request.course.id'}) {
 4874: 	    return 'not_in_class';
 4875: 	}
 4876:     }
 4877: # --------------------------------------------------------------- Make the user
 4878:     my $reply=&modifyuser
 4879: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4880:          $desiredhome,$email);
 4881:     unless ($reply eq 'ok') { return $reply; }
 4882:     # This will cause &modify_student_enrollment to get the uid from the
 4883:     # students environment
 4884:     $uid = undef if (!$forceid);
 4885:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4886: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4887:     return $reply;
 4888: }
 4889: 
 4890: sub modify_student_enrollment {
 4891:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4892:     my ($cdom,$cnum,$chome);
 4893:     if (!$cid) {
 4894: 	unless ($cid=$env{'request.course.id'}) {
 4895: 	    return 'not_in_class';
 4896: 	}
 4897: 	$cdom=$env{'course.'.$cid.'.domain'};
 4898: 	$cnum=$env{'course.'.$cid.'.num'};
 4899:     } else {
 4900: 	($cdom,$cnum)=split(/_/,$cid);
 4901:     }
 4902:     $chome=$env{'course.'.$cid.'.home'};
 4903:     if (!$chome) {
 4904: 	$chome=&homeserver($cnum,$cdom);
 4905:     }
 4906:     if (!$chome) { return 'unknown_course'; }
 4907:     # Make sure the user exists
 4908:     my $uhome=&homeserver($uname,$udom);
 4909:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4910: 	return 'error: no such user';
 4911:     }
 4912:     # Get student data if we were not given enough information
 4913:     if (!defined($first)  || $first  eq '' || 
 4914:         !defined($last)   || $last   eq '' || 
 4915:         !defined($uid)    || $uid    eq '' || 
 4916:         !defined($middle) || $middle eq '' || 
 4917:         !defined($gene)   || $gene   eq '') {
 4918:         # They did not supply us with enough data to enroll the student, so
 4919:         # we need to pick up more information.
 4920:         my %tmp = &get('environment',
 4921:                        ['firstname','middlename','lastname', 'generation','id']
 4922:                        ,$udom,$uname);
 4923: 
 4924:         #foreach my $key (keys(%tmp)) {
 4925:         #    &logthis("key $key = ".$tmp{$key});
 4926:         #}
 4927:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4928:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4929:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4930:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4931:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4932:     }
 4933:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4934:     my $reply=cput('classlist',
 4935: 		   {"$uname:$udom" => 
 4936: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4937: 		   $cdom,$cnum);
 4938:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4939: 	return 'error: '.$reply;
 4940:     } else {
 4941: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4942:     }
 4943:     # Add student role to user
 4944:     my $uurl='/'.$cid;
 4945:     $uurl=~s/\_/\//g;
 4946:     if ($usec) {
 4947: 	$uurl.='/'.$usec;
 4948:     }
 4949:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4950: }
 4951: 
 4952: sub format_name {
 4953:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4954:     my $name;
 4955:     if ($first ne 'lastname') {
 4956: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4957:     } else {
 4958: 	if ($lastname=~/\S/) {
 4959: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4960: 	    $name=~s/\s+,/,/;
 4961: 	} else {
 4962: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4963: 	}
 4964:     }
 4965:     $name=~s/^\s+//;
 4966:     $name=~s/\s+$//;
 4967:     $name=~s/\s+/ /g;
 4968:     return $name;
 4969: }
 4970: 
 4971: # ------------------------------------------------- Write to course preferences
 4972: 
 4973: sub writecoursepref {
 4974:     my ($courseid,%prefs)=@_;
 4975:     $courseid=~s/^\///;
 4976:     $courseid=~s/\_/\//g;
 4977:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4978:     my $chome=homeserver($cnum,$cdomain);
 4979:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4980: 	return 'error: no such course';
 4981:     }
 4982:     my $cstring='';
 4983:     foreach my $pref (keys(%prefs)) {
 4984: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 4985:     }
 4986:     $cstring=~s/\&$//;
 4987:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4988: }
 4989: 
 4990: # ---------------------------------------------------------- Make/modify course
 4991: 
 4992: sub createcourse {
 4993:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4994:         $course_owner,$crstype)=@_;
 4995:     $url=&declutter($url);
 4996:     my $cid='';
 4997:     unless (&allowed('ccc',$udom)) {
 4998:         return 'refused';
 4999:     }
 5000: # ------------------------------------------------------------------- Create ID
 5001:    my $uname=int(1+rand(9)).
 5002:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5003:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5004:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5005: # ----------------------------------------------- Make sure that does not exist
 5006:    my $uhome=&homeserver($uname,$udom,'true');
 5007:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5008:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5009:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5010:        $uhome=&homeserver($uname,$udom,'true');       
 5011:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5012:            return 'error: unable to generate unique course-ID';
 5013:        } 
 5014:    }
 5015: # ------------------------------------------------ Check supplied server name
 5016:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5017:     if (! exists($libserv{$course_server})) {
 5018:         return 'error:bad server name '.$course_server;
 5019:     }
 5020: # ------------------------------------------------------------- Make the course
 5021:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5022:                       $course_server);
 5023:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5024:     $uhome=&homeserver($uname,$udom,'true');
 5025:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5026: 	return 'error: no such course';
 5027:     }
 5028: # ----------------------------------------------------------------- Course made
 5029: # log existence
 5030:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5031:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5032:                   &escape($crstype),$uhome);
 5033:     &flushcourselogs();
 5034: # set toplevel url
 5035:     my $topurl=$url;
 5036:     unless ($nonstandard) {
 5037: # ------------------------------------------ For standard courses, make top url
 5038:         my $mapurl=&clutter($url);
 5039:         if ($mapurl eq '/res/') { $mapurl=''; }
 5040:         $env{'form.initmap'}=(<<ENDINITMAP);
 5041: <map>
 5042: <resource id="1" type="start"></resource>
 5043: <resource id="2" src="$mapurl"></resource>
 5044: <resource id="3" type="finish"></resource>
 5045: <link index="1" from="1" to="2"></link>
 5046: <link index="2" from="2" to="3"></link>
 5047: </map>
 5048: ENDINITMAP
 5049:         $topurl=&declutter(
 5050:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5051:                           );
 5052:     }
 5053: # ----------------------------------------------------------- Write preferences
 5054:     &writecoursepref($udom.'_'.$uname,
 5055:                      ('description' => $description,
 5056:                       'url'         => $topurl));
 5057:     return '/'.$udom.'/'.$uname;
 5058: }
 5059: 
 5060: sub is_course {
 5061:     my ($cdom,$cnum) = @_;
 5062:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5063: 				undef,'.');
 5064:     if (exists($courses{$cdom.'_'.$cnum})) {
 5065:         return 1;
 5066:     }
 5067:     return 0;
 5068: }
 5069: 
 5070: # ---------------------------------------------------------- Assign Custom Role
 5071: 
 5072: sub assigncustomrole {
 5073:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5074:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5075:                        $end,$start,$deleteflag);
 5076: }
 5077: 
 5078: # ----------------------------------------------------------------- Revoke Role
 5079: 
 5080: sub revokerole {
 5081:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5082:     my $now=time;
 5083:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5084: }
 5085: 
 5086: # ---------------------------------------------------------- Revoke Custom Role
 5087: 
 5088: sub revokecustomrole {
 5089:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5090:     my $now=time;
 5091:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5092:            $deleteflag);
 5093: }
 5094: 
 5095: # ------------------------------------------------------------ Disk usage
 5096: sub diskusage {
 5097:     my ($udom,$uname,$directoryRoot)=@_;
 5098:     $directoryRoot =~ s/\/$//;
 5099:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5100:     return $listing;
 5101: }
 5102: 
 5103: sub is_locked {
 5104:     my ($file_name, $domain, $user) = @_;
 5105:     my @check;
 5106:     my $is_locked;
 5107:     push @check, $file_name;
 5108:     my %locked = &get('file_permissions',\@check,
 5109: 		      $env{'user.domain'},$env{'user.name'});
 5110:     my ($tmp)=keys(%locked);
 5111:     if ($tmp=~/^error:/) { undef(%locked); }
 5112:     
 5113:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5114:         $is_locked = 'false';
 5115:         foreach my $entry (@{$locked{$file_name}}) {
 5116:            if (ref($entry) eq 'ARRAY') { 
 5117:                $is_locked = 'true';
 5118:                last;
 5119:            }
 5120:        }
 5121:     } else {
 5122:         $is_locked = 'false';
 5123:     }
 5124: }
 5125: 
 5126: sub declutter_portfile {
 5127:     my ($file) = @_;
 5128:     &logthis("got $file");
 5129:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 5130:     &logthis("ret $file");
 5131:     return $file;
 5132: }
 5133: 
 5134: # ------------------------------------------------------------- Mark as Read Only
 5135: 
 5136: sub mark_as_readonly {
 5137:     my ($domain,$user,$files,$what) = @_;
 5138:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5139:     my ($tmp)=keys(%current_permissions);
 5140:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5141:     foreach my $file (@{$files}) {
 5142: 	$file = &declutter_portfile($file);
 5143:         push(@{$current_permissions{$file}},$what);
 5144:     }
 5145:     &put('file_permissions',\%current_permissions,$domain,$user);
 5146:     return;
 5147: }
 5148: 
 5149: # ------------------------------------------------------------Save Selected Files
 5150: 
 5151: sub save_selected_files {
 5152:     my ($user, $path, @files) = @_;
 5153:     my $filename = $user."savedfiles";
 5154:     my @other_files = &files_not_in_path($user, $path);
 5155:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5156:     foreach my $file (@files) {
 5157:         print (OUT $env{'form.currentpath'}.$file."\n");
 5158:     }
 5159:     foreach my $file (@other_files) {
 5160:         print (OUT $file."\n");
 5161:     }
 5162:     close (OUT);
 5163:     return 'ok';
 5164: }
 5165: 
 5166: sub clear_selected_files {
 5167:     my ($user) = @_;
 5168:     my $filename = $user."savedfiles";
 5169:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5170:     print (OUT undef);
 5171:     close (OUT);
 5172:     return ("ok");    
 5173: }
 5174: 
 5175: sub files_in_path {
 5176:     my ($user, $path) = @_;
 5177:     my $filename = $user."savedfiles";
 5178:     my %return_files;
 5179:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5180:     while (my $line_in = <IN>) {
 5181:         chomp ($line_in);
 5182:         my @paths_and_file = split (m!/!, $line_in);
 5183:         my $file_part = pop (@paths_and_file);
 5184:         my $path_part = join ('/', @paths_and_file);
 5185:         $path_part.='/';
 5186:         my $path_and_file = $path_part.$file_part;
 5187:         if ($path_part eq $path) {
 5188:             $return_files{$file_part}= 'selected';
 5189:         }
 5190:     }
 5191:     close (IN);
 5192:     return (\%return_files);
 5193: }
 5194: 
 5195: # called in portfolio select mode, to show files selected NOT in current directory
 5196: sub files_not_in_path {
 5197:     my ($user, $path) = @_;
 5198:     my $filename = $user."savedfiles";
 5199:     my @return_files;
 5200:     my $path_part;
 5201:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5202:     while (my $line = <IN>) {
 5203:         #ok, I know it's clunky, but I want it to work
 5204:         my @paths_and_file = split(m|/|, $line);
 5205:         my $file_part = pop(@paths_and_file);
 5206:         chomp($file_part);
 5207:         my $path_part = join('/', @paths_and_file);
 5208:         $path_part .= '/';
 5209:         my $path_and_file = $path_part.$file_part;
 5210:         if ($path_part ne $path) {
 5211:             push(@return_files, ($path_and_file));
 5212:         }
 5213:     }
 5214:     close(OUT);
 5215:     return (@return_files);
 5216: }
 5217: 
 5218: #----------------------------------------------Get portfolio file permissions
 5219: 
 5220: sub get_portfile_permissions {
 5221:     my ($domain,$user) = @_;
 5222:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5223:     my ($tmp)=keys(%current_permissions);
 5224:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5225:     return \%current_permissions;
 5226: }
 5227: 
 5228: #---------------------------------------------Get portfolio file access controls
 5229: 
 5230: sub get_access_controls {
 5231:     my ($current_permissions,$group,$file) = @_;
 5232:     my %access;
 5233:     my $real_file = $file;
 5234:     $file =~ s/\.meta$//;
 5235:     if (defined($file)) {
 5236:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5237:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5238:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5239:             }
 5240:         }
 5241:     } else {
 5242:         foreach my $key (keys(%{$current_permissions})) {
 5243:             if ($key =~ /\0accesscontrol$/) {
 5244:                 if (defined($group)) {
 5245:                     if ($key !~ m-^\Q$group\E/-) {
 5246:                         next;
 5247:                     }
 5248:                 }
 5249:                 my ($fullpath) = split(/\0/,$key);
 5250:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5251:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5252:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5253:                     }
 5254:                 }
 5255:             }
 5256:         }
 5257:     }
 5258:     return %access;
 5259: }
 5260: 
 5261: sub modify_access_controls {
 5262:     my ($file_name,$changes,$domain,$user)=@_;
 5263:     my ($outcome,$deloutcome);
 5264:     my %store_permissions;
 5265:     my %new_values;
 5266:     my %new_control;
 5267:     my %translation;
 5268:     my @deletions = ();
 5269:     my $now = time;
 5270:     if (exists($$changes{'activate'})) {
 5271:         if (ref($$changes{'activate'}) eq 'HASH') {
 5272:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5273:             my $numnew = scalar(@newitems);
 5274:             for (my $i=0; $i<$numnew; $i++) {
 5275:                 my $newkey = $newitems[$i];
 5276:                 my $newid = &Apache::loncommon::get_cgi_id();
 5277:                 if ($newkey =~ /^\d+:/) { 
 5278:                     $newkey =~ s/^(\d+)/$newid/;
 5279:                     $translation{$1} = $newid;
 5280:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5281:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5282:                     $translation{$1} = $newid;
 5283:                 }
 5284:                 $new_values{$file_name."\0".$newkey} = 
 5285:                                           $$changes{'activate'}{$newitems[$i]};
 5286:                 $new_control{$newkey} = $now;
 5287:             }
 5288:         }
 5289:     }
 5290:     my %todelete;
 5291:     my %changed_items;
 5292:     foreach my $action ('delete','update') {
 5293:         if (exists($$changes{$action})) {
 5294:             if (ref($$changes{$action}) eq 'HASH') {
 5295:                 foreach my $key (keys(%{$$changes{$action}})) {
 5296:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5297:                     if ($action eq 'delete') { 
 5298:                         $todelete{$itemnum} = 1;
 5299:                     } else {
 5300:                         $changed_items{$itemnum} = $key;
 5301:                     }
 5302:                 }
 5303:             }
 5304:         }
 5305:     }
 5306:     # get lock on access controls for file.
 5307:     my $lockhash = {
 5308:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5309:                                                        ':'.$env{'user.domain'},
 5310:                    }; 
 5311:     my $tries = 0;
 5312:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5313:    
 5314:     while (($gotlock ne 'ok') && $tries <3) {
 5315:         $tries ++;
 5316:         sleep 1;
 5317:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5318:     }
 5319:     if ($gotlock eq 'ok') {
 5320:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5321:         my ($tmp)=keys(%curr_permissions);
 5322:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5323:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5324:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5325:             if (ref($curr_controls) eq 'HASH') {
 5326:                 foreach my $control_item (keys(%{$curr_controls})) {
 5327:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5328:                     if (defined($todelete{$itemnum})) {
 5329:                         push(@deletions,$file_name."\0".$control_item);
 5330:                     } else {
 5331:                         if (defined($changed_items{$itemnum})) {
 5332:                             $new_control{$changed_items{$itemnum}} = $now;
 5333:                             push(@deletions,$file_name."\0".$control_item);
 5334:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5335:                         } else {
 5336:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5337:                         }
 5338:                     }
 5339:                 }
 5340:             }
 5341:         }
 5342:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5343:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5344:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5345:         #  remove lock
 5346:         my @del_lock = ($file_name."\0".'locked_access_records');
 5347:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5348:         my ($file,$group);
 5349:         if (&is_course($domain,$user)) {
 5350:             ($group,$file) = split(/\//,$file_name,2);
 5351:         } else {
 5352:             $file = $file_name;
 5353:         }
 5354:         my $sqlresult =
 5355:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5356:                                     $group);
 5357:     } else {
 5358:         $outcome = "error: could not obtain lockfile\n";  
 5359:     }
 5360:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5361: }
 5362: 
 5363: #------------------------------------------------------Get Marked as Read Only
 5364: 
 5365: sub get_marked_as_readonly {
 5366:     my ($domain,$user,$what,$group) = @_;
 5367:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5368:     my @readonly_files;
 5369:     my $cmp1=$what;
 5370:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5371:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5372:         if (defined($group)) {
 5373:             if ($file_name !~ m-^\Q$group\E/-) {
 5374:                 next;
 5375:             }
 5376:         }
 5377:         if (ref($value) eq "ARRAY"){
 5378:             foreach my $stored_what (@{$value}) {
 5379:                 my $cmp2=$stored_what;
 5380:                 if (ref($stored_what) eq 'ARRAY') {
 5381:                     $cmp2=join('',@{$stored_what});
 5382:                 }
 5383:                 if ($cmp1 eq $cmp2) {
 5384:                     push(@readonly_files, $file_name);
 5385:                     last;
 5386:                 } elsif (!defined($what)) {
 5387:                     push(@readonly_files, $file_name);
 5388:                     last;
 5389:                 }
 5390:             }
 5391:         }
 5392:     }
 5393:     return @readonly_files;
 5394: }
 5395: #-----------------------------------------------------------Get Marked as Read Only Hash
 5396: 
 5397: sub get_marked_as_readonly_hash {
 5398:     my ($current_permissions,$group,$what) = @_;
 5399:     my %readonly_files;
 5400:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5401:         if (defined($group)) {
 5402:             if ($file_name !~ m-^\Q$group\E/-) {
 5403:                 next;
 5404:             }
 5405:         }
 5406:         if (ref($value) eq "ARRAY"){
 5407:             foreach my $stored_what (@{$value}) {
 5408:                 if (ref($stored_what) eq 'ARRAY') {
 5409:                     foreach my $lock_descriptor(@{$stored_what}) {
 5410:                         if ($lock_descriptor eq 'graded') {
 5411:                             $readonly_files{$file_name} = 'graded';
 5412:                         } elsif ($lock_descriptor eq 'handback') {
 5413:                             $readonly_files{$file_name} = 'handback';
 5414:                         } else {
 5415:                             if (!exists($readonly_files{$file_name})) {
 5416:                                 $readonly_files{$file_name} = 'locked';
 5417:                             }
 5418:                         }
 5419:                     }
 5420:                 } 
 5421:             }
 5422:         } 
 5423:     }
 5424:     return %readonly_files;
 5425: }
 5426: # ------------------------------------------------------------ Unmark as Read Only
 5427: 
 5428: sub unmark_as_readonly {
 5429:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5430:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5431:     my ($domain,$user,$what,$file_name,$group) = @_;
 5432:     $file_name = &declutter_portfile($file_name);
 5433:     my $symb_crs = $what;
 5434:     if (ref($what)) { $symb_crs=join('',@$what); }
 5435:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5436:     my ($tmp)=keys(%current_permissions);
 5437:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5438:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5439:     foreach my $file (@readonly_files) {
 5440: 	my $clean_file = &declutter_portfile($file);
 5441: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5442: 	my $current_locks = $current_permissions{$file};
 5443:         my @new_locks;
 5444:         my @del_keys;
 5445:         if (ref($current_locks) eq "ARRAY"){
 5446:             foreach my $locker (@{$current_locks}) {
 5447:                 my $compare=$locker;
 5448:                 if (ref($locker) eq 'ARRAY') {
 5449:                     $compare=join('',@{$locker});
 5450:                     if ($compare ne $symb_crs) {
 5451:                         push(@new_locks, $locker);
 5452:                     }
 5453:                 }
 5454:             }
 5455:             if (scalar(@new_locks) > 0) {
 5456:                 $current_permissions{$file} = \@new_locks;
 5457:             } else {
 5458:                 push(@del_keys, $file);
 5459:                 &del('file_permissions',\@del_keys, $domain, $user);
 5460:                 delete($current_permissions{$file});
 5461:             }
 5462:         }
 5463:     }
 5464:     &put('file_permissions',\%current_permissions,$domain,$user);
 5465:     return;
 5466: }
 5467: 
 5468: # ------------------------------------------------------------ Directory lister
 5469: 
 5470: sub dirlist {
 5471:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5472: 
 5473:     $uri=~s/^\///;
 5474:     $uri=~s/\/$//;
 5475:     my ($udom, $uname);
 5476:     (undef,$udom,$uname)=split(/\//,$uri);
 5477:     if(defined($userdomain)) {
 5478:         $udom = $userdomain;
 5479:     }
 5480:     if(defined($username)) {
 5481:         $uname = $username;
 5482:     }
 5483: 
 5484:     my $dirRoot = $perlvar{'lonDocRoot'};
 5485:     if(defined($alternateDirectoryRoot)) {
 5486:         $dirRoot = $alternateDirectoryRoot;
 5487:         $dirRoot =~ s/\/$//;
 5488:     }
 5489: 
 5490:     if($udom) {
 5491:         if($uname) {
 5492:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5493: 				 &homeserver($uname,$udom));
 5494:             my @listing_results;
 5495:             if ($listing eq 'unknown_cmd') {
 5496:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5497: 				  &homeserver($uname,$udom));
 5498:                 @listing_results = split(/:/,$listing);
 5499:             } else {
 5500:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5501:             }
 5502:             return @listing_results;
 5503:         } elsif(!defined($alternateDirectoryRoot)) {
 5504:             my %allusers;
 5505:             foreach my $tryserver (keys(%libserv)) {
 5506:                 if($hostdom{$tryserver} eq $udom) {
 5507:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5508: 					 $udom, $tryserver);
 5509:                     my @listing_results;
 5510:                     if ($listing eq 'unknown_cmd') {
 5511:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5512: 					  $udom, $tryserver);
 5513:                         @listing_results = split(/:/,$listing);
 5514:                     } else {
 5515:                         @listing_results =
 5516:                             map { &unescape($_); } split(/:/,$listing);
 5517:                     }
 5518:                     if ($listing_results[0] ne 'no_such_dir' && 
 5519:                         $listing_results[0] ne 'empty'       &&
 5520:                         $listing_results[0] ne 'con_lost') {
 5521:                         foreach my $line (@listing_results) {
 5522:                             my ($entry) = split(/&/,$line,2);
 5523:                             $allusers{$entry} = 1;
 5524:                         }
 5525:                     }
 5526:                 }
 5527:             }
 5528:             my $alluserstr='';
 5529:             foreach my $user (sort(keys(%allusers))) {
 5530:                 $alluserstr.=$user.'&user:';
 5531:             }
 5532:             $alluserstr=~s/:$//;
 5533:             return split(/:/,$alluserstr);
 5534:         } else {
 5535:             return ('missing user name');
 5536:         }
 5537:     } elsif(!defined($alternateDirectoryRoot)) {
 5538:         my $tryserver;
 5539:         my %alldom=();
 5540:         foreach $tryserver (keys(%libserv)) {
 5541:             $alldom{$hostdom{$tryserver}}=1;
 5542:         }
 5543:         my $alldomstr='';
 5544:         foreach my $domain (sort(keys(%alldom))) {
 5545:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
 5546:         }
 5547:         $alldomstr=~s/:$//;
 5548:         return split(/:/,$alldomstr);       
 5549:     } else {
 5550:         return ('missing domain');
 5551:     }
 5552: }
 5553: 
 5554: # --------------------------------------------- GetFileTimestamp
 5555: # This function utilizes dirlist and returns the date stamp for
 5556: # when it was last modified.  It will also return an error of -1
 5557: # if an error occurs
 5558: 
 5559: ##
 5560: ## FIXME: This subroutine assumes its caller knows something about the
 5561: ## directory structure of the home server for the student ($root).
 5562: ## Not a good assumption to make.  Since this is for looking up files
 5563: ## in user directories, the full path should be constructed by lond, not
 5564: ## whatever machine we request data from.
 5565: ##
 5566: sub GetFileTimestamp {
 5567:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5568:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5569:     $studentName   = &LONCAPA::clean_username($studentName);
 5570:     my $subdir=$studentName.'__';
 5571:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5572:     my $proname="$studentDomain/$subdir/$studentName";
 5573:     $proname .= '/'.$filename;
 5574:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5575:                                               $studentName, $root);
 5576:     my @stats = split('&', $fileStat);
 5577:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5578:         # @stats contains first the filename, then the stat output
 5579:         return $stats[10]; # so this is 10 instead of 9.
 5580:     } else {
 5581:         return -1;
 5582:     }
 5583: }
 5584: 
 5585: sub stat_file {
 5586:     my ($uri) = @_;
 5587:     $uri = &clutter_with_no_wrapper($uri);
 5588: 
 5589:     my ($udom,$uname,$file,$dir);
 5590:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5591: 	($udom,$uname,$file) =
 5592: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5593: 	$file = 'userfiles/'.$file;
 5594: 	$dir = &propath($udom,$uname);
 5595:     }
 5596:     if ($uri =~ m-^/res/-) {
 5597: 	($udom,$uname) = 
 5598: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5599: 	$file = $uri;
 5600:     }
 5601: 
 5602:     if (!$udom || !$uname || !$file) {
 5603: 	# unable to handle the uri
 5604: 	return ();
 5605:     }
 5606: 
 5607:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5608:     my @stats = split('&', $result);
 5609:     
 5610:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5611: 	shift(@stats); #filename is first
 5612: 	return @stats;
 5613:     }
 5614:     return ();
 5615: }
 5616: 
 5617: # -------------------------------------------------------- Value of a Condition
 5618: 
 5619: # gets the value of a specific preevaluated condition
 5620: #    stored in the string  $env{user.state.<cid>}
 5621: # or looks up a condition reference in the bighash and if if hasn't
 5622: # already been evaluated recurses into docondval to get the value of
 5623: # the condition, then memoizing it to 
 5624: #   $env{user.state.<cid>.<condition>}
 5625: sub directcondval {
 5626:     my $number=shift;
 5627:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5628: 	&Apache::lonuserstate::evalstate();
 5629:     }
 5630:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5631: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5632:     } elsif ($number =~ /^_/) {
 5633: 	my $sub_condition;
 5634: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5635: 		&GDBM_READER(),0640)) {
 5636: 	    $sub_condition=$bighash{'conditions'.$number};
 5637: 	    untie(%bighash);
 5638: 	}
 5639: 	my $value = &docondval($sub_condition);
 5640: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5641: 	return $value;
 5642:     }
 5643:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5644:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5645:     } else {
 5646:        return 2;
 5647:     }
 5648: }
 5649: 
 5650: # get the collection of conditions for this resource
 5651: sub condval {
 5652:     my $condidx=shift;
 5653:     my $allpathcond='';
 5654:     foreach my $cond (split(/\|/,$condidx)) {
 5655: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5656: 	    $allpathcond.=
 5657: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5658: 	}
 5659:     }
 5660:     $allpathcond=~s/\|$//;
 5661:     return &docondval($allpathcond);
 5662: }
 5663: 
 5664: #evaluates an expression of conditions
 5665: sub docondval {
 5666:     my ($allpathcond) = @_;
 5667:     my $result=0;
 5668:     if ($env{'request.course.id'}
 5669: 	&& defined($allpathcond)) {
 5670: 	my $operand='|';
 5671: 	my @stack;
 5672: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5673: 	    if ($chunk eq '(') {
 5674: 		push @stack,($operand,$result);
 5675: 	    } elsif ($chunk eq ')') {
 5676: 		my $before=pop @stack;
 5677: 		if (pop @stack eq '&') {
 5678: 		    $result=$result>$before?$before:$result;
 5679: 		} else {
 5680: 		    $result=$result>$before?$result:$before;
 5681: 		}
 5682: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5683: 		$operand=$chunk;
 5684: 	    } else {
 5685: 		my $new=directcondval($chunk);
 5686: 		if ($operand eq '&') {
 5687: 		    $result=$result>$new?$new:$result;
 5688: 		} else {
 5689: 		    $result=$result>$new?$result:$new;
 5690: 		}
 5691: 	    }
 5692: 	}
 5693:     }
 5694:     return $result;
 5695: }
 5696: 
 5697: # ---------------------------------------------------- Devalidate courseresdata
 5698: 
 5699: sub devalidatecourseresdata {
 5700:     my ($coursenum,$coursedomain)=@_;
 5701:     my $hashid=$coursenum.':'.$coursedomain;
 5702:     &devalidate_cache_new('courseres',$hashid);
 5703: }
 5704: 
 5705: 
 5706: # --------------------------------------------------- Course Resourcedata Query
 5707: 
 5708: sub get_courseresdata {
 5709:     my ($coursenum,$coursedomain)=@_;
 5710:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5711:     my $hashid=$coursenum.':'.$coursedomain;
 5712:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5713:     my %dumpreply;
 5714:     unless (defined($cached)) {
 5715: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5716: 	$result=\%dumpreply;
 5717: 	my ($tmp) = keys(%dumpreply);
 5718: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5719: 	    &do_cache_new('courseres',$hashid,$result,600);
 5720: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5721: 	    return $tmp;
 5722: 	} elsif ($tmp =~ /^(error)/) {
 5723: 	    $result=undef;
 5724: 	    &do_cache_new('courseres',$hashid,$result,600);
 5725: 	}
 5726:     }
 5727:     return $result;
 5728: }
 5729: 
 5730: sub devalidateuserresdata {
 5731:     my ($uname,$udom)=@_;
 5732:     my $hashid="$udom:$uname";
 5733:     &devalidate_cache_new('userres',$hashid);
 5734: }
 5735: 
 5736: sub get_userresdata {
 5737:     my ($uname,$udom)=@_;
 5738:     #most student don\'t have any data set, check if there is some data
 5739:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5740: 
 5741:     my $hashid="$udom:$uname";
 5742:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5743:     if (!defined($cached)) {
 5744: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5745: 	$result=\%resourcedata;
 5746: 	&do_cache_new('userres',$hashid,$result,600);
 5747:     }
 5748:     my ($tmp)=keys(%$result);
 5749:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5750: 	return $result;
 5751:     }
 5752:     #error 2 occurs when the .db doesn't exist
 5753:     if ($tmp!~/error: 2 /) {
 5754: 	&logthis("<font color=\"blue\">WARNING:".
 5755: 		 " Trying to get resource data for ".
 5756: 		 $uname." at ".$udom.": ".
 5757: 		 $tmp."</font>");
 5758:     } elsif ($tmp=~/error: 2 /) {
 5759: 	#&EXT_cache_set($udom,$uname);
 5760: 	&do_cache_new('userres',$hashid,undef,600);
 5761: 	undef($tmp); # not really an error so don't send it back
 5762:     }
 5763:     return $tmp;
 5764: }
 5765: 
 5766: sub resdata {
 5767:     my ($name,$domain,$type,@which)=@_;
 5768:     my $result;
 5769:     if ($type eq 'course') {
 5770: 	$result=&get_courseresdata($name,$domain);
 5771:     } elsif ($type eq 'user') {
 5772: 	$result=&get_userresdata($name,$domain);
 5773:     }
 5774:     if (!ref($result)) { return $result; }    
 5775:     foreach my $item (@which) {
 5776: 	if (defined($result->{$item})) {
 5777: 	    return $result->{$item};
 5778: 	}
 5779:     }
 5780:     return undef;
 5781: }
 5782: 
 5783: #
 5784: # EXT resource caching routines
 5785: #
 5786: 
 5787: sub clear_EXT_cache_status {
 5788:     &delenv('cache.EXT.');
 5789: }
 5790: 
 5791: sub EXT_cache_status {
 5792:     my ($target_domain,$target_user) = @_;
 5793:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5794:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5795:         # We know already the user has no data
 5796:         return 1;
 5797:     } else {
 5798:         return 0;
 5799:     }
 5800: }
 5801: 
 5802: sub EXT_cache_set {
 5803:     my ($target_domain,$target_user) = @_;
 5804:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5805:     #&appenv($cachename => time);
 5806: }
 5807: 
 5808: # --------------------------------------------------------- Value of a Variable
 5809: sub EXT {
 5810: 
 5811:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5812:     unless ($varname) { return ''; }
 5813:     #get real user name/domain, courseid and symb
 5814:     my $courseid;
 5815:     my $publicuser;
 5816:     if ($symbparm) {
 5817: 	$symbparm=&get_symb_from_alias($symbparm);
 5818:     }
 5819:     if (!($uname && $udom)) {
 5820:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5821:       if (!$symbparm) {	$symbparm=$cursymb; }
 5822:     } else {
 5823: 	$courseid=$env{'request.course.id'};
 5824:     }
 5825:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5826:     my $rest;
 5827:     if (defined($therest[0])) {
 5828:        $rest=join('.',@therest);
 5829:     } else {
 5830:        $rest='';
 5831:     }
 5832: 
 5833:     my $qualifierrest=$qualifier;
 5834:     if ($rest) { $qualifierrest.='.'.$rest; }
 5835:     my $spacequalifierrest=$space;
 5836:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5837:     if ($realm eq 'user') {
 5838: # --------------------------------------------------------------- user.resource
 5839: 	if ($space eq 'resource') {
 5840: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5841: 		  || defined($Apache::lonhomework::parsing_a_task))
 5842: 		 &&
 5843: 		 ($symbparm eq &symbread()) ) {	
 5844: 		# if we are in the middle of processing the resource the
 5845: 		# get the value we are planning on committing
 5846:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5847:                     return $Apache::lonhomework::results{$qualifierrest};
 5848:                 } else {
 5849:                     return $Apache::lonhomework::history{$qualifierrest};
 5850:                 }
 5851: 	    } else {
 5852: 		my %restored;
 5853: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5854: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5855: 		} else {
 5856: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5857: 		}
 5858: 		return $restored{$qualifierrest};
 5859: 	    }
 5860: # ----------------------------------------------------------------- user.access
 5861:         } elsif ($space eq 'access') {
 5862: 	    # FIXME - not supporting calls for a specific user
 5863:             return &allowed($qualifier,$rest);
 5864: # ------------------------------------------ user.preferences, user.environment
 5865:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5866: 	    if (($uname eq $env{'user.name'}) &&
 5867: 		($udom eq $env{'user.domain'})) {
 5868: 		return $env{join('.',('environment',$qualifierrest))};
 5869: 	    } else {
 5870: 		my %returnhash;
 5871: 		if (!$publicuser) {
 5872: 		    %returnhash=&userenvironment($udom,$uname,
 5873: 						 $qualifierrest);
 5874: 		}
 5875: 		return $returnhash{$qualifierrest};
 5876: 	    }
 5877: # ----------------------------------------------------------------- user.course
 5878:         } elsif ($space eq 'course') {
 5879: 	    # FIXME - not supporting calls for a specific user
 5880:             return $env{join('.',('request.course',$qualifier))};
 5881: # ------------------------------------------------------------------- user.role
 5882:         } elsif ($space eq 'role') {
 5883: 	    # FIXME - not supporting calls for a specific user
 5884:             my ($role,$where)=split(/\./,$env{'request.role'});
 5885:             if ($qualifier eq 'value') {
 5886: 		return $role;
 5887:             } elsif ($qualifier eq 'extent') {
 5888:                 return $where;
 5889:             }
 5890: # ----------------------------------------------------------------- user.domain
 5891:         } elsif ($space eq 'domain') {
 5892:             return $udom;
 5893: # ------------------------------------------------------------------- user.name
 5894:         } elsif ($space eq 'name') {
 5895:             return $uname;
 5896: # ---------------------------------------------------- Any other user namespace
 5897:         } else {
 5898: 	    my %reply;
 5899: 	    if (!$publicuser) {
 5900: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5901: 	    }
 5902: 	    return $reply{$qualifierrest};
 5903:         }
 5904:     } elsif ($realm eq 'query') {
 5905: # ---------------------------------------------- pull stuff out of query string
 5906:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5907: 						[$spacequalifierrest]);
 5908: 	return $env{'form.'.$spacequalifierrest}; 
 5909:    } elsif ($realm eq 'request') {
 5910: # ------------------------------------------------------------- request.browser
 5911:         if ($space eq 'browser') {
 5912: 	    if ($qualifier eq 'textremote') {
 5913: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5914: 		    return 1;
 5915: 		} else {
 5916: 		    return 0;
 5917: 		}
 5918: 	    } else {
 5919: 		return $env{'browser.'.$qualifier};
 5920: 	    }
 5921: # ------------------------------------------------------------ request.filename
 5922:         } else {
 5923:             return $env{'request.'.$spacequalifierrest};
 5924:         }
 5925:     } elsif ($realm eq 'course') {
 5926: # ---------------------------------------------------------- course.description
 5927:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5928:     } elsif ($realm eq 'resource') {
 5929: 
 5930: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5931: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5932: 	}
 5933: 
 5934: 	if ($space eq 'title') {
 5935: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5936: 	    return &gettitle($symbparm);
 5937: 	}
 5938: 	
 5939: 	if ($space eq 'map') {
 5940: 	    my ($map) = &decode_symb($symbparm);
 5941: 	    return &symbread($map);
 5942: 	}
 5943: 
 5944: 	my ($section, $group, @groups);
 5945: 	my ($courselevelm,$courselevel);
 5946: 	if ($symbparm && defined($courseid) && 
 5947: 	    $courseid eq $env{'request.course.id'}) {
 5948: 
 5949: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5950: 
 5951: # ----------------------------------------------------- Cascading lookup scheme
 5952: 	    my $symbp=$symbparm;
 5953: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5954: 
 5955: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5956: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5957: 
 5958: 	    if (($env{'user.name'} eq $uname) &&
 5959: 		($env{'user.domain'} eq $udom)) {
 5960: 		$section=$env{'request.course.sec'};
 5961:                 @groups = split(/:/,$env{'request.course.groups'});  
 5962:                 @groups=&sort_course_groups($courseid,@groups); 
 5963: 	    } else {
 5964: 		if (! defined($usection)) {
 5965: 		    $section=&getsection($udom,$uname,$courseid);
 5966: 		} else {
 5967: 		    $section = $usection;
 5968: 		}
 5969:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5970: 	    }
 5971: 
 5972: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5973: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5974: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5975: 
 5976: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5977: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5978: 	    $courselevelm=$courseid.'.'.$mapparm;
 5979: 
 5980: # ----------------------------------------------------------- first, check user
 5981: 
 5982: 	    my $userreply=&resdata($uname,$udom,'user',
 5983: 				       ($courselevelr,$courselevelm,
 5984: 					$courselevel));
 5985: 	    if (defined($userreply)) { return $userreply; }
 5986: 
 5987: # ------------------------------------------------ second, check some of course
 5988:             my $coursereply;
 5989:             if (@groups > 0) {
 5990:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5991:                                        $mapparm,$spacequalifierrest);
 5992:                 if (defined($coursereply)) { return $coursereply; }
 5993:             }
 5994: 
 5995: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5996: 				     $env{'course.'.$courseid.'.domain'},
 5997: 				     'course',
 5998: 				     ($seclevelr,$seclevelm,$seclevel,
 5999: 				      $courselevelr));
 6000: 	    if (defined($coursereply)) { return $coursereply; }
 6001: 
 6002: # ------------------------------------------------------ third, check map parms
 6003: 	    my %parmhash=();
 6004: 	    my $thisparm='';
 6005: 	    if (tie(%parmhash,'GDBM_File',
 6006: 		    $env{'request.course.fn'}.'_parms.db',
 6007: 		    &GDBM_READER(),0640)) {
 6008: 		$thisparm=$parmhash{$symbparm};
 6009: 		untie(%parmhash);
 6010: 	    }
 6011: 	    if ($thisparm) { return $thisparm; }
 6012: 	}
 6013: # ------------------------------------------ fourth, look in resource metadata
 6014: 
 6015: 	$spacequalifierrest=~s/\./\_/;
 6016: 	my $filename;
 6017: 	if (!$symbparm) { $symbparm=&symbread(); }
 6018: 	if ($symbparm) {
 6019: 	    $filename=(&decode_symb($symbparm))[2];
 6020: 	} else {
 6021: 	    $filename=$env{'request.filename'};
 6022: 	}
 6023: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6024: 	if (defined($metadata)) { return $metadata; }
 6025: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6026: 	if (defined($metadata)) { return $metadata; }
 6027: 
 6028: # ---------------------------------------------- fourth, look in rest pf course
 6029: 	if ($symbparm && defined($courseid) && 
 6030: 	    $courseid eq $env{'request.course.id'}) {
 6031: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6032: 				     $env{'course.'.$courseid.'.domain'},
 6033: 				     'course',
 6034: 				     ($courselevelm,$courselevel));
 6035: 	    if (defined($coursereply)) { return $coursereply; }
 6036: 	}
 6037: # ------------------------------------------------------------------ Cascade up
 6038: 	unless ($space eq '0') {
 6039: 	    my @parts=split(/_/,$space);
 6040: 	    my $id=pop(@parts);
 6041: 	    my $part=join('_',@parts);
 6042: 	    if ($part eq '') { $part='0'; }
 6043: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6044: 				 $symbparm,$udom,$uname,$section,1);
 6045: 	    if (defined($partgeneral)) { return $partgeneral; }
 6046: 	}
 6047: 	if ($recurse) { return undef; }
 6048: 	my $pack_def=&packages_tab_default($filename,$varname);
 6049: 	if (defined($pack_def)) { return $pack_def; }
 6050: 
 6051: # ---------------------------------------------------- Any other user namespace
 6052:     } elsif ($realm eq 'environment') {
 6053: # ----------------------------------------------------------------- environment
 6054: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6055: 	    return $env{'environment.'.$spacequalifierrest};
 6056: 	} else {
 6057: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6058: 		return '';
 6059: 	    }
 6060: 	    my %returnhash=&userenvironment($udom,$uname,
 6061: 					    $spacequalifierrest);
 6062: 	    return $returnhash{$spacequalifierrest};
 6063: 	}
 6064:     } elsif ($realm eq 'system') {
 6065: # ----------------------------------------------------------------- system.time
 6066: 	if ($space eq 'time') {
 6067: 	    return time;
 6068:         }
 6069:     } elsif ($realm eq 'server') {
 6070: # ----------------------------------------------------------------- system.time
 6071: 	if ($space eq 'name') {
 6072: 	    return $ENV{'SERVER_NAME'};
 6073:         }
 6074:     }
 6075:     return '';
 6076: }
 6077: 
 6078: sub check_group_parms {
 6079:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6080:     my @groupitems = ();
 6081:     my $resultitem;
 6082:     my @levels = ($symbparm,$mapparm,$what);
 6083:     foreach my $group (@{$groups}) {
 6084:         foreach my $level (@levels) {
 6085:              my $item = $courseid.'.['.$group.'].'.$level;
 6086:              push(@groupitems,$item);
 6087:         }
 6088:     }
 6089:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6090:                             $env{'course.'.$courseid.'.domain'},
 6091:                                      'course',@groupitems);
 6092:     return $coursereply;
 6093: }
 6094: 
 6095: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6096:     my ($courseid,@groups) = @_;
 6097:     @groups = sort(@groups);
 6098:     return @groups;
 6099: }
 6100: 
 6101: sub packages_tab_default {
 6102:     my ($uri,$varname)=@_;
 6103:     my (undef,$part,$name)=split(/\./,$varname);
 6104: 
 6105:     my (@extension,@specifics,$do_default);
 6106:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6107: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6108: 	if ($pack_type eq 'default') {
 6109: 	    $do_default=1;
 6110: 	} elsif ($pack_type eq 'extension') {
 6111: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6112: 	} else {
 6113: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6114: 	}
 6115:     }
 6116:     # first look for a package that matches the requested part id
 6117:     foreach my $package (@specifics) {
 6118: 	my (undef,$pack_type,$pack_part)=@{$package};
 6119: 	next if ($pack_part ne $part);
 6120: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6121: 	    return $packagetab{"$pack_type&$name&default"};
 6122: 	}
 6123:     }
 6124:     # look for any possible matching non extension_ package
 6125:     foreach my $package (@specifics) {
 6126: 	my (undef,$pack_type,$pack_part)=@{$package};
 6127: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6128: 	    return $packagetab{"$pack_type&$name&default"};
 6129: 	}
 6130: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6131: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6132: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6133: 	}
 6134:     }
 6135:     # look for any posible extension_ match
 6136:     foreach my $package (@extension) {
 6137: 	my ($package,$pack_type)=@{$package};
 6138: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6139: 	    return $packagetab{"$pack_type&$name&default"};
 6140: 	}
 6141: 	if (defined($packagetab{$package."&$name&default"})) {
 6142: 	    return $packagetab{$package."&$name&default"};
 6143: 	}
 6144:     }
 6145:     # look for a global default setting
 6146:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6147: 	return $packagetab{"default&$name&default"};
 6148:     }
 6149:     return undef;
 6150: }
 6151: 
 6152: sub add_prefix_and_part {
 6153:     my ($prefix,$part)=@_;
 6154:     my $keyroot;
 6155:     if (defined($prefix) && $prefix !~ /^__/) {
 6156: 	# prefix that has a part already
 6157: 	$keyroot=$prefix;
 6158:     } elsif (defined($prefix)) {
 6159: 	# prefix that is missing a part
 6160: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6161:     } else {
 6162: 	# no prefix at all
 6163: 	if (defined($part)) { $keyroot='_'.$part; }
 6164:     }
 6165:     return $keyroot;
 6166: }
 6167: 
 6168: # ---------------------------------------------------------------- Get metadata
 6169: 
 6170: my %metaentry;
 6171: sub metadata {
 6172:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6173:     $uri=&declutter($uri);
 6174:     # if it is a non metadata possible uri return quickly
 6175:     if (($uri eq '') || 
 6176: 	(($uri =~ m|^/*adm/|) && 
 6177: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6178:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6179: 	($uri =~ m|home/$match_username/public_html/|)) {
 6180: 	return undef;
 6181:     }
 6182:     my $filename=$uri;
 6183:     $uri=~s/\.meta$//;
 6184: #
 6185: # Is the metadata already cached?
 6186: # Look at timestamp of caching
 6187: # Everything is cached by the main uri, libraries are never directly cached
 6188: #
 6189:     if (!defined($liburi)) {
 6190: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6191: 	if (defined($cached)) { return $result->{':'.$what}; }
 6192:     }
 6193:     {
 6194: #
 6195: # Is this a recursive call for a library?
 6196: #
 6197: #	if (! exists($metacache{$uri})) {
 6198: #	    $metacache{$uri}={};
 6199: #	}
 6200:         if ($liburi) {
 6201: 	    $liburi=&declutter($liburi);
 6202:             $filename=$liburi;
 6203:         } else {
 6204: 	    &devalidate_cache_new('meta',$uri);
 6205: 	    undef(%metaentry);
 6206: 	}
 6207:         my %metathesekeys=();
 6208:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6209: 	my $metastring;
 6210: 	if ($uri !~ m -^(editupload)/-) {
 6211: 	    my $file=&filelocation('',&clutter($filename));
 6212: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6213: 	    $metastring=&getfile($file);
 6214: 	}
 6215:         my $parser=HTML::LCParser->new(\$metastring);
 6216:         my $token;
 6217:         undef %metathesekeys;
 6218:         while ($token=$parser->get_token) {
 6219: 	    if ($token->[0] eq 'S') {
 6220: 		if (defined($token->[2]->{'package'})) {
 6221: #
 6222: # This is a package - get package info
 6223: #
 6224: 		    my $package=$token->[2]->{'package'};
 6225: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6226: 		    if (defined($token->[2]->{'id'})) { 
 6227: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6228: 		    }
 6229: 		    if ($metaentry{':packages'}) {
 6230: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6231: 		    } else {
 6232: 			$metaentry{':packages'}=$package.$keyroot;
 6233: 		    }
 6234: 		    foreach my $pack_entry (keys(%packagetab)) {
 6235: 			my $part=$keyroot;
 6236: 			$part=~s/^\_//;
 6237: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6238: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6239: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6240: 			    # ignore package.tab specified default values
 6241:                             # here &package_tab_default() will fetch those
 6242: 			    if ($subp eq 'default') { next; }
 6243: 			    my $value=$packagetab{$pack_entry};
 6244: 			    my $unikey;
 6245: 			    if ($pack =~ /_0$/) {
 6246: 				$unikey='parameter_0_'.$name;
 6247: 				$part=0;
 6248: 			    } else {
 6249: 				$unikey='parameter'.$keyroot.'_'.$name;
 6250: 			    }
 6251: 			    if ($subp eq 'display') {
 6252: 				$value.=' [Part: '.$part.']';
 6253: 			    }
 6254: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6255: 			    $metathesekeys{$unikey}=1;
 6256: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6257: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6258: 			    }
 6259: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6260: 				$metaentry{':'.$unikey}=
 6261: 				    $metaentry{':'.$unikey.'.default'};
 6262: 			    }
 6263: 			}
 6264: 		    }
 6265: 		} else {
 6266: #
 6267: # This is not a package - some other kind of start tag
 6268: #
 6269: 		    my $entry=$token->[1];
 6270: 		    my $unikey;
 6271: 		    if ($entry eq 'import') {
 6272: 			$unikey='';
 6273: 		    } else {
 6274: 			$unikey=$entry;
 6275: 		    }
 6276: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6277: 
 6278: 		    if (defined($token->[2]->{'id'})) { 
 6279: 			$unikey.='_'.$token->[2]->{'id'}; 
 6280: 		    }
 6281: 
 6282: 		    if ($entry eq 'import') {
 6283: #
 6284: # Importing a library here
 6285: #
 6286: 			if ($depthcount<20) {
 6287: 			    my $location=$parser->get_text('/import');
 6288: 			    my $dir=$filename;
 6289: 			    $dir=~s|[^/]*$||;
 6290: 			    $location=&filelocation($dir,$location);
 6291: 			    my $metadata = 
 6292: 				&metadata($uri,'keys', $location,$unikey,
 6293: 					  $depthcount+1);
 6294: 			    foreach my $meta (split(',',$metadata)) {
 6295: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6296: 				$metathesekeys{$meta}=1;
 6297: 			    }
 6298: 			}
 6299: 		    } else { 
 6300: 			
 6301: 			if (defined($token->[2]->{'name'})) { 
 6302: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6303: 			}
 6304: 			$metathesekeys{$unikey}=1;
 6305: 			foreach my $param (@{$token->[3]}) {
 6306: 			    $metaentry{':'.$unikey.'.'.$param} =
 6307: 				$token->[2]->{$param};
 6308: 			}
 6309: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6310: 			my $default=$metaentry{':'.$unikey.'.default'};
 6311: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6312: 		 # only ws inside the tag, and not in default, so use default
 6313: 		 # as value
 6314: 			    $metaentry{':'.$unikey}=$default;
 6315: 			} else {
 6316: 		  # either something interesting inside the tag or default
 6317:                   # uninteresting
 6318: 			    $metaentry{':'.$unikey}=$internaltext;
 6319: 			}
 6320: # end of not-a-package not-a-library import
 6321: 		    }
 6322: # end of not-a-package start tag
 6323: 		}
 6324: # the next is the end of "start tag"
 6325: 	    }
 6326: 	}
 6327: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6328: 	foreach my $key (keys(%packagetab)) {
 6329: 	    #no specific packages #how's our extension
 6330: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6331: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6332: 					 \%metathesekeys);
 6333: 	}
 6334: 	if (!exists($metaentry{':packages'})) {
 6335: 	    foreach my $key (keys(%packagetab)) {
 6336: 		#no specific packages well let's get default then
 6337: 		if ($key!~/^default&/) { next; }
 6338: 		&metadata_create_package_def($uri,$key,'default',
 6339: 					     \%metathesekeys);
 6340: 	    }
 6341: 	}
 6342: # are there custom rights to evaluate
 6343: 	if ($metaentry{':copyright'} eq 'custom') {
 6344: 
 6345:     #
 6346:     # Importing a rights file here
 6347:     #
 6348: 	    unless ($depthcount) {
 6349: 		my $location=$metaentry{':customdistributionfile'};
 6350: 		my $dir=$filename;
 6351: 		$dir=~s|[^/]*$||;
 6352: 		$location=&filelocation($dir,$location);
 6353: 		my $rights_metadata =
 6354: 		    &metadata($uri,'keys',$location,'_rights',
 6355: 			      $depthcount+1);
 6356: 		foreach my $rights (split(',',$rights_metadata)) {
 6357: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6358: 		    $metathesekeys{$rights}=1;
 6359: 		}
 6360: 	    }
 6361: 	}
 6362: 	# uniqifiy package listing
 6363: 	my %seen;
 6364: 	my @uniq_packages =
 6365: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6366: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6367: 
 6368: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6369: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6370: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6371: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6372: # this is the end of "was not already recently cached
 6373:     }
 6374:     return $metaentry{':'.$what};
 6375: }
 6376: 
 6377: sub metadata_create_package_def {
 6378:     my ($uri,$key,$package,$metathesekeys)=@_;
 6379:     my ($pack,$name,$subp)=split(/\&/,$key);
 6380:     if ($subp eq 'default') { next; }
 6381:     
 6382:     if (defined($metaentry{':packages'})) {
 6383: 	$metaentry{':packages'}.=','.$package;
 6384:     } else {
 6385: 	$metaentry{':packages'}=$package;
 6386:     }
 6387:     my $value=$packagetab{$key};
 6388:     my $unikey;
 6389:     $unikey='parameter_0_'.$name;
 6390:     $metaentry{':'.$unikey.'.part'}=0;
 6391:     $$metathesekeys{$unikey}=1;
 6392:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6393: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6394:     }
 6395:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6396: 	$metaentry{':'.$unikey}=
 6397: 	    $metaentry{':'.$unikey.'.default'};
 6398:     }
 6399: }
 6400: 
 6401: sub metadata_generate_part0 {
 6402:     my ($metadata,$metacache,$uri) = @_;
 6403:     my %allnames;
 6404:     foreach my $metakey (keys(%$metadata)) {
 6405: 	if ($metakey=~/^parameter\_(.*)/) {
 6406: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6407: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6408: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6409: 	    $allnames{$name}=$part;
 6410: 	  }
 6411: 	}
 6412:     }
 6413:     foreach my $name (keys(%allnames)) {
 6414:       $$metadata{"parameter_0_$name"}=1;
 6415:       my $key=":parameter_0_$name";
 6416:       $$metacache{"$key.part"}='0';
 6417:       $$metacache{"$key.name"}=$name;
 6418:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6419: 					   $allnames{$name}.'_'.$name.
 6420: 					   '.type'};
 6421:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6422: 			     '.display'};
 6423:       my $expr='[Part: '.$allnames{$name}.']';
 6424:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6425:       $$metacache{"$key.display"}=$olddis;
 6426:     }
 6427: }
 6428: 
 6429: # ------------------------------------------------------ Devalidate title cache
 6430: 
 6431: sub devalidate_title_cache {
 6432:     my ($url)=@_;
 6433:     if (!$env{'request.course.id'}) { return; }
 6434:     my $symb=&symbread($url);
 6435:     if (!$symb) { return; }
 6436:     my $key=$env{'request.course.id'}."\0".$symb;
 6437:     &devalidate_cache_new('title',$key);
 6438: }
 6439: 
 6440: # ------------------------------------------------- Get the title of a resource
 6441: 
 6442: sub gettitle {
 6443:     my $urlsymb=shift;
 6444:     my $symb=&symbread($urlsymb);
 6445:     if ($symb) {
 6446: 	my $key=$env{'request.course.id'}."\0".$symb;
 6447: 	my ($result,$cached)=&is_cached_new('title',$key);
 6448: 	if (defined($cached)) { 
 6449: 	    return $result;
 6450: 	}
 6451: 	my ($map,$resid,$url)=&decode_symb($symb);
 6452: 	my $title='';
 6453: 	my %bighash;
 6454: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6455: 		&GDBM_READER(),0640)) {
 6456: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6457: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6458: 	    untie %bighash;
 6459: 	}
 6460: 	$title=~s/\&colon\;/\:/gs;
 6461: 	if ($title) {
 6462: 	    return &do_cache_new('title',$key,$title,600);
 6463: 	}
 6464: 	$urlsymb=$url;
 6465:     }
 6466:     my $title=&metadata($urlsymb,'title');
 6467:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6468:     return $title;
 6469: }
 6470: 
 6471: sub get_slot {
 6472:     my ($which,$cnum,$cdom)=@_;
 6473:     if (!$cnum || !$cdom) {
 6474: 	(undef,my $courseid)=&whichuser();
 6475: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6476: 	$cnum=$env{'course.'.$courseid.'.num'};
 6477:     }
 6478:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6479:     my %slotinfo;
 6480:     if (exists($remembered{$key})) {
 6481: 	$slotinfo{$which} = $remembered{$key};
 6482:     } else {
 6483: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6484: 	&Apache::lonhomework::showhash(%slotinfo);
 6485: 	my ($tmp)=keys(%slotinfo);
 6486: 	if ($tmp=~/^error:/) { return (); }
 6487: 	$remembered{$key} = $slotinfo{$which};
 6488:     }
 6489:     if (ref($slotinfo{$which}) eq 'HASH') {
 6490: 	return %{$slotinfo{$which}};
 6491:     }
 6492:     return $slotinfo{$which};
 6493: }
 6494: # ------------------------------------------------- Update symbolic store links
 6495: 
 6496: sub symblist {
 6497:     my ($mapname,%newhash)=@_;
 6498:     $mapname=&deversion(&declutter($mapname));
 6499:     my %hash;
 6500:     if (($env{'request.course.fn'}) && (%newhash)) {
 6501:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6502:                       &GDBM_WRCREAT(),0640)) {
 6503: 	    foreach my $url (keys %newhash) {
 6504: 		next if ($url eq 'last_known'
 6505: 			 && $env{'form.no_update_last_known'});
 6506: 		$hash{declutter($url)}=&encode_symb($mapname,
 6507: 						    $newhash{$url}->[1],
 6508: 						    $newhash{$url}->[0]);
 6509:             }
 6510:             if (untie(%hash)) {
 6511: 		return 'ok';
 6512:             }
 6513:         }
 6514:     }
 6515:     return 'error';
 6516: }
 6517: 
 6518: # --------------------------------------------------------------- Verify a symb
 6519: 
 6520: sub symbverify {
 6521:     my ($symb,$thisurl)=@_;
 6522:     my $thisfn=$thisurl;
 6523:     $thisfn=&declutter($thisfn);
 6524: # direct jump to resource in page or to a sequence - will construct own symbs
 6525:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6526: # check URL part
 6527:     my ($map,$resid,$url)=&decode_symb($symb);
 6528: 
 6529:     unless ($url eq $thisfn) { return 0; }
 6530: 
 6531:     $symb=&symbclean($symb);
 6532:     $thisurl=&deversion($thisurl);
 6533:     $thisfn=&deversion($thisfn);
 6534: 
 6535:     my %bighash;
 6536:     my $okay=0;
 6537: 
 6538:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6539:                             &GDBM_READER(),0640)) {
 6540:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6541:         unless ($ids) { 
 6542:            $ids=$bighash{'ids_/'.$thisurl};
 6543:         }
 6544:         if ($ids) {
 6545: # ------------------------------------------------------------------- Has ID(s)
 6546: 	    foreach my $id (split(/\,/,$ids)) {
 6547: 	       my ($mapid,$resid)=split(/\./,$id);
 6548:                if (
 6549:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6550:    eq $symb) { 
 6551: 		   if (($env{'request.role.adv'}) ||
 6552: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6553: 		       $okay=1; 
 6554: 		   }
 6555: 	       }
 6556: 	   }
 6557:         }
 6558: 	untie(%bighash);
 6559:     }
 6560:     return $okay;
 6561: }
 6562: 
 6563: # --------------------------------------------------------------- Clean-up symb
 6564: 
 6565: sub symbclean {
 6566:     my $symb=shift;
 6567:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6568: # remove version from map
 6569:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6570: 
 6571: # remove version from URL
 6572:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6573: 
 6574: # remove wrapper
 6575: 
 6576:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6577:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6578:     return $symb;
 6579: }
 6580: 
 6581: # ---------------------------------------------- Split symb to find map and url
 6582: 
 6583: sub encode_symb {
 6584:     my ($map,$resid,$url)=@_;
 6585:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6586: }
 6587: 
 6588: sub decode_symb {
 6589:     my $symb=shift;
 6590:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6591:     my ($map,$resid,$url)=split(/___/,$symb);
 6592:     return (&fixversion($map),$resid,&fixversion($url));
 6593: }
 6594: 
 6595: sub fixversion {
 6596:     my $fn=shift;
 6597:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6598:     my %bighash;
 6599:     my $uri=&clutter($fn);
 6600:     my $key=$env{'request.course.id'}.'_'.$uri;
 6601: # is this cached?
 6602:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6603:     if (defined($cached)) { return $result; }
 6604: # unfortunately not cached, or expired
 6605:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6606: 	    &GDBM_READER(),0640)) {
 6607:  	if ($bighash{'version_'.$uri}) {
 6608:  	    my $version=$bighash{'version_'.$uri};
 6609:  	    unless (($version eq 'mostrecent') || 
 6610: 		    ($version==&getversion($uri))) {
 6611:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6612:  	    }
 6613:  	}
 6614:  	untie %bighash;
 6615:     }
 6616:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6617: }
 6618: 
 6619: sub deversion {
 6620:     my $url=shift;
 6621:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6622:     return $url;
 6623: }
 6624: 
 6625: # ------------------------------------------------------ Return symb list entry
 6626: 
 6627: sub symbread {
 6628:     my ($thisfn,$donotrecurse)=@_;
 6629:     my $cache_str='request.symbread.cached.'.$thisfn;
 6630:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6631: # no filename provided? try from environment
 6632:     unless ($thisfn) {
 6633:         if ($env{'request.symb'}) {
 6634: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6635: 	}
 6636: 	$thisfn=$env{'request.filename'};
 6637:     }
 6638:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6639: # is that filename actually a symb? Verify, clean, and return
 6640:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6641: 	if (&symbverify($thisfn,$1)) {
 6642: 	    return $env{$cache_str}=&symbclean($thisfn);
 6643: 	}
 6644:     }
 6645:     $thisfn=declutter($thisfn);
 6646:     my %hash;
 6647:     my %bighash;
 6648:     my $syval='';
 6649:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6650:         my $targetfn = $thisfn;
 6651:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6652:             $targetfn = 'adm/wrapper/'.$thisfn;
 6653:         }
 6654: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6655: 	    $targetfn=$1;
 6656: 	}
 6657:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6658:                       &GDBM_READER(),0640)) {
 6659: 	    $syval=$hash{$targetfn};
 6660:             untie(%hash);
 6661:         }
 6662: # ---------------------------------------------------------- There was an entry
 6663:         if ($syval) {
 6664: 	    #unless ($syval=~/\_\d+$/) {
 6665: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6666: 		    #&appenv('request.ambiguous' => $thisfn);
 6667: 		    #return $env{$cache_str}='';
 6668: 		#}    
 6669: 		#$syval.=$1;
 6670: 	    #}
 6671:         } else {
 6672: # ------------------------------------------------------- Was not in symb table
 6673:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6674:                             &GDBM_READER(),0640)) {
 6675: # ---------------------------------------------- Get ID(s) for current resource
 6676:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6677:               unless ($ids) { 
 6678:                  $ids=$bighash{'ids_/'.$thisfn};
 6679:               }
 6680:               unless ($ids) {
 6681: # alias?
 6682: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6683:               }
 6684:               if ($ids) {
 6685: # ------------------------------------------------------------------- Has ID(s)
 6686:                  my @possibilities=split(/\,/,$ids);
 6687:                  if ($#possibilities==0) {
 6688: # ----------------------------------------------- There is only one possibility
 6689: 		     my ($mapid,$resid)=split(/\./,$ids);
 6690: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6691: 						    $resid,$thisfn);
 6692:                  } elsif (!$donotrecurse) {
 6693: # ------------------------------------------ There is more than one possibility
 6694:                      my $realpossible=0;
 6695:                      foreach my $id (@possibilities) {
 6696: 			 my $file=$bighash{'src_'.$id};
 6697:                          if (&allowed('bre',$file)) {
 6698:          		    my ($mapid,$resid)=split(/\./,$id);
 6699:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6700: 				$realpossible++;
 6701:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6702: 						    $resid,$thisfn);
 6703:                             }
 6704: 			 }
 6705:                      }
 6706: 		     if ($realpossible!=1) { $syval=''; }
 6707:                  } else {
 6708:                      $syval='';
 6709:                  }
 6710: 	      }
 6711:               untie(%bighash)
 6712:            }
 6713:         }
 6714:         if ($syval) {
 6715: 	    return $env{$cache_str}=$syval;
 6716:         }
 6717:     }
 6718:     &appenv('request.ambiguous' => $thisfn);
 6719:     return $env{$cache_str}='';
 6720: }
 6721: 
 6722: # ---------------------------------------------------------- Return random seed
 6723: 
 6724: sub numval {
 6725:     my $txt=shift;
 6726:     $txt=~tr/A-J/0-9/;
 6727:     $txt=~tr/a-j/0-9/;
 6728:     $txt=~tr/K-T/0-9/;
 6729:     $txt=~tr/k-t/0-9/;
 6730:     $txt=~tr/U-Z/0-5/;
 6731:     $txt=~tr/u-z/0-5/;
 6732:     $txt=~s/\D//g;
 6733:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6734:     return int($txt);
 6735: }
 6736: 
 6737: sub numval2 {
 6738:     my $txt=shift;
 6739:     $txt=~tr/A-J/0-9/;
 6740:     $txt=~tr/a-j/0-9/;
 6741:     $txt=~tr/K-T/0-9/;
 6742:     $txt=~tr/k-t/0-9/;
 6743:     $txt=~tr/U-Z/0-5/;
 6744:     $txt=~tr/u-z/0-5/;
 6745:     $txt=~s/\D//g;
 6746:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6747:     my $total;
 6748:     foreach my $val (@txts) { $total+=$val; }
 6749:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6750:     return int($total);
 6751: }
 6752: 
 6753: sub numval3 {
 6754:     use integer;
 6755:     my $txt=shift;
 6756:     $txt=~tr/A-J/0-9/;
 6757:     $txt=~tr/a-j/0-9/;
 6758:     $txt=~tr/K-T/0-9/;
 6759:     $txt=~tr/k-t/0-9/;
 6760:     $txt=~tr/U-Z/0-5/;
 6761:     $txt=~tr/u-z/0-5/;
 6762:     $txt=~s/\D//g;
 6763:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6764:     my $total;
 6765:     foreach my $val (@txts) { $total+=$val; }
 6766:     if ($_64bit) { $total=(($total<<32)>>32); }
 6767:     return $total;
 6768: }
 6769: 
 6770: sub digest {
 6771:     my ($data)=@_;
 6772:     my $digest=&Digest::MD5::md5($data);
 6773:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6774:     my ($e,$f);
 6775:     {
 6776:         use integer;
 6777:         $e=($a+$b);
 6778:         $f=($c+$d);
 6779:         if ($_64bit) {
 6780:             $e=(($e<<32)>>32);
 6781:             $f=(($f<<32)>>32);
 6782:         }
 6783:     }
 6784:     if (wantarray) {
 6785: 	return ($e,$f);
 6786:     } else {
 6787: 	my $g;
 6788: 	{
 6789: 	    use integer;
 6790: 	    $g=($e+$f);
 6791: 	    if ($_64bit) {
 6792: 		$g=(($g<<32)>>32);
 6793: 	    }
 6794: 	}
 6795: 	return $g;
 6796:     }
 6797: }
 6798: 
 6799: sub latest_rnd_algorithm_id {
 6800:     return '64bit5';
 6801: }
 6802: 
 6803: sub get_rand_alg {
 6804:     my ($courseid)=@_;
 6805:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6806:     if ($courseid) {
 6807: 	return $env{"course.$courseid.rndseed"};
 6808:     }
 6809:     return &latest_rnd_algorithm_id();
 6810: }
 6811: 
 6812: sub validCODE {
 6813:     my ($CODE)=@_;
 6814:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6815:     return 0;
 6816: }
 6817: 
 6818: sub getCODE {
 6819:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6820:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6821: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6822: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6823: 	return $Apache::lonhomework::history{'resource.CODE'};
 6824:     }
 6825:     return undef;
 6826: }
 6827: 
 6828: sub rndseed {
 6829:     my ($symb,$courseid,$domain,$username)=@_;
 6830: 
 6831:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6832:     if (!$symb) {
 6833: 	unless ($symb=$wsymb) { return time; }
 6834:     }
 6835:     if (!$courseid) { $courseid=$wcourseid; }
 6836:     if (!$domain) { $domain=$wdomain; }
 6837:     if (!$username) { $username=$wusername }
 6838:     my $which=&get_rand_alg();
 6839: 
 6840:     if (defined(&getCODE())) {
 6841: 	if ($which eq '64bit5') {
 6842: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6843: 	} elsif ($which eq '64bit4') {
 6844: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6845: 	} else {
 6846: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6847: 	}
 6848:     } elsif ($which eq '64bit5') {
 6849: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6850:     } elsif ($which eq '64bit4') {
 6851: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6852:     } elsif ($which eq '64bit3') {
 6853: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6854:     } elsif ($which eq '64bit2') {
 6855: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6856:     } elsif ($which eq '64bit') {
 6857: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6858:     }
 6859:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6860: }
 6861: 
 6862: sub rndseed_32bit {
 6863:     my ($symb,$courseid,$domain,$username)=@_;
 6864:     {
 6865: 	use integer;
 6866: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6867: 	my $symbseed=numval($symb) << 22;
 6868: 	my $namechck=unpack("%32C*",$username) << 17;
 6869: 	my $nameseed=numval($username) << 12;
 6870: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6871: 	my $courseseed=unpack("%32C*",$courseid);
 6872: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6873: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6874: 	#&logthis("rndseed :$num:$symb");
 6875: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6876: 	return $num;
 6877:     }
 6878: }
 6879: 
 6880: sub rndseed_64bit {
 6881:     my ($symb,$courseid,$domain,$username)=@_;
 6882:     {
 6883: 	use integer;
 6884: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6885: 	my $symbseed=numval($symb) << 10;
 6886: 	my $namechck=unpack("%32S*",$username);
 6887: 	
 6888: 	my $nameseed=numval($username) << 21;
 6889: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6890: 	my $courseseed=unpack("%32S*",$courseid);
 6891: 	
 6892: 	my $num1=$symbchck+$symbseed+$namechck;
 6893: 	my $num2=$nameseed+$domainseed+$courseseed;
 6894: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6895: 	#&logthis("rndseed :$num:$symb");
 6896: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6897: 	return "$num1,$num2";
 6898:     }
 6899: }
 6900: 
 6901: sub rndseed_64bit2 {
 6902:     my ($symb,$courseid,$domain,$username)=@_;
 6903:     {
 6904: 	use integer;
 6905: 	# strings need to be an even # of cahracters long, it it is odd the
 6906:         # last characters gets thrown away
 6907: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6908: 	my $symbseed=numval($symb) << 10;
 6909: 	my $namechck=unpack("%32S*",$username.' ');
 6910: 	
 6911: 	my $nameseed=numval($username) << 21;
 6912: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6913: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6914: 	
 6915: 	my $num1=$symbchck+$symbseed+$namechck;
 6916: 	my $num2=$nameseed+$domainseed+$courseseed;
 6917: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6918: 	#&logthis("rndseed :$num:$symb");
 6919: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6920: 	return "$num1,$num2";
 6921:     }
 6922: }
 6923: 
 6924: sub rndseed_64bit3 {
 6925:     my ($symb,$courseid,$domain,$username)=@_;
 6926:     {
 6927: 	use integer;
 6928: 	# strings need to be an even # of cahracters long, it it is odd the
 6929:         # last characters gets thrown away
 6930: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6931: 	my $symbseed=numval2($symb) << 10;
 6932: 	my $namechck=unpack("%32S*",$username.' ');
 6933: 	
 6934: 	my $nameseed=numval2($username) << 21;
 6935: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6936: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6937: 	
 6938: 	my $num1=$symbchck+$symbseed+$namechck;
 6939: 	my $num2=$nameseed+$domainseed+$courseseed;
 6940: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6941: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 6942: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6943: 	
 6944: 	return "$num1:$num2";
 6945:     }
 6946: }
 6947: 
 6948: sub rndseed_64bit4 {
 6949:     my ($symb,$courseid,$domain,$username)=@_;
 6950:     {
 6951: 	use integer;
 6952: 	# strings need to be an even # of cahracters long, it it is odd the
 6953:         # last characters gets thrown away
 6954: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6955: 	my $symbseed=numval3($symb) << 10;
 6956: 	my $namechck=unpack("%32S*",$username.' ');
 6957: 	
 6958: 	my $nameseed=numval3($username) << 21;
 6959: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6960: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6961: 	
 6962: 	my $num1=$symbchck+$symbseed+$namechck;
 6963: 	my $num2=$nameseed+$domainseed+$courseseed;
 6964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6965: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 6966: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6967: 	
 6968: 	return "$num1:$num2";
 6969:     }
 6970: }
 6971: 
 6972: sub rndseed_64bit5 {
 6973:     my ($symb,$courseid,$domain,$username)=@_;
 6974:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6975:     return "$num1:$num2";
 6976: }
 6977: 
 6978: sub rndseed_CODE_64bit {
 6979:     my ($symb,$courseid,$domain,$username)=@_;
 6980:     {
 6981: 	use integer;
 6982: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6983: 	my $symbseed=numval2($symb);
 6984: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6985: 	my $CODEseed=numval(&getCODE());
 6986: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6987: 	my $num1=$symbseed+$CODEchck;
 6988: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6989: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6990: 	#&logthis("rndseed :$num1:$num2:$symb");
 6991: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6992: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6993: 	return "$num1:$num2";
 6994:     }
 6995: }
 6996: 
 6997: sub rndseed_CODE_64bit4 {
 6998:     my ($symb,$courseid,$domain,$username)=@_;
 6999:     {
 7000: 	use integer;
 7001: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7002: 	my $symbseed=numval3($symb);
 7003: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7004: 	my $CODEseed=numval3(&getCODE());
 7005: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7006: 	my $num1=$symbseed+$CODEchck;
 7007: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7008: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7009: 	#&logthis("rndseed :$num1:$num2:$symb");
 7010: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7011: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7012: 	return "$num1:$num2";
 7013:     }
 7014: }
 7015: 
 7016: sub rndseed_CODE_64bit5 {
 7017:     my ($symb,$courseid,$domain,$username)=@_;
 7018:     my $code = &getCODE();
 7019:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7020:     return "$num1:$num2";
 7021: }
 7022: 
 7023: sub setup_random_from_rndseed {
 7024:     my ($rndseed)=@_;
 7025:     if ($rndseed =~/([,:])/) {
 7026: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7027: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7028:     } else {
 7029: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7030:     }
 7031: }
 7032: 
 7033: sub latest_receipt_algorithm_id {
 7034:     return 'receipt2';
 7035: }
 7036: 
 7037: sub recunique {
 7038:     my $fucourseid=shift;
 7039:     my $unique;
 7040:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7041: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7042:     } else {
 7043: 	$unique=$perlvar{'lonReceipt'};
 7044:     }
 7045:     return unpack("%32C*",$unique);
 7046: }
 7047: 
 7048: sub recprefix {
 7049:     my $fucourseid=shift;
 7050:     my $prefix;
 7051:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7052: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7053:     } else {
 7054: 	$prefix=$perlvar{'lonHostID'};
 7055:     }
 7056:     return unpack("%32C*",$prefix);
 7057: }
 7058: 
 7059: sub ireceipt {
 7060:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7061:     my $cuname=unpack("%32C*",$funame);
 7062:     my $cudom=unpack("%32C*",$fudom);
 7063:     my $cucourseid=unpack("%32C*",$fucourseid);
 7064:     my $cusymb=unpack("%32C*",$fusymb);
 7065:     my $cunique=&recunique($fucourseid);
 7066:     my $cpart=unpack("%32S*",$part);
 7067:     my $return =&recprefix($fucourseid).'-';
 7068:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7069: 	$env{'request.state'} eq 'construct') {
 7070: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7071: 			       
 7072: 	$return.= ($cunique%$cuname+
 7073: 		   $cunique%$cudom+
 7074: 		   $cusymb%$cuname+
 7075: 		   $cusymb%$cudom+
 7076: 		   $cucourseid%$cuname+
 7077: 		   $cucourseid%$cudom+
 7078: 		   $cpart%$cuname+
 7079: 		   $cpart%$cudom);
 7080:     } else {
 7081: 	$return.= ($cunique%$cuname+
 7082: 		   $cunique%$cudom+
 7083: 		   $cusymb%$cuname+
 7084: 		   $cusymb%$cudom+
 7085: 		   $cucourseid%$cuname+
 7086: 		   $cucourseid%$cudom);
 7087:     }
 7088:     return $return;
 7089: }
 7090: 
 7091: sub receipt {
 7092:     my ($part)=@_;
 7093:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7094:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7095: }
 7096: 
 7097: sub whichuser {
 7098:     my ($passedsymb)=@_;
 7099:     my ($symb,$courseid,$domain,$name,$publicuser);
 7100:     if (defined($env{'form.grade_symb'})) {
 7101: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7102: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7103: 	if (!$allowed &&
 7104: 	    exists($env{'request.course.sec'}) &&
 7105: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7106: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7107: 			      '/'.$env{'request.course.sec'});
 7108: 	}
 7109: 	if ($allowed) {
 7110: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7111: 	    $courseid=$tmp_courseid;
 7112: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7113: 	    ($name)=&get_env_multiple('form.grade_username');
 7114: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7115: 	}
 7116:     }
 7117:     if (!$passedsymb) {
 7118: 	$symb=&symbread();
 7119:     } else {
 7120: 	$symb=$passedsymb;
 7121:     }
 7122:     $courseid=$env{'request.course.id'};
 7123:     $domain=$env{'user.domain'};
 7124:     $name=$env{'user.name'};
 7125:     if ($name eq 'public' && $domain eq 'public') {
 7126: 	if (!defined($env{'form.username'})) {
 7127: 	    $env{'form.username'}.=time.rand(10000000);
 7128: 	}
 7129: 	$name.=$env{'form.username'};
 7130:     }
 7131:     return ($symb,$courseid,$domain,$name,$publicuser);
 7132: 
 7133: }
 7134: 
 7135: # ------------------------------------------------------------ Serves up a file
 7136: # returns either the contents of the file or 
 7137: # -1 if the file doesn't exist
 7138: #
 7139: # if the target is a file that was uploaded via DOCS, 
 7140: # a check will be made to see if a current copy exists on the local server,
 7141: # if it does this will be served, otherwise a copy will be retrieved from
 7142: # the home server for the course and stored in /home/httpd/html/userfiles on
 7143: # the local server.   
 7144: 
 7145: sub getfile {
 7146:     my ($file) = @_;
 7147:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7148:     &repcopy($file);
 7149:     return &readfile($file);
 7150: }
 7151: 
 7152: sub repcopy_userfile {
 7153:     my ($file)=@_;
 7154:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7155:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7156:     my ($cdom,$cnum,$filename) = 
 7157: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7158:     my ($info,$rtncode);
 7159:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7160:     if (-e "$file") {
 7161: 	my @fileinfo = stat($file);
 7162: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7163: 	if ($lwpresp ne 'ok') {
 7164: 	    if ($rtncode eq '404') {
 7165: 		unlink($file);
 7166: 	    }
 7167: 	    #my $ua=new LWP::UserAgent;
 7168: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 7169: 	    #my $response=$ua->request($request);
 7170: 	    #if ($response->is_success()) {
 7171: 	#	return $response->content;
 7172: 	#    } else {
 7173: 	#	return -1;
 7174: 	#    }
 7175: 	    return -1;
 7176: 	}
 7177: 	if ($info < $fileinfo[9]) {
 7178: 	    return 'ok';
 7179: 	}
 7180: 	$info = '';
 7181: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 7182: 	if ($lwpresp ne 'ok') {
 7183: 	    return -1;
 7184: 	}
 7185:     } else {
 7186: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 7187: 	if ($lwpresp ne 'ok') {
 7188: 	    return -1;
 7189: 	}
 7190: 	my @parts = ($cdom,$cnum); 
 7191: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 7192: 	    push @parts, split(/\//,$1);
 7193: 	}
 7194: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7195: 	foreach my $part (@parts) {
 7196: 	    $path .= '/'.$part;
 7197: 	    if (!-e $path) {
 7198: 		mkdir($path,0770);
 7199: 	    }
 7200: 	}
 7201:     }
 7202:     open(FILE,">$file");
 7203:     print FILE $info;
 7204:     close(FILE);
 7205:     return 'ok';
 7206: }
 7207: 
 7208: sub tokenwrapper {
 7209:     my $uri=shift;
 7210:     $uri=~s|^http\://([^/]+)||;
 7211:     $uri=~s|^/||;
 7212:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7213:     my $token=$1;
 7214:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7215:     if ($udom && $uname && $file) {
 7216: 	$file=~s|(\?\.*)*$||;
 7217:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7218:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 7219:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7220:                                '&tokenissued='.$perlvar{'lonHostID'};
 7221:     } else {
 7222:         return '/adm/notfound.html';
 7223:     }
 7224: }
 7225: 
 7226: sub getuploaded {
 7227:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7228:     $uri=~s/^\///;
 7229:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 7230:     my $ua=new LWP::UserAgent;
 7231:     my $request=new HTTP::Request($reqtype,$uri);
 7232:     my $response=$ua->request($request);
 7233:     $$rtncode = $response->code;
 7234:     if (! $response->is_success()) {
 7235: 	return 'failed';
 7236:     }      
 7237:     if ($reqtype eq 'HEAD') {
 7238: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7239:     } elsif ($reqtype eq 'GET') {
 7240: 	$$info = $response->content;
 7241:     }
 7242:     return 'ok';
 7243: }
 7244: 
 7245: sub readfile {
 7246:     my $file = shift;
 7247:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7248:     my $fh;
 7249:     open($fh,"<$file");
 7250:     my $a='';
 7251:     while (my $line = <$fh>) { $a .= $line; }
 7252:     return $a;
 7253: }
 7254: 
 7255: sub filelocation {
 7256:     my ($dir,$file) = @_;
 7257:     my $location;
 7258:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7259: 
 7260:     if ($file =~ m-^/adm/-) {
 7261: 	$file=~s-^/adm/wrapper/-/-;
 7262: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7263:     }
 7264:     if ($file=~m:^/~:) { # is a contruction space reference
 7265:         $location = $file;
 7266:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7267:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7268: 	# is a correct contruction space reference
 7269:         $location = $file;
 7270:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7271:         my ($udom,$uname,$filename)=
 7272:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7273:         my $home=&homeserver($uname,$udom);
 7274:         my $is_me=0;
 7275:         my @ids=&current_machine_ids();
 7276:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7277:         if ($is_me) {
 7278:   	    $location=&propath($udom,$uname).
 7279:   	      '/userfiles/'.$filename;
 7280:         } else {
 7281:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7282:   	      $udom.'/'.$uname.'/'.$filename;
 7283:         }
 7284:     } else {
 7285:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7286:         $file=~s:^/res/:/:;
 7287:         if ( !( $file =~ m:^/:) ) {
 7288:             $location = $dir. '/'.$file;
 7289:         } else {
 7290:             $location = '/home/httpd/html/res'.$file;
 7291:         }
 7292:     }
 7293:     $location=~s://+:/:g; # remove duplicate /
 7294:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7295:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7296:     return $location;
 7297: }
 7298: 
 7299: sub hreflocation {
 7300:     my ($dir,$file)=@_;
 7301:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7302: 	$file=filelocation($dir,$file);
 7303:     } elsif ($file=~m-^/adm/-) {
 7304: 	$file=~s-^/adm/wrapper/-/-;
 7305: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7306:     }
 7307:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7308: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7309:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7310: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7311:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7312: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7313: 	    -/uploaded/$1/$2/-x;
 7314:     }
 7315:     return $file;
 7316: }
 7317: 
 7318: sub current_machine_domains {
 7319:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7320:     my @domains;
 7321:     while( my($id, $name) = each(%hostname)) {
 7322: #	&logthis("-$id-$name-$hostname-");
 7323: 	if ($hostname eq $name) {
 7324: 	    push(@domains,$hostdom{$id});
 7325: 	}
 7326:     }
 7327:     return @domains;
 7328: }
 7329: 
 7330: sub current_machine_ids {
 7331:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7332:     my @ids;
 7333:     while( my($id, $name) = each(%hostname)) {
 7334: #	&logthis("-$id-$name-$hostname-");
 7335: 	if ($hostname eq $name) {
 7336: 	    push(@ids,$id);
 7337: 	}
 7338:     }
 7339:     return @ids;
 7340: }
 7341: 
 7342: sub additional_machine_domains {
 7343:     my @domains;
 7344:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7345:     while( my $line = <$fh>) {
 7346:         $line =~ s/\s//g;
 7347:         push(@domains,$line);
 7348:     }
 7349:     return @domains;
 7350: }
 7351: 
 7352: sub default_login_domain {
 7353:     my $domain = $perlvar{'lonDefDomain'};
 7354:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7355:     foreach my $posdom (&current_machine_domains(),
 7356:                         &additional_machine_domains()) {
 7357:         if (lc($posdom) eq lc($testdomain)) {
 7358:             $domain=$posdom;
 7359:             last;
 7360:         }
 7361:     }
 7362:     return $domain;
 7363: }
 7364: 
 7365: # ------------------------------------------------------------- Declutters URLs
 7366: 
 7367: sub declutter {
 7368:     my $thisfn=shift;
 7369:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7370:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7371:     $thisfn=~s/^\///;
 7372:     $thisfn=~s|^adm/wrapper/||;
 7373:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7374:     $thisfn=~s/^res\///;
 7375:     $thisfn=~s/\?.+$//;
 7376:     return $thisfn;
 7377: }
 7378: 
 7379: # ------------------------------------------------------------- Clutter up URLs
 7380: 
 7381: sub clutter {
 7382:     my $thisfn='/'.&declutter(shift);
 7383:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7384:        $thisfn='/res'.$thisfn; 
 7385:     }
 7386:     if ($thisfn !~m|/adm|) {
 7387: 	if ($thisfn =~ m|/ext/|) {
 7388: 	    $thisfn='/adm/wrapper'.$thisfn;
 7389: 	} else {
 7390: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7391: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7392: 	    if ($embstyle eq 'ssi'
 7393: 		|| ($embstyle eq 'hdn')
 7394: 		|| ($embstyle eq 'rat')
 7395: 		|| ($embstyle eq 'prv')
 7396: 		|| ($embstyle eq 'ign')) {
 7397: 		#do nothing with these
 7398: 	    } elsif (($embstyle eq 'img') 
 7399: 		|| ($embstyle eq 'emb')
 7400: 		|| ($embstyle eq 'wrp')) {
 7401: 		$thisfn='/adm/wrapper'.$thisfn;
 7402: 	    } elsif ($embstyle eq 'unk'
 7403: 		     && $thisfn!~/\.(sequence|page)$/) {
 7404: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7405: 	    } else {
 7406: #		&logthis("Got a blank emb style");
 7407: 	    }
 7408: 	}
 7409:     }
 7410:     return $thisfn;
 7411: }
 7412: 
 7413: sub clutter_with_no_wrapper {
 7414:     my $uri = &clutter(shift);
 7415:     if ($uri =~ m-^/adm/-) {
 7416: 	$uri =~ s-^/adm/wrapper/-/-;
 7417: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7418:     }
 7419:     return $uri;
 7420: }
 7421: 
 7422: sub freeze_escape {
 7423:     my ($value)=@_;
 7424:     if (ref($value)) {
 7425: 	$value=&nfreeze($value);
 7426: 	return '__FROZEN__'.&escape($value);
 7427:     }
 7428:     return &escape($value);
 7429: }
 7430: 
 7431: 
 7432: sub thaw_unescape {
 7433:     my ($value)=@_;
 7434:     if ($value =~ /^__FROZEN__/) {
 7435: 	substr($value,0,10,undef);
 7436: 	$value=&unescape($value);
 7437: 	return &thaw($value);
 7438:     }
 7439:     return &unescape($value);
 7440: }
 7441: 
 7442: sub correct_line_ends {
 7443:     my ($result)=@_;
 7444:     $$result =~s/\r\n/\n/mg;
 7445:     $$result =~s/\r/\n/mg;
 7446: }
 7447: # ================================================================ Main Program
 7448: 
 7449: sub goodbye {
 7450:    &logthis("Starting Shut down");
 7451: #not converted to using infrastruture and probably shouldn't be
 7452:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7453: #converted
 7454: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7455:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7456: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7457: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7458: #1.1 only
 7459: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7460: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7461: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7462: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7463:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7464:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7465:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7466:    &flushcourselogs();
 7467:    &logthis("Shutting down");
 7468: }
 7469: 
 7470: BEGIN {
 7471: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7472:     unless ($readit) {
 7473: {
 7474:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7475:     %perlvar = (%perlvar,%{$configvars});
 7476: }
 7477: 
 7478: # ------------------------------------------------------------ Read domain file
 7479: {
 7480:     %domaindescription = ();
 7481:     %domain_auth_def = ();
 7482:     %domain_auth_arg_def = ();
 7483:     my $fh;
 7484:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7485: 	while (my $line = <$fh>) {
 7486:            next if ($line =~ /^(\#|\s*$)/);
 7487: #           next if /^\#/;
 7488:            chomp $line;
 7489:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7490: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
 7491: 	   $domain_auth_def{$domain}=$def_auth;
 7492:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7493: 	   $domaindescription{$domain}=$domain_description;
 7494: 	   $domain_lang_def{$domain}=$def_lang;
 7495: 	   $domain_city{$domain}=$city;
 7496: 	   $domain_longi{$domain}=$longi;
 7497: 	   $domain_lati{$domain}=$lati;
 7498:            $domain_primary{$domain}=$primary;
 7499: 
 7500:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7501: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7502: 	}
 7503:     }
 7504:     close ($fh);
 7505: }
 7506: 
 7507: 
 7508: # ------------------------------------------------------------- Read hosts file
 7509: {
 7510:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7511: 
 7512:     while (my $configline=<$config>) {
 7513:        next if ($configline =~ /^(\#|\s*$)/);
 7514:        chomp($configline);
 7515:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7516:        $name=~s/\s//g;
 7517:        if ($id && $domain && $role && $name) {
 7518: 	 $hostname{$id}=$name;
 7519: 	 $hostdom{$id}=$domain;
 7520: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7521:        }
 7522:     }
 7523:     close($config);
 7524:     # FIXME: dev server don't want this, production servers _do_ want this
 7525:     #&get_iphost();
 7526: }
 7527: 
 7528: sub get_iphost {
 7529:     if (%iphost) { return %iphost; }
 7530:     my %name_to_ip;
 7531:     foreach my $id (keys(%hostname)) {
 7532: 	my $name=$hostname{$id};
 7533: 	my $ip;
 7534: 	if (!exists($name_to_ip{$name})) {
 7535: 	    $ip = gethostbyname($name);
 7536: 	    if (!$ip || length($ip) ne 4) {
 7537: 		&logthis("Skipping host $id name $name no IP found\n");
 7538: 		next;
 7539: 	    }
 7540: 	    $ip=inet_ntoa($ip);
 7541: 	    $name_to_ip{$name} = $ip;
 7542: 	} else {
 7543: 	    $ip = $name_to_ip{$name};
 7544: 	}
 7545: 	push(@{$iphost{$ip}},$id);
 7546:     }
 7547:     return %iphost;
 7548: }
 7549: 
 7550: # ------------------------------------------------------ Read spare server file
 7551: {
 7552:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7553: 
 7554:     while (my $configline=<$config>) {
 7555:        chomp($configline);
 7556:        if ($configline) {
 7557: 	   my ($host,$type) = split(':',$configline,2);
 7558: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7559: 	   push(@{ $spareid{$type} }, $host);
 7560:        }
 7561:     }
 7562:     close($config);
 7563: }
 7564: # ------------------------------------------------------------ Read permissions
 7565: {
 7566:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7567: 
 7568:     while (my $configline=<$config>) {
 7569: 	chomp($configline);
 7570: 	if ($configline) {
 7571: 	    my ($role,$perm)=split(/ /,$configline);
 7572: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7573: 	}
 7574:     }
 7575:     close($config);
 7576: }
 7577: 
 7578: # -------------------------------------------- Read plain texts for permissions
 7579: {
 7580:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7581: 
 7582:     while (my $configline=<$config>) {
 7583: 	chomp($configline);
 7584: 	if ($configline) {
 7585: 	    my ($short,@plain)=split(/:/,$configline);
 7586:             %{$prp{$short}} = ();
 7587: 	    if (@plain > 0) {
 7588:                 $prp{$short}{'std'} = $plain[0];
 7589:                 for (my $i=1; $i<@plain; $i++) {
 7590:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7591:                 }
 7592:             }
 7593: 	}
 7594:     }
 7595:     close($config);
 7596: }
 7597: 
 7598: # ---------------------------------------------------------- Read package table
 7599: {
 7600:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7601: 
 7602:     while (my $configline=<$config>) {
 7603: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7604: 	chomp($configline);
 7605: 	my ($short,$plain)=split(/:/,$configline);
 7606: 	my ($pack,$name)=split(/\&/,$short);
 7607: 	if ($plain ne '') {
 7608: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7609: 	    $packagetab{$short}=$plain; 
 7610: 	}
 7611:     }
 7612:     close($config);
 7613: }
 7614: 
 7615: # ------------- set up temporary directory
 7616: {
 7617:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7618: 
 7619: }
 7620: 
 7621: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7622: 				'compress_threshold'=> 20_000,
 7623:  			        });
 7624: 
 7625: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7626: $dumpcount=0;
 7627: 
 7628: &logtouch();
 7629: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7630: $readit=1;
 7631:     {
 7632: 	use integer;
 7633: 	my $test=(2**32)+1;
 7634: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7635: 	&logthis(" Detected 64bit platform ($_64bit)");
 7636:     }
 7637: }
 7638: }
 7639: 
 7640: 1;
 7641: __END__
 7642: 
 7643: =pod
 7644: 
 7645: =head1 NAME
 7646: 
 7647: Apache::lonnet - Subroutines to ask questions about things in the network.
 7648: 
 7649: =head1 SYNOPSIS
 7650: 
 7651: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7652: 
 7653:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7654: 
 7655: Common parameters:
 7656: 
 7657: =over 4
 7658: 
 7659: =item *
 7660: 
 7661: $uname : an internal username (if $cname expecting a course Id specifically)
 7662: 
 7663: =item *
 7664: 
 7665: $udom : a domain (if $cdom expecting a course's domain specifically)
 7666: 
 7667: =item *
 7668: 
 7669: $symb : a resource instance identifier
 7670: 
 7671: =item *
 7672: 
 7673: $namespace : the name of a .db file that contains the data needed or
 7674: being set.
 7675: 
 7676: =back
 7677: 
 7678: =head1 OVERVIEW
 7679: 
 7680: lonnet provides subroutines which interact with the
 7681: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7682: about classes, users, and resources.
 7683: 
 7684: For many of these objects you can also use this to store data about
 7685: them or modify them in various ways.
 7686: 
 7687: =head2 Symbs
 7688: 
 7689: To identify a specific instance of a resource, LON-CAPA uses symbols
 7690: or "symbs"X<symb>. These identifiers are built from the URL of the
 7691: map, the resource number of the resource in the map, and the URL of
 7692: the resource itself. The latter is somewhat redundant, but might help
 7693: if maps change.
 7694: 
 7695: An example is
 7696: 
 7697:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7698: 
 7699: The respective map entry is
 7700: 
 7701:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7702:   title="Problem 2">
 7703:  </resource>
 7704: 
 7705: Symbs are used by the random number generator, as well as to store and
 7706: restore data specific to a certain instance of for example a problem.
 7707: 
 7708: =head2 Storing And Retrieving Data
 7709: 
 7710: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7711: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7712: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7713: is is the non-critical message twin of cstore. These functions are for
 7714: handlers to store a perl hash to a user's permanent data space in an
 7715: easy manner, and to retrieve it again on another call. It is expected
 7716: that a handler would use this once at the beginning to retrieve data,
 7717: and then again once at the end to send only the new data back.
 7718: 
 7719: The data is stored in the user's data directory on the user's
 7720: homeserver under the ID of the course.
 7721: 
 7722: The hash that is returned by restore will have all of the previous
 7723: value for all of the elements of the hash.
 7724: 
 7725: Example:
 7726: 
 7727:  #creating a hash
 7728:  my %hash;
 7729:  $hash{'foo'}='bar';
 7730: 
 7731:  #storing it
 7732:  &Apache::lonnet::cstore(\%hash);
 7733: 
 7734:  #changing a value
 7735:  $hash{'foo'}='notbar';
 7736: 
 7737:  #adding a new value
 7738:  $hash{'bar'}='foo';
 7739:  &Apache::lonnet::cstore(\%hash);
 7740: 
 7741:  #retrieving the hash
 7742:  my %history=&Apache::lonnet::restore();
 7743: 
 7744:  #print the hash
 7745:  foreach my $key (sort(keys(%history))) {
 7746:    print("\%history{$key} = $history{$key}");
 7747:  }
 7748: 
 7749: Will print out:
 7750: 
 7751:  %history{1:foo} = bar
 7752:  %history{1:keys} = foo:timestamp
 7753:  %history{1:timestamp} = 990455579
 7754:  %history{2:bar} = foo
 7755:  %history{2:foo} = notbar
 7756:  %history{2:keys} = foo:bar:timestamp
 7757:  %history{2:timestamp} = 990455580
 7758:  %history{bar} = foo
 7759:  %history{foo} = notbar
 7760:  %history{timestamp} = 990455580
 7761:  %history{version} = 2
 7762: 
 7763: Note that the special hash entries C<keys>, C<version> and
 7764: C<timestamp> were added to the hash. C<version> will be equal to the
 7765: total number of versions of the data that have been stored. The
 7766: C<timestamp> attribute will be the UNIX time the hash was
 7767: stored. C<keys> is available in every historical section to list which
 7768: keys were added or changed at a specific historical revision of a
 7769: hash.
 7770: 
 7771: B<Warning>: do not store the hash that restore returns directly. This
 7772: will cause a mess since it will restore the historical keys as if the
 7773: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7774: 
 7775: Calling convention:
 7776: 
 7777:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7778:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7779: 
 7780: For more detailed information, see lonnet specific documentation.
 7781: 
 7782: =head1 RETURN MESSAGES
 7783: 
 7784: =over 4
 7785: 
 7786: =item * B<con_lost>: unable to contact remote host
 7787: 
 7788: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7789: when the connection is brought back up
 7790: 
 7791: =item * B<con_failed>: unable to contact remote host and unable to save message
 7792: for later delivery
 7793: 
 7794: =item * B<error:>: an error a occured, a description of the error follows the :
 7795: 
 7796: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7797: that was requested
 7798: 
 7799: =back
 7800: 
 7801: =head1 PUBLIC SUBROUTINES
 7802: 
 7803: =head2 Session Environment Functions
 7804: 
 7805: =over 4
 7806: 
 7807: =item * 
 7808: X<appenv()>
 7809: B<appenv(%hash)>: the value of %hash is written to
 7810: the user envirnoment file, and will be restored for each access this
 7811: user makes during this session, also modifies the %env for the current
 7812: process
 7813: 
 7814: =item *
 7815: X<delenv()>
 7816: B<delenv($regexp)>: removes all items from the session
 7817: environment file that matches the regular expression in $regexp. The
 7818: values are also delted from the current processes %env.
 7819: 
 7820: =item * get_env_multiple($name) 
 7821: 
 7822: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7823: values may be defined and end up as an array ref.
 7824: 
 7825: returns an array of values
 7826: 
 7827: =back
 7828: 
 7829: =head2 User Information
 7830: 
 7831: =over 4
 7832: 
 7833: =item *
 7834: X<queryauthenticate()>
 7835: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7836: authentication scheme
 7837: 
 7838: =item *
 7839: X<authenticate()>
 7840: B<authenticate($uname,$upass,$udom)>: try to
 7841: authenticate user from domain's lib servers (first use the current
 7842: one). C<$upass> should be the users password.
 7843: 
 7844: =item *
 7845: X<homeserver()>
 7846: B<homeserver($uname,$udom)>: find the server which has
 7847: the user's directory and files (there must be only one), this caches
 7848: the answer, and also caches if there is a borken connection.
 7849: 
 7850: =item *
 7851: X<idget()>
 7852: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7853: (IDs are a unique resource in a domain, there must be only 1 ID per
 7854: username, and only 1 username per ID in a specific domain) (returns
 7855: hash: id=>name,id=>name)
 7856: 
 7857: =item *
 7858: X<idrget()>
 7859: B<idrget($udom,@unames)>: find the IDs behind a list of
 7860: usernames (returns hash: name=>id,name=>id)
 7861: 
 7862: =item *
 7863: X<idput()>
 7864: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7865: 
 7866: =item *
 7867: X<rolesinit()>
 7868: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7869: 
 7870: =item *
 7871: X<getsection()>
 7872: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7873: course $cname, return section name/number or '' for "not in course"
 7874: and '-1' for "no section"
 7875: 
 7876: =item *
 7877: X<userenvironment()>
 7878: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7879: passed in @what from the requested user's environment, returns a hash
 7880: 
 7881: =back
 7882: 
 7883: =head2 User Roles
 7884: 
 7885: =over 4
 7886: 
 7887: =item *
 7888: 
 7889: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 7890:  F: full access
 7891:  U,I,K: authentication modes (cxx only)
 7892:  '': forbidden
 7893:  1: user needs to choose course
 7894:  2: browse allowed
 7895:  A: passphrase authentication needed
 7896: 
 7897: =item *
 7898: 
 7899: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7900: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7901: and course level
 7902: 
 7903: =item *
 7904: 
 7905: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7906: explanation of a user role term
 7907: 
 7908: =back
 7909: 
 7910: =head2 User Modification
 7911: 
 7912: =over 4
 7913: 
 7914: =item *
 7915: 
 7916: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7917: user for the level given by URL.  Optional start and end dates (leave empty
 7918: string or zero for "no date")
 7919: 
 7920: =item *
 7921: 
 7922: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7923: change a users, password, possible return values are: ok,
 7924: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7925: refused
 7926: 
 7927: =item *
 7928: 
 7929: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7930: 
 7931: =item *
 7932: 
 7933: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7934: modify user
 7935: 
 7936: =item *
 7937: 
 7938: modifystudent
 7939: 
 7940: modify a students enrollment and identification information.
 7941: The course id is resolved based on the current users environment.  
 7942: This means the envoking user must be a course coordinator or otherwise
 7943: associated with a course.
 7944: 
 7945: This call is essentially a wrapper for lonnet::modifyuser and
 7946: lonnet::modify_student_enrollment
 7947: 
 7948: Inputs: 
 7949: 
 7950: =over 4
 7951: 
 7952: =item B<$udom> Students loncapa domain
 7953: 
 7954: =item B<$uname> Students loncapa login name
 7955: 
 7956: =item B<$uid> Students id/student number
 7957: 
 7958: =item B<$umode> Students authentication mode
 7959: 
 7960: =item B<$upass> Students password
 7961: 
 7962: =item B<$first> Students first name
 7963: 
 7964: =item B<$middle> Students middle name
 7965: 
 7966: =item B<$last> Students last name
 7967: 
 7968: =item B<$gene> Students generation
 7969: 
 7970: =item B<$usec> Students section in course
 7971: 
 7972: =item B<$end> Unix time of the roles expiration
 7973: 
 7974: =item B<$start> Unix time of the roles start date
 7975: 
 7976: =item B<$forceid> If defined, allow $uid to be changed
 7977: 
 7978: =item B<$desiredhome> server to use as home server for student
 7979: 
 7980: =back
 7981: 
 7982: =item *
 7983: 
 7984: modify_student_enrollment
 7985: 
 7986: Change a students enrollment status in a class.  The environment variable
 7987: 'role.request.course' must be defined for this function to proceed.
 7988: 
 7989: Inputs:
 7990: 
 7991: =over 4
 7992: 
 7993: =item $udom, students domain
 7994: 
 7995: =item $uname, students name
 7996: 
 7997: =item $uid, students user id
 7998: 
 7999: =item $first, students first name
 8000: 
 8001: =item $middle
 8002: 
 8003: =item $last
 8004: 
 8005: =item $gene
 8006: 
 8007: =item $usec
 8008: 
 8009: =item $end
 8010: 
 8011: =item $start
 8012: 
 8013: =back
 8014: 
 8015: 
 8016: =item *
 8017: 
 8018: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8019: custom role; give a custom role to a user for the level given by URL.  Specify
 8020: name and domain of role author, and role name
 8021: 
 8022: =item *
 8023: 
 8024: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8025: 
 8026: =item *
 8027: 
 8028: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8029: 
 8030: =back
 8031: 
 8032: =head2 Course Infomation
 8033: 
 8034: =over 4
 8035: 
 8036: =item *
 8037: 
 8038: coursedescription($courseid) : returns a hash of information about the
 8039: specified course id, including all environment settings for the
 8040: course, the description of the course will be in the hash under the
 8041: key 'description'
 8042: 
 8043: =item *
 8044: 
 8045: resdata($name,$domain,$type,@which) : request for current parameter
 8046: setting for a specific $type, where $type is either 'course' or 'user',
 8047: @what should be a list of parameters to ask about. This routine caches
 8048: answers for 5 minutes.
 8049: 
 8050: =back
 8051: 
 8052: =head2 Course Modification
 8053: 
 8054: =over 4
 8055: 
 8056: =item *
 8057: 
 8058: writecoursepref($courseid,%prefs) : write preferences (environment
 8059: database) for a course
 8060: 
 8061: =item *
 8062: 
 8063: createcourse($udom,$description,$url) : make/modify course
 8064: 
 8065: =back
 8066: 
 8067: =head2 Resource Subroutines
 8068: 
 8069: =over 4
 8070: 
 8071: =item *
 8072: 
 8073: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8074: 
 8075: =item *
 8076: 
 8077: repcopy($filename) : subscribes to the requested file, and attempts to
 8078: replicate from the owning library server, Might return
 8079: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8080: 'bad_request', also attempts to grab the metadata for the
 8081: resource. Expects the local filesystem pathname
 8082: (/home/httpd/html/res/....)
 8083: 
 8084: =back
 8085: 
 8086: =head2 Resource Information
 8087: 
 8088: =over 4
 8089: 
 8090: =item *
 8091: 
 8092: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8093: a vairety of different possible values, $varname should be a request
 8094: string, and the other parameters can be used to specify who and what
 8095: one is asking about.
 8096: 
 8097: Possible values for $varname are environment.lastname (or other item
 8098: from the envirnment hash), user.name (or someother aspect about the
 8099: user), resource.0.maxtries (or some other part and parameter of a
 8100: resource)
 8101: 
 8102: =item *
 8103: 
 8104: directcondval($number) : get current value of a condition; reads from a state
 8105: string
 8106: 
 8107: =item *
 8108: 
 8109: condval($condidx) : value of condition index based on state
 8110: 
 8111: =item *
 8112: 
 8113: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8114: resource's metadata, $what should be either a specific key, or either
 8115: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8116: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8117: 
 8118: this function automatically caches all requests
 8119: 
 8120: =item *
 8121: 
 8122: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8123: network of library servers; returns file handle of where SQL and regex results
 8124: will be stored for query
 8125: 
 8126: =item *
 8127: 
 8128: symbread($filename) : return symbolic list entry (filename argument optional);
 8129: returns the data handle
 8130: 
 8131: =item *
 8132: 
 8133: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8134: a possible symb for the URL in $thisfn, and if is an encryypted
 8135: resource that the user accessed using /enc/ returns a 1 on success, 0
 8136: on failure, user must be in a course, as it assumes the existance of
 8137: the course initial hash, and uses $env('request.course.id'}
 8138: 
 8139: 
 8140: =item *
 8141: 
 8142: symbclean($symb) : removes versions numbers from a symb, returns the
 8143: cleaned symb
 8144: 
 8145: =item *
 8146: 
 8147: is_on_map($uri) : checks if the $uri is somewhere on the current
 8148: course map, user must be in a course for it to work.
 8149: 
 8150: =item *
 8151: 
 8152: numval($salt) : return random seed value (addend for rndseed)
 8153: 
 8154: =item *
 8155: 
 8156: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8157: a random seed, all arguments are optional, if they aren't sent it uses the
 8158: environment to derive them. Note: if symb isn't sent and it can't get one
 8159: from &symbread it will use the current time as its return value
 8160: 
 8161: =item *
 8162: 
 8163: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8164: unfakeable, receipt
 8165: 
 8166: =item *
 8167: 
 8168: receipt() : API to ireceipt working off of env values; given out to users
 8169: 
 8170: =item *
 8171: 
 8172: countacc($url) : count the number of accesses to a given URL
 8173: 
 8174: =item *
 8175: 
 8176: 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
 8177: 
 8178: =item *
 8179: 
 8180: 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)
 8181: 
 8182: =item *
 8183: 
 8184: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8185: 
 8186: =item *
 8187: 
 8188: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8189: forcing spreadsheet to reevaluate the resource scores next time.
 8190: 
 8191: =back
 8192: 
 8193: =head2 Storing/Retreiving Data
 8194: 
 8195: =over 4
 8196: 
 8197: =item *
 8198: 
 8199: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8200: for this url; hashref needs to be given and should be a \%hashname; the
 8201: remaining args aren't required and if they aren't passed or are '' they will
 8202: be derived from the env
 8203: 
 8204: =item *
 8205: 
 8206: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8207: uses critical subroutine
 8208: 
 8209: =item *
 8210: 
 8211: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8212: all args are optional
 8213: 
 8214: =item *
 8215: 
 8216: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8217: dumps the complete (or key matching regexp) namespace into a hash
 8218: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8219: normally &store()ed into
 8220: 
 8221: $range should be either an integer '100' (give me the first 100
 8222:                                            matching records)
 8223:               or be  two integers sperated by a - with no spaces
 8224:                  '30-50' (give me the 30th through the 50th matching
 8225:                           records)
 8226: 
 8227: 
 8228: =item *
 8229: 
 8230: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8231: replaces a &store() version of data with a replacement set of data
 8232: for a particular resource in a namespace passed in the $storehash hash 
 8233: reference
 8234: 
 8235: =item *
 8236: 
 8237: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8238: works very similar to store/cstore, but all data is stored in a
 8239: temporary location and can be reset using tmpreset, $storehash should
 8240: be a hash reference, returns nothing on success
 8241: 
 8242: =item *
 8243: 
 8244: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8245: similar to restore, but all data is stored in a temporary location and
 8246: can be reset using tmpreset. Returns a hash of values on success,
 8247: error string otherwise.
 8248: 
 8249: =item *
 8250: 
 8251: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8252: deltes all keys for $symb form the temporary storage hash.
 8253: 
 8254: =item *
 8255: 
 8256: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8257: reference filled in from namesp ($udom and $uname are optional)
 8258: 
 8259: =item *
 8260: 
 8261: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8262: namesp ($udom and $uname are optional)
 8263: 
 8264: =item *
 8265: 
 8266: dump($namespace,$udom,$uname,$regexp,$range) : 
 8267: dumps the complete (or key matching regexp) namespace into a hash
 8268: ($udom, $uname, $regexp, $range are optional)
 8269: 
 8270: $range should be either an integer '100' (give me the first 100
 8271:                                            matching records)
 8272:               or be  two integers sperated by a - with no spaces
 8273:                  '30-50' (give me the 30th through the 50th matching
 8274:                           records)
 8275: =item *
 8276: 
 8277: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8278: $store can be a scalar, an array reference, or if the amount to be 
 8279: incremented is > 1, a hash reference.
 8280: 
 8281: ($udom and $uname are optional)
 8282: 
 8283: =item *
 8284: 
 8285: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8286: ($udom and $uname are optional)
 8287: 
 8288: =item *
 8289: 
 8290: cput($namespace,$storehash,$udom,$uname) : critical put
 8291: ($udom and $uname are optional)
 8292: 
 8293: =item *
 8294: 
 8295: newput($namespace,$storehash,$udom,$uname) :
 8296: 
 8297: Attempts to store the items in the $storehash, but only if they don't
 8298: currently exist, if this succeeds you can be certain that you have 
 8299: successfully created a new key value pair in the $namespace db.
 8300: 
 8301: 
 8302: Args:
 8303:  $namespace: name of database to store values to
 8304:  $storehash: hashref to store to the db
 8305:  $udom: (optional) domain of user containing the db
 8306:  $uname: (optional) name of user caontaining the db
 8307: 
 8308: Returns:
 8309:  'ok' -> succeeded in storing all keys of $storehash
 8310:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8311:                         least <key> already existed in the db (other
 8312:                         requested keys may also already exist)
 8313:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8314:  'con_lost' -> unable to contact request server
 8315:  'refused' -> action was not allowed by remote machine
 8316: 
 8317: 
 8318: =item *
 8319: 
 8320: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8321: reference filled in from namesp (encrypts the return communication)
 8322: ($udom and $uname are optional)
 8323: 
 8324: =item *
 8325: 
 8326: log($udom,$name,$home,$message) : write to permanent log for user; use
 8327: critical subroutine
 8328: 
 8329: =item *
 8330: 
 8331: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
 8332: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
 8333: 
 8334: =item *
 8335: 
 8336: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
 8337: 
 8338: =back
 8339: 
 8340: =head2 Network Status Functions
 8341: 
 8342: =over 4
 8343: 
 8344: =item *
 8345: 
 8346: dirlist($uri) : return directory list based on URI
 8347: 
 8348: =item *
 8349: 
 8350: spareserver() : find server with least workload from spare.tab
 8351: 
 8352: =back
 8353: 
 8354: =head2 Apache Request
 8355: 
 8356: =over 4
 8357: 
 8358: =item *
 8359: 
 8360: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8361: localhost, posts hash
 8362: 
 8363: =back
 8364: 
 8365: =head2 Data to String to Data
 8366: 
 8367: =over 4
 8368: 
 8369: =item *
 8370: 
 8371: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8372: and '&' separators, supports elements that are arrayrefs and hashrefs
 8373: 
 8374: =item *
 8375: 
 8376: hashref2str($hashref) : convert a hashref into a string complete with
 8377: escaping and '=' and '&' separators, supports elements that are
 8378: arrayrefs and hashrefs
 8379: 
 8380: =item *
 8381: 
 8382: arrayref2str($arrayref) : convert an arrayref into a string complete
 8383: with escaping and '&' separators, supports elements that are arrayrefs
 8384: and hashrefs
 8385: 
 8386: =item *
 8387: 
 8388: str2hash($string) : convert string to hash using unescaping and
 8389: splitting on '=' and '&', supports elements that are arrayrefs and
 8390: hashrefs
 8391: 
 8392: =item *
 8393: 
 8394: str2array($string) : convert string to hash using unescaping and
 8395: splitting on '&', supports elements that are arrayrefs and hashrefs
 8396: 
 8397: =back
 8398: 
 8399: =head2 Logging Routines
 8400: 
 8401: =over 4
 8402: 
 8403: These routines allow one to make log messages in the lonnet.log and
 8404: lonnet.perm logfiles.
 8405: 
 8406: =item *
 8407: 
 8408: logtouch() : make sure the logfile, lonnet.log, exists
 8409: 
 8410: =item *
 8411: 
 8412: logthis() : append message to the normal lonnet.log file, it gets
 8413: preiodically rolled over and deleted.
 8414: 
 8415: =item *
 8416: 
 8417: logperm() : append a permanent message to lonnet.perm.log, this log
 8418: file never gets deleted by any automated portion of the system, only
 8419: messages of critical importance should go in here.
 8420: 
 8421: =back
 8422: 
 8423: =head2 General File Helper Routines
 8424: 
 8425: =over 4
 8426: 
 8427: =item *
 8428: 
 8429: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8430: (a) files in /uploaded
 8431:   (i) If a local copy of the file exists - 
 8432:       compares modification date of local copy with last-modified date for 
 8433:       definitive version stored on home server for course. If local copy is 
 8434:       stale, requests a new version from the home server and stores it. 
 8435:       If the original has been removed from the home server, then local copy 
 8436:       is unlinked.
 8437:   (ii) If local copy does not exist -
 8438:       requests the file from the home server and stores it. 
 8439:   
 8440:   If $caller is 'uploadrep':  
 8441:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8442:     for request for files originally uploaded via DOCS. 
 8443:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8444:   
 8445:   Otherwise:
 8446:      This indicates a call from the content generation phase of the request.
 8447:      -  returns the entire contents of the file or -1.
 8448:      
 8449: (b) files in /res
 8450:    - returns the entire contents of a file or -1; 
 8451:    it properly subscribes to and replicates the file if neccessary.
 8452: 
 8453: 
 8454: =item *
 8455: 
 8456: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8457:                   reference
 8458: 
 8459: returns either a stat() list of data about the file or an empty list
 8460: if the file doesn't exist or couldn't find out about it (connection
 8461: problems or user unknown)
 8462: 
 8463: =item *
 8464: 
 8465: filelocation($dir,$file) : returns file system location of a file
 8466: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8467: directory that relative $file lookups are to looked in ($dir of /a/dir
 8468: and a file of ../bob will become /a/bob)
 8469: 
 8470: =item *
 8471: 
 8472: hreflocation($dir,$file) : returns file system location or a URL; same as
 8473: filelocation except for hrefs
 8474: 
 8475: =item *
 8476: 
 8477: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8478: 
 8479: =back
 8480: 
 8481: =head2 Usererfile file routines (/uploaded*)
 8482: 
 8483: =over 4
 8484: 
 8485: =item *
 8486: 
 8487: userfileupload(): main rotine for putting a file in a user or course's
 8488:                   filespace, arguments are,
 8489: 
 8490:  formname - required - this is the name of the element in $env where the
 8491:            filename, and the contents of the file to create/modifed exist
 8492:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8493:            contents of the file is located in $env{'form.'.$formname}
 8494:  coursedoc - if true, store the file in the course of the active role
 8495:              of the current user
 8496:  subdir - required - subdirectory to put the file in under ../userfiles/
 8497:          if undefined, it will be placed in "unknown"
 8498: 
 8499:  (This routine calls clean_filename() to remove any dangerous
 8500:  characters from the filename, and then calls finuserfileupload() to
 8501:  complete the transaction)
 8502: 
 8503:  returns either the url of the uploaded file (/uploaded/....) if successful
 8504:  and /adm/notfound.html if unsuccessful
 8505: 
 8506: =item *
 8507: 
 8508: clean_filename(): routine for cleaing a filename up for storage in
 8509:                  userfile space, argument is:
 8510: 
 8511:  filename - proposed filename
 8512: 
 8513: returns: the new clean filename
 8514: 
 8515: =item *
 8516: 
 8517: finishuserfileupload(): routine that creaes and sends the file to
 8518: userspace, probably shouldn't be called directly
 8519: 
 8520:   docuname: username or courseid of destination for the file
 8521:   docudom: domain of user/course of destination for the file
 8522:   formname: same as for userfileupload()
 8523:   fname: filename (inculding subdirectories) for the file
 8524: 
 8525:  returns either the url of the uploaded file (/uploaded/....) if successful
 8526:  and /adm/notfound.html if unsuccessful
 8527: 
 8528: =item *
 8529: 
 8530: renameuserfile(): renames an existing userfile to a new name
 8531: 
 8532:   Args:
 8533:    docuname: username or courseid of destination for the file
 8534:    docudom: domain of user/course of destination for the file
 8535:    old: current file name (including any subdirs under userfiles)
 8536:    new: desired file name (including any subdirs under userfiles)
 8537: 
 8538: =item *
 8539: 
 8540: mkdiruserfile(): creates a directory is a userfiles dir
 8541: 
 8542:   Args:
 8543:    docuname: username or courseid of destination for the file
 8544:    docudom: domain of user/course of destination for the file
 8545:    dir: dir to create (including any subdirs under userfiles)
 8546: 
 8547: =item *
 8548: 
 8549: removeuserfile(): removes a file that exists in userfiles
 8550: 
 8551:   Args:
 8552:    docuname: username or courseid of destination for the file
 8553:    docudom: domain of user/course of destination for the file
 8554:    fname: filname to delete (including any subdirs under userfiles)
 8555: 
 8556: =item *
 8557: 
 8558: removeuploadedurl(): convience function for removeuserfile()
 8559: 
 8560:   Args:
 8561:    url:  a full /uploaded/... url to delete
 8562: 
 8563: =item * 
 8564: 
 8565: get_portfile_permissions():
 8566:   Args:
 8567:     domain: domain of user or course contain the portfolio files
 8568:     user: name of user or num of course contain the portfolio files
 8569:   Returns:
 8570:     hashref of a dump of the proper file_permissions.db
 8571:    
 8572: 
 8573: =item * 
 8574: 
 8575: get_access_controls():
 8576: 
 8577: Args:
 8578:   current_permissions: the hash ref returned from get_portfile_permissions()
 8579:   group: (optional) the group you want the files associated with
 8580:   file: (optional) the file you want access info on
 8581: 
 8582: Returns:
 8583:     a hash (keys are file names) of hashes containing
 8584:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8585:         values are XML containing access control settings (see below) 
 8586: 
 8587: Internal notes:
 8588: 
 8589:  access controls are stored in file_permissions.db as key=value pairs.
 8590:     key -> path to file/file_name\0uniqueID:scope_end_start
 8591:         where scope -> public,guest,course,group,domains or users.
 8592:               end -> UNIX time for end of access (0 -> no end date)
 8593:               start -> UNIX time for start of access
 8594: 
 8595:     value -> XML description of access control
 8596:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8597:             <start></start>
 8598:             <end></end>
 8599: 
 8600:             <password></password>  for scope type = guest
 8601: 
 8602:             <domain></domain>     for scope type = course or group
 8603:             <number></number>
 8604:             <roles id="">
 8605:              <role></role>
 8606:              <access></access>
 8607:              <section></section>
 8608:              <group></group>
 8609:             </roles>
 8610: 
 8611:             <dom></dom>         for scope type = domains
 8612: 
 8613:             <users>             for scope type = users
 8614:              <user>
 8615:               <uname></uname>
 8616:               <udom></udom>
 8617:              </user>
 8618:             </users>
 8619:            </scope> 
 8620:               
 8621:  Access data is also aggregated for each file in an additional key=value pair:
 8622:  key -> path to file/file_name\0accesscontrol 
 8623:  value -> reference to hash
 8624:           hash contains key = value pairs
 8625:           where key = uniqueID:scope_end_start
 8626:                 value = UNIX time record was last updated
 8627: 
 8628:           Used to improve speed of look-ups of access controls for each file.  
 8629:  
 8630:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8631: 
 8632: modify_access_controls():
 8633: 
 8634: Modifies access controls for a portfolio file
 8635: Args
 8636: 1. file name
 8637: 2. reference to hash of required changes,
 8638: 3. domain
 8639: 4. username
 8640:   where domain,username are the domain of the portfolio owner 
 8641:   (either a user or a course) 
 8642: 
 8643: Returns:
 8644: 1. result of additions or updates ('ok' or 'error', with error message). 
 8645: 2. result of deletions ('ok' or 'error', with error message).
 8646: 3. reference to hash of any new or updated access controls.
 8647: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8648:    key = integer (inbound ID)
 8649:    value = uniqueID  
 8650: 
 8651: =back
 8652: 
 8653: =head2 HTTP Helper Routines
 8654: 
 8655: =over 4
 8656: 
 8657: =item *
 8658: 
 8659: escape() : unpack non-word characters into CGI-compatible hex codes
 8660: 
 8661: =item *
 8662: 
 8663: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8664: 
 8665: =back
 8666: 
 8667: =head1 PRIVATE SUBROUTINES
 8668: 
 8669: =head2 Underlying communication routines (Shouldn't call)
 8670: 
 8671: =over 4
 8672: 
 8673: =item *
 8674: 
 8675: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8676: 
 8677: =item *
 8678: 
 8679: reply() : uses subreply to send a message to remote machine, logs all failures
 8680: 
 8681: =item *
 8682: 
 8683: critical() : passes a critical message to another server; if cannot
 8684: get through then place message in connection buffer directory and
 8685: returns con_delayed, if incapable of saving message, returns
 8686: con_failed
 8687: 
 8688: =item *
 8689: 
 8690: reconlonc() : tries to reconnect lonc client processes.
 8691: 
 8692: =back
 8693: 
 8694: =head2 Resource Access Logging
 8695: 
 8696: =over 4
 8697: 
 8698: =item *
 8699: 
 8700: flushcourselogs() : flush (save) buffer logs and access logs
 8701: 
 8702: =item *
 8703: 
 8704: courselog($what) : save message for course in hash
 8705: 
 8706: =item *
 8707: 
 8708: courseacclog($what) : save message for course using &courselog().  Perform
 8709: special processing for specific resource types (problems, exams, quizzes, etc).
 8710: 
 8711: =item *
 8712: 
 8713: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8714: as a PerlChildExitHandler
 8715: 
 8716: =back
 8717: 
 8718: =head2 Other
 8719: 
 8720: =over 4
 8721: 
 8722: =item *
 8723: 
 8724: symblist($mapname,%newhash) : update symbolic storage links
 8725: 
 8726: =back
 8727: 
 8728: =cut

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