File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.830: download - view: text, annotated - select for diffs
Thu Jan 25 21:09:24 2007 UTC (17 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- restoring the functionality of waiting for the flock on the session env (while still using the db files for the env)

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

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