File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.872: download - view: text, annotated - select for diffs
Wed May 2 22:00:02 2007 UTC (17 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- &escaping of the id makes it expand so we could cross the magic 250 characters mark after escaping the id, so check the length of the id after escaping it it might exceed things
- also start complainging if caching is failing.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.872 2007/05/02 22:00:02 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::Date;
   35: # use Date::Parse;
   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   37:             $_64bit %env);
   38: 
   39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   42:     %courseownerbuf, %coursetypebuf);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use Fcntl qw(:flock);
   48: use Storable qw(thaw nfreeze);
   49: use Time::HiRes qw( gettimeofday tv_interval );
   50: use Cache::Memcached;
   51: use Digest::MD5;
   52: use Math::Random;
   53: use LONCAPA qw(:DEFAULT :match);
   54: use LONCAPA::Configuration;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: {
   89:     my $logid;
   90:     sub instructor_log {
   91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   92: 	$logid++;
   93: 	my $id=time().'00000'.$$.'00000'.$logid;
   94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   95: 				    { $id => {
   96: 					'exe_uname' => $env{'user.name'},
   97: 					'exe_udom'  => $env{'user.domain'},
   98: 					'exe_time'  => time(),
   99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  100: 					'delflag'   => $delflag,
  101: 					'logentry'  => $storehash,
  102: 					'uname'     => $uname,
  103: 					'udom'      => $udom,
  104: 				    }
  105: 				  },
  106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  108: 				    );
  109:     }
  110: }
  111: 
  112: sub logtouch {
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     unless (-e "$execdir/logs/lonnet.log") {	
  115: 	open(my $fh,">>$execdir/logs/lonnet.log");
  116: 	close $fh;
  117:     }
  118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  120: }
  121: 
  122: sub logthis {
  123:     my $message=shift;
  124:     my $execdir=$perlvar{'lonDaemons'};
  125:     my $now=time;
  126:     my $local=localtime($now);
  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  128: 	print $fh "$local ($$): $message\n";
  129: 	close($fh);
  130:     }
  131:     return 1;
  132: }
  133: 
  134: sub logperm {
  135:     my $message=shift;
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     my $now=time;
  138:     my $local=localtime($now);
  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  140: 	print $fh "$now:$message:$local\n";
  141: 	close($fh);
  142:     }
  143:     return 1;
  144: }
  145: 
  146: sub create_connection {
  147:     my ($hostname,$lonid) = @_;
  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  149: 				     Type    => SOCK_STREAM,
  150: 				     Timeout => 10);
  151:     return 0 if (!$client);
  152:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
  153:     my $result = <$client>;
  154:     chomp($result);
  155:     return 1 if ($result eq 'done');
  156:     return 0;
  157: }
  158: 
  159: 
  160: # -------------------------------------------------- Non-critical communication
  161: sub subreply {
  162:     my ($cmd,$server)=@_;
  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  164:     #
  165:     #  With loncnew process trimming, there's a timing hole between lonc server
  166:     #  process exit and the master server picking up the listen on the AF_UNIX
  167:     #  socket.  In that time interval, a lock file will exist:
  168: 
  169:     my $lockfile=$peerfile.".lock";
  170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  171: 	sleep(1);
  172:     }
  173:     # At this point, either a loncnew parent is listening or an old lonc
  174:     # or loncnew child is listening so we can connect or everything's dead.
  175:     #
  176:     #   We'll give the connection a few tries before abandoning it.  If
  177:     #   connection is not possible, we'll con_lost back to the client.
  178:     #   
  179:     my $client;
  180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  182: 				      Type    => SOCK_STREAM,
  183: 				      Timeout => 10);
  184: 	if ($client) {
  185: 	    last;		# Connected!
  186: 	} else {
  187: 	    &create_connection(&hostname($server),$server);
  188: 	}
  189:         sleep(1);		# Try again later if failed connection.
  190:     }
  191:     my $answer;
  192:     if ($client) {
  193: 	print $client "sethost:$server:$cmd\n";
  194: 	$answer=<$client>;
  195: 	if (!$answer) { $answer="con_lost"; }
  196: 	chomp($answer);
  197:     } else {
  198: 	$answer = 'con_lost';	# Failed connection.
  199:     }
  200:     return $answer;
  201: }
  202: 
  203: sub reply {
  204:     my ($cmd,$server)=@_;
  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  206:     my $answer=subreply($cmd,$server);
  207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  208:        &logthis("<font color=\"blue\">WARNING:".
  209:                 " $cmd to $server returned $answer</font>");
  210:     }
  211:     return $answer;
  212: }
  213: 
  214: # ----------------------------------------------------------- Send USR1 to lonc
  215: 
  216: sub reconlonc {
  217:     &logthis("Trying to reconnect lonc");
  218:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  219:     if (open(my $fh,"<$loncfile")) {
  220: 	my $loncpid=<$fh>;
  221:         chomp($loncpid);
  222:         if (kill 0 => $loncpid) {
  223: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  224:             kill USR1 => $loncpid;
  225:             sleep 1;
  226:          } else {
  227: 	    &logthis(
  228:                "<font color=\"blue\">WARNING:".
  229:                " lonc at pid $loncpid not responding, giving up</font>");
  230:         }
  231:     } else {
  232: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  233:     }
  234: }
  235: 
  236: # ------------------------------------------------------ Critical communication
  237: 
  238: sub critical {
  239:     my ($cmd,$server)=@_;
  240:     unless (&hostname($server)) {
  241:         &logthis("<font color=\"blue\">WARNING:".
  242:                " Critical message to unknown server ($server)</font>");
  243:         return 'no_such_host';
  244:     }
  245:     my $answer=reply($cmd,$server);
  246:     if ($answer eq 'con_lost') {
  247: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  248: 	my $answer=reply($cmd,$server);
  249:         if ($answer eq 'con_lost') {
  250:             my $now=time;
  251:             my $middlename=$cmd;
  252:             $middlename=substr($middlename,0,16);
  253:             $middlename=~s/\W//g;
  254:             my $dfilename=
  255:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  256:             $dumpcount++;
  257:             {
  258: 		my $dfh;
  259: 		if (open($dfh,">$dfilename")) {
  260: 		    print $dfh "$cmd\n"; 
  261: 		    close($dfh);
  262: 		}
  263:             }
  264:             sleep 2;
  265:             my $wcmd='';
  266:             {
  267: 		my $dfh;
  268: 		if (open($dfh,"<$dfilename")) {
  269: 		    $wcmd=<$dfh>; 
  270: 		    close($dfh);
  271: 		}
  272:             }
  273:             chomp($wcmd);
  274:             if ($wcmd eq $cmd) {
  275: 		&logthis("<font color=\"blue\">WARNING: ".
  276:                          "Connection buffer $dfilename: $cmd</font>");
  277:                 &logperm("D:$server:$cmd");
  278: 	        return 'con_delayed';
  279:             } else {
  280:                 &logthis("<font color=\"red\">CRITICAL:"
  281:                         ." Critical connection failed: $server $cmd</font>");
  282:                 &logperm("F:$server:$cmd");
  283:                 return 'con_failed';
  284:             }
  285:         }
  286:     }
  287:     return $answer;
  288: }
  289: 
  290: # ------------------------------------------- check if return value is an error
  291: 
  292: sub error {
  293:     my ($result) = @_;
  294:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  295: 	if ($2 == 2) { return undef; }
  296: 	return $1;
  297:     }
  298:     return undef;
  299: }
  300: 
  301: sub convert_and_load_session_env {
  302:     my ($lonidsdir,$handle)=@_;
  303:     my @profile;
  304:     {
  305: 	open(my $idf,"$lonidsdir/$handle.id");
  306: 	flock($idf,LOCK_SH);
  307: 	@profile=<$idf>;
  308: 	close($idf);
  309:     }
  310:     my %temp_env;
  311:     foreach my $line (@profile) {
  312: 	if ($line !~ m/=/) {
  313: 	    return 0;
  314: 	}
  315: 	chomp($line);
  316: 	my ($envname,$envvalue)=split(/=/,$line,2);
  317: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  318:     }
  319:     unlink("$lonidsdir/$handle.id");
  320:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  321: 	    0640)) {
  322: 	%disk_env = %temp_env;
  323: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  324: 	untie(%disk_env);
  325:     }
  326:     return 1;
  327: }
  328: 
  329: # ------------------------------------------- Transfer profile into environment
  330: my $env_loaded;
  331: sub transfer_profile_to_env {
  332:     my ($lonidsdir,$handle,$force_transfer) = @_;
  333:     if (!$force_transfer && $env_loaded) { return; } 
  334: 
  335:     if (!defined($lonidsdir)) {
  336: 	$lonidsdir = $perlvar{'lonIDsDir'};
  337:     }
  338:     if (!defined($handle)) {
  339:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  340:     }
  341: 
  342:     my $convert;
  343:     {
  344:     	open(my $idf,"$lonidsdir/$handle.id");
  345: 	flock($idf,LOCK_SH);
  346: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  347: 		&GDBM_READER(),0640)) {
  348: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  349: 	    untie(%disk_env);
  350: 	} else {
  351: 	    $convert = 1;
  352: 	}
  353:     }
  354:     if ($convert) {
  355: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  356: 	    &logthis("Failed to load session, or convert session.");
  357: 	}
  358:     }
  359: 
  360:     my %remove;
  361:     while ( my $envname = each(%env) ) {
  362:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  363:             if ($time < time-300) {
  364:                 $remove{$key}++;
  365:             }
  366:         }
  367:     }
  368: 
  369:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  370:     $env_loaded=1;
  371:     foreach my $expired_key (keys(%remove)) {
  372:         &delenv($expired_key);
  373:     }
  374: }
  375: 
  376: sub timed_flock {
  377:     my ($file,$lock_type) = @_;
  378:     my $failed=0;
  379:     eval {
  380: 	local $SIG{__DIE__}='DEFAULT';
  381: 	local $SIG{ALRM}=sub {
  382: 	    $failed=1;
  383: 	    die("failed lock");
  384: 	};
  385: 	alarm(13);
  386: 	flock($file,$lock_type);
  387: 	alarm(0);
  388:     };
  389:     if ($failed) {
  390: 	return undef;
  391:     } else {
  392: 	return 1;
  393:     }
  394: }
  395: 
  396: # ---------------------------------------------------------- Append Environment
  397: 
  398: sub appenv {
  399:     my %newenv=@_;
  400:     foreach my $key (keys(%newenv)) {
  401: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  402:             &logthis("<font color=\"blue\">WARNING: ".
  403:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  404:                 .'</font>');
  405: 	    delete($newenv{$key});
  406:         } else {
  407:             $env{$key}=$newenv{$key};
  408:         }
  409:     }
  410:     open(my $env_file,$env{'user.environment'});
  411:     if (&timed_flock($env_file,LOCK_EX)
  412: 	&&
  413: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  414: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  415: 	while (my ($key,$value) = each(%newenv)) {
  416: 	    $disk_env{$key} = $value;
  417: 	}
  418: 	untie(%disk_env);
  419:     }
  420:     return 'ok';
  421: }
  422: # ----------------------------------------------------- Delete from Environment
  423: 
  424: sub delenv {
  425:     my $delthis=shift;
  426:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  427:         &logthis("<font color=\"blue\">WARNING: ".
  428:                 "Attempt to delete from environment ".$delthis);
  429:         return 'error';
  430:     }
  431:     open(my $env_file,$env{'user.environment'});
  432:     if (&timed_flock($env_file,LOCK_EX)
  433: 	&&
  434: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  435: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  436: 	foreach my $key (keys(%disk_env)) {
  437: 	    if ($key=~/^$delthis/) { 
  438:                 delete($env{$key});
  439:                 delete($disk_env{$key});
  440:             }
  441: 	}
  442: 	untie(%disk_env);
  443:     }
  444:     return 'ok';
  445: }
  446: 
  447: sub get_env_multiple {
  448:     my ($name) = @_;
  449:     my @values;
  450:     if (defined($env{$name})) {
  451:         # exists is it an array
  452:         if (ref($env{$name})) {
  453:             @values=@{ $env{$name} };
  454:         } else {
  455:             $values[0]=$env{$name};
  456:         }
  457:     }
  458:     return(@values);
  459: }
  460: 
  461: # ------------------------------------------ Find out current server userload
  462: # there is a copy in lond
  463: sub userload {
  464:     my $numusers=0;
  465:     {
  466: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  467: 	my $filename;
  468: 	my $curtime=time;
  469: 	while ($filename=readdir(LONIDS)) {
  470: 	    if ($filename eq '.' || $filename eq '..') {next;}
  471: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  472: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  473: 	}
  474: 	closedir(LONIDS);
  475:     }
  476:     my $userloadpercent=0;
  477:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  478:     if ($maxuserload) {
  479: 	$userloadpercent=100*$numusers/$maxuserload;
  480:     }
  481:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  482:     return $userloadpercent;
  483: }
  484: 
  485: # ------------------------------------------ Fight off request when overloaded
  486: 
  487: sub overloaderror {
  488:     my ($r,$checkserver)=@_;
  489:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  490:     my $loadavg;
  491:     if ($checkserver eq $perlvar{'lonHostID'}) {
  492:        open(my $loadfile,'/proc/loadavg');
  493:        $loadavg=<$loadfile>;
  494:        $loadavg =~ s/\s.*//g;
  495:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  496:        close($loadfile);
  497:     } else {
  498:        $loadavg=&reply('load',$checkserver);
  499:     }
  500:     my $overload=$loadavg-100;
  501:     if ($overload>0) {
  502: 	$r->err_headers_out->{'Retry-After'}=$overload;
  503:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  504:         return 413;
  505:     }    
  506:     return '';
  507: }
  508: 
  509: # ------------------------------ Find server with least workload from spare.tab
  510: 
  511: sub spareserver {
  512:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  513:     my $spare_server;
  514:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  515:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  516:                                                      :  $userloadpercent;
  517:     
  518:     foreach my $try_server (@{ $spareid{'primary'} }) {
  519: 	($spare_server, $lowest_load) =
  520: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  521:     }
  522: 
  523:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  524: 
  525:     if (!$found_server) {
  526: 	foreach my $try_server (@{ $spareid{'default'} }) {
  527: 	    ($spare_server, $lowest_load) =
  528: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  529: 	}
  530:     }
  531: 
  532:     if (!$want_server_name) {
  533: 	$spare_server="http://".&hostname($spare_server);
  534:     }
  535:     return $spare_server;
  536: }
  537: 
  538: sub compare_server_load {
  539:     my ($try_server, $spare_server, $lowest_load) = @_;
  540: 
  541:     my $loadans     = &reply('load',    $try_server);
  542:     my $userloadans = &reply('userload',$try_server);
  543: 
  544:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  545: 	next; #didn't get a number from the server
  546:     }
  547: 
  548:     my $load;
  549:     if ($loadans =~ /\d/) {
  550: 	if ($userloadans =~ /\d/) {
  551: 	    #both are numbers, pick the bigger one
  552: 	    $load = ($loadans > $userloadans) ? $loadans 
  553: 		                              : $userloadans;
  554: 	} else {
  555: 	    $load = $loadans;
  556: 	}
  557:     } else {
  558: 	$load = $userloadans;
  559:     }
  560: 
  561:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  562: 	$spare_server = $try_server;
  563: 	$lowest_load  = $load;
  564:     }
  565:     return ($spare_server,$lowest_load);
  566: }
  567: # --------------------------------------------- Try to change a user's password
  568: 
  569: sub changepass {
  570:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  571:     $currentpass = &escape($currentpass);
  572:     $newpass     = &escape($newpass);
  573:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  574: 		       $server);
  575:     if (! $answer) {
  576: 	&logthis("No reply on password change request to $server ".
  577: 		 "by $uname in domain $udom.");
  578:     } elsif ($answer =~ "^ok") {
  579:         &logthis("$uname in $udom successfully changed their password ".
  580: 		 "on $server.");
  581:     } elsif ($answer =~ "^pwchange_failure") {
  582: 	&logthis("$uname in $udom was unable to change their password ".
  583: 		 "on $server.  The action was blocked by either lcpasswd ".
  584: 		 "or pwchange");
  585:     } elsif ($answer =~ "^non_authorized") {
  586:         &logthis("$uname in $udom did not get their password correct when ".
  587: 		 "attempting to change it on $server.");
  588:     } elsif ($answer =~ "^auth_mode_error") {
  589:         &logthis("$uname in $udom attempted to change their password despite ".
  590: 		 "not being locally or internally authenticated on $server.");
  591:     } elsif ($answer =~ "^unknown_user") {
  592:         &logthis("$uname in $udom attempted to change their password ".
  593: 		 "on $server but were unable to because $server is not ".
  594: 		 "their home server.");
  595:     } elsif ($answer =~ "^refused") {
  596: 	&logthis("$server refused to change $uname in $udom password because ".
  597: 		 "it was sent an unencrypted request to change the password.");
  598:     }
  599:     return $answer;
  600: }
  601: 
  602: # ----------------------- Try to determine user's current authentication scheme
  603: 
  604: sub queryauthenticate {
  605:     my ($uname,$udom)=@_;
  606:     my $uhome=&homeserver($uname,$udom);
  607:     if (!$uhome) {
  608: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  609: 	return 'no_host';
  610:     }
  611:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  612:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  613: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  614:     }
  615:     return $answer;
  616: }
  617: 
  618: # --------- Try to authenticate user from domain's lib servers (first this one)
  619: 
  620: sub authenticate {
  621:     my ($uname,$upass,$udom)=@_;
  622:     $upass=&escape($upass);
  623:     $uname= &LONCAPA::clean_username($uname);
  624:     my $uhome=&homeserver($uname,$udom,1);
  625:     if ((!$uhome) || ($uhome eq 'no_host')) {
  626: # Maybe the machine was offline and only re-appeared again recently?
  627:         &reconlonc();
  628: # One more
  629: 	my $uhome=&homeserver($uname,$udom,1);
  630: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  631: 	    &logthis("User $uname at $udom is unknown in authenticate");
  632: 	}
  633: 	return 'no_host';
  634:     }
  635:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  636:     if ($answer eq 'authorized') {
  637: 	&logthis("User $uname at $udom authorized by $uhome"); 
  638: 	return $uhome; 
  639:     }
  640:     if ($answer eq 'non_authorized') {
  641: 	&logthis("User $uname at $udom rejected by $uhome");
  642: 	return 'no_host'; 
  643:     }
  644:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  645:     return 'no_host';
  646: }
  647: 
  648: # ---------------------- Find the homebase for a user from domain's lib servers
  649: 
  650: my %homecache;
  651: sub homeserver {
  652:     my ($uname,$udom,$ignoreBadCache)=@_;
  653:     my $index="$uname:$udom";
  654: 
  655:     if (exists($homecache{$index})) { return $homecache{$index}; }
  656: 
  657:     my %servers = &get_servers($udom,'library');
  658:     foreach my $tryserver (keys(%servers)) {
  659:         next if ($ignoreBadCache ne 'true' && 
  660: 		 exists($badServerCache{$tryserver}));
  661: 
  662: 	my $answer=reply("home:$udom:$uname",$tryserver);
  663: 	if ($answer eq 'found') {
  664: 	    delete($badServerCache{$tryserver}); 
  665: 	    return $homecache{$index}=$tryserver;
  666: 	} elsif ($answer eq 'no_host') {
  667: 	    $badServerCache{$tryserver}=1;
  668: 	}
  669:     }    
  670:     return 'no_host';
  671: }
  672: 
  673: # ------------------------------------- Find the usernames behind a list of IDs
  674: 
  675: sub idget {
  676:     my ($udom,@ids)=@_;
  677:     my %returnhash=();
  678:     
  679:     my %servers = &get_servers($udom,'library');
  680:     foreach my $tryserver (keys(%servers)) {
  681: 	my $idlist=join('&',@ids);
  682: 	$idlist=~tr/A-Z/a-z/; 
  683: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  684: 	my @answer=();
  685: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  686: 	    @answer=split(/\&/,$reply);
  687: 	}                    ;
  688: 	my $i;
  689: 	for ($i=0;$i<=$#ids;$i++) {
  690: 	    if ($answer[$i]) {
  691: 		$returnhash{$ids[$i]}=$answer[$i];
  692: 	    } 
  693: 	}
  694:     } 
  695:     return %returnhash;
  696: }
  697: 
  698: # ------------------------------------- Find the IDs behind a list of usernames
  699: 
  700: sub idrget {
  701:     my ($udom,@unames)=@_;
  702:     my %returnhash=();
  703:     foreach my $uname (@unames) {
  704:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  705:     }
  706:     return %returnhash;
  707: }
  708: 
  709: # ------------------------------- Store away a list of names and associated IDs
  710: 
  711: sub idput {
  712:     my ($udom,%ids)=@_;
  713:     my %servers=();
  714:     foreach my $uname (keys(%ids)) {
  715: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  716:         my $uhom=&homeserver($uname,$udom);
  717:         if ($uhom ne 'no_host') {
  718:             my $id=&escape($ids{$uname});
  719:             $id=~tr/A-Z/a-z/;
  720:             my $esc_unam=&escape($uname);
  721: 	    if ($servers{$uhom}) {
  722: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  723:             } else {
  724:                 $servers{$uhom}=$id.'='.$esc_unam;
  725:             }
  726:         }
  727:     }
  728:     foreach my $server (keys(%servers)) {
  729:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  730:     }
  731: }
  732: 
  733: # ------------------------------------------- get items from domain db files   
  734: 
  735: sub get_dom {
  736:     my ($namespace,$storearr,$udom,$uhome)=@_;
  737:     my $items='';
  738:     foreach my $item (@$storearr) {
  739:         $items.=&escape($item).'&';
  740:     }
  741:     $items=~s/\&$//;
  742:     if (!$udom) {
  743:         $udom=$env{'user.domain'};
  744:         if (defined(&domain($udom,'primary'))) {
  745:             $uhome=&domain($udom,'primary');
  746:         } else {
  747:             $uhome eq '';
  748:         }
  749:     } else {
  750:         if (!$uhome) {
  751:             if (defined(&domain($udom,'primary'))) {
  752:                 $uhome=&domain($udom,'primary');
  753:             }
  754:         }
  755:     }
  756:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  757:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  758:         my %returnhash;
  759:         if ($rep =~ /^error: 2 /) {
  760:             return %returnhash;
  761:         }
  762:         my @pairs=split(/\&/,$rep);
  763:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  764:             return @pairs;
  765:         }
  766:         my %returnhash=();
  767:         my $i=0;
  768:         foreach my $item (@$storearr) {
  769:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  770:             $i++;
  771:         }
  772:         return %returnhash;
  773:     } else {
  774:         &logthis("get_dom failed - no homeserver and/or domain");
  775:     }
  776: }
  777: 
  778: # -------------------------------------------- put items in domain db files 
  779: 
  780: sub put_dom {
  781:     my ($namespace,$storehash,$udom,$uhome)=@_;
  782:     if (!$udom) {
  783:         $udom=$env{'user.domain'};
  784:         if (defined(&domain($udom,'primary'))) {
  785:             $uhome=&domain($udom,'primary');
  786:         } else {
  787:             $uhome eq '';
  788:         }
  789:     } else {
  790:         if (!$uhome) {
  791:             if (defined(&domain($udom,'primary'))) {
  792:                 $uhome=&domain($udom,'primary');
  793:             }
  794:         }
  795:     } 
  796:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  797:         my $items='';
  798:         foreach my $item (keys(%$storehash)) {
  799:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  800:         }
  801:         $items=~s/\&$//;
  802:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  803:     } else {
  804:         &logthis("put_dom failed - no homeserver and/or domain");
  805:     }
  806: }
  807: 
  808: sub retrieve_inst_usertypes {
  809:     my ($udom) = @_;
  810:     my (%returnhash,@order);
  811:     if (defined(&domain($udom,'primary'))) {
  812:         my $uhome=&domain($udom,'primary');
  813:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  814:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  815:         my @pairs=split(/\&/,$hashitems);
  816:         foreach my $item (@pairs) {
  817:             my ($key,$value)=split(/=/,$item,2);
  818:             $key = &unescape($key);
  819:             next if ($key =~ /^error: 2 /);
  820:             $returnhash{$key}=&thaw_unescape($value);
  821:         }
  822:         my @esc_order = split(/\&/,$orderitems);
  823:         foreach my $item (@esc_order) {
  824:             push(@order,&unescape($item));
  825:         }
  826:     } else {
  827:         &logthis("get_dom failed - no primary domain server for $udom");
  828:     }
  829:     return (\%returnhash,\@order);
  830: }
  831: 
  832: sub is_domainimage {
  833:     my ($url) = @_;
  834:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  835:         if (&domain($1) ne '') {
  836:             return '1';
  837:         }
  838:     }
  839:     return;
  840: }
  841: 
  842: # --------------------------------------------------- Assign a key to a student
  843: 
  844: sub assign_access_key {
  845: #
  846: # a valid key looks like uname:udom#comments
  847: # comments are being appended
  848: #
  849:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  850:     $kdom=
  851:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  852:     $knum=
  853:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  854:     $cdom=
  855:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  856:     $cnum=
  857:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  858:     $udom=$env{'user.name'} unless (defined($udom));
  859:     $uname=$env{'user.domain'} unless (defined($uname));
  860:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  861:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  862:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  863:                                                   # assigned to this person
  864:                                                   # - this should not happen,
  865:                                                   # unless something went wrong
  866:                                                   # the first time around
  867: # ready to assign
  868:         $logentry=$1.'; '.$logentry;
  869:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  870:                                                  $kdom,$knum) eq 'ok') {
  871: # key now belongs to user
  872: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  873:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  874:                 &appenv('environment.'.$envkey => $ckey);
  875:                 return 'ok';
  876:             } else {
  877:                 return 
  878:   'error: Count not permanently assign key, will need to be re-entered later.';
  879: 	    }
  880:         } else {
  881:             return 'error: Could not assign key, try again later.';
  882:         }
  883:     } elsif (!$existing{$ckey}) {
  884: # the key does not exist
  885: 	return 'error: The key does not exist';
  886:     } else {
  887: # the key is somebody else's
  888: 	return 'error: The key is already in use';
  889:     }
  890: }
  891: 
  892: # ------------------------------------------ put an additional comment on a key
  893: 
  894: sub comment_access_key {
  895: #
  896: # a valid key looks like uname:udom#comments
  897: # comments are being appended
  898: #
  899:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  900:     $cdom=
  901:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  902:     $cnum=
  903:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  904:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  905:     if ($existing{$ckey}) {
  906:         $existing{$ckey}.='; '.$logentry;
  907: # ready to assign
  908:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  909:                                                  $cdom,$cnum) eq 'ok') {
  910: 	    return 'ok';
  911:         } else {
  912: 	    return 'error: Count not store comment.';
  913:         }
  914:     } else {
  915: # the key does not exist
  916: 	return 'error: The key does not exist';
  917:     }
  918: }
  919: 
  920: # ------------------------------------------------------ Generate a set of keys
  921: 
  922: sub generate_access_keys {
  923:     my ($number,$cdom,$cnum,$logentry)=@_;
  924:     $cdom=
  925:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  926:     $cnum=
  927:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  928:     unless (&allowed('mky',$cdom)) { return 0; }
  929:     unless (($cdom) && ($cnum)) { return 0; }
  930:     if ($number>10000) { return 0; }
  931:     sleep(2); # make sure don't get same seed twice
  932:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  933:     my $total=0;
  934:     for (my $i=1;$i<=$number;$i++) {
  935:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  936:                   sprintf("%lx",int(100000*rand)).'-'.
  937:                   sprintf("%lx",int(100000*rand));
  938:        $newkey=~s/1/g/g; # folks mix up 1 and l
  939:        $newkey=~s/0/h/g; # and also 0 and O
  940:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  941:        if ($existing{$newkey}) {
  942:            $i--;
  943:        } else {
  944: 	  if (&put('accesskeys',
  945:               { $newkey => '# generated '.localtime().
  946:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  947:                            '; '.$logentry },
  948: 		   $cdom,$cnum) eq 'ok') {
  949:               $total++;
  950: 	  }
  951:        }
  952:     }
  953:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  954:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  955:     return $total;
  956: }
  957: 
  958: # ------------------------------------------------------- Validate an accesskey
  959: 
  960: sub validate_access_key {
  961:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  962:     $cdom=
  963:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  964:     $cnum=
  965:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  966:     $udom=$env{'user.domain'} unless (defined($udom));
  967:     $uname=$env{'user.name'} unless (defined($uname));
  968:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  969:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  970: }
  971: 
  972: # ------------------------------------- Find the section of student in a course
  973: sub devalidate_getsection_cache {
  974:     my ($udom,$unam,$courseid)=@_;
  975:     my $hashid="$udom:$unam:$courseid";
  976:     &devalidate_cache_new('getsection',$hashid);
  977: }
  978: 
  979: sub courseid_to_courseurl {
  980:     my ($courseid) = @_;
  981:     #already url style courseid
  982:     return $courseid if ($courseid =~ m{^/});
  983: 
  984:     if (exists($env{'course.'.$courseid.'.num'})) {
  985: 	my $cnum = $env{'course.'.$courseid.'.num'};
  986: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  987: 	return "/$cdom/$cnum";
  988:     }
  989: 
  990:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  991:     if (exists($courseinfo{'num'})) {
  992: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  993:     }
  994: 
  995:     return undef;
  996: }
  997: 
  998: sub getsection {
  999:     my ($udom,$unam,$courseid)=@_;
 1000:     my $cachetime=1800;
 1001: 
 1002:     my $hashid="$udom:$unam:$courseid";
 1003:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1004:     if (defined($cached)) { return $result; }
 1005: 
 1006:     my %Pending; 
 1007:     my %Expired;
 1008:     #
 1009:     # Each role can either have not started yet (pending), be active, 
 1010:     #    or have expired.
 1011:     #
 1012:     # If there is an active role, we are done.
 1013:     #
 1014:     # If there is more than one role which has not started yet, 
 1015:     #     choose the one which will start sooner
 1016:     # If there is one role which has not started yet, return it.
 1017:     #
 1018:     # If there is more than one expired role, choose the one which ended last.
 1019:     # If there is a role which has expired, return it.
 1020:     #
 1021:     $courseid = &courseid_to_courseurl($courseid);
 1022:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1023:     foreach my $key (keys(%roleshash)) {
 1024:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1025:         my $section=$1;
 1026:         if ($key eq $courseid.'_st') { $section=''; }
 1027:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1028:         my $now=time;
 1029:         if (defined($end) && $end && ($now > $end)) {
 1030:             $Expired{$end}=$section;
 1031:             next;
 1032:         }
 1033:         if (defined($start) && $start && ($now < $start)) {
 1034:             $Pending{$start}=$section;
 1035:             next;
 1036:         }
 1037:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1038:     }
 1039:     #
 1040:     # Presumedly there will be few matching roles from the above
 1041:     # loop and the sorting time will be negligible.
 1042:     if (scalar(keys(%Pending))) {
 1043:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1044:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1045:     } 
 1046:     if (scalar(keys(%Expired))) {
 1047:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1048:         my $time = pop(@sorted);
 1049:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1050:     }
 1051:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1052: }
 1053: 
 1054: sub save_cache {
 1055:     &purge_remembered();
 1056:     #&Apache::loncommon::validate_page();
 1057:     undef(%env);
 1058:     undef($env_loaded);
 1059: }
 1060: 
 1061: my $to_remember=-1;
 1062: my %remembered;
 1063: my %accessed;
 1064: my $kicks=0;
 1065: my $hits=0;
 1066: sub make_key {
 1067:     my ($name,$id) = @_;
 1068:     if (length($id) > 65 
 1069: 	&& length(&escape($id)) > 200) {
 1070: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1071:     }
 1072:     return &escape($name.':'.$id);
 1073: }
 1074: 
 1075: sub devalidate_cache_new {
 1076:     my ($name,$id,$debug) = @_;
 1077:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1078:     $id=&make_key($name,$id);
 1079:     $memcache->delete($id);
 1080:     delete($remembered{$id});
 1081:     delete($accessed{$id});
 1082: }
 1083: 
 1084: sub is_cached_new {
 1085:     my ($name,$id,$debug) = @_;
 1086:     $id=&make_key($name,$id);
 1087:     if (exists($remembered{$id})) {
 1088: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1089: 	$accessed{$id}=[&gettimeofday()];
 1090: 	$hits++;
 1091: 	return ($remembered{$id},1);
 1092:     }
 1093:     my $value = $memcache->get($id);
 1094:     if (!(defined($value))) {
 1095: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1096: 	return (undef,undef);
 1097:     }
 1098:     if ($value eq '__undef__') {
 1099: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1100: 	$value=undef;
 1101:     }
 1102:     &make_room($id,$value,$debug);
 1103:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1104:     return ($value,1);
 1105: }
 1106: 
 1107: sub do_cache_new {
 1108:     my ($name,$id,$value,$time,$debug) = @_;
 1109:     $id=&make_key($name,$id);
 1110:     my $setvalue=$value;
 1111:     if (!defined($setvalue)) {
 1112: 	$setvalue='__undef__';
 1113:     }
 1114:     if (!defined($time) ) {
 1115: 	$time=600;
 1116:     }
 1117:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1118:     if (!($memcache->set($id,$setvalue,$time))) {
 1119: 	&logthis("caching of id -> $id  failed");
 1120:     }
 1121:     # need to make a copy of $value
 1122:     #&make_room($id,$value,$debug);
 1123:     return $value;
 1124: }
 1125: 
 1126: sub make_room {
 1127:     my ($id,$value,$debug)=@_;
 1128:     $remembered{$id}=$value;
 1129:     if ($to_remember<0) { return; }
 1130:     $accessed{$id}=[&gettimeofday()];
 1131:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1132:     my $to_kick;
 1133:     my $max_time=0;
 1134:     foreach my $other (keys(%accessed)) {
 1135: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1136: 	    $to_kick=$other;
 1137: 	    $max_time=&tv_interval($accessed{$other});
 1138: 	}
 1139:     }
 1140:     delete($remembered{$to_kick});
 1141:     delete($accessed{$to_kick});
 1142:     $kicks++;
 1143:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1144:     return;
 1145: }
 1146: 
 1147: sub purge_remembered {
 1148:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1149:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1150:     undef(%remembered);
 1151:     undef(%accessed);
 1152: }
 1153: # ------------------------------------- Read an entry from a user's environment
 1154: 
 1155: sub userenvironment {
 1156:     my ($udom,$unam,@what)=@_;
 1157:     my %returnhash=();
 1158:     my @answer=split(/\&/,
 1159:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1160:                       &homeserver($unam,$udom)));
 1161:     my $i;
 1162:     for ($i=0;$i<=$#what;$i++) {
 1163: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1164:     }
 1165:     return %returnhash;
 1166: }
 1167: 
 1168: # ---------------------------------------------------------- Get a studentphoto
 1169: sub studentphoto {
 1170:     my ($udom,$unam,$ext) = @_;
 1171:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1172:     if (defined($env{'request.course.id'})) {
 1173:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1174:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1175:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1176:             } else {
 1177:                 my ($result,$perm_reqd)=
 1178: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1179:                 if ($result eq 'ok') {
 1180:                     if (!($perm_reqd eq 'yes')) {
 1181:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1182:                     }
 1183:                 }
 1184:             }
 1185:         }
 1186:     } else {
 1187:         my ($result,$perm_reqd) = 
 1188: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1189:         if ($result eq 'ok') {
 1190:             if (!($perm_reqd eq 'yes')) {
 1191:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1192:             }
 1193:         }
 1194:     }
 1195:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1196: }
 1197: 
 1198: sub retrievestudentphoto {
 1199:     my ($udom,$unam,$ext,$type) = @_;
 1200:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1201:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1202:     if ($ret eq 'ok') {
 1203:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1204:         if ($type eq 'thumbnail') {
 1205:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1206:         }
 1207:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1208:         return $tokenurl;
 1209:     } else {
 1210:         if ($type eq 'thumbnail') {
 1211:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1212:         } else { 
 1213:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1214:         }
 1215:     }
 1216: }
 1217: 
 1218: # -------------------------------------------------------------------- New chat
 1219: 
 1220: sub chatsend {
 1221:     my ($newentry,$anon,$group)=@_;
 1222:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1223:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1224:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1225:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1226: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1227: 		   &escape($newentry)).':'.$group,$chome);
 1228: }
 1229: 
 1230: # ------------------------------------------ Find current version of a resource
 1231: 
 1232: sub getversion {
 1233:     my $fname=&clutter(shift);
 1234:     unless ($fname=~/^\/res\//) { return -1; }
 1235:     return &currentversion(&filelocation('',$fname));
 1236: }
 1237: 
 1238: sub currentversion {
 1239:     my $fname=shift;
 1240:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1241:     if (defined($cached)) { return $result; }
 1242:     my $author=$fname;
 1243:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1244:     my ($udom,$uname)=split(/\//,$author);
 1245:     my $home=homeserver($uname,$udom);
 1246:     if ($home eq 'no_host') { 
 1247:         return -1; 
 1248:     }
 1249:     my $answer=reply("currentversion:$fname",$home);
 1250:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1251: 	return -1;
 1252:     }
 1253:     return &do_cache_new('resversion',$fname,$answer,600);
 1254: }
 1255: 
 1256: # ----------------------------- Subscribe to a resource, return URL if possible
 1257: 
 1258: sub subscribe {
 1259:     my $fname=shift;
 1260:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1261:     $fname=~s/[\n\r]//g;
 1262:     my $author=$fname;
 1263:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1264:     my ($udom,$uname)=split(/\//,$author);
 1265:     my $home=homeserver($uname,$udom);
 1266:     if ($home eq 'no_host') {
 1267:         return 'not_found';
 1268:     }
 1269:     my $answer=reply("sub:$fname",$home);
 1270:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1271: 	$answer.=' by '.$home;
 1272:     }
 1273:     return $answer;
 1274: }
 1275:     
 1276: # -------------------------------------------------------------- Replicate file
 1277: 
 1278: sub repcopy {
 1279:     my $filename=shift;
 1280:     $filename=~s/\/+/\//g;
 1281:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1282:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1283:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1284: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1285: 	return &repcopy_userfile($filename);
 1286:     }
 1287:     $filename=~s/[\n\r]//g;
 1288:     my $transname="$filename.in.transfer";
 1289: # FIXME: this should flock
 1290:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1291:     my $remoteurl=subscribe($filename);
 1292:     if ($remoteurl =~ /^con_lost by/) {
 1293: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1294:            return 'unavailable';
 1295:     } elsif ($remoteurl eq 'not_found') {
 1296: 	   #&logthis("Subscribe returned not_found: $filename");
 1297: 	   return 'not_found';
 1298:     } elsif ($remoteurl =~ /^rejected by/) {
 1299: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1300:            return 'forbidden';
 1301:     } elsif ($remoteurl eq 'directory') {
 1302:            return 'ok';
 1303:     } else {
 1304:         my $author=$filename;
 1305:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1306:         my ($udom,$uname)=split(/\//,$author);
 1307:         my $home=homeserver($uname,$udom);
 1308:         unless ($home eq $perlvar{'lonHostID'}) {
 1309:            my @parts=split(/\//,$filename);
 1310:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1311:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1312:                &logthis("Malconfiguration for replication: $filename");
 1313: 	       return 'bad_request';
 1314:            }
 1315:            my $count;
 1316:            for ($count=5;$count<$#parts;$count++) {
 1317:                $path.="/$parts[$count]";
 1318:                if ((-e $path)!=1) {
 1319: 		   mkdir($path,0777);
 1320:                }
 1321:            }
 1322:            my $ua=new LWP::UserAgent;
 1323:            my $request=new HTTP::Request('GET',"$remoteurl");
 1324:            my $response=$ua->request($request,$transname);
 1325:            if ($response->is_error()) {
 1326: 	       unlink($transname);
 1327:                my $message=$response->status_line;
 1328:                &logthis("<font color=\"blue\">WARNING:"
 1329:                        ." LWP get: $message: $filename</font>");
 1330:                return 'unavailable';
 1331:            } else {
 1332: 	       if ($remoteurl!~/\.meta$/) {
 1333:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1334:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1335:                   if ($mresponse->is_error()) {
 1336: 		      unlink($filename.'.meta');
 1337:                       &logthis(
 1338:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1339:                   }
 1340: 	       }
 1341:                rename($transname,$filename);
 1342:                return 'ok';
 1343:            }
 1344:        }
 1345:     }
 1346: }
 1347: 
 1348: # ------------------------------------------------ Get server side include body
 1349: sub ssi_body {
 1350:     my ($filelink,%form)=@_;
 1351:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1352:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1353:     }
 1354:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1355:                                      &ssi($filelink,%form));
 1356:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1357:     $output=~s/^.*?\<body[^\>]*\>//si;
 1358:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1359:     return $output;
 1360: }
 1361: 
 1362: # --------------------------------------------------------- Server Side Include
 1363: 
 1364: sub absolute_url {
 1365:     my ($host_name) = @_;
 1366:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1367:     if ($host_name eq '') {
 1368: 	$host_name = $ENV{'SERVER_NAME'};
 1369:     }
 1370:     return $protocol.$host_name;
 1371: }
 1372: 
 1373: sub ssi {
 1374: 
 1375:     my ($fn,%form)=@_;
 1376: 
 1377:     my $ua=new LWP::UserAgent;
 1378:     
 1379:     my $request;
 1380: 
 1381:     $form{'no_update_last_known'}=1;
 1382: 
 1383:     if (%form) {
 1384:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1385:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1386:     } else {
 1387:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1388:     }
 1389: 
 1390:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1391:     my $response=$ua->request($request);
 1392: 
 1393:     return $response->content;
 1394: }
 1395: 
 1396: sub externalssi {
 1397:     my ($url)=@_;
 1398:     my $ua=new LWP::UserAgent;
 1399:     my $request=new HTTP::Request('GET',$url);
 1400:     my $response=$ua->request($request);
 1401:     return $response->content;
 1402: }
 1403: 
 1404: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1405: 
 1406: sub allowuploaded {
 1407:     my ($srcurl,$url)=@_;
 1408:     $url=&clutter(&declutter($url));
 1409:     my $dir=$url;
 1410:     $dir=~s/\/[^\/]+$//;
 1411:     my %httpref=();
 1412:     my $httpurl=&hreflocation('',$url);
 1413:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1414:     &Apache::lonnet::appenv(%httpref);
 1415: }
 1416: 
 1417: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1418: # input: action, courseID, current domain, intended
 1419: #        path to file, source of file, instruction to parse file for objects,
 1420: #        ref to hash for embedded objects,
 1421: #        ref to hash for codebase of java objects.
 1422: #
 1423: # output: url to file (if action was uploaddoc), 
 1424: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1425: #
 1426: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1427: # course.
 1428: #
 1429: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1430: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1431: #          course's home server.
 1432: #
 1433: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1434: #          be copied from $source (current location) to 
 1435: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1436: #         and will then be copied to
 1437: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1438: #         course's home server.
 1439: #
 1440: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1441: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1442: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1443: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1444: #         in course's home server.
 1445: #
 1446: 
 1447: sub process_coursefile {
 1448:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1449:     my $fetchresult;
 1450:     my $home=&homeserver($docuname,$docudom);
 1451:     if ($action eq 'propagate') {
 1452:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1453: 			     $home);
 1454:     } else {
 1455:         my $fpath = '';
 1456:         my $fname = $file;
 1457:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1458:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1459:         my $filepath = &build_filepath($fpath);
 1460:         if ($action eq 'copy') {
 1461:             if ($source eq '') {
 1462:                 $fetchresult = 'no source file';
 1463:                 return $fetchresult;
 1464:             } else {
 1465:                 my $destination = $filepath.'/'.$fname;
 1466:                 rename($source,$destination);
 1467:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1468:                                  $home);
 1469:             }
 1470:         } elsif ($action eq 'uploaddoc') {
 1471:             open(my $fh,'>'.$filepath.'/'.$fname);
 1472:             print $fh $env{'form.'.$source};
 1473:             close($fh);
 1474:             if ($parser eq 'parse') {
 1475:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1476:                 unless ($parse_result eq 'ok') {
 1477:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1478:                 }
 1479:             }
 1480:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1481:                                  $home);
 1482:             if ($fetchresult eq 'ok') {
 1483:                 return '/uploaded/'.$fpath.'/'.$fname;
 1484:             } else {
 1485:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1486:                         ' to host '.$home.': '.$fetchresult);
 1487:                 return '/adm/notfound.html';
 1488:             }
 1489:         }
 1490:     }
 1491:     unless ( $fetchresult eq 'ok') {
 1492:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1493:              ' to host '.$home.': '.$fetchresult);
 1494:     }
 1495:     return $fetchresult;
 1496: }
 1497: 
 1498: sub build_filepath {
 1499:     my ($fpath) = @_;
 1500:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1501:     unless ($fpath eq '') {
 1502:         my @parts=split('/',$fpath);
 1503:         foreach my $part (@parts) {
 1504:             $filepath.= '/'.$part;
 1505:             if ((-e $filepath)!=1) {
 1506:                 mkdir($filepath,0777);
 1507:             }
 1508:         }
 1509:     }
 1510:     return $filepath;
 1511: }
 1512: 
 1513: sub store_edited_file {
 1514:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1515:     my $file = $primary_url;
 1516:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1517:     my $fpath = '';
 1518:     my $fname = $file;
 1519:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1520:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1521:     my $filepath = &build_filepath($fpath);
 1522:     open(my $fh,'>'.$filepath.'/'.$fname);
 1523:     print $fh $content;
 1524:     close($fh);
 1525:     my $home=&homeserver($docuname,$docudom);
 1526:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1527: 			  $home);
 1528:     if ($$fetchresult eq 'ok') {
 1529:         return '/uploaded/'.$fpath.'/'.$fname;
 1530:     } else {
 1531:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1532: 		 ' to host '.$home.': '.$$fetchresult);
 1533:         return '/adm/notfound.html';
 1534:     }
 1535: }
 1536: 
 1537: sub clean_filename {
 1538:     my ($fname,$args)=@_;
 1539: # Replace Windows backslashes by forward slashes
 1540:     $fname=~s/\\/\//g;
 1541:     if (!$args->{'keep_path'}) {
 1542:         # Get rid of everything but the actual filename
 1543: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1544:     }
 1545: # Replace spaces by underscores
 1546:     $fname=~s/\s+/\_/g;
 1547: # Replace all other weird characters by nothing
 1548:     $fname=~s{[^/\w\.\-]}{}g;
 1549: # Replace all .\d. sequences with _\d. so they no longer look like version
 1550: # numbers
 1551:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1552:     return $fname;
 1553: }
 1554: 
 1555: # --------------- Take an uploaded file and put it into the userfiles directory
 1556: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1557: #                    the desired filenam is in $env{"form.$formname.filename"}
 1558: #        $coursedoc - if true up to the current course
 1559: #                     if false
 1560: #        $subdir - directory in userfile to store the file into
 1561: #        $parser - instruction to parse file for objects ($parser = parse)    
 1562: #        $allfiles - reference to hash for embedded objects
 1563: #        $codebase - reference to hash for codebase of java objects
 1564: #        $desuname - username for permanent storage of uploaded file
 1565: #        $dsetudom - domain for permanaent storage of uploaded file
 1566: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1567: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1568: # 
 1569: # output: url of file in userspace, or error: <message> 
 1570: #             or /adm/notfound.html if failure to upload occurse
 1571: 
 1572: 
 1573: sub userfileupload {
 1574:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1575:         $destudom,$thumbwidth,$thumbheight)=@_;
 1576:     if (!defined($subdir)) { $subdir='unknown'; }
 1577:     my $fname=$env{'form.'.$formname.'.filename'};
 1578:     $fname=&clean_filename($fname);
 1579: # See if there is anything left
 1580:     unless ($fname) { return 'error: no uploaded file'; }
 1581:     chop($env{'form.'.$formname});
 1582:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1583:         my $now = time;
 1584:         my $filepath = 'tmp/helprequests/'.$now;
 1585:         my @parts=split(/\//,$filepath);
 1586:         my $fullpath = $perlvar{'lonDaemons'};
 1587:         for (my $i=0;$i<@parts;$i++) {
 1588:             $fullpath .= '/'.$parts[$i];
 1589:             if ((-e $fullpath)!=1) {
 1590:                 mkdir($fullpath,0777);
 1591:             }
 1592:         }
 1593:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1594:         print $fh $env{'form.'.$formname};
 1595:         close($fh);
 1596:         return $fullpath.'/'.$fname;
 1597:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1598:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1599:                        '_'.$env{'user.domain'}.'/pending';
 1600:         my @parts=split(/\//,$filepath);
 1601:         my $fullpath = $perlvar{'lonDaemons'};
 1602:         for (my $i=0;$i<@parts;$i++) {
 1603:             $fullpath .= '/'.$parts[$i];
 1604:             if ((-e $fullpath)!=1) {
 1605:                 mkdir($fullpath,0777);
 1606:             }
 1607:         }
 1608:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1609:         print $fh $env{'form.'.$formname};
 1610:         close($fh);
 1611:         return $fullpath.'/'.$fname;
 1612:     }
 1613:     
 1614: # Create the directory if not present
 1615:     $fname="$subdir/$fname";
 1616:     if ($coursedoc) {
 1617: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1618: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1619:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1620:             return &finishuserfileupload($docuname,$docudom,
 1621: 					 $formname,$fname,$parser,$allfiles,
 1622: 					 $codebase,$thumbwidth,$thumbheight);
 1623:         } else {
 1624:             $fname=$env{'form.folder'}.'/'.$fname;
 1625:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1626: 				       $fname,$formname,$parser,
 1627: 				       $allfiles,$codebase);
 1628:         }
 1629:     } elsif (defined($destuname)) {
 1630:         my $docuname=$destuname;
 1631:         my $docudom=$destudom;
 1632: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1633: 				     $parser,$allfiles,$codebase,
 1634:                                      $thumbwidth,$thumbheight);
 1635:         
 1636:     } else {
 1637:         my $docuname=$env{'user.name'};
 1638:         my $docudom=$env{'user.domain'};
 1639:         if (exists($env{'form.group'})) {
 1640:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1641:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1642:         }
 1643: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1644: 				     $parser,$allfiles,$codebase,
 1645:                                      $thumbwidth,$thumbheight);
 1646:     }
 1647: }
 1648: 
 1649: sub finishuserfileupload {
 1650:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1651:         $thumbwidth,$thumbheight) = @_;
 1652:     my $path=$docudom.'/'.$docuname.'/';
 1653:     my $filepath=$perlvar{'lonDocRoot'};
 1654:     my ($fnamepath,$file,$fetchthumb);
 1655:     $file=$fname;
 1656:     if ($fname=~m|/|) {
 1657:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1658: 	$path.=$fnamepath.'/';
 1659:     }
 1660:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1661:     my $count;
 1662:     for ($count=4;$count<=$#parts;$count++) {
 1663:         $filepath.="/$parts[$count]";
 1664:         if ((-e $filepath)!=1) {
 1665: 	    mkdir($filepath,0777);
 1666:         }
 1667:     }
 1668: # Save the file
 1669:     {
 1670: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1671: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1672: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1673: 	    return '/adm/notfound.html';
 1674: 	}
 1675: 	if (!print FH ($env{'form.'.$formname})) {
 1676: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1677: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1678: 	    return '/adm/notfound.html';
 1679: 	}
 1680: 	close(FH);
 1681:     }
 1682:     if ($parser eq 'parse') {
 1683:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1684: 						   $codebase);
 1685:         unless ($parse_result eq 'ok') {
 1686:             &logthis('Failed to parse '.$filepath.$file.
 1687: 		     ' for embedded media: '.$parse_result); 
 1688:         }
 1689:     }
 1690:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1691:         my $input = $filepath.'/'.$file;
 1692:         my $output = $filepath.'/'.'tn-'.$file;
 1693:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1694:         system("convert -sample $thumbsize $input $output");
 1695:         if (-e $filepath.'/'.'tn-'.$file) {
 1696:             $fetchthumb  = 1; 
 1697:         }
 1698:     }
 1699:  
 1700: # Notify homeserver to grep it
 1701: #
 1702:     my $docuhome=&homeserver($docuname,$docudom);
 1703:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1704:     if ($fetchresult eq 'ok') {
 1705:         if ($fetchthumb) {
 1706:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1707:             if ($thumbresult ne 'ok') {
 1708:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1709:                          $docuhome.': '.$thumbresult);
 1710:             }
 1711:         }
 1712: #
 1713: # Return the URL to it
 1714:         return '/uploaded/'.$path.$file;
 1715:     } else {
 1716:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1717: 		 ': '.$fetchresult);
 1718:         return '/adm/notfound.html';
 1719:     }
 1720: }
 1721: 
 1722: sub extract_embedded_items {
 1723:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1724:     my @state = ();
 1725:     my %javafiles = (
 1726:                       codebase => '',
 1727:                       code => '',
 1728:                       archive => ''
 1729:                     );
 1730:     my %mediafiles = (
 1731:                       src => '',
 1732:                       movie => '',
 1733:                      );
 1734:     my $p;
 1735:     if ($content) {
 1736:         $p = HTML::LCParser->new($content);
 1737:     } else {
 1738:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1739:     }
 1740:     while (my $t=$p->get_token()) {
 1741: 	if ($t->[0] eq 'S') {
 1742: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1743: 	    push (@state, $tagname);
 1744:             if (lc($tagname) eq 'allow') {
 1745:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1746:             }
 1747: 	    if (lc($tagname) eq 'img') {
 1748: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1749: 	    }
 1750:             if (lc($tagname) eq 'script') {
 1751:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1752:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1753:                 } else {
 1754:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1755:                 }
 1756:             }
 1757:             if (lc($tagname) eq 'link') {
 1758:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1759:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1760:                 }
 1761:             }
 1762: 	    if (lc($tagname) eq 'object' ||
 1763: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1764: 		foreach my $item (keys(%javafiles)) {
 1765: 		    $javafiles{$item} = '';
 1766: 		}
 1767: 	    }
 1768: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1769: 		my $name = lc($attr->{'name'});
 1770: 		foreach my $item (keys(%javafiles)) {
 1771: 		    if ($name eq $item) {
 1772: 			$javafiles{$item} = $attr->{'value'};
 1773: 			last;
 1774: 		    }
 1775: 		}
 1776: 		foreach my $item (keys(%mediafiles)) {
 1777: 		    if ($name eq $item) {
 1778: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1779: 			last;
 1780: 		    }
 1781: 		}
 1782: 	    }
 1783: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1784: 		foreach my $item (keys(%javafiles)) {
 1785: 		    if ($attr->{$item}) {
 1786: 			$javafiles{$item} = $attr->{$item};
 1787: 			last;
 1788: 		    }
 1789: 		}
 1790: 		foreach my $item (keys(%mediafiles)) {
 1791: 		    if ($attr->{$item}) {
 1792: 			&add_filetype($allfiles,$attr->{$item},$item);
 1793: 			last;
 1794: 		    }
 1795: 		}
 1796: 	    }
 1797: 	} elsif ($t->[0] eq 'E') {
 1798: 	    my ($tagname) = ($t->[1]);
 1799: 	    if ($javafiles{'codebase'} ne '') {
 1800: 		$javafiles{'codebase'} .= '/';
 1801: 	    }  
 1802: 	    if (lc($tagname) eq 'applet' ||
 1803: 		lc($tagname) eq 'object' ||
 1804: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1805: 		) {
 1806: 		foreach my $item (keys(%javafiles)) {
 1807: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1808: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1809: 			&add_filetype($allfiles,$file,$item);
 1810: 		    }
 1811: 		}
 1812: 	    } 
 1813: 	    pop @state;
 1814: 	}
 1815:     }
 1816:     return 'ok';
 1817: }
 1818: 
 1819: sub add_filetype {
 1820:     my ($allfiles,$file,$type)=@_;
 1821:     if (exists($allfiles->{$file})) {
 1822: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1823: 	    push(@{$allfiles->{$file}}, &escape($type));
 1824: 	}
 1825:     } else {
 1826: 	@{$allfiles->{$file}} = (&escape($type));
 1827:     }
 1828: }
 1829: 
 1830: sub removeuploadedurl {
 1831:     my ($url)=@_;
 1832:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1833:     return &removeuserfile($uname,$udom,$fname);
 1834: }
 1835: 
 1836: sub removeuserfile {
 1837:     my ($docuname,$docudom,$fname)=@_;
 1838:     my $home=&homeserver($docuname,$docudom);
 1839:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1840:     if ($result eq 'ok') {
 1841:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1842:             my $metafile = $fname.'.meta';
 1843:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1844: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1845:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1846:             my $sqlresult = 
 1847:                 &update_portfolio_table($docuname,$docudom,$file,
 1848:                                         'portfolio_metadata',$group,
 1849:                                         'delete');
 1850:         }
 1851:     }
 1852:     return $result;
 1853: }
 1854: 
 1855: sub mkdiruserfile {
 1856:     my ($docuname,$docudom,$dir)=@_;
 1857:     my $home=&homeserver($docuname,$docudom);
 1858:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1859: }
 1860: 
 1861: sub renameuserfile {
 1862:     my ($docuname,$docudom,$old,$new)=@_;
 1863:     my $home=&homeserver($docuname,$docudom);
 1864:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1865:                         &escape("$old").':'.&escape("$new"),$home);
 1866:     if ($result eq 'ok') {
 1867:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1868:             my $oldmeta = $old.'.meta';
 1869:             my $newmeta = $new.'.meta';
 1870:             my $metaresult = 
 1871:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1872: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1873:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1874:             my $sqlresult = 
 1875:                 &update_portfolio_table($docuname,$docudom,$file,
 1876:                                         'portfolio_metadata',$group,
 1877:                                         'delete');
 1878:         }
 1879:     }
 1880:     return $result;
 1881: }
 1882: 
 1883: # ------------------------------------------------------------------------- Log
 1884: 
 1885: sub log {
 1886:     my ($dom,$nam,$hom,$what)=@_;
 1887:     return critical("log:$dom:$nam:$what",$hom);
 1888: }
 1889: 
 1890: # ------------------------------------------------------------------ Course Log
 1891: #
 1892: # This routine flushes several buffers of non-mission-critical nature
 1893: #
 1894: 
 1895: sub flushcourselogs {
 1896:     &logthis('Flushing log buffers');
 1897: #
 1898: # course logs
 1899: # This is a log of all transactions in a course, which can be used
 1900: # for data mining purposes
 1901: #
 1902: # It also collects the courseid database, which lists last transaction
 1903: # times and course titles for all courseids
 1904: #
 1905:     my %courseidbuffer=();
 1906:     foreach my $crsid (keys %courselogs) {
 1907:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1908: 		          &escape($courselogs{$crsid}),
 1909: 		          $coursehombuf{$crsid}) eq 'ok') {
 1910: 	    delete $courselogs{$crsid};
 1911:         } else {
 1912:             &logthis('Failed to flush log buffer for '.$crsid);
 1913:             if (length($courselogs{$crsid})>40000) {
 1914:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1915:                         " exceeded maximum size, deleting.</font>");
 1916:                delete $courselogs{$crsid};
 1917:             }
 1918:         }
 1919:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1920:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1921: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1922:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1923:         } else {
 1924:            $courseidbuffer{$coursehombuf{$crsid}}=
 1925: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1926:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1927:         }
 1928:     }
 1929: #
 1930: # Write course id database (reverse lookup) to homeserver of courses 
 1931: # Is used in pickcourse
 1932: #
 1933:     foreach my $crs_home (keys(%courseidbuffer)) {
 1934:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1935: 		     $crs_home);
 1936:     }
 1937: #
 1938: # File accesses
 1939: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1940: #
 1941:     foreach my $entry (keys(%accesshash)) {
 1942:         if ($entry =~ /___count$/) {
 1943:             my ($dom,$name);
 1944:             ($dom,$name,undef)=
 1945: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1946:             if (! defined($dom) || $dom eq '' || 
 1947:                 ! defined($name) || $name eq '') {
 1948:                 my $cid = $env{'request.course.id'};
 1949:                 $dom  = $env{'request.'.$cid.'.domain'};
 1950:                 $name = $env{'request.'.$cid.'.num'};
 1951:             }
 1952:             my $value = $accesshash{$entry};
 1953:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1954:             my %temphash=($url => $value);
 1955:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1956:             if ($result eq 'ok') {
 1957:                 delete $accesshash{$entry};
 1958:             } elsif ($result eq 'unknown_cmd') {
 1959:                 # Target server has old code running on it.
 1960:                 my %temphash=($entry => $value);
 1961:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1962:                     delete $accesshash{$entry};
 1963:                 }
 1964:             }
 1965:         } else {
 1966:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1967:             my %temphash=($entry => $accesshash{$entry});
 1968:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1969:                 delete $accesshash{$entry};
 1970:             }
 1971:         }
 1972:     }
 1973: #
 1974: # Roles
 1975: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1976: #
 1977:     foreach my $entry (keys(%userrolehash)) {
 1978:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1979: 	    split(/\:/,$entry);
 1980:         if (&Apache::lonnet::put('nohist_userroles',
 1981:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1982:                 $rudom,$runame) eq 'ok') {
 1983: 	    delete $userrolehash{$entry};
 1984:         }
 1985:     }
 1986: #
 1987: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1988: #
 1989:     my %domrolebuffer = ();
 1990:     foreach my $entry (keys %domainrolehash) {
 1991:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1992:         if ($domrolebuffer{$rudom}) {
 1993:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1994:                       '='.&escape($domainrolehash{$entry});
 1995:         } else {
 1996:             $domrolebuffer{$rudom}.=&escape($entry).
 1997:                       '='.&escape($domainrolehash{$entry});
 1998:         }
 1999:         delete $domainrolehash{$entry};
 2000:     }
 2001:     foreach my $dom (keys(%domrolebuffer)) {
 2002: 	my %servers = &get_servers($dom,'library');
 2003: 	foreach my $tryserver (keys(%servers)) {
 2004: 	    unless (&reply('domroleput:'.$dom.':'.
 2005: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2006: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2007: 	    }
 2008:         }
 2009:     }
 2010:     $dumpcount++;
 2011: }
 2012: 
 2013: sub courselog {
 2014:     my $what=shift;
 2015:     $what=time.':'.$what;
 2016:     unless ($env{'request.course.id'}) { return ''; }
 2017:     $coursedombuf{$env{'request.course.id'}}=
 2018:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2019:     $coursenumbuf{$env{'request.course.id'}}=
 2020:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2021:     $coursehombuf{$env{'request.course.id'}}=
 2022:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2023:     $coursedescrbuf{$env{'request.course.id'}}=
 2024:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2025:     $courseinstcodebuf{$env{'request.course.id'}}=
 2026:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2027:     $courseownerbuf{$env{'request.course.id'}}=
 2028:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2029:     $coursetypebuf{$env{'request.course.id'}}=
 2030:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2031:     if (defined $courselogs{$env{'request.course.id'}}) {
 2032: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2033:     } else {
 2034: 	$courselogs{$env{'request.course.id'}}.=$what;
 2035:     }
 2036:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2037: 	&flushcourselogs();
 2038:     }
 2039: }
 2040: 
 2041: sub courseacclog {
 2042:     my $fnsymb=shift;
 2043:     unless ($env{'request.course.id'}) { return ''; }
 2044:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2045:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2046:         $what.=':POST';
 2047:         # FIXME: Probably ought to escape things....
 2048: 	foreach my $key (keys(%env)) {
 2049:             if ($key=~/^form\.(.*)/) {
 2050: 		$what.=':'.$1.'='.$env{$key};
 2051:             }
 2052:         }
 2053:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2054:         # FIXME: We should not be depending on a form parameter that someone
 2055:         # editing lonsearchcat.pm might change in the future.
 2056:         if ($env{'form.phase'} eq 'course_search') {
 2057:             $what.= ':POST';
 2058:             # FIXME: Probably ought to escape things....
 2059:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2060:                                  'crsdiscuss') {
 2061:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2062:             }
 2063:         }
 2064:     }
 2065:     &courselog($what);
 2066: }
 2067: 
 2068: sub countacc {
 2069:     my $url=&declutter(shift);
 2070:     return if (! defined($url) || $url eq '');
 2071:     unless ($env{'request.course.id'}) { return ''; }
 2072:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2073:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2074:     $accesshash{$key}++;
 2075: }
 2076: 
 2077: sub linklog {
 2078:     my ($from,$to)=@_;
 2079:     $from=&declutter($from);
 2080:     $to=&declutter($to);
 2081:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2082:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2083: }
 2084:   
 2085: sub userrolelog {
 2086:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2087:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2088:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2089:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2090:         ($trole=~/^ta/)) {
 2091:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2092:        $userrolehash
 2093:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2094:                     =$tend.':'.$tstart;
 2095:     }
 2096:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2097:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2098:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2099:         ($trole=~/^sc/)) {
 2100:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2101:        $domainrolehash
 2102:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2103:                     = $tend.':'.$tstart;
 2104:     }
 2105: }
 2106: 
 2107: sub get_course_adv_roles {
 2108:     my $cid=shift;
 2109:     $cid=$env{'request.course.id'} unless (defined($cid));
 2110:     my %coursehash=&coursedescription($cid);
 2111:     my %nothide=();
 2112:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2113: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2114:     }
 2115:     my %returnhash=();
 2116:     my %dumphash=
 2117:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2118:     my $now=time;
 2119:     foreach my $entry (keys %dumphash) {
 2120: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2121:         if (($tstart) && ($tstart<0)) { next; }
 2122:         if (($tend) && ($tend<$now)) { next; }
 2123:         if (($tstart) && ($now<$tstart)) { next; }
 2124:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2125: 	if ($username eq '' || $domain eq '') { next; }
 2126: 	if ((&privileged($username,$domain)) && 
 2127: 	    (!$nothide{$username.':'.$domain})) { next; }
 2128: 	if ($role eq 'cr') { next; }
 2129:         my $key=&plaintext($role);
 2130:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2131:         if ($returnhash{$key}) {
 2132: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2133:         } else {
 2134:             $returnhash{$key}=$username.':'.$domain;
 2135:         }
 2136:      }
 2137:     return %returnhash;
 2138: }
 2139: 
 2140: sub get_my_roles {
 2141:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2142:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2143:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2144:     my %dumphash;
 2145:     if ($context eq 'userroles') { 
 2146:         %dumphash = &dump('roles',$udom,$uname);
 2147:     } else {
 2148:         %dumphash=
 2149:             &dump('nohist_userroles',$udom,$uname);
 2150:     }
 2151:     my %returnhash=();
 2152:     my $now=time;
 2153:     foreach my $entry (keys(%dumphash)) {
 2154:         my ($role,$tend,$tstart);
 2155:         if ($context eq 'userroles') {
 2156: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2157:         } else {
 2158:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2159:         }
 2160:         if (($tstart) && ($tstart<0)) { next; }
 2161:         my $status = 'active';
 2162:         if (($tend) && ($tend<$now)) {
 2163:             $status = 'previous';
 2164:         } 
 2165:         if (($tstart) && ($now<$tstart)) {
 2166:             $status = 'future';
 2167:         }
 2168:         if (ref($types) eq 'ARRAY') {
 2169:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2170:                 next;
 2171:             } 
 2172:         } else {
 2173:             if ($status ne 'active') {
 2174:                 next;
 2175:             }
 2176:         }
 2177:         my ($rolecode,$username,$domain,$section,$area);
 2178:         if ($context eq 'userroles') {
 2179:             ($area,$rolecode) = split(/_/,$entry);
 2180:             (undef,$domain,$username,$section) = split(/\//,$area);
 2181:         } else {
 2182:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2183:         }
 2184:         if (ref($roledoms) eq 'ARRAY') {
 2185:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2186:                 next;
 2187:             }
 2188:         }
 2189:         if (ref($roles) eq 'ARRAY') {
 2190:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2191:                 next;
 2192:             }
 2193:         }
 2194: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2195:     }
 2196:     return %returnhash;
 2197: }
 2198: 
 2199: # ----------------------------------------------------- Frontpage Announcements
 2200: #
 2201: #
 2202: 
 2203: sub postannounce {
 2204:     my ($server,$text)=@_;
 2205:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2206:     unless ($text=~/\w/) { $text=''; }
 2207:     return &reply('setannounce:'.&escape($text),$server);
 2208: }
 2209: 
 2210: sub getannounce {
 2211: 
 2212:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2213: 	my $announcement='';
 2214: 	while (my $line = <$fh>) { $announcement .= $line; }
 2215: 	close($fh);
 2216: 	if ($announcement=~/\w/) { 
 2217: 	    return 
 2218:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2219:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2220: 	} else {
 2221: 	    return '';
 2222: 	}
 2223:     } else {
 2224: 	return '';
 2225:     }
 2226: }
 2227: 
 2228: # ---------------------------------------------------------- Course ID routines
 2229: # Deal with domain's nohist_courseid.db files
 2230: #
 2231: 
 2232: sub courseidput {
 2233:     my ($domain,$what,$coursehome)=@_;
 2234:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2235: }
 2236: 
 2237: sub courseiddump {
 2238:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2239:     my %returnhash=();
 2240:     unless ($domfilter) { $domfilter=''; }
 2241:     my %libserv = &all_library();
 2242:     foreach my $tryserver (keys(%libserv)) {
 2243:         if ( (  $hostidflag == 1 
 2244: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2245: 	     || (!defined($hostidflag)) ) {
 2246: 
 2247: 	    if ($domfilter eq ''
 2248: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2249: 	        foreach my $line (
 2250:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2251: 			       $sincefilter.':'.&escape($descfilter).':'.
 2252:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2253:                                $tryserver))) {
 2254: 		    my ($key,$value)=split(/\=/,$line,2);
 2255:                     if (($key) && ($value)) {
 2256: 		        $returnhash{&unescape($key)}=$value;
 2257:                     }
 2258:                 }
 2259:             }
 2260:         }
 2261:     }
 2262:     return %returnhash;
 2263: }
 2264: 
 2265: # ---------------------------------------------------------- DC e-mail
 2266: 
 2267: sub dcmailput {
 2268:     my ($domain,$msgid,$message,$server)=@_;
 2269:     my $status = &Apache::lonnet::critical(
 2270:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2271:        &escape($message),$server);
 2272:     return $status;
 2273: }
 2274: 
 2275: sub dcmaildump {
 2276:     my ($dom,$startdate,$enddate,$senders) = @_;
 2277:     my %returnhash=();
 2278: 
 2279:     if (defined(&domain($dom,'primary'))) {
 2280:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2281:                                                          &escape($enddate).':';
 2282: 	my @esc_senders=map { &escape($_)} @$senders;
 2283: 	$cmd.=&escape(join('&',@esc_senders));
 2284: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2285:             my ($key,$value) = split(/\=/,$line,2);
 2286:             if (($key) && ($value)) {
 2287:                 $returnhash{&unescape($key)} = &unescape($value);
 2288:             }
 2289:         }
 2290:     }
 2291:     return %returnhash;
 2292: }
 2293: # ---------------------------------------------------------- Domain roles
 2294: 
 2295: sub get_domain_roles {
 2296:     my ($dom,$roles,$startdate,$enddate)=@_;
 2297:     if (undef($startdate) || $startdate eq '') {
 2298:         $startdate = '.';
 2299:     }
 2300:     if (undef($enddate) || $enddate eq '') {
 2301:         $enddate = '.';
 2302:     }
 2303:     my $rolelist = join(':',@{$roles});
 2304:     my %personnel = ();
 2305: 
 2306:     my %servers = &get_servers($dom,'library');
 2307:     foreach my $tryserver (keys(%servers)) {
 2308: 	%{$personnel{$tryserver}}=();
 2309: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2310: 					    &escape($startdate).':'.
 2311: 					    &escape($enddate).':'.
 2312: 					    &escape($rolelist), $tryserver))) {
 2313: 	    my ($key,$value) = split(/\=/,$line,2);
 2314: 	    if (($key) && ($value)) {
 2315: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2316: 	    }
 2317: 	}
 2318:     }
 2319:     return %personnel;
 2320: }
 2321: 
 2322: # ----------------------------------------------------------- Check out an item
 2323: 
 2324: sub get_first_access {
 2325:     my ($type,$argsymb)=@_;
 2326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2327:     if ($argsymb) { $symb=$argsymb; }
 2328:     my ($map,$id,$res)=&decode_symb($symb);
 2329:     if ($type eq 'map') {
 2330: 	$res=&symbread($map);
 2331:     } else {
 2332: 	$res=$symb;
 2333:     }
 2334:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2335:     return $times{"$courseid\0$res"};
 2336: }
 2337: 
 2338: sub set_first_access {
 2339:     my ($type)=@_;
 2340:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2341:     my ($map,$id,$res)=&decode_symb($symb);
 2342:     if ($type eq 'map') {
 2343: 	$res=&symbread($map);
 2344:     } else {
 2345: 	$res=$symb;
 2346:     }
 2347:     my $firstaccess=&get_first_access($type,$symb);
 2348:     if (!$firstaccess) {
 2349: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2350:     }
 2351:     return 'already_set';
 2352: }
 2353: 
 2354: sub checkout {
 2355:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2356:     my $now=time;
 2357:     my $lonhost=$perlvar{'lonHostID'};
 2358:     my $infostr=&escape(
 2359:                  'CHECKOUTTOKEN&'.
 2360:                  $tuname.'&'.
 2361:                  $tudom.'&'.
 2362:                  $tcrsid.'&'.
 2363:                  $symb.'&'.
 2364: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2365:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2366:     if ($token=~/^error\:/) { 
 2367:         &logthis("<font color=\"blue\">WARNING: ".
 2368:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2369:                  "</font>");
 2370:         return ''; 
 2371:     }
 2372: 
 2373:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2374:     $token=~tr/a-z/A-Z/;
 2375: 
 2376:     my %infohash=('resource.0.outtoken' => $token,
 2377:                   'resource.0.checkouttime' => $now,
 2378:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2379: 
 2380:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2381:        return '';
 2382:     } else {
 2383:         &logthis("<font color=\"blue\">WARNING: ".
 2384:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2385:                  "</font>");
 2386:     }    
 2387: 
 2388:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2389:                          &escape('Checkout '.$infostr.' - '.
 2390:                                                  $token)) ne 'ok') {
 2391: 	return '';
 2392:     } else {
 2393:         &logthis("<font color=\"blue\">WARNING: ".
 2394:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2395:                  "</font>");
 2396:     }
 2397:     return $token;
 2398: }
 2399: 
 2400: # ------------------------------------------------------------ Check in an item
 2401: 
 2402: sub checkin {
 2403:     my $token=shift;
 2404:     my $now=time;
 2405:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2406:     $lonhost=~tr/A-Z/a-z/;
 2407:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2408:     $dtoken=~s/\W/\_/g;
 2409:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2410:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2411: 
 2412:     unless (($tuname) && ($tudom)) {
 2413:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2414:         return '';
 2415:     }
 2416:     
 2417:     unless (&allowed('mgr',$tcrsid)) {
 2418:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2419:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2420:         return '';
 2421:     }
 2422: 
 2423:     my %infohash=('resource.0.intoken' => $token,
 2424:                   'resource.0.checkintime' => $now,
 2425:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2426: 
 2427:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2428:        return '';
 2429:     }    
 2430: 
 2431:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2432:                          &escape('Checkin - '.$token)) ne 'ok') {
 2433: 	return '';
 2434:     }
 2435: 
 2436:     return ($symb,$tuname,$tudom,$tcrsid);    
 2437: }
 2438: 
 2439: # --------------------------------------------- Set Expire Date for Spreadsheet
 2440: 
 2441: sub expirespread {
 2442:     my ($uname,$udom,$stype,$usymb)=@_;
 2443:     my $cid=$env{'request.course.id'}; 
 2444:     if ($cid) {
 2445:        my $now=time;
 2446:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2447:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2448:                             $env{'course.'.$cid.'.num'}.
 2449: 	        	    ':nohist_expirationdates:'.
 2450:                             &escape($key).'='.$now,
 2451:                             $env{'course.'.$cid.'.home'})
 2452:     }
 2453:     return 'ok';
 2454: }
 2455: 
 2456: # ----------------------------------------------------- Devalidate Spreadsheets
 2457: 
 2458: sub devalidate {
 2459:     my ($symb,$uname,$udom)=@_;
 2460:     my $cid=$env{'request.course.id'}; 
 2461:     if ($cid) {
 2462:         # delete the stored spreadsheets for
 2463:         # - the student level sheet of this user in course's homespace
 2464:         # - the assessment level sheet for this resource 
 2465:         #   for this user in user's homespace
 2466: 	# - current conditional state info
 2467: 	my $key=$uname.':'.$udom.':';
 2468:         my $status=
 2469: 	    &del('nohist_calculatedsheets',
 2470: 		 [$key.'studentcalc:'],
 2471: 		 $env{'course.'.$cid.'.domain'},
 2472: 		 $env{'course.'.$cid.'.num'})
 2473: 		.' '.
 2474: 	    &del('nohist_calculatedsheets_'.$cid,
 2475: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2476:         unless ($status eq 'ok ok') {
 2477:            &logthis('Could not devalidate spreadsheet '.
 2478:                     $uname.' at '.$udom.' for '.
 2479: 		    $symb.': '.$status);
 2480:         }
 2481: 	&delenv('user.state.'.$cid);
 2482:     }
 2483: }
 2484: 
 2485: sub get_scalar {
 2486:     my ($string,$end) = @_;
 2487:     my $value;
 2488:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2489: 	$value = $1;
 2490:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2491: 	$value = $1;
 2492:     }
 2493:     return &unescape($value);
 2494: }
 2495: 
 2496: sub array2str {
 2497:   my (@array) = @_;
 2498:   my $result=&arrayref2str(\@array);
 2499:   $result=~s/^__ARRAY_REF__//;
 2500:   $result=~s/__END_ARRAY_REF__$//;
 2501:   return $result;
 2502: }
 2503: 
 2504: sub arrayref2str {
 2505:   my ($arrayref) = @_;
 2506:   my $result='__ARRAY_REF__';
 2507:   foreach my $elem (@$arrayref) {
 2508:     if(ref($elem) eq 'ARRAY') {
 2509:       $result.=&arrayref2str($elem).'&';
 2510:     } elsif(ref($elem) eq 'HASH') {
 2511:       $result.=&hashref2str($elem).'&';
 2512:     } elsif(ref($elem)) {
 2513:       #print("Got a ref of ".(ref($elem))." skipping.");
 2514:     } else {
 2515:       $result.=&escape($elem).'&';
 2516:     }
 2517:   }
 2518:   $result=~s/\&$//;
 2519:   $result .= '__END_ARRAY_REF__';
 2520:   return $result;
 2521: }
 2522: 
 2523: sub hash2str {
 2524:   my (%hash) = @_;
 2525:   my $result=&hashref2str(\%hash);
 2526:   $result=~s/^__HASH_REF__//;
 2527:   $result=~s/__END_HASH_REF__$//;
 2528:   return $result;
 2529: }
 2530: 
 2531: sub hashref2str {
 2532:   my ($hashref)=@_;
 2533:   my $result='__HASH_REF__';
 2534:   foreach my $key (sort(keys(%$hashref))) {
 2535:     if (ref($key) eq 'ARRAY') {
 2536:       $result.=&arrayref2str($key).'=';
 2537:     } elsif (ref($key) eq 'HASH') {
 2538:       $result.=&hashref2str($key).'=';
 2539:     } elsif (ref($key)) {
 2540:       $result.='=';
 2541:       #print("Got a ref of ".(ref($key))." skipping.");
 2542:     } else {
 2543: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2544:     }
 2545: 
 2546:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2547:       $result.=&arrayref2str($hashref->{$key}).'&';
 2548:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2549:       $result.=&hashref2str($hashref->{$key}).'&';
 2550:     } elsif(ref($hashref->{$key})) {
 2551:        $result.='&';
 2552:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2553:     } else {
 2554:       $result.=&escape($hashref->{$key}).'&';
 2555:     }
 2556:   }
 2557:   $result=~s/\&$//;
 2558:   $result .= '__END_HASH_REF__';
 2559:   return $result;
 2560: }
 2561: 
 2562: sub str2hash {
 2563:     my ($string)=@_;
 2564:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2565:     return %$hash;
 2566: }
 2567: 
 2568: sub str2hashref {
 2569:   my ($string) = @_;
 2570: 
 2571:   my %hash;
 2572: 
 2573:   if($string !~ /^__HASH_REF__/) {
 2574:       if (! ($string eq '' || !defined($string))) {
 2575: 	  $hash{'error'}='Not hash reference';
 2576:       }
 2577:       return (\%hash, $string);
 2578:   }
 2579: 
 2580:   $string =~ s/^__HASH_REF__//;
 2581: 
 2582:   while($string !~ /^__END_HASH_REF__/) {
 2583:       #key
 2584:       my $key='';
 2585:       if($string =~ /^__HASH_REF__/) {
 2586:           ($key, $string)=&str2hashref($string);
 2587:           if(defined($key->{'error'})) {
 2588:               $hash{'error'}='Bad data';
 2589:               return (\%hash, $string);
 2590:           }
 2591:       } elsif($string =~ /^__ARRAY_REF__/) {
 2592:           ($key, $string)=&str2arrayref($string);
 2593:           if($key->[0] eq 'Array reference error') {
 2594:               $hash{'error'}='Bad data';
 2595:               return (\%hash, $string);
 2596:           }
 2597:       } else {
 2598:           $string =~ s/^(.*?)=//;
 2599: 	  $key=&unescape($1);
 2600:       }
 2601:       $string =~ s/^=//;
 2602: 
 2603:       #value
 2604:       my $value='';
 2605:       if($string =~ /^__HASH_REF__/) {
 2606:           ($value, $string)=&str2hashref($string);
 2607:           if(defined($value->{'error'})) {
 2608:               $hash{'error'}='Bad data';
 2609:               return (\%hash, $string);
 2610:           }
 2611:       } elsif($string =~ /^__ARRAY_REF__/) {
 2612:           ($value, $string)=&str2arrayref($string);
 2613:           if($value->[0] eq 'Array reference error') {
 2614:               $hash{'error'}='Bad data';
 2615:               return (\%hash, $string);
 2616:           }
 2617:       } else {
 2618: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2619:       }
 2620:       $string =~ s/^&//;
 2621: 
 2622:       $hash{$key}=$value;
 2623:   }
 2624: 
 2625:   $string =~ s/^__END_HASH_REF__//;
 2626: 
 2627:   return (\%hash, $string);
 2628: }
 2629: 
 2630: sub str2array {
 2631:     my ($string)=@_;
 2632:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2633:     return @$array;
 2634: }
 2635: 
 2636: sub str2arrayref {
 2637:   my ($string) = @_;
 2638:   my @array;
 2639: 
 2640:   if($string !~ /^__ARRAY_REF__/) {
 2641:       if (! ($string eq '' || !defined($string))) {
 2642: 	  $array[0]='Array reference error';
 2643:       }
 2644:       return (\@array, $string);
 2645:   }
 2646: 
 2647:   $string =~ s/^__ARRAY_REF__//;
 2648: 
 2649:   while($string !~ /^__END_ARRAY_REF__/) {
 2650:       my $value='';
 2651:       if($string =~ /^__HASH_REF__/) {
 2652:           ($value, $string)=&str2hashref($string);
 2653:           if(defined($value->{'error'})) {
 2654:               $array[0] ='Array reference error';
 2655:               return (\@array, $string);
 2656:           }
 2657:       } elsif($string =~ /^__ARRAY_REF__/) {
 2658:           ($value, $string)=&str2arrayref($string);
 2659:           if($value->[0] eq 'Array reference error') {
 2660:               $array[0] ='Array reference error';
 2661:               return (\@array, $string);
 2662:           }
 2663:       } else {
 2664: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2665:       }
 2666:       $string =~ s/^&//;
 2667: 
 2668:       push(@array, $value);
 2669:   }
 2670: 
 2671:   $string =~ s/^__END_ARRAY_REF__//;
 2672: 
 2673:   return (\@array, $string);
 2674: }
 2675: 
 2676: # -------------------------------------------------------------------Temp Store
 2677: 
 2678: sub tmpreset {
 2679:   my ($symb,$namespace,$domain,$stuname) = @_;
 2680:   if (!$symb) {
 2681:     $symb=&symbread();
 2682:     if (!$symb) { $symb= $env{'request.url'}; }
 2683:   }
 2684:   $symb=escape($symb);
 2685: 
 2686:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2687:   $namespace=~s/\//\_/g;
 2688:   $namespace=~s/\W//g;
 2689: 
 2690:   if (!$domain) { $domain=$env{'user.domain'}; }
 2691:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2692:   if ($domain eq 'public' && $stuname eq 'public') {
 2693:       $stuname=$ENV{'REMOTE_ADDR'};
 2694:   }
 2695:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2696:   my %hash;
 2697:   if (tie(%hash,'GDBM_File',
 2698: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2699: 	  &GDBM_WRCREAT(),0640)) {
 2700:     foreach my $key (keys %hash) {
 2701:       if ($key=~ /:$symb/) {
 2702: 	delete($hash{$key});
 2703:       }
 2704:     }
 2705:   }
 2706: }
 2707: 
 2708: sub tmpstore {
 2709:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2710: 
 2711:   if (!$symb) {
 2712:     $symb=&symbread();
 2713:     if (!$symb) { $symb= $env{'request.url'}; }
 2714:   }
 2715:   $symb=escape($symb);
 2716: 
 2717:   if (!$namespace) {
 2718:     # I don't think we would ever want to store this for a course.
 2719:     # it seems this will only be used if we don't have a course.
 2720:     #$namespace=$env{'request.course.id'};
 2721:     #if (!$namespace) {
 2722:       $namespace=$env{'request.state'};
 2723:     #}
 2724:   }
 2725:   $namespace=~s/\//\_/g;
 2726:   $namespace=~s/\W//g;
 2727:   if (!$domain) { $domain=$env{'user.domain'}; }
 2728:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2729:   if ($domain eq 'public' && $stuname eq 'public') {
 2730:       $stuname=$ENV{'REMOTE_ADDR'};
 2731:   }
 2732:   my $now=time;
 2733:   my %hash;
 2734:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2735:   if (tie(%hash,'GDBM_File',
 2736: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2737: 	  &GDBM_WRCREAT(),0640)) {
 2738:     $hash{"version:$symb"}++;
 2739:     my $version=$hash{"version:$symb"};
 2740:     my $allkeys=''; 
 2741:     foreach my $key (keys(%$storehash)) {
 2742:       $allkeys.=$key.':';
 2743:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2744:     }
 2745:     $hash{"$version:$symb:timestamp"}=$now;
 2746:     $allkeys.='timestamp';
 2747:     $hash{"$version:keys:$symb"}=$allkeys;
 2748:     if (untie(%hash)) {
 2749:       return 'ok';
 2750:     } else {
 2751:       return "error:$!";
 2752:     }
 2753:   } else {
 2754:     return "error:$!";
 2755:   }
 2756: }
 2757: 
 2758: # -----------------------------------------------------------------Temp Restore
 2759: 
 2760: sub tmprestore {
 2761:   my ($symb,$namespace,$domain,$stuname) = @_;
 2762: 
 2763:   if (!$symb) {
 2764:     $symb=&symbread();
 2765:     if (!$symb) { $symb= $env{'request.url'}; }
 2766:   }
 2767:   $symb=escape($symb);
 2768: 
 2769:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2770: 
 2771:   if (!$domain) { $domain=$env{'user.domain'}; }
 2772:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2773:   if ($domain eq 'public' && $stuname eq 'public') {
 2774:       $stuname=$ENV{'REMOTE_ADDR'};
 2775:   }
 2776:   my %returnhash;
 2777:   $namespace=~s/\//\_/g;
 2778:   $namespace=~s/\W//g;
 2779:   my %hash;
 2780:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2781:   if (tie(%hash,'GDBM_File',
 2782: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2783: 	  &GDBM_READER(),0640)) {
 2784:     my $version=$hash{"version:$symb"};
 2785:     $returnhash{'version'}=$version;
 2786:     my $scope;
 2787:     for ($scope=1;$scope<=$version;$scope++) {
 2788:       my $vkeys=$hash{"$scope:keys:$symb"};
 2789:       my @keys=split(/:/,$vkeys);
 2790:       my $key;
 2791:       $returnhash{"$scope:keys"}=$vkeys;
 2792:       foreach $key (@keys) {
 2793: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2794: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2795:       }
 2796:     }
 2797:     if (!(untie(%hash))) {
 2798:       return "error:$!";
 2799:     }
 2800:   } else {
 2801:     return "error:$!";
 2802:   }
 2803:   return %returnhash;
 2804: }
 2805: 
 2806: # ----------------------------------------------------------------------- Store
 2807: 
 2808: sub store {
 2809:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2810:     my $home='';
 2811: 
 2812:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2813: 
 2814:     $symb=&symbclean($symb);
 2815:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2816: 
 2817:     if (!$domain) { $domain=$env{'user.domain'}; }
 2818:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2819: 
 2820:     &devalidate($symb,$stuname,$domain);
 2821: 
 2822:     $symb=escape($symb);
 2823:     if (!$namespace) { 
 2824:        unless ($namespace=$env{'request.course.id'}) { 
 2825:           return ''; 
 2826:        } 
 2827:     }
 2828:     if (!$home) { $home=$env{'user.home'}; }
 2829: 
 2830:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2831:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2832: 
 2833:     my $namevalue='';
 2834:     foreach my $key (keys(%$storehash)) {
 2835:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2836:     }
 2837:     $namevalue=~s/\&$//;
 2838:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2839:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2840: }
 2841: 
 2842: # -------------------------------------------------------------- Critical Store
 2843: 
 2844: sub cstore {
 2845:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2846:     my $home='';
 2847: 
 2848:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2849: 
 2850:     $symb=&symbclean($symb);
 2851:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2852: 
 2853:     if (!$domain) { $domain=$env{'user.domain'}; }
 2854:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2855: 
 2856:     &devalidate($symb,$stuname,$domain);
 2857: 
 2858:     $symb=escape($symb);
 2859:     if (!$namespace) { 
 2860:        unless ($namespace=$env{'request.course.id'}) { 
 2861:           return ''; 
 2862:        } 
 2863:     }
 2864:     if (!$home) { $home=$env{'user.home'}; }
 2865: 
 2866:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2867:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2868: 
 2869:     my $namevalue='';
 2870:     foreach my $key (keys(%$storehash)) {
 2871:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2872:     }
 2873:     $namevalue=~s/\&$//;
 2874:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2875:     return critical
 2876:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2877: }
 2878: 
 2879: # --------------------------------------------------------------------- Restore
 2880: 
 2881: sub restore {
 2882:     my ($symb,$namespace,$domain,$stuname) = @_;
 2883:     my $home='';
 2884: 
 2885:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2886: 
 2887:     if (!$symb) {
 2888:       unless ($symb=escape(&symbread())) { return ''; }
 2889:     } else {
 2890:       $symb=&escape(&symbclean($symb));
 2891:     }
 2892:     if (!$namespace) { 
 2893:        unless ($namespace=$env{'request.course.id'}) { 
 2894:           return ''; 
 2895:        } 
 2896:     }
 2897:     if (!$domain) { $domain=$env{'user.domain'}; }
 2898:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2899:     if (!$home) { $home=$env{'user.home'}; }
 2900:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2901: 
 2902:     my %returnhash=();
 2903:     foreach my $line (split(/\&/,$answer)) {
 2904: 	my ($name,$value)=split(/\=/,$line);
 2905:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2906:     }
 2907:     my $version;
 2908:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2909:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2910:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2911:        }
 2912:     }
 2913:     return %returnhash;
 2914: }
 2915: 
 2916: # ---------------------------------------------------------- Course Description
 2917: 
 2918: sub coursedescription {
 2919:     my ($courseid,$args)=@_;
 2920:     $courseid=~s/^\///;
 2921:     $courseid=~s/\_/\//g;
 2922:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2923:     my $chome=&homeserver($cnum,$cdomain);
 2924:     my $normalid=$cdomain.'_'.$cnum;
 2925:     # need to always cache even if we get errors otherwise we keep 
 2926:     # trying and trying and trying to get the course description.
 2927:     my %envhash=();
 2928:     my %returnhash=();
 2929:     
 2930:     my $expiretime=600;
 2931:     if ($env{'request.course.id'} eq $normalid) {
 2932: 	$expiretime=120;
 2933:     }
 2934: 
 2935:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2936:     if (!$args->{'freshen_cache'}
 2937: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2938: 	foreach my $key (keys(%env)) {
 2939: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2940: 	    my ($setting) = $1;
 2941: 	    $returnhash{$setting} = $env{$key};
 2942: 	}
 2943: 	return %returnhash;
 2944:     }
 2945: 
 2946:     # get the data agin
 2947:     if (!$args->{'one_time'}) {
 2948: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2949:     }
 2950: 
 2951:     if ($chome ne 'no_host') {
 2952:        %returnhash=&dump('environment',$cdomain,$cnum);
 2953:        if (!exists($returnhash{'con_lost'})) {
 2954:            $returnhash{'home'}= $chome;
 2955: 	   $returnhash{'domain'} = $cdomain;
 2956: 	   $returnhash{'num'} = $cnum;
 2957:            if (!defined($returnhash{'type'})) {
 2958:                $returnhash{'type'} = 'Course';
 2959:            }
 2960:            while (my ($name,$value) = each %returnhash) {
 2961:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2962:            }
 2963:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2964:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2965: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2966:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2967:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2968:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2969:        }
 2970:     }
 2971:     if (!$args->{'one_time'}) {
 2972: 	&appenv(%envhash);
 2973:     }
 2974:     return %returnhash;
 2975: }
 2976: 
 2977: # -------------------------------------------------See if a user is privileged
 2978: 
 2979: sub privileged {
 2980:     my ($username,$domain)=@_;
 2981:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2982: 			&homeserver($username,$domain));
 2983:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2984:     my $now=time;
 2985:     if ($rolesdump ne '') {
 2986:         foreach my $entry (split(/&/,$rolesdump)) {
 2987: 	    if ($entry!~/^rolesdef_/) {
 2988: 		my ($area,$role)=split(/=/,$entry);
 2989: 		$area=~s/\_\w\w$//;
 2990: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2991: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2992: 		    my $active=1;
 2993: 		    if ($tend) {
 2994: 			if ($tend<$now) { $active=0; }
 2995: 		    }
 2996: 		    if ($tstart) {
 2997: 			if ($tstart>$now) { $active=0; }
 2998: 		    }
 2999: 		    if ($active) { return 1; }
 3000: 		}
 3001: 	    }
 3002: 	}
 3003:     }
 3004:     return 0;
 3005: }
 3006: 
 3007: # -------------------------------------------------------- Get user privileges
 3008: 
 3009: sub rolesinit {
 3010:     my ($domain,$username,$authhost)=@_;
 3011:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3012:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3013:     my %allroles=();
 3014:     my %allgroups=();   
 3015:     my $now=time;
 3016:     my %userroles = ('user.login.time' => $now);
 3017:     my $group_privs;
 3018: 
 3019:     if ($rolesdump ne '') {
 3020:         foreach my $entry (split(/&/,$rolesdump)) {
 3021: 	  if ($entry!~/^rolesdef_/) {
 3022:             my ($area,$role)=split(/=/,$entry);
 3023: 	    $area=~s/\_\w\w$//;
 3024:             my ($trole,$tend,$tstart,$group_privs);
 3025: 	    if ($role=~/^cr/) { 
 3026: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3027: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3028: 		    ($tend,$tstart)=split('_',$trest);
 3029: 		} else {
 3030: 		    $trole=$role;
 3031: 		}
 3032:             } elsif ($role =~ m|^gr/|) {
 3033:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3034:                 ($trole,$group_privs) = split(/\//,$trole);
 3035:                 $group_privs = &unescape($group_privs);
 3036: 	    } else {
 3037: 		($trole,$tend,$tstart)=split(/_/,$role);
 3038: 	    }
 3039: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3040: 					 $username);
 3041: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3042:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3043:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3044:             if (($area ne '') && ($trole ne '')) {
 3045: 		my $spec=$trole.'.'.$area;
 3046: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3047: 		if ($trole =~ /^cr\//) {
 3048:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3049:                 } elsif ($trole eq 'gr') {
 3050:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3051: 		} else {
 3052:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3053: 		}
 3054:             }
 3055:           }
 3056:         }
 3057:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3058:         $userroles{'user.adv'}    = $adv;
 3059: 	$userroles{'user.author'} = $author;
 3060:         $env{'user.adv'}=$adv;
 3061:     }
 3062:     return \%userroles;  
 3063: }
 3064: 
 3065: sub set_arearole {
 3066:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3067: # log the associated role with the area
 3068:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3069:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3070: }
 3071: 
 3072: sub custom_roleprivs {
 3073:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3074:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3075:     my $homsvr=homeserver($rauthor,$rdomain);
 3076:     if (&hostname($homsvr) ne '') {
 3077:         my ($rdummy,$roledef)=
 3078:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3079:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3080:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3081:             if (defined($syspriv)) {
 3082:                 $$allroles{'cm./'}.=':'.$syspriv;
 3083:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3084:             }
 3085:             if ($tdomain ne '') {
 3086:                 if (defined($dompriv)) {
 3087:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3088:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3089:                 }
 3090:                 if (($trest ne '') && (defined($coursepriv))) {
 3091:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3092:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3093:                 }
 3094:             }
 3095:         }
 3096:     }
 3097: }
 3098: 
 3099: sub group_roleprivs {
 3100:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3101:     my $access = 1;
 3102:     my $now = time;
 3103:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3104:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3105:     if ($access) {
 3106:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3107:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3108:     }
 3109: }
 3110: 
 3111: sub standard_roleprivs {
 3112:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3113:     if (defined($pr{$trole.':s'})) {
 3114:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3115:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3116:     }
 3117:     if ($tdomain ne '') {
 3118:         if (defined($pr{$trole.':d'})) {
 3119:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3120:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3121:         }
 3122:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3123:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3124:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3125:         }
 3126:     }
 3127: }
 3128: 
 3129: sub set_userprivs {
 3130:     my ($userroles,$allroles,$allgroups) = @_; 
 3131:     my $author=0;
 3132:     my $adv=0;
 3133:     my %grouproles = ();
 3134:     if (keys(%{$allgroups}) > 0) {
 3135:         foreach my $role (keys %{$allroles}) {
 3136:             my ($trole,$area,$sec,$extendedarea);
 3137:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3138:                 $trole = $1;
 3139:                 $area = $2;
 3140:                 $sec = $3;
 3141:                 $extendedarea = $area.$sec;
 3142:                 if (exists($$allgroups{$area})) {
 3143:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3144:                         my $spec = $trole.'.'.$extendedarea;
 3145:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3146:                                                 $$allgroups{$area}{$group};
 3147:                     }
 3148:                 }
 3149:             }
 3150:         }
 3151:     }
 3152:     foreach my $group (keys(%grouproles)) {
 3153:         $$allroles{$group} = $grouproles{$group};
 3154:     }
 3155:     foreach my $role (keys(%{$allroles})) {
 3156:         my %thesepriv;
 3157:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3158:         foreach my $item (split(/:/,$$allroles{$role})) {
 3159:             if ($item ne '') {
 3160:                 my ($privilege,$restrictions)=split(/&/,$item);
 3161:                 if ($restrictions eq '') {
 3162:                     $thesepriv{$privilege}='F';
 3163:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3164:                     $thesepriv{$privilege}.=$restrictions;
 3165:                 }
 3166:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3167:             }
 3168:         }
 3169:         my $thesestr='';
 3170:         foreach my $priv (keys(%thesepriv)) {
 3171: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3172: 	}
 3173:         $userroles->{'user.priv.'.$role} = $thesestr;
 3174:     }
 3175:     return ($author,$adv);
 3176: }
 3177: 
 3178: # --------------------------------------------------------------- get interface
 3179: 
 3180: sub get {
 3181:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3182:    my $items='';
 3183:    foreach my $item (@$storearr) {
 3184:        $items.=&escape($item).'&';
 3185:    }
 3186:    $items=~s/\&$//;
 3187:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3188:    if (!$uname) { $uname=$env{'user.name'}; }
 3189:    my $uhome=&homeserver($uname,$udomain);
 3190: 
 3191:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3192:    my @pairs=split(/\&/,$rep);
 3193:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3194:      return @pairs;
 3195:    }
 3196:    my %returnhash=();
 3197:    my $i=0;
 3198:    foreach my $item (@$storearr) {
 3199:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3200:       $i++;
 3201:    }
 3202:    return %returnhash;
 3203: }
 3204: 
 3205: # --------------------------------------------------------------- del interface
 3206: 
 3207: sub del {
 3208:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3209:    my $items='';
 3210:    foreach my $item (@$storearr) {
 3211:        $items.=&escape($item).'&';
 3212:    }
 3213:    $items=~s/\&$//;
 3214:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3215:    if (!$uname) { $uname=$env{'user.name'}; }
 3216:    my $uhome=&homeserver($uname,$udomain);
 3217: 
 3218:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3219: }
 3220: 
 3221: # -------------------------------------------------------------- dump interface
 3222: 
 3223: sub dump {
 3224:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3225:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3226:     if (!$uname) { $uname=$env{'user.name'}; }
 3227:     my $uhome=&homeserver($uname,$udomain);
 3228:     if ($regexp) {
 3229: 	$regexp=&escape($regexp);
 3230:     } else {
 3231: 	$regexp='.';
 3232:     }
 3233:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3234:     my @pairs=split(/\&/,$rep);
 3235:     my %returnhash=();
 3236:     foreach my $item (@pairs) {
 3237: 	my ($key,$value)=split(/=/,$item,2);
 3238: 	$key = &unescape($key);
 3239: 	next if ($key =~ /^error: 2 /);
 3240: 	$returnhash{$key}=&thaw_unescape($value);
 3241:     }
 3242:     return %returnhash;
 3243: }
 3244: 
 3245: # --------------------------------------------------------- dumpstore interface
 3246: 
 3247: sub dumpstore {
 3248:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3249:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3250:    if (!$uname) { $uname=$env{'user.name'}; }
 3251:    my $uhome=&homeserver($uname,$udomain);
 3252:    if ($regexp) {
 3253:        $regexp=&escape($regexp);
 3254:    } else {
 3255:        $regexp='.';
 3256:    }
 3257:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3258:    my @pairs=split(/\&/,$rep);
 3259:    my %returnhash=();
 3260:    foreach my $item (@pairs) {
 3261:        my ($key,$value)=split(/=/,$item,2);
 3262:        next if ($key =~ /^error: 2 /);
 3263:        $returnhash{$key}=&thaw_unescape($value);
 3264:    }
 3265:    return %returnhash;
 3266: }
 3267: 
 3268: # -------------------------------------------------------------- keys interface
 3269: 
 3270: sub getkeys {
 3271:    my ($namespace,$udomain,$uname)=@_;
 3272:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3273:    if (!$uname) { $uname=$env{'user.name'}; }
 3274:    my $uhome=&homeserver($uname,$udomain);
 3275:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3276:    my @keyarray=();
 3277:    foreach my $key (split(/\&/,$rep)) {
 3278:       next if ($key =~ /^error: 2 /);
 3279:       push(@keyarray,&unescape($key));
 3280:    }
 3281:    return @keyarray;
 3282: }
 3283: 
 3284: # --------------------------------------------------------------- currentdump
 3285: sub currentdump {
 3286:    my ($courseid,$sdom,$sname)=@_;
 3287:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3288:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3289:    $sname    = $env{'user.name'}         if (! defined($sname));
 3290:    my $uhome = &homeserver($sname,$sdom);
 3291:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3292:    return if ($rep =~ /^(error:|no_such_host)/);
 3293:    #
 3294:    my %returnhash=();
 3295:    #
 3296:    if ($rep eq "unknown_cmd") { 
 3297:        # an old lond will not know currentdump
 3298:        # Do a dump and make it look like a currentdump
 3299:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3300:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3301:        my %hash = @tmp;
 3302:        @tmp=();
 3303:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3304:    } else {
 3305:        my @pairs=split(/\&/,$rep);
 3306:        foreach my $pair (@pairs) {
 3307:            my ($key,$value)=split(/=/,$pair,2);
 3308:            my ($symb,$param) = split(/:/,$key);
 3309:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3310:                                                         &thaw_unescape($value);
 3311:        }
 3312:    }
 3313:    return %returnhash;
 3314: }
 3315: 
 3316: sub convert_dump_to_currentdump{
 3317:     my %hash = %{shift()};
 3318:     my %returnhash;
 3319:     # Code ripped from lond, essentially.  The only difference
 3320:     # here is the unescaping done by lonnet::dump().  Conceivably
 3321:     # we might run in to problems with parameter names =~ /^v\./
 3322:     while (my ($key,$value) = each(%hash)) {
 3323:         my ($v,$symb,$param) = split(/:/,$key);
 3324: 	$symb  = &unescape($symb);
 3325: 	$param = &unescape($param);
 3326:         next if ($v eq 'version' || $symb eq 'keys');
 3327:         next if (exists($returnhash{$symb}) &&
 3328:                  exists($returnhash{$symb}->{$param}) &&
 3329:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3330:         $returnhash{$symb}->{$param}=$value;
 3331:         $returnhash{$symb}->{'v.'.$param}=$v;
 3332:     }
 3333:     #
 3334:     # Remove all of the keys in the hashes which keep track of
 3335:     # the version of the parameter.
 3336:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3337:         # use a foreach because we are going to delete from the hash.
 3338:         foreach my $key (keys(%$param_hash)) {
 3339:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3340:         }
 3341:     }
 3342:     return \%returnhash;
 3343: }
 3344: 
 3345: # ------------------------------------------------------ critical inc interface
 3346: 
 3347: sub cinc {
 3348:     return &inc(@_,'critical');
 3349: }
 3350: 
 3351: # --------------------------------------------------------------- inc interface
 3352: 
 3353: sub inc {
 3354:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3355:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3356:     if (!$uname) { $uname=$env{'user.name'}; }
 3357:     my $uhome=&homeserver($uname,$udomain);
 3358:     my $items='';
 3359:     if (! ref($store)) {
 3360:         # got a single value, so use that instead
 3361:         $items = &escape($store).'=&';
 3362:     } elsif (ref($store) eq 'SCALAR') {
 3363:         $items = &escape($$store).'=&';        
 3364:     } elsif (ref($store) eq 'ARRAY') {
 3365:         $items = join('=&',map {&escape($_);} @{$store});
 3366:     } elsif (ref($store) eq 'HASH') {
 3367:         while (my($key,$value) = each(%{$store})) {
 3368:             $items.= &escape($key).'='.&escape($value).'&';
 3369:         }
 3370:     }
 3371:     $items=~s/\&$//;
 3372:     if ($critical) {
 3373: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3374:     } else {
 3375: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3376:     }
 3377: }
 3378: 
 3379: # --------------------------------------------------------------- put interface
 3380: 
 3381: sub put {
 3382:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3383:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3384:    if (!$uname) { $uname=$env{'user.name'}; }
 3385:    my $uhome=&homeserver($uname,$udomain);
 3386:    my $items='';
 3387:    foreach my $item (keys(%$storehash)) {
 3388:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3389:    }
 3390:    $items=~s/\&$//;
 3391:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3392: }
 3393: 
 3394: # ------------------------------------------------------------ newput interface
 3395: 
 3396: sub newput {
 3397:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3399:    if (!$uname) { $uname=$env{'user.name'}; }
 3400:    my $uhome=&homeserver($uname,$udomain);
 3401:    my $items='';
 3402:    foreach my $key (keys(%$storehash)) {
 3403:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3404:    }
 3405:    $items=~s/\&$//;
 3406:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3407: }
 3408: 
 3409: # ---------------------------------------------------------  putstore interface
 3410: 
 3411: sub putstore {
 3412:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3413:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3414:    if (!$uname) { $uname=$env{'user.name'}; }
 3415:    my $uhome=&homeserver($uname,$udomain);
 3416:    my $items='';
 3417:    foreach my $key (keys(%$storehash)) {
 3418:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3419:    }
 3420:    $items=~s/\&$//;
 3421:    my $esc_symb=&escape($symb);
 3422:    my $esc_v=&escape($version);
 3423:    my $reply =
 3424:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3425: 	      $uhome);
 3426:    if ($reply eq 'unknown_cmd') {
 3427:        # gfall back to way things use to be done
 3428:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3429: 			    $uname);
 3430:    }
 3431:    return $reply;
 3432: }
 3433: 
 3434: sub old_putstore {
 3435:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3436:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3437:     if (!$uname) { $uname=$env{'user.name'}; }
 3438:     my $uhome=&homeserver($uname,$udomain);
 3439:     my %newstorehash;
 3440:     foreach my $item (keys(%$storehash)) {
 3441: 	my $key = $version.':'.&escape($symb).':'.$item;
 3442: 	$newstorehash{$key} = $storehash->{$item};
 3443:     }
 3444:     my $items='';
 3445:     my %allitems = ();
 3446:     foreach my $item (keys(%newstorehash)) {
 3447: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3448: 	    my $key = $1.':keys:'.$2;
 3449: 	    $allitems{$key} .= $3.':';
 3450: 	}
 3451: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3452:     }
 3453:     foreach my $item (keys(%allitems)) {
 3454: 	$allitems{$item} =~ s/\:$//;
 3455: 	$items.= $item.'='.$allitems{$item}.'&';
 3456:     }
 3457:     $items=~s/\&$//;
 3458:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3459: }
 3460: 
 3461: # ------------------------------------------------------ critical put interface
 3462: 
 3463: sub cput {
 3464:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3465:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3466:    if (!$uname) { $uname=$env{'user.name'}; }
 3467:    my $uhome=&homeserver($uname,$udomain);
 3468:    my $items='';
 3469:    foreach my $item (keys(%$storehash)) {
 3470:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3471:    }
 3472:    $items=~s/\&$//;
 3473:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3474: }
 3475: 
 3476: # -------------------------------------------------------------- eget interface
 3477: 
 3478: sub eget {
 3479:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3480:    my $items='';
 3481:    foreach my $item (@$storearr) {
 3482:        $items.=&escape($item).'&';
 3483:    }
 3484:    $items=~s/\&$//;
 3485:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3486:    if (!$uname) { $uname=$env{'user.name'}; }
 3487:    my $uhome=&homeserver($uname,$udomain);
 3488:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3489:    my @pairs=split(/\&/,$rep);
 3490:    my %returnhash=();
 3491:    my $i=0;
 3492:    foreach my $item (@$storearr) {
 3493:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3494:       $i++;
 3495:    }
 3496:    return %returnhash;
 3497: }
 3498: 
 3499: # ------------------------------------------------------------ tmpput interface
 3500: sub tmpput {
 3501:     my ($storehash,$server,$context)=@_;
 3502:     my $items='';
 3503:     foreach my $item (keys(%$storehash)) {
 3504: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3505:     }
 3506:     $items=~s/\&$//;
 3507:     if (defined($context)) {
 3508:         $items .= ':'.&escape($context);
 3509:     }
 3510:     return &reply("tmpput:$items",$server);
 3511: }
 3512: 
 3513: # ------------------------------------------------------------ tmpget interface
 3514: sub tmpget {
 3515:     my ($token,$server)=@_;
 3516:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3517:     my $rep=&reply("tmpget:$token",$server);
 3518:     my %returnhash;
 3519:     foreach my $item (split(/\&/,$rep)) {
 3520: 	my ($key,$value)=split(/=/,$item);
 3521: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3522:     }
 3523:     return %returnhash;
 3524: }
 3525: 
 3526: # ------------------------------------------------------------ tmpget interface
 3527: sub tmpdel {
 3528:     my ($token,$server)=@_;
 3529:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3530:     return &reply("tmpdel:$token",$server);
 3531: }
 3532: 
 3533: # -------------------------------------------------- portfolio access checking
 3534: 
 3535: sub portfolio_access {
 3536:     my ($requrl) = @_;
 3537:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3538:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3539:     if ($result) {
 3540:         my %setters;
 3541:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3542:             my ($startblock,$endblock) =
 3543:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3544:             if ($startblock && $endblock) {
 3545:                 return 'B';
 3546:             }
 3547:         } else {
 3548:             my ($startblock,$endblock) =
 3549:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3550:             if ($startblock && $endblock) {
 3551:                 return 'B';
 3552:             }
 3553:         }
 3554:     }
 3555:     if ($result eq 'ok') {
 3556:        return 'F';
 3557:     } elsif ($result =~ /^[^:]+:guest_/) {
 3558:        return 'A';
 3559:     }
 3560:     return '';
 3561: }
 3562: 
 3563: sub get_portfolio_access {
 3564:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3565: 
 3566:     if (!ref($access_hash)) {
 3567: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3568: 	my %access_controls = &get_access_controls($current_perms,$group,
 3569: 						   $file_name);
 3570: 	$access_hash = $access_controls{$file_name};
 3571:     }
 3572: 
 3573:     my ($public,$guest,@domains,@users,@courses,@groups);
 3574:     my $now = time;
 3575:     if (ref($access_hash) eq 'HASH') {
 3576:         foreach my $key (keys(%{$access_hash})) {
 3577:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3578:             if ($start > $now) {
 3579:                 next;
 3580:             }
 3581:             if ($end && $end<$now) {
 3582:                 next;
 3583:             }
 3584:             if ($scope eq 'public') {
 3585:                 $public = $key;
 3586:                 last;
 3587:             } elsif ($scope eq 'guest') {
 3588:                 $guest = $key;
 3589:             } elsif ($scope eq 'domains') {
 3590:                 push(@domains,$key);
 3591:             } elsif ($scope eq 'users') {
 3592:                 push(@users,$key);
 3593:             } elsif ($scope eq 'course') {
 3594:                 push(@courses,$key);
 3595:             } elsif ($scope eq 'group') {
 3596:                 push(@groups,$key);
 3597:             }
 3598:         }
 3599:         if ($public) {
 3600:             return 'ok';
 3601:         }
 3602:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3603:             if ($guest) {
 3604:                 return $guest;
 3605:             }
 3606:         } else {
 3607:             if (@domains > 0) {
 3608:                 foreach my $domkey (@domains) {
 3609:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3610:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3611:                             return 'ok';
 3612:                         }
 3613:                     }
 3614:                 }
 3615:             }
 3616:             if (@users > 0) {
 3617:                 foreach my $userkey (@users) {
 3618:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3619:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3620:                             if (ref($item) eq 'HASH') {
 3621:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3622:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3623:                                     return 'ok';
 3624:                                 }
 3625:                             }
 3626:                         }
 3627:                     } 
 3628:                 }
 3629:             }
 3630:             my %roleshash;
 3631:             my @courses_and_groups = @courses;
 3632:             push(@courses_and_groups,@groups); 
 3633:             if (@courses_and_groups > 0) {
 3634:                 my (%allgroups,%allroles); 
 3635:                 my ($start,$end,$role,$sec,$group);
 3636:                 foreach my $envkey (%env) {
 3637:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3638:                         my $cid = $2.'_'.$3; 
 3639:                         if ($1 eq 'gr') {
 3640:                             $group = $4;
 3641:                             $allgroups{$cid}{$group} = $env{$envkey};
 3642:                         } else {
 3643:                             if ($4 eq '') {
 3644:                                 $sec = 'none';
 3645:                             } else {
 3646:                                 $sec = $4;
 3647:                             }
 3648:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3649:                         }
 3650:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3651:                         my $cid = $2.'_'.$3;
 3652:                         if ($4 eq '') {
 3653:                             $sec = 'none';
 3654:                         } else {
 3655:                             $sec = $4;
 3656:                         }
 3657:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3658:                     }
 3659:                 }
 3660:                 if (keys(%allroles) == 0) {
 3661:                     return;
 3662:                 }
 3663:                 foreach my $key (@courses_and_groups) {
 3664:                     my %content = %{$$access_hash{$key}};
 3665:                     my $cnum = $content{'number'};
 3666:                     my $cdom = $content{'domain'};
 3667:                     my $cid = $cdom.'_'.$cnum;
 3668:                     if (!exists($allroles{$cid})) {
 3669:                         next;
 3670:                     }    
 3671:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3672:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3673:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3674:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3675:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3676:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3677:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3678:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3679:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3680:                                         if (grep/^all$/,@sections) {
 3681:                                             return 'ok';
 3682:                                         } else {
 3683:                                             if (grep/^$sec$/,@sections) {
 3684:                                                 return 'ok';
 3685:                                             }
 3686:                                         }
 3687:                                     }
 3688:                                 }
 3689:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3690:                                     if (grep/^none$/,@groups) {
 3691:                                         return 'ok';
 3692:                                     }
 3693:                                 } else {
 3694:                                     if (grep/^all$/,@groups) {
 3695:                                         return 'ok';
 3696:                                     } 
 3697:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3698:                                         if (grep/^$group$/,@groups) {
 3699:                                             return 'ok';
 3700:                                         }
 3701:                                     }
 3702:                                 } 
 3703:                             }
 3704:                         }
 3705:                     }
 3706:                 }
 3707:             }
 3708:             if ($guest) {
 3709:                 return $guest;
 3710:             }
 3711:         }
 3712:     }
 3713:     return;
 3714: }
 3715: 
 3716: sub course_group_datechecker {
 3717:     my ($dates,$now,$status) = @_;
 3718:     my ($start,$end) = split(/\./,$dates);
 3719:     if (!$start && !$end) {
 3720:         return 'ok';
 3721:     }
 3722:     if (grep/^active$/,@{$status}) {
 3723:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3724:             return 'ok';
 3725:         }
 3726:     }
 3727:     if (grep/^previous$/,@{$status}) {
 3728:         if ($end > $now ) {
 3729:             return 'ok';
 3730:         }
 3731:     }
 3732:     if (grep/^future$/,@{$status}) {
 3733:         if ($start > $now) {
 3734:             return 'ok';
 3735:         }
 3736:     }
 3737:     return; 
 3738: }
 3739: 
 3740: sub parse_portfolio_url {
 3741:     my ($url) = @_;
 3742: 
 3743:     my ($type,$udom,$unum,$group,$file_name);
 3744:     
 3745:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3746: 	$type = 1;
 3747:         $udom = $1;
 3748:         $unum = $2;
 3749:         $file_name = $3;
 3750:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3751: 	$type = 2;
 3752:         $udom = $1;
 3753:         $unum = $2;
 3754:         $group = $3;
 3755:         $file_name = $3.'/'.$4;
 3756:     }
 3757:     if (wantarray) {
 3758: 	return ($type,$udom,$unum,$file_name,$group);
 3759:     }
 3760:     return $type;
 3761: }
 3762: 
 3763: sub is_portfolio_url {
 3764:     my ($url) = @_;
 3765:     return scalar(&parse_portfolio_url($url));
 3766: }
 3767: 
 3768: sub is_portfolio_file {
 3769:     my ($file) = @_;
 3770:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3771:         return 1;
 3772:     }
 3773:     return;
 3774: }
 3775: 
 3776: 
 3777: # ---------------------------------------------- Custom access rule evaluation
 3778: 
 3779: sub customaccess {
 3780:     my ($priv,$uri)=@_;
 3781:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3782:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3783:     $udom = &LONCAPA::clean_domain($udom);
 3784:     $ucrs = &LONCAPA::clean_username($ucrs);
 3785:     my $access=0;
 3786:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3787: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3788:         if ($role) {
 3789: 	   if ($role ne $urole) { next; }
 3790:         }
 3791:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3792:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3793:             if ($tdom) {
 3794: 		if ($tdom ne $udom) { next; }
 3795:             }
 3796:             if ($tcrs) {
 3797: 		if ($tcrs ne $ucrs) { next; }
 3798:             }
 3799:             if ($tsec) {
 3800: 		if ($tsec ne $usec) { next; }
 3801:             }
 3802:             $access=($effect eq 'allow');
 3803:             last;
 3804:         }
 3805: 	if ($realm eq '' && $role eq '') {
 3806:             $access=($effect eq 'allow');
 3807: 	}
 3808:     }
 3809:     return $access;
 3810: }
 3811: 
 3812: # ------------------------------------------------- Check for a user privilege
 3813: 
 3814: sub allowed {
 3815:     my ($priv,$uri,$symb,$role)=@_;
 3816:     my $ver_orguri=$uri;
 3817:     $uri=&deversion($uri);
 3818:     my $orguri=$uri;
 3819:     $uri=&declutter($uri);
 3820: 
 3821:     if ($priv eq 'evb') {
 3822: # Evade communication block restrictions for specified role in a course
 3823:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3824:             return $1;
 3825:         } else {
 3826:             return;
 3827:         }
 3828:     }
 3829: 
 3830:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3831: # Free bre access to adm and meta resources
 3832:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3833: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3834: 	&& ($priv eq 'bre')) {
 3835: 	return 'F';
 3836:     }
 3837: 
 3838: # Free bre access to user's own portfolio contents
 3839:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3840:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3841: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3842:         my %setters;
 3843:         my ($startblock,$endblock) = 
 3844:             &Apache::loncommon::blockcheck(\%setters,'port');
 3845:         if ($startblock && $endblock) {
 3846:             return 'B';
 3847:         } else {
 3848:             return 'F';
 3849:         }
 3850:     }
 3851: 
 3852: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3853:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3854:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3855:         if (exists($env{'request.course.id'})) {
 3856:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3857:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3858:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3859:                 my $courseprivid=$env{'request.course.id'};
 3860:                 $courseprivid=~s/\_/\//;
 3861:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3862:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3863:                     return $1; 
 3864:                 } else {
 3865:                     if ($env{'request.course.sec'}) {
 3866:                         $courseprivid.='/'.$env{'request.course.sec'};
 3867:                     }
 3868:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3869:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3870:                         return $2;
 3871:                     }
 3872:                 }
 3873:             }
 3874:         }
 3875:     }
 3876: 
 3877: # Free bre to public access
 3878: 
 3879:     if ($priv eq 'bre') {
 3880:         my $copyright=&metadata($uri,'copyright');
 3881: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3882:            return 'F'; 
 3883:         }
 3884:         if ($copyright eq 'priv') {
 3885:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3886: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3887: 		return '';
 3888:             }
 3889:         }
 3890:         if ($copyright eq 'domain') {
 3891:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3892: 	    unless (($env{'user.domain'} eq $1) ||
 3893:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3894: 		return '';
 3895:             }
 3896:         }
 3897:         if ($env{'request.role'}=~ /li\.\//) {
 3898:             # Library role, so allow browsing of resources in this domain.
 3899:             return 'F';
 3900:         }
 3901:         if ($copyright eq 'custom') {
 3902: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3903:         }
 3904:     }
 3905:     # Domain coordinator is trying to create a course
 3906:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3907:         # uri is the requested domain in this case.
 3908:         # comparison to 'request.role.domain' shows if the user has selected
 3909:         # a role of dc for the domain in question.
 3910:         return 'F' if ($uri eq $env{'request.role.domain'});
 3911:     }
 3912: 
 3913:     my $thisallowed='';
 3914:     my $statecond=0;
 3915:     my $courseprivid='';
 3916: 
 3917: # Course
 3918: 
 3919:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3920:        $thisallowed.=$1;
 3921:     }
 3922: 
 3923: # Domain
 3924: 
 3925:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3926:        =~/\Q$priv\E\&([^\:]*)/) {
 3927:        $thisallowed.=$1;
 3928:     }
 3929: 
 3930: # Course: uri itself is a course
 3931:     my $courseuri=$uri;
 3932:     $courseuri=~s/\_(\d)/\/$1/;
 3933:     $courseuri=~s/^([^\/])/\/$1/;
 3934: 
 3935:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3936:        =~/\Q$priv\E\&([^\:]*)/) {
 3937:        $thisallowed.=$1;
 3938:     }
 3939: 
 3940: # URI is an uploaded document for this course, default permissions don't matter
 3941: # not allowing 'edit' access (editupload) to uploaded course docs
 3942:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3943: 	$thisallowed='';
 3944:         my ($match)=&is_on_map($uri);
 3945:         if ($match) {
 3946:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3947:                   =~/\Q$priv\E\&([^\:]*)/) {
 3948:                 $thisallowed.=$1;
 3949:             }
 3950:         } else {
 3951:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3952:             if ($refuri) {
 3953:                 if ($refuri =~ m|^/adm/|) {
 3954:                     $thisallowed='F';
 3955:                 } else {
 3956:                     $refuri=&declutter($refuri);
 3957:                     my ($match) = &is_on_map($refuri);
 3958:                     if ($match) {
 3959:                         $thisallowed='F';
 3960:                     }
 3961:                 }
 3962:             }
 3963:         }
 3964:     }
 3965: 
 3966:     if ($priv eq 'bre'
 3967: 	&& $thisallowed ne 'F' 
 3968: 	&& $thisallowed ne '2'
 3969: 	&& &is_portfolio_url($uri)) {
 3970: 	$thisallowed = &portfolio_access($uri);
 3971:     }
 3972:     
 3973: # Full access at system, domain or course-wide level? Exit.
 3974: 
 3975:     if ($thisallowed=~/F/) {
 3976: 	return 'F';
 3977:     }
 3978: 
 3979: # If this is generating or modifying users, exit with special codes
 3980: 
 3981:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3982: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3983: 	    my ($audom,$auname)=split('/',$uri);
 3984: # no author name given, so this just checks on the general right to make a co-author in this domain
 3985: 	    unless ($auname) { return $thisallowed; }
 3986: # an author name is given, so we are about to actually make a co-author for a certain account
 3987: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3988: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3989: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3990: 	}
 3991: 	return $thisallowed;
 3992:     }
 3993: #
 3994: # Gathered so far: system, domain and course wide privileges
 3995: #
 3996: # Course: See if uri or referer is an individual resource that is part of 
 3997: # the course
 3998: 
 3999:     if ($env{'request.course.id'}) {
 4000: 
 4001:        $courseprivid=$env{'request.course.id'};
 4002:        if ($env{'request.course.sec'}) {
 4003:           $courseprivid.='/'.$env{'request.course.sec'};
 4004:        }
 4005:        $courseprivid=~s/\_/\//;
 4006:        my $checkreferer=1;
 4007:        my ($match,$cond)=&is_on_map($uri);
 4008:        if ($match) {
 4009:            $statecond=$cond;
 4010:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4011:                =~/\Q$priv\E\&([^\:]*)/) {
 4012:                $thisallowed.=$1;
 4013:                $checkreferer=0;
 4014:            }
 4015:        }
 4016:        
 4017:        if ($checkreferer) {
 4018: 	  my $refuri=$env{'httpref.'.$orguri};
 4019:             unless ($refuri) {
 4020:                 foreach my $key (keys(%env)) {
 4021: 		    if ($key=~/^httpref\..*\*/) {
 4022: 			my $pattern=$key;
 4023:                         $pattern=~s/^httpref\.\/res\///;
 4024:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4025:                         $pattern=~s/\//\\\//g;
 4026:                         if ($orguri=~/$pattern/) {
 4027: 			    $refuri=$env{$key};
 4028:                         }
 4029:                     }
 4030:                 }
 4031:             }
 4032: 
 4033:          if ($refuri) { 
 4034: 	  $refuri=&declutter($refuri);
 4035:           my ($match,$cond)=&is_on_map($refuri);
 4036:             if ($match) {
 4037:               my $refstatecond=$cond;
 4038:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4039:                   =~/\Q$priv\E\&([^\:]*)/) {
 4040:                   $thisallowed.=$1;
 4041:                   $uri=$refuri;
 4042:                   $statecond=$refstatecond;
 4043:               }
 4044:           }
 4045:         }
 4046:        }
 4047:    }
 4048: 
 4049: #
 4050: # Gathered now: all privileges that could apply, and condition number
 4051: # 
 4052: #
 4053: # Full or no access?
 4054: #
 4055: 
 4056:     if ($thisallowed=~/F/) {
 4057: 	return 'F';
 4058:     }
 4059: 
 4060:     unless ($thisallowed) {
 4061:         return '';
 4062:     }
 4063: 
 4064: # Restrictions exist, deal with them
 4065: #
 4066: #   C:according to course preferences
 4067: #   R:according to resource settings
 4068: #   L:unless locked
 4069: #   X:according to user session state
 4070: #
 4071: 
 4072: # Possibly locked functionality, check all courses
 4073: # Locks might take effect only after 10 minutes cache expiration for other
 4074: # courses, and 2 minutes for current course
 4075: 
 4076:     my $envkey;
 4077:     if ($thisallowed=~/L/) {
 4078:         foreach $envkey (keys %env) {
 4079:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4080:                my $courseid=$2;
 4081:                my $roleid=$1.'.'.$2;
 4082:                $courseid=~s/^\///;
 4083:                my $expiretime=600;
 4084:                if ($env{'request.role'} eq $roleid) {
 4085: 		  $expiretime=120;
 4086:                }
 4087: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4088:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4089:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4090: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4091:                }
 4092:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4093:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4094: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4095:                        &log($env{'user.domain'},$env{'user.name'},
 4096:                             $env{'user.home'},
 4097:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4098:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4099:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4100: 		       return '';
 4101:                    }
 4102:                }
 4103:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4104:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4105: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4106:                        &log($env{'user.domain'},$env{'user.name'},
 4107:                             $env{'user.home'},
 4108:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4109:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4110:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4111: 		       return '';
 4112:                    }
 4113:                }
 4114: 	   }
 4115:        }
 4116:     }
 4117:    
 4118: #
 4119: # Rest of the restrictions depend on selected course
 4120: #
 4121: 
 4122:     unless ($env{'request.course.id'}) {
 4123: 	if ($thisallowed eq 'A') {
 4124: 	    return 'A';
 4125:         } elsif ($thisallowed eq 'B') {
 4126:             return 'B';
 4127: 	} else {
 4128: 	    return '1';
 4129: 	}
 4130:     }
 4131: 
 4132: #
 4133: # Now user is definitely in a course
 4134: #
 4135: 
 4136: 
 4137: # Course preferences
 4138: 
 4139:    if ($thisallowed=~/C/) {
 4140:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4141:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4142:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4143: 	   =~/\Q$rolecode\E/) {
 4144: 	   if ($priv ne 'pch') { 
 4145: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4146: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4147: 			$env{'request.course.id'});
 4148: 	   }
 4149:            return '';
 4150:        }
 4151: 
 4152:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4153: 	   =~/\Q$unamedom\E/) {
 4154: 	   if ($priv ne 'pch') { 
 4155: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4156: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4157: 			$env{'request.course.id'});
 4158: 	   }
 4159:            return '';
 4160:        }
 4161:    }
 4162: 
 4163: # Resource preferences
 4164: 
 4165:    if ($thisallowed=~/R/) {
 4166:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4167:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4168: 	   if ($priv ne 'pch') { 
 4169: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4170: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4171: 	   }
 4172: 	   return '';
 4173:        }
 4174:    }
 4175: 
 4176: # Restricted by state or randomout?
 4177: 
 4178:    if ($thisallowed=~/X/) {
 4179:       if ($env{'acc.randomout'}) {
 4180: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4181:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4182:             return ''; 
 4183:          }
 4184:       }
 4185:       if (&condval($statecond)) {
 4186: 	 return '2';
 4187:       } else {
 4188:          return '';
 4189:       }
 4190:    }
 4191: 
 4192:     if ($thisallowed eq 'A') {
 4193: 	return 'A';
 4194:     } elsif ($thisallowed eq 'B') {
 4195:         return 'B';
 4196:     }
 4197:    return 'F';
 4198: }
 4199: 
 4200: sub split_uri_for_cond {
 4201:     my $uri=&deversion(&declutter(shift));
 4202:     my @uriparts=split(/\//,$uri);
 4203:     my $filename=pop(@uriparts);
 4204:     my $pathname=join('/',@uriparts);
 4205:     return ($pathname,$filename);
 4206: }
 4207: # --------------------------------------------------- Is a resource on the map?
 4208: 
 4209: sub is_on_map {
 4210:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4211:     #Trying to find the conditional for the file
 4212:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4213: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4214:     if ($match) {
 4215: 	return (1,$1);
 4216:     } else {
 4217: 	return (0,0);
 4218:     }
 4219: }
 4220: 
 4221: # --------------------------------------------------------- Get symb from alias
 4222: 
 4223: sub get_symb_from_alias {
 4224:     my $symb=shift;
 4225:     my ($map,$resid,$url)=&decode_symb($symb);
 4226: # Already is a symb
 4227:     if ($url) { return $symb; }
 4228: # Must be an alias
 4229:     my $aliassymb='';
 4230:     my %bighash;
 4231:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4232:                             &GDBM_READER(),0640)) {
 4233:         my $rid=$bighash{'mapalias_'.$symb};
 4234: 	if ($rid) {
 4235: 	    my ($mapid,$resid)=split(/\./,$rid);
 4236: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4237: 				    $resid,$bighash{'src_'.$rid});
 4238: 	}
 4239:         untie %bighash;
 4240:     }
 4241:     return $aliassymb;
 4242: }
 4243: 
 4244: # ----------------------------------------------------------------- Define Role
 4245: 
 4246: sub definerole {
 4247:   if (allowed('mcr','/')) {
 4248:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4249:     foreach my $role (split(':',$sysrole)) {
 4250: 	my ($crole,$cqual)=split(/\&/,$role);
 4251:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4252:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4253: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4254:                return "refused:s:$crole&$cqual"; 
 4255:             }
 4256:         }
 4257:     }
 4258:     foreach my $role (split(':',$domrole)) {
 4259: 	my ($crole,$cqual)=split(/\&/,$role);
 4260:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4261:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4262: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4263:                return "refused:d:$crole&$cqual"; 
 4264:             }
 4265:         }
 4266:     }
 4267:     foreach my $role (split(':',$courole)) {
 4268: 	my ($crole,$cqual)=split(/\&/,$role);
 4269:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4270:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4271: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4272:                return "refused:c:$crole&$cqual"; 
 4273:             }
 4274:         }
 4275:     }
 4276:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4277:                 "$env{'user.domain'}:$env{'user.name'}:".
 4278: 	        "rolesdef_$rolename=".
 4279:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4280:     return reply($command,$env{'user.home'});
 4281:   } else {
 4282:     return 'refused';
 4283:   }
 4284: }
 4285: 
 4286: # ---------------- Make a metadata query against the network of library servers
 4287: 
 4288: sub metadata_query {
 4289:     my ($query,$custom,$customshow,$server_array)=@_;
 4290:     my %rhash;
 4291:     my %libserv = &all_library();
 4292:     my @server_list = (defined($server_array) ? @$server_array
 4293:                                               : keys(%libserv) );
 4294:     for my $server (@server_list) {
 4295: 	unless ($custom or $customshow) {
 4296: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4297: 	    $rhash{$server}=$reply;
 4298: 	}
 4299: 	else {
 4300: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4301: 			     &escape($custom).':'.&escape($customshow),
 4302: 			     $server);
 4303: 	    $rhash{$server}=$reply;
 4304: 	}
 4305:     }
 4306:     return \%rhash;
 4307: }
 4308: 
 4309: # ----------------------------------------- Send log queries and wait for reply
 4310: 
 4311: sub log_query {
 4312:     my ($uname,$udom,$query,%filters)=@_;
 4313:     my $uhome=&homeserver($uname,$udom);
 4314:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4315:     my $uhost=&hostname($uhome);
 4316:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4317:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4318:                        $uhome);
 4319:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4320:     return get_query_reply($queryid);
 4321: }
 4322: 
 4323: # -------------------------- Update MySQL table for portfolio file
 4324: 
 4325: sub update_portfolio_table {
 4326:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4327:     my $homeserver = &homeserver($uname,$udom);
 4328:     my $queryid=
 4329:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4330:                ':'.&escape($file_name).':'.$action,$homeserver);
 4331:     my $reply = &get_query_reply($queryid);
 4332:     return $reply;
 4333: }
 4334: 
 4335: # ------- Request retrieval of institutional classlists for course(s)
 4336: 
 4337: sub fetch_enrollment_query {
 4338:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4339:     my $homeserver;
 4340:     my $maxtries = 1;
 4341:     if ($context eq 'automated') {
 4342:         $homeserver = $perlvar{'lonHostID'};
 4343:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4344:     } else {
 4345:         $homeserver = &homeserver($cnum,$dom);
 4346:     }
 4347:     my $host=&hostname($homeserver);
 4348:     my $cmd = '';
 4349:     foreach my $affiliate (keys %{$affiliatesref}) {
 4350:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4351:     }
 4352:     $cmd =~ s/%%$//;
 4353:     $cmd = &escape($cmd);
 4354:     my $query = 'fetchenrollment';
 4355:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4356:     unless ($queryid=~/^\Q$host\E\_/) { 
 4357:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4358:         return 'error: '.$queryid;
 4359:     }
 4360:     my $reply = &get_query_reply($queryid);
 4361:     my $tries = 1;
 4362:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4363:         $reply = &get_query_reply($queryid);
 4364:         $tries ++;
 4365:     }
 4366:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4367:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4368:     } else {
 4369:         my @responses = split/:/,$reply;
 4370:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4371:             foreach my $line (@responses) {
 4372:                 my ($key,$value) = split(/=/,$line,2);
 4373:                 $$replyref{$key} = $value;
 4374:             }
 4375:         } else {
 4376:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4377:             foreach my $line (@responses) {
 4378:                 my ($key,$value) = split(/=/,$line);
 4379:                 $$replyref{$key} = $value;
 4380:                 if ($value > 0) {
 4381:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4382:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4383:                         my $destname = $pathname.'/'.$filename;
 4384:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4385:                         if ($xml_classlist =~ /^error/) {
 4386:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4387:                         } else {
 4388:                             if ( open(FILE,">$destname") ) {
 4389:                                 print FILE &unescape($xml_classlist);
 4390:                                 close(FILE);
 4391:                             } else {
 4392:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4393:                             }
 4394:                         }
 4395:                     }
 4396:                 }
 4397:             }
 4398:         }
 4399:         return 'ok';
 4400:     }
 4401:     return 'error';
 4402: }
 4403: 
 4404: sub get_query_reply {
 4405:     my $queryid=shift;
 4406:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4407:     my $reply='';
 4408:     for (1..100) {
 4409: 	sleep 2;
 4410:         if (-e $replyfile.'.end') {
 4411: 	    if (open(my $fh,$replyfile)) {
 4412:                $reply.=<$fh>;
 4413:                close($fh);
 4414: 	   } else { return 'error: reply_file_error'; }
 4415:            return &unescape($reply);
 4416: 	}
 4417:     }
 4418:     return 'timeout:'.$queryid;
 4419: }
 4420: 
 4421: sub courselog_query {
 4422: #
 4423: # possible filters:
 4424: # url: url or symb
 4425: # username
 4426: # domain
 4427: # action: view, submit, grade
 4428: # start: timestamp
 4429: # end: timestamp
 4430: #
 4431:     my (%filters)=@_;
 4432:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4433:     if ($filters{'url'}) {
 4434: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4435:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4436:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4437:     }
 4438:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4439:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4440:     return &log_query($cname,$cdom,'courselog',%filters);
 4441: }
 4442: 
 4443: sub userlog_query {
 4444: #
 4445: # possible filters:
 4446: # action: log check role
 4447: # start: timestamp
 4448: # end: timestamp
 4449: #
 4450:     my ($uname,$udom,%filters)=@_;
 4451:     return &log_query($uname,$udom,'userlog',%filters);
 4452: }
 4453: 
 4454: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4455: 
 4456: sub auto_run {
 4457:     my ($cnum,$cdom) = @_;
 4458:     my $homeserver = &homeserver($cnum,$cdom);
 4459:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4460:     return $response;
 4461: }
 4462: 
 4463: sub auto_get_sections {
 4464:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4465:     my $homeserver = &homeserver($cnum,$cdom);
 4466:     my @secs = ();
 4467:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4468:     unless ($response eq 'refused') {
 4469:         @secs = split/:/,$response;
 4470:     }
 4471:     return @secs;
 4472: }
 4473: 
 4474: sub auto_new_course {
 4475:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4476:     my $homeserver = &homeserver($cnum,$cdom);
 4477:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4478:     return $response;
 4479: }
 4480: 
 4481: sub auto_validate_courseID {
 4482:     my ($cnum,$cdom,$inst_course_id) = @_;
 4483:     my $homeserver = &homeserver($cnum,$cdom);
 4484:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4485:     return $response;
 4486: }
 4487: 
 4488: sub auto_create_password {
 4489:     my ($cnum,$cdom,$authparam) = @_;
 4490:     my $homeserver = &homeserver($cnum,$cdom); 
 4491:     my $create_passwd = 0;
 4492:     my $authchk = '';
 4493:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4494:     if ($response eq 'refused') {
 4495:         $authchk = 'refused';
 4496:     } else {
 4497:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4498:     }
 4499:     return ($authparam,$create_passwd,$authchk);
 4500: }
 4501: 
 4502: sub auto_photo_permission {
 4503:     my ($cnum,$cdom,$students) = @_;
 4504:     my $homeserver = &homeserver($cnum,$cdom);
 4505:     my ($outcome,$perm_reqd,$conditions) = 
 4506: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4507:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4508: 	return (undef,undef);
 4509:     }
 4510:     return ($outcome,$perm_reqd,$conditions);
 4511: }
 4512: 
 4513: sub auto_checkphotos {
 4514:     my ($uname,$udom,$pid) = @_;
 4515:     my $homeserver = &homeserver($uname,$udom);
 4516:     my ($result,$resulttype);
 4517:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4518: 				   &escape($uname).':'.&escape($pid),
 4519: 				   $homeserver));
 4520:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4521: 	return (undef,undef);
 4522:     }
 4523:     if ($outcome) {
 4524:         ($result,$resulttype) = split(/:/,$outcome);
 4525:     } 
 4526:     return ($result,$resulttype);
 4527: }
 4528: 
 4529: sub auto_photochoice {
 4530:     my ($cnum,$cdom) = @_;
 4531:     my $homeserver = &homeserver($cnum,$cdom);
 4532:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4533: 						       &escape($cdom),
 4534: 						       $homeserver)));
 4535:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4536: 	return (undef,undef);
 4537:     }
 4538:     return ($update,$comment);
 4539: }
 4540: 
 4541: sub auto_photoupdate {
 4542:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4543:     my $homeserver = &homeserver($cnum,$dom);
 4544:     my $host=&hostname($homeserver);
 4545:     my $cmd = '';
 4546:     my $maxtries = 1;
 4547:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4548:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4549:     }
 4550:     $cmd =~ s/%%$//;
 4551:     $cmd = &escape($cmd);
 4552:     my $query = 'institutionalphotos';
 4553:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4554:     unless ($queryid=~/^\Q$host\E\_/) {
 4555:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4556:         return 'error: '.$queryid;
 4557:     }
 4558:     my $reply = &get_query_reply($queryid);
 4559:     my $tries = 1;
 4560:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4561:         $reply = &get_query_reply($queryid);
 4562:         $tries ++;
 4563:     }
 4564:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4565:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4566:     } else {
 4567:         my @responses = split(/:/,$reply);
 4568:         my $outcome = shift(@responses); 
 4569:         foreach my $item (@responses) {
 4570:             my ($key,$value) = split(/=/,$item);
 4571:             $$photo{$key} = $value;
 4572:         }
 4573:         return $outcome;
 4574:     }
 4575:     return 'error';
 4576: }
 4577: 
 4578: sub auto_instcode_format {
 4579:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4580: 	$cat_order) = @_;
 4581:     my $courses = '';
 4582:     my @homeservers;
 4583:     if ($caller eq 'global') {
 4584: 	my %servers = &get_servers($codedom,'library');
 4585: 	foreach my $tryserver (keys(%servers)) {
 4586: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4587: 		push(@homeservers,$tryserver);
 4588: 	    }
 4589:         }
 4590:     } else {
 4591:         push(@homeservers,&homeserver($caller,$codedom));
 4592:     }
 4593:     foreach my $code (keys(%{$instcodes})) {
 4594:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4595:     }
 4596:     chop($courses);
 4597:     my $ok_response = 0;
 4598:     my $response;
 4599:     while (@homeservers > 0 && $ok_response == 0) {
 4600:         my $server = shift(@homeservers); 
 4601:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4602:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4603:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4604: 		split/:/,$response;
 4605:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4606:             push(@{$codetitles},&str2array($codetitles_str));
 4607:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4608:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4609:             $ok_response = 1;
 4610:         }
 4611:     }
 4612:     if ($ok_response) {
 4613:         return 'ok';
 4614:     } else {
 4615:         return $response;
 4616:     }
 4617: }
 4618: 
 4619: sub auto_instcode_defaults {
 4620:     my ($domain,$returnhash,$code_order) = @_;
 4621:     my @homeservers;
 4622: 
 4623:     my %servers = &get_servers($domain,'library');
 4624:     foreach my $tryserver (keys(%servers)) {
 4625: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4626: 	    push(@homeservers,$tryserver);
 4627: 	}
 4628:     }
 4629: 
 4630:     my $response;
 4631:     foreach my $server (@homeservers) {
 4632:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4633:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4634: 	
 4635: 	foreach my $pair (split(/\&/,$response)) {
 4636: 	    my ($name,$value)=split(/\=/,$pair);
 4637: 	    if ($name eq 'code_order') {
 4638: 		@{$code_order} = split(/\&/,&unescape($value));
 4639: 	    } else {
 4640: 		$returnhash->{&unescape($name)}=&unescape($value);
 4641: 	    }
 4642: 	}
 4643: 	return 'ok';
 4644:     }
 4645: 
 4646:     return $response;
 4647: } 
 4648: 
 4649: sub auto_validate_class_sec {
 4650:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4651:     my $homeserver = &homeserver($cnum,$cdom);
 4652:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4653:                         &escape($owner).':'.$cdom,$homeserver);
 4654:     return $response;
 4655: }
 4656: 
 4657: # ------------------------------------------------------- Course Group routines
 4658: 
 4659: sub get_coursegroups {
 4660:     my ($cdom,$cnum,$group,$namespace) = @_;
 4661:     return(&dump($namespace,$cdom,$cnum,$group));
 4662: }
 4663: 
 4664: sub modify_coursegroup {
 4665:     my ($cdom,$cnum,$groupsettings) = @_;
 4666:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4667: }
 4668: 
 4669: sub toggle_coursegroup_status {
 4670:     my ($cdom,$cnum,$group,$action) = @_;
 4671:     my ($from_namespace,$to_namespace);
 4672:     if ($action eq 'delete') {
 4673:         $from_namespace = 'coursegroups';
 4674:         $to_namespace = 'deleted_groups';
 4675:     } else {
 4676:         $from_namespace = 'deleted_groups';
 4677:         $to_namespace = 'coursegroups';
 4678:     }
 4679:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4680:     if (my $tmp = &error(%curr_group)) {
 4681:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4682:         return ('read error',$tmp);
 4683:     } else {
 4684:         my %savedsettings = %curr_group; 
 4685:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4686:         my $deloutcome;
 4687:         if ($result eq 'ok') {
 4688:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4689:         } else {
 4690:             return ('write error',$result);
 4691:         }
 4692:         if ($deloutcome eq 'ok') {
 4693:             return 'ok';
 4694:         } else {
 4695:             return ('delete error',$deloutcome);
 4696:         }
 4697:     }
 4698: }
 4699: 
 4700: sub modify_group_roles {
 4701:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4702:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4703:     my $role = 'gr/'.&escape($userprivs);
 4704:     my ($uname,$udom) = split(/:/,$user);
 4705:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4706:     if ($result eq 'ok') {
 4707:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4708:     }
 4709:     return $result;
 4710: }
 4711: 
 4712: sub modify_coursegroup_membership {
 4713:     my ($cdom,$cnum,$membership) = @_;
 4714:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4715:     return $result;
 4716: }
 4717: 
 4718: sub get_active_groups {
 4719:     my ($udom,$uname,$cdom,$cnum) = @_;
 4720:     my $now = time;
 4721:     my %groups = ();
 4722:     foreach my $key (keys(%env)) {
 4723:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4724:             my ($start,$end) = split(/\./,$env{$key});
 4725:             if (($end!=0) && ($end<$now)) { next; }
 4726:             if (($start!=0) && ($start>$now)) { next; }
 4727:             if ($1 eq $cdom && $2 eq $cnum) {
 4728:                 $groups{$3} = $env{$key} ;
 4729:             }
 4730:         }
 4731:     }
 4732:     return %groups;
 4733: }
 4734: 
 4735: sub get_group_membership {
 4736:     my ($cdom,$cnum,$group) = @_;
 4737:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4738: }
 4739: 
 4740: sub get_users_groups {
 4741:     my ($udom,$uname,$courseid) = @_;
 4742:     my @usersgroups;
 4743:     my $cachetime=1800;
 4744: 
 4745:     my $hashid="$udom:$uname:$courseid";
 4746:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4747:     if (defined($cached)) {
 4748:         @usersgroups = split(/:/,$grouplist);
 4749:     } else {  
 4750:         $grouplist = '';
 4751:         my $courseurl = &courseid_to_courseurl($courseid);
 4752:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4753:         my $access_end = $env{'course.'.$courseid.
 4754:                               '.default_enrollment_end_date'};
 4755:         my $now = time;
 4756:         foreach my $key (keys(%roleshash)) {
 4757:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4758:                 my $group = $1;
 4759:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4760:                     my $start = $2;
 4761:                     my $end = $1;
 4762:                     if ($start == -1) { next; } # deleted from group
 4763:                     if (($start!=0) && ($start>$now)) { next; }
 4764:                     if (($end!=0) && ($end<$now)) {
 4765:                         if ($access_end && $access_end < $now) {
 4766:                             if ($access_end - $end < 86400) {
 4767:                                 push(@usersgroups,$group);
 4768:                             }
 4769:                         }
 4770:                         next;
 4771:                     }
 4772:                     push(@usersgroups,$group);
 4773:                 }
 4774:             }
 4775:         }
 4776:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4777:         $grouplist = join(':',@usersgroups);
 4778:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4779:     }
 4780:     return @usersgroups;
 4781: }
 4782: 
 4783: sub devalidate_getgroups_cache {
 4784:     my ($udom,$uname,$cdom,$cnum)=@_;
 4785:     my $courseid = $cdom.'_'.$cnum;
 4786: 
 4787:     my $hashid="$udom:$uname:$courseid";
 4788:     &devalidate_cache_new('getgroups',$hashid);
 4789: }
 4790: 
 4791: # ------------------------------------------------------------------ Plain Text
 4792: 
 4793: sub plaintext {
 4794:     my ($short,$type,$cid) = @_;
 4795:     if ($short =~ /^cr/) {
 4796: 	return (split('/',$short))[-1];
 4797:     }
 4798:     if (!defined($cid)) {
 4799:         $cid = $env{'request.course.id'};
 4800:     }
 4801:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4802:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4803:                                           '.plaintext'});
 4804:     }
 4805:     my %rolenames = (
 4806:                       Course => 'std',
 4807:                       Group => 'alt1',
 4808:                     );
 4809:     if (defined($type) && 
 4810:          defined($rolenames{$type}) && 
 4811:          defined($prp{$short}{$rolenames{$type}})) {
 4812:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4813:     } else {
 4814:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4815:     }
 4816: }
 4817: 
 4818: # ----------------------------------------------------------------- Assign Role
 4819: 
 4820: sub assignrole {
 4821:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4822:     my $mrole;
 4823:     if ($role =~ /^cr\//) {
 4824:         my $cwosec=$url;
 4825:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4826: 	unless (&allowed('ccr',$cwosec)) {
 4827:            &logthis('Refused custom assignrole: '.
 4828:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4829: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4830:            return 'refused'; 
 4831:         }
 4832:         $mrole='cr';
 4833:     } elsif ($role =~ /^gr\//) {
 4834:         my $cwogrp=$url;
 4835:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4836:         unless (&allowed('mdg',$cwogrp)) {
 4837:             &logthis('Refused group assignrole: '.
 4838:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4839:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4840:             return 'refused';
 4841:         }
 4842:         $mrole='gr';
 4843:     } else {
 4844:         my $cwosec=$url;
 4845:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4846:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4847:            &logthis('Refused assignrole: '.
 4848:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4849: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4850:            return 'refused'; 
 4851:         }
 4852:         $mrole=$role;
 4853:     }
 4854:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4855:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4856:     if ($end) { $command.='_'.$end; }
 4857:     if ($start) {
 4858: 	if ($end) { 
 4859:            $command.='_'.$start; 
 4860:         } else {
 4861:            $command.='_0_'.$start;
 4862:         }
 4863:     }
 4864:     my $origstart = $start;
 4865:     my $origend = $end;
 4866: # actually delete
 4867:     if ($deleteflag) {
 4868: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4869: # modify command to delete the role
 4870:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4871:                 "$udom:$uname:$url".'_'."$mrole";
 4872: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4873: # set start and finish to negative values for userrolelog
 4874:            $start=-1;
 4875:            $end=-1;
 4876:         }
 4877:     }
 4878: # send command
 4879:     my $answer=&reply($command,&homeserver($uname,$udom));
 4880: # log new user role if status is ok
 4881:     if ($answer eq 'ok') {
 4882: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4883: # for course roles, perform group memberships changes triggered by role change.
 4884:         unless ($role =~ /^gr/) {
 4885:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4886:                                              $origstart);
 4887:         }
 4888:     }
 4889:     return $answer;
 4890: }
 4891: 
 4892: # -------------------------------------------------- Modify user authentication
 4893: # Overrides without validation
 4894: 
 4895: sub modifyuserauth {
 4896:     my ($udom,$uname,$umode,$upass)=@_;
 4897:     my $uhome=&homeserver($uname,$udom);
 4898:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4899:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4900:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4901:              ' in domain '.$env{'request.role.domain'});  
 4902:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4903: 		     &escape($upass),$uhome);
 4904:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4905:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4906:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4907:     &log($udom,,$uname,$uhome,
 4908:         'Authentication changed by '.$env{'user.domain'}.', '.
 4909:                                      $env{'user.name'}.', '.$umode.
 4910:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4911:     unless ($reply eq 'ok') {
 4912:         &logthis('Authentication mode error: '.$reply);
 4913: 	return 'error: '.$reply;
 4914:     }   
 4915:     return 'ok';
 4916: }
 4917: 
 4918: # --------------------------------------------------------------- Modify a user
 4919: 
 4920: sub modifyuser {
 4921:     my ($udom,    $uname, $uid,
 4922:         $umode,   $upass, $first,
 4923:         $middle,  $last,  $gene,
 4924:         $forceid, $desiredhome, $email)=@_;
 4925:     $udom= &LONCAPA::clean_domain($udom);
 4926:     $uname=&LONCAPA::clean_username($uname);
 4927:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4928:              $umode.', '.$first.', '.$middle.', '.
 4929: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4930:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4931:                                      ' desiredhome not specified'). 
 4932:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4933:              ' in domain '.$env{'request.role.domain'});
 4934:     my $uhome=&homeserver($uname,$udom,'true');
 4935: # ----------------------------------------------------------------- Create User
 4936:     if (($uhome eq 'no_host') && 
 4937: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4938:         my $unhome='';
 4939:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4940:             $unhome = $desiredhome;
 4941: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4942: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4943:         } else { # load balancing routine for determining $unhome
 4944:             my $loadm=10000000;
 4945: 	    my %servers = &get_servers($udom,'library');
 4946: 	    foreach my $tryserver (keys(%servers)) {
 4947: 		my $answer=reply('load',$tryserver);
 4948: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4949: 		    $loadm=$answer;
 4950: 		    $unhome=$tryserver;
 4951: 		}
 4952: 	    }
 4953:         }
 4954:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4955: 	    return 'error: unable to find a home server for '.$uname.
 4956:                    ' in domain '.$udom;
 4957:         }
 4958:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4959:                          &escape($upass),$unhome);
 4960: 	unless ($reply eq 'ok') {
 4961:             return 'error: '.$reply;
 4962:         }   
 4963:         $uhome=&homeserver($uname,$udom,'true');
 4964:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4965: 	    return 'error: unable verify users home machine.';
 4966:         }
 4967:     }   # End of creation of new user
 4968: # ---------------------------------------------------------------------- Add ID
 4969:     if ($uid) {
 4970:        $uid=~tr/A-Z/a-z/;
 4971:        my %uidhash=&idrget($udom,$uname);
 4972:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4973:          && (!$forceid)) {
 4974: 	  unless ($uid eq $uidhash{$uname}) {
 4975: 	      return 'error: user id "'.$uid.'" does not match '.
 4976:                   'current user id "'.$uidhash{$uname}.'".';
 4977:           }
 4978:        } else {
 4979: 	  &idput($udom,($uname => $uid));
 4980:        }
 4981:     }
 4982: # -------------------------------------------------------------- Add names, etc
 4983:     my @tmp=&get('environment',
 4984: 		   ['firstname','middlename','lastname','generation'],
 4985: 		   $udom,$uname);
 4986:     my %names;
 4987:     if ($tmp[0] =~ m/^error:.*/) { 
 4988:         %names=(); 
 4989:     } else {
 4990:         %names = @tmp;
 4991:     }
 4992: #
 4993: # Make sure to not trash student environment if instructor does not bother
 4994: # to supply name and email information
 4995: #
 4996:     if ($first)  { $names{'firstname'}  = $first; }
 4997:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4998:     if ($last)   { $names{'lastname'}   = $last; }
 4999:     if (defined($gene))   { $names{'generation'} = $gene; }
 5000:     if ($email) {
 5001:        $email=~s/[^\w\@\.\-\,]//gs;
 5002:        if ($email=~/\@/) { $names{'notification'} = $email;
 5003: 			   $names{'critnotification'} = $email;
 5004: 			   $names{'permanentemail'} = $email; }
 5005:     }
 5006:     my $reply = &put('environment', \%names, $udom,$uname);
 5007:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5008:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5009:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5010:              $umode.', '.$first.', '.$middle.', '.
 5011: 	     $last.', '.$gene.' by '.
 5012:              $env{'user.name'}.' at '.$env{'user.domain'});
 5013:     return 'ok';
 5014: }
 5015: 
 5016: # -------------------------------------------------------------- Modify student
 5017: 
 5018: sub modifystudent {
 5019:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5020:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5021:     if (!$cid) {
 5022: 	unless ($cid=$env{'request.course.id'}) {
 5023: 	    return 'not_in_class';
 5024: 	}
 5025:     }
 5026: # --------------------------------------------------------------- Make the user
 5027:     my $reply=&modifyuser
 5028: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5029:          $desiredhome,$email);
 5030:     unless ($reply eq 'ok') { return $reply; }
 5031:     # This will cause &modify_student_enrollment to get the uid from the
 5032:     # students environment
 5033:     $uid = undef if (!$forceid);
 5034:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5035: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5036:     return $reply;
 5037: }
 5038: 
 5039: sub modify_student_enrollment {
 5040:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5041:     my ($cdom,$cnum,$chome);
 5042:     if (!$cid) {
 5043: 	unless ($cid=$env{'request.course.id'}) {
 5044: 	    return 'not_in_class';
 5045: 	}
 5046: 	$cdom=$env{'course.'.$cid.'.domain'};
 5047: 	$cnum=$env{'course.'.$cid.'.num'};
 5048:     } else {
 5049: 	($cdom,$cnum)=split(/_/,$cid);
 5050:     }
 5051:     $chome=$env{'course.'.$cid.'.home'};
 5052:     if (!$chome) {
 5053: 	$chome=&homeserver($cnum,$cdom);
 5054:     }
 5055:     if (!$chome) { return 'unknown_course'; }
 5056:     # Make sure the user exists
 5057:     my $uhome=&homeserver($uname,$udom);
 5058:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5059: 	return 'error: no such user';
 5060:     }
 5061:     # Get student data if we were not given enough information
 5062:     if (!defined($first)  || $first  eq '' || 
 5063:         !defined($last)   || $last   eq '' || 
 5064:         !defined($uid)    || $uid    eq '' || 
 5065:         !defined($middle) || $middle eq '' || 
 5066:         !defined($gene)   || $gene   eq '') {
 5067:         # They did not supply us with enough data to enroll the student, so
 5068:         # we need to pick up more information.
 5069:         my %tmp = &get('environment',
 5070:                        ['firstname','middlename','lastname', 'generation','id']
 5071:                        ,$udom,$uname);
 5072: 
 5073:         #foreach my $key (keys(%tmp)) {
 5074:         #    &logthis("key $key = ".$tmp{$key});
 5075:         #}
 5076:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5077:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5078:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5079:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5080:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5081:     }
 5082:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5083:     my $reply=cput('classlist',
 5084: 		   {"$uname:$udom" => 
 5085: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5086: 		   $cdom,$cnum);
 5087:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5088: 	return 'error: '.$reply;
 5089:     } else {
 5090: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5091:     }
 5092:     # Add student role to user
 5093:     my $uurl='/'.$cid;
 5094:     $uurl=~s/\_/\//g;
 5095:     if ($usec) {
 5096: 	$uurl.='/'.$usec;
 5097:     }
 5098:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5099: }
 5100: 
 5101: sub format_name {
 5102:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5103:     my $name;
 5104:     if ($first ne 'lastname') {
 5105: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5106:     } else {
 5107: 	if ($lastname=~/\S/) {
 5108: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5109: 	    $name=~s/\s+,/,/;
 5110: 	} else {
 5111: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5112: 	}
 5113:     }
 5114:     $name=~s/^\s+//;
 5115:     $name=~s/\s+$//;
 5116:     $name=~s/\s+/ /g;
 5117:     return $name;
 5118: }
 5119: 
 5120: # ------------------------------------------------- Write to course preferences
 5121: 
 5122: sub writecoursepref {
 5123:     my ($courseid,%prefs)=@_;
 5124:     $courseid=~s/^\///;
 5125:     $courseid=~s/\_/\//g;
 5126:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5127:     my $chome=homeserver($cnum,$cdomain);
 5128:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5129: 	return 'error: no such course';
 5130:     }
 5131:     my $cstring='';
 5132:     foreach my $pref (keys(%prefs)) {
 5133: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5134:     }
 5135:     $cstring=~s/\&$//;
 5136:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5137: }
 5138: 
 5139: # ---------------------------------------------------------- Make/modify course
 5140: 
 5141: sub createcourse {
 5142:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5143:         $course_owner,$crstype)=@_;
 5144:     $url=&declutter($url);
 5145:     my $cid='';
 5146:     unless (&allowed('ccc',$udom)) {
 5147:         return 'refused';
 5148:     }
 5149: # ------------------------------------------------------------------- Create ID
 5150:    my $uname=int(1+rand(9)).
 5151:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5152:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5153:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5154: # ----------------------------------------------- Make sure that does not exist
 5155:    my $uhome=&homeserver($uname,$udom,'true');
 5156:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5157:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5158:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5159:        $uhome=&homeserver($uname,$udom,'true');       
 5160:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5161:            return 'error: unable to generate unique course-ID';
 5162:        } 
 5163:    }
 5164: # ------------------------------------------------ Check supplied server name
 5165:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5166:     if (! &is_library($course_server)) {
 5167:         return 'error:bad server name '.$course_server;
 5168:     }
 5169: # ------------------------------------------------------------- Make the course
 5170:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5171:                       $course_server);
 5172:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5173:     $uhome=&homeserver($uname,$udom,'true');
 5174:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5175: 	return 'error: no such course';
 5176:     }
 5177: # ----------------------------------------------------------------- Course made
 5178: # log existence
 5179:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5180:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5181:                   &escape($crstype),$uhome);
 5182:     &flushcourselogs();
 5183: # set toplevel url
 5184:     my $topurl=$url;
 5185:     unless ($nonstandard) {
 5186: # ------------------------------------------ For standard courses, make top url
 5187:         my $mapurl=&clutter($url);
 5188:         if ($mapurl eq '/res/') { $mapurl=''; }
 5189:         $env{'form.initmap'}=(<<ENDINITMAP);
 5190: <map>
 5191: <resource id="1" type="start"></resource>
 5192: <resource id="2" src="$mapurl"></resource>
 5193: <resource id="3" type="finish"></resource>
 5194: <link index="1" from="1" to="2"></link>
 5195: <link index="2" from="2" to="3"></link>
 5196: </map>
 5197: ENDINITMAP
 5198:         $topurl=&declutter(
 5199:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5200:                           );
 5201:     }
 5202: # ----------------------------------------------------------- Write preferences
 5203:     &writecoursepref($udom.'_'.$uname,
 5204:                      ('description' => $description,
 5205:                       'url'         => $topurl));
 5206:     return '/'.$udom.'/'.$uname;
 5207: }
 5208: 
 5209: sub is_course {
 5210:     my ($cdom,$cnum) = @_;
 5211:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5212: 				undef,'.');
 5213:     if (exists($courses{$cdom.'_'.$cnum})) {
 5214:         return 1;
 5215:     }
 5216:     return 0;
 5217: }
 5218: 
 5219: # ---------------------------------------------------------- Assign Custom Role
 5220: 
 5221: sub assigncustomrole {
 5222:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5223:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5224:                        $end,$start,$deleteflag);
 5225: }
 5226: 
 5227: # ----------------------------------------------------------------- Revoke Role
 5228: 
 5229: sub revokerole {
 5230:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5231:     my $now=time;
 5232:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5233: }
 5234: 
 5235: # ---------------------------------------------------------- Revoke Custom Role
 5236: 
 5237: sub revokecustomrole {
 5238:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5239:     my $now=time;
 5240:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5241:            $deleteflag);
 5242: }
 5243: 
 5244: # ------------------------------------------------------------ Disk usage
 5245: sub diskusage {
 5246:     my ($udom,$uname,$directoryRoot)=@_;
 5247:     $directoryRoot =~ s/\/$//;
 5248:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5249:     return $listing;
 5250: }
 5251: 
 5252: sub is_locked {
 5253:     my ($file_name, $domain, $user) = @_;
 5254:     my @check;
 5255:     my $is_locked;
 5256:     push @check, $file_name;
 5257:     my %locked = &get('file_permissions',\@check,
 5258: 		      $env{'user.domain'},$env{'user.name'});
 5259:     my ($tmp)=keys(%locked);
 5260:     if ($tmp=~/^error:/) { undef(%locked); }
 5261:     
 5262:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5263:         $is_locked = 'false';
 5264:         foreach my $entry (@{$locked{$file_name}}) {
 5265:            if (ref($entry) eq 'ARRAY') { 
 5266:                $is_locked = 'true';
 5267:                last;
 5268:            }
 5269:        }
 5270:     } else {
 5271:         $is_locked = 'false';
 5272:     }
 5273: }
 5274: 
 5275: sub declutter_portfile {
 5276:     my ($file) = @_;
 5277:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5278:     return $file;
 5279: }
 5280: 
 5281: # ------------------------------------------------------------- Mark as Read Only
 5282: 
 5283: sub mark_as_readonly {
 5284:     my ($domain,$user,$files,$what) = @_;
 5285:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5286:     my ($tmp)=keys(%current_permissions);
 5287:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5288:     foreach my $file (@{$files}) {
 5289: 	$file = &declutter_portfile($file);
 5290:         push(@{$current_permissions{$file}},$what);
 5291:     }
 5292:     &put('file_permissions',\%current_permissions,$domain,$user);
 5293:     return;
 5294: }
 5295: 
 5296: # ------------------------------------------------------------Save Selected Files
 5297: 
 5298: sub save_selected_files {
 5299:     my ($user, $path, @files) = @_;
 5300:     my $filename = $user."savedfiles";
 5301:     my @other_files = &files_not_in_path($user, $path);
 5302:     open (OUT, '>'.$tmpdir.$filename);
 5303:     foreach my $file (@files) {
 5304:         print (OUT $env{'form.currentpath'}.$file."\n");
 5305:     }
 5306:     foreach my $file (@other_files) {
 5307:         print (OUT $file."\n");
 5308:     }
 5309:     close (OUT);
 5310:     return 'ok';
 5311: }
 5312: 
 5313: sub clear_selected_files {
 5314:     my ($user) = @_;
 5315:     my $filename = $user."savedfiles";
 5316:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5317:     print (OUT undef);
 5318:     close (OUT);
 5319:     return ("ok");    
 5320: }
 5321: 
 5322: sub files_in_path {
 5323:     my ($user, $path) = @_;
 5324:     my $filename = $user."savedfiles";
 5325:     my %return_files;
 5326:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5327:     while (my $line_in = <IN>) {
 5328:         chomp ($line_in);
 5329:         my @paths_and_file = split (m!/!, $line_in);
 5330:         my $file_part = pop (@paths_and_file);
 5331:         my $path_part = join ('/', @paths_and_file);
 5332:         $path_part.='/';
 5333:         my $path_and_file = $path_part.$file_part;
 5334:         if ($path_part eq $path) {
 5335:             $return_files{$file_part}= 'selected';
 5336:         }
 5337:     }
 5338:     close (IN);
 5339:     return (\%return_files);
 5340: }
 5341: 
 5342: # called in portfolio select mode, to show files selected NOT in current directory
 5343: sub files_not_in_path {
 5344:     my ($user, $path) = @_;
 5345:     my $filename = $user."savedfiles";
 5346:     my @return_files;
 5347:     my $path_part;
 5348:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5349:     while (my $line = <IN>) {
 5350:         #ok, I know it's clunky, but I want it to work
 5351:         my @paths_and_file = split(m|/|, $line);
 5352:         my $file_part = pop(@paths_and_file);
 5353:         chomp($file_part);
 5354:         my $path_part = join('/', @paths_and_file);
 5355:         $path_part .= '/';
 5356:         my $path_and_file = $path_part.$file_part;
 5357:         if ($path_part ne $path) {
 5358:             push(@return_files, ($path_and_file));
 5359:         }
 5360:     }
 5361:     close(OUT);
 5362:     return (@return_files);
 5363: }
 5364: 
 5365: #----------------------------------------------Get portfolio file permissions
 5366: 
 5367: sub get_portfile_permissions {
 5368:     my ($domain,$user) = @_;
 5369:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5370:     my ($tmp)=keys(%current_permissions);
 5371:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5372:     return \%current_permissions;
 5373: }
 5374: 
 5375: #---------------------------------------------Get portfolio file access controls
 5376: 
 5377: sub get_access_controls {
 5378:     my ($current_permissions,$group,$file) = @_;
 5379:     my %access;
 5380:     my $real_file = $file;
 5381:     $file =~ s/\.meta$//;
 5382:     if (defined($file)) {
 5383:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5384:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5385:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5386:             }
 5387:         }
 5388:     } else {
 5389:         foreach my $key (keys(%{$current_permissions})) {
 5390:             if ($key =~ /\0accesscontrol$/) {
 5391:                 if (defined($group)) {
 5392:                     if ($key !~ m-^\Q$group\E/-) {
 5393:                         next;
 5394:                     }
 5395:                 }
 5396:                 my ($fullpath) = split(/\0/,$key);
 5397:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5398:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5399:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5400:                     }
 5401:                 }
 5402:             }
 5403:         }
 5404:     }
 5405:     return %access;
 5406: }
 5407: 
 5408: sub modify_access_controls {
 5409:     my ($file_name,$changes,$domain,$user)=@_;
 5410:     my ($outcome,$deloutcome);
 5411:     my %store_permissions;
 5412:     my %new_values;
 5413:     my %new_control;
 5414:     my %translation;
 5415:     my @deletions = ();
 5416:     my $now = time;
 5417:     if (exists($$changes{'activate'})) {
 5418:         if (ref($$changes{'activate'}) eq 'HASH') {
 5419:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5420:             my $numnew = scalar(@newitems);
 5421:             for (my $i=0; $i<$numnew; $i++) {
 5422:                 my $newkey = $newitems[$i];
 5423:                 my $newid = &Apache::loncommon::get_cgi_id();
 5424:                 if ($newkey =~ /^\d+:/) { 
 5425:                     $newkey =~ s/^(\d+)/$newid/;
 5426:                     $translation{$1} = $newid;
 5427:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5428:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5429:                     $translation{$1} = $newid;
 5430:                 }
 5431:                 $new_values{$file_name."\0".$newkey} = 
 5432:                                           $$changes{'activate'}{$newitems[$i]};
 5433:                 $new_control{$newkey} = $now;
 5434:             }
 5435:         }
 5436:     }
 5437:     my %todelete;
 5438:     my %changed_items;
 5439:     foreach my $action ('delete','update') {
 5440:         if (exists($$changes{$action})) {
 5441:             if (ref($$changes{$action}) eq 'HASH') {
 5442:                 foreach my $key (keys(%{$$changes{$action}})) {
 5443:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5444:                     if ($action eq 'delete') { 
 5445:                         $todelete{$itemnum} = 1;
 5446:                     } else {
 5447:                         $changed_items{$itemnum} = $key;
 5448:                     }
 5449:                 }
 5450:             }
 5451:         }
 5452:     }
 5453:     # get lock on access controls for file.
 5454:     my $lockhash = {
 5455:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5456:                                                        ':'.$env{'user.domain'},
 5457:                    }; 
 5458:     my $tries = 0;
 5459:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5460:    
 5461:     while (($gotlock ne 'ok') && $tries <3) {
 5462:         $tries ++;
 5463:         sleep 1;
 5464:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5465:     }
 5466:     if ($gotlock eq 'ok') {
 5467:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5468:         my ($tmp)=keys(%curr_permissions);
 5469:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5470:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5471:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5472:             if (ref($curr_controls) eq 'HASH') {
 5473:                 foreach my $control_item (keys(%{$curr_controls})) {
 5474:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5475:                     if (defined($todelete{$itemnum})) {
 5476:                         push(@deletions,$file_name."\0".$control_item);
 5477:                     } else {
 5478:                         if (defined($changed_items{$itemnum})) {
 5479:                             $new_control{$changed_items{$itemnum}} = $now;
 5480:                             push(@deletions,$file_name."\0".$control_item);
 5481:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5482:                         } else {
 5483:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5484:                         }
 5485:                     }
 5486:                 }
 5487:             }
 5488:         }
 5489:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5490:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5491:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5492:         #  remove lock
 5493:         my @del_lock = ($file_name."\0".'locked_access_records');
 5494:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5495:         my ($file,$group);
 5496:         if (&is_course($domain,$user)) {
 5497:             ($group,$file) = split(/\//,$file_name,2);
 5498:         } else {
 5499:             $file = $file_name;
 5500:         }
 5501:         my $sqlresult =
 5502:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5503:                                     $group);
 5504:     } else {
 5505:         $outcome = "error: could not obtain lockfile\n";  
 5506:     }
 5507:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5508: }
 5509: 
 5510: sub make_public_indefinitely {
 5511:     my ($requrl) = @_;
 5512:     my $now = time;
 5513:     my $action = 'activate';
 5514:     my $aclnum = 0;
 5515:     if (&is_portfolio_url($requrl)) {
 5516:         my (undef,$udom,$unum,$file_name,$group) =
 5517:             &parse_portfolio_url($requrl);
 5518:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5519:         my %access_controls = &get_access_controls($current_perms,
 5520:                                                    $group,$file_name);
 5521:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5522:             my ($num,$scope,$end,$start) = 
 5523:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5524:             if ($scope eq 'public') {
 5525:                 if ($start <= $now && $end == 0) {
 5526:                     $action = 'none';
 5527:                 } else {
 5528:                     $action = 'update';
 5529:                     $aclnum = $num;
 5530:                 }
 5531:                 last;
 5532:             }
 5533:         }
 5534:         if ($action eq 'none') {
 5535:              return 'ok';
 5536:         } else {
 5537:             my %changes;
 5538:             my $newend = 0;
 5539:             my $newstart = $now;
 5540:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5541:             $changes{$action}{$newkey} = {
 5542:                 type => 'public',
 5543:                 time => {
 5544:                     start => $newstart,
 5545:                     end   => $newend,
 5546:                 },
 5547:             };
 5548:             my ($outcome,$deloutcome,$new_values,$translation) =
 5549:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5550:             return $outcome;
 5551:         }
 5552:     } else {
 5553:         return 'invalid';
 5554:     }
 5555: }
 5556: 
 5557: #------------------------------------------------------Get Marked as Read Only
 5558: 
 5559: sub get_marked_as_readonly {
 5560:     my ($domain,$user,$what,$group) = @_;
 5561:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5562:     my @readonly_files;
 5563:     my $cmp1=$what;
 5564:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5565:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5566:         if (defined($group)) {
 5567:             if ($file_name !~ m-^\Q$group\E/-) {
 5568:                 next;
 5569:             }
 5570:         }
 5571:         if (ref($value) eq "ARRAY"){
 5572:             foreach my $stored_what (@{$value}) {
 5573:                 my $cmp2=$stored_what;
 5574:                 if (ref($stored_what) eq 'ARRAY') {
 5575:                     $cmp2=join('',@{$stored_what});
 5576:                 }
 5577:                 if ($cmp1 eq $cmp2) {
 5578:                     push(@readonly_files, $file_name);
 5579:                     last;
 5580:                 } elsif (!defined($what)) {
 5581:                     push(@readonly_files, $file_name);
 5582:                     last;
 5583:                 }
 5584:             }
 5585:         }
 5586:     }
 5587:     return @readonly_files;
 5588: }
 5589: #-----------------------------------------------------------Get Marked as Read Only Hash
 5590: 
 5591: sub get_marked_as_readonly_hash {
 5592:     my ($current_permissions,$group,$what) = @_;
 5593:     my %readonly_files;
 5594:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5595:         if (defined($group)) {
 5596:             if ($file_name !~ m-^\Q$group\E/-) {
 5597:                 next;
 5598:             }
 5599:         }
 5600:         if (ref($value) eq "ARRAY"){
 5601:             foreach my $stored_what (@{$value}) {
 5602:                 if (ref($stored_what) eq 'ARRAY') {
 5603:                     foreach my $lock_descriptor(@{$stored_what}) {
 5604:                         if ($lock_descriptor eq 'graded') {
 5605:                             $readonly_files{$file_name} = 'graded';
 5606:                         } elsif ($lock_descriptor eq 'handback') {
 5607:                             $readonly_files{$file_name} = 'handback';
 5608:                         } else {
 5609:                             if (!exists($readonly_files{$file_name})) {
 5610:                                 $readonly_files{$file_name} = 'locked';
 5611:                             }
 5612:                         }
 5613:                     }
 5614:                 } 
 5615:             }
 5616:         } 
 5617:     }
 5618:     return %readonly_files;
 5619: }
 5620: # ------------------------------------------------------------ Unmark as Read Only
 5621: 
 5622: sub unmark_as_readonly {
 5623:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5624:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5625:     my ($domain,$user,$what,$file_name,$group) = @_;
 5626:     $file_name = &declutter_portfile($file_name);
 5627:     my $symb_crs = $what;
 5628:     if (ref($what)) { $symb_crs=join('',@$what); }
 5629:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5630:     my ($tmp)=keys(%current_permissions);
 5631:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5632:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5633:     foreach my $file (@readonly_files) {
 5634: 	my $clean_file = &declutter_portfile($file);
 5635: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5636: 	my $current_locks = $current_permissions{$file};
 5637:         my @new_locks;
 5638:         my @del_keys;
 5639:         if (ref($current_locks) eq "ARRAY"){
 5640:             foreach my $locker (@{$current_locks}) {
 5641:                 my $compare=$locker;
 5642:                 if (ref($locker) eq 'ARRAY') {
 5643:                     $compare=join('',@{$locker});
 5644:                     if ($compare ne $symb_crs) {
 5645:                         push(@new_locks, $locker);
 5646:                     }
 5647:                 }
 5648:             }
 5649:             if (scalar(@new_locks) > 0) {
 5650:                 $current_permissions{$file} = \@new_locks;
 5651:             } else {
 5652:                 push(@del_keys, $file);
 5653:                 &del('file_permissions',\@del_keys, $domain, $user);
 5654:                 delete($current_permissions{$file});
 5655:             }
 5656:         }
 5657:     }
 5658:     &put('file_permissions',\%current_permissions,$domain,$user);
 5659:     return;
 5660: }
 5661: 
 5662: # ------------------------------------------------------------ Directory lister
 5663: 
 5664: sub dirlist {
 5665:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5666: 
 5667:     $uri=~s/^\///;
 5668:     $uri=~s/\/$//;
 5669:     my ($udom, $uname);
 5670:     (undef,$udom,$uname)=split(/\//,$uri);
 5671:     if(defined($userdomain)) {
 5672:         $udom = $userdomain;
 5673:     }
 5674:     if(defined($username)) {
 5675:         $uname = $username;
 5676:     }
 5677: 
 5678:     my $dirRoot = $perlvar{'lonDocRoot'};
 5679:     if(defined($alternateDirectoryRoot)) {
 5680:         $dirRoot = $alternateDirectoryRoot;
 5681:         $dirRoot =~ s/\/$//;
 5682:     }
 5683: 
 5684:     if($udom) {
 5685:         if($uname) {
 5686:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5687: 				 &homeserver($uname,$udom));
 5688:             my @listing_results;
 5689:             if ($listing eq 'unknown_cmd') {
 5690:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5691: 				  &homeserver($uname,$udom));
 5692:                 @listing_results = split(/:/,$listing);
 5693:             } else {
 5694:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5695:             }
 5696:             return @listing_results;
 5697:         } elsif(!defined($alternateDirectoryRoot)) {
 5698:             my %allusers;
 5699: 	    my %servers = &get_servers($udom,'library');
 5700: 	    foreach my $tryserver (keys(%servers)) {
 5701: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5702: 				     $udom, $tryserver);
 5703: 		my @listing_results;
 5704: 		if ($listing eq 'unknown_cmd') {
 5705: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5706: 				      $udom, $tryserver);
 5707: 		    @listing_results = split(/:/,$listing);
 5708: 		} else {
 5709: 		    @listing_results =
 5710: 			map { &unescape($_); } split(/:/,$listing);
 5711: 		}
 5712: 		if ($listing_results[0] ne 'no_such_dir' && 
 5713: 		    $listing_results[0] ne 'empty'       &&
 5714: 		    $listing_results[0] ne 'con_lost') {
 5715: 		    foreach my $line (@listing_results) {
 5716: 			my ($entry) = split(/&/,$line,2);
 5717: 			$allusers{$entry} = 1;
 5718: 		    }
 5719: 		}
 5720:             }
 5721:             my $alluserstr='';
 5722:             foreach my $user (sort(keys(%allusers))) {
 5723:                 $alluserstr.=$user.'&user:';
 5724:             }
 5725:             $alluserstr=~s/:$//;
 5726:             return split(/:/,$alluserstr);
 5727:         } else {
 5728:             return ('missing user name');
 5729:         }
 5730:     } elsif(!defined($alternateDirectoryRoot)) {
 5731:         my @all_domains = sort(&all_domains());
 5732:          foreach my $domain (@all_domains) {
 5733:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5734:          }
 5735:          return @all_domains;
 5736:      } else {
 5737:         return ('missing domain');
 5738:     }
 5739: }
 5740: 
 5741: # --------------------------------------------- GetFileTimestamp
 5742: # This function utilizes dirlist and returns the date stamp for
 5743: # when it was last modified.  It will also return an error of -1
 5744: # if an error occurs
 5745: 
 5746: ##
 5747: ## FIXME: This subroutine assumes its caller knows something about the
 5748: ## directory structure of the home server for the student ($root).
 5749: ## Not a good assumption to make.  Since this is for looking up files
 5750: ## in user directories, the full path should be constructed by lond, not
 5751: ## whatever machine we request data from.
 5752: ##
 5753: sub GetFileTimestamp {
 5754:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5755:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5756:     $studentName   = &LONCAPA::clean_username($studentName);
 5757:     my $subdir=$studentName.'__';
 5758:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5759:     my $proname="$studentDomain/$subdir/$studentName";
 5760:     $proname .= '/'.$filename;
 5761:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5762:                                               $studentName, $root);
 5763:     my @stats = split('&', $fileStat);
 5764:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5765:         # @stats contains first the filename, then the stat output
 5766:         return $stats[10]; # so this is 10 instead of 9.
 5767:     } else {
 5768:         return -1;
 5769:     }
 5770: }
 5771: 
 5772: sub stat_file {
 5773:     my ($uri) = @_;
 5774:     $uri = &clutter_with_no_wrapper($uri);
 5775: 
 5776:     my ($udom,$uname,$file,$dir);
 5777:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5778: 	($udom,$uname,$file) =
 5779: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5780: 	$file = 'userfiles/'.$file;
 5781: 	$dir = &propath($udom,$uname);
 5782:     }
 5783:     if ($uri =~ m-^/res/-) {
 5784: 	($udom,$uname) = 
 5785: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5786: 	$file = $uri;
 5787:     }
 5788: 
 5789:     if (!$udom || !$uname || !$file) {
 5790: 	# unable to handle the uri
 5791: 	return ();
 5792:     }
 5793: 
 5794:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5795:     my @stats = split('&', $result);
 5796:     
 5797:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5798: 	shift(@stats); #filename is first
 5799: 	return @stats;
 5800:     }
 5801:     return ();
 5802: }
 5803: 
 5804: # -------------------------------------------------------- Value of a Condition
 5805: 
 5806: # gets the value of a specific preevaluated condition
 5807: #    stored in the string  $env{user.state.<cid>}
 5808: # or looks up a condition reference in the bighash and if if hasn't
 5809: # already been evaluated recurses into docondval to get the value of
 5810: # the condition, then memoizing it to 
 5811: #   $env{user.state.<cid>.<condition>}
 5812: sub directcondval {
 5813:     my $number=shift;
 5814:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5815: 	&Apache::lonuserstate::evalstate();
 5816:     }
 5817:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5818: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5819:     } elsif ($number =~ /^_/) {
 5820: 	my $sub_condition;
 5821: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5822: 		&GDBM_READER(),0640)) {
 5823: 	    $sub_condition=$bighash{'conditions'.$number};
 5824: 	    untie(%bighash);
 5825: 	}
 5826: 	my $value = &docondval($sub_condition);
 5827: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5828: 	return $value;
 5829:     }
 5830:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5831:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5832:     } else {
 5833:        return 2;
 5834:     }
 5835: }
 5836: 
 5837: # get the collection of conditions for this resource
 5838: sub condval {
 5839:     my $condidx=shift;
 5840:     my $allpathcond='';
 5841:     foreach my $cond (split(/\|/,$condidx)) {
 5842: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5843: 	    $allpathcond.=
 5844: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5845: 	}
 5846:     }
 5847:     $allpathcond=~s/\|$//;
 5848:     return &docondval($allpathcond);
 5849: }
 5850: 
 5851: #evaluates an expression of conditions
 5852: sub docondval {
 5853:     my ($allpathcond) = @_;
 5854:     my $result=0;
 5855:     if ($env{'request.course.id'}
 5856: 	&& defined($allpathcond)) {
 5857: 	my $operand='|';
 5858: 	my @stack;
 5859: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5860: 	    if ($chunk eq '(') {
 5861: 		push @stack,($operand,$result);
 5862: 	    } elsif ($chunk eq ')') {
 5863: 		my $before=pop @stack;
 5864: 		if (pop @stack eq '&') {
 5865: 		    $result=$result>$before?$before:$result;
 5866: 		} else {
 5867: 		    $result=$result>$before?$result:$before;
 5868: 		}
 5869: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5870: 		$operand=$chunk;
 5871: 	    } else {
 5872: 		my $new=directcondval($chunk);
 5873: 		if ($operand eq '&') {
 5874: 		    $result=$result>$new?$new:$result;
 5875: 		} else {
 5876: 		    $result=$result>$new?$result:$new;
 5877: 		}
 5878: 	    }
 5879: 	}
 5880:     }
 5881:     return $result;
 5882: }
 5883: 
 5884: # ---------------------------------------------------- Devalidate courseresdata
 5885: 
 5886: sub devalidatecourseresdata {
 5887:     my ($coursenum,$coursedomain)=@_;
 5888:     my $hashid=$coursenum.':'.$coursedomain;
 5889:     &devalidate_cache_new('courseres',$hashid);
 5890: }
 5891: 
 5892: 
 5893: # --------------------------------------------------- Course Resourcedata Query
 5894: 
 5895: sub get_courseresdata {
 5896:     my ($coursenum,$coursedomain)=@_;
 5897:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5898:     my $hashid=$coursenum.':'.$coursedomain;
 5899:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5900:     my %dumpreply;
 5901:     unless (defined($cached)) {
 5902: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5903: 	$result=\%dumpreply;
 5904: 	my ($tmp) = keys(%dumpreply);
 5905: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5906: 	    &do_cache_new('courseres',$hashid,$result,600);
 5907: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5908: 	    return $tmp;
 5909: 	} elsif ($tmp =~ /^(error)/) {
 5910: 	    $result=undef;
 5911: 	    &do_cache_new('courseres',$hashid,$result,600);
 5912: 	}
 5913:     }
 5914:     return $result;
 5915: }
 5916: 
 5917: sub devalidateuserresdata {
 5918:     my ($uname,$udom)=@_;
 5919:     my $hashid="$udom:$uname";
 5920:     &devalidate_cache_new('userres',$hashid);
 5921: }
 5922: 
 5923: sub get_userresdata {
 5924:     my ($uname,$udom)=@_;
 5925:     #most student don\'t have any data set, check if there is some data
 5926:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5927: 
 5928:     my $hashid="$udom:$uname";
 5929:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5930:     if (!defined($cached)) {
 5931: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5932: 	$result=\%resourcedata;
 5933: 	&do_cache_new('userres',$hashid,$result,600);
 5934:     }
 5935:     my ($tmp)=keys(%$result);
 5936:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5937: 	return $result;
 5938:     }
 5939:     #error 2 occurs when the .db doesn't exist
 5940:     if ($tmp!~/error: 2 /) {
 5941: 	&logthis("<font color=\"blue\">WARNING:".
 5942: 		 " Trying to get resource data for ".
 5943: 		 $uname." at ".$udom.": ".
 5944: 		 $tmp."</font>");
 5945:     } elsif ($tmp=~/error: 2 /) {
 5946: 	#&EXT_cache_set($udom,$uname);
 5947: 	&do_cache_new('userres',$hashid,undef,600);
 5948: 	undef($tmp); # not really an error so don't send it back
 5949:     }
 5950:     return $tmp;
 5951: }
 5952: 
 5953: sub resdata {
 5954:     my ($name,$domain,$type,@which)=@_;
 5955:     my $result;
 5956:     if ($type eq 'course') {
 5957: 	$result=&get_courseresdata($name,$domain);
 5958:     } elsif ($type eq 'user') {
 5959: 	$result=&get_userresdata($name,$domain);
 5960:     }
 5961:     if (!ref($result)) { return $result; }    
 5962:     foreach my $item (@which) {
 5963: 	if (defined($result->{$item})) {
 5964: 	    return $result->{$item};
 5965: 	}
 5966:     }
 5967:     return undef;
 5968: }
 5969: 
 5970: #
 5971: # EXT resource caching routines
 5972: #
 5973: 
 5974: sub clear_EXT_cache_status {
 5975:     &delenv('cache.EXT.');
 5976: }
 5977: 
 5978: sub EXT_cache_status {
 5979:     my ($target_domain,$target_user) = @_;
 5980:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5981:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5982:         # We know already the user has no data
 5983:         return 1;
 5984:     } else {
 5985:         return 0;
 5986:     }
 5987: }
 5988: 
 5989: sub EXT_cache_set {
 5990:     my ($target_domain,$target_user) = @_;
 5991:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5992:     #&appenv($cachename => time);
 5993: }
 5994: 
 5995: # --------------------------------------------------------- Value of a Variable
 5996: sub EXT {
 5997: 
 5998:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5999:     unless ($varname) { return ''; }
 6000:     #get real user name/domain, courseid and symb
 6001:     my $courseid;
 6002:     my $publicuser;
 6003:     if ($symbparm) {
 6004: 	$symbparm=&get_symb_from_alias($symbparm);
 6005:     }
 6006:     if (!($uname && $udom)) {
 6007:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6008:       if (!$symbparm) {	$symbparm=$cursymb; }
 6009:     } else {
 6010: 	$courseid=$env{'request.course.id'};
 6011:     }
 6012:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6013:     my $rest;
 6014:     if (defined($therest[0])) {
 6015:        $rest=join('.',@therest);
 6016:     } else {
 6017:        $rest='';
 6018:     }
 6019: 
 6020:     my $qualifierrest=$qualifier;
 6021:     if ($rest) { $qualifierrest.='.'.$rest; }
 6022:     my $spacequalifierrest=$space;
 6023:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6024:     if ($realm eq 'user') {
 6025: # --------------------------------------------------------------- user.resource
 6026: 	if ($space eq 'resource') {
 6027: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6028: 		  || defined($Apache::lonhomework::parsing_a_task))
 6029: 		 &&
 6030: 		 ($symbparm eq &symbread()) ) {	
 6031: 		# if we are in the middle of processing the resource the
 6032: 		# get the value we are planning on committing
 6033:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6034:                     return $Apache::lonhomework::results{$qualifierrest};
 6035:                 } else {
 6036:                     return $Apache::lonhomework::history{$qualifierrest};
 6037:                 }
 6038: 	    } else {
 6039: 		my %restored;
 6040: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6041: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6042: 		} else {
 6043: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6044: 		}
 6045: 		return $restored{$qualifierrest};
 6046: 	    }
 6047: # ----------------------------------------------------------------- user.access
 6048:         } elsif ($space eq 'access') {
 6049: 	    # FIXME - not supporting calls for a specific user
 6050:             return &allowed($qualifier,$rest);
 6051: # ------------------------------------------ user.preferences, user.environment
 6052:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6053: 	    if (($uname eq $env{'user.name'}) &&
 6054: 		($udom eq $env{'user.domain'})) {
 6055: 		return $env{join('.',('environment',$qualifierrest))};
 6056: 	    } else {
 6057: 		my %returnhash;
 6058: 		if (!$publicuser) {
 6059: 		    %returnhash=&userenvironment($udom,$uname,
 6060: 						 $qualifierrest);
 6061: 		}
 6062: 		return $returnhash{$qualifierrest};
 6063: 	    }
 6064: # ----------------------------------------------------------------- user.course
 6065:         } elsif ($space eq 'course') {
 6066: 	    # FIXME - not supporting calls for a specific user
 6067:             return $env{join('.',('request.course',$qualifier))};
 6068: # ------------------------------------------------------------------- user.role
 6069:         } elsif ($space eq 'role') {
 6070: 	    # FIXME - not supporting calls for a specific user
 6071:             my ($role,$where)=split(/\./,$env{'request.role'});
 6072:             if ($qualifier eq 'value') {
 6073: 		return $role;
 6074:             } elsif ($qualifier eq 'extent') {
 6075:                 return $where;
 6076:             }
 6077: # ----------------------------------------------------------------- user.domain
 6078:         } elsif ($space eq 'domain') {
 6079:             return $udom;
 6080: # ------------------------------------------------------------------- user.name
 6081:         } elsif ($space eq 'name') {
 6082:             return $uname;
 6083: # ---------------------------------------------------- Any other user namespace
 6084:         } else {
 6085: 	    my %reply;
 6086: 	    if (!$publicuser) {
 6087: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6088: 	    }
 6089: 	    return $reply{$qualifierrest};
 6090:         }
 6091:     } elsif ($realm eq 'query') {
 6092: # ---------------------------------------------- pull stuff out of query string
 6093:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6094: 						[$spacequalifierrest]);
 6095: 	return $env{'form.'.$spacequalifierrest}; 
 6096:    } elsif ($realm eq 'request') {
 6097: # ------------------------------------------------------------- request.browser
 6098:         if ($space eq 'browser') {
 6099: 	    if ($qualifier eq 'textremote') {
 6100: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6101: 		    return 1;
 6102: 		} else {
 6103: 		    return 0;
 6104: 		}
 6105: 	    } else {
 6106: 		return $env{'browser.'.$qualifier};
 6107: 	    }
 6108: # ------------------------------------------------------------ request.filename
 6109:         } else {
 6110:             return $env{'request.'.$spacequalifierrest};
 6111:         }
 6112:     } elsif ($realm eq 'course') {
 6113: # ---------------------------------------------------------- course.description
 6114:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6115:     } elsif ($realm eq 'resource') {
 6116: 
 6117: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6118: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6119: 	}
 6120: 
 6121: 	if ($space eq 'title') {
 6122: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6123: 	    return &gettitle($symbparm);
 6124: 	}
 6125: 	
 6126: 	if ($space eq 'map') {
 6127: 	    my ($map) = &decode_symb($symbparm);
 6128: 	    return &symbread($map);
 6129: 	}
 6130: 
 6131: 	my ($section, $group, @groups);
 6132: 	my ($courselevelm,$courselevel);
 6133: 	if ($symbparm && defined($courseid) && 
 6134: 	    $courseid eq $env{'request.course.id'}) {
 6135: 
 6136: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6137: 
 6138: # ----------------------------------------------------- Cascading lookup scheme
 6139: 	    my $symbp=$symbparm;
 6140: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6141: 
 6142: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6143: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6144: 
 6145: 	    if (($env{'user.name'} eq $uname) &&
 6146: 		($env{'user.domain'} eq $udom)) {
 6147: 		$section=$env{'request.course.sec'};
 6148:                 @groups = split(/:/,$env{'request.course.groups'});  
 6149:                 @groups=&sort_course_groups($courseid,@groups); 
 6150: 	    } else {
 6151: 		if (! defined($usection)) {
 6152: 		    $section=&getsection($udom,$uname,$courseid);
 6153: 		} else {
 6154: 		    $section = $usection;
 6155: 		}
 6156:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6157: 	    }
 6158: 
 6159: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6160: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6161: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6162: 
 6163: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6164: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6165: 	    $courselevelm=$courseid.'.'.$mapparm;
 6166: 
 6167: # ----------------------------------------------------------- first, check user
 6168: 
 6169: 	    my $userreply=&resdata($uname,$udom,'user',
 6170: 				       ($courselevelr,$courselevelm,
 6171: 					$courselevel));
 6172: 	    if (defined($userreply)) { return $userreply; }
 6173: 
 6174: # ------------------------------------------------ second, check some of course
 6175:             my $coursereply;
 6176:             if (@groups > 0) {
 6177:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6178:                                        $mapparm,$spacequalifierrest);
 6179:                 if (defined($coursereply)) { return $coursereply; }
 6180:             }
 6181: 
 6182: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6183: 				     $env{'course.'.$courseid.'.domain'},
 6184: 				     'course',
 6185: 				     ($seclevelr,$seclevelm,$seclevel,
 6186: 				      $courselevelr));
 6187: 	    if (defined($coursereply)) { return $coursereply; }
 6188: 
 6189: # ------------------------------------------------------ third, check map parms
 6190: 	    my %parmhash=();
 6191: 	    my $thisparm='';
 6192: 	    if (tie(%parmhash,'GDBM_File',
 6193: 		    $env{'request.course.fn'}.'_parms.db',
 6194: 		    &GDBM_READER(),0640)) {
 6195: 		$thisparm=$parmhash{$symbparm};
 6196: 		untie(%parmhash);
 6197: 	    }
 6198: 	    if ($thisparm) { return $thisparm; }
 6199: 	}
 6200: # ------------------------------------------ fourth, look in resource metadata
 6201: 
 6202: 	$spacequalifierrest=~s/\./\_/;
 6203: 	my $filename;
 6204: 	if (!$symbparm) { $symbparm=&symbread(); }
 6205: 	if ($symbparm) {
 6206: 	    $filename=(&decode_symb($symbparm))[2];
 6207: 	} else {
 6208: 	    $filename=$env{'request.filename'};
 6209: 	}
 6210: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6211: 	if (defined($metadata)) { return $metadata; }
 6212: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6213: 	if (defined($metadata)) { return $metadata; }
 6214: 
 6215: # ---------------------------------------------- fourth, look in rest pf course
 6216: 	if ($symbparm && defined($courseid) && 
 6217: 	    $courseid eq $env{'request.course.id'}) {
 6218: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6219: 				     $env{'course.'.$courseid.'.domain'},
 6220: 				     'course',
 6221: 				     ($courselevelm,$courselevel));
 6222: 	    if (defined($coursereply)) { return $coursereply; }
 6223: 	}
 6224: # ------------------------------------------------------------------ Cascade up
 6225: 	unless ($space eq '0') {
 6226: 	    my @parts=split(/_/,$space);
 6227: 	    my $id=pop(@parts);
 6228: 	    my $part=join('_',@parts);
 6229: 	    if ($part eq '') { $part='0'; }
 6230: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6231: 				 $symbparm,$udom,$uname,$section,1);
 6232: 	    if (defined($partgeneral)) { return $partgeneral; }
 6233: 	}
 6234: 	if ($recurse) { return undef; }
 6235: 	my $pack_def=&packages_tab_default($filename,$varname);
 6236: 	if (defined($pack_def)) { return $pack_def; }
 6237: 
 6238: # ---------------------------------------------------- Any other user namespace
 6239:     } elsif ($realm eq 'environment') {
 6240: # ----------------------------------------------------------------- environment
 6241: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6242: 	    return $env{'environment.'.$spacequalifierrest};
 6243: 	} else {
 6244: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6245: 		return '';
 6246: 	    }
 6247: 	    my %returnhash=&userenvironment($udom,$uname,
 6248: 					    $spacequalifierrest);
 6249: 	    return $returnhash{$spacequalifierrest};
 6250: 	}
 6251:     } elsif ($realm eq 'system') {
 6252: # ----------------------------------------------------------------- system.time
 6253: 	if ($space eq 'time') {
 6254: 	    return time;
 6255:         }
 6256:     } elsif ($realm eq 'server') {
 6257: # ----------------------------------------------------------------- system.time
 6258: 	if ($space eq 'name') {
 6259: 	    return $ENV{'SERVER_NAME'};
 6260:         }
 6261:     }
 6262:     return '';
 6263: }
 6264: 
 6265: sub check_group_parms {
 6266:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6267:     my @groupitems = ();
 6268:     my $resultitem;
 6269:     my @levels = ($symbparm,$mapparm,$what);
 6270:     foreach my $group (@{$groups}) {
 6271:         foreach my $level (@levels) {
 6272:              my $item = $courseid.'.['.$group.'].'.$level;
 6273:              push(@groupitems,$item);
 6274:         }
 6275:     }
 6276:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6277:                             $env{'course.'.$courseid.'.domain'},
 6278:                                      'course',@groupitems);
 6279:     return $coursereply;
 6280: }
 6281: 
 6282: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6283:     my ($courseid,@groups) = @_;
 6284:     @groups = sort(@groups);
 6285:     return @groups;
 6286: }
 6287: 
 6288: sub packages_tab_default {
 6289:     my ($uri,$varname)=@_;
 6290:     my (undef,$part,$name)=split(/\./,$varname);
 6291: 
 6292:     my (@extension,@specifics,$do_default);
 6293:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6294: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6295: 	if ($pack_type eq 'default') {
 6296: 	    $do_default=1;
 6297: 	} elsif ($pack_type eq 'extension') {
 6298: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6299: 	} elsif ($pack_part eq $part) {
 6300: 	    # only look at packages defaults for packages that this id is
 6301: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6302: 	}
 6303:     }
 6304:     # first look for a package that matches the requested part id
 6305:     foreach my $package (@specifics) {
 6306: 	my (undef,$pack_type,$pack_part)=@{$package};
 6307: 	next if ($pack_part ne $part);
 6308: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6309: 	    return $packagetab{"$pack_type&$name&default"};
 6310: 	}
 6311:     }
 6312:     # look for any possible matching non extension_ package
 6313:     foreach my $package (@specifics) {
 6314: 	my (undef,$pack_type,$pack_part)=@{$package};
 6315: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6316: 	    return $packagetab{"$pack_type&$name&default"};
 6317: 	}
 6318: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6319: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6320: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6321: 	}
 6322:     }
 6323:     # look for any posible extension_ match
 6324:     foreach my $package (@extension) {
 6325: 	my ($package,$pack_type)=@{$package};
 6326: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6327: 	    return $packagetab{"$pack_type&$name&default"};
 6328: 	}
 6329: 	if (defined($packagetab{$package."&$name&default"})) {
 6330: 	    return $packagetab{$package."&$name&default"};
 6331: 	}
 6332:     }
 6333:     # look for a global default setting
 6334:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6335: 	return $packagetab{"default&$name&default"};
 6336:     }
 6337:     return undef;
 6338: }
 6339: 
 6340: sub add_prefix_and_part {
 6341:     my ($prefix,$part)=@_;
 6342:     my $keyroot;
 6343:     if (defined($prefix) && $prefix !~ /^__/) {
 6344: 	# prefix that has a part already
 6345: 	$keyroot=$prefix;
 6346:     } elsif (defined($prefix)) {
 6347: 	# prefix that is missing a part
 6348: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6349:     } else {
 6350: 	# no prefix at all
 6351: 	if (defined($part)) { $keyroot='_'.$part; }
 6352:     }
 6353:     return $keyroot;
 6354: }
 6355: 
 6356: # ---------------------------------------------------------------- Get metadata
 6357: 
 6358: my %metaentry;
 6359: sub metadata {
 6360:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6361:     $uri=&declutter($uri);
 6362:     # if it is a non metadata possible uri return quickly
 6363:     if (($uri eq '') || 
 6364: 	(($uri =~ m|^/*adm/|) && 
 6365: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6366:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6367: 	($uri =~ m|home/$match_username/public_html/|)) {
 6368: 	return undef;
 6369:     }
 6370:     my $filename=$uri;
 6371:     $uri=~s/\.meta$//;
 6372: #
 6373: # Is the metadata already cached?
 6374: # Look at timestamp of caching
 6375: # Everything is cached by the main uri, libraries are never directly cached
 6376: #
 6377:     if (!defined($liburi)) {
 6378: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6379: 	if (defined($cached)) { return $result->{':'.$what}; }
 6380:     }
 6381:     {
 6382: #
 6383: # Is this a recursive call for a library?
 6384: #
 6385: #	if (! exists($metacache{$uri})) {
 6386: #	    $metacache{$uri}={};
 6387: #	}
 6388:         if ($liburi) {
 6389: 	    $liburi=&declutter($liburi);
 6390:             $filename=$liburi;
 6391:         } else {
 6392: 	    &devalidate_cache_new('meta',$uri);
 6393: 	    undef(%metaentry);
 6394: 	}
 6395:         my %metathesekeys=();
 6396:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6397: 	my $metastring;
 6398: 	if ($uri !~ m -^(editupload)/-) {
 6399: 	    my $file=&filelocation('',&clutter($filename));
 6400: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6401: 	    $metastring=&getfile($file);
 6402: 	}
 6403:         my $parser=HTML::LCParser->new(\$metastring);
 6404:         my $token;
 6405:         undef %metathesekeys;
 6406:         while ($token=$parser->get_token) {
 6407: 	    if ($token->[0] eq 'S') {
 6408: 		if (defined($token->[2]->{'package'})) {
 6409: #
 6410: # This is a package - get package info
 6411: #
 6412: 		    my $package=$token->[2]->{'package'};
 6413: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6414: 		    if (defined($token->[2]->{'id'})) { 
 6415: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6416: 		    }
 6417: 		    if ($metaentry{':packages'}) {
 6418: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6419: 		    } else {
 6420: 			$metaentry{':packages'}=$package.$keyroot;
 6421: 		    }
 6422: 		    foreach my $pack_entry (keys(%packagetab)) {
 6423: 			my $part=$keyroot;
 6424: 			$part=~s/^\_//;
 6425: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6426: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6427: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6428: 			    # ignore package.tab specified default values
 6429:                             # here &package_tab_default() will fetch those
 6430: 			    if ($subp eq 'default') { next; }
 6431: 			    my $value=$packagetab{$pack_entry};
 6432: 			    my $unikey;
 6433: 			    if ($pack =~ /_0$/) {
 6434: 				$unikey='parameter_0_'.$name;
 6435: 				$part=0;
 6436: 			    } else {
 6437: 				$unikey='parameter'.$keyroot.'_'.$name;
 6438: 			    }
 6439: 			    if ($subp eq 'display') {
 6440: 				$value.=' [Part: '.$part.']';
 6441: 			    }
 6442: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6443: 			    $metathesekeys{$unikey}=1;
 6444: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6445: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6446: 			    }
 6447: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6448: 				$metaentry{':'.$unikey}=
 6449: 				    $metaentry{':'.$unikey.'.default'};
 6450: 			    }
 6451: 			}
 6452: 		    }
 6453: 		} else {
 6454: #
 6455: # This is not a package - some other kind of start tag
 6456: #
 6457: 		    my $entry=$token->[1];
 6458: 		    my $unikey;
 6459: 		    if ($entry eq 'import') {
 6460: 			$unikey='';
 6461: 		    } else {
 6462: 			$unikey=$entry;
 6463: 		    }
 6464: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6465: 
 6466: 		    if (defined($token->[2]->{'id'})) { 
 6467: 			$unikey.='_'.$token->[2]->{'id'}; 
 6468: 		    }
 6469: 
 6470: 		    if ($entry eq 'import') {
 6471: #
 6472: # Importing a library here
 6473: #
 6474: 			if ($depthcount<20) {
 6475: 			    my $location=$parser->get_text('/import');
 6476: 			    my $dir=$filename;
 6477: 			    $dir=~s|[^/]*$||;
 6478: 			    $location=&filelocation($dir,$location);
 6479: 			    my $metadata = 
 6480: 				&metadata($uri,'keys', $location,$unikey,
 6481: 					  $depthcount+1);
 6482: 			    foreach my $meta (split(',',$metadata)) {
 6483: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6484: 				$metathesekeys{$meta}=1;
 6485: 			    }
 6486: 			}
 6487: 		    } else { 
 6488: 			
 6489: 			if (defined($token->[2]->{'name'})) { 
 6490: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6491: 			}
 6492: 			$metathesekeys{$unikey}=1;
 6493: 			foreach my $param (@{$token->[3]}) {
 6494: 			    $metaentry{':'.$unikey.'.'.$param} =
 6495: 				$token->[2]->{$param};
 6496: 			}
 6497: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6498: 			my $default=$metaentry{':'.$unikey.'.default'};
 6499: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6500: 		 # only ws inside the tag, and not in default, so use default
 6501: 		 # as value
 6502: 			    $metaentry{':'.$unikey}=$default;
 6503: 			} else {
 6504: 		  # either something interesting inside the tag or default
 6505:                   # uninteresting
 6506: 			    $metaentry{':'.$unikey}=$internaltext;
 6507: 			}
 6508: # end of not-a-package not-a-library import
 6509: 		    }
 6510: # end of not-a-package start tag
 6511: 		}
 6512: # the next is the end of "start tag"
 6513: 	    }
 6514: 	}
 6515: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6516: 	foreach my $key (keys(%packagetab)) {
 6517: 	    #no specific packages #how's our extension
 6518: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6519: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6520: 					 \%metathesekeys);
 6521: 	}
 6522: 	if (!exists($metaentry{':packages'})) {
 6523: 	    foreach my $key (keys(%packagetab)) {
 6524: 		#no specific packages well let's get default then
 6525: 		if ($key!~/^default&/) { next; }
 6526: 		&metadata_create_package_def($uri,$key,'default',
 6527: 					     \%metathesekeys);
 6528: 	    }
 6529: 	}
 6530: # are there custom rights to evaluate
 6531: 	if ($metaentry{':copyright'} eq 'custom') {
 6532: 
 6533:     #
 6534:     # Importing a rights file here
 6535:     #
 6536: 	    unless ($depthcount) {
 6537: 		my $location=$metaentry{':customdistributionfile'};
 6538: 		my $dir=$filename;
 6539: 		$dir=~s|[^/]*$||;
 6540: 		$location=&filelocation($dir,$location);
 6541: 		my $rights_metadata =
 6542: 		    &metadata($uri,'keys',$location,'_rights',
 6543: 			      $depthcount+1);
 6544: 		foreach my $rights (split(',',$rights_metadata)) {
 6545: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6546: 		    $metathesekeys{$rights}=1;
 6547: 		}
 6548: 	    }
 6549: 	}
 6550: 	# uniqifiy package listing
 6551: 	my %seen;
 6552: 	my @uniq_packages =
 6553: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6554: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6555: 
 6556: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6557: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6558: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6559: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6560: # this is the end of "was not already recently cached
 6561:     }
 6562:     return $metaentry{':'.$what};
 6563: }
 6564: 
 6565: sub metadata_create_package_def {
 6566:     my ($uri,$key,$package,$metathesekeys)=@_;
 6567:     my ($pack,$name,$subp)=split(/\&/,$key);
 6568:     if ($subp eq 'default') { next; }
 6569:     
 6570:     if (defined($metaentry{':packages'})) {
 6571: 	$metaentry{':packages'}.=','.$package;
 6572:     } else {
 6573: 	$metaentry{':packages'}=$package;
 6574:     }
 6575:     my $value=$packagetab{$key};
 6576:     my $unikey;
 6577:     $unikey='parameter_0_'.$name;
 6578:     $metaentry{':'.$unikey.'.part'}=0;
 6579:     $$metathesekeys{$unikey}=1;
 6580:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6581: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6582:     }
 6583:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6584: 	$metaentry{':'.$unikey}=
 6585: 	    $metaentry{':'.$unikey.'.default'};
 6586:     }
 6587: }
 6588: 
 6589: sub metadata_generate_part0 {
 6590:     my ($metadata,$metacache,$uri) = @_;
 6591:     my %allnames;
 6592:     foreach my $metakey (keys(%$metadata)) {
 6593: 	if ($metakey=~/^parameter\_(.*)/) {
 6594: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6595: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6596: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6597: 	    $allnames{$name}=$part;
 6598: 	  }
 6599: 	}
 6600:     }
 6601:     foreach my $name (keys(%allnames)) {
 6602:       $$metadata{"parameter_0_$name"}=1;
 6603:       my $key=":parameter_0_$name";
 6604:       $$metacache{"$key.part"}='0';
 6605:       $$metacache{"$key.name"}=$name;
 6606:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6607: 					   $allnames{$name}.'_'.$name.
 6608: 					   '.type'};
 6609:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6610: 			     '.display'};
 6611:       my $expr='[Part: '.$allnames{$name}.']';
 6612:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6613:       $$metacache{"$key.display"}=$olddis;
 6614:     }
 6615: }
 6616: 
 6617: # ------------------------------------------------------ Devalidate title cache
 6618: 
 6619: sub devalidate_title_cache {
 6620:     my ($url)=@_;
 6621:     if (!$env{'request.course.id'}) { return; }
 6622:     my $symb=&symbread($url);
 6623:     if (!$symb) { return; }
 6624:     my $key=$env{'request.course.id'}."\0".$symb;
 6625:     &devalidate_cache_new('title',$key);
 6626: }
 6627: 
 6628: # ------------------------------------------------- Get the title of a resource
 6629: 
 6630: sub gettitle {
 6631:     my $urlsymb=shift;
 6632:     my $symb=&symbread($urlsymb);
 6633:     if ($symb) {
 6634: 	my $key=$env{'request.course.id'}."\0".$symb;
 6635: 	my ($result,$cached)=&is_cached_new('title',$key);
 6636: 	if (defined($cached)) { 
 6637: 	    return $result;
 6638: 	}
 6639: 	my ($map,$resid,$url)=&decode_symb($symb);
 6640: 	my $title='';
 6641: 	my %bighash;
 6642: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6643: 		&GDBM_READER(),0640)) {
 6644: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6645: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6646: 	    untie %bighash;
 6647: 	}
 6648: 	$title=~s/\&colon\;/\:/gs;
 6649: 	if ($title) {
 6650: 	    return &do_cache_new('title',$key,$title,600);
 6651: 	}
 6652: 	$urlsymb=$url;
 6653:     }
 6654:     my $title=&metadata($urlsymb,'title');
 6655:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6656:     return $title;
 6657: }
 6658: 
 6659: sub get_slot {
 6660:     my ($which,$cnum,$cdom)=@_;
 6661:     if (!$cnum || !$cdom) {
 6662: 	(undef,my $courseid)=&whichuser();
 6663: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6664: 	$cnum=$env{'course.'.$courseid.'.num'};
 6665:     }
 6666:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6667:     my %slotinfo;
 6668:     if (exists($remembered{$key})) {
 6669: 	$slotinfo{$which} = $remembered{$key};
 6670:     } else {
 6671: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6672: 	&Apache::lonhomework::showhash(%slotinfo);
 6673: 	my ($tmp)=keys(%slotinfo);
 6674: 	if ($tmp=~/^error:/) { return (); }
 6675: 	$remembered{$key} = $slotinfo{$which};
 6676:     }
 6677:     if (ref($slotinfo{$which}) eq 'HASH') {
 6678: 	return %{$slotinfo{$which}};
 6679:     }
 6680:     return $slotinfo{$which};
 6681: }
 6682: # ------------------------------------------------- Update symbolic store links
 6683: 
 6684: sub symblist {
 6685:     my ($mapname,%newhash)=@_;
 6686:     $mapname=&deversion(&declutter($mapname));
 6687:     my %hash;
 6688:     if (($env{'request.course.fn'}) && (%newhash)) {
 6689:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6690:                       &GDBM_WRCREAT(),0640)) {
 6691: 	    foreach my $url (keys %newhash) {
 6692: 		next if ($url eq 'last_known'
 6693: 			 && $env{'form.no_update_last_known'});
 6694: 		$hash{declutter($url)}=&encode_symb($mapname,
 6695: 						    $newhash{$url}->[1],
 6696: 						    $newhash{$url}->[0]);
 6697:             }
 6698:             if (untie(%hash)) {
 6699: 		return 'ok';
 6700:             }
 6701:         }
 6702:     }
 6703:     return 'error';
 6704: }
 6705: 
 6706: # --------------------------------------------------------------- Verify a symb
 6707: 
 6708: sub symbverify {
 6709:     my ($symb,$thisurl)=@_;
 6710:     my $thisfn=$thisurl;
 6711:     $thisfn=&declutter($thisfn);
 6712: # direct jump to resource in page or to a sequence - will construct own symbs
 6713:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6714: # check URL part
 6715:     my ($map,$resid,$url)=&decode_symb($symb);
 6716: 
 6717:     unless ($url eq $thisfn) { return 0; }
 6718: 
 6719:     $symb=&symbclean($symb);
 6720:     $thisurl=&deversion($thisurl);
 6721:     $thisfn=&deversion($thisfn);
 6722: 
 6723:     my %bighash;
 6724:     my $okay=0;
 6725: 
 6726:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6727:                             &GDBM_READER(),0640)) {
 6728:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6729:         unless ($ids) { 
 6730:            $ids=$bighash{'ids_/'.$thisurl};
 6731:         }
 6732:         if ($ids) {
 6733: # ------------------------------------------------------------------- Has ID(s)
 6734: 	    foreach my $id (split(/\,/,$ids)) {
 6735: 	       my ($mapid,$resid)=split(/\./,$id);
 6736:                if (
 6737:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6738:    eq $symb) { 
 6739: 		   if (($env{'request.role.adv'}) ||
 6740: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6741: 		       $okay=1; 
 6742: 		   }
 6743: 	       }
 6744: 	   }
 6745:         }
 6746: 	untie(%bighash);
 6747:     }
 6748:     return $okay;
 6749: }
 6750: 
 6751: # --------------------------------------------------------------- Clean-up symb
 6752: 
 6753: sub symbclean {
 6754:     my $symb=shift;
 6755:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6756: # remove version from map
 6757:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6758: 
 6759: # remove version from URL
 6760:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6761: 
 6762: # remove wrapper
 6763: 
 6764:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6765:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6766:     return $symb;
 6767: }
 6768: 
 6769: # ---------------------------------------------- Split symb to find map and url
 6770: 
 6771: sub encode_symb {
 6772:     my ($map,$resid,$url)=@_;
 6773:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6774: }
 6775: 
 6776: sub decode_symb {
 6777:     my $symb=shift;
 6778:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6779:     my ($map,$resid,$url)=split(/___/,$symb);
 6780:     return (&fixversion($map),$resid,&fixversion($url));
 6781: }
 6782: 
 6783: sub fixversion {
 6784:     my $fn=shift;
 6785:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6786:     my %bighash;
 6787:     my $uri=&clutter($fn);
 6788:     my $key=$env{'request.course.id'}.'_'.$uri;
 6789: # is this cached?
 6790:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6791:     if (defined($cached)) { return $result; }
 6792: # unfortunately not cached, or expired
 6793:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6794: 	    &GDBM_READER(),0640)) {
 6795:  	if ($bighash{'version_'.$uri}) {
 6796:  	    my $version=$bighash{'version_'.$uri};
 6797:  	    unless (($version eq 'mostrecent') || 
 6798: 		    ($version==&getversion($uri))) {
 6799:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6800:  	    }
 6801:  	}
 6802:  	untie %bighash;
 6803:     }
 6804:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6805: }
 6806: 
 6807: sub deversion {
 6808:     my $url=shift;
 6809:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6810:     return $url;
 6811: }
 6812: 
 6813: # ------------------------------------------------------ Return symb list entry
 6814: 
 6815: sub symbread {
 6816:     my ($thisfn,$donotrecurse)=@_;
 6817:     my $cache_str='request.symbread.cached.'.$thisfn;
 6818:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6819: # no filename provided? try from environment
 6820:     unless ($thisfn) {
 6821:         if ($env{'request.symb'}) {
 6822: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6823: 	}
 6824: 	$thisfn=$env{'request.filename'};
 6825:     }
 6826:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6827: # is that filename actually a symb? Verify, clean, and return
 6828:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6829: 	if (&symbverify($thisfn,$1)) {
 6830: 	    return $env{$cache_str}=&symbclean($thisfn);
 6831: 	}
 6832:     }
 6833:     $thisfn=declutter($thisfn);
 6834:     my %hash;
 6835:     my %bighash;
 6836:     my $syval='';
 6837:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6838:         my $targetfn = $thisfn;
 6839:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6840:             $targetfn = 'adm/wrapper/'.$thisfn;
 6841:         }
 6842: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6843: 	    $targetfn=$1;
 6844: 	}
 6845:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6846:                       &GDBM_READER(),0640)) {
 6847: 	    $syval=$hash{$targetfn};
 6848:             untie(%hash);
 6849:         }
 6850: # ---------------------------------------------------------- There was an entry
 6851:         if ($syval) {
 6852: 	    #unless ($syval=~/\_\d+$/) {
 6853: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6854: 		    #&appenv('request.ambiguous' => $thisfn);
 6855: 		    #return $env{$cache_str}='';
 6856: 		#}    
 6857: 		#$syval.=$1;
 6858: 	    #}
 6859:         } else {
 6860: # ------------------------------------------------------- Was not in symb table
 6861:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6862:                             &GDBM_READER(),0640)) {
 6863: # ---------------------------------------------- Get ID(s) for current resource
 6864:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6865:               unless ($ids) { 
 6866:                  $ids=$bighash{'ids_/'.$thisfn};
 6867:               }
 6868:               unless ($ids) {
 6869: # alias?
 6870: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6871:               }
 6872:               if ($ids) {
 6873: # ------------------------------------------------------------------- Has ID(s)
 6874:                  my @possibilities=split(/\,/,$ids);
 6875:                  if ($#possibilities==0) {
 6876: # ----------------------------------------------- There is only one possibility
 6877: 		     my ($mapid,$resid)=split(/\./,$ids);
 6878: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6879: 						    $resid,$thisfn);
 6880:                  } elsif (!$donotrecurse) {
 6881: # ------------------------------------------ There is more than one possibility
 6882:                      my $realpossible=0;
 6883:                      foreach my $id (@possibilities) {
 6884: 			 my $file=$bighash{'src_'.$id};
 6885:                          if (&allowed('bre',$file)) {
 6886:          		    my ($mapid,$resid)=split(/\./,$id);
 6887:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6888: 				$realpossible++;
 6889:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6890: 						    $resid,$thisfn);
 6891:                             }
 6892: 			 }
 6893:                      }
 6894: 		     if ($realpossible!=1) { $syval=''; }
 6895:                  } else {
 6896:                      $syval='';
 6897:                  }
 6898: 	      }
 6899:               untie(%bighash)
 6900:            }
 6901:         }
 6902:         if ($syval) {
 6903: 	    return $env{$cache_str}=$syval;
 6904:         }
 6905:     }
 6906:     &appenv('request.ambiguous' => $thisfn);
 6907:     return $env{$cache_str}='';
 6908: }
 6909: 
 6910: # ---------------------------------------------------------- Return random seed
 6911: 
 6912: sub numval {
 6913:     my $txt=shift;
 6914:     $txt=~tr/A-J/0-9/;
 6915:     $txt=~tr/a-j/0-9/;
 6916:     $txt=~tr/K-T/0-9/;
 6917:     $txt=~tr/k-t/0-9/;
 6918:     $txt=~tr/U-Z/0-5/;
 6919:     $txt=~tr/u-z/0-5/;
 6920:     $txt=~s/\D//g;
 6921:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6922:     return int($txt);
 6923: }
 6924: 
 6925: sub numval2 {
 6926:     my $txt=shift;
 6927:     $txt=~tr/A-J/0-9/;
 6928:     $txt=~tr/a-j/0-9/;
 6929:     $txt=~tr/K-T/0-9/;
 6930:     $txt=~tr/k-t/0-9/;
 6931:     $txt=~tr/U-Z/0-5/;
 6932:     $txt=~tr/u-z/0-5/;
 6933:     $txt=~s/\D//g;
 6934:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6935:     my $total;
 6936:     foreach my $val (@txts) { $total+=$val; }
 6937:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6938:     return int($total);
 6939: }
 6940: 
 6941: sub numval3 {
 6942:     use integer;
 6943:     my $txt=shift;
 6944:     $txt=~tr/A-J/0-9/;
 6945:     $txt=~tr/a-j/0-9/;
 6946:     $txt=~tr/K-T/0-9/;
 6947:     $txt=~tr/k-t/0-9/;
 6948:     $txt=~tr/U-Z/0-5/;
 6949:     $txt=~tr/u-z/0-5/;
 6950:     $txt=~s/\D//g;
 6951:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6952:     my $total;
 6953:     foreach my $val (@txts) { $total+=$val; }
 6954:     if ($_64bit) { $total=(($total<<32)>>32); }
 6955:     return $total;
 6956: }
 6957: 
 6958: sub digest {
 6959:     my ($data)=@_;
 6960:     my $digest=&Digest::MD5::md5($data);
 6961:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6962:     my ($e,$f);
 6963:     {
 6964:         use integer;
 6965:         $e=($a+$b);
 6966:         $f=($c+$d);
 6967:         if ($_64bit) {
 6968:             $e=(($e<<32)>>32);
 6969:             $f=(($f<<32)>>32);
 6970:         }
 6971:     }
 6972:     if (wantarray) {
 6973: 	return ($e,$f);
 6974:     } else {
 6975: 	my $g;
 6976: 	{
 6977: 	    use integer;
 6978: 	    $g=($e+$f);
 6979: 	    if ($_64bit) {
 6980: 		$g=(($g<<32)>>32);
 6981: 	    }
 6982: 	}
 6983: 	return $g;
 6984:     }
 6985: }
 6986: 
 6987: sub latest_rnd_algorithm_id {
 6988:     return '64bit5';
 6989: }
 6990: 
 6991: sub get_rand_alg {
 6992:     my ($courseid)=@_;
 6993:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6994:     if ($courseid) {
 6995: 	return $env{"course.$courseid.rndseed"};
 6996:     }
 6997:     return &latest_rnd_algorithm_id();
 6998: }
 6999: 
 7000: sub validCODE {
 7001:     my ($CODE)=@_;
 7002:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7003:     return 0;
 7004: }
 7005: 
 7006: sub getCODE {
 7007:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7008:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7009: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7010: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7011: 	return $Apache::lonhomework::history{'resource.CODE'};
 7012:     }
 7013:     return undef;
 7014: }
 7015: 
 7016: sub rndseed {
 7017:     my ($symb,$courseid,$domain,$username)=@_;
 7018:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7019:     if (!$symb) {
 7020: 	unless ($symb=$wsymb) { return time; }
 7021:     }
 7022:     if (!$courseid) { $courseid=$wcourseid; }
 7023:     if (!$domain) { $domain=$wdomain; }
 7024:     if (!$username) { $username=$wusername }
 7025:     my $which=&get_rand_alg();
 7026: 
 7027:     if (defined(&getCODE())) {
 7028: 	if ($which eq '64bit5') {
 7029: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7030: 	} elsif ($which eq '64bit4') {
 7031: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7032: 	} else {
 7033: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7034: 	}
 7035:     } elsif ($which eq '64bit5') {
 7036: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7037:     } elsif ($which eq '64bit4') {
 7038: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7039:     } elsif ($which eq '64bit3') {
 7040: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7041:     } elsif ($which eq '64bit2') {
 7042: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7043:     } elsif ($which eq '64bit') {
 7044: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7045:     }
 7046:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7047: }
 7048: 
 7049: sub rndseed_32bit {
 7050:     my ($symb,$courseid,$domain,$username)=@_;
 7051:     {
 7052: 	use integer;
 7053: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7054: 	my $symbseed=numval($symb) << 22;
 7055: 	my $namechck=unpack("%32C*",$username) << 17;
 7056: 	my $nameseed=numval($username) << 12;
 7057: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7058: 	my $courseseed=unpack("%32C*",$courseid);
 7059: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7060: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7061: 	#&logthis("rndseed :$num:$symb");
 7062: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7063: 	return $num;
 7064:     }
 7065: }
 7066: 
 7067: sub rndseed_64bit {
 7068:     my ($symb,$courseid,$domain,$username)=@_;
 7069:     {
 7070: 	use integer;
 7071: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7072: 	my $symbseed=numval($symb) << 10;
 7073: 	my $namechck=unpack("%32S*",$username);
 7074: 	
 7075: 	my $nameseed=numval($username) << 21;
 7076: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7077: 	my $courseseed=unpack("%32S*",$courseid);
 7078: 	
 7079: 	my $num1=$symbchck+$symbseed+$namechck;
 7080: 	my $num2=$nameseed+$domainseed+$courseseed;
 7081: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7082: 	#&logthis("rndseed :$num:$symb");
 7083: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7084: 	return "$num1,$num2";
 7085:     }
 7086: }
 7087: 
 7088: sub rndseed_64bit2 {
 7089:     my ($symb,$courseid,$domain,$username)=@_;
 7090:     {
 7091: 	use integer;
 7092: 	# strings need to be an even # of cahracters long, it it is odd the
 7093:         # last characters gets thrown away
 7094: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7095: 	my $symbseed=numval($symb) << 10;
 7096: 	my $namechck=unpack("%32S*",$username.' ');
 7097: 	
 7098: 	my $nameseed=numval($username) << 21;
 7099: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7100: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7101: 	
 7102: 	my $num1=$symbchck+$symbseed+$namechck;
 7103: 	my $num2=$nameseed+$domainseed+$courseseed;
 7104: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7105: 	#&logthis("rndseed :$num:$symb");
 7106: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7107: 	return "$num1,$num2";
 7108:     }
 7109: }
 7110: 
 7111: sub rndseed_64bit3 {
 7112:     my ($symb,$courseid,$domain,$username)=@_;
 7113:     {
 7114: 	use integer;
 7115: 	# strings need to be an even # of cahracters long, it it is odd the
 7116:         # last characters gets thrown away
 7117: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7118: 	my $symbseed=numval2($symb) << 10;
 7119: 	my $namechck=unpack("%32S*",$username.' ');
 7120: 	
 7121: 	my $nameseed=numval2($username) << 21;
 7122: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7123: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7124: 	
 7125: 	my $num1=$symbchck+$symbseed+$namechck;
 7126: 	my $num2=$nameseed+$domainseed+$courseseed;
 7127: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7128: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7129: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7130: 	
 7131: 	return "$num1:$num2";
 7132:     }
 7133: }
 7134: 
 7135: sub rndseed_64bit4 {
 7136:     my ($symb,$courseid,$domain,$username)=@_;
 7137:     {
 7138: 	use integer;
 7139: 	# strings need to be an even # of cahracters long, it it is odd the
 7140:         # last characters gets thrown away
 7141: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7142: 	my $symbseed=numval3($symb) << 10;
 7143: 	my $namechck=unpack("%32S*",$username.' ');
 7144: 	
 7145: 	my $nameseed=numval3($username) << 21;
 7146: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7147: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7148: 	
 7149: 	my $num1=$symbchck+$symbseed+$namechck;
 7150: 	my $num2=$nameseed+$domainseed+$courseseed;
 7151: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7152: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7153: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7154: 	
 7155: 	return "$num1:$num2";
 7156:     }
 7157: }
 7158: 
 7159: sub rndseed_64bit5 {
 7160:     my ($symb,$courseid,$domain,$username)=@_;
 7161:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7162:     return "$num1:$num2";
 7163: }
 7164: 
 7165: sub rndseed_CODE_64bit {
 7166:     my ($symb,$courseid,$domain,$username)=@_;
 7167:     {
 7168: 	use integer;
 7169: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7170: 	my $symbseed=numval2($symb);
 7171: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7172: 	my $CODEseed=numval(&getCODE());
 7173: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7174: 	my $num1=$symbseed+$CODEchck;
 7175: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7176: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7177: 	#&logthis("rndseed :$num1:$num2:$symb");
 7178: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7179: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7180: 	return "$num1:$num2";
 7181:     }
 7182: }
 7183: 
 7184: sub rndseed_CODE_64bit4 {
 7185:     my ($symb,$courseid,$domain,$username)=@_;
 7186:     {
 7187: 	use integer;
 7188: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7189: 	my $symbseed=numval3($symb);
 7190: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7191: 	my $CODEseed=numval3(&getCODE());
 7192: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7193: 	my $num1=$symbseed+$CODEchck;
 7194: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7195: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7196: 	#&logthis("rndseed :$num1:$num2:$symb");
 7197: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7198: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7199: 	return "$num1:$num2";
 7200:     }
 7201: }
 7202: 
 7203: sub rndseed_CODE_64bit5 {
 7204:     my ($symb,$courseid,$domain,$username)=@_;
 7205:     my $code = &getCODE();
 7206:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7207:     return "$num1:$num2";
 7208: }
 7209: 
 7210: sub setup_random_from_rndseed {
 7211:     my ($rndseed)=@_;
 7212:     if ($rndseed =~/([,:])/) {
 7213: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7214: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7215:     } else {
 7216: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7217:     }
 7218: }
 7219: 
 7220: sub latest_receipt_algorithm_id {
 7221:     return 'receipt3';
 7222: }
 7223: 
 7224: sub recunique {
 7225:     my $fucourseid=shift;
 7226:     my $unique;
 7227:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7228: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7229: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7230:     } else {
 7231: 	$unique=$perlvar{'lonReceipt'};
 7232:     }
 7233:     return unpack("%32C*",$unique);
 7234: }
 7235: 
 7236: sub recprefix {
 7237:     my $fucourseid=shift;
 7238:     my $prefix;
 7239:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7240: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7241: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7242:     } else {
 7243: 	$prefix=$perlvar{'lonHostID'};
 7244:     }
 7245:     return unpack("%32C*",$prefix);
 7246: }
 7247: 
 7248: sub ireceipt {
 7249:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7250: 
 7251:     my $return =&recprefix($fucourseid).'-';
 7252: 
 7253:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7254: 	$env{'request.state'} eq 'construct') {
 7255: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7256: 	return $return;
 7257:     }
 7258: 
 7259:     my $cuname=unpack("%32C*",$funame);
 7260:     my $cudom=unpack("%32C*",$fudom);
 7261:     my $cucourseid=unpack("%32C*",$fucourseid);
 7262:     my $cusymb=unpack("%32C*",$fusymb);
 7263:     my $cunique=&recunique($fucourseid);
 7264:     my $cpart=unpack("%32S*",$part);
 7265:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7266: 
 7267: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7268: 			       
 7269: 	$return.= ($cunique%$cuname+
 7270: 		   $cunique%$cudom+
 7271: 		   $cusymb%$cuname+
 7272: 		   $cusymb%$cudom+
 7273: 		   $cucourseid%$cuname+
 7274: 		   $cucourseid%$cudom+
 7275: 		   $cpart%$cuname+
 7276: 		   $cpart%$cudom);
 7277:     } else {
 7278: 	$return.= ($cunique%$cuname+
 7279: 		   $cunique%$cudom+
 7280: 		   $cusymb%$cuname+
 7281: 		   $cusymb%$cudom+
 7282: 		   $cucourseid%$cuname+
 7283: 		   $cucourseid%$cudom);
 7284:     }
 7285:     return $return;
 7286: }
 7287: 
 7288: sub receipt {
 7289:     my ($part)=@_;
 7290:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7291:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7292: }
 7293: 
 7294: sub whichuser {
 7295:     my ($passedsymb)=@_;
 7296:     my ($symb,$courseid,$domain,$name,$publicuser);
 7297:     if (defined($env{'form.grade_symb'})) {
 7298: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7299: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7300: 	if (!$allowed &&
 7301: 	    exists($env{'request.course.sec'}) &&
 7302: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7303: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7304: 			      '/'.$env{'request.course.sec'});
 7305: 	}
 7306: 	if ($allowed) {
 7307: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7308: 	    $courseid=$tmp_courseid;
 7309: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7310: 	    ($name)=&get_env_multiple('form.grade_username');
 7311: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7312: 	}
 7313:     }
 7314:     if (!$passedsymb) {
 7315: 	$symb=&symbread();
 7316:     } else {
 7317: 	$symb=$passedsymb;
 7318:     }
 7319:     $courseid=$env{'request.course.id'};
 7320:     $domain=$env{'user.domain'};
 7321:     $name=$env{'user.name'};
 7322:     if ($name eq 'public' && $domain eq 'public') {
 7323: 	if (!defined($env{'form.username'})) {
 7324: 	    $env{'form.username'}.=time.rand(10000000);
 7325: 	}
 7326: 	$name.=$env{'form.username'};
 7327:     }
 7328:     return ($symb,$courseid,$domain,$name,$publicuser);
 7329: 
 7330: }
 7331: 
 7332: # ------------------------------------------------------------ Serves up a file
 7333: # returns either the contents of the file or 
 7334: # -1 if the file doesn't exist
 7335: #
 7336: # if the target is a file that was uploaded via DOCS, 
 7337: # a check will be made to see if a current copy exists on the local server,
 7338: # if it does this will be served, otherwise a copy will be retrieved from
 7339: # the home server for the course and stored in /home/httpd/html/userfiles on
 7340: # the local server.   
 7341: 
 7342: sub getfile {
 7343:     my ($file) = @_;
 7344:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7345:     &repcopy($file);
 7346:     return &readfile($file);
 7347: }
 7348: 
 7349: sub repcopy_userfile {
 7350:     my ($file)=@_;
 7351:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7352:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7353:     my ($cdom,$cnum,$filename) = 
 7354: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7355:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7356:     if (-e "$file") {
 7357: # we already have a local copy, check it out
 7358: 	my @fileinfo = stat($file);
 7359: 	my $rtncode;
 7360: 	my $info;
 7361: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7362: 	if ($lwpresp ne 'ok') {
 7363: # there is no such file anymore, even though we had a local copy
 7364: 	    if ($rtncode eq '404') {
 7365: 		unlink($file);
 7366: 	    }
 7367: 	    return -1;
 7368: 	}
 7369: 	if ($info < $fileinfo[9]) {
 7370: # nice, the file we have is up-to-date, just say okay
 7371: 	    return 'ok';
 7372: 	} else {
 7373: # the file is outdated, get rid of it
 7374: 	    unlink($file);
 7375: 	}
 7376:     }
 7377: # one way or the other, at this point, we don't have the file
 7378: # construct the correct path for the file
 7379:     my @parts = ($cdom,$cnum); 
 7380:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7381: 	push @parts, split(/\//,$1);
 7382:     }
 7383:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7384:     foreach my $part (@parts) {
 7385: 	$path .= '/'.$part;
 7386: 	if (!-e $path) {
 7387: 	    mkdir($path,0770);
 7388: 	}
 7389:     }
 7390: # now the path exists for sure
 7391: # get a user agent
 7392:     my $ua=new LWP::UserAgent;
 7393:     my $transferfile=$file.'.in.transfer';
 7394: # FIXME: this should flock
 7395:     if (-e $transferfile) { return 'ok'; }
 7396:     my $request;
 7397:     $uri=~s/^\///;
 7398:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7399:     my $response=$ua->request($request,$transferfile);
 7400: # did it work?
 7401:     if ($response->is_error()) {
 7402: 	unlink($transferfile);
 7403: 	&logthis("Userfile repcopy failed for $uri");
 7404: 	return -1;
 7405:     }
 7406: # worked, rename the transfer file
 7407:     rename($transferfile,$file);
 7408:     return 'ok';
 7409: }
 7410: 
 7411: sub tokenwrapper {
 7412:     my $uri=shift;
 7413:     $uri=~s|^http\://([^/]+)||;
 7414:     $uri=~s|^/||;
 7415:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7416:     my $token=$1;
 7417:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7418:     if ($udom && $uname && $file) {
 7419: 	$file=~s|(\?\.*)*$||;
 7420:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7421:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7422:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7423:                                '&tokenissued='.$perlvar{'lonHostID'};
 7424:     } else {
 7425:         return '/adm/notfound.html';
 7426:     }
 7427: }
 7428: 
 7429: # call with reqtype HEAD: get last modification time
 7430: # call with reqtype GET: get the file contents
 7431: # Do not call this with reqtype GET for large files! It loads everything into memory
 7432: #
 7433: sub getuploaded {
 7434:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7435:     $uri=~s/^\///;
 7436:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7437:     my $ua=new LWP::UserAgent;
 7438:     my $request=new HTTP::Request($reqtype,$uri);
 7439:     my $response=$ua->request($request);
 7440:     $$rtncode = $response->code;
 7441:     if (! $response->is_success()) {
 7442: 	return 'failed';
 7443:     }      
 7444:     if ($reqtype eq 'HEAD') {
 7445: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7446:     } elsif ($reqtype eq 'GET') {
 7447: 	$$info = $response->content;
 7448:     }
 7449:     return 'ok';
 7450: }
 7451: 
 7452: sub readfile {
 7453:     my $file = shift;
 7454:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7455:     my $fh;
 7456:     open($fh,"<$file");
 7457:     my $a='';
 7458:     while (my $line = <$fh>) { $a .= $line; }
 7459:     return $a;
 7460: }
 7461: 
 7462: sub filelocation {
 7463:     my ($dir,$file) = @_;
 7464:     my $location;
 7465:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7466: 
 7467:     if ($file =~ m-^/adm/-) {
 7468: 	$file=~s-^/adm/wrapper/-/-;
 7469: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7470:     }
 7471:     if ($file=~m:^/~:) { # is a contruction space reference
 7472:         $location = $file;
 7473:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7474:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7475: 	# is a correct contruction space reference
 7476:         $location = $file;
 7477:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7478:         my ($udom,$uname,$filename)=
 7479:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7480:         my $home=&homeserver($uname,$udom);
 7481:         my $is_me=0;
 7482:         my @ids=&current_machine_ids();
 7483:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7484:         if ($is_me) {
 7485:   	    $location=&propath($udom,$uname).
 7486:   	      '/userfiles/'.$filename;
 7487:         } else {
 7488:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7489:   	      $udom.'/'.$uname.'/'.$filename;
 7490:         }
 7491:     } else {
 7492:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7493:         $file=~s:^/res/:/:;
 7494:         if ( !( $file =~ m:^/:) ) {
 7495:             $location = $dir. '/'.$file;
 7496:         } else {
 7497:             $location = '/home/httpd/html/res'.$file;
 7498:         }
 7499:     }
 7500:     $location=~s://+:/:g; # remove duplicate /
 7501:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7502:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7503:     return $location;
 7504: }
 7505: 
 7506: sub hreflocation {
 7507:     my ($dir,$file)=@_;
 7508:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7509: 	$file=filelocation($dir,$file);
 7510:     } elsif ($file=~m-^/adm/-) {
 7511: 	$file=~s-^/adm/wrapper/-/-;
 7512: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7513:     }
 7514:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7515: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7516:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7517: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7518:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7519: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7520: 	    -/uploaded/$1/$2/-x;
 7521:     }
 7522:     return $file;
 7523: }
 7524: 
 7525: sub current_machine_domains {
 7526:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7527: }
 7528: 
 7529: sub machine_domains {
 7530:     my ($hostname) = @_;
 7531:     my @domains;
 7532:     my %hostname = &all_hostnames();
 7533:     while( my($id, $name) = each(%hostname)) {
 7534: #	&logthis("-$id-$name-$hostname-");
 7535: 	if ($hostname eq $name) {
 7536: 	    push(@domains,&host_domain($id));
 7537: 	}
 7538:     }
 7539:     return @domains;
 7540: }
 7541: 
 7542: sub current_machine_ids {
 7543:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7544: }
 7545: 
 7546: sub machine_ids {
 7547:     my ($hostname) = @_;
 7548:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7549:     my @ids;
 7550:     my %hostname = &all_hostnames();
 7551:     while( my($id, $name) = each(%hostname)) {
 7552: #	&logthis("-$id-$name-$hostname-");
 7553: 	if ($hostname eq $name) {
 7554: 	    push(@ids,$id);
 7555: 	}
 7556:     }
 7557:     return @ids;
 7558: }
 7559: 
 7560: sub additional_machine_domains {
 7561:     my @domains;
 7562:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7563:     while( my $line = <$fh>) {
 7564:         $line =~ s/\s//g;
 7565:         push(@domains,$line);
 7566:     }
 7567:     return @domains;
 7568: }
 7569: 
 7570: sub default_login_domain {
 7571:     my $domain = $perlvar{'lonDefDomain'};
 7572:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7573:     foreach my $posdom (&current_machine_domains(),
 7574:                         &additional_machine_domains()) {
 7575:         if (lc($posdom) eq lc($testdomain)) {
 7576:             $domain=$posdom;
 7577:             last;
 7578:         }
 7579:     }
 7580:     return $domain;
 7581: }
 7582: 
 7583: # ------------------------------------------------------------- Declutters URLs
 7584: 
 7585: sub declutter {
 7586:     my $thisfn=shift;
 7587:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7588:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7589:     $thisfn=~s/^\///;
 7590:     $thisfn=~s|^adm/wrapper/||;
 7591:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7592:     $thisfn=~s/^res\///;
 7593:     $thisfn=~s/\?.+$//;
 7594:     return $thisfn;
 7595: }
 7596: 
 7597: # ------------------------------------------------------------- Clutter up URLs
 7598: 
 7599: sub clutter {
 7600:     my $thisfn='/'.&declutter(shift);
 7601:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7602:        $thisfn='/res'.$thisfn; 
 7603:     }
 7604:     if ($thisfn !~m|/adm|) {
 7605: 	if ($thisfn =~ m|/ext/|) {
 7606: 	    $thisfn='/adm/wrapper'.$thisfn;
 7607: 	} else {
 7608: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7609: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7610: 	    if ($embstyle eq 'ssi'
 7611: 		|| ($embstyle eq 'hdn')
 7612: 		|| ($embstyle eq 'rat')
 7613: 		|| ($embstyle eq 'prv')
 7614: 		|| ($embstyle eq 'ign')) {
 7615: 		#do nothing with these
 7616: 	    } elsif (($embstyle eq 'img') 
 7617: 		|| ($embstyle eq 'emb')
 7618: 		|| ($embstyle eq 'wrp')) {
 7619: 		$thisfn='/adm/wrapper'.$thisfn;
 7620: 	    } elsif ($embstyle eq 'unk'
 7621: 		     && $thisfn!~/\.(sequence|page)$/) {
 7622: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7623: 	    } else {
 7624: #		&logthis("Got a blank emb style");
 7625: 	    }
 7626: 	}
 7627:     }
 7628:     return $thisfn;
 7629: }
 7630: 
 7631: sub clutter_with_no_wrapper {
 7632:     my $uri = &clutter(shift);
 7633:     if ($uri =~ m-^/adm/-) {
 7634: 	$uri =~ s-^/adm/wrapper/-/-;
 7635: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7636:     }
 7637:     return $uri;
 7638: }
 7639: 
 7640: sub freeze_escape {
 7641:     my ($value)=@_;
 7642:     if (ref($value)) {
 7643: 	$value=&nfreeze($value);
 7644: 	return '__FROZEN__'.&escape($value);
 7645:     }
 7646:     return &escape($value);
 7647: }
 7648: 
 7649: 
 7650: sub thaw_unescape {
 7651:     my ($value)=@_;
 7652:     if ($value =~ /^__FROZEN__/) {
 7653: 	substr($value,0,10,undef);
 7654: 	$value=&unescape($value);
 7655: 	return &thaw($value);
 7656:     }
 7657:     return &unescape($value);
 7658: }
 7659: 
 7660: sub correct_line_ends {
 7661:     my ($result)=@_;
 7662:     $$result =~s/\r\n/\n/mg;
 7663:     $$result =~s/\r/\n/mg;
 7664: }
 7665: # ================================================================ Main Program
 7666: 
 7667: sub goodbye {
 7668:    &logthis("Starting Shut down");
 7669: #not converted to using infrastruture and probably shouldn't be
 7670:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7671: #converted
 7672: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7673:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7674: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7675: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7676: #1.1 only
 7677: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7678: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7679: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7680: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7681:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7682:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7683:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7684:    &flushcourselogs();
 7685:    &logthis("Shutting down");
 7686: }
 7687: 
 7688: sub get_dns {
 7689:     my ($url,$func,$ignore_cache) = @_;
 7690:     if (!$ignore_cache) {
 7691: 	my ($content,$cached)=
 7692: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7693: 	if ($cached) {
 7694: 	    &$func($content);
 7695: 	    return;
 7696: 	}
 7697:     }
 7698: 
 7699:     my %alldns;
 7700:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7701:     foreach my $dns (<$config>) {
 7702: 	next if ($dns !~ /^\^(\S*)/x);
 7703: 	$alldns{$1} = 1;
 7704:     }
 7705:     while (%alldns) {
 7706: 	my ($dns) = keys(%alldns);
 7707: 	delete($alldns{$dns});
 7708: 	my $ua=new LWP::UserAgent;
 7709: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7710: 	my $response=$ua->request($request);
 7711: 	next if ($response->is_error());
 7712: 	my @content = split("\n",$response->content);
 7713: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7714: 	&$func(\@content);
 7715: 	return;
 7716:     }
 7717:     close($config);
 7718:     my $which = (split('/',$url))[3];
 7719:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 7720:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 7721:     my @content = <$config>;
 7722:     &$func(\@content);
 7723:     return;
 7724: }
 7725: # ------------------------------------------------------------ Read domain file
 7726: {
 7727:     my $loaded;
 7728:     my %domain;
 7729: 
 7730:     sub parse_domain_tab {
 7731: 	my ($lines) = @_;
 7732: 	foreach my $line (@$lines) {
 7733: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7734: 
 7735: 	    chomp($line);
 7736: 	    my ($name,@elements) = split(/:/,$line,9);
 7737: 	    my %this_domain;
 7738: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7739: 			       'lang_def', 'city', 'longi', 'lati',
 7740: 			       'primary') {
 7741: 		$this_domain{$field} = shift(@elements);
 7742: 	    }
 7743: 	    $domain{$name} = \%this_domain;
 7744: 	}
 7745:     }
 7746: 
 7747:     sub reset_domain_info {
 7748: 	undef($loaded);
 7749: 	undef(%domain);
 7750:     }
 7751: 
 7752:     sub load_domain_tab {
 7753: 	my ($ignore_cache) = @_;
 7754: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7755: 	my $fh;
 7756: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7757: 	    my @lines = <$fh>;
 7758: 	    &parse_domain_tab(\@lines);
 7759: 	}
 7760: 	close($fh);
 7761: 	$loaded = 1;
 7762:     }
 7763: 
 7764:     sub domain {
 7765: 	&load_domain_tab() if (!$loaded);
 7766: 
 7767: 	my ($name,$what) = @_;
 7768: 	return if ( !exists($domain{$name}) );
 7769: 
 7770: 	if (!$what) {
 7771: 	    return $domain{$name}{'description'};
 7772: 	}
 7773: 	return $domain{$name}{$what};
 7774:     }
 7775: }
 7776: 
 7777: 
 7778: # ------------------------------------------------------------- Read hosts file
 7779: {
 7780:     my %hostname;
 7781:     my %hostdom;
 7782:     my %libserv;
 7783:     my $loaded;
 7784: 
 7785:     sub parse_hosts_tab {
 7786: 	my ($file) = @_;
 7787: 	foreach my $configline (@$file) {
 7788: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7789: 	    next if ($configline =~ /^\^/);
 7790: 	    chomp($configline);
 7791: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7792: 	    $name=~s/\s//g;
 7793: 	    if ($id && $domain && $role && $name) {
 7794: 		$hostname{$id}=$name;
 7795: 		$hostdom{$id}=$domain;
 7796: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7797: 	    }
 7798: 	}
 7799:     }
 7800:     
 7801:     sub reset_hosts_info {
 7802: 	&reset_domain_info();
 7803: 	&reset_hosts_ip_info();
 7804: 	undef(%hostname);
 7805: 	undef(%hostdom);
 7806: 	undef(%libserv);
 7807: 	undef($loaded);
 7808:     }
 7809: 
 7810:     sub load_hosts_tab {
 7811: 	my ($ignore_cache) = @_;
 7812: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 7813: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7814: 	my @config = <$config>;
 7815: 	&parse_hosts_tab(\@config);
 7816: 	close($config);
 7817: 	$loaded=1;
 7818:     }
 7819: 
 7820:     sub hostname {
 7821: 	&load_hosts_tab() if (!$loaded);
 7822: 
 7823: 	my ($lonid) = @_;
 7824: 	return $hostname{$lonid};
 7825:     }
 7826: 
 7827:     sub all_hostnames {
 7828: 	&load_hosts_tab() if (!$loaded);
 7829: 
 7830: 	return %hostname;
 7831:     }
 7832: 
 7833:     sub is_library {
 7834: 	&load_hosts_tab() if (!$loaded);
 7835: 
 7836: 	return exists($libserv{$_[0]});
 7837:     }
 7838: 
 7839:     sub all_library {
 7840: 	&load_hosts_tab() if (!$loaded);
 7841: 
 7842: 	return %libserv;
 7843:     }
 7844: 
 7845:     sub get_servers {
 7846: 	&load_hosts_tab() if (!$loaded);
 7847: 
 7848: 	my ($domain,$type) = @_;
 7849: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7850: 	                                          : %hostname;
 7851: 	my %result;
 7852: 	if (ref($domain) eq 'ARRAY') {
 7853: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7854: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7855: 		    $result{$host} = $hostname;
 7856: 		}
 7857: 	    }
 7858: 	} else {
 7859: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7860: 		if ($hostdom{$host} eq $domain) {
 7861: 		    $result{$host} = $hostname;
 7862: 		}
 7863: 	    }
 7864: 	}
 7865: 	return %result;
 7866:     }
 7867: 
 7868:     sub host_domain {
 7869: 	&load_hosts_tab() if (!$loaded);
 7870: 
 7871: 	my ($lonid) = @_;
 7872: 	return $hostdom{$lonid};
 7873:     }
 7874: 
 7875:     sub all_domains {
 7876: 	&load_hosts_tab() if (!$loaded);
 7877: 
 7878: 	my %seen;
 7879: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7880: 	return @uniq;
 7881:     }
 7882: }
 7883: 
 7884: { 
 7885:     my %iphost;
 7886:     my %name_to_ip;
 7887:     my %lonid_to_ip;
 7888: 
 7889:     my %valid_ip;
 7890:     sub valid_ip {
 7891: 	my ($ip) = @_;
 7892: 	if (exists($iphost{$ip}) || exists($valid_ip{$ip})) {
 7893: 	    return 1;	
 7894: 	}
 7895: 	my $name = gethostbyip($ip);
 7896: 	my $lonid = &hostname($name);
 7897: 	if (defined($lonid)) {
 7898: 	    $valid_ip{$ip} = $lonid;
 7899: 	    return 1;
 7900: 	}
 7901: 	my %iphosts = &get_iphost();
 7902: 	if (ref($iphost{$ip})) {
 7903: 	    return 1;	
 7904: 	}
 7905:     }
 7906: 
 7907:     sub get_hosts_from_ip {
 7908: 	my ($ip) = @_;
 7909: 	my %iphosts = &get_iphost();
 7910: 	if (ref($iphosts{$ip})) {
 7911: 	    return @{$iphosts{$ip}};
 7912: 	}
 7913: 	return;
 7914:     }
 7915:     
 7916:     sub reset_hosts_ip_info {
 7917: 	undef(%iphost);
 7918: 	undef(%name_to_ip);
 7919: 	undef(%lonid_to_ip);
 7920:     }
 7921: 
 7922:     sub get_host_ip {
 7923: 	my ($lonid) = @_;
 7924: 	if (exists($lonid_to_ip{$lonid})) {
 7925: 	    return $lonid_to_ip{$lonid};
 7926: 	}
 7927: 	my $name=&hostname($lonid);
 7928:    	my $ip = gethostbyname($name);
 7929: 	return if (!$ip || length($ip) ne 4);
 7930: 	$ip=inet_ntoa($ip);
 7931: 	$name_to_ip{$name}   = $ip;
 7932: 	$lonid_to_ip{$lonid} = $ip;
 7933: 	return $ip;
 7934:     }
 7935:     
 7936:     sub get_iphost {
 7937: 	my ($ignore_cache) = @_;
 7938: 	if (!$ignore_cache) {
 7939: 	    if (%iphost) {
 7940: 		return %iphost;
 7941: 	    }
 7942: 	    my ($ip_info,$cached)=
 7943: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 7944: 	    if ($cached) {
 7945: 		%iphost      = %{$ip_info->[0]};
 7946: 		%name_to_ip  = %{$ip_info->[1]};
 7947: 		%lonid_to_ip = %{$ip_info->[2]};
 7948: 		return %iphost;
 7949: 	    }
 7950: 	}
 7951: 	my %hostname = &all_hostnames();
 7952: 	foreach my $id (keys(%hostname)) {
 7953: 	    my $name=&hostname($id);
 7954: 	    my $ip;
 7955: 	    if (!exists($name_to_ip{$name})) {
 7956: 		$ip = gethostbyname($name);
 7957: 		if (!$ip || length($ip) ne 4) {
 7958: 		    &logthis("Skipping host $id name $name no IP found");
 7959: 		    next;
 7960: 		}
 7961: 		$ip=inet_ntoa($ip);
 7962: 		$name_to_ip{$name} = $ip;
 7963: 	    } else {
 7964: 		$ip = $name_to_ip{$name};
 7965: 	    }
 7966: 	    $lonid_to_ip{$id} = $ip;
 7967: 	    push(@{$iphost{$ip}},$id);
 7968: 	}
 7969: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 7970: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 7971: 				      24*60*60);
 7972: 
 7973: 	return %iphost;
 7974:     }
 7975: }
 7976: 
 7977: BEGIN {
 7978: 
 7979: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7980:     unless ($readit) {
 7981: {
 7982:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7983:     %perlvar = (%perlvar,%{$configvars});
 7984: }
 7985: 
 7986: 
 7987: # ------------------------------------------------------ Read spare server file
 7988: {
 7989:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7990: 
 7991:     while (my $configline=<$config>) {
 7992:        chomp($configline);
 7993:        if ($configline) {
 7994: 	   my ($host,$type) = split(':',$configline,2);
 7995: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7996: 	   push(@{ $spareid{$type} }, $host);
 7997:        }
 7998:     }
 7999:     close($config);
 8000: }
 8001: # ------------------------------------------------------------ Read permissions
 8002: {
 8003:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8004: 
 8005:     while (my $configline=<$config>) {
 8006: 	chomp($configline);
 8007: 	if ($configline) {
 8008: 	    my ($role,$perm)=split(/ /,$configline);
 8009: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8010: 	}
 8011:     }
 8012:     close($config);
 8013: }
 8014: 
 8015: # -------------------------------------------- Read plain texts for permissions
 8016: {
 8017:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8018: 
 8019:     while (my $configline=<$config>) {
 8020: 	chomp($configline);
 8021: 	if ($configline) {
 8022: 	    my ($short,@plain)=split(/:/,$configline);
 8023:             %{$prp{$short}} = ();
 8024: 	    if (@plain > 0) {
 8025:                 $prp{$short}{'std'} = $plain[0];
 8026:                 for (my $i=1; $i<@plain; $i++) {
 8027:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8028:                 }
 8029:             }
 8030: 	}
 8031:     }
 8032:     close($config);
 8033: }
 8034: 
 8035: # ---------------------------------------------------------- Read package table
 8036: {
 8037:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8038: 
 8039:     while (my $configline=<$config>) {
 8040: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8041: 	chomp($configline);
 8042: 	my ($short,$plain)=split(/:/,$configline);
 8043: 	my ($pack,$name)=split(/\&/,$short);
 8044: 	if ($plain ne '') {
 8045: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8046: 	    $packagetab{$short}=$plain; 
 8047: 	}
 8048:     }
 8049:     close($config);
 8050: }
 8051: 
 8052: # ------------- set up temporary directory
 8053: {
 8054:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8055: 
 8056: }
 8057: 
 8058: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8059: 				'compress_threshold'=> 20_000,
 8060:  			        });
 8061: 
 8062: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8063: $dumpcount=0;
 8064: 
 8065: &logtouch();
 8066: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8067: $readit=1;
 8068:     {
 8069: 	use integer;
 8070: 	my $test=(2**32)+1;
 8071: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8072: 	&logthis(" Detected 64bit platform ($_64bit)");
 8073:     }
 8074: }
 8075: }
 8076: 
 8077: 1;
 8078: __END__
 8079: 
 8080: =pod
 8081: 
 8082: =head1 NAME
 8083: 
 8084: Apache::lonnet - Subroutines to ask questions about things in the network.
 8085: 
 8086: =head1 SYNOPSIS
 8087: 
 8088: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8089: 
 8090:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8091: 
 8092: Common parameters:
 8093: 
 8094: =over 4
 8095: 
 8096: =item *
 8097: 
 8098: $uname : an internal username (if $cname expecting a course Id specifically)
 8099: 
 8100: =item *
 8101: 
 8102: $udom : a domain (if $cdom expecting a course's domain specifically)
 8103: 
 8104: =item *
 8105: 
 8106: $symb : a resource instance identifier
 8107: 
 8108: =item *
 8109: 
 8110: $namespace : the name of a .db file that contains the data needed or
 8111: being set.
 8112: 
 8113: =back
 8114: 
 8115: =head1 OVERVIEW
 8116: 
 8117: lonnet provides subroutines which interact with the
 8118: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8119: about classes, users, and resources.
 8120: 
 8121: For many of these objects you can also use this to store data about
 8122: them or modify them in various ways.
 8123: 
 8124: =head2 Symbs
 8125: 
 8126: To identify a specific instance of a resource, LON-CAPA uses symbols
 8127: or "symbs"X<symb>. These identifiers are built from the URL of the
 8128: map, the resource number of the resource in the map, and the URL of
 8129: the resource itself. The latter is somewhat redundant, but might help
 8130: if maps change.
 8131: 
 8132: An example is
 8133: 
 8134:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8135: 
 8136: The respective map entry is
 8137: 
 8138:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8139:   title="Problem 2">
 8140:  </resource>
 8141: 
 8142: Symbs are used by the random number generator, as well as to store and
 8143: restore data specific to a certain instance of for example a problem.
 8144: 
 8145: =head2 Storing And Retrieving Data
 8146: 
 8147: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8148: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8149: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8150: is is the non-critical message twin of cstore. These functions are for
 8151: handlers to store a perl hash to a user's permanent data space in an
 8152: easy manner, and to retrieve it again on another call. It is expected
 8153: that a handler would use this once at the beginning to retrieve data,
 8154: and then again once at the end to send only the new data back.
 8155: 
 8156: The data is stored in the user's data directory on the user's
 8157: homeserver under the ID of the course.
 8158: 
 8159: The hash that is returned by restore will have all of the previous
 8160: value for all of the elements of the hash.
 8161: 
 8162: Example:
 8163: 
 8164:  #creating a hash
 8165:  my %hash;
 8166:  $hash{'foo'}='bar';
 8167: 
 8168:  #storing it
 8169:  &Apache::lonnet::cstore(\%hash);
 8170: 
 8171:  #changing a value
 8172:  $hash{'foo'}='notbar';
 8173: 
 8174:  #adding a new value
 8175:  $hash{'bar'}='foo';
 8176:  &Apache::lonnet::cstore(\%hash);
 8177: 
 8178:  #retrieving the hash
 8179:  my %history=&Apache::lonnet::restore();
 8180: 
 8181:  #print the hash
 8182:  foreach my $key (sort(keys(%history))) {
 8183:    print("\%history{$key} = $history{$key}");
 8184:  }
 8185: 
 8186: Will print out:
 8187: 
 8188:  %history{1:foo} = bar
 8189:  %history{1:keys} = foo:timestamp
 8190:  %history{1:timestamp} = 990455579
 8191:  %history{2:bar} = foo
 8192:  %history{2:foo} = notbar
 8193:  %history{2:keys} = foo:bar:timestamp
 8194:  %history{2:timestamp} = 990455580
 8195:  %history{bar} = foo
 8196:  %history{foo} = notbar
 8197:  %history{timestamp} = 990455580
 8198:  %history{version} = 2
 8199: 
 8200: Note that the special hash entries C<keys>, C<version> and
 8201: C<timestamp> were added to the hash. C<version> will be equal to the
 8202: total number of versions of the data that have been stored. The
 8203: C<timestamp> attribute will be the UNIX time the hash was
 8204: stored. C<keys> is available in every historical section to list which
 8205: keys were added or changed at a specific historical revision of a
 8206: hash.
 8207: 
 8208: B<Warning>: do not store the hash that restore returns directly. This
 8209: will cause a mess since it will restore the historical keys as if the
 8210: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8211: 
 8212: Calling convention:
 8213: 
 8214:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8215:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8216: 
 8217: For more detailed information, see lonnet specific documentation.
 8218: 
 8219: =head1 RETURN MESSAGES
 8220: 
 8221: =over 4
 8222: 
 8223: =item * B<con_lost>: unable to contact remote host
 8224: 
 8225: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8226: when the connection is brought back up
 8227: 
 8228: =item * B<con_failed>: unable to contact remote host and unable to save message
 8229: for later delivery
 8230: 
 8231: =item * B<error:>: an error a occured, a description of the error follows the :
 8232: 
 8233: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8234: that was requested
 8235: 
 8236: =back
 8237: 
 8238: =head1 PUBLIC SUBROUTINES
 8239: 
 8240: =head2 Session Environment Functions
 8241: 
 8242: =over 4
 8243: 
 8244: =item * 
 8245: X<appenv()>
 8246: B<appenv(%hash)>: the value of %hash is written to
 8247: the user envirnoment file, and will be restored for each access this
 8248: user makes during this session, also modifies the %env for the current
 8249: process
 8250: 
 8251: =item *
 8252: X<delenv()>
 8253: B<delenv($regexp)>: removes all items from the session
 8254: environment file that matches the regular expression in $regexp. The
 8255: values are also delted from the current processes %env.
 8256: 
 8257: =item * get_env_multiple($name) 
 8258: 
 8259: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8260: values may be defined and end up as an array ref.
 8261: 
 8262: returns an array of values
 8263: 
 8264: =back
 8265: 
 8266: =head2 User Information
 8267: 
 8268: =over 4
 8269: 
 8270: =item *
 8271: X<queryauthenticate()>
 8272: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8273: authentication scheme
 8274: 
 8275: =item *
 8276: X<authenticate()>
 8277: B<authenticate($uname,$upass,$udom)>: try to
 8278: authenticate user from domain's lib servers (first use the current
 8279: one). C<$upass> should be the users password.
 8280: 
 8281: =item *
 8282: X<homeserver()>
 8283: B<homeserver($uname,$udom)>: find the server which has
 8284: the user's directory and files (there must be only one), this caches
 8285: the answer, and also caches if there is a borken connection.
 8286: 
 8287: =item *
 8288: X<idget()>
 8289: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8290: (IDs are a unique resource in a domain, there must be only 1 ID per
 8291: username, and only 1 username per ID in a specific domain) (returns
 8292: hash: id=>name,id=>name)
 8293: 
 8294: =item *
 8295: X<idrget()>
 8296: B<idrget($udom,@unames)>: find the IDs behind a list of
 8297: usernames (returns hash: name=>id,name=>id)
 8298: 
 8299: =item *
 8300: X<idput()>
 8301: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8302: 
 8303: =item *
 8304: X<rolesinit()>
 8305: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8306: 
 8307: =item *
 8308: X<getsection()>
 8309: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8310: course $cname, return section name/number or '' for "not in course"
 8311: and '-1' for "no section"
 8312: 
 8313: =item *
 8314: X<userenvironment()>
 8315: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8316: passed in @what from the requested user's environment, returns a hash
 8317: 
 8318: =item * 
 8319: X<userlog_query()>
 8320: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8321: activity.log file. %filters defines filters applied when parsing the
 8322: log file. These can be start or end timestamps, or the type of action
 8323: - log to look for Login or Logout events, check for Checkin or
 8324: Checkout, role for role selection. The response is in the form
 8325: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8326: escaped strings of the action recorded in the activity.log file.
 8327: 
 8328: =back
 8329: 
 8330: =head2 User Roles
 8331: 
 8332: =over 4
 8333: 
 8334: =item *
 8335: 
 8336: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8337:  F: full access
 8338:  U,I,K: authentication modes (cxx only)
 8339:  '': forbidden
 8340:  1: user needs to choose course
 8341:  2: browse allowed
 8342:  A: passphrase authentication needed
 8343: 
 8344: =item *
 8345: 
 8346: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8347: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8348: and course level
 8349: 
 8350: =item *
 8351: 
 8352: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8353: explanation of a user role term
 8354: 
 8355: =item *
 8356: 
 8357: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8358: All arguments are optional. Returns a hash of a roles, either for
 8359: co-author/assistant author roles for a user's Construction Space
 8360: (default), or if $context is 'user', roles for the user himself,
 8361: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8362: and value is set to colon-separated start and end times for the role.
 8363: If no username and domain are specified, will default to current
 8364: user/domain. Types, roles, and roledoms are references to arrays,
 8365: of role statuses (active, future or previous), roles 
 8366: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8367: to restrict the list of roles reported. If no array ref is 
 8368: provided for types, will default to return only active roles.
 8369: 
 8370: =back
 8371: 
 8372: =head2 User Modification
 8373: 
 8374: =over 4
 8375: 
 8376: =item *
 8377: 
 8378: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8379: user for the level given by URL.  Optional start and end dates (leave empty
 8380: string or zero for "no date")
 8381: 
 8382: =item *
 8383: 
 8384: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8385: change a users, password, possible return values are: ok,
 8386: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8387: refused
 8388: 
 8389: =item *
 8390: 
 8391: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8392: 
 8393: =item *
 8394: 
 8395: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8396: modify user
 8397: 
 8398: =item *
 8399: 
 8400: modifystudent
 8401: 
 8402: modify a students enrollment and identification information.
 8403: The course id is resolved based on the current users environment.  
 8404: This means the envoking user must be a course coordinator or otherwise
 8405: associated with a course.
 8406: 
 8407: This call is essentially a wrapper for lonnet::modifyuser and
 8408: lonnet::modify_student_enrollment
 8409: 
 8410: Inputs: 
 8411: 
 8412: =over 4
 8413: 
 8414: =item B<$udom> Students loncapa domain
 8415: 
 8416: =item B<$uname> Students loncapa login name
 8417: 
 8418: =item B<$uid> Students id/student number
 8419: 
 8420: =item B<$umode> Students authentication mode
 8421: 
 8422: =item B<$upass> Students password
 8423: 
 8424: =item B<$first> Students first name
 8425: 
 8426: =item B<$middle> Students middle name
 8427: 
 8428: =item B<$last> Students last name
 8429: 
 8430: =item B<$gene> Students generation
 8431: 
 8432: =item B<$usec> Students section in course
 8433: 
 8434: =item B<$end> Unix time of the roles expiration
 8435: 
 8436: =item B<$start> Unix time of the roles start date
 8437: 
 8438: =item B<$forceid> If defined, allow $uid to be changed
 8439: 
 8440: =item B<$desiredhome> server to use as home server for student
 8441: 
 8442: =back
 8443: 
 8444: =item *
 8445: 
 8446: modify_student_enrollment
 8447: 
 8448: Change a students enrollment status in a class.  The environment variable
 8449: 'role.request.course' must be defined for this function to proceed.
 8450: 
 8451: Inputs:
 8452: 
 8453: =over 4
 8454: 
 8455: =item $udom, students domain
 8456: 
 8457: =item $uname, students name
 8458: 
 8459: =item $uid, students user id
 8460: 
 8461: =item $first, students first name
 8462: 
 8463: =item $middle
 8464: 
 8465: =item $last
 8466: 
 8467: =item $gene
 8468: 
 8469: =item $usec
 8470: 
 8471: =item $end
 8472: 
 8473: =item $start
 8474: 
 8475: =back
 8476: 
 8477: 
 8478: =item *
 8479: 
 8480: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8481: custom role; give a custom role to a user for the level given by URL.  Specify
 8482: name and domain of role author, and role name
 8483: 
 8484: =item *
 8485: 
 8486: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8487: 
 8488: =item *
 8489: 
 8490: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8491: 
 8492: =back
 8493: 
 8494: =head2 Course Infomation
 8495: 
 8496: =over 4
 8497: 
 8498: =item *
 8499: 
 8500: coursedescription($courseid) : returns a hash of information about the
 8501: specified course id, including all environment settings for the
 8502: course, the description of the course will be in the hash under the
 8503: key 'description'
 8504: 
 8505: =item *
 8506: 
 8507: resdata($name,$domain,$type,@which) : request for current parameter
 8508: setting for a specific $type, where $type is either 'course' or 'user',
 8509: @what should be a list of parameters to ask about. This routine caches
 8510: answers for 5 minutes.
 8511: 
 8512: =back
 8513: 
 8514: =head2 Course Modification
 8515: 
 8516: =over 4
 8517: 
 8518: =item *
 8519: 
 8520: writecoursepref($courseid,%prefs) : write preferences (environment
 8521: database) for a course
 8522: 
 8523: =item *
 8524: 
 8525: createcourse($udom,$description,$url) : make/modify course
 8526: 
 8527: =back
 8528: 
 8529: =head2 Resource Subroutines
 8530: 
 8531: =over 4
 8532: 
 8533: =item *
 8534: 
 8535: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8536: 
 8537: =item *
 8538: 
 8539: repcopy($filename) : subscribes to the requested file, and attempts to
 8540: replicate from the owning library server, Might return
 8541: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8542: 'bad_request', also attempts to grab the metadata for the
 8543: resource. Expects the local filesystem pathname
 8544: (/home/httpd/html/res/....)
 8545: 
 8546: =back
 8547: 
 8548: =head2 Resource Information
 8549: 
 8550: =over 4
 8551: 
 8552: =item *
 8553: 
 8554: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8555: a vairety of different possible values, $varname should be a request
 8556: string, and the other parameters can be used to specify who and what
 8557: one is asking about.
 8558: 
 8559: Possible values for $varname are environment.lastname (or other item
 8560: from the envirnment hash), user.name (or someother aspect about the
 8561: user), resource.0.maxtries (or some other part and parameter of a
 8562: resource)
 8563: 
 8564: =item *
 8565: 
 8566: directcondval($number) : get current value of a condition; reads from a state
 8567: string
 8568: 
 8569: =item *
 8570: 
 8571: condval($condidx) : value of condition index based on state
 8572: 
 8573: =item *
 8574: 
 8575: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8576: resource's metadata, $what should be either a specific key, or either
 8577: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8578: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8579: 
 8580: this function automatically caches all requests
 8581: 
 8582: =item *
 8583: 
 8584: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8585: network of library servers; returns file handle of where SQL and regex results
 8586: will be stored for query
 8587: 
 8588: =item *
 8589: 
 8590: symbread($filename) : return symbolic list entry (filename argument optional);
 8591: returns the data handle
 8592: 
 8593: =item *
 8594: 
 8595: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8596: a possible symb for the URL in $thisfn, and if is an encryypted
 8597: resource that the user accessed using /enc/ returns a 1 on success, 0
 8598: on failure, user must be in a course, as it assumes the existance of
 8599: the course initial hash, and uses $env('request.course.id'}
 8600: 
 8601: 
 8602: =item *
 8603: 
 8604: symbclean($symb) : removes versions numbers from a symb, returns the
 8605: cleaned symb
 8606: 
 8607: =item *
 8608: 
 8609: is_on_map($uri) : checks if the $uri is somewhere on the current
 8610: course map, user must be in a course for it to work.
 8611: 
 8612: =item *
 8613: 
 8614: numval($salt) : return random seed value (addend for rndseed)
 8615: 
 8616: =item *
 8617: 
 8618: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8619: a random seed, all arguments are optional, if they aren't sent it uses the
 8620: environment to derive them. Note: if symb isn't sent and it can't get one
 8621: from &symbread it will use the current time as its return value
 8622: 
 8623: =item *
 8624: 
 8625: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8626: unfakeable, receipt
 8627: 
 8628: =item *
 8629: 
 8630: receipt() : API to ireceipt working off of env values; given out to users
 8631: 
 8632: =item *
 8633: 
 8634: countacc($url) : count the number of accesses to a given URL
 8635: 
 8636: =item *
 8637: 
 8638: 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
 8639: 
 8640: =item *
 8641: 
 8642: 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)
 8643: 
 8644: =item *
 8645: 
 8646: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8647: 
 8648: =item *
 8649: 
 8650: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8651: forcing spreadsheet to reevaluate the resource scores next time.
 8652: 
 8653: =back
 8654: 
 8655: =head2 Storing/Retreiving Data
 8656: 
 8657: =over 4
 8658: 
 8659: =item *
 8660: 
 8661: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8662: for this url; hashref needs to be given and should be a \%hashname; the
 8663: remaining args aren't required and if they aren't passed or are '' they will
 8664: be derived from the env
 8665: 
 8666: =item *
 8667: 
 8668: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8669: uses critical subroutine
 8670: 
 8671: =item *
 8672: 
 8673: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8674: all args are optional
 8675: 
 8676: =item *
 8677: 
 8678: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8679: dumps the complete (or key matching regexp) namespace into a hash
 8680: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8681: normally &store()ed into
 8682: 
 8683: $range should be either an integer '100' (give me the first 100
 8684:                                            matching records)
 8685:               or be  two integers sperated by a - with no spaces
 8686:                  '30-50' (give me the 30th through the 50th matching
 8687:                           records)
 8688: 
 8689: 
 8690: =item *
 8691: 
 8692: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8693: replaces a &store() version of data with a replacement set of data
 8694: for a particular resource in a namespace passed in the $storehash hash 
 8695: reference
 8696: 
 8697: =item *
 8698: 
 8699: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8700: works very similar to store/cstore, but all data is stored in a
 8701: temporary location and can be reset using tmpreset, $storehash should
 8702: be a hash reference, returns nothing on success
 8703: 
 8704: =item *
 8705: 
 8706: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8707: similar to restore, but all data is stored in a temporary location and
 8708: can be reset using tmpreset. Returns a hash of values on success,
 8709: error string otherwise.
 8710: 
 8711: =item *
 8712: 
 8713: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8714: deltes all keys for $symb form the temporary storage hash.
 8715: 
 8716: =item *
 8717: 
 8718: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8719: reference filled in from namesp ($udom and $uname are optional)
 8720: 
 8721: =item *
 8722: 
 8723: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8724: namesp ($udom and $uname are optional)
 8725: 
 8726: =item *
 8727: 
 8728: dump($namespace,$udom,$uname,$regexp,$range) : 
 8729: dumps the complete (or key matching regexp) namespace into a hash
 8730: ($udom, $uname, $regexp, $range are optional)
 8731: 
 8732: $range should be either an integer '100' (give me the first 100
 8733:                                            matching records)
 8734:               or be  two integers sperated by a - with no spaces
 8735:                  '30-50' (give me the 30th through the 50th matching
 8736:                           records)
 8737: =item *
 8738: 
 8739: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8740: $store can be a scalar, an array reference, or if the amount to be 
 8741: incremented is > 1, a hash reference.
 8742: 
 8743: ($udom and $uname are optional)
 8744: 
 8745: =item *
 8746: 
 8747: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8748: ($udom and $uname are optional)
 8749: 
 8750: =item *
 8751: 
 8752: cput($namespace,$storehash,$udom,$uname) : critical put
 8753: ($udom and $uname are optional)
 8754: 
 8755: =item *
 8756: 
 8757: newput($namespace,$storehash,$udom,$uname) :
 8758: 
 8759: Attempts to store the items in the $storehash, but only if they don't
 8760: currently exist, if this succeeds you can be certain that you have 
 8761: successfully created a new key value pair in the $namespace db.
 8762: 
 8763: 
 8764: Args:
 8765:  $namespace: name of database to store values to
 8766:  $storehash: hashref to store to the db
 8767:  $udom: (optional) domain of user containing the db
 8768:  $uname: (optional) name of user caontaining the db
 8769: 
 8770: Returns:
 8771:  'ok' -> succeeded in storing all keys of $storehash
 8772:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8773:                         least <key> already existed in the db (other
 8774:                         requested keys may also already exist)
 8775:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8776:  'con_lost' -> unable to contact request server
 8777:  'refused' -> action was not allowed by remote machine
 8778: 
 8779: 
 8780: =item *
 8781: 
 8782: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8783: reference filled in from namesp (encrypts the return communication)
 8784: ($udom and $uname are optional)
 8785: 
 8786: =item *
 8787: 
 8788: log($udom,$name,$home,$message) : write to permanent log for user; use
 8789: critical subroutine
 8790: 
 8791: =item *
 8792: 
 8793: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8794: array reference filled in from namespace found in domain level on either
 8795: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8796: 
 8797: =item *
 8798: 
 8799: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8800: domain level either on specified domain server ($uhome) or primary domain 
 8801: server ($udom and $uhome are optional)
 8802: 
 8803: =back
 8804: 
 8805: =head2 Network Status Functions
 8806: 
 8807: =over 4
 8808: 
 8809: =item *
 8810: 
 8811: dirlist($uri) : return directory list based on URI
 8812: 
 8813: =item *
 8814: 
 8815: spareserver() : find server with least workload from spare.tab
 8816: 
 8817: =back
 8818: 
 8819: =head2 Apache Request
 8820: 
 8821: =over 4
 8822: 
 8823: =item *
 8824: 
 8825: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8826: localhost, posts hash
 8827: 
 8828: =back
 8829: 
 8830: =head2 Data to String to Data
 8831: 
 8832: =over 4
 8833: 
 8834: =item *
 8835: 
 8836: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8837: and '&' separators, supports elements that are arrayrefs and hashrefs
 8838: 
 8839: =item *
 8840: 
 8841: hashref2str($hashref) : convert a hashref into a string complete with
 8842: escaping and '=' and '&' separators, supports elements that are
 8843: arrayrefs and hashrefs
 8844: 
 8845: =item *
 8846: 
 8847: arrayref2str($arrayref) : convert an arrayref into a string complete
 8848: with escaping and '&' separators, supports elements that are arrayrefs
 8849: and hashrefs
 8850: 
 8851: =item *
 8852: 
 8853: str2hash($string) : convert string to hash using unescaping and
 8854: splitting on '=' and '&', supports elements that are arrayrefs and
 8855: hashrefs
 8856: 
 8857: =item *
 8858: 
 8859: str2array($string) : convert string to hash using unescaping and
 8860: splitting on '&', supports elements that are arrayrefs and hashrefs
 8861: 
 8862: =back
 8863: 
 8864: =head2 Logging Routines
 8865: 
 8866: =over 4
 8867: 
 8868: These routines allow one to make log messages in the lonnet.log and
 8869: lonnet.perm logfiles.
 8870: 
 8871: =item *
 8872: 
 8873: logtouch() : make sure the logfile, lonnet.log, exists
 8874: 
 8875: =item *
 8876: 
 8877: logthis() : append message to the normal lonnet.log file, it gets
 8878: preiodically rolled over and deleted.
 8879: 
 8880: =item *
 8881: 
 8882: logperm() : append a permanent message to lonnet.perm.log, this log
 8883: file never gets deleted by any automated portion of the system, only
 8884: messages of critical importance should go in here.
 8885: 
 8886: =back
 8887: 
 8888: =head2 General File Helper Routines
 8889: 
 8890: =over 4
 8891: 
 8892: =item *
 8893: 
 8894: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8895: (a) files in /uploaded
 8896:   (i) If a local copy of the file exists - 
 8897:       compares modification date of local copy with last-modified date for 
 8898:       definitive version stored on home server for course. If local copy is 
 8899:       stale, requests a new version from the home server and stores it. 
 8900:       If the original has been removed from the home server, then local copy 
 8901:       is unlinked.
 8902:   (ii) If local copy does not exist -
 8903:       requests the file from the home server and stores it. 
 8904:   
 8905:   If $caller is 'uploadrep':  
 8906:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8907:     for request for files originally uploaded via DOCS. 
 8908:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8909:   
 8910:   Otherwise:
 8911:      This indicates a call from the content generation phase of the request.
 8912:      -  returns the entire contents of the file or -1.
 8913:      
 8914: (b) files in /res
 8915:    - returns the entire contents of a file or -1; 
 8916:    it properly subscribes to and replicates the file if neccessary.
 8917: 
 8918: 
 8919: =item *
 8920: 
 8921: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8922:                   reference
 8923: 
 8924: returns either a stat() list of data about the file or an empty list
 8925: if the file doesn't exist or couldn't find out about it (connection
 8926: problems or user unknown)
 8927: 
 8928: =item *
 8929: 
 8930: filelocation($dir,$file) : returns file system location of a file
 8931: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8932: directory that relative $file lookups are to looked in ($dir of /a/dir
 8933: and a file of ../bob will become /a/bob)
 8934: 
 8935: =item *
 8936: 
 8937: hreflocation($dir,$file) : returns file system location or a URL; same as
 8938: filelocation except for hrefs
 8939: 
 8940: =item *
 8941: 
 8942: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8943: 
 8944: =back
 8945: 
 8946: =head2 Usererfile file routines (/uploaded*)
 8947: 
 8948: =over 4
 8949: 
 8950: =item *
 8951: 
 8952: userfileupload(): main rotine for putting a file in a user or course's
 8953:                   filespace, arguments are,
 8954: 
 8955:  formname - required - this is the name of the element in $env where the
 8956:            filename, and the contents of the file to create/modifed exist
 8957:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8958:            contents of the file is located in $env{'form.'.$formname}
 8959:  coursedoc - if true, store the file in the course of the active role
 8960:              of the current user
 8961:  subdir - required - subdirectory to put the file in under ../userfiles/
 8962:          if undefined, it will be placed in "unknown"
 8963: 
 8964:  (This routine calls clean_filename() to remove any dangerous
 8965:  characters from the filename, and then calls finuserfileupload() to
 8966:  complete the transaction)
 8967: 
 8968:  returns either the url of the uploaded file (/uploaded/....) if successful
 8969:  and /adm/notfound.html if unsuccessful
 8970: 
 8971: =item *
 8972: 
 8973: clean_filename(): routine for cleaing a filename up for storage in
 8974:                  userfile space, argument is:
 8975: 
 8976:  filename - proposed filename
 8977: 
 8978: returns: the new clean filename
 8979: 
 8980: =item *
 8981: 
 8982: finishuserfileupload(): routine that creaes and sends the file to
 8983: userspace, probably shouldn't be called directly
 8984: 
 8985:   docuname: username or courseid of destination for the file
 8986:   docudom: domain of user/course of destination for the file
 8987:   formname: same as for userfileupload()
 8988:   fname: filename (inculding subdirectories) for the file
 8989: 
 8990:  returns either the url of the uploaded file (/uploaded/....) if successful
 8991:  and /adm/notfound.html if unsuccessful
 8992: 
 8993: =item *
 8994: 
 8995: renameuserfile(): renames an existing userfile to a new name
 8996: 
 8997:   Args:
 8998:    docuname: username or courseid of destination for the file
 8999:    docudom: domain of user/course of destination for the file
 9000:    old: current file name (including any subdirs under userfiles)
 9001:    new: desired file name (including any subdirs under userfiles)
 9002: 
 9003: =item *
 9004: 
 9005: mkdiruserfile(): creates a directory is a userfiles dir
 9006: 
 9007:   Args:
 9008:    docuname: username or courseid of destination for the file
 9009:    docudom: domain of user/course of destination for the file
 9010:    dir: dir to create (including any subdirs under userfiles)
 9011: 
 9012: =item *
 9013: 
 9014: removeuserfile(): removes a file that exists in userfiles
 9015: 
 9016:   Args:
 9017:    docuname: username or courseid of destination for the file
 9018:    docudom: domain of user/course of destination for the file
 9019:    fname: filname to delete (including any subdirs under userfiles)
 9020: 
 9021: =item *
 9022: 
 9023: removeuploadedurl(): convience function for removeuserfile()
 9024: 
 9025:   Args:
 9026:    url:  a full /uploaded/... url to delete
 9027: 
 9028: =item * 
 9029: 
 9030: get_portfile_permissions():
 9031:   Args:
 9032:     domain: domain of user or course contain the portfolio files
 9033:     user: name of user or num of course contain the portfolio files
 9034:   Returns:
 9035:     hashref of a dump of the proper file_permissions.db
 9036:    
 9037: 
 9038: =item * 
 9039: 
 9040: get_access_controls():
 9041: 
 9042: Args:
 9043:   current_permissions: the hash ref returned from get_portfile_permissions()
 9044:   group: (optional) the group you want the files associated with
 9045:   file: (optional) the file you want access info on
 9046: 
 9047: Returns:
 9048:     a hash (keys are file names) of hashes containing
 9049:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9050:         values are XML containing access control settings (see below) 
 9051: 
 9052: Internal notes:
 9053: 
 9054:  access controls are stored in file_permissions.db as key=value pairs.
 9055:     key -> path to file/file_name\0uniqueID:scope_end_start
 9056:         where scope -> public,guest,course,group,domains or users.
 9057:               end -> UNIX time for end of access (0 -> no end date)
 9058:               start -> UNIX time for start of access
 9059: 
 9060:     value -> XML description of access control
 9061:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9062:             <start></start>
 9063:             <end></end>
 9064: 
 9065:             <password></password>  for scope type = guest
 9066: 
 9067:             <domain></domain>     for scope type = course or group
 9068:             <number></number>
 9069:             <roles id="">
 9070:              <role></role>
 9071:              <access></access>
 9072:              <section></section>
 9073:              <group></group>
 9074:             </roles>
 9075: 
 9076:             <dom></dom>         for scope type = domains
 9077: 
 9078:             <users>             for scope type = users
 9079:              <user>
 9080:               <uname></uname>
 9081:               <udom></udom>
 9082:              </user>
 9083:             </users>
 9084:            </scope> 
 9085:               
 9086:  Access data is also aggregated for each file in an additional key=value pair:
 9087:  key -> path to file/file_name\0accesscontrol 
 9088:  value -> reference to hash
 9089:           hash contains key = value pairs
 9090:           where key = uniqueID:scope_end_start
 9091:                 value = UNIX time record was last updated
 9092: 
 9093:           Used to improve speed of look-ups of access controls for each file.  
 9094:  
 9095:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9096: 
 9097: modify_access_controls():
 9098: 
 9099: Modifies access controls for a portfolio file
 9100: Args
 9101: 1. file name
 9102: 2. reference to hash of required changes,
 9103: 3. domain
 9104: 4. username
 9105:   where domain,username are the domain of the portfolio owner 
 9106:   (either a user or a course) 
 9107: 
 9108: Returns:
 9109: 1. result of additions or updates ('ok' or 'error', with error message). 
 9110: 2. result of deletions ('ok' or 'error', with error message).
 9111: 3. reference to hash of any new or updated access controls.
 9112: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9113:    key = integer (inbound ID)
 9114:    value = uniqueID  
 9115: 
 9116: =back
 9117: 
 9118: =head2 HTTP Helper Routines
 9119: 
 9120: =over 4
 9121: 
 9122: =item *
 9123: 
 9124: escape() : unpack non-word characters into CGI-compatible hex codes
 9125: 
 9126: =item *
 9127: 
 9128: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9129: 
 9130: =back
 9131: 
 9132: =head1 PRIVATE SUBROUTINES
 9133: 
 9134: =head2 Underlying communication routines (Shouldn't call)
 9135: 
 9136: =over 4
 9137: 
 9138: =item *
 9139: 
 9140: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9141: 
 9142: =item *
 9143: 
 9144: reply() : uses subreply to send a message to remote machine, logs all failures
 9145: 
 9146: =item *
 9147: 
 9148: critical() : passes a critical message to another server; if cannot
 9149: get through then place message in connection buffer directory and
 9150: returns con_delayed, if incapable of saving message, returns
 9151: con_failed
 9152: 
 9153: =item *
 9154: 
 9155: reconlonc() : tries to reconnect lonc client processes.
 9156: 
 9157: =back
 9158: 
 9159: =head2 Resource Access Logging
 9160: 
 9161: =over 4
 9162: 
 9163: =item *
 9164: 
 9165: flushcourselogs() : flush (save) buffer logs and access logs
 9166: 
 9167: =item *
 9168: 
 9169: courselog($what) : save message for course in hash
 9170: 
 9171: =item *
 9172: 
 9173: courseacclog($what) : save message for course using &courselog().  Perform
 9174: special processing for specific resource types (problems, exams, quizzes, etc).
 9175: 
 9176: =item *
 9177: 
 9178: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9179: as a PerlChildExitHandler
 9180: 
 9181: =back
 9182: 
 9183: =head2 Other
 9184: 
 9185: =over 4
 9186: 
 9187: =item *
 9188: 
 9189: symblist($mapname,%newhash) : update symbolic storage links
 9190: 
 9191: =back
 9192: 
 9193: =cut

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