File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.953: download - view: text, annotated - select for diffs
Fri Mar 28 14:52:57 2008 UTC (16 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Saving my work, bug #5631. This might not work at all yet.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.953 2008/03/28 14:52:57 www 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($hostname))."\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:     my ($lonid) = @_;
  218:     my $hostname = &hostname($lonid);
  219:     if ($lonid) {
  220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  221: 	if ($hostname && -e $peerfile) {
  222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  224: 					     Type    => SOCK_STREAM,
  225: 					     Timeout => 10);
  226: 	    if ($client) {
  227: 		print $client ("reset_retries\n");
  228: 		my $answer=<$client>;
  229: 		#reset just this one.
  230: 	    }
  231: 	}
  232: 	return;
  233:     }
  234: 
  235:     &logthis("Trying to reconnect lonc");
  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  237:     if (open(my $fh,"<$loncfile")) {
  238: 	my $loncpid=<$fh>;
  239:         chomp($loncpid);
  240:         if (kill 0 => $loncpid) {
  241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  242:             kill USR1 => $loncpid;
  243:             sleep 1;
  244:          } else {
  245: 	    &logthis(
  246:                "<font color=\"blue\">WARNING:".
  247:                " lonc at pid $loncpid not responding, giving up</font>");
  248:         }
  249:     } else {
  250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  251:     }
  252: }
  253: 
  254: # ------------------------------------------------------ Critical communication
  255: 
  256: sub critical {
  257:     my ($cmd,$server)=@_;
  258:     unless (&hostname($server)) {
  259:         &logthis("<font color=\"blue\">WARNING:".
  260:                " Critical message to unknown server ($server)</font>");
  261:         return 'no_such_host';
  262:     }
  263:     my $answer=reply($cmd,$server);
  264:     if ($answer eq 'con_lost') {
  265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  266: 	my $answer=reply($cmd,$server);
  267:         if ($answer eq 'con_lost') {
  268:             my $now=time;
  269:             my $middlename=$cmd;
  270:             $middlename=substr($middlename,0,16);
  271:             $middlename=~s/\W//g;
  272:             my $dfilename=
  273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  274:             $dumpcount++;
  275:             {
  276: 		my $dfh;
  277: 		if (open($dfh,">$dfilename")) {
  278: 		    print $dfh "$cmd\n"; 
  279: 		    close($dfh);
  280: 		}
  281:             }
  282:             sleep 2;
  283:             my $wcmd='';
  284:             {
  285: 		my $dfh;
  286: 		if (open($dfh,"<$dfilename")) {
  287: 		    $wcmd=<$dfh>; 
  288: 		    close($dfh);
  289: 		}
  290:             }
  291:             chomp($wcmd);
  292:             if ($wcmd eq $cmd) {
  293: 		&logthis("<font color=\"blue\">WARNING: ".
  294:                          "Connection buffer $dfilename: $cmd</font>");
  295:                 &logperm("D:$server:$cmd");
  296: 	        return 'con_delayed';
  297:             } else {
  298:                 &logthis("<font color=\"red\">CRITICAL:"
  299:                         ." Critical connection failed: $server $cmd</font>");
  300:                 &logperm("F:$server:$cmd");
  301:                 return 'con_failed';
  302:             }
  303:         }
  304:     }
  305:     return $answer;
  306: }
  307: 
  308: # ------------------------------------------- check if return value is an error
  309: 
  310: sub error {
  311:     my ($result) = @_;
  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  313: 	if ($2 == 2) { return undef; }
  314: 	return $1;
  315:     }
  316:     return undef;
  317: }
  318: 
  319: sub convert_and_load_session_env {
  320:     my ($lonidsdir,$handle)=@_;
  321:     my @profile;
  322:     {
  323: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  324: 	if (!$opened) {
  325: 	    return 0;
  326: 	}
  327: 	flock($idf,LOCK_SH);
  328: 	@profile=<$idf>;
  329: 	close($idf);
  330:     }
  331:     my %temp_env;
  332:     foreach my $line (@profile) {
  333: 	if ($line !~ m/=/) {
  334: 	    return 0;
  335: 	}
  336: 	chomp($line);
  337: 	my ($envname,$envvalue)=split(/=/,$line,2);
  338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  339:     }
  340:     unlink("$lonidsdir/$handle.id");
  341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  342: 	    0640)) {
  343: 	%disk_env = %temp_env;
  344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  345: 	untie(%disk_env);
  346:     }
  347:     return 1;
  348: }
  349: 
  350: # ------------------------------------------- Transfer profile into environment
  351: my $env_loaded;
  352: sub transfer_profile_to_env {
  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
  354:     if (!$force_transfer && $env_loaded) { return; } 
  355: 
  356:     if (!defined($lonidsdir)) {
  357: 	$lonidsdir = $perlvar{'lonIDsDir'};
  358:     }
  359:     if (!defined($handle)) {
  360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  361:     }
  362: 
  363:     my $convert;
  364:     {
  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  366: 	if (!$opened) {
  367: 	    return;
  368: 	}
  369: 	flock($idf,LOCK_SH);
  370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  371: 		&GDBM_READER(),0640)) {
  372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  373: 	    untie(%disk_env);
  374: 	} else {
  375: 	    $convert = 1;
  376: 	}
  377:     }
  378:     if ($convert) {
  379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  380: 	    &logthis("Failed to load session, or convert session.");
  381: 	}
  382:     }
  383: 
  384:     my %remove;
  385:     while ( my $envname = each(%env) ) {
  386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  387:             if ($time < time-300) {
  388:                 $remove{$key}++;
  389:             }
  390:         }
  391:     }
  392: 
  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  394:     $env_loaded=1;
  395:     foreach my $expired_key (keys(%remove)) {
  396:         &delenv($expired_key);
  397:     }
  398: }
  399: 
  400: # ---------------------------------------------------- Check for valid session 
  401: sub check_for_valid_session {
  402:     my ($r) = @_;
  403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  404:     my $lonid=$cookies{'lonID'};
  405:     return undef if (!$lonid);
  406: 
  407:     my $handle=&LONCAPA::clean_handle($lonid->value);
  408:     my $lonidsdir=$r->dir_config('lonIDsDir');
  409:     return undef if (!-e "$lonidsdir/$handle.id");
  410: 
  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  412:     return undef if (!$opened);
  413: 
  414:     flock($idf,LOCK_SH);
  415:     my %disk_env;
  416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  417: 	    &GDBM_READER(),0640)) {
  418: 	return undef;	
  419:     }
  420: 
  421:     if (!defined($disk_env{'user.name'})
  422: 	|| !defined($disk_env{'user.domain'})) {
  423: 	return undef;
  424:     }
  425:     return $handle;
  426: }
  427: 
  428: sub timed_flock {
  429:     my ($file,$lock_type) = @_;
  430:     my $failed=0;
  431:     eval {
  432: 	local $SIG{__DIE__}='DEFAULT';
  433: 	local $SIG{ALRM}=sub {
  434: 	    $failed=1;
  435: 	    die("failed lock");
  436: 	};
  437: 	alarm(13);
  438: 	flock($file,$lock_type);
  439: 	alarm(0);
  440:     };
  441:     if ($failed) {
  442: 	return undef;
  443:     } else {
  444: 	return 1;
  445:     }
  446: }
  447: 
  448: # ---------------------------------------------------------- Append Environment
  449: 
  450: sub appenv {
  451:     my ($newenv,$roles) = @_;
  452:     if (ref($newenv) eq 'HASH') {
  453:         foreach my $key (keys(%{$newenv})) {
  454:             my $refused = 0;
  455: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  456:                 $refused = 1;
  457:                 if (ref($roles) eq 'ARRAY') {
  458:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  459:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  460:                         $refused = 0;
  461:                     }
  462:                 }
  463:             }
  464:             if ($refused) {
  465:                 &logthis("<font color=\"blue\">WARNING: ".
  466:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  467:                          .'</font>');
  468: 	        delete($newenv->{$key});
  469:             } else {
  470:                 $env{$key}=$newenv->{$key};
  471:             }
  472:         }
  473:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  474:         if ($opened
  475: 	    && &timed_flock($env_file,LOCK_EX)
  476: 	    &&
  477: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  478: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  479: 	    while (my ($key,$value) = each(%{$newenv})) {
  480: 	        $disk_env{$key} = $value;
  481: 	    }
  482: 	    untie(%disk_env);
  483:         }
  484:     }
  485:     return 'ok';
  486: }
  487: # ----------------------------------------------------- Delete from Environment
  488: 
  489: sub delenv {
  490:     my $delthis=shift;
  491:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  492:         &logthis("<font color=\"blue\">WARNING: ".
  493:                 "Attempt to delete from environment ".$delthis);
  494:         return 'error';
  495:     }
  496:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  497:     if ($opened
  498: 	&& &timed_flock($env_file,LOCK_EX)
  499: 	&&
  500: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  501: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  502: 	foreach my $key (keys(%disk_env)) {
  503: 	    if ($key=~/^$delthis/) { 
  504: 		delete($env{$key});
  505: 		delete($disk_env{$key});
  506: 	    }
  507: 	}
  508: 	untie(%disk_env);
  509:     }
  510:     return 'ok';
  511: }
  512: 
  513: sub get_env_multiple {
  514:     my ($name) = @_;
  515:     my @values;
  516:     if (defined($env{$name})) {
  517:         # exists is it an array
  518:         if (ref($env{$name})) {
  519:             @values=@{ $env{$name} };
  520:         } else {
  521:             $values[0]=$env{$name};
  522:         }
  523:     }
  524:     return(@values);
  525: }
  526: 
  527: # ------------------------------------------ Find out current server userload
  528: sub userload {
  529:     my $numusers=0;
  530:     {
  531: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  532: 	my $filename;
  533: 	my $curtime=time;
  534: 	while ($filename=readdir(LONIDS)) {
  535: 	    next if ($filename eq '.' || $filename eq '..');
  536: 	    next if ($filename =~ /publicuser_\d+\.id/);
  537: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  538: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  539: 	}
  540: 	closedir(LONIDS);
  541:     }
  542:     my $userloadpercent=0;
  543:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  544:     if ($maxuserload) {
  545: 	$userloadpercent=100*$numusers/$maxuserload;
  546:     }
  547:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  548:     return $userloadpercent;
  549: }
  550: 
  551: # ------------------------------------------ Fight off request when overloaded
  552: 
  553: sub overloaderror {
  554:     my ($r,$checkserver)=@_;
  555:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  556:     my $loadavg;
  557:     if ($checkserver eq $perlvar{'lonHostID'}) {
  558:        open(my $loadfile,'/proc/loadavg');
  559:        $loadavg=<$loadfile>;
  560:        $loadavg =~ s/\s.*//g;
  561:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  562:        close($loadfile);
  563:     } else {
  564:        $loadavg=&reply('load',$checkserver);
  565:     }
  566:     my $overload=$loadavg-100;
  567:     if ($overload>0) {
  568: 	$r->err_headers_out->{'Retry-After'}=$overload;
  569:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  570:         return 413;
  571:     }    
  572:     return '';
  573: }
  574: 
  575: # ------------------------------ Find server with least workload from spare.tab
  576: 
  577: sub spareserver {
  578:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  579:     my $spare_server;
  580:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  581:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  582:                                                      :  $userloadpercent;
  583:     
  584:     foreach my $try_server (@{ $spareid{'primary'} }) {
  585: 	($spare_server, $lowest_load) =
  586: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  587:     }
  588: 
  589:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  590: 
  591:     if (!$found_server) {
  592: 	foreach my $try_server (@{ $spareid{'default'} }) {
  593: 	    ($spare_server, $lowest_load) =
  594: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  595: 	}
  596:     }
  597: 
  598:     if (!$want_server_name) {
  599: 	$spare_server="http://".&hostname($spare_server);
  600:     }
  601:     return $spare_server;
  602: }
  603: 
  604: sub compare_server_load {
  605:     my ($try_server, $spare_server, $lowest_load) = @_;
  606: 
  607:     my $loadans     = &reply('load',    $try_server);
  608:     my $userloadans = &reply('userload',$try_server);
  609: 
  610:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  611: 	next; #didn't get a number from the server
  612:     }
  613: 
  614:     my $load;
  615:     if ($loadans =~ /\d/) {
  616: 	if ($userloadans =~ /\d/) {
  617: 	    #both are numbers, pick the bigger one
  618: 	    $load = ($loadans > $userloadans) ? $loadans 
  619: 		                              : $userloadans;
  620: 	} else {
  621: 	    $load = $loadans;
  622: 	}
  623:     } else {
  624: 	$load = $userloadans;
  625:     }
  626: 
  627:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  628: 	$spare_server = $try_server;
  629: 	$lowest_load  = $load;
  630:     }
  631:     return ($spare_server,$lowest_load);
  632: }
  633: 
  634: # --------------------------- ask offload servers if user already has a session
  635: sub find_existing_session {
  636:     my ($udom,$uname) = @_;
  637:     foreach my $try_server (@{ $spareid{'primary'} },
  638: 			    @{ $spareid{'default'} }) {
  639: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  640:     }
  641:     return;
  642: }
  643: 
  644: # -------------------------------- ask if server already has a session for user
  645: sub has_user_session {
  646:     my ($lonid,$udom,$uname) = @_;
  647:     my $result = &reply(join(':','userhassession',
  648: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  649:     return 1 if ($result eq 'ok');
  650: 
  651:     return 0;
  652: }
  653: 
  654: # --------------------------------------------- Try to change a user's password
  655: 
  656: sub changepass {
  657:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  658:     $currentpass = &escape($currentpass);
  659:     $newpass     = &escape($newpass);
  660:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  661: 		       $server);
  662:     if (! $answer) {
  663: 	&logthis("No reply on password change request to $server ".
  664: 		 "by $uname in domain $udom.");
  665:     } elsif ($answer =~ "^ok") {
  666:         &logthis("$uname in $udom successfully changed their password ".
  667: 		 "on $server.");
  668:     } elsif ($answer =~ "^pwchange_failure") {
  669: 	&logthis("$uname in $udom was unable to change their password ".
  670: 		 "on $server.  The action was blocked by either lcpasswd ".
  671: 		 "or pwchange");
  672:     } elsif ($answer =~ "^non_authorized") {
  673:         &logthis("$uname in $udom did not get their password correct when ".
  674: 		 "attempting to change it on $server.");
  675:     } elsif ($answer =~ "^auth_mode_error") {
  676:         &logthis("$uname in $udom attempted to change their password despite ".
  677: 		 "not being locally or internally authenticated on $server.");
  678:     } elsif ($answer =~ "^unknown_user") {
  679:         &logthis("$uname in $udom attempted to change their password ".
  680: 		 "on $server but were unable to because $server is not ".
  681: 		 "their home server.");
  682:     } elsif ($answer =~ "^refused") {
  683: 	&logthis("$server refused to change $uname in $udom password because ".
  684: 		 "it was sent an unencrypted request to change the password.");
  685:     }
  686:     return $answer;
  687: }
  688: 
  689: # ----------------------- Try to determine user's current authentication scheme
  690: 
  691: sub queryauthenticate {
  692:     my ($uname,$udom)=@_;
  693:     my $uhome=&homeserver($uname,$udom);
  694:     if (!$uhome) {
  695: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  696: 	return 'no_host';
  697:     }
  698:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  699:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  700: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  701:     }
  702:     return $answer;
  703: }
  704: 
  705: # --------- Try to authenticate user from domain's lib servers (first this one)
  706: 
  707: sub authenticate {
  708:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  709:     $upass=&escape($upass);
  710:     $uname= &LONCAPA::clean_username($uname);
  711:     my $uhome=&homeserver($uname,$udom,1);
  712:     my $newhome;
  713:     if ((!$uhome) || ($uhome eq 'no_host')) {
  714: # Maybe the machine was offline and only re-appeared again recently?
  715:         &reconlonc();
  716: # One more
  717: 	$uhome=&homeserver($uname,$udom,1);
  718:         if (($uhome eq 'no_host') && $checkdefauth) {
  719:             if (defined(&domain($udom,'primary'))) {
  720:                 $newhome=&domain($udom,'primary');
  721:             }
  722:             if ($newhome ne '') {
  723:                 $uhome = $newhome;
  724:             }
  725:         }
  726: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  727: 	    &logthis("User $uname at $udom is unknown in authenticate");
  728: 	    return 'no_host';
  729:         }
  730:     }
  731:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  732:     if ($answer eq 'authorized') {
  733:         if ($newhome) {
  734:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  735:             return 'no_account_on_host'; 
  736:         } else {
  737:             &logthis("User $uname at $udom authorized by $uhome");
  738:             return $uhome;
  739:         }
  740:     }
  741:     if ($answer eq 'non_authorized') {
  742: 	&logthis("User $uname at $udom rejected by $uhome");
  743: 	return 'no_host'; 
  744:     }
  745:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  746:     return 'no_host';
  747: }
  748: 
  749: # ---------------------- Find the homebase for a user from domain's lib servers
  750: 
  751: my %homecache;
  752: sub homeserver {
  753:     my ($uname,$udom,$ignoreBadCache)=@_;
  754:     my $index="$uname:$udom";
  755: 
  756:     if (exists($homecache{$index})) { return $homecache{$index}; }
  757: 
  758:     my %servers = &get_servers($udom,'library');
  759:     foreach my $tryserver (keys(%servers)) {
  760:         next if ($ignoreBadCache ne 'true' && 
  761: 		 exists($badServerCache{$tryserver}));
  762: 
  763: 	my $answer=reply("home:$udom:$uname",$tryserver);
  764: 	if ($answer eq 'found') {
  765: 	    delete($badServerCache{$tryserver}); 
  766: 	    return $homecache{$index}=$tryserver;
  767: 	} elsif ($answer eq 'no_host') {
  768: 	    $badServerCache{$tryserver}=1;
  769: 	}
  770:     }    
  771:     return 'no_host';
  772: }
  773: 
  774: # ------------------------------------- Find the usernames behind a list of IDs
  775: 
  776: sub idget {
  777:     my ($udom,@ids)=@_;
  778:     my %returnhash=();
  779:     
  780:     my %servers = &get_servers($udom,'library');
  781:     foreach my $tryserver (keys(%servers)) {
  782: 	my $idlist=join('&',@ids);
  783: 	$idlist=~tr/A-Z/a-z/; 
  784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  785: 	my @answer=();
  786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  787: 	    @answer=split(/\&/,$reply);
  788: 	}                    ;
  789: 	my $i;
  790: 	for ($i=0;$i<=$#ids;$i++) {
  791: 	    if ($answer[$i]) {
  792: 		$returnhash{$ids[$i]}=$answer[$i];
  793: 	    } 
  794: 	}
  795:     } 
  796:     return %returnhash;
  797: }
  798: 
  799: # ------------------------------------- Find the IDs behind a list of usernames
  800: 
  801: sub idrget {
  802:     my ($udom,@unames)=@_;
  803:     my %returnhash=();
  804:     foreach my $uname (@unames) {
  805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  806:     }
  807:     return %returnhash;
  808: }
  809: 
  810: # ------------------------------- Store away a list of names and associated IDs
  811: 
  812: sub idput {
  813:     my ($udom,%ids)=@_;
  814:     my %servers=();
  815:     foreach my $uname (keys(%ids)) {
  816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  817:         my $uhom=&homeserver($uname,$udom);
  818:         if ($uhom ne 'no_host') {
  819:             my $id=&escape($ids{$uname});
  820:             $id=~tr/A-Z/a-z/;
  821:             my $esc_unam=&escape($uname);
  822: 	    if ($servers{$uhom}) {
  823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  824:             } else {
  825:                 $servers{$uhom}=$id.'='.$esc_unam;
  826:             }
  827:         }
  828:     }
  829:     foreach my $server (keys(%servers)) {
  830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  831:     }
  832: }
  833: 
  834: # ------------------------------------------- get items from domain db files   
  835: 
  836: sub get_dom {
  837:     my ($namespace,$storearr,$udom,$uhome)=@_;
  838:     my $items='';
  839:     foreach my $item (@$storearr) {
  840:         $items.=&escape($item).'&';
  841:     }
  842:     $items=~s/\&$//;
  843:     if (!$udom) {
  844:         $udom=$env{'user.domain'};
  845:         if (defined(&domain($udom,'primary'))) {
  846:             $uhome=&domain($udom,'primary');
  847:         } else {
  848:             undef($uhome);
  849:         }
  850:     } else {
  851:         if (!$uhome) {
  852:             if (defined(&domain($udom,'primary'))) {
  853:                 $uhome=&domain($udom,'primary');
  854:             }
  855:         }
  856:     }
  857:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  858:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  859:         my %returnhash;
  860:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  861:             return %returnhash;
  862:         }
  863:         my @pairs=split(/\&/,$rep);
  864:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  865:             return @pairs;
  866:         }
  867:         my $i=0;
  868:         foreach my $item (@$storearr) {
  869:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  870:             $i++;
  871:         }
  872:         return %returnhash;
  873:     } else {
  874:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  875:     }
  876: }
  877: 
  878: # -------------------------------------------- put items in domain db files 
  879: 
  880: sub put_dom {
  881:     my ($namespace,$storehash,$udom,$uhome)=@_;
  882:     if (!$udom) {
  883:         $udom=$env{'user.domain'};
  884:         if (defined(&domain($udom,'primary'))) {
  885:             $uhome=&domain($udom,'primary');
  886:         } else {
  887:             undef($uhome);
  888:         }
  889:     } else {
  890:         if (!$uhome) {
  891:             if (defined(&domain($udom,'primary'))) {
  892:                 $uhome=&domain($udom,'primary');
  893:             }
  894:         }
  895:     } 
  896:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  897:         my $items='';
  898:         foreach my $item (keys(%$storehash)) {
  899:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  900:         }
  901:         $items=~s/\&$//;
  902:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  903:     } else {
  904:         &logthis("put_dom failed - no homeserver and/or domain");
  905:     }
  906: }
  907: 
  908: sub retrieve_inst_usertypes {
  909:     my ($udom) = @_;
  910:     my (%returnhash,@order);
  911:     if (defined(&domain($udom,'primary'))) {
  912:         my $uhome=&domain($udom,'primary');
  913:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  914:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  915:         my @pairs=split(/\&/,$hashitems);
  916:         foreach my $item (@pairs) {
  917:             my ($key,$value)=split(/=/,$item,2);
  918:             $key = &unescape($key);
  919:             next if ($key =~ /^error: 2 /);
  920:             $returnhash{$key}=&thaw_unescape($value);
  921:         }
  922:         my @esc_order = split(/\&/,$orderitems);
  923:         foreach my $item (@esc_order) {
  924:             push(@order,&unescape($item));
  925:         }
  926:     } else {
  927:         &logthis("get_dom failed - no primary domain server for $udom");
  928:     }
  929:     return (\%returnhash,\@order);
  930: }
  931: 
  932: sub is_domainimage {
  933:     my ($url) = @_;
  934:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  935:         if (&domain($1) ne '') {
  936:             return '1';
  937:         }
  938:     }
  939:     return;
  940: }
  941: 
  942: sub inst_directory_query {
  943:     my ($srch) = @_;
  944:     my $udom = $srch->{'srchdomain'};
  945:     my %results;
  946:     my $homeserver = &domain($udom,'primary');
  947:     my $outcome;
  948:     if ($homeserver ne '') {
  949: 	my $queryid=&reply("querysend:instdirsearch:".
  950: 			   &escape($srch->{'srchby'}).':'.
  951: 			   &escape($srch->{'srchterm'}).':'.
  952: 			   &escape($srch->{'srchtype'}),$homeserver);
  953: 	my $host=&hostname($homeserver);
  954: 	if ($queryid !~/^\Q$host\E\_/) {
  955: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  956: 	    return;
  957: 	}
  958: 	my $response = &get_query_reply($queryid);
  959: 	my $maxtries = 5;
  960: 	my $tries = 1;
  961: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  962: 	    $response = &get_query_reply($queryid);
  963: 	    $tries ++;
  964: 	}
  965: 
  966:         if (!&error($response) && $response ne 'refused') {
  967:             if ($response eq 'unavailable') {
  968:                 $outcome = $response;
  969:             } else {
  970:                 $outcome = 'ok';
  971:                 my @matches = split(/\n/,$response);
  972:                 foreach my $match (@matches) {
  973:                     my ($key,$value) = split(/=/,$match);
  974:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  975:                 }
  976:             }
  977:         }
  978:     }
  979:     return ($outcome,%results);
  980: }
  981: 
  982: sub usersearch {
  983:     my ($srch) = @_;
  984:     my $dom = $srch->{'srchdomain'};
  985:     my %results;
  986:     my %libserv = &all_library();
  987:     my $query = 'usersearch';
  988:     foreach my $tryserver (keys(%libserv)) {
  989:         if (&host_domain($tryserver) eq $dom) {
  990:             my $host=&hostname($tryserver);
  991:             my $queryid=
  992:                 &reply("querysend:".&escape($query).':'.
  993:                        &escape($srch->{'srchby'}).':'.
  994:                        &escape($srch->{'srchtype'}).':'.
  995:                        &escape($srch->{'srchterm'}),$tryserver);
  996:             if ($queryid !~/^\Q$host\E\_/) {
  997:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  998:                 next;
  999:             }
 1000:             my $reply = &get_query_reply($queryid);
 1001:             my $maxtries = 1;
 1002:             my $tries = 1;
 1003:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1004:                 $reply = &get_query_reply($queryid);
 1005:                 $tries ++;
 1006:             }
 1007:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1008:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1009:             } else {
 1010:                 my @matches;
 1011:                 if ($reply =~ /\n/) {
 1012:                     @matches = split(/\n/,$reply);
 1013:                 } else {
 1014:                     @matches = split(/\&/,$reply);
 1015:                 }
 1016:                 foreach my $match (@matches) {
 1017:                     my ($uname,$udom,%userhash);
 1018:                     foreach my $entry (split(/:/,$match)) {
 1019:                         my ($key,$value) =
 1020:                             map {&unescape($_);} split(/=/,$entry);
 1021:                         $userhash{$key} = $value;
 1022:                         if ($key eq 'username') {
 1023:                             $uname = $value;
 1024:                         } elsif ($key eq 'domain') {
 1025:                             $udom = $value;
 1026:                         }
 1027:                     }
 1028:                     $results{$uname.':'.$udom} = \%userhash;
 1029:                 }
 1030:             }
 1031:         }
 1032:     }
 1033:     return %results;
 1034: }
 1035: 
 1036: sub get_instuser {
 1037:     my ($udom,$uname,$id) = @_;
 1038:     my $homeserver = &domain($udom,'primary');
 1039:     my ($outcome,%results);
 1040:     if ($homeserver ne '') {
 1041:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1042:                            &escape($id).':'.&escape($udom),$homeserver);
 1043:         my $host=&hostname($homeserver);
 1044:         if ($queryid !~/^\Q$host\E\_/) {
 1045:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1046:             return;
 1047:         }
 1048:         my $response = &get_query_reply($queryid);
 1049:         my $maxtries = 5;
 1050:         my $tries = 1;
 1051:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1052:             $response = &get_query_reply($queryid);
 1053:             $tries ++;
 1054:         }
 1055:         if (!&error($response) && $response ne 'refused') {
 1056:             if ($response eq 'unavailable') {
 1057:                 $outcome = $response;
 1058:             } else {
 1059:                 $outcome = 'ok';
 1060:                 my @matches = split(/\n/,$response);
 1061:                 foreach my $match (@matches) {
 1062:                     my ($key,$value) = split(/=/,$match);
 1063:                     $results{&unescape($key)} = &thaw_unescape($value);
 1064:                 }
 1065:             }
 1066:         }
 1067:     }
 1068:     my %userinfo;
 1069:     if (ref($results{$uname}) eq 'HASH') {
 1070:         %userinfo = %{$results{$uname}};
 1071:     } 
 1072:     return ($outcome,%userinfo);
 1073: }
 1074: 
 1075: sub inst_rulecheck {
 1076:     my ($udom,$uname,$id,$item,$rules) = @_;
 1077:     my %returnhash;
 1078:     if ($udom ne '') {
 1079:         if (ref($rules) eq 'ARRAY') {
 1080:             @{$rules} = map {&escape($_);} (@{$rules});
 1081:             my $rulestr = join(':',@{$rules});
 1082:             my $homeserver=&domain($udom,'primary');
 1083:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1084:                 my $response;
 1085:                 if ($item eq 'username') {                
 1086:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1087:                                               ':'.&escape($uname).':'.$rulestr,
 1088:                                               $homeserver));
 1089:                 } elsif ($item eq 'id') {
 1090:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1091:                                               ':'.&escape($id).':'.$rulestr,
 1092:                                               $homeserver));
 1093:                 } elsif ($item eq 'selfcreate') {
 1094:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1095:                                                &escape($udom).':'.&escape($uname).
 1096:                                               ':'.$rulestr,$homeserver));
 1097:                 }
 1098:                 if ($response ne 'refused') {
 1099:                     my @pairs=split(/\&/,$response);
 1100:                     foreach my $item (@pairs) {
 1101:                         my ($key,$value)=split(/=/,$item,2);
 1102:                         $key = &unescape($key);
 1103:                         next if ($key =~ /^error: 2 /);
 1104:                         $returnhash{$key}=&thaw_unescape($value);
 1105:                     }
 1106:                 }
 1107:             }
 1108:         }
 1109:     }
 1110:     return %returnhash;
 1111: }
 1112: 
 1113: sub inst_userrules {
 1114:     my ($udom,$check) = @_;
 1115:     my (%ruleshash,@ruleorder);
 1116:     if ($udom ne '') {
 1117:         my $homeserver=&domain($udom,'primary');
 1118:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1119:             my $response;
 1120:             if ($check eq 'id') {
 1121:                 $response=&reply('instidrules:'.&escape($udom),
 1122:                                  $homeserver);
 1123:             } elsif ($check eq 'email') {
 1124:                 $response=&reply('instemailrules:'.&escape($udom),
 1125:                                  $homeserver);
 1126:             } else {
 1127:                 $response=&reply('instuserrules:'.&escape($udom),
 1128:                                  $homeserver);
 1129:             }
 1130:             if (($response ne 'refused') && ($response ne 'error') && 
 1131:                 ($response ne 'unknown_cmd') && 
 1132:                 ($response ne 'no_such_host')) {
 1133:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1134:                 my @pairs=split(/\&/,$hashitems);
 1135:                 foreach my $item (@pairs) {
 1136:                     my ($key,$value)=split(/=/,$item,2);
 1137:                     $key = &unescape($key);
 1138:                     next if ($key =~ /^error: 2 /);
 1139:                     $ruleshash{$key}=&thaw_unescape($value);
 1140:                 }
 1141:                 my @esc_order = split(/\&/,$orderitems);
 1142:                 foreach my $item (@esc_order) {
 1143:                     push(@ruleorder,&unescape($item));
 1144:                 }
 1145:             }
 1146:         }
 1147:     }
 1148:     return (\%ruleshash,\@ruleorder);
 1149: }
 1150: 
 1151: # ------------------------- Get Authentication and Language Defaults for Domain
 1152: 
 1153: sub get_domain_defaults {
 1154:     my ($domain) = @_;
 1155:     my $cachetime = 60*60*24;
 1156:     my ($defauthtype,$defautharg,$deflang);
 1157:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1158:     if (defined($cached)) {
 1159:         if (ref($result) eq 'HASH') {
 1160:             return %{$result};
 1161:         }
 1162:     }
 1163:     my %domdefaults;
 1164:     my %domconfig =
 1165:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
 1166:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1167:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1168:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1169:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1170:     } else {
 1171:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1172:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1173:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1174:     }
 1175:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1176:                                   $cachetime);
 1177:     return %domdefaults;
 1178: }
 1179: 
 1180: # --------------------------------------------------- Assign a key to a student
 1181: 
 1182: sub assign_access_key {
 1183: #
 1184: # a valid key looks like uname:udom#comments
 1185: # comments are being appended
 1186: #
 1187:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1188:     $kdom=
 1189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1190:     $knum=
 1191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1192:     $cdom=
 1193:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1194:     $cnum=
 1195:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1196:     $udom=$env{'user.name'} unless (defined($udom));
 1197:     $uname=$env{'user.domain'} unless (defined($uname));
 1198:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1199:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1200:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1201:                                                   # assigned to this person
 1202:                                                   # - this should not happen,
 1203:                                                   # unless something went wrong
 1204:                                                   # the first time around
 1205: # ready to assign
 1206:         $logentry=$1.'; '.$logentry;
 1207:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1208:                                                  $kdom,$knum) eq 'ok') {
 1209: # key now belongs to user
 1210: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1211:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1212:                 &appenv({'environment.'.$envkey => $ckey});
 1213:                 return 'ok';
 1214:             } else {
 1215:                 return 
 1216:   'error: Count not permanently assign key, will need to be re-entered later.';
 1217: 	    }
 1218:         } else {
 1219:             return 'error: Could not assign key, try again later.';
 1220:         }
 1221:     } elsif (!$existing{$ckey}) {
 1222: # the key does not exist
 1223: 	return 'error: The key does not exist';
 1224:     } else {
 1225: # the key is somebody else's
 1226: 	return 'error: The key is already in use';
 1227:     }
 1228: }
 1229: 
 1230: # ------------------------------------------ put an additional comment on a key
 1231: 
 1232: sub comment_access_key {
 1233: #
 1234: # a valid key looks like uname:udom#comments
 1235: # comments are being appended
 1236: #
 1237:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1238:     $cdom=
 1239:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1240:     $cnum=
 1241:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1242:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1243:     if ($existing{$ckey}) {
 1244:         $existing{$ckey}.='; '.$logentry;
 1245: # ready to assign
 1246:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1247:                                                  $cdom,$cnum) eq 'ok') {
 1248: 	    return 'ok';
 1249:         } else {
 1250: 	    return 'error: Count not store comment.';
 1251:         }
 1252:     } else {
 1253: # the key does not exist
 1254: 	return 'error: The key does not exist';
 1255:     }
 1256: }
 1257: 
 1258: # ------------------------------------------------------ Generate a set of keys
 1259: 
 1260: sub generate_access_keys {
 1261:     my ($number,$cdom,$cnum,$logentry)=@_;
 1262:     $cdom=
 1263:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1264:     $cnum=
 1265:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1266:     unless (&allowed('mky',$cdom)) { return 0; }
 1267:     unless (($cdom) && ($cnum)) { return 0; }
 1268:     if ($number>10000) { return 0; }
 1269:     sleep(2); # make sure don't get same seed twice
 1270:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1271:     my $total=0;
 1272:     for (my $i=1;$i<=$number;$i++) {
 1273:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1274:                   sprintf("%lx",int(100000*rand)).'-'.
 1275:                   sprintf("%lx",int(100000*rand));
 1276:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1277:        $newkey=~s/0/h/g; # and also 0 and O
 1278:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1279:        if ($existing{$newkey}) {
 1280:            $i--;
 1281:        } else {
 1282: 	  if (&put('accesskeys',
 1283:               { $newkey => '# generated '.localtime().
 1284:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1285:                            '; '.$logentry },
 1286: 		   $cdom,$cnum) eq 'ok') {
 1287:               $total++;
 1288: 	  }
 1289:        }
 1290:     }
 1291:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1292:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1293:     return $total;
 1294: }
 1295: 
 1296: # ------------------------------------------------------- Validate an accesskey
 1297: 
 1298: sub validate_access_key {
 1299:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1300:     $cdom=
 1301:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1302:     $cnum=
 1303:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1304:     $udom=$env{'user.domain'} unless (defined($udom));
 1305:     $uname=$env{'user.name'} unless (defined($uname));
 1306:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1307:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1308: }
 1309: 
 1310: # ------------------------------------- Find the section of student in a course
 1311: sub devalidate_getsection_cache {
 1312:     my ($udom,$unam,$courseid)=@_;
 1313:     my $hashid="$udom:$unam:$courseid";
 1314:     &devalidate_cache_new('getsection',$hashid);
 1315: }
 1316: 
 1317: sub courseid_to_courseurl {
 1318:     my ($courseid) = @_;
 1319:     #already url style courseid
 1320:     return $courseid if ($courseid =~ m{^/});
 1321: 
 1322:     if (exists($env{'course.'.$courseid.'.num'})) {
 1323: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1324: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1325: 	return "/$cdom/$cnum";
 1326:     }
 1327: 
 1328:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1329:     if (exists($courseinfo{'num'})) {
 1330: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1331:     }
 1332: 
 1333:     return undef;
 1334: }
 1335: 
 1336: sub getsection {
 1337:     my ($udom,$unam,$courseid)=@_;
 1338:     my $cachetime=1800;
 1339: 
 1340:     my $hashid="$udom:$unam:$courseid";
 1341:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1342:     if (defined($cached)) { return $result; }
 1343: 
 1344:     my %Pending; 
 1345:     my %Expired;
 1346:     #
 1347:     # Each role can either have not started yet (pending), be active, 
 1348:     #    or have expired.
 1349:     #
 1350:     # If there is an active role, we are done.
 1351:     #
 1352:     # If there is more than one role which has not started yet, 
 1353:     #     choose the one which will start sooner
 1354:     # If there is one role which has not started yet, return it.
 1355:     #
 1356:     # If there is more than one expired role, choose the one which ended last.
 1357:     # If there is a role which has expired, return it.
 1358:     #
 1359:     $courseid = &courseid_to_courseurl($courseid);
 1360:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1361:     foreach my $key (keys(%roleshash)) {
 1362:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1363:         my $section=$1;
 1364:         if ($key eq $courseid.'_st') { $section=''; }
 1365:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1366:         my $now=time;
 1367:         if (defined($end) && $end && ($now > $end)) {
 1368:             $Expired{$end}=$section;
 1369:             next;
 1370:         }
 1371:         if (defined($start) && $start && ($now < $start)) {
 1372:             $Pending{$start}=$section;
 1373:             next;
 1374:         }
 1375:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1376:     }
 1377:     #
 1378:     # Presumedly there will be few matching roles from the above
 1379:     # loop and the sorting time will be negligible.
 1380:     if (scalar(keys(%Pending))) {
 1381:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1382:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1383:     } 
 1384:     if (scalar(keys(%Expired))) {
 1385:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1386:         my $time = pop(@sorted);
 1387:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1388:     }
 1389:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1390: }
 1391: 
 1392: sub save_cache {
 1393:     &purge_remembered();
 1394:     #&Apache::loncommon::validate_page();
 1395:     undef(%env);
 1396:     undef($env_loaded);
 1397: }
 1398: 
 1399: my $to_remember=-1;
 1400: my %remembered;
 1401: my %accessed;
 1402: my $kicks=0;
 1403: my $hits=0;
 1404: sub make_key {
 1405:     my ($name,$id) = @_;
 1406:     if (length($id) > 65 
 1407: 	&& length(&escape($id)) > 200) {
 1408: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1409:     }
 1410:     return &escape($name.':'.$id);
 1411: }
 1412: 
 1413: sub devalidate_cache_new {
 1414:     my ($name,$id,$debug) = @_;
 1415:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1416:     $id=&make_key($name,$id);
 1417:     $memcache->delete($id);
 1418:     delete($remembered{$id});
 1419:     delete($accessed{$id});
 1420: }
 1421: 
 1422: sub is_cached_new {
 1423:     my ($name,$id,$debug) = @_;
 1424:     $id=&make_key($name,$id);
 1425:     if (exists($remembered{$id})) {
 1426: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1427: 	$accessed{$id}=[&gettimeofday()];
 1428: 	$hits++;
 1429: 	return ($remembered{$id},1);
 1430:     }
 1431:     my $value = $memcache->get($id);
 1432:     if (!(defined($value))) {
 1433: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1434: 	return (undef,undef);
 1435:     }
 1436:     if ($value eq '__undef__') {
 1437: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1438: 	$value=undef;
 1439:     }
 1440:     &make_room($id,$value,$debug);
 1441:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1442:     return ($value,1);
 1443: }
 1444: 
 1445: sub do_cache_new {
 1446:     my ($name,$id,$value,$time,$debug) = @_;
 1447:     $id=&make_key($name,$id);
 1448:     my $setvalue=$value;
 1449:     if (!defined($setvalue)) {
 1450: 	$setvalue='__undef__';
 1451:     }
 1452:     if (!defined($time) ) {
 1453: 	$time=600;
 1454:     }
 1455:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1456:     my $result = $memcache->set($id,$setvalue,$time);
 1457:     if (! $result) {
 1458: 	&logthis("caching of id -> $id  failed");
 1459: 	$memcache->disconnect_all();
 1460:     }
 1461:     # need to make a copy of $value
 1462:     &make_room($id,$value,$debug);
 1463:     return $value;
 1464: }
 1465: 
 1466: sub make_room {
 1467:     my ($id,$value,$debug)=@_;
 1468: 
 1469:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1470:                                     : $value;
 1471:     if ($to_remember<0) { return; }
 1472:     $accessed{$id}=[&gettimeofday()];
 1473:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1474:     my $to_kick;
 1475:     my $max_time=0;
 1476:     foreach my $other (keys(%accessed)) {
 1477: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1478: 	    $to_kick=$other;
 1479: 	    $max_time=&tv_interval($accessed{$other});
 1480: 	}
 1481:     }
 1482:     delete($remembered{$to_kick});
 1483:     delete($accessed{$to_kick});
 1484:     $kicks++;
 1485:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1486:     return;
 1487: }
 1488: 
 1489: sub purge_remembered {
 1490:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1491:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1492:     undef(%remembered);
 1493:     undef(%accessed);
 1494: }
 1495: # ------------------------------------- Read an entry from a user's environment
 1496: 
 1497: sub userenvironment {
 1498:     my ($udom,$unam,@what)=@_;
 1499:     my %returnhash=();
 1500:     my @answer=split(/\&/,
 1501:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1502:                       &homeserver($unam,$udom)));
 1503:     my $i;
 1504:     for ($i=0;$i<=$#what;$i++) {
 1505: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1506:     }
 1507:     return %returnhash;
 1508: }
 1509: 
 1510: # ---------------------------------------------------------- Get a studentphoto
 1511: sub studentphoto {
 1512:     my ($udom,$unam,$ext) = @_;
 1513:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1514:     if (defined($env{'request.course.id'})) {
 1515:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1516:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1517:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1518:             } else {
 1519:                 my ($result,$perm_reqd)=
 1520: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1521:                 if ($result eq 'ok') {
 1522:                     if (!($perm_reqd eq 'yes')) {
 1523:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1524:                     }
 1525:                 }
 1526:             }
 1527:         }
 1528:     } else {
 1529:         my ($result,$perm_reqd) = 
 1530: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1531:         if ($result eq 'ok') {
 1532:             if (!($perm_reqd eq 'yes')) {
 1533:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1534:             }
 1535:         }
 1536:     }
 1537:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1538: }
 1539: 
 1540: sub retrievestudentphoto {
 1541:     my ($udom,$unam,$ext,$type) = @_;
 1542:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1543:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1544:     if ($ret eq 'ok') {
 1545:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1546:         if ($type eq 'thumbnail') {
 1547:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1548:         }
 1549:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1550:         return $tokenurl;
 1551:     } else {
 1552:         if ($type eq 'thumbnail') {
 1553:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1554:         } else { 
 1555:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1556:         }
 1557:     }
 1558: }
 1559: 
 1560: # -------------------------------------------------------------------- New chat
 1561: 
 1562: sub chatsend {
 1563:     my ($newentry,$anon,$group)=@_;
 1564:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1565:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1566:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1567:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1568: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1569: 		   &escape($newentry)).':'.$group,$chome);
 1570: }
 1571: 
 1572: # ------------------------------------------ Find current version of a resource
 1573: 
 1574: sub getversion {
 1575:     my $fname=&clutter(shift);
 1576:     unless ($fname=~/^\/res\//) { return -1; }
 1577:     return &currentversion(&filelocation('',$fname));
 1578: }
 1579: 
 1580: sub currentversion {
 1581:     my $fname=shift;
 1582:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1583:     if (defined($cached)) { return $result; }
 1584:     my $author=$fname;
 1585:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1586:     my ($udom,$uname)=split(/\//,$author);
 1587:     my $home=homeserver($uname,$udom);
 1588:     if ($home eq 'no_host') { 
 1589:         return -1; 
 1590:     }
 1591:     my $answer=reply("currentversion:$fname",$home);
 1592:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1593: 	return -1;
 1594:     }
 1595:     return &do_cache_new('resversion',$fname,$answer,600);
 1596: }
 1597: 
 1598: # ----------------------------- Subscribe to a resource, return URL if possible
 1599: 
 1600: sub subscribe {
 1601:     my $fname=shift;
 1602:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1603:     $fname=~s/[\n\r]//g;
 1604:     my $author=$fname;
 1605:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1606:     my ($udom,$uname)=split(/\//,$author);
 1607:     my $home=homeserver($uname,$udom);
 1608:     if ($home eq 'no_host') {
 1609:         return 'not_found';
 1610:     }
 1611:     my $answer=reply("sub:$fname",$home);
 1612:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1613: 	$answer.=' by '.$home;
 1614:     }
 1615:     return $answer;
 1616: }
 1617:     
 1618: # -------------------------------------------------------------- Replicate file
 1619: 
 1620: sub repcopy {
 1621:     my $filename=shift;
 1622:     $filename=~s/\/+/\//g;
 1623:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1624:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1625:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1626: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1627: 	return &repcopy_userfile($filename);
 1628:     }
 1629:     $filename=~s/[\n\r]//g;
 1630:     my $transname="$filename.in.transfer";
 1631: # FIXME: this should flock
 1632:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1633:     my $remoteurl=subscribe($filename);
 1634:     if ($remoteurl =~ /^con_lost by/) {
 1635: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1636:            return 'unavailable';
 1637:     } elsif ($remoteurl eq 'not_found') {
 1638: 	   #&logthis("Subscribe returned not_found: $filename");
 1639: 	   return 'not_found';
 1640:     } elsif ($remoteurl =~ /^rejected by/) {
 1641: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1642:            return 'forbidden';
 1643:     } elsif ($remoteurl eq 'directory') {
 1644:            return 'ok';
 1645:     } else {
 1646:         my $author=$filename;
 1647:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1648:         my ($udom,$uname)=split(/\//,$author);
 1649:         my $home=homeserver($uname,$udom);
 1650:         unless ($home eq $perlvar{'lonHostID'}) {
 1651:            my @parts=split(/\//,$filename);
 1652:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1653:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1654:                &logthis("Malconfiguration for replication: $filename");
 1655: 	       return 'bad_request';
 1656:            }
 1657:            my $count;
 1658:            for ($count=5;$count<$#parts;$count++) {
 1659:                $path.="/$parts[$count]";
 1660:                if ((-e $path)!=1) {
 1661: 		   mkdir($path,0777);
 1662:                }
 1663:            }
 1664:            my $ua=new LWP::UserAgent;
 1665:            my $request=new HTTP::Request('GET',"$remoteurl");
 1666:            my $response=$ua->request($request,$transname);
 1667:            if ($response->is_error()) {
 1668: 	       unlink($transname);
 1669:                my $message=$response->status_line;
 1670:                &logthis("<font color=\"blue\">WARNING:"
 1671:                        ." LWP get: $message: $filename</font>");
 1672:                return 'unavailable';
 1673:            } else {
 1674: 	       if ($remoteurl!~/\.meta$/) {
 1675:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1676:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1677:                   if ($mresponse->is_error()) {
 1678: 		      unlink($filename.'.meta');
 1679:                       &logthis(
 1680:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1681:                   }
 1682: 	       }
 1683:                rename($transname,$filename);
 1684:                return 'ok';
 1685:            }
 1686:        }
 1687:     }
 1688: }
 1689: 
 1690: # ------------------------------------------------ Get server side include body
 1691: sub ssi_body {
 1692:     my ($filelink,%form)=@_;
 1693:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1694:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1695:     }
 1696:     my $output='';
 1697:     my $response;
 1698:     if ($filelink=~/^http\:/) {
 1699:        $output=&externalssi($filelink);
 1700:     } else {
 1701:        ($output,$response)=&ssi($filelink,%form);
 1702:     }
 1703:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1704:     $output=~s/^.*?\<body[^\>]*\>//si;
 1705:     $output=~s/\<\/body\s*\>.*?$//si;
 1706:     if (wantarray) {
 1707:         return ($output, $response);
 1708:     } else {
 1709:         return $output;
 1710:     }
 1711: }
 1712: 
 1713: # --------------------------------------------------------- Server Side Include
 1714: 
 1715: sub absolute_url {
 1716:     my ($host_name) = @_;
 1717:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1718:     if ($host_name eq '') {
 1719: 	$host_name = $ENV{'SERVER_NAME'};
 1720:     }
 1721:     return $protocol.$host_name;
 1722: }
 1723: 
 1724: #
 1725: #   Server side include.
 1726: # Parameters:
 1727: #  fn     Possibly encrypted resource name/id.
 1728: #  form   Hash that describes how the rendering should be done
 1729: #         and other things.
 1730: # Returns:
 1731: #   Scalar context: The content of the response.
 1732: #   Array context:  2 element list of the content and the full response object.
 1733: #     
 1734: sub ssi {
 1735: 
 1736:     my ($fn,%form)=@_;
 1737:     my $ua=new LWP::UserAgent;
 1738:     my $request;
 1739: 
 1740:     $form{'no_update_last_known'}=1;
 1741:     &Apache::lonenc::check_encrypt(\$fn);
 1742:     if (%form) {
 1743:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1744:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1745:     } else {
 1746:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1747:     }
 1748: 
 1749:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1750:     my $response=$ua->request($request);
 1751: 
 1752:     if (wantarray) {
 1753: 	return ($response->content, $response);
 1754:     } else {
 1755: 	return $response->content;
 1756:     }
 1757: }
 1758: 
 1759: sub externalssi {
 1760:     my ($url)=@_;
 1761:     my $ua=new LWP::UserAgent;
 1762:     my $request=new HTTP::Request('GET',$url);
 1763:     my $response=$ua->request($request);
 1764:     return $response->content;
 1765: }
 1766: 
 1767: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1768: 
 1769: sub allowuploaded {
 1770:     my ($srcurl,$url)=@_;
 1771:     $url=&clutter(&declutter($url));
 1772:     my $dir=$url;
 1773:     $dir=~s/\/[^\/]+$//;
 1774:     my %httpref=();
 1775:     my $httpurl=&hreflocation('',$url);
 1776:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1777:     &Apache::lonnet::appenv(\%httpref);
 1778: }
 1779: 
 1780: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1781: # input: action, courseID, current domain, intended
 1782: #        path to file, source of file, instruction to parse file for objects,
 1783: #        ref to hash for embedded objects,
 1784: #        ref to hash for codebase of java objects.
 1785: #
 1786: # output: url to file (if action was uploaddoc), 
 1787: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1788: #
 1789: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1790: # course.
 1791: #
 1792: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1793: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1794: #          course's home server.
 1795: #
 1796: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1797: #          be copied from $source (current location) to 
 1798: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1799: #         and will then be copied to
 1800: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1801: #         course's home server.
 1802: #
 1803: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1804: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1805: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1806: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1807: #         in course's home server.
 1808: #
 1809: 
 1810: sub process_coursefile {
 1811:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1812:     my $fetchresult;
 1813:     my $home=&homeserver($docuname,$docudom);
 1814:     if ($action eq 'propagate') {
 1815:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1816: 			     $home);
 1817:     } else {
 1818:         my $fpath = '';
 1819:         my $fname = $file;
 1820:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1821:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1822:         my $filepath = &build_filepath($fpath);
 1823:         if ($action eq 'copy') {
 1824:             if ($source eq '') {
 1825:                 $fetchresult = 'no source file';
 1826:                 return $fetchresult;
 1827:             } else {
 1828:                 my $destination = $filepath.'/'.$fname;
 1829:                 rename($source,$destination);
 1830:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1831:                                  $home);
 1832:             }
 1833:         } elsif ($action eq 'uploaddoc') {
 1834:             open(my $fh,'>'.$filepath.'/'.$fname);
 1835:             print $fh $env{'form.'.$source};
 1836:             close($fh);
 1837:             if ($parser eq 'parse') {
 1838:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1839:                 unless ($parse_result eq 'ok') {
 1840:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1841:                 }
 1842:             }
 1843:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1844:                                  $home);
 1845:             if ($fetchresult eq 'ok') {
 1846:                 return '/uploaded/'.$fpath.'/'.$fname;
 1847:             } else {
 1848:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1849:                         ' to host '.$home.': '.$fetchresult);
 1850:                 return '/adm/notfound.html';
 1851:             }
 1852:         }
 1853:     }
 1854:     unless ( $fetchresult eq 'ok') {
 1855:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1856:              ' to host '.$home.': '.$fetchresult);
 1857:     }
 1858:     return $fetchresult;
 1859: }
 1860: 
 1861: sub build_filepath {
 1862:     my ($fpath) = @_;
 1863:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1864:     unless ($fpath eq '') {
 1865:         my @parts=split('/',$fpath);
 1866:         foreach my $part (@parts) {
 1867:             $filepath.= '/'.$part;
 1868:             if ((-e $filepath)!=1) {
 1869:                 mkdir($filepath,0777);
 1870:             }
 1871:         }
 1872:     }
 1873:     return $filepath;
 1874: }
 1875: 
 1876: sub store_edited_file {
 1877:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1878:     my $file = $primary_url;
 1879:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1880:     my $fpath = '';
 1881:     my $fname = $file;
 1882:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1883:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1884:     my $filepath = &build_filepath($fpath);
 1885:     open(my $fh,'>'.$filepath.'/'.$fname);
 1886:     print $fh $content;
 1887:     close($fh);
 1888:     my $home=&homeserver($docuname,$docudom);
 1889:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1890: 			  $home);
 1891:     if ($$fetchresult eq 'ok') {
 1892:         return '/uploaded/'.$fpath.'/'.$fname;
 1893:     } else {
 1894:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1895: 		 ' to host '.$home.': '.$$fetchresult);
 1896:         return '/adm/notfound.html';
 1897:     }
 1898: }
 1899: 
 1900: sub clean_filename {
 1901:     my ($fname,$args)=@_;
 1902: # Replace Windows backslashes by forward slashes
 1903:     $fname=~s/\\/\//g;
 1904:     if (!$args->{'keep_path'}) {
 1905:         # Get rid of everything but the actual filename
 1906: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1907:     }
 1908: # Replace spaces by underscores
 1909:     $fname=~s/\s+/\_/g;
 1910: # Replace all other weird characters by nothing
 1911:     $fname=~s{[^/\w\.\-]}{}g;
 1912: # Replace all .\d. sequences with _\d. so they no longer look like version
 1913: # numbers
 1914:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1915:     return $fname;
 1916: }
 1917: 
 1918: # --------------- Take an uploaded file and put it into the userfiles directory
 1919: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1920: #                    the desired filenam is in $env{"form.$formname.filename"}
 1921: #        $coursedoc - if true up to the current course
 1922: #                     if false
 1923: #        $subdir - directory in userfile to store the file into
 1924: #        $parser - instruction to parse file for objects ($parser = parse)    
 1925: #        $allfiles - reference to hash for embedded objects
 1926: #        $codebase - reference to hash for codebase of java objects
 1927: #        $desuname - username for permanent storage of uploaded file
 1928: #        $dsetudom - domain for permanaent storage of uploaded file
 1929: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1930: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1931: # 
 1932: # output: url of file in userspace, or error: <message> 
 1933: #             or /adm/notfound.html if failure to upload occurse
 1934: 
 1935: 
 1936: sub userfileupload {
 1937:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1938:         $destudom,$thumbwidth,$thumbheight)=@_;
 1939:     if (!defined($subdir)) { $subdir='unknown'; }
 1940:     my $fname=$env{'form.'.$formname.'.filename'};
 1941:     $fname=&clean_filename($fname);
 1942: # See if there is anything left
 1943:     unless ($fname) { return 'error: no uploaded file'; }
 1944:     chop($env{'form.'.$formname});
 1945:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1946:         my $now = time;
 1947:         my $filepath = 'tmp/helprequests/'.$now;
 1948:         my @parts=split(/\//,$filepath);
 1949:         my $fullpath = $perlvar{'lonDaemons'};
 1950:         for (my $i=0;$i<@parts;$i++) {
 1951:             $fullpath .= '/'.$parts[$i];
 1952:             if ((-e $fullpath)!=1) {
 1953:                 mkdir($fullpath,0777);
 1954:             }
 1955:         }
 1956:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1957:         print $fh $env{'form.'.$formname};
 1958:         close($fh);
 1959:         return $fullpath.'/'.$fname;
 1960:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1961:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1962:                        '_'.$env{'user.domain'}.'/pending';
 1963:         my @parts=split(/\//,$filepath);
 1964:         my $fullpath = $perlvar{'lonDaemons'};
 1965:         for (my $i=0;$i<@parts;$i++) {
 1966:             $fullpath .= '/'.$parts[$i];
 1967:             if ((-e $fullpath)!=1) {
 1968:                 mkdir($fullpath,0777);
 1969:             }
 1970:         }
 1971:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1972:         print $fh $env{'form.'.$formname};
 1973:         close($fh);
 1974:         return $fullpath.'/'.$fname;
 1975:     }
 1976:     
 1977: # Create the directory if not present
 1978:     $fname="$subdir/$fname";
 1979:     if ($coursedoc) {
 1980: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1981: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1982:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1983:             return &finishuserfileupload($docuname,$docudom,
 1984: 					 $formname,$fname,$parser,$allfiles,
 1985: 					 $codebase,$thumbwidth,$thumbheight);
 1986:         } else {
 1987:             $fname=$env{'form.folder'}.'/'.$fname;
 1988:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1989: 				       $fname,$formname,$parser,
 1990: 				       $allfiles,$codebase);
 1991:         }
 1992:     } elsif (defined($destuname)) {
 1993:         my $docuname=$destuname;
 1994:         my $docudom=$destudom;
 1995: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1996: 				     $parser,$allfiles,$codebase,
 1997:                                      $thumbwidth,$thumbheight);
 1998:         
 1999:     } else {
 2000:         my $docuname=$env{'user.name'};
 2001:         my $docudom=$env{'user.domain'};
 2002:         if (exists($env{'form.group'})) {
 2003:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2004:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2005:         }
 2006: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2007: 				     $parser,$allfiles,$codebase,
 2008:                                      $thumbwidth,$thumbheight);
 2009:     }
 2010: }
 2011: 
 2012: sub finishuserfileupload {
 2013:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2014:         $thumbwidth,$thumbheight) = @_;
 2015:     my $path=$docudom.'/'.$docuname.'/';
 2016:     my $filepath=$perlvar{'lonDocRoot'};
 2017:     my ($fnamepath,$file,$fetchthumb);
 2018:     $file=$fname;
 2019:     if ($fname=~m|/|) {
 2020:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2021: 	$path.=$fnamepath.'/';
 2022:     }
 2023:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2024:     my $count;
 2025:     for ($count=4;$count<=$#parts;$count++) {
 2026:         $filepath.="/$parts[$count]";
 2027:         if ((-e $filepath)!=1) {
 2028: 	    mkdir($filepath,0777);
 2029:         }
 2030:     }
 2031: # Save the file
 2032:     {
 2033: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2034: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2035: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2036: 	    return '/adm/notfound.html';
 2037: 	}
 2038: 	if (!print FH ($env{'form.'.$formname})) {
 2039: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2040: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2041: 	    return '/adm/notfound.html';
 2042: 	}
 2043: 	close(FH);
 2044:     }
 2045:     if ($parser eq 'parse') {
 2046:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 2047: 						   $codebase);
 2048:         unless ($parse_result eq 'ok') {
 2049:             &logthis('Failed to parse '.$filepath.$file.
 2050: 		     ' for embedded media: '.$parse_result); 
 2051:         }
 2052:     }
 2053:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2054:         my $input = $filepath.'/'.$file;
 2055:         my $output = $filepath.'/'.'tn-'.$file;
 2056:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2057:         system("convert -sample $thumbsize $input $output");
 2058:         if (-e $filepath.'/'.'tn-'.$file) {
 2059:             $fetchthumb  = 1; 
 2060:         }
 2061:     }
 2062:  
 2063: # Notify homeserver to grep it
 2064: #
 2065:     my $docuhome=&homeserver($docuname,$docudom);
 2066:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2067:     if ($fetchresult eq 'ok') {
 2068:         if ($fetchthumb) {
 2069:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2070:             if ($thumbresult ne 'ok') {
 2071:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2072:                          $docuhome.': '.$thumbresult);
 2073:             }
 2074:         }
 2075: #
 2076: # Return the URL to it
 2077:         return '/uploaded/'.$path.$file;
 2078:     } else {
 2079:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2080: 		 ': '.$fetchresult);
 2081:         return '/adm/notfound.html';
 2082:     }
 2083: }
 2084: 
 2085: sub extract_embedded_items {
 2086:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2087:     my @state = ();
 2088:     my %javafiles = (
 2089:                       codebase => '',
 2090:                       code => '',
 2091:                       archive => ''
 2092:                     );
 2093:     my %mediafiles = (
 2094:                       src => '',
 2095:                       movie => '',
 2096:                      );
 2097:     my $p;
 2098:     if ($content) {
 2099:         $p = HTML::LCParser->new($content);
 2100:     } else {
 2101:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2102:     }
 2103:     while (my $t=$p->get_token()) {
 2104: 	if ($t->[0] eq 'S') {
 2105: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2106: 	    push(@state, $tagname);
 2107:             if (lc($tagname) eq 'allow') {
 2108:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2109:             }
 2110: 	    if (lc($tagname) eq 'img') {
 2111: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2112: 	    }
 2113: 	    if (lc($tagname) eq 'a') {
 2114: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2115: 	    }
 2116:             if (lc($tagname) eq 'script') {
 2117:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2118:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2119:                 } else {
 2120:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2121:                 }
 2122:             }
 2123:             if (lc($tagname) eq 'link') {
 2124:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2125:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2126:                 }
 2127:             }
 2128: 	    if (lc($tagname) eq 'object' ||
 2129: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2130: 		foreach my $item (keys(%javafiles)) {
 2131: 		    $javafiles{$item} = '';
 2132: 		}
 2133: 	    }
 2134: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2135: 		my $name = lc($attr->{'name'});
 2136: 		foreach my $item (keys(%javafiles)) {
 2137: 		    if ($name eq $item) {
 2138: 			$javafiles{$item} = $attr->{'value'};
 2139: 			last;
 2140: 		    }
 2141: 		}
 2142: 		foreach my $item (keys(%mediafiles)) {
 2143: 		    if ($name eq $item) {
 2144: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2145: 			last;
 2146: 		    }
 2147: 		}
 2148: 	    }
 2149: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2150: 		foreach my $item (keys(%javafiles)) {
 2151: 		    if ($attr->{$item}) {
 2152: 			$javafiles{$item} = $attr->{$item};
 2153: 			last;
 2154: 		    }
 2155: 		}
 2156: 		foreach my $item (keys(%mediafiles)) {
 2157: 		    if ($attr->{$item}) {
 2158: 			&add_filetype($allfiles,$attr->{$item},$item);
 2159: 			last;
 2160: 		    }
 2161: 		}
 2162: 	    }
 2163: 	} elsif ($t->[0] eq 'E') {
 2164: 	    my ($tagname) = ($t->[1]);
 2165: 	    if ($javafiles{'codebase'} ne '') {
 2166: 		$javafiles{'codebase'} .= '/';
 2167: 	    }  
 2168: 	    if (lc($tagname) eq 'applet' ||
 2169: 		lc($tagname) eq 'object' ||
 2170: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2171: 		) {
 2172: 		foreach my $item (keys(%javafiles)) {
 2173: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2174: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2175: 			&add_filetype($allfiles,$file,$item);
 2176: 		    }
 2177: 		}
 2178: 	    } 
 2179: 	    pop @state;
 2180: 	}
 2181:     }
 2182:     return 'ok';
 2183: }
 2184: 
 2185: sub add_filetype {
 2186:     my ($allfiles,$file,$type)=@_;
 2187:     if (exists($allfiles->{$file})) {
 2188: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2189: 	    push(@{$allfiles->{$file}}, &escape($type));
 2190: 	}
 2191:     } else {
 2192: 	@{$allfiles->{$file}} = (&escape($type));
 2193:     }
 2194: }
 2195: 
 2196: sub removeuploadedurl {
 2197:     my ($url)=@_;
 2198:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2199:     return &removeuserfile($uname,$udom,$fname);
 2200: }
 2201: 
 2202: sub removeuserfile {
 2203:     my ($docuname,$docudom,$fname)=@_;
 2204:     my $home=&homeserver($docuname,$docudom);
 2205:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2206:     if ($result eq 'ok') {
 2207:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2208:             my $metafile = $fname.'.meta';
 2209:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2210: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2212:             my $sqlresult = 
 2213:                 &update_portfolio_table($docuname,$docudom,$file,
 2214:                                         'portfolio_metadata',$group,
 2215:                                         'delete');
 2216:         }
 2217:     }
 2218:     return $result;
 2219: }
 2220: 
 2221: sub mkdiruserfile {
 2222:     my ($docuname,$docudom,$dir)=@_;
 2223:     my $home=&homeserver($docuname,$docudom);
 2224:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2225: }
 2226: 
 2227: sub renameuserfile {
 2228:     my ($docuname,$docudom,$old,$new)=@_;
 2229:     my $home=&homeserver($docuname,$docudom);
 2230:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2231:                         &escape("$old").':'.&escape("$new"),$home);
 2232:     if ($result eq 'ok') {
 2233:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2234:             my $oldmeta = $old.'.meta';
 2235:             my $newmeta = $new.'.meta';
 2236:             my $metaresult = 
 2237:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2238: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2239:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2240:             my $sqlresult = 
 2241:                 &update_portfolio_table($docuname,$docudom,$file,
 2242:                                         'portfolio_metadata',$group,
 2243:                                         'delete');
 2244:         }
 2245:     }
 2246:     return $result;
 2247: }
 2248: 
 2249: # ------------------------------------------------------------------------- Log
 2250: 
 2251: sub log {
 2252:     my ($dom,$nam,$hom,$what)=@_;
 2253:     return critical("log:$dom:$nam:$what",$hom);
 2254: }
 2255: 
 2256: # ------------------------------------------------------------------ Course Log
 2257: #
 2258: # This routine flushes several buffers of non-mission-critical nature
 2259: #
 2260: 
 2261: sub flushcourselogs {
 2262:     &logthis('Flushing log buffers');
 2263: #
 2264: # course logs
 2265: # This is a log of all transactions in a course, which can be used
 2266: # for data mining purposes
 2267: #
 2268: # It also collects the courseid database, which lists last transaction
 2269: # times and course titles for all courseids
 2270: #
 2271:     my %courseidbuffer=();
 2272:     foreach my $crsid (keys(%courselogs)) {
 2273:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2274: 		          &escape($courselogs{$crsid}),
 2275: 		          $coursehombuf{$crsid}) eq 'ok') {
 2276: 	    delete $courselogs{$crsid};
 2277:         } else {
 2278:             &logthis('Failed to flush log buffer for '.$crsid);
 2279:             if (length($courselogs{$crsid})>40000) {
 2280:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2281:                         " exceeded maximum size, deleting.</font>");
 2282:                delete $courselogs{$crsid};
 2283:             }
 2284:         }
 2285:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2286:             'description' => $coursedescrbuf{$crsid},
 2287:             'inst_code'    => $courseinstcodebuf{$crsid},
 2288:             'type'        => $coursetypebuf{$crsid},
 2289:             'owner'       => $courseownerbuf{$crsid},
 2290:         };
 2291:     }
 2292: #
 2293: # Write course id database (reverse lookup) to homeserver of courses 
 2294: # Is used in pickcourse
 2295: #
 2296:     foreach my $crs_home (keys(%courseidbuffer)) {
 2297:         my $response = &courseidput(&host_domain($crs_home),
 2298:                                     $courseidbuffer{$crs_home},
 2299:                                     $crs_home,'timeonly');
 2300:     }
 2301: #
 2302: # File accesses
 2303: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2304: #
 2305:     foreach my $entry (keys(%accesshash)) {
 2306:         if ($entry =~ /___count$/) {
 2307:             my ($dom,$name);
 2308:             ($dom,$name,undef)=
 2309: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2310:             if (! defined($dom) || $dom eq '' || 
 2311:                 ! defined($name) || $name eq '') {
 2312:                 my $cid = $env{'request.course.id'};
 2313:                 $dom  = $env{'request.'.$cid.'.domain'};
 2314:                 $name = $env{'request.'.$cid.'.num'};
 2315:             }
 2316:             my $value = $accesshash{$entry};
 2317:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2318:             my %temphash=($url => $value);
 2319:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2320:             if ($result eq 'ok') {
 2321:                 delete $accesshash{$entry};
 2322:             } elsif ($result eq 'unknown_cmd') {
 2323:                 # Target server has old code running on it.
 2324:                 my %temphash=($entry => $value);
 2325:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2326:                     delete $accesshash{$entry};
 2327:                 }
 2328:             }
 2329:         } else {
 2330:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2331:             my %temphash=($entry => $accesshash{$entry});
 2332:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2333:                 delete $accesshash{$entry};
 2334:             }
 2335:         }
 2336:     }
 2337: #
 2338: # Roles
 2339: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2340: #
 2341:     foreach my $entry (keys(%userrolehash)) {
 2342:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2343: 	    split(/\:/,$entry);
 2344:         if (&Apache::lonnet::put('nohist_userroles',
 2345:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2346:                 $rudom,$runame) eq 'ok') {
 2347: 	    delete $userrolehash{$entry};
 2348:         }
 2349:     }
 2350: #
 2351: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2352: #
 2353:     my %domrolebuffer = ();
 2354:     foreach my $entry (keys %domainrolehash) {
 2355:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2356:         if ($domrolebuffer{$rudom}) {
 2357:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2358:                       '='.&escape($domainrolehash{$entry});
 2359:         } else {
 2360:             $domrolebuffer{$rudom}.=&escape($entry).
 2361:                       '='.&escape($domainrolehash{$entry});
 2362:         }
 2363:         delete $domainrolehash{$entry};
 2364:     }
 2365:     foreach my $dom (keys(%domrolebuffer)) {
 2366: 	my %servers = &get_servers($dom,'library');
 2367: 	foreach my $tryserver (keys(%servers)) {
 2368: 	    unless (&reply('domroleput:'.$dom.':'.
 2369: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2370: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2371: 	    }
 2372:         }
 2373:     }
 2374:     $dumpcount++;
 2375: }
 2376: 
 2377: sub courselog {
 2378:     my $what=shift;
 2379:     $what=time.':'.$what;
 2380:     unless ($env{'request.course.id'}) { return ''; }
 2381:     $coursedombuf{$env{'request.course.id'}}=
 2382:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2383:     $coursenumbuf{$env{'request.course.id'}}=
 2384:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2385:     $coursehombuf{$env{'request.course.id'}}=
 2386:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2387:     $coursedescrbuf{$env{'request.course.id'}}=
 2388:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2389:     $courseinstcodebuf{$env{'request.course.id'}}=
 2390:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2391:     $courseownerbuf{$env{'request.course.id'}}=
 2392:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2393:     $coursetypebuf{$env{'request.course.id'}}=
 2394:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2395:     if (defined $courselogs{$env{'request.course.id'}}) {
 2396: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2397:     } else {
 2398: 	$courselogs{$env{'request.course.id'}}.=$what;
 2399:     }
 2400:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2401: 	&flushcourselogs();
 2402:     }
 2403: }
 2404: 
 2405: sub courseacclog {
 2406:     my $fnsymb=shift;
 2407:     unless ($env{'request.course.id'}) { return ''; }
 2408:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2409:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2410:         $what.=':POST';
 2411:         # FIXME: Probably ought to escape things....
 2412: 	foreach my $key (keys(%env)) {
 2413:             if ($key=~/^form\.(.*)/) {
 2414: 		$what.=':'.$1.'='.$env{$key};
 2415:             }
 2416:         }
 2417:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2418:         # FIXME: We should not be depending on a form parameter that someone
 2419:         # editing lonsearchcat.pm might change in the future.
 2420:         if ($env{'form.phase'} eq 'course_search') {
 2421:             $what.= ':POST';
 2422:             # FIXME: Probably ought to escape things....
 2423:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2424:                                  'crsdiscuss') {
 2425:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2426:             }
 2427:         }
 2428:     }
 2429:     &courselog($what);
 2430: }
 2431: 
 2432: sub countacc {
 2433:     my $url=&declutter(shift);
 2434:     return if (! defined($url) || $url eq '');
 2435:     unless ($env{'request.course.id'}) { return ''; }
 2436:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2437:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2438:     $accesshash{$key}++;
 2439: }
 2440: 
 2441: sub linklog {
 2442:     my ($from,$to)=@_;
 2443:     $from=&declutter($from);
 2444:     $to=&declutter($to);
 2445:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2446:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2447: }
 2448:   
 2449: sub userrolelog {
 2450:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2451:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2452:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2453:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2454:         ($trole=~/^ta/)) {
 2455:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2456:        $userrolehash
 2457:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2458:                     =$tend.':'.$tstart;
 2459:     }
 2460:     if (($env{'request.role'} =~ /dc\./) &&
 2461: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2462: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2463: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2464:        $userrolehash
 2465:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2466:                     =$tend.':'.$tstart;
 2467:     }
 2468:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2469:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2470:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2471:         ($trole=~/^sc/)) {
 2472:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2473:        $domainrolehash
 2474:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2475:                     = $tend.':'.$tstart;
 2476:     }
 2477: }
 2478: 
 2479: sub get_course_adv_roles {
 2480:     my ($cid,$codes) = @_;
 2481:     $cid=$env{'request.course.id'} unless (defined($cid));
 2482:     my %coursehash=&coursedescription($cid);
 2483:     my %nothide=();
 2484:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2485:         if ($user !~ /:/) {
 2486: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2487:         } else {
 2488:             $nothide{$user}=1;
 2489:         }
 2490:     }
 2491:     my %returnhash=();
 2492:     my %dumphash=
 2493:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2494:     my $now=time;
 2495:     foreach my $entry (keys %dumphash) {
 2496: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2497:         if (($tstart) && ($tstart<0)) { next; }
 2498:         if (($tend) && ($tend<$now)) { next; }
 2499:         if (($tstart) && ($now<$tstart)) { next; }
 2500:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2501: 	if ($username eq '' || $domain eq '') { next; }
 2502: 	if ((&privileged($username,$domain)) && 
 2503: 	    (!$nothide{$username.':'.$domain})) { next; }
 2504: 	if ($role eq 'cr') { next; }
 2505:         if ($codes) {
 2506:             if ($section) { $role .= ':'.$section; }
 2507:             if ($returnhash{$role}) {
 2508:                 $returnhash{$role}.=','.$username.':'.$domain;
 2509:             } else {
 2510:                 $returnhash{$role}=$username.':'.$domain;
 2511:             }
 2512:         } else {
 2513:             my $key=&plaintext($role);
 2514:             if ($section) { $key.=' (Section '.$section.')'; }
 2515:             if ($returnhash{$key}) {
 2516: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2517:             } else {
 2518:                 $returnhash{$key}=$username.':'.$domain;
 2519:             }
 2520:         }
 2521:     }
 2522:     return %returnhash;
 2523: }
 2524: 
 2525: sub get_my_roles {
 2526:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2527:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2528:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2529:     my (%dumphash,%nothide);
 2530:     if ($context eq 'userroles') { 
 2531:         %dumphash = &dump('roles',$udom,$uname);
 2532:     } else {
 2533:         %dumphash=
 2534:             &dump('nohist_userroles',$udom,$uname);
 2535:         if ($hidepriv) {
 2536:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2537:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2538:                 if ($user !~ /:/) {
 2539:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2540:                 } else {
 2541:                     $nothide{$user} = 1;
 2542:                 }
 2543:             }
 2544:         }
 2545:     }
 2546:     my %returnhash=();
 2547:     my $now=time;
 2548:     foreach my $entry (keys(%dumphash)) {
 2549:         my ($role,$tend,$tstart);
 2550:         if ($context eq 'userroles') {
 2551: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2552:         } else {
 2553:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2554:         }
 2555:         if (($tstart) && ($tstart<0)) { next; }
 2556:         my $status = 'active';
 2557:         if (($tend) && ($tend<=$now)) {
 2558:             $status = 'previous';
 2559:         } 
 2560:         if (($tstart) && ($now<$tstart)) {
 2561:             $status = 'future';
 2562:         }
 2563:         if (ref($types) eq 'ARRAY') {
 2564:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2565:                 next;
 2566:             } 
 2567:         } else {
 2568:             if ($status ne 'active') {
 2569:                 next;
 2570:             }
 2571:         }
 2572:         my ($rolecode,$username,$domain,$section,$area);
 2573:         if ($context eq 'userroles') {
 2574:             ($area,$rolecode) = split(/_/,$entry);
 2575:             (undef,$domain,$username,$section) = split(/\//,$area);
 2576:         } else {
 2577:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2578:         }
 2579:         if (ref($roledoms) eq 'ARRAY') {
 2580:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2581:                 next;
 2582:             }
 2583:         }
 2584:         if (ref($roles) eq 'ARRAY') {
 2585:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2586:                 if ($role =~ /^cr\//) {
 2587:                     if (!grep(/^cr$/,@{$roles})) {
 2588:                         next;
 2589:                     }
 2590:                 } else {
 2591:                     next;
 2592:                 }
 2593:             }
 2594:         }
 2595:         if ($hidepriv) {
 2596:             if ((&privileged($username,$domain)) &&
 2597:                 (!$nothide{$username.':'.$domain})) { 
 2598:                 next;
 2599:             }
 2600:         }
 2601:         if ($withsec) {
 2602:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2603:                 $tstart.':'.$tend;
 2604:         } else {
 2605:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2606:         }
 2607:     }
 2608:     return %returnhash;
 2609: }
 2610: 
 2611: # ----------------------------------------------------- Frontpage Announcements
 2612: #
 2613: #
 2614: 
 2615: sub postannounce {
 2616:     my ($server,$text)=@_;
 2617:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2618:     unless ($text=~/\w/) { $text=''; }
 2619:     return &reply('setannounce:'.&escape($text),$server);
 2620: }
 2621: 
 2622: sub getannounce {
 2623: 
 2624:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2625: 	my $announcement='';
 2626: 	while (my $line = <$fh>) { $announcement .= $line; }
 2627: 	close($fh);
 2628: 	if ($announcement=~/\w/) { 
 2629: 	    return 
 2630:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2631:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2632: 	} else {
 2633: 	    return '';
 2634: 	}
 2635:     } else {
 2636: 	return '';
 2637:     }
 2638: }
 2639: 
 2640: # ---------------------------------------------------------- Course ID routines
 2641: # Deal with domain's nohist_courseid.db files
 2642: #
 2643: 
 2644: sub courseidput {
 2645:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2646:     my $outcome;
 2647:     if ($caller eq 'timeonly') {
 2648:         my $cids = '';
 2649:         foreach my $item (keys(%$storehash)) {
 2650:             $cids.=&escape($item).'&';
 2651:         }
 2652:         $cids=~s/\&$//;
 2653:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2654:                           $coursehome);       
 2655:     } else {
 2656:         my $items = '';
 2657:         foreach my $item (keys(%$storehash)) {
 2658:             $items.= &escape($item).'='.
 2659:                      &freeze_escape($$storehash{$item}).'&';
 2660:         }
 2661:         $items=~s/\&$//;
 2662:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2663:                           $coursehome);
 2664:     }
 2665:     if ($outcome eq 'unknown_cmd') {
 2666:         my $what;
 2667:         foreach my $cid (keys(%$storehash)) {
 2668:             $what .= &escape($cid).'=';
 2669:             foreach my $item ('description','inst_code','owner','type') {
 2670:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2671:             }
 2672:             $what =~ s/\:$/&/;
 2673:         }
 2674:         $what =~ s/\&$//;  
 2675:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2676:     } else {
 2677:         return $outcome;
 2678:     }
 2679: }
 2680: 
 2681: sub courseiddump {
 2682:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2683:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2684:         $selfenrollonly)=@_;
 2685:     my $as_hash = 1;
 2686:     my %returnhash;
 2687:     if (!$domfilter) { $domfilter=''; }
 2688:     my %libserv = &all_library();
 2689:     foreach my $tryserver (keys(%libserv)) {
 2690:         if ( (  $hostidflag == 1 
 2691: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2692: 	     || (!defined($hostidflag)) ) {
 2693: 
 2694: 	    if (($domfilter eq '') ||
 2695: 		(&host_domain($tryserver) eq $domfilter)) {
 2696:                 my $rep = 
 2697:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2698:                          $sincefilter.':'.&escape($descfilter).':'.
 2699:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2700:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2701:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2702:                          &escape($selfenrollonly),$tryserver);
 2703:                 my @pairs=split(/\&/,$rep);
 2704:                 foreach my $item (@pairs) {
 2705:                     my ($key,$value)=split(/\=/,$item,2);
 2706:                     $key = &unescape($key);
 2707:                     next if ($key =~ /^error: 2 /);
 2708:                     my $result = &thaw_unescape($value);
 2709:                     if (ref($result) eq 'HASH') {
 2710:                         $returnhash{$key}=$result;
 2711:                     } else {
 2712:                         my @responses = split(/:/,$value);
 2713:                         my @items = ('description','inst_code','owner','type');
 2714:                         for (my $i=0; $i<@responses; $i++) {
 2715:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2716:                         }
 2717:                     } 
 2718:                 }
 2719:             }
 2720:         }
 2721:     }
 2722:     return %returnhash;
 2723: }
 2724: 
 2725: # ---------------------------------------------------------- DC e-mail
 2726: 
 2727: sub dcmailput {
 2728:     my ($domain,$msgid,$message,$server)=@_;
 2729:     my $status = &Apache::lonnet::critical(
 2730:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2731:        &escape($message),$server);
 2732:     return $status;
 2733: }
 2734: 
 2735: sub dcmaildump {
 2736:     my ($dom,$startdate,$enddate,$senders) = @_;
 2737:     my %returnhash=();
 2738: 
 2739:     if (defined(&domain($dom,'primary'))) {
 2740:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2741:                                                          &escape($enddate).':';
 2742: 	my @esc_senders=map { &escape($_)} @$senders;
 2743: 	$cmd.=&escape(join('&',@esc_senders));
 2744: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2745:             my ($key,$value) = split(/\=/,$line,2);
 2746:             if (($key) && ($value)) {
 2747:                 $returnhash{&unescape($key)} = &unescape($value);
 2748:             }
 2749:         }
 2750:     }
 2751:     return %returnhash;
 2752: }
 2753: # ---------------------------------------------------------- Domain roles
 2754: 
 2755: sub get_domain_roles {
 2756:     my ($dom,$roles,$startdate,$enddate)=@_;
 2757:     if (undef($startdate) || $startdate eq '') {
 2758:         $startdate = '.';
 2759:     }
 2760:     if (undef($enddate) || $enddate eq '') {
 2761:         $enddate = '.';
 2762:     }
 2763:     my $rolelist;
 2764:     if (ref($roles) eq 'ARRAY') {
 2765:         $rolelist = join(':',@{$roles});
 2766:     }
 2767:     my %personnel = ();
 2768: 
 2769:     my %servers = &get_servers($dom,'library');
 2770:     foreach my $tryserver (keys(%servers)) {
 2771: 	%{$personnel{$tryserver}}=();
 2772: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2773: 					    &escape($startdate).':'.
 2774: 					    &escape($enddate).':'.
 2775: 					    &escape($rolelist), $tryserver))) {
 2776: 	    my ($key,$value) = split(/\=/,$line,2);
 2777: 	    if (($key) && ($value)) {
 2778: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2779: 	    }
 2780: 	}
 2781:     }
 2782:     return %personnel;
 2783: }
 2784: 
 2785: # ----------------------------------------------------------- Check out an item
 2786: 
 2787: sub get_first_access {
 2788:     my ($type,$argsymb)=@_;
 2789:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2790:     if ($argsymb) { $symb=$argsymb; }
 2791:     my ($map,$id,$res)=&decode_symb($symb);
 2792:     if ($type eq 'course') {
 2793: 	$res='course';
 2794:     } elsif ($type eq 'map') {
 2795: 	$res=&symbread($map);
 2796:     } else {
 2797: 	$res=$symb;
 2798:     }
 2799:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2800:     return $times{"$courseid\0$res"};
 2801: }
 2802: 
 2803: sub set_first_access {
 2804:     my ($type)=@_;
 2805:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2806:     my ($map,$id,$res)=&decode_symb($symb);
 2807:     if ($type eq 'course') {
 2808: 	$res='course';
 2809:     } elsif ($type eq 'map') {
 2810: 	$res=&symbread($map);
 2811:     } else {
 2812: 	$res=$symb;
 2813:     }
 2814:     my $firstaccess=&get_first_access($type,$symb);
 2815:     if (!$firstaccess) {
 2816: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2817:     }
 2818:     return 'already_set';
 2819: }
 2820: 
 2821: sub checkout {
 2822:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2823:     my $now=time;
 2824:     my $lonhost=$perlvar{'lonHostID'};
 2825:     my $infostr=&escape(
 2826:                  'CHECKOUTTOKEN&'.
 2827:                  $tuname.'&'.
 2828:                  $tudom.'&'.
 2829:                  $tcrsid.'&'.
 2830:                  $symb.'&'.
 2831: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2832:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2833:     if ($token=~/^error\:/) { 
 2834:         &logthis("<font color=\"blue\">WARNING: ".
 2835:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2836:                  "</font>");
 2837:         return ''; 
 2838:     }
 2839: 
 2840:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2841:     $token=~tr/a-z/A-Z/;
 2842: 
 2843:     my %infohash=('resource.0.outtoken' => $token,
 2844:                   'resource.0.checkouttime' => $now,
 2845:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2846: 
 2847:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2848:        return '';
 2849:     } else {
 2850:         &logthis("<font color=\"blue\">WARNING: ".
 2851:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2852:                  "</font>");
 2853:     }    
 2854: 
 2855:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2856:                          &escape('Checkout '.$infostr.' - '.
 2857:                                                  $token)) ne 'ok') {
 2858: 	return '';
 2859:     } else {
 2860:         &logthis("<font color=\"blue\">WARNING: ".
 2861:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2862:                  "</font>");
 2863:     }
 2864:     return $token;
 2865: }
 2866: 
 2867: # ------------------------------------------------------------ Check in an item
 2868: 
 2869: sub checkin {
 2870:     my $token=shift;
 2871:     my $now=time;
 2872:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2873:     $lonhost=~tr/A-Z/a-z/;
 2874:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2875:     $dtoken=~s/\W/\_/g;
 2876:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2877:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2878: 
 2879:     unless (($tuname) && ($tudom)) {
 2880:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2881:         return '';
 2882:     }
 2883:     
 2884:     unless (&allowed('mgr',$tcrsid)) {
 2885:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2886:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2887:         return '';
 2888:     }
 2889: 
 2890:     my %infohash=('resource.0.intoken' => $token,
 2891:                   'resource.0.checkintime' => $now,
 2892:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2893: 
 2894:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2895:        return '';
 2896:     }    
 2897: 
 2898:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2899:                          &escape('Checkin - '.$token)) ne 'ok') {
 2900: 	return '';
 2901:     }
 2902: 
 2903:     return ($symb,$tuname,$tudom,$tcrsid);    
 2904: }
 2905: 
 2906: # --------------------------------------------- Set Expire Date for Spreadsheet
 2907: 
 2908: sub expirespread {
 2909:     my ($uname,$udom,$stype,$usymb)=@_;
 2910:     my $cid=$env{'request.course.id'}; 
 2911:     if ($cid) {
 2912:        my $now=time;
 2913:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2914:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2915:                             $env{'course.'.$cid.'.num'}.
 2916: 	        	    ':nohist_expirationdates:'.
 2917:                             &escape($key).'='.$now,
 2918:                             $env{'course.'.$cid.'.home'})
 2919:     }
 2920:     return 'ok';
 2921: }
 2922: 
 2923: # ----------------------------------------------------- Devalidate Spreadsheets
 2924: 
 2925: sub devalidate {
 2926:     my ($symb,$uname,$udom)=@_;
 2927:     my $cid=$env{'request.course.id'}; 
 2928:     if ($cid) {
 2929:         # delete the stored spreadsheets for
 2930:         # - the student level sheet of this user in course's homespace
 2931:         # - the assessment level sheet for this resource 
 2932:         #   for this user in user's homespace
 2933: 	# - current conditional state info
 2934: 	my $key=$uname.':'.$udom.':';
 2935:         my $status=
 2936: 	    &del('nohist_calculatedsheets',
 2937: 		 [$key.'studentcalc:'],
 2938: 		 $env{'course.'.$cid.'.domain'},
 2939: 		 $env{'course.'.$cid.'.num'})
 2940: 		.' '.
 2941: 	    &del('nohist_calculatedsheets_'.$cid,
 2942: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2943:         unless ($status eq 'ok ok') {
 2944:            &logthis('Could not devalidate spreadsheet '.
 2945:                     $uname.' at '.$udom.' for '.
 2946: 		    $symb.': '.$status);
 2947:         }
 2948: 	&delenv('user.state.'.$cid);
 2949:     }
 2950: }
 2951: 
 2952: sub get_scalar {
 2953:     my ($string,$end) = @_;
 2954:     my $value;
 2955:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2956: 	$value = $1;
 2957:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2958: 	$value = $1;
 2959:     }
 2960:     return &unescape($value);
 2961: }
 2962: 
 2963: sub array2str {
 2964:   my (@array) = @_;
 2965:   my $result=&arrayref2str(\@array);
 2966:   $result=~s/^__ARRAY_REF__//;
 2967:   $result=~s/__END_ARRAY_REF__$//;
 2968:   return $result;
 2969: }
 2970: 
 2971: sub arrayref2str {
 2972:   my ($arrayref) = @_;
 2973:   my $result='__ARRAY_REF__';
 2974:   foreach my $elem (@$arrayref) {
 2975:     if(ref($elem) eq 'ARRAY') {
 2976:       $result.=&arrayref2str($elem).'&';
 2977:     } elsif(ref($elem) eq 'HASH') {
 2978:       $result.=&hashref2str($elem).'&';
 2979:     } elsif(ref($elem)) {
 2980:       #print("Got a ref of ".(ref($elem))." skipping.");
 2981:     } else {
 2982:       $result.=&escape($elem).'&';
 2983:     }
 2984:   }
 2985:   $result=~s/\&$//;
 2986:   $result .= '__END_ARRAY_REF__';
 2987:   return $result;
 2988: }
 2989: 
 2990: sub hash2str {
 2991:   my (%hash) = @_;
 2992:   my $result=&hashref2str(\%hash);
 2993:   $result=~s/^__HASH_REF__//;
 2994:   $result=~s/__END_HASH_REF__$//;
 2995:   return $result;
 2996: }
 2997: 
 2998: sub hashref2str {
 2999:   my ($hashref)=@_;
 3000:   my $result='__HASH_REF__';
 3001:   foreach my $key (sort(keys(%$hashref))) {
 3002:     if (ref($key) eq 'ARRAY') {
 3003:       $result.=&arrayref2str($key).'=';
 3004:     } elsif (ref($key) eq 'HASH') {
 3005:       $result.=&hashref2str($key).'=';
 3006:     } elsif (ref($key)) {
 3007:       $result.='=';
 3008:       #print("Got a ref of ".(ref($key))." skipping.");
 3009:     } else {
 3010: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3011:     }
 3012: 
 3013:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3014:       $result.=&arrayref2str($hashref->{$key}).'&';
 3015:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3016:       $result.=&hashref2str($hashref->{$key}).'&';
 3017:     } elsif(ref($hashref->{$key})) {
 3018:        $result.='&';
 3019:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3020:     } else {
 3021:       $result.=&escape($hashref->{$key}).'&';
 3022:     }
 3023:   }
 3024:   $result=~s/\&$//;
 3025:   $result .= '__END_HASH_REF__';
 3026:   return $result;
 3027: }
 3028: 
 3029: sub str2hash {
 3030:     my ($string)=@_;
 3031:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3032:     return %$hash;
 3033: }
 3034: 
 3035: sub str2hashref {
 3036:   my ($string) = @_;
 3037: 
 3038:   my %hash;
 3039: 
 3040:   if($string !~ /^__HASH_REF__/) {
 3041:       if (! ($string eq '' || !defined($string))) {
 3042: 	  $hash{'error'}='Not hash reference';
 3043:       }
 3044:       return (\%hash, $string);
 3045:   }
 3046: 
 3047:   $string =~ s/^__HASH_REF__//;
 3048: 
 3049:   while($string !~ /^__END_HASH_REF__/) {
 3050:       #key
 3051:       my $key='';
 3052:       if($string =~ /^__HASH_REF__/) {
 3053:           ($key, $string)=&str2hashref($string);
 3054:           if(defined($key->{'error'})) {
 3055:               $hash{'error'}='Bad data';
 3056:               return (\%hash, $string);
 3057:           }
 3058:       } elsif($string =~ /^__ARRAY_REF__/) {
 3059:           ($key, $string)=&str2arrayref($string);
 3060:           if($key->[0] eq 'Array reference error') {
 3061:               $hash{'error'}='Bad data';
 3062:               return (\%hash, $string);
 3063:           }
 3064:       } else {
 3065:           $string =~ s/^(.*?)=//;
 3066: 	  $key=&unescape($1);
 3067:       }
 3068:       $string =~ s/^=//;
 3069: 
 3070:       #value
 3071:       my $value='';
 3072:       if($string =~ /^__HASH_REF__/) {
 3073:           ($value, $string)=&str2hashref($string);
 3074:           if(defined($value->{'error'})) {
 3075:               $hash{'error'}='Bad data';
 3076:               return (\%hash, $string);
 3077:           }
 3078:       } elsif($string =~ /^__ARRAY_REF__/) {
 3079:           ($value, $string)=&str2arrayref($string);
 3080:           if($value->[0] eq 'Array reference error') {
 3081:               $hash{'error'}='Bad data';
 3082:               return (\%hash, $string);
 3083:           }
 3084:       } else {
 3085: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3086:       }
 3087:       $string =~ s/^&//;
 3088: 
 3089:       $hash{$key}=$value;
 3090:   }
 3091: 
 3092:   $string =~ s/^__END_HASH_REF__//;
 3093: 
 3094:   return (\%hash, $string);
 3095: }
 3096: 
 3097: sub str2array {
 3098:     my ($string)=@_;
 3099:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3100:     return @$array;
 3101: }
 3102: 
 3103: sub str2arrayref {
 3104:   my ($string) = @_;
 3105:   my @array;
 3106: 
 3107:   if($string !~ /^__ARRAY_REF__/) {
 3108:       if (! ($string eq '' || !defined($string))) {
 3109: 	  $array[0]='Array reference error';
 3110:       }
 3111:       return (\@array, $string);
 3112:   }
 3113: 
 3114:   $string =~ s/^__ARRAY_REF__//;
 3115: 
 3116:   while($string !~ /^__END_ARRAY_REF__/) {
 3117:       my $value='';
 3118:       if($string =~ /^__HASH_REF__/) {
 3119:           ($value, $string)=&str2hashref($string);
 3120:           if(defined($value->{'error'})) {
 3121:               $array[0] ='Array reference error';
 3122:               return (\@array, $string);
 3123:           }
 3124:       } elsif($string =~ /^__ARRAY_REF__/) {
 3125:           ($value, $string)=&str2arrayref($string);
 3126:           if($value->[0] eq 'Array reference error') {
 3127:               $array[0] ='Array reference error';
 3128:               return (\@array, $string);
 3129:           }
 3130:       } else {
 3131: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3132:       }
 3133:       $string =~ s/^&//;
 3134: 
 3135:       push(@array, $value);
 3136:   }
 3137: 
 3138:   $string =~ s/^__END_ARRAY_REF__//;
 3139: 
 3140:   return (\@array, $string);
 3141: }
 3142: 
 3143: # -------------------------------------------------------------------Temp Store
 3144: 
 3145: sub tmpreset {
 3146:   my ($symb,$namespace,$domain,$stuname) = @_;
 3147:   if (!$symb) {
 3148:     $symb=&symbread();
 3149:     if (!$symb) { $symb= $env{'request.url'}; }
 3150:   }
 3151:   $symb=escape($symb);
 3152: 
 3153:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3154:   $namespace=~s/\//\_/g;
 3155:   $namespace=~s/\W//g;
 3156: 
 3157:   if (!$domain) { $domain=$env{'user.domain'}; }
 3158:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3159:   if ($domain eq 'public' && $stuname eq 'public') {
 3160:       $stuname=$ENV{'REMOTE_ADDR'};
 3161:   }
 3162:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3163:   my %hash;
 3164:   if (tie(%hash,'GDBM_File',
 3165: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3166: 	  &GDBM_WRCREAT(),0640)) {
 3167:     foreach my $key (keys %hash) {
 3168:       if ($key=~ /:$symb/) {
 3169: 	delete($hash{$key});
 3170:       }
 3171:     }
 3172:   }
 3173: }
 3174: 
 3175: sub tmpstore {
 3176:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3177: 
 3178:   if (!$symb) {
 3179:     $symb=&symbread();
 3180:     if (!$symb) { $symb= $env{'request.url'}; }
 3181:   }
 3182:   $symb=escape($symb);
 3183: 
 3184:   if (!$namespace) {
 3185:     # I don't think we would ever want to store this for a course.
 3186:     # it seems this will only be used if we don't have a course.
 3187:     #$namespace=$env{'request.course.id'};
 3188:     #if (!$namespace) {
 3189:       $namespace=$env{'request.state'};
 3190:     #}
 3191:   }
 3192:   $namespace=~s/\//\_/g;
 3193:   $namespace=~s/\W//g;
 3194:   if (!$domain) { $domain=$env{'user.domain'}; }
 3195:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3196:   if ($domain eq 'public' && $stuname eq 'public') {
 3197:       $stuname=$ENV{'REMOTE_ADDR'};
 3198:   }
 3199:   my $now=time;
 3200:   my %hash;
 3201:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3202:   if (tie(%hash,'GDBM_File',
 3203: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3204: 	  &GDBM_WRCREAT(),0640)) {
 3205:     $hash{"version:$symb"}++;
 3206:     my $version=$hash{"version:$symb"};
 3207:     my $allkeys=''; 
 3208:     foreach my $key (keys(%$storehash)) {
 3209:       $allkeys.=$key.':';
 3210:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3211:     }
 3212:     $hash{"$version:$symb:timestamp"}=$now;
 3213:     $allkeys.='timestamp';
 3214:     $hash{"$version:keys:$symb"}=$allkeys;
 3215:     if (untie(%hash)) {
 3216:       return 'ok';
 3217:     } else {
 3218:       return "error:$!";
 3219:     }
 3220:   } else {
 3221:     return "error:$!";
 3222:   }
 3223: }
 3224: 
 3225: # -----------------------------------------------------------------Temp Restore
 3226: 
 3227: sub tmprestore {
 3228:   my ($symb,$namespace,$domain,$stuname) = @_;
 3229: 
 3230:   if (!$symb) {
 3231:     $symb=&symbread();
 3232:     if (!$symb) { $symb= $env{'request.url'}; }
 3233:   }
 3234:   $symb=escape($symb);
 3235: 
 3236:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3237: 
 3238:   if (!$domain) { $domain=$env{'user.domain'}; }
 3239:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3240:   if ($domain eq 'public' && $stuname eq 'public') {
 3241:       $stuname=$ENV{'REMOTE_ADDR'};
 3242:   }
 3243:   my %returnhash;
 3244:   $namespace=~s/\//\_/g;
 3245:   $namespace=~s/\W//g;
 3246:   my %hash;
 3247:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3248:   if (tie(%hash,'GDBM_File',
 3249: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3250: 	  &GDBM_READER(),0640)) {
 3251:     my $version=$hash{"version:$symb"};
 3252:     $returnhash{'version'}=$version;
 3253:     my $scope;
 3254:     for ($scope=1;$scope<=$version;$scope++) {
 3255:       my $vkeys=$hash{"$scope:keys:$symb"};
 3256:       my @keys=split(/:/,$vkeys);
 3257:       my $key;
 3258:       $returnhash{"$scope:keys"}=$vkeys;
 3259:       foreach $key (@keys) {
 3260: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3261: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3262:       }
 3263:     }
 3264:     if (!(untie(%hash))) {
 3265:       return "error:$!";
 3266:     }
 3267:   } else {
 3268:     return "error:$!";
 3269:   }
 3270:   return %returnhash;
 3271: }
 3272: 
 3273: # ----------------------------------------------------------------------- Store
 3274: 
 3275: sub store {
 3276:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3277:     my $home='';
 3278: 
 3279:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3280: 
 3281:     $symb=&symbclean($symb);
 3282:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3283: 
 3284:     if (!$domain) { $domain=$env{'user.domain'}; }
 3285:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3286: 
 3287:     &devalidate($symb,$stuname,$domain);
 3288: 
 3289:     $symb=escape($symb);
 3290:     if (!$namespace) { 
 3291:        unless ($namespace=$env{'request.course.id'}) { 
 3292:           return ''; 
 3293:        } 
 3294:     }
 3295:     if (!$home) { $home=$env{'user.home'}; }
 3296: 
 3297:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3298:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3299: 
 3300:     my $namevalue='';
 3301:     foreach my $key (keys(%$storehash)) {
 3302:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3303:     }
 3304:     $namevalue=~s/\&$//;
 3305:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3306:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3307: }
 3308: 
 3309: # -------------------------------------------------------------- Critical Store
 3310: 
 3311: sub cstore {
 3312:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3313:     my $home='';
 3314: 
 3315:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3316: 
 3317:     $symb=&symbclean($symb);
 3318:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3319: 
 3320:     if (!$domain) { $domain=$env{'user.domain'}; }
 3321:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3322: 
 3323:     &devalidate($symb,$stuname,$domain);
 3324: 
 3325:     $symb=escape($symb);
 3326:     if (!$namespace) { 
 3327:        unless ($namespace=$env{'request.course.id'}) { 
 3328:           return ''; 
 3329:        } 
 3330:     }
 3331:     if (!$home) { $home=$env{'user.home'}; }
 3332: 
 3333:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3334:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3335: 
 3336:     my $namevalue='';
 3337:     foreach my $key (keys(%$storehash)) {
 3338:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3339:     }
 3340:     $namevalue=~s/\&$//;
 3341:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3342:     return critical
 3343:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3344: }
 3345: 
 3346: # --------------------------------------------------------------------- Restore
 3347: 
 3348: sub restore {
 3349:     my ($symb,$namespace,$domain,$stuname) = @_;
 3350:     my $home='';
 3351: 
 3352:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3353: 
 3354:     if (!$symb) {
 3355:       unless ($symb=escape(&symbread())) { return ''; }
 3356:     } else {
 3357:       $symb=&escape(&symbclean($symb));
 3358:     }
 3359:     if (!$namespace) { 
 3360:        unless ($namespace=$env{'request.course.id'}) { 
 3361:           return ''; 
 3362:        } 
 3363:     }
 3364:     if (!$domain) { $domain=$env{'user.domain'}; }
 3365:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3366:     if (!$home) { $home=$env{'user.home'}; }
 3367:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3368: 
 3369:     my %returnhash=();
 3370:     foreach my $line (split(/\&/,$answer)) {
 3371: 	my ($name,$value)=split(/\=/,$line);
 3372:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3373:     }
 3374:     my $version;
 3375:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3376:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3377:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3378:        }
 3379:     }
 3380:     return %returnhash;
 3381: }
 3382: 
 3383: # ---------------------------------------------------------- Course Description
 3384: 
 3385: sub coursedescription {
 3386:     my ($courseid,$args)=@_;
 3387:     $courseid=~s/^\///;
 3388:     $courseid=~s/\_/\//g;
 3389:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3390:     my $chome=&homeserver($cnum,$cdomain);
 3391:     my $normalid=$cdomain.'_'.$cnum;
 3392:     # need to always cache even if we get errors otherwise we keep 
 3393:     # trying and trying and trying to get the course description.
 3394:     my %envhash=();
 3395:     my %returnhash=();
 3396:     
 3397:     my $expiretime=600;
 3398:     if ($env{'request.course.id'} eq $normalid) {
 3399: 	$expiretime=120;
 3400:     }
 3401: 
 3402:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3403:     if (!$args->{'freshen_cache'}
 3404: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3405: 	foreach my $key (keys(%env)) {
 3406: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3407: 	    my ($setting) = $1;
 3408: 	    $returnhash{$setting} = $env{$key};
 3409: 	}
 3410: 	return %returnhash;
 3411:     }
 3412: 
 3413:     # get the data agin
 3414:     if (!$args->{'one_time'}) {
 3415: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3416:     }
 3417: 
 3418:     if ($chome ne 'no_host') {
 3419:        %returnhash=&dump('environment',$cdomain,$cnum);
 3420:        if (!exists($returnhash{'con_lost'})) {
 3421:            $returnhash{'home'}= $chome;
 3422: 	   $returnhash{'domain'} = $cdomain;
 3423: 	   $returnhash{'num'} = $cnum;
 3424:            if (!defined($returnhash{'type'})) {
 3425:                $returnhash{'type'} = 'Course';
 3426:            }
 3427:            while (my ($name,$value) = each %returnhash) {
 3428:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3429:            }
 3430:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3431:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3432: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3433:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3434:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3435:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3436:        }
 3437:     }
 3438:     if (!$args->{'one_time'}) {
 3439: 	&appenv(\%envhash);
 3440:     }
 3441:     return %returnhash;
 3442: }
 3443: 
 3444: # -------------------------------------------------See if a user is privileged
 3445: 
 3446: sub privileged {
 3447:     my ($username,$domain)=@_;
 3448:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3449: 			&homeserver($username,$domain));
 3450:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3451:     my $now=time;
 3452:     if ($rolesdump ne '') {
 3453:         foreach my $entry (split(/&/,$rolesdump)) {
 3454: 	    if ($entry!~/^rolesdef_/) {
 3455: 		my ($area,$role)=split(/=/,$entry);
 3456: 		$area=~s/\_\w\w$//;
 3457: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3458: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3459: 		    my $active=1;
 3460: 		    if ($tend) {
 3461: 			if ($tend<$now) { $active=0; }
 3462: 		    }
 3463: 		    if ($tstart) {
 3464: 			if ($tstart>$now) { $active=0; }
 3465: 		    }
 3466: 		    if ($active) { return 1; }
 3467: 		}
 3468: 	    }
 3469: 	}
 3470:     }
 3471:     return 0;
 3472: }
 3473: 
 3474: # -------------------------------------------------------- Get user privileges
 3475: 
 3476: sub rolesinit {
 3477:     my ($domain,$username,$authhost)=@_;
 3478:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3479:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3480:     my %allroles=();
 3481:     my %allgroups=();   
 3482:     my $now=time;
 3483:     my %userroles = ('user.login.time' => $now);
 3484:     my $group_privs;
 3485: 
 3486:     if ($rolesdump ne '') {
 3487:         foreach my $entry (split(/&/,$rolesdump)) {
 3488: 	  if ($entry!~/^rolesdef_/) {
 3489:             my ($area,$role)=split(/=/,$entry);
 3490: 	    $area=~s/\_\w\w$//;
 3491:             my ($trole,$tend,$tstart,$group_privs);
 3492: 	    if ($role=~/^cr/) { 
 3493: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3494: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3495: 		    ($tend,$tstart)=split('_',$trest);
 3496: 		} else {
 3497: 		    $trole=$role;
 3498: 		}
 3499:             } elsif ($role =~ m|^gr/|) {
 3500:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3501:                 ($trole,$group_privs) = split(/\//,$trole);
 3502:                 $group_privs = &unescape($group_privs);
 3503: 	    } else {
 3504: 		($trole,$tend,$tstart)=split(/_/,$role);
 3505: 	    }
 3506: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3507: 					 $username);
 3508: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3509:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3510:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3511:             if (($area ne '') && ($trole ne '')) {
 3512: 		my $spec=$trole.'.'.$area;
 3513: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3514: 		if ($trole =~ /^cr\//) {
 3515:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3516:                 } elsif ($trole eq 'gr') {
 3517:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3518: 		} else {
 3519:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3520: 		}
 3521:             }
 3522:           }
 3523:         }
 3524:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3525:         $userroles{'user.adv'}    = $adv;
 3526: 	$userroles{'user.author'} = $author;
 3527:         $env{'user.adv'}=$adv;
 3528:     }
 3529:     return \%userroles;  
 3530: }
 3531: 
 3532: sub set_arearole {
 3533:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3534: # log the associated role with the area
 3535:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3536:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3537: }
 3538: 
 3539: sub custom_roleprivs {
 3540:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3541:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3542:     my $homsvr=homeserver($rauthor,$rdomain);
 3543:     if (&hostname($homsvr) ne '') {
 3544:         my ($rdummy,$roledef)=
 3545:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3546:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3547:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3548:             if (defined($syspriv)) {
 3549:                 $$allroles{'cm./'}.=':'.$syspriv;
 3550:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3551:             }
 3552:             if ($tdomain ne '') {
 3553:                 if (defined($dompriv)) {
 3554:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3555:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3556:                 }
 3557:                 if (($trest ne '') && (defined($coursepriv))) {
 3558:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3559:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3560:                 }
 3561:             }
 3562:         }
 3563:     }
 3564: }
 3565: 
 3566: sub group_roleprivs {
 3567:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3568:     my $access = 1;
 3569:     my $now = time;
 3570:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3571:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3572:     if ($access) {
 3573:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3574:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3575:     }
 3576: }
 3577: 
 3578: sub standard_roleprivs {
 3579:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3580:     if (defined($pr{$trole.':s'})) {
 3581:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3582:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3583:     }
 3584:     if ($tdomain ne '') {
 3585:         if (defined($pr{$trole.':d'})) {
 3586:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3587:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3588:         }
 3589:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3590:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3591:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3592:         }
 3593:     }
 3594: }
 3595: 
 3596: sub set_userprivs {
 3597:     my ($userroles,$allroles,$allgroups) = @_; 
 3598:     my $author=0;
 3599:     my $adv=0;
 3600:     my %grouproles = ();
 3601:     if (keys(%{$allgroups}) > 0) {
 3602:         foreach my $role (keys %{$allroles}) {
 3603:             my ($trole,$area,$sec,$extendedarea);
 3604:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3605:                 $trole = $1;
 3606:                 $area = $2;
 3607:                 $sec = $3;
 3608:                 $extendedarea = $area.$sec;
 3609:                 if (exists($$allgroups{$area})) {
 3610:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3611:                         my $spec = $trole.'.'.$extendedarea;
 3612:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3613:                                                 $$allgroups{$area}{$group};
 3614:                     }
 3615:                 }
 3616:             }
 3617:         }
 3618:     }
 3619:     foreach my $group (keys(%grouproles)) {
 3620:         $$allroles{$group} = $grouproles{$group};
 3621:     }
 3622:     foreach my $role (keys(%{$allroles})) {
 3623:         my %thesepriv;
 3624:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3625:         foreach my $item (split(/:/,$$allroles{$role})) {
 3626:             if ($item ne '') {
 3627:                 my ($privilege,$restrictions)=split(/&/,$item);
 3628:                 if ($restrictions eq '') {
 3629:                     $thesepriv{$privilege}='F';
 3630:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3631:                     $thesepriv{$privilege}.=$restrictions;
 3632:                 }
 3633:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3634:             }
 3635:         }
 3636:         my $thesestr='';
 3637:         foreach my $priv (keys(%thesepriv)) {
 3638: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3639: 	}
 3640:         $userroles->{'user.priv.'.$role} = $thesestr;
 3641:     }
 3642:     return ($author,$adv);
 3643: }
 3644: 
 3645: # --------------------------------------------------------------- get interface
 3646: 
 3647: sub get {
 3648:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3649:    my $items='';
 3650:    foreach my $item (@$storearr) {
 3651:        $items.=&escape($item).'&';
 3652:    }
 3653:    $items=~s/\&$//;
 3654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3655:    if (!$uname) { $uname=$env{'user.name'}; }
 3656:    my $uhome=&homeserver($uname,$udomain);
 3657: 
 3658:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3659:    my @pairs=split(/\&/,$rep);
 3660:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3661:      return @pairs;
 3662:    }
 3663:    my %returnhash=();
 3664:    my $i=0;
 3665:    foreach my $item (@$storearr) {
 3666:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3667:       $i++;
 3668:    }
 3669:    return %returnhash;
 3670: }
 3671: 
 3672: # --------------------------------------------------------------- del interface
 3673: 
 3674: sub del {
 3675:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3676:    my $items='';
 3677:    foreach my $item (@$storearr) {
 3678:        $items.=&escape($item).'&';
 3679:    }
 3680:    $items=~s/\&$//;
 3681:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3682:    if (!$uname) { $uname=$env{'user.name'}; }
 3683:    my $uhome=&homeserver($uname,$udomain);
 3684: 
 3685:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3686: }
 3687: 
 3688: # -------------------------------------------------------------- dump interface
 3689: 
 3690: sub dump {
 3691:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3692:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3693:     if (!$uname) { $uname=$env{'user.name'}; }
 3694:     my $uhome=&homeserver($uname,$udomain);
 3695:     if ($regexp) {
 3696: 	$regexp=&escape($regexp);
 3697:     } else {
 3698: 	$regexp='.';
 3699:     }
 3700:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3701:     my @pairs=split(/\&/,$rep);
 3702:     my %returnhash=();
 3703:     foreach my $item (@pairs) {
 3704: 	my ($key,$value)=split(/=/,$item,2);
 3705: 	$key = &unescape($key);
 3706: 	next if ($key =~ /^error: 2 /);
 3707: 	$returnhash{$key}=&thaw_unescape($value);
 3708:     }
 3709:     return %returnhash;
 3710: }
 3711: 
 3712: # --------------------------------------------------------- dumpstore interface
 3713: 
 3714: sub dumpstore {
 3715:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3716:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3717:    if (!$uname) { $uname=$env{'user.name'}; }
 3718:    my $uhome=&homeserver($uname,$udomain);
 3719:    if ($regexp) {
 3720:        $regexp=&escape($regexp);
 3721:    } else {
 3722:        $regexp='.';
 3723:    }
 3724:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3725:    my @pairs=split(/\&/,$rep);
 3726:    my %returnhash=();
 3727:    foreach my $item (@pairs) {
 3728:        my ($key,$value)=split(/=/,$item,2);
 3729:        next if ($key =~ /^error: 2 /);
 3730:        $returnhash{$key}=&thaw_unescape($value);
 3731:    }
 3732:    return %returnhash;
 3733: }
 3734: 
 3735: # -------------------------------------------------------------- keys interface
 3736: 
 3737: sub getkeys {
 3738:    my ($namespace,$udomain,$uname)=@_;
 3739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3740:    if (!$uname) { $uname=$env{'user.name'}; }
 3741:    my $uhome=&homeserver($uname,$udomain);
 3742:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3743:    my @keyarray=();
 3744:    foreach my $key (split(/\&/,$rep)) {
 3745:       next if ($key =~ /^error: 2 /);
 3746:       push(@keyarray,&unescape($key));
 3747:    }
 3748:    return @keyarray;
 3749: }
 3750: 
 3751: # --------------------------------------------------------------- currentdump
 3752: sub currentdump {
 3753:    my ($courseid,$sdom,$sname)=@_;
 3754:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3755:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3756:    $sname    = $env{'user.name'}         if (! defined($sname));
 3757:    my $uhome = &homeserver($sname,$sdom);
 3758:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3759:    return if ($rep =~ /^(error:|no_such_host)/);
 3760:    #
 3761:    my %returnhash=();
 3762:    #
 3763:    if ($rep eq "unknown_cmd") { 
 3764:        # an old lond will not know currentdump
 3765:        # Do a dump and make it look like a currentdump
 3766:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3767:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3768:        my %hash = @tmp;
 3769:        @tmp=();
 3770:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3771:    } else {
 3772:        my @pairs=split(/\&/,$rep);
 3773:        foreach my $pair (@pairs) {
 3774:            my ($key,$value)=split(/=/,$pair,2);
 3775:            my ($symb,$param) = split(/:/,$key);
 3776:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3777:                                                         &thaw_unescape($value);
 3778:        }
 3779:    }
 3780:    return %returnhash;
 3781: }
 3782: 
 3783: sub convert_dump_to_currentdump{
 3784:     my %hash = %{shift()};
 3785:     my %returnhash;
 3786:     # Code ripped from lond, essentially.  The only difference
 3787:     # here is the unescaping done by lonnet::dump().  Conceivably
 3788:     # we might run in to problems with parameter names =~ /^v\./
 3789:     while (my ($key,$value) = each(%hash)) {
 3790:         my ($v,$symb,$param) = split(/:/,$key);
 3791: 	$symb  = &unescape($symb);
 3792: 	$param = &unescape($param);
 3793:         next if ($v eq 'version' || $symb eq 'keys');
 3794:         next if (exists($returnhash{$symb}) &&
 3795:                  exists($returnhash{$symb}->{$param}) &&
 3796:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3797:         $returnhash{$symb}->{$param}=$value;
 3798:         $returnhash{$symb}->{'v.'.$param}=$v;
 3799:     }
 3800:     #
 3801:     # Remove all of the keys in the hashes which keep track of
 3802:     # the version of the parameter.
 3803:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3804:         # use a foreach because we are going to delete from the hash.
 3805:         foreach my $key (keys(%$param_hash)) {
 3806:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3807:         }
 3808:     }
 3809:     return \%returnhash;
 3810: }
 3811: 
 3812: # ------------------------------------------------------ critical inc interface
 3813: 
 3814: sub cinc {
 3815:     return &inc(@_,'critical');
 3816: }
 3817: 
 3818: # --------------------------------------------------------------- inc interface
 3819: 
 3820: sub inc {
 3821:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3822:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3823:     if (!$uname) { $uname=$env{'user.name'}; }
 3824:     my $uhome=&homeserver($uname,$udomain);
 3825:     my $items='';
 3826:     if (! ref($store)) {
 3827:         # got a single value, so use that instead
 3828:         $items = &escape($store).'=&';
 3829:     } elsif (ref($store) eq 'SCALAR') {
 3830:         $items = &escape($$store).'=&';        
 3831:     } elsif (ref($store) eq 'ARRAY') {
 3832:         $items = join('=&',map {&escape($_);} @{$store});
 3833:     } elsif (ref($store) eq 'HASH') {
 3834:         while (my($key,$value) = each(%{$store})) {
 3835:             $items.= &escape($key).'='.&escape($value).'&';
 3836:         }
 3837:     }
 3838:     $items=~s/\&$//;
 3839:     if ($critical) {
 3840: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3841:     } else {
 3842: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3843:     }
 3844: }
 3845: 
 3846: # --------------------------------------------------------------- put interface
 3847: 
 3848: sub put {
 3849:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3851:    if (!$uname) { $uname=$env{'user.name'}; }
 3852:    my $uhome=&homeserver($uname,$udomain);
 3853:    my $items='';
 3854:    foreach my $item (keys(%$storehash)) {
 3855:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3856:    }
 3857:    $items=~s/\&$//;
 3858:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3859: }
 3860: 
 3861: # ------------------------------------------------------------ newput interface
 3862: 
 3863: sub newput {
 3864:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3865:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3866:    if (!$uname) { $uname=$env{'user.name'}; }
 3867:    my $uhome=&homeserver($uname,$udomain);
 3868:    my $items='';
 3869:    foreach my $key (keys(%$storehash)) {
 3870:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3871:    }
 3872:    $items=~s/\&$//;
 3873:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3874: }
 3875: 
 3876: # ---------------------------------------------------------  putstore interface
 3877: 
 3878: sub putstore {
 3879:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3881:    if (!$uname) { $uname=$env{'user.name'}; }
 3882:    my $uhome=&homeserver($uname,$udomain);
 3883:    my $items='';
 3884:    foreach my $key (keys(%$storehash)) {
 3885:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3886:    }
 3887:    $items=~s/\&$//;
 3888:    my $esc_symb=&escape($symb);
 3889:    my $esc_v=&escape($version);
 3890:    my $reply =
 3891:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3892: 	      $uhome);
 3893:    if ($reply eq 'unknown_cmd') {
 3894:        # gfall back to way things use to be done
 3895:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3896: 			    $uname);
 3897:    }
 3898:    return $reply;
 3899: }
 3900: 
 3901: sub old_putstore {
 3902:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3903:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3904:     if (!$uname) { $uname=$env{'user.name'}; }
 3905:     my $uhome=&homeserver($uname,$udomain);
 3906:     my %newstorehash;
 3907:     foreach my $item (keys(%$storehash)) {
 3908: 	my $key = $version.':'.&escape($symb).':'.$item;
 3909: 	$newstorehash{$key} = $storehash->{$item};
 3910:     }
 3911:     my $items='';
 3912:     my %allitems = ();
 3913:     foreach my $item (keys(%newstorehash)) {
 3914: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3915: 	    my $key = $1.':keys:'.$2;
 3916: 	    $allitems{$key} .= $3.':';
 3917: 	}
 3918: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3919:     }
 3920:     foreach my $item (keys(%allitems)) {
 3921: 	$allitems{$item} =~ s/\:$//;
 3922: 	$items.= $item.'='.$allitems{$item}.'&';
 3923:     }
 3924:     $items=~s/\&$//;
 3925:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3926: }
 3927: 
 3928: # ------------------------------------------------------ critical put interface
 3929: 
 3930: sub cput {
 3931:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3932:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3933:    if (!$uname) { $uname=$env{'user.name'}; }
 3934:    my $uhome=&homeserver($uname,$udomain);
 3935:    my $items='';
 3936:    foreach my $item (keys(%$storehash)) {
 3937:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3938:    }
 3939:    $items=~s/\&$//;
 3940:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3941: }
 3942: 
 3943: # -------------------------------------------------------------- eget interface
 3944: 
 3945: sub eget {
 3946:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3947:    my $items='';
 3948:    foreach my $item (@$storearr) {
 3949:        $items.=&escape($item).'&';
 3950:    }
 3951:    $items=~s/\&$//;
 3952:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3953:    if (!$uname) { $uname=$env{'user.name'}; }
 3954:    my $uhome=&homeserver($uname,$udomain);
 3955:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3956:    my @pairs=split(/\&/,$rep);
 3957:    my %returnhash=();
 3958:    my $i=0;
 3959:    foreach my $item (@$storearr) {
 3960:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3961:       $i++;
 3962:    }
 3963:    return %returnhash;
 3964: }
 3965: 
 3966: # ------------------------------------------------------------ tmpput interface
 3967: sub tmpput {
 3968:     my ($storehash,$server,$context)=@_;
 3969:     my $items='';
 3970:     foreach my $item (keys(%$storehash)) {
 3971: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3972:     }
 3973:     $items=~s/\&$//;
 3974:     if (defined($context)) {
 3975:         $items .= ':'.&escape($context);
 3976:     }
 3977:     return &reply("tmpput:$items",$server);
 3978: }
 3979: 
 3980: # ------------------------------------------------------------ tmpget interface
 3981: sub tmpget {
 3982:     my ($token,$server)=@_;
 3983:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3984:     my $rep=&reply("tmpget:$token",$server);
 3985:     my %returnhash;
 3986:     foreach my $item (split(/\&/,$rep)) {
 3987: 	my ($key,$value)=split(/=/,$item);
 3988:         next if ($key =~ /^error: 2 /);
 3989: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3990:     }
 3991:     return %returnhash;
 3992: }
 3993: 
 3994: # ------------------------------------------------------------ tmpget interface
 3995: sub tmpdel {
 3996:     my ($token,$server)=@_;
 3997:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3998:     return &reply("tmpdel:$token",$server);
 3999: }
 4000: 
 4001: # -------------------------------------------------- portfolio access checking
 4002: 
 4003: sub portfolio_access {
 4004:     my ($requrl) = @_;
 4005:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4006:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4007:     if ($result) {
 4008:         my %setters;
 4009:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4010:             my ($startblock,$endblock) =
 4011:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4012:             if ($startblock && $endblock) {
 4013:                 return 'B';
 4014:             }
 4015:         } else {
 4016:             my ($startblock,$endblock) =
 4017:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4018:             if ($startblock && $endblock) {
 4019:                 return 'B';
 4020:             }
 4021:         }
 4022:     }
 4023:     if ($result eq 'ok') {
 4024:        return 'F';
 4025:     } elsif ($result =~ /^[^:]+:guest_/) {
 4026:        return 'A';
 4027:     }
 4028:     return '';
 4029: }
 4030: 
 4031: sub get_portfolio_access {
 4032:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4033: 
 4034:     if (!ref($access_hash)) {
 4035: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4036: 	my %access_controls = &get_access_controls($current_perms,$group,
 4037: 						   $file_name);
 4038: 	$access_hash = $access_controls{$file_name};
 4039:     }
 4040: 
 4041:     my ($public,$guest,@domains,@users,@courses,@groups);
 4042:     my $now = time;
 4043:     if (ref($access_hash) eq 'HASH') {
 4044:         foreach my $key (keys(%{$access_hash})) {
 4045:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4046:             if ($start > $now) {
 4047:                 next;
 4048:             }
 4049:             if ($end && $end<$now) {
 4050:                 next;
 4051:             }
 4052:             if ($scope eq 'public') {
 4053:                 $public = $key;
 4054:                 last;
 4055:             } elsif ($scope eq 'guest') {
 4056:                 $guest = $key;
 4057:             } elsif ($scope eq 'domains') {
 4058:                 push(@domains,$key);
 4059:             } elsif ($scope eq 'users') {
 4060:                 push(@users,$key);
 4061:             } elsif ($scope eq 'course') {
 4062:                 push(@courses,$key);
 4063:             } elsif ($scope eq 'group') {
 4064:                 push(@groups,$key);
 4065:             }
 4066:         }
 4067:         if ($public) {
 4068:             return 'ok';
 4069:         }
 4070:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4071:             if ($guest) {
 4072:                 return $guest;
 4073:             }
 4074:         } else {
 4075:             if (@domains > 0) {
 4076:                 foreach my $domkey (@domains) {
 4077:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4078:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4079:                             return 'ok';
 4080:                         }
 4081:                     }
 4082:                 }
 4083:             }
 4084:             if (@users > 0) {
 4085:                 foreach my $userkey (@users) {
 4086:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4087:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4088:                             if (ref($item) eq 'HASH') {
 4089:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4090:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4091:                                     return 'ok';
 4092:                                 }
 4093:                             }
 4094:                         }
 4095:                     } 
 4096:                 }
 4097:             }
 4098:             my %roleshash;
 4099:             my @courses_and_groups = @courses;
 4100:             push(@courses_and_groups,@groups); 
 4101:             if (@courses_and_groups > 0) {
 4102:                 my (%allgroups,%allroles); 
 4103:                 my ($start,$end,$role,$sec,$group);
 4104:                 foreach my $envkey (%env) {
 4105:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4106:                         my $cid = $2.'_'.$3; 
 4107:                         if ($1 eq 'gr') {
 4108:                             $group = $4;
 4109:                             $allgroups{$cid}{$group} = $env{$envkey};
 4110:                         } else {
 4111:                             if ($4 eq '') {
 4112:                                 $sec = 'none';
 4113:                             } else {
 4114:                                 $sec = $4;
 4115:                             }
 4116:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4117:                         }
 4118:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4119:                         my $cid = $2.'_'.$3;
 4120:                         if ($4 eq '') {
 4121:                             $sec = 'none';
 4122:                         } else {
 4123:                             $sec = $4;
 4124:                         }
 4125:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4126:                     }
 4127:                 }
 4128:                 if (keys(%allroles) == 0) {
 4129:                     return;
 4130:                 }
 4131:                 foreach my $key (@courses_and_groups) {
 4132:                     my %content = %{$$access_hash{$key}};
 4133:                     my $cnum = $content{'number'};
 4134:                     my $cdom = $content{'domain'};
 4135:                     my $cid = $cdom.'_'.$cnum;
 4136:                     if (!exists($allroles{$cid})) {
 4137:                         next;
 4138:                     }    
 4139:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4140:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4141:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4142:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4143:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4144:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4145:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4146:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4147:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4148:                                         if (grep/^all$/,@sections) {
 4149:                                             return 'ok';
 4150:                                         } else {
 4151:                                             if (grep/^$sec$/,@sections) {
 4152:                                                 return 'ok';
 4153:                                             }
 4154:                                         }
 4155:                                     }
 4156:                                 }
 4157:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4158:                                     if (grep/^none$/,@groups) {
 4159:                                         return 'ok';
 4160:                                     }
 4161:                                 } else {
 4162:                                     if (grep/^all$/,@groups) {
 4163:                                         return 'ok';
 4164:                                     } 
 4165:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4166:                                         if (grep/^$group$/,@groups) {
 4167:                                             return 'ok';
 4168:                                         }
 4169:                                     }
 4170:                                 } 
 4171:                             }
 4172:                         }
 4173:                     }
 4174:                 }
 4175:             }
 4176:             if ($guest) {
 4177:                 return $guest;
 4178:             }
 4179:         }
 4180:     }
 4181:     return;
 4182: }
 4183: 
 4184: sub course_group_datechecker {
 4185:     my ($dates,$now,$status) = @_;
 4186:     my ($start,$end) = split(/\./,$dates);
 4187:     if (!$start && !$end) {
 4188:         return 'ok';
 4189:     }
 4190:     if (grep/^active$/,@{$status}) {
 4191:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4192:             return 'ok';
 4193:         }
 4194:     }
 4195:     if (grep/^previous$/,@{$status}) {
 4196:         if ($end > $now ) {
 4197:             return 'ok';
 4198:         }
 4199:     }
 4200:     if (grep/^future$/,@{$status}) {
 4201:         if ($start > $now) {
 4202:             return 'ok';
 4203:         }
 4204:     }
 4205:     return; 
 4206: }
 4207: 
 4208: sub parse_portfolio_url {
 4209:     my ($url) = @_;
 4210: 
 4211:     my ($type,$udom,$unum,$group,$file_name);
 4212:     
 4213:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4214: 	$type = 1;
 4215:         $udom = $1;
 4216:         $unum = $2;
 4217:         $file_name = $3;
 4218:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4219: 	$type = 2;
 4220:         $udom = $1;
 4221:         $unum = $2;
 4222:         $group = $3;
 4223:         $file_name = $3.'/'.$4;
 4224:     }
 4225:     if (wantarray) {
 4226: 	return ($type,$udom,$unum,$file_name,$group);
 4227:     }
 4228:     return $type;
 4229: }
 4230: 
 4231: sub is_portfolio_url {
 4232:     my ($url) = @_;
 4233:     return scalar(&parse_portfolio_url($url));
 4234: }
 4235: 
 4236: sub is_portfolio_file {
 4237:     my ($file) = @_;
 4238:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4239:         return 1;
 4240:     }
 4241:     return;
 4242: }
 4243: 
 4244: 
 4245: # ---------------------------------------------- Custom access rule evaluation
 4246: 
 4247: sub customaccess {
 4248:     my ($priv,$uri)=@_;
 4249:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4250:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4251:     $udom = &LONCAPA::clean_domain($udom);
 4252:     $ucrs = &LONCAPA::clean_username($ucrs);
 4253:     my $access=0;
 4254:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4255: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4256: 	if ($type eq 'user') {
 4257: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4258: 		my ($tdom,$tuname)=split(m{/},$scope);
 4259: 		if ($tdom) {
 4260: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4261: 		}
 4262: 		if ($tuname) {
 4263: 		    if ($tuname ne $env{'user.name'}) { next; }
 4264: 		}
 4265: 		$access=($effect eq 'allow');
 4266: 		last;
 4267: 	    }
 4268: 	} else {
 4269: 	    if ($role) {
 4270: 		if ($role ne $urole) { next; }
 4271: 	    }
 4272: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4273: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4274: 		if ($tdom) {
 4275: 		    if ($tdom ne $udom) { next; }
 4276: 		}
 4277: 		if ($tcrs) {
 4278: 		    if ($tcrs ne $ucrs) { next; }
 4279: 		}
 4280: 		if ($tsec) {
 4281: 		    if ($tsec ne $usec) { next; }
 4282: 		}
 4283: 		$access=($effect eq 'allow');
 4284: 		last;
 4285: 	    }
 4286: 	    if ($realm eq '' && $role eq '') {
 4287: 		$access=($effect eq 'allow');
 4288: 	    }
 4289: 	}
 4290:     }
 4291:     return $access;
 4292: }
 4293: 
 4294: # ------------------------------------------------- Check for a user privilege
 4295: 
 4296: sub allowed {
 4297:     my ($priv,$uri,$symb,$role)=@_;
 4298:     my $ver_orguri=$uri;
 4299:     $uri=&deversion($uri);
 4300:     my $orguri=$uri;
 4301:     $uri=&declutter($uri);
 4302: 
 4303:     if ($priv eq 'evb') {
 4304: # Evade communication block restrictions for specified role in a course
 4305:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4306:             return $1;
 4307:         } else {
 4308:             return;
 4309:         }
 4310:     }
 4311: 
 4312:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4313: # Free bre access to adm and meta resources
 4314:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4315: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4316: 	&& ($priv eq 'bre')) {
 4317: 	return 'F';
 4318:     }
 4319: 
 4320: # Free bre access to user's own portfolio contents
 4321:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4322:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4323: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4324:         my %setters;
 4325:         my ($startblock,$endblock) = 
 4326:             &Apache::loncommon::blockcheck(\%setters,'port');
 4327:         if ($startblock && $endblock) {
 4328:             return 'B';
 4329:         } else {
 4330:             return 'F';
 4331:         }
 4332:     }
 4333: 
 4334: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4335:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4336:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4337:         if (exists($env{'request.course.id'})) {
 4338:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4339:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4340:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4341:                 my $courseprivid=$env{'request.course.id'};
 4342:                 $courseprivid=~s/\_/\//;
 4343:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4344:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4345:                     return $1; 
 4346:                 } else {
 4347:                     if ($env{'request.course.sec'}) {
 4348:                         $courseprivid.='/'.$env{'request.course.sec'};
 4349:                     }
 4350:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4351:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4352:                         return $2;
 4353:                     }
 4354:                 }
 4355:             }
 4356:         }
 4357:     }
 4358: 
 4359: # Free bre to public access
 4360: 
 4361:     if ($priv eq 'bre') {
 4362:         my $copyright=&metadata($uri,'copyright');
 4363: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4364:            return 'F'; 
 4365:         }
 4366:         if ($copyright eq 'priv') {
 4367:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4368: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4369: 		return '';
 4370:             }
 4371:         }
 4372:         if ($copyright eq 'domain') {
 4373:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4374: 	    unless (($env{'user.domain'} eq $1) ||
 4375:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4376: 		return '';
 4377:             }
 4378:         }
 4379:         if ($env{'request.role'}=~ /li\.\//) {
 4380:             # Library role, so allow browsing of resources in this domain.
 4381:             return 'F';
 4382:         }
 4383:         if ($copyright eq 'custom') {
 4384: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4385:         }
 4386:     }
 4387:     # Domain coordinator is trying to create a course
 4388:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4389:         # uri is the requested domain in this case.
 4390:         # comparison to 'request.role.domain' shows if the user has selected
 4391:         # a role of dc for the domain in question.
 4392:         return 'F' if ($uri eq $env{'request.role.domain'});
 4393:     }
 4394: 
 4395:     my $thisallowed='';
 4396:     my $statecond=0;
 4397:     my $courseprivid='';
 4398: 
 4399: # Course
 4400: 
 4401:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4402:        $thisallowed.=$1;
 4403:     }
 4404: 
 4405: # Domain
 4406: 
 4407:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4408:        =~/\Q$priv\E\&([^\:]*)/) {
 4409:        $thisallowed.=$1;
 4410:     }
 4411: 
 4412: # Course: uri itself is a course
 4413:     my $courseuri=$uri;
 4414:     $courseuri=~s/\_(\d)/\/$1/;
 4415:     $courseuri=~s/^([^\/])/\/$1/;
 4416: 
 4417:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4418:        =~/\Q$priv\E\&([^\:]*)/) {
 4419:        $thisallowed.=$1;
 4420:     }
 4421: 
 4422: # URI is an uploaded document for this course, default permissions don't matter
 4423: # not allowing 'edit' access (editupload) to uploaded course docs
 4424:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4425: 	$thisallowed='';
 4426:         my ($match)=&is_on_map($uri);
 4427:         if ($match) {
 4428:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4429:                   =~/\Q$priv\E\&([^\:]*)/) {
 4430:                 $thisallowed.=$1;
 4431:             }
 4432:         } else {
 4433:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4434:             if ($refuri) {
 4435:                 if ($refuri =~ m|^/adm/|) {
 4436:                     $thisallowed='F';
 4437:                 } else {
 4438:                     $refuri=&declutter($refuri);
 4439:                     my ($match) = &is_on_map($refuri);
 4440:                     if ($match) {
 4441:                         $thisallowed='F';
 4442:                     }
 4443:                 }
 4444:             }
 4445:         }
 4446:     }
 4447: 
 4448:     if ($priv eq 'bre'
 4449: 	&& $thisallowed ne 'F' 
 4450: 	&& $thisallowed ne '2'
 4451: 	&& &is_portfolio_url($uri)) {
 4452: 	$thisallowed = &portfolio_access($uri);
 4453:     }
 4454:     
 4455: # Full access at system, domain or course-wide level? Exit.
 4456: 
 4457:     if ($thisallowed=~/F/) {
 4458: 	return 'F';
 4459:     }
 4460: 
 4461: # If this is generating or modifying users, exit with special codes
 4462: 
 4463:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4464: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4465: 	    my ($audom,$auname)=split('/',$uri);
 4466: # no author name given, so this just checks on the general right to make a co-author in this domain
 4467: 	    unless ($auname) { return $thisallowed; }
 4468: # an author name is given, so we are about to actually make a co-author for a certain account
 4469: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4470: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4471: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4472: 	}
 4473: 	return $thisallowed;
 4474:     }
 4475: #
 4476: # Gathered so far: system, domain and course wide privileges
 4477: #
 4478: # Course: See if uri or referer is an individual resource that is part of 
 4479: # the course
 4480: 
 4481:     if ($env{'request.course.id'}) {
 4482: 
 4483:        $courseprivid=$env{'request.course.id'};
 4484:        if ($env{'request.course.sec'}) {
 4485:           $courseprivid.='/'.$env{'request.course.sec'};
 4486:        }
 4487:        $courseprivid=~s/\_/\//;
 4488:        my $checkreferer=1;
 4489:        my ($match,$cond)=&is_on_map($uri);
 4490:        if ($match) {
 4491:            $statecond=$cond;
 4492:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4493:                =~/\Q$priv\E\&([^\:]*)/) {
 4494:                $thisallowed.=$1;
 4495:                $checkreferer=0;
 4496:            }
 4497:        }
 4498:        
 4499:        if ($checkreferer) {
 4500: 	  my $refuri=$env{'httpref.'.$orguri};
 4501:             unless ($refuri) {
 4502:                 foreach my $key (keys(%env)) {
 4503: 		    if ($key=~/^httpref\..*\*/) {
 4504: 			my $pattern=$key;
 4505:                         $pattern=~s/^httpref\.\/res\///;
 4506:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4507:                         $pattern=~s/\//\\\//g;
 4508:                         if ($orguri=~/$pattern/) {
 4509: 			    $refuri=$env{$key};
 4510:                         }
 4511:                     }
 4512:                 }
 4513:             }
 4514: 
 4515:          if ($refuri) { 
 4516: 	  $refuri=&declutter($refuri);
 4517:           my ($match,$cond)=&is_on_map($refuri);
 4518:             if ($match) {
 4519:               my $refstatecond=$cond;
 4520:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4521:                   =~/\Q$priv\E\&([^\:]*)/) {
 4522:                   $thisallowed.=$1;
 4523:                   $uri=$refuri;
 4524:                   $statecond=$refstatecond;
 4525:               }
 4526:           }
 4527:         }
 4528:        }
 4529:    }
 4530: 
 4531: #
 4532: # Gathered now: all privileges that could apply, and condition number
 4533: # 
 4534: #
 4535: # Full or no access?
 4536: #
 4537: 
 4538:     if ($thisallowed=~/F/) {
 4539: 	return 'F';
 4540:     }
 4541: 
 4542:     unless ($thisallowed) {
 4543:         return '';
 4544:     }
 4545: 
 4546: # Restrictions exist, deal with them
 4547: #
 4548: #   C:according to course preferences
 4549: #   R:according to resource settings
 4550: #   L:unless locked
 4551: #   X:according to user session state
 4552: #
 4553: 
 4554: # Possibly locked functionality, check all courses
 4555: # Locks might take effect only after 10 minutes cache expiration for other
 4556: # courses, and 2 minutes for current course
 4557: 
 4558:     my $envkey;
 4559:     if ($thisallowed=~/L/) {
 4560:         foreach $envkey (keys %env) {
 4561:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4562:                my $courseid=$2;
 4563:                my $roleid=$1.'.'.$2;
 4564:                $courseid=~s/^\///;
 4565:                my $expiretime=600;
 4566:                if ($env{'request.role'} eq $roleid) {
 4567: 		  $expiretime=120;
 4568:                }
 4569: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4570:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4571:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4572: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4573:                }
 4574:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4575:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4576: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4577:                        &log($env{'user.domain'},$env{'user.name'},
 4578:                             $env{'user.home'},
 4579:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4580:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4581:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4582: 		       return '';
 4583:                    }
 4584:                }
 4585:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4586:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4587: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4588:                        &log($env{'user.domain'},$env{'user.name'},
 4589:                             $env{'user.home'},
 4590:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4591:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4592:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4593: 		       return '';
 4594:                    }
 4595:                }
 4596: 	   }
 4597:        }
 4598:     }
 4599:    
 4600: #
 4601: # Rest of the restrictions depend on selected course
 4602: #
 4603: 
 4604:     unless ($env{'request.course.id'}) {
 4605: 	if ($thisallowed eq 'A') {
 4606: 	    return 'A';
 4607:         } elsif ($thisallowed eq 'B') {
 4608:             return 'B';
 4609: 	} else {
 4610: 	    return '1';
 4611: 	}
 4612:     }
 4613: 
 4614: #
 4615: # Now user is definitely in a course
 4616: #
 4617: 
 4618: 
 4619: # Course preferences
 4620: 
 4621:    if ($thisallowed=~/C/) {
 4622:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4623:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4624:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4625: 	   =~/\Q$rolecode\E/) {
 4626: 	   if ($priv ne 'pch') { 
 4627: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4628: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4629: 			$env{'request.course.id'});
 4630: 	   }
 4631:            return '';
 4632:        }
 4633: 
 4634:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4635: 	   =~/\Q$unamedom\E/) {
 4636: 	   if ($priv ne 'pch') { 
 4637: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4638: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4639: 			$env{'request.course.id'});
 4640: 	   }
 4641:            return '';
 4642:        }
 4643:    }
 4644: 
 4645: # Resource preferences
 4646: 
 4647:    if ($thisallowed=~/R/) {
 4648:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4649:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4650: 	   if ($priv ne 'pch') { 
 4651: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4652: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4653: 	   }
 4654: 	   return '';
 4655:        }
 4656:    }
 4657: 
 4658: # Restricted by state or randomout?
 4659: 
 4660:    if ($thisallowed=~/X/) {
 4661:       if ($env{'acc.randomout'}) {
 4662: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4663:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4664:             return ''; 
 4665:          }
 4666:       }
 4667:       if (&condval($statecond)) {
 4668: 	 return '2';
 4669:       } else {
 4670:          return '';
 4671:       }
 4672:    }
 4673: 
 4674:     if ($thisallowed eq 'A') {
 4675: 	return 'A';
 4676:     } elsif ($thisallowed eq 'B') {
 4677:         return 'B';
 4678:     }
 4679:    return 'F';
 4680: }
 4681: 
 4682: sub split_uri_for_cond {
 4683:     my $uri=&deversion(&declutter(shift));
 4684:     my @uriparts=split(/\//,$uri);
 4685:     my $filename=pop(@uriparts);
 4686:     my $pathname=join('/',@uriparts);
 4687:     return ($pathname,$filename);
 4688: }
 4689: # --------------------------------------------------- Is a resource on the map?
 4690: 
 4691: sub is_on_map {
 4692:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4693:     #Trying to find the conditional for the file
 4694:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4695: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4696:     if ($match) {
 4697: 	return (1,$1);
 4698:     } else {
 4699: 	return (0,0);
 4700:     }
 4701: }
 4702: 
 4703: # --------------------------------------------------------- Get symb from alias
 4704: 
 4705: sub get_symb_from_alias {
 4706:     my $symb=shift;
 4707:     my ($map,$resid,$url)=&decode_symb($symb);
 4708: # Already is a symb
 4709:     if ($url) { return $symb; }
 4710: # Must be an alias
 4711:     my $aliassymb='';
 4712:     my %bighash;
 4713:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4714:                             &GDBM_READER(),0640)) {
 4715:         my $rid=$bighash{'mapalias_'.$symb};
 4716: 	if ($rid) {
 4717: 	    my ($mapid,$resid)=split(/\./,$rid);
 4718: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4719: 				    $resid,$bighash{'src_'.$rid});
 4720: 	}
 4721:         untie %bighash;
 4722:     }
 4723:     return $aliassymb;
 4724: }
 4725: 
 4726: # ----------------------------------------------------------------- Define Role
 4727: 
 4728: sub definerole {
 4729:   if (allowed('mcr','/')) {
 4730:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4731:     foreach my $role (split(':',$sysrole)) {
 4732: 	my ($crole,$cqual)=split(/\&/,$role);
 4733:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4734:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4735: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4736:                return "refused:s:$crole&$cqual"; 
 4737:             }
 4738:         }
 4739:     }
 4740:     foreach my $role (split(':',$domrole)) {
 4741: 	my ($crole,$cqual)=split(/\&/,$role);
 4742:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4743:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4744: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4745:                return "refused:d:$crole&$cqual"; 
 4746:             }
 4747:         }
 4748:     }
 4749:     foreach my $role (split(':',$courole)) {
 4750: 	my ($crole,$cqual)=split(/\&/,$role);
 4751:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4752:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4753: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4754:                return "refused:c:$crole&$cqual"; 
 4755:             }
 4756:         }
 4757:     }
 4758:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4759:                 "$env{'user.domain'}:$env{'user.name'}:".
 4760: 	        "rolesdef_$rolename=".
 4761:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4762:     return reply($command,$env{'user.home'});
 4763:   } else {
 4764:     return 'refused';
 4765:   }
 4766: }
 4767: 
 4768: # ---------------- Make a metadata query against the network of library servers
 4769: 
 4770: sub metadata_query {
 4771:     my ($query,$custom,$customshow,$server_array)=@_;
 4772:     my %rhash;
 4773:     my %libserv = &all_library();
 4774:     my @server_list = (defined($server_array) ? @$server_array
 4775:                                               : keys(%libserv) );
 4776:     for my $server (@server_list) {
 4777: 	unless ($custom or $customshow) {
 4778: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4779: 	    $rhash{$server}=$reply;
 4780: 	}
 4781: 	else {
 4782: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4783: 			     &escape($custom).':'.&escape($customshow),
 4784: 			     $server);
 4785: 	    $rhash{$server}=$reply;
 4786: 	}
 4787:     }
 4788:     return \%rhash;
 4789: }
 4790: 
 4791: # ----------------------------------------- Send log queries and wait for reply
 4792: 
 4793: sub log_query {
 4794:     my ($uname,$udom,$query,%filters)=@_;
 4795:     my $uhome=&homeserver($uname,$udom);
 4796:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4797:     my $uhost=&hostname($uhome);
 4798:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4799:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4800:                        $uhome);
 4801:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4802:     return get_query_reply($queryid);
 4803: }
 4804: 
 4805: # -------------------------- Update MySQL table for portfolio file
 4806: 
 4807: sub update_portfolio_table {
 4808:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4809:     my $homeserver = &homeserver($uname,$udom);
 4810:     my $queryid=
 4811:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4812:                ':'.&escape($file_name).':'.$action,$homeserver);
 4813:     my $reply = &get_query_reply($queryid);
 4814:     return $reply;
 4815: }
 4816: 
 4817: # -------------------------- Update MySQL allusers table
 4818: 
 4819: sub update_allusers_table {
 4820:     my ($uname,$udom,$names) = @_;
 4821:     my $homeserver = &homeserver($uname,$udom);
 4822:     my $queryid=
 4823:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4824:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4825:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4826:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4827:                'generation='.&escape($names->{'generation'}).'%%'.
 4828:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4829:                'id='.&escape($names->{'id'}),$homeserver);
 4830:     my $reply = &get_query_reply($queryid);
 4831:     return $reply;
 4832: }
 4833: 
 4834: # ------- Request retrieval of institutional classlists for course(s)
 4835: 
 4836: sub fetch_enrollment_query {
 4837:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4838:     my $homeserver;
 4839:     my $maxtries = 1;
 4840:     if ($context eq 'automated') {
 4841:         $homeserver = $perlvar{'lonHostID'};
 4842:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4843:     } else {
 4844:         $homeserver = &homeserver($cnum,$dom);
 4845:     }
 4846:     my $host=&hostname($homeserver);
 4847:     my $cmd = '';
 4848:     foreach my $affiliate (keys %{$affiliatesref}) {
 4849:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4850:     }
 4851:     $cmd =~ s/%%$//;
 4852:     $cmd = &escape($cmd);
 4853:     my $query = 'fetchenrollment';
 4854:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4855:     unless ($queryid=~/^\Q$host\E\_/) { 
 4856:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4857:         return 'error: '.$queryid;
 4858:     }
 4859:     my $reply = &get_query_reply($queryid);
 4860:     my $tries = 1;
 4861:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4862:         $reply = &get_query_reply($queryid);
 4863:         $tries ++;
 4864:     }
 4865:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4866:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4867:     } else {
 4868:         my @responses = split(/:/,$reply);
 4869:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4870:             foreach my $line (@responses) {
 4871:                 my ($key,$value) = split(/=/,$line,2);
 4872:                 $$replyref{$key} = $value;
 4873:             }
 4874:         } else {
 4875:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4876:             foreach my $line (@responses) {
 4877:                 my ($key,$value) = split(/=/,$line);
 4878:                 $$replyref{$key} = $value;
 4879:                 if ($value > 0) {
 4880:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4881:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4882:                         my $destname = $pathname.'/'.$filename;
 4883:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4884:                         if ($xml_classlist =~ /^error/) {
 4885:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4886:                         } else {
 4887:                             if ( open(FILE,">$destname") ) {
 4888:                                 print FILE &unescape($xml_classlist);
 4889:                                 close(FILE);
 4890:                             } else {
 4891:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4892:                             }
 4893:                         }
 4894:                     }
 4895:                 }
 4896:             }
 4897:         }
 4898:         return 'ok';
 4899:     }
 4900:     return 'error';
 4901: }
 4902: 
 4903: sub get_query_reply {
 4904:     my $queryid=shift;
 4905:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4906:     my $reply='';
 4907:     for (1..100) {
 4908: 	sleep 2;
 4909:         if (-e $replyfile.'.end') {
 4910: 	    if (open(my $fh,$replyfile)) {
 4911: 		$reply = join('',<$fh>);
 4912: 		close($fh);
 4913: 	   } else { return 'error: reply_file_error'; }
 4914:            return &unescape($reply);
 4915: 	}
 4916:     }
 4917:     return 'timeout:'.$queryid;
 4918: }
 4919: 
 4920: sub courselog_query {
 4921: #
 4922: # possible filters:
 4923: # url: url or symb
 4924: # username
 4925: # domain
 4926: # action: view, submit, grade
 4927: # start: timestamp
 4928: # end: timestamp
 4929: #
 4930:     my (%filters)=@_;
 4931:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4932:     if ($filters{'url'}) {
 4933: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4934:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4935:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4936:     }
 4937:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4938:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4939:     return &log_query($cname,$cdom,'courselog',%filters);
 4940: }
 4941: 
 4942: sub userlog_query {
 4943: #
 4944: # possible filters:
 4945: # action: log check role
 4946: # start: timestamp
 4947: # end: timestamp
 4948: #
 4949:     my ($uname,$udom,%filters)=@_;
 4950:     return &log_query($uname,$udom,'userlog',%filters);
 4951: }
 4952: 
 4953: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4954: 
 4955: sub auto_run {
 4956:     my ($cnum,$cdom) = @_;
 4957:     my $response = 0;
 4958:     my $settings;
 4959:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4960:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4961:         $settings = $domconfig{'autoenroll'};
 4962:         if ($settings->{'run'} eq '1') {
 4963:             $response = 1;
 4964:         }
 4965:     } else {
 4966:         my $homeserver;
 4967:         if (&is_course($cdom,$cnum)) {
 4968:             $homeserver = &homeserver($cnum,$cdom);
 4969:         } else {
 4970:             $homeserver = &domain($cdom,'primary');
 4971:         }
 4972:         if ($homeserver ne 'no_host') {
 4973:             $response = &reply('autorun:'.$cdom,$homeserver);
 4974:         }
 4975:     }
 4976:     return $response;
 4977: }
 4978: 
 4979: sub auto_get_sections {
 4980:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4981:     my $homeserver = &homeserver($cnum,$cdom);
 4982:     my @secs = ();
 4983:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4984:     unless ($response eq 'refused') {
 4985:         @secs = split(/:/,$response);
 4986:     }
 4987:     return @secs;
 4988: }
 4989: 
 4990: sub auto_new_course {
 4991:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4992:     my $homeserver = &homeserver($cnum,$cdom);
 4993:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4994:     return $response;
 4995: }
 4996: 
 4997: sub auto_validate_courseID {
 4998:     my ($cnum,$cdom,$inst_course_id) = @_;
 4999:     my $homeserver = &homeserver($cnum,$cdom);
 5000:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5001:     return $response;
 5002: }
 5003: 
 5004: sub auto_create_password {
 5005:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5006:     my ($homeserver,$response);
 5007:     my $create_passwd = 0;
 5008:     my $authchk = '';
 5009:     if ($udom =~ /^$match_domain$/) {
 5010:         $homeserver = &domain($udom,'primary');
 5011:     }
 5012:     if ($homeserver eq '') {
 5013:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5014:             $homeserver = &homeserver($cnum,$cdom);
 5015:         }
 5016:     }
 5017:     if ($homeserver eq '') {
 5018:         $authchk = 'nodomain';
 5019:     } else {
 5020:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5021:         if ($response eq 'refused') {
 5022:             $authchk = 'refused';
 5023:         } else {
 5024:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5025:         }
 5026:     }
 5027:     return ($authparam,$create_passwd,$authchk);
 5028: }
 5029: 
 5030: sub auto_photo_permission {
 5031:     my ($cnum,$cdom,$students) = @_;
 5032:     my $homeserver = &homeserver($cnum,$cdom);
 5033:     my ($outcome,$perm_reqd,$conditions) = 
 5034: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5035:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5036: 	return (undef,undef);
 5037:     }
 5038:     return ($outcome,$perm_reqd,$conditions);
 5039: }
 5040: 
 5041: sub auto_checkphotos {
 5042:     my ($uname,$udom,$pid) = @_;
 5043:     my $homeserver = &homeserver($uname,$udom);
 5044:     my ($result,$resulttype);
 5045:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5046: 				   &escape($uname).':'.&escape($pid),
 5047: 				   $homeserver));
 5048:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5049: 	return (undef,undef);
 5050:     }
 5051:     if ($outcome) {
 5052:         ($result,$resulttype) = split(/:/,$outcome);
 5053:     } 
 5054:     return ($result,$resulttype);
 5055: }
 5056: 
 5057: sub auto_photochoice {
 5058:     my ($cnum,$cdom) = @_;
 5059:     my $homeserver = &homeserver($cnum,$cdom);
 5060:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5061: 						       &escape($cdom),
 5062: 						       $homeserver)));
 5063:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5064: 	return (undef,undef);
 5065:     }
 5066:     return ($update,$comment);
 5067: }
 5068: 
 5069: sub auto_photoupdate {
 5070:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5071:     my $homeserver = &homeserver($cnum,$dom);
 5072:     my $host=&hostname($homeserver);
 5073:     my $cmd = '';
 5074:     my $maxtries = 1;
 5075:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5076:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5077:     }
 5078:     $cmd =~ s/%%$//;
 5079:     $cmd = &escape($cmd);
 5080:     my $query = 'institutionalphotos';
 5081:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5082:     unless ($queryid=~/^\Q$host\E\_/) {
 5083:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5084:         return 'error: '.$queryid;
 5085:     }
 5086:     my $reply = &get_query_reply($queryid);
 5087:     my $tries = 1;
 5088:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5089:         $reply = &get_query_reply($queryid);
 5090:         $tries ++;
 5091:     }
 5092:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5093:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5094:     } else {
 5095:         my @responses = split(/:/,$reply);
 5096:         my $outcome = shift(@responses); 
 5097:         foreach my $item (@responses) {
 5098:             my ($key,$value) = split(/=/,$item);
 5099:             $$photo{$key} = $value;
 5100:         }
 5101:         return $outcome;
 5102:     }
 5103:     return 'error';
 5104: }
 5105: 
 5106: sub auto_instcode_format {
 5107:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5108: 	$cat_order) = @_;
 5109:     my $courses = '';
 5110:     my @homeservers;
 5111:     if ($caller eq 'global') {
 5112: 	my %servers = &get_servers($codedom,'library');
 5113: 	foreach my $tryserver (keys(%servers)) {
 5114: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5115: 		push(@homeservers,$tryserver);
 5116: 	    }
 5117:         }
 5118:     } else {
 5119:         push(@homeservers,&homeserver($caller,$codedom));
 5120:     }
 5121:     foreach my $code (keys(%{$instcodes})) {
 5122:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5123:     }
 5124:     chop($courses);
 5125:     my $ok_response = 0;
 5126:     my $response;
 5127:     while (@homeservers > 0 && $ok_response == 0) {
 5128:         my $server = shift(@homeservers); 
 5129:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5130:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5131:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5132: 		split(/:/,$response);
 5133:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5134:             push(@{$codetitles},&str2array($codetitles_str));
 5135:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5136:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5137:             $ok_response = 1;
 5138:         }
 5139:     }
 5140:     if ($ok_response) {
 5141:         return 'ok';
 5142:     } else {
 5143:         return $response;
 5144:     }
 5145: }
 5146: 
 5147: sub auto_instcode_defaults {
 5148:     my ($domain,$returnhash,$code_order) = @_;
 5149:     my @homeservers;
 5150: 
 5151:     my %servers = &get_servers($domain,'library');
 5152:     foreach my $tryserver (keys(%servers)) {
 5153: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5154: 	    push(@homeservers,$tryserver);
 5155: 	}
 5156:     }
 5157: 
 5158:     my $response;
 5159:     foreach my $server (@homeservers) {
 5160:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5161:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5162: 	
 5163: 	foreach my $pair (split(/\&/,$response)) {
 5164: 	    my ($name,$value)=split(/\=/,$pair);
 5165: 	    if ($name eq 'code_order') {
 5166: 		@{$code_order} = split(/\&/,&unescape($value));
 5167: 	    } else {
 5168: 		$returnhash->{&unescape($name)}=&unescape($value);
 5169: 	    }
 5170: 	}
 5171: 	return 'ok';
 5172:     }
 5173: 
 5174:     return $response;
 5175: } 
 5176: 
 5177: sub auto_validate_class_sec {
 5178:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5179:     my $homeserver = &homeserver($cnum,$cdom);
 5180:     my $ownerlist;
 5181:     if (ref($owners) eq 'ARRAY') {
 5182:         $ownerlist = join(',',@{$owners});
 5183:     } else {
 5184:         $ownerlist = $owners;
 5185:     }
 5186:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5187:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5188:     return $response;
 5189: }
 5190: 
 5191: # ------------------------------------------------------- Course Group routines
 5192: 
 5193: sub get_coursegroups {
 5194:     my ($cdom,$cnum,$group,$namespace) = @_;
 5195:     return(&dump($namespace,$cdom,$cnum,$group));
 5196: }
 5197: 
 5198: sub modify_coursegroup {
 5199:     my ($cdom,$cnum,$groupsettings) = @_;
 5200:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5201: }
 5202: 
 5203: sub toggle_coursegroup_status {
 5204:     my ($cdom,$cnum,$group,$action) = @_;
 5205:     my ($from_namespace,$to_namespace);
 5206:     if ($action eq 'delete') {
 5207:         $from_namespace = 'coursegroups';
 5208:         $to_namespace = 'deleted_groups';
 5209:     } else {
 5210:         $from_namespace = 'deleted_groups';
 5211:         $to_namespace = 'coursegroups';
 5212:     }
 5213:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5214:     if (my $tmp = &error(%curr_group)) {
 5215:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5216:         return ('read error',$tmp);
 5217:     } else {
 5218:         my %savedsettings = %curr_group; 
 5219:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5220:         my $deloutcome;
 5221:         if ($result eq 'ok') {
 5222:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5223:         } else {
 5224:             return ('write error',$result);
 5225:         }
 5226:         if ($deloutcome eq 'ok') {
 5227:             return 'ok';
 5228:         } else {
 5229:             return ('delete error',$deloutcome);
 5230:         }
 5231:     }
 5232: }
 5233: 
 5234: sub modify_group_roles {
 5235:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5236:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5237:     my $role = 'gr/'.&escape($userprivs);
 5238:     my ($uname,$udom) = split(/:/,$user);
 5239:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5240:     if ($result eq 'ok') {
 5241:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5242:     }
 5243:     return $result;
 5244: }
 5245: 
 5246: sub modify_coursegroup_membership {
 5247:     my ($cdom,$cnum,$membership) = @_;
 5248:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5249:     return $result;
 5250: }
 5251: 
 5252: sub get_active_groups {
 5253:     my ($udom,$uname,$cdom,$cnum) = @_;
 5254:     my $now = time;
 5255:     my %groups = ();
 5256:     foreach my $key (keys(%env)) {
 5257:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5258:             my ($start,$end) = split(/\./,$env{$key});
 5259:             if (($end!=0) && ($end<$now)) { next; }
 5260:             if (($start!=0) && ($start>$now)) { next; }
 5261:             if ($1 eq $cdom && $2 eq $cnum) {
 5262:                 $groups{$3} = $env{$key} ;
 5263:             }
 5264:         }
 5265:     }
 5266:     return %groups;
 5267: }
 5268: 
 5269: sub get_group_membership {
 5270:     my ($cdom,$cnum,$group) = @_;
 5271:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5272: }
 5273: 
 5274: sub get_users_groups {
 5275:     my ($udom,$uname,$courseid) = @_;
 5276:     my @usersgroups;
 5277:     my $cachetime=1800;
 5278: 
 5279:     my $hashid="$udom:$uname:$courseid";
 5280:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5281:     if (defined($cached)) {
 5282:         @usersgroups = split(/:/,$grouplist);
 5283:     } else {  
 5284:         $grouplist = '';
 5285:         my $courseurl = &courseid_to_courseurl($courseid);
 5286:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5287:         my $access_end = $env{'course.'.$courseid.
 5288:                               '.default_enrollment_end_date'};
 5289:         my $now = time;
 5290:         foreach my $key (keys(%roleshash)) {
 5291:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5292:                 my $group = $1;
 5293:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5294:                     my $start = $2;
 5295:                     my $end = $1;
 5296:                     if ($start == -1) { next; } # deleted from group
 5297:                     if (($start!=0) && ($start>$now)) { next; }
 5298:                     if (($end!=0) && ($end<$now)) {
 5299:                         if ($access_end && $access_end < $now) {
 5300:                             if ($access_end - $end < 86400) {
 5301:                                 push(@usersgroups,$group);
 5302:                             }
 5303:                         }
 5304:                         next;
 5305:                     }
 5306:                     push(@usersgroups,$group);
 5307:                 }
 5308:             }
 5309:         }
 5310:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5311:         $grouplist = join(':',@usersgroups);
 5312:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5313:     }
 5314:     return @usersgroups;
 5315: }
 5316: 
 5317: sub devalidate_getgroups_cache {
 5318:     my ($udom,$uname,$cdom,$cnum)=@_;
 5319:     my $courseid = $cdom.'_'.$cnum;
 5320: 
 5321:     my $hashid="$udom:$uname:$courseid";
 5322:     &devalidate_cache_new('getgroups',$hashid);
 5323: }
 5324: 
 5325: # ------------------------------------------------------------------ Plain Text
 5326: 
 5327: sub plaintext {
 5328:     my ($short,$type,$cid) = @_;
 5329:     if ($short =~ /^cr/) {
 5330: 	return (split('/',$short))[-1];
 5331:     }
 5332:     if (!defined($cid)) {
 5333:         $cid = $env{'request.course.id'};
 5334:     }
 5335:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5336:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5337:                                           '.plaintext'});
 5338:     }
 5339:     my %rolenames = (
 5340:                       Course => 'std',
 5341:                       Group => 'alt1',
 5342:                     );
 5343:     if (defined($type) && 
 5344:          defined($rolenames{$type}) && 
 5345:          defined($prp{$short}{$rolenames{$type}})) {
 5346:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5347:     } else {
 5348:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5349:     }
 5350: }
 5351: 
 5352: # ----------------------------------------------------------------- Assign Role
 5353: 
 5354: sub assignrole {
 5355:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
 5356:     my $mrole;
 5357:     if ($role =~ /^cr\//) {
 5358:         my $cwosec=$url;
 5359:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5360: 	unless (&allowed('ccr',$cwosec)) {
 5361:            &logthis('Refused custom assignrole: '.
 5362:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5363: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5364:            return 'refused'; 
 5365:         }
 5366:         $mrole='cr';
 5367:     } elsif ($role =~ /^gr\//) {
 5368:         my $cwogrp=$url;
 5369:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5370:         unless (&allowed('mdg',$cwogrp)) {
 5371:             &logthis('Refused group assignrole: '.
 5372:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5373:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5374:             return 'refused';
 5375:         }
 5376:         $mrole='gr';
 5377:     } else {
 5378:         my $cwosec=$url;
 5379:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5380:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5381:             my $refused;
 5382:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5383:                 if (!(&allowed('c'.$role,$url))) {
 5384:                     $refused = 1;
 5385:                 }
 5386:             } else {
 5387:                 $refused = 1;
 5388:             }
 5389:             if ($refused) {
 5390:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5391:                     $refused = '';
 5392:                 } else {
 5393:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5394:                              ' '.$role.' '.$end.' '.$start.' by '.
 5395: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5396:                     return 'refused';
 5397:                 }
 5398:             }
 5399:         }
 5400:         $mrole=$role;
 5401:     }
 5402:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5403:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5404:     if ($end) { $command.='_'.$end; }
 5405:     if ($start) {
 5406: 	if ($end) { 
 5407:            $command.='_'.$start; 
 5408:         } else {
 5409:            $command.='_0_'.$start;
 5410:         }
 5411:     }
 5412:     my $origstart = $start;
 5413:     my $origend = $end;
 5414: # actually delete
 5415:     if ($deleteflag) {
 5416: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5417: # modify command to delete the role
 5418:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5419:                 "$udom:$uname:$url".'_'."$mrole";
 5420: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5421: # set start and finish to negative values for userrolelog
 5422:            $start=-1;
 5423:            $end=-1;
 5424:         }
 5425:     }
 5426: # send command
 5427:     my $answer=&reply($command,&homeserver($uname,$udom));
 5428: # log new user role if status is ok
 5429:     if ($answer eq 'ok') {
 5430: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5431: # for course roles, perform group memberships changes triggered by role change.
 5432:         unless ($role =~ /^gr/) {
 5433:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5434:                                              $origstart);
 5435:         }
 5436:     }
 5437:     return $answer;
 5438: }
 5439: 
 5440: # -------------------------------------------------- Modify user authentication
 5441: # Overrides without validation
 5442: 
 5443: sub modifyuserauth {
 5444:     my ($udom,$uname,$umode,$upass)=@_;
 5445:     my $uhome=&homeserver($uname,$udom);
 5446:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5447:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5448:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5449:              ' in domain '.$env{'request.role.domain'});  
 5450:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5451: 		     &escape($upass),$uhome);
 5452:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5453:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5454:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5455:     &log($udom,,$uname,$uhome,
 5456:         'Authentication changed by '.$env{'user.domain'}.', '.
 5457:                                      $env{'user.name'}.', '.$umode.
 5458:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5459:     unless ($reply eq 'ok') {
 5460:         &logthis('Authentication mode error: '.$reply);
 5461: 	return 'error: '.$reply;
 5462:     }   
 5463:     return 'ok';
 5464: }
 5465: 
 5466: # --------------------------------------------------------------- Modify a user
 5467: 
 5468: sub modifyuser {
 5469:     my ($udom,    $uname, $uid,
 5470:         $umode,   $upass, $first,
 5471:         $middle,  $last,  $gene,
 5472:         $forceid, $desiredhome, $email)=@_;
 5473:     $udom= &LONCAPA::clean_domain($udom);
 5474:     $uname=&LONCAPA::clean_username($uname);
 5475:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5476:              $umode.', '.$first.', '.$middle.', '.
 5477: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5478:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5479:                                      ' desiredhome not specified'). 
 5480:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5481:              ' in domain '.$env{'request.role.domain'});
 5482:     my $uhome=&homeserver($uname,$udom,'true');
 5483: # ----------------------------------------------------------------- Create User
 5484:     if (($uhome eq 'no_host') && 
 5485: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5486:         my $unhome='';
 5487:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5488:             $unhome = $desiredhome;
 5489: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5490: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5491:         } else { # load balancing routine for determining $unhome
 5492:             my $loadm=10000000;
 5493: 	    my %servers = &get_servers($udom,'library');
 5494: 	    foreach my $tryserver (keys(%servers)) {
 5495: 		my $answer=reply('load',$tryserver);
 5496: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5497: 		    $loadm=$answer;
 5498: 		    $unhome=$tryserver;
 5499: 		}
 5500: 	    }
 5501:         }
 5502:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5503: 	    return 'error: unable to find a home server for '.$uname.
 5504:                    ' in domain '.$udom;
 5505:         }
 5506:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5507:                          &escape($upass),$unhome);
 5508: 	unless ($reply eq 'ok') {
 5509:             return 'error: '.$reply;
 5510:         }   
 5511:         $uhome=&homeserver($uname,$udom,'true');
 5512:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5513: 	    return 'error: unable verify users home machine.';
 5514:         }
 5515:     }   # End of creation of new user
 5516: # ---------------------------------------------------------------------- Add ID
 5517:     if ($uid) {
 5518:        $uid=~tr/A-Z/a-z/;
 5519:        my %uidhash=&idrget($udom,$uname);
 5520:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5521:          && (!$forceid)) {
 5522: 	  unless ($uid eq $uidhash{$uname}) {
 5523: 	      return 'error: user id "'.$uid.'" does not match '.
 5524:                   'current user id "'.$uidhash{$uname}.'".';
 5525:           }
 5526:        } else {
 5527: 	  &idput($udom,($uname => $uid));
 5528:        }
 5529:     }
 5530: # -------------------------------------------------------------- Add names, etc
 5531:     my @tmp=&get('environment',
 5532: 		   ['firstname','middlename','lastname','generation','id',
 5533:                     'permanentemail'],
 5534: 		   $udom,$uname);
 5535:     my %names;
 5536:     if ($tmp[0] =~ m/^error:.*/) { 
 5537:         %names=(); 
 5538:     } else {
 5539:         %names = @tmp;
 5540:     }
 5541: #
 5542: # Make sure to not trash student environment if instructor does not bother
 5543: # to supply name and email information
 5544: #
 5545:     if ($first)  { $names{'firstname'}  = $first; }
 5546:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5547:     if ($last)   { $names{'lastname'}   = $last; }
 5548:     if (defined($gene))   { $names{'generation'} = $gene; }
 5549:     if ($email) {
 5550:        $email=~s/[^\w\@\.\-\,]//gs;
 5551:        if ($email=~/\@/) { $names{'notification'} = $email;
 5552: 			   $names{'critnotification'} = $email;
 5553: 			   $names{'permanentemail'} = $email; }
 5554:     }
 5555:     if ($uid) { $names{'id'}  = $uid; }
 5556:     my $reply = &put('environment', \%names, $udom,$uname);
 5557:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5558:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5559:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5560:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5561:              $umode.', '.$first.', '.$middle.', '.
 5562: 	     $last.', '.$gene.' by '.
 5563:              $env{'user.name'}.' at '.$env{'user.domain'});
 5564:     return 'ok';
 5565: }
 5566: 
 5567: # -------------------------------------------------------------- Modify student
 5568: 
 5569: sub modifystudent {
 5570:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5571:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5572:     if (!$cid) {
 5573: 	unless ($cid=$env{'request.course.id'}) {
 5574: 	    return 'not_in_class';
 5575: 	}
 5576:     }
 5577: # --------------------------------------------------------------- Make the user
 5578:     my $reply=&modifyuser
 5579: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5580:          $desiredhome,$email);
 5581:     unless ($reply eq 'ok') { return $reply; }
 5582:     # This will cause &modify_student_enrollment to get the uid from the
 5583:     # students environment
 5584:     $uid = undef if (!$forceid);
 5585:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5586: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5587:     return $reply;
 5588: }
 5589: 
 5590: sub modify_student_enrollment {
 5591:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
 5592:     my ($cdom,$cnum,$chome);
 5593:     if (!$cid) {
 5594: 	unless ($cid=$env{'request.course.id'}) {
 5595: 	    return 'not_in_class';
 5596: 	}
 5597: 	$cdom=$env{'course.'.$cid.'.domain'};
 5598: 	$cnum=$env{'course.'.$cid.'.num'};
 5599:     } else {
 5600: 	($cdom,$cnum)=split(/_/,$cid);
 5601:     }
 5602:     $chome=$env{'course.'.$cid.'.home'};
 5603:     if (!$chome) {
 5604: 	$chome=&homeserver($cnum,$cdom);
 5605:     }
 5606:     if (!$chome) { return 'unknown_course'; }
 5607:     # Make sure the user exists
 5608:     my $uhome=&homeserver($uname,$udom);
 5609:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5610: 	return 'error: no such user';
 5611:     }
 5612:     # Get student data if we were not given enough information
 5613:     if (!defined($first)  || $first  eq '' || 
 5614:         !defined($last)   || $last   eq '' || 
 5615:         !defined($uid)    || $uid    eq '' || 
 5616:         !defined($middle) || $middle eq '' || 
 5617:         !defined($gene)   || $gene   eq '') {
 5618:         # They did not supply us with enough data to enroll the student, so
 5619:         # we need to pick up more information.
 5620:         my %tmp = &get('environment',
 5621:                        ['firstname','middlename','lastname', 'generation','id']
 5622:                        ,$udom,$uname);
 5623: 
 5624:         #foreach my $key (keys(%tmp)) {
 5625:         #    &logthis("key $key = ".$tmp{$key});
 5626:         #}
 5627:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5628:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5629:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5630:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5631:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5632:     }
 5633:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5634:     my $reply=cput('classlist',
 5635: 		   {"$uname:$udom" => 
 5636: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5637: 		   $cdom,$cnum);
 5638:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5639: 	return 'error: '.$reply;
 5640:     } else {
 5641: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5642:     }
 5643:     # Add student role to user
 5644:     my $uurl='/'.$cid;
 5645:     $uurl=~s/\_/\//g;
 5646:     if ($usec) {
 5647: 	$uurl.='/'.$usec;
 5648:     }
 5649:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
 5650: }
 5651: 
 5652: sub format_name {
 5653:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5654:     my $name;
 5655:     if ($first ne 'lastname') {
 5656: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5657:     } else {
 5658: 	if ($lastname=~/\S/) {
 5659: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5660: 	    $name=~s/\s+,/,/;
 5661: 	} else {
 5662: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5663: 	}
 5664:     }
 5665:     $name=~s/^\s+//;
 5666:     $name=~s/\s+$//;
 5667:     $name=~s/\s+/ /g;
 5668:     return $name;
 5669: }
 5670: 
 5671: # ------------------------------------------------- Write to course preferences
 5672: 
 5673: sub writecoursepref {
 5674:     my ($courseid,%prefs)=@_;
 5675:     $courseid=~s/^\///;
 5676:     $courseid=~s/\_/\//g;
 5677:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5678:     my $chome=homeserver($cnum,$cdomain);
 5679:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5680: 	return 'error: no such course';
 5681:     }
 5682:     my $cstring='';
 5683:     foreach my $pref (keys(%prefs)) {
 5684: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5685:     }
 5686:     $cstring=~s/\&$//;
 5687:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5688: }
 5689: 
 5690: # ---------------------------------------------------------- Make/modify course
 5691: 
 5692: sub createcourse {
 5693:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5694:         $course_owner,$crstype)=@_;
 5695:     $url=&declutter($url);
 5696:     my $cid='';
 5697:     unless (&allowed('ccc',$udom)) {
 5698:         return 'refused';
 5699:     }
 5700: # ------------------------------------------------------------------- Create ID
 5701:    my $uname=int(1+rand(9)).
 5702:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5703:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5704:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5705: # ----------------------------------------------- Make sure that does not exist
 5706:    my $uhome=&homeserver($uname,$udom,'true');
 5707:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5708:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5709:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5710:        $uhome=&homeserver($uname,$udom,'true');       
 5711:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5712:            return 'error: unable to generate unique course-ID';
 5713:        } 
 5714:    }
 5715: # ------------------------------------------------ Check supplied server name
 5716:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5717:     if (! &is_library($course_server)) {
 5718:         return 'error:bad server name '.$course_server;
 5719:     }
 5720: # ------------------------------------------------------------- Make the course
 5721:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5722:                       $course_server);
 5723:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5724:     $uhome=&homeserver($uname,$udom,'true');
 5725:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5726: 	return 'error: no such course';
 5727:     }
 5728: # ----------------------------------------------------------------- Course made
 5729: # log existence
 5730:     my $newcourse = {
 5731:                     $udom.'_'.$uname => {
 5732:                                      description => $description,
 5733:                                      inst_code   => $inst_code,
 5734:                                      owner       => $course_owner,
 5735:                                      type        => $crstype,
 5736:                                                 },
 5737:                     };
 5738:     &courseidput($udom,$newcourse,$uhome,'notime');
 5739: # set toplevel url
 5740:     my $topurl=$url;
 5741:     unless ($nonstandard) {
 5742: # ------------------------------------------ For standard courses, make top url
 5743:         my $mapurl=&clutter($url);
 5744:         if ($mapurl eq '/res/') { $mapurl=''; }
 5745:         $env{'form.initmap'}=(<<ENDINITMAP);
 5746: <map>
 5747: <resource id="1" type="start"></resource>
 5748: <resource id="2" src="$mapurl"></resource>
 5749: <resource id="3" type="finish"></resource>
 5750: <link index="1" from="1" to="2"></link>
 5751: <link index="2" from="2" to="3"></link>
 5752: </map>
 5753: ENDINITMAP
 5754:         $topurl=&declutter(
 5755:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5756:                           );
 5757:     }
 5758: # ----------------------------------------------------------- Write preferences
 5759:     &writecoursepref($udom.'_'.$uname,
 5760:                      ('description' => $description,
 5761:                       'url'         => $topurl));
 5762:     return '/'.$udom.'/'.$uname;
 5763: }
 5764: 
 5765: sub is_course {
 5766:     my ($cdom,$cnum) = @_;
 5767:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5768: 				undef,'.');
 5769:     if (exists($courses{$cdom.'_'.$cnum})) {
 5770:         return 1;
 5771:     }
 5772:     return 0;
 5773: }
 5774: 
 5775: # ---------------------------------------------------------- Assign Custom Role
 5776: 
 5777: sub assigncustomrole {
 5778:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5779:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5780:                        $end,$start,$deleteflag);
 5781: }
 5782: 
 5783: # ----------------------------------------------------------------- Revoke Role
 5784: 
 5785: sub revokerole {
 5786:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5787:     my $now=time;
 5788:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5789: }
 5790: 
 5791: # ---------------------------------------------------------- Revoke Custom Role
 5792: 
 5793: sub revokecustomrole {
 5794:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5795:     my $now=time;
 5796:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5797:            $deleteflag);
 5798: }
 5799: 
 5800: # ------------------------------------------------------------ Disk usage
 5801: sub diskusage {
 5802:     my ($udom,$uname,$directoryRoot)=@_;
 5803:     $directoryRoot =~ s/\/$//;
 5804:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5805:     return $listing;
 5806: }
 5807: 
 5808: sub is_locked {
 5809:     my ($file_name, $domain, $user) = @_;
 5810:     my @check;
 5811:     my $is_locked;
 5812:     push @check, $file_name;
 5813:     my %locked = &get('file_permissions',\@check,
 5814: 		      $env{'user.domain'},$env{'user.name'});
 5815:     my ($tmp)=keys(%locked);
 5816:     if ($tmp=~/^error:/) { undef(%locked); }
 5817:     
 5818:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5819:         $is_locked = 'false';
 5820:         foreach my $entry (@{$locked{$file_name}}) {
 5821:            if (ref($entry) eq 'ARRAY') { 
 5822:                $is_locked = 'true';
 5823:                last;
 5824:            }
 5825:        }
 5826:     } else {
 5827:         $is_locked = 'false';
 5828:     }
 5829: }
 5830: 
 5831: sub declutter_portfile {
 5832:     my ($file) = @_;
 5833:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5834:     return $file;
 5835: }
 5836: 
 5837: # ------------------------------------------------------------- Mark as Read Only
 5838: 
 5839: sub mark_as_readonly {
 5840:     my ($domain,$user,$files,$what) = @_;
 5841:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5842:     my ($tmp)=keys(%current_permissions);
 5843:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5844:     foreach my $file (@{$files}) {
 5845: 	$file = &declutter_portfile($file);
 5846:         push(@{$current_permissions{$file}},$what);
 5847:     }
 5848:     &put('file_permissions',\%current_permissions,$domain,$user);
 5849:     return;
 5850: }
 5851: 
 5852: # ------------------------------------------------------------Save Selected Files
 5853: 
 5854: sub save_selected_files {
 5855:     my ($user, $path, @files) = @_;
 5856:     my $filename = $user."savedfiles";
 5857:     my @other_files = &files_not_in_path($user, $path);
 5858:     open (OUT, '>'.$tmpdir.$filename);
 5859:     foreach my $file (@files) {
 5860:         print (OUT $env{'form.currentpath'}.$file."\n");
 5861:     }
 5862:     foreach my $file (@other_files) {
 5863:         print (OUT $file."\n");
 5864:     }
 5865:     close (OUT);
 5866:     return 'ok';
 5867: }
 5868: 
 5869: sub clear_selected_files {
 5870:     my ($user) = @_;
 5871:     my $filename = $user."savedfiles";
 5872:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5873:     print (OUT undef);
 5874:     close (OUT);
 5875:     return ("ok");    
 5876: }
 5877: 
 5878: sub files_in_path {
 5879:     my ($user, $path) = @_;
 5880:     my $filename = $user."savedfiles";
 5881:     my %return_files;
 5882:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5883:     while (my $line_in = <IN>) {
 5884:         chomp ($line_in);
 5885:         my @paths_and_file = split (m!/!, $line_in);
 5886:         my $file_part = pop (@paths_and_file);
 5887:         my $path_part = join ('/', @paths_and_file);
 5888:         $path_part.='/';
 5889:         my $path_and_file = $path_part.$file_part;
 5890:         if ($path_part eq $path) {
 5891:             $return_files{$file_part}= 'selected';
 5892:         }
 5893:     }
 5894:     close (IN);
 5895:     return (\%return_files);
 5896: }
 5897: 
 5898: # called in portfolio select mode, to show files selected NOT in current directory
 5899: sub files_not_in_path {
 5900:     my ($user, $path) = @_;
 5901:     my $filename = $user."savedfiles";
 5902:     my @return_files;
 5903:     my $path_part;
 5904:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5905:     while (my $line = <IN>) {
 5906:         #ok, I know it's clunky, but I want it to work
 5907:         my @paths_and_file = split(m|/|, $line);
 5908:         my $file_part = pop(@paths_and_file);
 5909:         chomp($file_part);
 5910:         my $path_part = join('/', @paths_and_file);
 5911:         $path_part .= '/';
 5912:         my $path_and_file = $path_part.$file_part;
 5913:         if ($path_part ne $path) {
 5914:             push(@return_files, ($path_and_file));
 5915:         }
 5916:     }
 5917:     close(OUT);
 5918:     return (@return_files);
 5919: }
 5920: 
 5921: #----------------------------------------------Get portfolio file permissions
 5922: 
 5923: sub get_portfile_permissions {
 5924:     my ($domain,$user) = @_;
 5925:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5926:     my ($tmp)=keys(%current_permissions);
 5927:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5928:     return \%current_permissions;
 5929: }
 5930: 
 5931: #---------------------------------------------Get portfolio file access controls
 5932: 
 5933: sub get_access_controls {
 5934:     my ($current_permissions,$group,$file) = @_;
 5935:     my %access;
 5936:     my $real_file = $file;
 5937:     $file =~ s/\.meta$//;
 5938:     if (defined($file)) {
 5939:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5940:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5941:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5942:             }
 5943:         }
 5944:     } else {
 5945:         foreach my $key (keys(%{$current_permissions})) {
 5946:             if ($key =~ /\0accesscontrol$/) {
 5947:                 if (defined($group)) {
 5948:                     if ($key !~ m-^\Q$group\E/-) {
 5949:                         next;
 5950:                     }
 5951:                 }
 5952:                 my ($fullpath) = split(/\0/,$key);
 5953:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5954:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5955:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5956:                     }
 5957:                 }
 5958:             }
 5959:         }
 5960:     }
 5961:     return %access;
 5962: }
 5963: 
 5964: sub modify_access_controls {
 5965:     my ($file_name,$changes,$domain,$user)=@_;
 5966:     my ($outcome,$deloutcome);
 5967:     my %store_permissions;
 5968:     my %new_values;
 5969:     my %new_control;
 5970:     my %translation;
 5971:     my @deletions = ();
 5972:     my $now = time;
 5973:     if (exists($$changes{'activate'})) {
 5974:         if (ref($$changes{'activate'}) eq 'HASH') {
 5975:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5976:             my $numnew = scalar(@newitems);
 5977:             for (my $i=0; $i<$numnew; $i++) {
 5978:                 my $newkey = $newitems[$i];
 5979:                 my $newid = &Apache::loncommon::get_cgi_id();
 5980:                 if ($newkey =~ /^\d+:/) { 
 5981:                     $newkey =~ s/^(\d+)/$newid/;
 5982:                     $translation{$1} = $newid;
 5983:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5984:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5985:                     $translation{$1} = $newid;
 5986:                 }
 5987:                 $new_values{$file_name."\0".$newkey} = 
 5988:                                           $$changes{'activate'}{$newitems[$i]};
 5989:                 $new_control{$newkey} = $now;
 5990:             }
 5991:         }
 5992:     }
 5993:     my %todelete;
 5994:     my %changed_items;
 5995:     foreach my $action ('delete','update') {
 5996:         if (exists($$changes{$action})) {
 5997:             if (ref($$changes{$action}) eq 'HASH') {
 5998:                 foreach my $key (keys(%{$$changes{$action}})) {
 5999:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6000:                     if ($action eq 'delete') { 
 6001:                         $todelete{$itemnum} = 1;
 6002:                     } else {
 6003:                         $changed_items{$itemnum} = $key;
 6004:                     }
 6005:                 }
 6006:             }
 6007:         }
 6008:     }
 6009:     # get lock on access controls for file.
 6010:     my $lockhash = {
 6011:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6012:                                                        ':'.$env{'user.domain'},
 6013:                    }; 
 6014:     my $tries = 0;
 6015:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6016:    
 6017:     while (($gotlock ne 'ok') && $tries <3) {
 6018:         $tries ++;
 6019:         sleep 1;
 6020:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6021:     }
 6022:     if ($gotlock eq 'ok') {
 6023:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6024:         my ($tmp)=keys(%curr_permissions);
 6025:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6026:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6027:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6028:             if (ref($curr_controls) eq 'HASH') {
 6029:                 foreach my $control_item (keys(%{$curr_controls})) {
 6030:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6031:                     if (defined($todelete{$itemnum})) {
 6032:                         push(@deletions,$file_name."\0".$control_item);
 6033:                     } else {
 6034:                         if (defined($changed_items{$itemnum})) {
 6035:                             $new_control{$changed_items{$itemnum}} = $now;
 6036:                             push(@deletions,$file_name."\0".$control_item);
 6037:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6038:                         } else {
 6039:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6040:                         }
 6041:                     }
 6042:                 }
 6043:             }
 6044:         }
 6045:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6046:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6047:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6048:         #  remove lock
 6049:         my @del_lock = ($file_name."\0".'locked_access_records');
 6050:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6051:         my ($file,$group);
 6052:         if (&is_course($domain,$user)) {
 6053:             ($group,$file) = split(/\//,$file_name,2);
 6054:         } else {
 6055:             $file = $file_name;
 6056:         }
 6057:         my $sqlresult =
 6058:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 6059:                                     $group);
 6060:     } else {
 6061:         $outcome = "error: could not obtain lockfile\n";  
 6062:     }
 6063:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6064: }
 6065: 
 6066: sub make_public_indefinitely {
 6067:     my ($requrl) = @_;
 6068:     my $now = time;
 6069:     my $action = 'activate';
 6070:     my $aclnum = 0;
 6071:     if (&is_portfolio_url($requrl)) {
 6072:         my (undef,$udom,$unum,$file_name,$group) =
 6073:             &parse_portfolio_url($requrl);
 6074:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6075:         my %access_controls = &get_access_controls($current_perms,
 6076:                                                    $group,$file_name);
 6077:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6078:             my ($num,$scope,$end,$start) = 
 6079:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6080:             if ($scope eq 'public') {
 6081:                 if ($start <= $now && $end == 0) {
 6082:                     $action = 'none';
 6083:                 } else {
 6084:                     $action = 'update';
 6085:                     $aclnum = $num;
 6086:                 }
 6087:                 last;
 6088:             }
 6089:         }
 6090:         if ($action eq 'none') {
 6091:              return 'ok';
 6092:         } else {
 6093:             my %changes;
 6094:             my $newend = 0;
 6095:             my $newstart = $now;
 6096:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6097:             $changes{$action}{$newkey} = {
 6098:                 type => 'public',
 6099:                 time => {
 6100:                     start => $newstart,
 6101:                     end   => $newend,
 6102:                 },
 6103:             };
 6104:             my ($outcome,$deloutcome,$new_values,$translation) =
 6105:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6106:             return $outcome;
 6107:         }
 6108:     } else {
 6109:         return 'invalid';
 6110:     }
 6111: }
 6112: 
 6113: #------------------------------------------------------Get Marked as Read Only
 6114: 
 6115: sub get_marked_as_readonly {
 6116:     my ($domain,$user,$what,$group) = @_;
 6117:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6118:     my @readonly_files;
 6119:     my $cmp1=$what;
 6120:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6121:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6122:         if (defined($group)) {
 6123:             if ($file_name !~ m-^\Q$group\E/-) {
 6124:                 next;
 6125:             }
 6126:         }
 6127:         if (ref($value) eq "ARRAY"){
 6128:             foreach my $stored_what (@{$value}) {
 6129:                 my $cmp2=$stored_what;
 6130:                 if (ref($stored_what) eq 'ARRAY') {
 6131:                     $cmp2=join('',@{$stored_what});
 6132:                 }
 6133:                 if ($cmp1 eq $cmp2) {
 6134:                     push(@readonly_files, $file_name);
 6135:                     last;
 6136:                 } elsif (!defined($what)) {
 6137:                     push(@readonly_files, $file_name);
 6138:                     last;
 6139:                 }
 6140:             }
 6141:         }
 6142:     }
 6143:     return @readonly_files;
 6144: }
 6145: #-----------------------------------------------------------Get Marked as Read Only Hash
 6146: 
 6147: sub get_marked_as_readonly_hash {
 6148:     my ($current_permissions,$group,$what) = @_;
 6149:     my %readonly_files;
 6150:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6151:         if (defined($group)) {
 6152:             if ($file_name !~ m-^\Q$group\E/-) {
 6153:                 next;
 6154:             }
 6155:         }
 6156:         if (ref($value) eq "ARRAY"){
 6157:             foreach my $stored_what (@{$value}) {
 6158:                 if (ref($stored_what) eq 'ARRAY') {
 6159:                     foreach my $lock_descriptor(@{$stored_what}) {
 6160:                         if ($lock_descriptor eq 'graded') {
 6161:                             $readonly_files{$file_name} = 'graded';
 6162:                         } elsif ($lock_descriptor eq 'handback') {
 6163:                             $readonly_files{$file_name} = 'handback';
 6164:                         } else {
 6165:                             if (!exists($readonly_files{$file_name})) {
 6166:                                 $readonly_files{$file_name} = 'locked';
 6167:                             }
 6168:                         }
 6169:                     }
 6170:                 } 
 6171:             }
 6172:         } 
 6173:     }
 6174:     return %readonly_files;
 6175: }
 6176: # ------------------------------------------------------------ Unmark as Read Only
 6177: 
 6178: sub unmark_as_readonly {
 6179:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6180:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6181:     my ($domain,$user,$what,$file_name,$group) = @_;
 6182:     $file_name = &declutter_portfile($file_name);
 6183:     my $symb_crs = $what;
 6184:     if (ref($what)) { $symb_crs=join('',@$what); }
 6185:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6186:     my ($tmp)=keys(%current_permissions);
 6187:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6188:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6189:     foreach my $file (@readonly_files) {
 6190: 	my $clean_file = &declutter_portfile($file);
 6191: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6192: 	my $current_locks = $current_permissions{$file};
 6193:         my @new_locks;
 6194:         my @del_keys;
 6195:         if (ref($current_locks) eq "ARRAY"){
 6196:             foreach my $locker (@{$current_locks}) {
 6197:                 my $compare=$locker;
 6198:                 if (ref($locker) eq 'ARRAY') {
 6199:                     $compare=join('',@{$locker});
 6200:                     if ($compare ne $symb_crs) {
 6201:                         push(@new_locks, $locker);
 6202:                     }
 6203:                 }
 6204:             }
 6205:             if (scalar(@new_locks) > 0) {
 6206:                 $current_permissions{$file} = \@new_locks;
 6207:             } else {
 6208:                 push(@del_keys, $file);
 6209:                 &del('file_permissions',\@del_keys, $domain, $user);
 6210:                 delete($current_permissions{$file});
 6211:             }
 6212:         }
 6213:     }
 6214:     &put('file_permissions',\%current_permissions,$domain,$user);
 6215:     return;
 6216: }
 6217: 
 6218: # ------------------------------------------------------------ Directory lister
 6219: 
 6220: sub dirlist {
 6221:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6222: 
 6223:     $uri=~s/^\///;
 6224:     $uri=~s/\/$//;
 6225:     my ($udom, $uname);
 6226:     (undef,$udom,$uname)=split(/\//,$uri);
 6227:     if(defined($userdomain)) {
 6228:         $udom = $userdomain;
 6229:     }
 6230:     if(defined($username)) {
 6231:         $uname = $username;
 6232:     }
 6233: 
 6234:     my $dirRoot = $perlvar{'lonDocRoot'};
 6235:     if(defined($alternateDirectoryRoot)) {
 6236:         $dirRoot = $alternateDirectoryRoot;
 6237:         $dirRoot =~ s/\/$//;
 6238:     }
 6239: 
 6240:     if($udom) {
 6241:         if($uname) {
 6242:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6243: 				 &homeserver($uname,$udom));
 6244:             my @listing_results;
 6245:             if ($listing eq 'unknown_cmd') {
 6246:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6247: 				  &homeserver($uname,$udom));
 6248:                 @listing_results = split(/:/,$listing);
 6249:             } else {
 6250:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6251:             }
 6252:             return @listing_results;
 6253:         } elsif(!defined($alternateDirectoryRoot)) {
 6254:             my %allusers;
 6255: 	    my %servers = &get_servers($udom,'library');
 6256: 	    foreach my $tryserver (keys(%servers)) {
 6257: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6258: 				     $udom, $tryserver);
 6259: 		my @listing_results;
 6260: 		if ($listing eq 'unknown_cmd') {
 6261: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6262: 				      $udom, $tryserver);
 6263: 		    @listing_results = split(/:/,$listing);
 6264: 		} else {
 6265: 		    @listing_results =
 6266: 			map { &unescape($_); } split(/:/,$listing);
 6267: 		}
 6268: 		if ($listing_results[0] ne 'no_such_dir' && 
 6269: 		    $listing_results[0] ne 'empty'       &&
 6270: 		    $listing_results[0] ne 'con_lost') {
 6271: 		    foreach my $line (@listing_results) {
 6272: 			my ($entry) = split(/&/,$line,2);
 6273: 			$allusers{$entry} = 1;
 6274: 		    }
 6275: 		}
 6276:             }
 6277:             my $alluserstr='';
 6278:             foreach my $user (sort(keys(%allusers))) {
 6279:                 $alluserstr.=$user.'&user:';
 6280:             }
 6281:             $alluserstr=~s/:$//;
 6282:             return split(/:/,$alluserstr);
 6283:         } else {
 6284:             return ('missing user name');
 6285:         }
 6286:     } elsif(!defined($alternateDirectoryRoot)) {
 6287:         my @all_domains = sort(&all_domains());
 6288:          foreach my $domain (@all_domains) {
 6289:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6290:          }
 6291:          return @all_domains;
 6292:      } else {
 6293:         return ('missing domain');
 6294:     }
 6295: }
 6296: 
 6297: # --------------------------------------------- GetFileTimestamp
 6298: # This function utilizes dirlist and returns the date stamp for
 6299: # when it was last modified.  It will also return an error of -1
 6300: # if an error occurs
 6301: 
 6302: ##
 6303: ## FIXME: This subroutine assumes its caller knows something about the
 6304: ## directory structure of the home server for the student ($root).
 6305: ## Not a good assumption to make.  Since this is for looking up files
 6306: ## in user directories, the full path should be constructed by lond, not
 6307: ## whatever machine we request data from.
 6308: ##
 6309: sub GetFileTimestamp {
 6310:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6311:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6312:     $studentName   = &LONCAPA::clean_username($studentName);
 6313:     my $subdir=$studentName.'__';
 6314:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6315:     my $proname="$studentDomain/$subdir/$studentName";
 6316:     $proname .= '/'.$filename;
 6317:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6318:                                               $studentName, $root);
 6319:     my @stats = split('&', $fileStat);
 6320:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6321:         # @stats contains first the filename, then the stat output
 6322:         return $stats[10]; # so this is 10 instead of 9.
 6323:     } else {
 6324:         return -1;
 6325:     }
 6326: }
 6327: 
 6328: sub stat_file {
 6329:     my ($uri) = @_;
 6330:     $uri = &clutter_with_no_wrapper($uri);
 6331: 
 6332:     my ($udom,$uname,$file,$dir);
 6333:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6334: 	($udom,$uname,$file) =
 6335: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6336: 	$file = 'userfiles/'.$file;
 6337: 	$dir = &propath($udom,$uname);
 6338:     }
 6339:     if ($uri =~ m-^/res/-) {
 6340: 	($udom,$uname) = 
 6341: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6342: 	$file = $uri;
 6343:     }
 6344: 
 6345:     if (!$udom || !$uname || !$file) {
 6346: 	# unable to handle the uri
 6347: 	return ();
 6348:     }
 6349: 
 6350:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6351:     my @stats = split('&', $result);
 6352:     
 6353:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6354: 	shift(@stats); #filename is first
 6355: 	return @stats;
 6356:     }
 6357:     return ();
 6358: }
 6359: 
 6360: # -------------------------------------------------------- Value of a Condition
 6361: 
 6362: # gets the value of a specific preevaluated condition
 6363: #    stored in the string  $env{user.state.<cid>}
 6364: # or looks up a condition reference in the bighash and if if hasn't
 6365: # already been evaluated recurses into docondval to get the value of
 6366: # the condition, then memoizing it to 
 6367: #   $env{user.state.<cid>.<condition>}
 6368: sub directcondval {
 6369:     my $number=shift;
 6370:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6371: 	&Apache::lonuserstate::evalstate();
 6372:     }
 6373:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6374: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6375:     } elsif ($number =~ /^_/) {
 6376: 	my $sub_condition;
 6377: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6378: 		&GDBM_READER(),0640)) {
 6379: 	    $sub_condition=$bighash{'conditions'.$number};
 6380: 	    untie(%bighash);
 6381: 	}
 6382: 	my $value = &docondval($sub_condition);
 6383: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6384: 	return $value;
 6385:     }
 6386:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6387:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6388:     } else {
 6389:        return 2;
 6390:     }
 6391: }
 6392: 
 6393: # get the collection of conditions for this resource
 6394: sub condval {
 6395:     my $condidx=shift;
 6396:     my $allpathcond='';
 6397:     foreach my $cond (split(/\|/,$condidx)) {
 6398: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6399: 	    $allpathcond.=
 6400: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6401: 	}
 6402:     }
 6403:     $allpathcond=~s/\|$//;
 6404:     return &docondval($allpathcond);
 6405: }
 6406: 
 6407: #evaluates an expression of conditions
 6408: sub docondval {
 6409:     my ($allpathcond) = @_;
 6410:     my $result=0;
 6411:     if ($env{'request.course.id'}
 6412: 	&& defined($allpathcond)) {
 6413: 	my $operand='|';
 6414: 	my @stack;
 6415: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6416: 	    if ($chunk eq '(') {
 6417: 		push @stack,($operand,$result);
 6418: 	    } elsif ($chunk eq ')') {
 6419: 		my $before=pop @stack;
 6420: 		if (pop @stack eq '&') {
 6421: 		    $result=$result>$before?$before:$result;
 6422: 		} else {
 6423: 		    $result=$result>$before?$result:$before;
 6424: 		}
 6425: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6426: 		$operand=$chunk;
 6427: 	    } else {
 6428: 		my $new=directcondval($chunk);
 6429: 		if ($operand eq '&') {
 6430: 		    $result=$result>$new?$new:$result;
 6431: 		} else {
 6432: 		    $result=$result>$new?$result:$new;
 6433: 		}
 6434: 	    }
 6435: 	}
 6436:     }
 6437:     return $result;
 6438: }
 6439: 
 6440: # ---------------------------------------------------- Devalidate courseresdata
 6441: 
 6442: sub devalidatecourseresdata {
 6443:     my ($coursenum,$coursedomain)=@_;
 6444:     my $hashid=$coursenum.':'.$coursedomain;
 6445:     &devalidate_cache_new('courseres',$hashid);
 6446: }
 6447: 
 6448: 
 6449: # --------------------------------------------------- Course Resourcedata Query
 6450: #
 6451: #  Parameters:
 6452: #      $coursenum    - Number of the course.
 6453: #      $coursedomain - Domain at which the course was created.
 6454: #  Returns:
 6455: #     A hash of the course parameters along (I think) with timestamps
 6456: #     and version info.
 6457: 
 6458: sub get_courseresdata {
 6459:     my ($coursenum,$coursedomain)=@_;
 6460:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6461:     my $hashid=$coursenum.':'.$coursedomain;
 6462:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6463:     my %dumpreply;
 6464:     unless (defined($cached)) {
 6465: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6466: 	$result=\%dumpreply;
 6467: 	my ($tmp) = keys(%dumpreply);
 6468: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6469: 	    &do_cache_new('courseres',$hashid,$result,600);
 6470: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6471: 	    return $tmp;
 6472: 	} elsif ($tmp =~ /^(error)/) {
 6473: 	    $result=undef;
 6474: 	    &do_cache_new('courseres',$hashid,$result,600);
 6475: 	}
 6476:     }
 6477:     return $result;
 6478: }
 6479: 
 6480: sub devalidateuserresdata {
 6481:     my ($uname,$udom)=@_;
 6482:     my $hashid="$udom:$uname";
 6483:     &devalidate_cache_new('userres',$hashid);
 6484: }
 6485: 
 6486: sub get_userresdata {
 6487:     my ($uname,$udom)=@_;
 6488:     #most student don\'t have any data set, check if there is some data
 6489:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6490: 
 6491:     my $hashid="$udom:$uname";
 6492:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6493:     if (!defined($cached)) {
 6494: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6495: 	$result=\%resourcedata;
 6496: 	&do_cache_new('userres',$hashid,$result,600);
 6497:     }
 6498:     my ($tmp)=keys(%$result);
 6499:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6500: 	return $result;
 6501:     }
 6502:     #error 2 occurs when the .db doesn't exist
 6503:     if ($tmp!~/error: 2 /) {
 6504: 	&logthis("<font color=\"blue\">WARNING:".
 6505: 		 " Trying to get resource data for ".
 6506: 		 $uname." at ".$udom.": ".
 6507: 		 $tmp."</font>");
 6508:     } elsif ($tmp=~/error: 2 /) {
 6509: 	#&EXT_cache_set($udom,$uname);
 6510: 	&do_cache_new('userres',$hashid,undef,600);
 6511: 	undef($tmp); # not really an error so don't send it back
 6512:     }
 6513:     return $tmp;
 6514: }
 6515: #----------------------------------------------- resdata - return resource data
 6516: #  Purpose:
 6517: #    Return resource data for either users or for a course.
 6518: #  Parameters:
 6519: #     $name      - Course/user name.
 6520: #     $domain    - Name of the domain the user/course is registered on.
 6521: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6522: #     @which     - Array of names of resources desired.
 6523: #  Returns:
 6524: #     The value of the first reasource in @which that is found in the
 6525: #     resource hash.
 6526: #  Exceptional Conditions:
 6527: #     If the $type passed in is not valid (not the string 'course' or 
 6528: #     'user', an undefined  reference is returned.
 6529: #     If none of the resources are found, an undef is returned
 6530: sub resdata {
 6531:     my ($name,$domain,$type,@which)=@_;
 6532:     my $result;
 6533:     if ($type eq 'course') {
 6534: 	$result=&get_courseresdata($name,$domain);
 6535:     } elsif ($type eq 'user') {
 6536: 	$result=&get_userresdata($name,$domain);
 6537:     }
 6538:     if (!ref($result)) { return $result; }    
 6539:     foreach my $item (@which) {
 6540: 	if (defined($result->{$item->[0]})) {
 6541: 	    return [$result->{$item->[0]},$item->[1]];
 6542: 	}
 6543:     }
 6544:     return undef;
 6545: }
 6546: 
 6547: #
 6548: # EXT resource caching routines
 6549: #
 6550: 
 6551: sub clear_EXT_cache_status {
 6552:     &delenv('cache.EXT.');
 6553: }
 6554: 
 6555: sub EXT_cache_status {
 6556:     my ($target_domain,$target_user) = @_;
 6557:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6558:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6559:         # We know already the user has no data
 6560:         return 1;
 6561:     } else {
 6562:         return 0;
 6563:     }
 6564: }
 6565: 
 6566: sub EXT_cache_set {
 6567:     my ($target_domain,$target_user) = @_;
 6568:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6569:     #&appenv({$cachename => time});
 6570: }
 6571: 
 6572: # --------------------------------------------------------- Value of a Variable
 6573: sub EXT {
 6574: 
 6575:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6576:     unless ($varname) { return ''; }
 6577:     #get real user name/domain, courseid and symb
 6578:     my $courseid;
 6579:     my $publicuser;
 6580:     if ($symbparm) {
 6581: 	$symbparm=&get_symb_from_alias($symbparm);
 6582:     }
 6583:     if (!($uname && $udom)) {
 6584:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6585:       if (!$symbparm) {	$symbparm=$cursymb; }
 6586:     } else {
 6587: 	$courseid=$env{'request.course.id'};
 6588:     }
 6589:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6590:     my $rest;
 6591:     if (defined($therest[0])) {
 6592:        $rest=join('.',@therest);
 6593:     } else {
 6594:        $rest='';
 6595:     }
 6596: 
 6597:     my $qualifierrest=$qualifier;
 6598:     if ($rest) { $qualifierrest.='.'.$rest; }
 6599:     my $spacequalifierrest=$space;
 6600:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6601:     if ($realm eq 'user') {
 6602: # --------------------------------------------------------------- user.resource
 6603: 	if ($space eq 'resource') {
 6604: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6605: 		  || defined($Apache::lonhomework::parsing_a_task))
 6606: 		 &&
 6607: 		 ($symbparm eq &symbread()) ) {	
 6608: 		# if we are in the middle of processing the resource the
 6609: 		# get the value we are planning on committing
 6610:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6611:                     return $Apache::lonhomework::results{$qualifierrest};
 6612:                 } else {
 6613:                     return $Apache::lonhomework::history{$qualifierrest};
 6614:                 }
 6615: 	    } else {
 6616: 		my %restored;
 6617: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6618: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6619: 		} else {
 6620: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6621: 		}
 6622: 		return $restored{$qualifierrest};
 6623: 	    }
 6624: # ----------------------------------------------------------------- user.access
 6625:         } elsif ($space eq 'access') {
 6626: 	    # FIXME - not supporting calls for a specific user
 6627:             return &allowed($qualifier,$rest);
 6628: # ------------------------------------------ user.preferences, user.environment
 6629:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6630: 	    if (($uname eq $env{'user.name'}) &&
 6631: 		($udom eq $env{'user.domain'})) {
 6632: 		return $env{join('.',('environment',$qualifierrest))};
 6633: 	    } else {
 6634: 		my %returnhash;
 6635: 		if (!$publicuser) {
 6636: 		    %returnhash=&userenvironment($udom,$uname,
 6637: 						 $qualifierrest);
 6638: 		}
 6639: 		return $returnhash{$qualifierrest};
 6640: 	    }
 6641: # ----------------------------------------------------------------- user.course
 6642:         } elsif ($space eq 'course') {
 6643: 	    # FIXME - not supporting calls for a specific user
 6644:             return $env{join('.',('request.course',$qualifier))};
 6645: # ------------------------------------------------------------------- user.role
 6646:         } elsif ($space eq 'role') {
 6647: 	    # FIXME - not supporting calls for a specific user
 6648:             my ($role,$where)=split(/\./,$env{'request.role'});
 6649:             if ($qualifier eq 'value') {
 6650: 		return $role;
 6651:             } elsif ($qualifier eq 'extent') {
 6652:                 return $where;
 6653:             }
 6654: # ----------------------------------------------------------------- user.domain
 6655:         } elsif ($space eq 'domain') {
 6656:             return $udom;
 6657: # ------------------------------------------------------------------- user.name
 6658:         } elsif ($space eq 'name') {
 6659:             return $uname;
 6660: # ---------------------------------------------------- Any other user namespace
 6661:         } else {
 6662: 	    my %reply;
 6663: 	    if (!$publicuser) {
 6664: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6665: 	    }
 6666: 	    return $reply{$qualifierrest};
 6667:         }
 6668:     } elsif ($realm eq 'query') {
 6669: # ---------------------------------------------- pull stuff out of query string
 6670:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6671: 						[$spacequalifierrest]);
 6672: 	return $env{'form.'.$spacequalifierrest}; 
 6673:    } elsif ($realm eq 'request') {
 6674: # ------------------------------------------------------------- request.browser
 6675:         if ($space eq 'browser') {
 6676: 	    if ($qualifier eq 'textremote') {
 6677: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6678: 		    return 1;
 6679: 		} else {
 6680: 		    return 0;
 6681: 		}
 6682: 	    } else {
 6683: 		return $env{'browser.'.$qualifier};
 6684: 	    }
 6685: # ------------------------------------------------------------ request.filename
 6686:         } else {
 6687:             return $env{'request.'.$spacequalifierrest};
 6688:         }
 6689:     } elsif ($realm eq 'course') {
 6690: # ---------------------------------------------------------- course.description
 6691:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6692:     } elsif ($realm eq 'resource') {
 6693: 
 6694: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6695: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6696: 	}
 6697: 
 6698: 	if ($space eq 'title') {
 6699: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6700: 	    return &gettitle($symbparm);
 6701: 	}
 6702: 	
 6703: 	if ($space eq 'map') {
 6704: 	    my ($map) = &decode_symb($symbparm);
 6705: 	    return &symbread($map);
 6706: 	}
 6707: 	if ($space eq 'filename') {
 6708: 	    if ($symbparm) {
 6709: 		return &clutter((&decode_symb($symbparm))[2]);
 6710: 	    }
 6711: 	    return &hreflocation('',$env{'request.filename'});
 6712: 	}
 6713: 
 6714: 	my ($section, $group, @groups);
 6715: 	my ($courselevelm,$courselevel);
 6716: 	if ($symbparm && defined($courseid) && 
 6717: 	    $courseid eq $env{'request.course.id'}) {
 6718: 
 6719: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6720: 
 6721: # ----------------------------------------------------- Cascading lookup scheme
 6722: 	    my $symbp=$symbparm;
 6723: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6724: 
 6725: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6726: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6727: 
 6728: 	    if (($env{'user.name'} eq $uname) &&
 6729: 		($env{'user.domain'} eq $udom)) {
 6730: 		$section=$env{'request.course.sec'};
 6731:                 @groups = split(/:/,$env{'request.course.groups'});  
 6732:                 @groups=&sort_course_groups($courseid,@groups); 
 6733: 	    } else {
 6734: 		if (! defined($usection)) {
 6735: 		    $section=&getsection($udom,$uname,$courseid);
 6736: 		} else {
 6737: 		    $section = $usection;
 6738: 		}
 6739:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6740: 	    }
 6741: 
 6742: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6743: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6744: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6745: 
 6746: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6747: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6748: 	    $courselevelm=$courseid.'.'.$mapparm;
 6749: 
 6750: # ----------------------------------------------------------- first, check user
 6751: 
 6752: 	    my $userreply=&resdata($uname,$udom,'user',
 6753: 				       ([$courselevelr,'resource'],
 6754: 					[$courselevelm,'map'     ],
 6755: 					[$courselevel, 'course'  ]));
 6756: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6757: 
 6758: # ------------------------------------------------ second, check some of course
 6759:             my $coursereply;
 6760:             if (@groups > 0) {
 6761:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6762:                                        $mapparm,$spacequalifierrest);
 6763:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6764:             }
 6765: 
 6766: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6767: 				  $env{'course.'.$courseid.'.domain'},
 6768: 				  'course',
 6769: 				  ([$seclevelr,   'resource'],
 6770: 				   [$seclevelm,   'map'     ],
 6771: 				   [$seclevel,    'course'  ],
 6772: 				   [$courselevelr,'resource']));
 6773: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6774: 
 6775: # ------------------------------------------------------ third, check map parms
 6776: 	    my %parmhash=();
 6777: 	    my $thisparm='';
 6778: 	    if (tie(%parmhash,'GDBM_File',
 6779: 		    $env{'request.course.fn'}.'_parms.db',
 6780: 		    &GDBM_READER(),0640)) {
 6781: 		$thisparm=$parmhash{$symbparm};
 6782: 		untie(%parmhash);
 6783: 	    }
 6784: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6785: 	}
 6786: # ------------------------------------------ fourth, look in resource metadata
 6787: 
 6788: 	$spacequalifierrest=~s/\./\_/;
 6789: 	my $filename;
 6790: 	if (!$symbparm) { $symbparm=&symbread(); }
 6791: 	if ($symbparm) {
 6792: 	    $filename=(&decode_symb($symbparm))[2];
 6793: 	} else {
 6794: 	    $filename=$env{'request.filename'};
 6795: 	}
 6796: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6797: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6798: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6799: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6800: 
 6801: # ---------------------------------------------- fourth, look in rest of course
 6802: 	if ($symbparm && defined($courseid) && 
 6803: 	    $courseid eq $env{'request.course.id'}) {
 6804: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6805: 				     $env{'course.'.$courseid.'.domain'},
 6806: 				     'course',
 6807: 				     ([$courselevelm,'map'   ],
 6808: 				      [$courselevel, 'course']));
 6809: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6810: 	}
 6811: # ------------------------------------------------------------------ Cascade up
 6812: 	unless ($space eq '0') {
 6813: 	    my @parts=split(/_/,$space);
 6814: 	    my $id=pop(@parts);
 6815: 	    my $part=join('_',@parts);
 6816: 	    if ($part eq '') { $part='0'; }
 6817: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6818: 				 $symbparm,$udom,$uname,$section,1);
 6819: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6820: 	}
 6821: 	if ($recurse) { return undef; }
 6822: 	my $pack_def=&packages_tab_default($filename,$varname);
 6823: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6824: # ---------------------------------------------------- Any other user namespace
 6825:     } elsif ($realm eq 'environment') {
 6826: # ----------------------------------------------------------------- environment
 6827: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6828: 	    return $env{'environment.'.$spacequalifierrest};
 6829: 	} else {
 6830: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6831: 		return '';
 6832: 	    }
 6833: 	    my %returnhash=&userenvironment($udom,$uname,
 6834: 					    $spacequalifierrest);
 6835: 	    return $returnhash{$spacequalifierrest};
 6836: 	}
 6837:     } elsif ($realm eq 'system') {
 6838: # ----------------------------------------------------------------- system.time
 6839: 	if ($space eq 'time') {
 6840: 	    return time;
 6841:         }
 6842:     } elsif ($realm eq 'server') {
 6843: # ----------------------------------------------------------------- system.time
 6844: 	if ($space eq 'name') {
 6845: 	    return $ENV{'SERVER_NAME'};
 6846:         }
 6847:     }
 6848:     return '';
 6849: }
 6850: 
 6851: sub get_reply {
 6852:     my ($reply_value) = @_;
 6853:     if (ref($reply_value) eq 'ARRAY') {
 6854:         if (wantarray) {
 6855: 	    return @$reply_value;
 6856:         }
 6857:         return $reply_value->[0];
 6858:     } else {
 6859:         return $reply_value;
 6860:     }
 6861: }
 6862: 
 6863: sub check_group_parms {
 6864:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6865:     my @groupitems = ();
 6866:     my $resultitem;
 6867:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6868:     foreach my $group (@{$groups}) {
 6869:         foreach my $level (@levels) {
 6870:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6871:              push(@groupitems,[$item,$level->[1]]);
 6872:         }
 6873:     }
 6874:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6875:                             $env{'course.'.$courseid.'.domain'},
 6876:                                      'course',@groupitems);
 6877:     return $coursereply;
 6878: }
 6879: 
 6880: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6881:     my ($courseid,@groups) = @_;
 6882:     @groups = sort(@groups);
 6883:     return @groups;
 6884: }
 6885: 
 6886: sub packages_tab_default {
 6887:     my ($uri,$varname)=@_;
 6888:     my (undef,$part,$name)=split(/\./,$varname);
 6889: 
 6890:     my (@extension,@specifics,$do_default);
 6891:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6892: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6893: 	if ($pack_type eq 'default') {
 6894: 	    $do_default=1;
 6895: 	} elsif ($pack_type eq 'extension') {
 6896: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6897: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6898: 	    # only look at packages defaults for packages that this id is
 6899: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6900: 	}
 6901:     }
 6902:     # first look for a package that matches the requested part id
 6903:     foreach my $package (@specifics) {
 6904: 	my (undef,$pack_type,$pack_part)=@{$package};
 6905: 	next if ($pack_part ne $part);
 6906: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6907: 	    return $packagetab{"$pack_type&$name&default"};
 6908: 	}
 6909:     }
 6910:     # look for any possible matching non extension_ package
 6911:     foreach my $package (@specifics) {
 6912: 	my (undef,$pack_type,$pack_part)=@{$package};
 6913: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6914: 	    return $packagetab{"$pack_type&$name&default"};
 6915: 	}
 6916: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6917: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6918: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6919: 	}
 6920:     }
 6921:     # look for any posible extension_ match
 6922:     foreach my $package (@extension) {
 6923: 	my ($package,$pack_type)=@{$package};
 6924: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6925: 	    return $packagetab{"$pack_type&$name&default"};
 6926: 	}
 6927: 	if (defined($packagetab{$package."&$name&default"})) {
 6928: 	    return $packagetab{$package."&$name&default"};
 6929: 	}
 6930:     }
 6931:     # look for a global default setting
 6932:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6933: 	return $packagetab{"default&$name&default"};
 6934:     }
 6935:     return undef;
 6936: }
 6937: 
 6938: sub add_prefix_and_part {
 6939:     my ($prefix,$part)=@_;
 6940:     my $keyroot;
 6941:     if (defined($prefix) && $prefix !~ /^__/) {
 6942: 	# prefix that has a part already
 6943: 	$keyroot=$prefix;
 6944:     } elsif (defined($prefix)) {
 6945: 	# prefix that is missing a part
 6946: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6947:     } else {
 6948: 	# no prefix at all
 6949: 	if (defined($part)) { $keyroot='_'.$part; }
 6950:     }
 6951:     return $keyroot;
 6952: }
 6953: 
 6954: # ---------------------------------------------------------------- Get metadata
 6955: 
 6956: my %metaentry;
 6957: sub metadata {
 6958:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6959:     $uri=&declutter($uri);
 6960:     # if it is a non metadata possible uri return quickly
 6961:     if (($uri eq '') || 
 6962: 	(($uri =~ m|^/*adm/|) && 
 6963: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6964:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6965: 	return undef;
 6966:     }
 6967:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6968: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6969: 	return undef;
 6970:     }
 6971:     my $filename=$uri;
 6972:     $uri=~s/\.meta$//;
 6973: #
 6974: # Is the metadata already cached?
 6975: # Look at timestamp of caching
 6976: # Everything is cached by the main uri, libraries are never directly cached
 6977: #
 6978:     if (!defined($liburi)) {
 6979: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6980: 	if (defined($cached)) { return $result->{':'.$what}; }
 6981:     }
 6982:     {
 6983: #
 6984: # Is this a recursive call for a library?
 6985: #
 6986: #	if (! exists($metacache{$uri})) {
 6987: #	    $metacache{$uri}={};
 6988: #	}
 6989: 	my $cachetime = 60*60;
 6990:         if ($liburi) {
 6991: 	    $liburi=&declutter($liburi);
 6992:             $filename=$liburi;
 6993:         } else {
 6994: 	    &devalidate_cache_new('meta',$uri);
 6995: 	    undef(%metaentry);
 6996: 	}
 6997:         my %metathesekeys=();
 6998:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6999: 	my $metastring;
 7000: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7001: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7002: 	    $metastring = 
 7003: 		&Apache::lonnet::ssi_body($which,
 7004: 					  ('grade_target' => 'meta'));
 7005: 	    $cachetime = 1; # only want this cached in the child not long term
 7006: 	} elsif ($uri !~ m -^(editupload)/-) {
 7007: 	    my $file=&filelocation('',&clutter($filename));
 7008: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7009: 	    $metastring=&getfile($file);
 7010: 	}
 7011:         my $parser=HTML::LCParser->new(\$metastring);
 7012:         my $token;
 7013:         undef %metathesekeys;
 7014:         while ($token=$parser->get_token) {
 7015: 	    if ($token->[0] eq 'S') {
 7016: 		if (defined($token->[2]->{'package'})) {
 7017: #
 7018: # This is a package - get package info
 7019: #
 7020: 		    my $package=$token->[2]->{'package'};
 7021: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7022: 		    if (defined($token->[2]->{'id'})) { 
 7023: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7024: 		    }
 7025: 		    if ($metaentry{':packages'}) {
 7026: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7027: 		    } else {
 7028: 			$metaentry{':packages'}=$package.$keyroot;
 7029: 		    }
 7030: 		    foreach my $pack_entry (keys(%packagetab)) {
 7031: 			my $part=$keyroot;
 7032: 			$part=~s/^\_//;
 7033: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7034: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7035: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7036: 			    # ignore package.tab specified default values
 7037:                             # here &package_tab_default() will fetch those
 7038: 			    if ($subp eq 'default') { next; }
 7039: 			    my $value=$packagetab{$pack_entry};
 7040: 			    my $unikey;
 7041: 			    if ($pack =~ /_0$/) {
 7042: 				$unikey='parameter_0_'.$name;
 7043: 				$part=0;
 7044: 			    } else {
 7045: 				$unikey='parameter'.$keyroot.'_'.$name;
 7046: 			    }
 7047: 			    if ($subp eq 'display') {
 7048: 				$value.=' [Part: '.$part.']';
 7049: 			    }
 7050: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7051: 			    $metathesekeys{$unikey}=1;
 7052: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7053: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7054: 			    }
 7055: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7056: 				$metaentry{':'.$unikey}=
 7057: 				    $metaentry{':'.$unikey.'.default'};
 7058: 			    }
 7059: 			}
 7060: 		    }
 7061: 		} else {
 7062: #
 7063: # This is not a package - some other kind of start tag
 7064: #
 7065: 		    my $entry=$token->[1];
 7066: 		    my $unikey;
 7067: 		    if ($entry eq 'import') {
 7068: 			$unikey='';
 7069: 		    } else {
 7070: 			$unikey=$entry;
 7071: 		    }
 7072: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7073: 
 7074: 		    if (defined($token->[2]->{'id'})) { 
 7075: 			$unikey.='_'.$token->[2]->{'id'}; 
 7076: 		    }
 7077: 
 7078: 		    if ($entry eq 'import') {
 7079: #
 7080: # Importing a library here
 7081: #
 7082: 			if ($depthcount<20) {
 7083: 			    my $location=$parser->get_text('/import');
 7084: 			    my $dir=$filename;
 7085: 			    $dir=~s|[^/]*$||;
 7086: 			    $location=&filelocation($dir,$location);
 7087: 			    my $metadata = 
 7088: 				&metadata($uri,'keys', $location,$unikey,
 7089: 					  $depthcount+1);
 7090: 			    foreach my $meta (split(',',$metadata)) {
 7091: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7092: 				$metathesekeys{$meta}=1;
 7093: 			    }
 7094: 			}
 7095: 		    } else { 
 7096: 			
 7097: 			if (defined($token->[2]->{'name'})) { 
 7098: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7099: 			}
 7100: 			$metathesekeys{$unikey}=1;
 7101: 			foreach my $param (@{$token->[3]}) {
 7102: 			    $metaentry{':'.$unikey.'.'.$param} =
 7103: 				$token->[2]->{$param};
 7104: 			}
 7105: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7106: 			my $default=$metaentry{':'.$unikey.'.default'};
 7107: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7108: 		 # only ws inside the tag, and not in default, so use default
 7109: 		 # as value
 7110: 			    $metaentry{':'.$unikey}=$default;
 7111: 			} elsif ( $internaltext =~ /\S/ ) {
 7112: 		  # something interesting inside the tag
 7113: 			    $metaentry{':'.$unikey}=$internaltext;
 7114: 			} else {
 7115: 		  # no interesting values, don't set a default
 7116: 			}
 7117: # end of not-a-package not-a-library import
 7118: 		    }
 7119: # end of not-a-package start tag
 7120: 		}
 7121: # the next is the end of "start tag"
 7122: 	    }
 7123: 	}
 7124: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7125: 	$extension = lc($extension);
 7126: 	if ($extension eq 'htm') { $extension='html'; }
 7127: 
 7128: 	foreach my $key (keys(%packagetab)) {
 7129: 	    #no specific packages #how's our extension
 7130: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7131: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7132: 					 \%metathesekeys);
 7133: 	}
 7134: 
 7135: 	if (!exists($metaentry{':packages'})
 7136: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7137: 	    foreach my $key (keys(%packagetab)) {
 7138: 		#no specific packages well let's get default then
 7139: 		if ($key!~/^default&/) { next; }
 7140: 		&metadata_create_package_def($uri,$key,'default',
 7141: 					     \%metathesekeys);
 7142: 	    }
 7143: 	}
 7144: # are there custom rights to evaluate
 7145: 	if ($metaentry{':copyright'} eq 'custom') {
 7146: 
 7147:     #
 7148:     # Importing a rights file here
 7149:     #
 7150: 	    unless ($depthcount) {
 7151: 		my $location=$metaentry{':customdistributionfile'};
 7152: 		my $dir=$filename;
 7153: 		$dir=~s|[^/]*$||;
 7154: 		$location=&filelocation($dir,$location);
 7155: 		my $rights_metadata =
 7156: 		    &metadata($uri,'keys',$location,'_rights',
 7157: 			      $depthcount+1);
 7158: 		foreach my $rights (split(',',$rights_metadata)) {
 7159: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7160: 		    $metathesekeys{$rights}=1;
 7161: 		}
 7162: 	    }
 7163: 	}
 7164: 	# uniqifiy package listing
 7165: 	my %seen;
 7166: 	my @uniq_packages =
 7167: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7168: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7169: 
 7170: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7171: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7172: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7173: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7174: # this is the end of "was not already recently cached
 7175:     }
 7176:     return $metaentry{':'.$what};
 7177: }
 7178: 
 7179: sub metadata_create_package_def {
 7180:     my ($uri,$key,$package,$metathesekeys)=@_;
 7181:     my ($pack,$name,$subp)=split(/\&/,$key);
 7182:     if ($subp eq 'default') { next; }
 7183:     
 7184:     if (defined($metaentry{':packages'})) {
 7185: 	$metaentry{':packages'}.=','.$package;
 7186:     } else {
 7187: 	$metaentry{':packages'}=$package;
 7188:     }
 7189:     my $value=$packagetab{$key};
 7190:     my $unikey;
 7191:     $unikey='parameter_0_'.$name;
 7192:     $metaentry{':'.$unikey.'.part'}=0;
 7193:     $$metathesekeys{$unikey}=1;
 7194:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7195: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7196:     }
 7197:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7198: 	$metaentry{':'.$unikey}=
 7199: 	    $metaentry{':'.$unikey.'.default'};
 7200:     }
 7201: }
 7202: 
 7203: sub metadata_generate_part0 {
 7204:     my ($metadata,$metacache,$uri) = @_;
 7205:     my %allnames;
 7206:     foreach my $metakey (keys(%$metadata)) {
 7207: 	if ($metakey=~/^parameter\_(.*)/) {
 7208: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7209: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7210: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7211: 	    $allnames{$name}=$part;
 7212: 	  }
 7213: 	}
 7214:     }
 7215:     foreach my $name (keys(%allnames)) {
 7216:       $$metadata{"parameter_0_$name"}=1;
 7217:       my $key=":parameter_0_$name";
 7218:       $$metacache{"$key.part"}='0';
 7219:       $$metacache{"$key.name"}=$name;
 7220:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7221: 					   $allnames{$name}.'_'.$name.
 7222: 					   '.type'};
 7223:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7224: 			     '.display'};
 7225:       my $expr='[Part: '.$allnames{$name}.']';
 7226:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7227:       $$metacache{"$key.display"}=$olddis;
 7228:     }
 7229: }
 7230: 
 7231: # ------------------------------------------------------ Devalidate title cache
 7232: 
 7233: sub devalidate_title_cache {
 7234:     my ($url)=@_;
 7235:     if (!$env{'request.course.id'}) { return; }
 7236:     my $symb=&symbread($url);
 7237:     if (!$symb) { return; }
 7238:     my $key=$env{'request.course.id'}."\0".$symb;
 7239:     &devalidate_cache_new('title',$key);
 7240: }
 7241: 
 7242: # ------------------------------------------------- Get the title of a resource
 7243: 
 7244: sub gettitle {
 7245:     my $urlsymb=shift;
 7246:     my $symb=&symbread($urlsymb);
 7247:     if ($symb) {
 7248: 	my $key=$env{'request.course.id'}."\0".$symb;
 7249: 	my ($result,$cached)=&is_cached_new('title',$key);
 7250: 	if (defined($cached)) { 
 7251: 	    return $result;
 7252: 	}
 7253: 	my ($map,$resid,$url)=&decode_symb($symb);
 7254: 	my $title='';
 7255: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7256: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7257: 	} else {
 7258: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7259: 		    &GDBM_READER(),0640)) {
 7260: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7261: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7262: 		untie(%bighash);
 7263: 	    }
 7264: 	}
 7265: 	$title=~s/\&colon\;/\:/gs;
 7266: 	if ($title) {
 7267: 	    return &do_cache_new('title',$key,$title,600);
 7268: 	}
 7269: 	$urlsymb=$url;
 7270:     }
 7271:     my $title=&metadata($urlsymb,'title');
 7272:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7273:     return $title;
 7274: }
 7275: 
 7276: sub get_slot {
 7277:     my ($which,$cnum,$cdom)=@_;
 7278:     if (!$cnum || !$cdom) {
 7279: 	(undef,my $courseid)=&whichuser();
 7280: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7281: 	$cnum=$env{'course.'.$courseid.'.num'};
 7282:     }
 7283:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7284:     my %slotinfo;
 7285:     if (exists($remembered{$key})) {
 7286: 	$slotinfo{$which} = $remembered{$key};
 7287:     } else {
 7288: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7289: 	&Apache::lonhomework::showhash(%slotinfo);
 7290: 	my ($tmp)=keys(%slotinfo);
 7291: 	if ($tmp=~/^error:/) { return (); }
 7292: 	$remembered{$key} = $slotinfo{$which};
 7293:     }
 7294:     if (ref($slotinfo{$which}) eq 'HASH') {
 7295: 	return %{$slotinfo{$which}};
 7296:     }
 7297:     return $slotinfo{$which};
 7298: }
 7299: # ------------------------------------------------- Update symbolic store links
 7300: 
 7301: sub symblist {
 7302:     my ($mapname,%newhash)=@_;
 7303:     $mapname=&deversion(&declutter($mapname));
 7304:     my %hash;
 7305:     if (($env{'request.course.fn'}) && (%newhash)) {
 7306:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7307:                       &GDBM_WRCREAT(),0640)) {
 7308: 	    foreach my $url (keys %newhash) {
 7309: 		next if ($url eq 'last_known'
 7310: 			 && $env{'form.no_update_last_known'});
 7311: 		$hash{declutter($url)}=&encode_symb($mapname,
 7312: 						    $newhash{$url}->[1],
 7313: 						    $newhash{$url}->[0]);
 7314:             }
 7315:             if (untie(%hash)) {
 7316: 		return 'ok';
 7317:             }
 7318:         }
 7319:     }
 7320:     return 'error';
 7321: }
 7322: 
 7323: # --------------------------------------------------------------- Verify a symb
 7324: 
 7325: sub symbverify {
 7326:     my ($symb,$thisurl)=@_;
 7327:     my $thisfn=$thisurl;
 7328:     $thisfn=&declutter($thisfn);
 7329: # direct jump to resource in page or to a sequence - will construct own symbs
 7330:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7331: # check URL part
 7332:     my ($map,$resid,$url)=&decode_symb($symb);
 7333: 
 7334:     unless ($url eq $thisfn) { return 0; }
 7335: 
 7336:     $symb=&symbclean($symb);
 7337:     $thisurl=&deversion($thisurl);
 7338:     $thisfn=&deversion($thisfn);
 7339: 
 7340:     my %bighash;
 7341:     my $okay=0;
 7342: 
 7343:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7344:                             &GDBM_READER(),0640)) {
 7345:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7346:         unless ($ids) { 
 7347:            $ids=$bighash{'ids_/'.$thisurl};
 7348:         }
 7349:         if ($ids) {
 7350: # ------------------------------------------------------------------- Has ID(s)
 7351: 	    foreach my $id (split(/\,/,$ids)) {
 7352: 	       my ($mapid,$resid)=split(/\./,$id);
 7353:                if (
 7354:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7355:    eq $symb) { 
 7356: 		   if (($env{'request.role.adv'}) ||
 7357: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7358: 		       $okay=1; 
 7359: 		   }
 7360: 	       }
 7361: 	   }
 7362:         }
 7363: 	untie(%bighash);
 7364:     }
 7365:     return $okay;
 7366: }
 7367: 
 7368: # --------------------------------------------------------------- Clean-up symb
 7369: 
 7370: sub symbclean {
 7371:     my $symb=shift;
 7372:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7373: # remove version from map
 7374:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7375: 
 7376: # remove version from URL
 7377:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7378: 
 7379: # remove wrapper
 7380: 
 7381:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7382:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7383:     return $symb;
 7384: }
 7385: 
 7386: # ---------------------------------------------- Split symb to find map and url
 7387: 
 7388: sub encode_symb {
 7389:     my ($map,$resid,$url)=@_;
 7390:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7391: }
 7392: 
 7393: sub decode_symb {
 7394:     my $symb=shift;
 7395:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7396:     my ($map,$resid,$url)=split(/___/,$symb);
 7397:     return (&fixversion($map),$resid,&fixversion($url));
 7398: }
 7399: 
 7400: sub fixversion {
 7401:     my $fn=shift;
 7402:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7403:     my %bighash;
 7404:     my $uri=&clutter($fn);
 7405:     my $key=$env{'request.course.id'}.'_'.$uri;
 7406: # is this cached?
 7407:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7408:     if (defined($cached)) { return $result; }
 7409: # unfortunately not cached, or expired
 7410:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7411: 	    &GDBM_READER(),0640)) {
 7412:  	if ($bighash{'version_'.$uri}) {
 7413:  	    my $version=$bighash{'version_'.$uri};
 7414:  	    unless (($version eq 'mostrecent') || 
 7415: 		    ($version==&getversion($uri))) {
 7416:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7417:  	    }
 7418:  	}
 7419:  	untie %bighash;
 7420:     }
 7421:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7422: }
 7423: 
 7424: sub deversion {
 7425:     my $url=shift;
 7426:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7427:     return $url;
 7428: }
 7429: 
 7430: # ------------------------------------------------------ Return symb list entry
 7431: 
 7432: sub symbread {
 7433:     my ($thisfn,$donotrecurse)=@_;
 7434:     my $cache_str='request.symbread.cached.'.$thisfn;
 7435:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7436: # no filename provided? try from environment
 7437:     unless ($thisfn) {
 7438:         if ($env{'request.symb'}) {
 7439: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7440: 	}
 7441: 	$thisfn=$env{'request.filename'};
 7442:     }
 7443:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7444: # is that filename actually a symb? Verify, clean, and return
 7445:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7446: 	if (&symbverify($thisfn,$1)) {
 7447: 	    return $env{$cache_str}=&symbclean($thisfn);
 7448: 	}
 7449:     }
 7450:     $thisfn=declutter($thisfn);
 7451:     my %hash;
 7452:     my %bighash;
 7453:     my $syval='';
 7454:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7455:         my $targetfn = $thisfn;
 7456:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7457:             $targetfn = 'adm/wrapper/'.$thisfn;
 7458:         }
 7459: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7460: 	    $targetfn=$1;
 7461: 	}
 7462:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7463:                       &GDBM_READER(),0640)) {
 7464: 	    $syval=$hash{$targetfn};
 7465:             untie(%hash);
 7466:         }
 7467: # ---------------------------------------------------------- There was an entry
 7468:         if ($syval) {
 7469: 	    #unless ($syval=~/\_\d+$/) {
 7470: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7471: 		    #&appenv({'request.ambiguous' => $thisfn});
 7472: 		    #return $env{$cache_str}='';
 7473: 		#}    
 7474: 		#$syval.=$1;
 7475: 	    #}
 7476:         } else {
 7477: # ------------------------------------------------------- Was not in symb table
 7478:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7479:                             &GDBM_READER(),0640)) {
 7480: # ---------------------------------------------- Get ID(s) for current resource
 7481:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7482:               unless ($ids) { 
 7483:                  $ids=$bighash{'ids_/'.$thisfn};
 7484:               }
 7485:               unless ($ids) {
 7486: # alias?
 7487: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7488:               }
 7489:               if ($ids) {
 7490: # ------------------------------------------------------------------- Has ID(s)
 7491:                  my @possibilities=split(/\,/,$ids);
 7492:                  if ($#possibilities==0) {
 7493: # ----------------------------------------------- There is only one possibility
 7494: 		     my ($mapid,$resid)=split(/\./,$ids);
 7495: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7496: 						    $resid,$thisfn);
 7497:                  } elsif (!$donotrecurse) {
 7498: # ------------------------------------------ There is more than one possibility
 7499:                      my $realpossible=0;
 7500:                      foreach my $id (@possibilities) {
 7501: 			 my $file=$bighash{'src_'.$id};
 7502:                          if (&allowed('bre',$file)) {
 7503:          		    my ($mapid,$resid)=split(/\./,$id);
 7504:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7505: 				$realpossible++;
 7506:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7507: 						    $resid,$thisfn);
 7508:                             }
 7509: 			 }
 7510:                      }
 7511: 		     if ($realpossible!=1) { $syval=''; }
 7512:                  } else {
 7513:                      $syval='';
 7514:                  }
 7515: 	      }
 7516:               untie(%bighash)
 7517:            }
 7518:         }
 7519:         if ($syval) {
 7520: 	    return $env{$cache_str}=$syval;
 7521:         }
 7522:     }
 7523:     &appenv({'request.ambiguous' => $thisfn});
 7524:     return $env{$cache_str}='';
 7525: }
 7526: 
 7527: # ---------------------------------------------------------- Return random seed
 7528: 
 7529: sub numval {
 7530:     my $txt=shift;
 7531:     $txt=~tr/A-J/0-9/;
 7532:     $txt=~tr/a-j/0-9/;
 7533:     $txt=~tr/K-T/0-9/;
 7534:     $txt=~tr/k-t/0-9/;
 7535:     $txt=~tr/U-Z/0-5/;
 7536:     $txt=~tr/u-z/0-5/;
 7537:     $txt=~s/\D//g;
 7538:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7539:     return int($txt);
 7540: }
 7541: 
 7542: sub numval2 {
 7543:     my $txt=shift;
 7544:     $txt=~tr/A-J/0-9/;
 7545:     $txt=~tr/a-j/0-9/;
 7546:     $txt=~tr/K-T/0-9/;
 7547:     $txt=~tr/k-t/0-9/;
 7548:     $txt=~tr/U-Z/0-5/;
 7549:     $txt=~tr/u-z/0-5/;
 7550:     $txt=~s/\D//g;
 7551:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7552:     my $total;
 7553:     foreach my $val (@txts) { $total+=$val; }
 7554:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7555:     return int($total);
 7556: }
 7557: 
 7558: sub numval3 {
 7559:     use integer;
 7560:     my $txt=shift;
 7561:     $txt=~tr/A-J/0-9/;
 7562:     $txt=~tr/a-j/0-9/;
 7563:     $txt=~tr/K-T/0-9/;
 7564:     $txt=~tr/k-t/0-9/;
 7565:     $txt=~tr/U-Z/0-5/;
 7566:     $txt=~tr/u-z/0-5/;
 7567:     $txt=~s/\D//g;
 7568:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7569:     my $total;
 7570:     foreach my $val (@txts) { $total+=$val; }
 7571:     if ($_64bit) { $total=(($total<<32)>>32); }
 7572:     return $total;
 7573: }
 7574: 
 7575: sub digest {
 7576:     my ($data)=@_;
 7577:     my $digest=&Digest::MD5::md5($data);
 7578:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7579:     my ($e,$f);
 7580:     {
 7581:         use integer;
 7582:         $e=($a+$b);
 7583:         $f=($c+$d);
 7584:         if ($_64bit) {
 7585:             $e=(($e<<32)>>32);
 7586:             $f=(($f<<32)>>32);
 7587:         }
 7588:     }
 7589:     if (wantarray) {
 7590: 	return ($e,$f);
 7591:     } else {
 7592: 	my $g;
 7593: 	{
 7594: 	    use integer;
 7595: 	    $g=($e+$f);
 7596: 	    if ($_64bit) {
 7597: 		$g=(($g<<32)>>32);
 7598: 	    }
 7599: 	}
 7600: 	return $g;
 7601:     }
 7602: }
 7603: 
 7604: sub latest_rnd_algorithm_id {
 7605:     return '64bit5';
 7606: }
 7607: 
 7608: sub get_rand_alg {
 7609:     my ($courseid)=@_;
 7610:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7611:     if ($courseid) {
 7612: 	return $env{"course.$courseid.rndseed"};
 7613:     }
 7614:     return &latest_rnd_algorithm_id();
 7615: }
 7616: 
 7617: sub validCODE {
 7618:     my ($CODE)=@_;
 7619:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7620:     return 0;
 7621: }
 7622: 
 7623: sub getCODE {
 7624:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7625:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7626: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7627: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7628: 	return $Apache::lonhomework::history{'resource.CODE'};
 7629:     }
 7630:     return undef;
 7631: }
 7632: 
 7633: sub rndseed {
 7634:     my ($symb,$courseid,$domain,$username)=@_;
 7635:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7636:     if (!defined($symb)) {
 7637: 	unless ($symb=$wsymb) { return time; }
 7638:     }
 7639:     if (!$courseid) { $courseid=$wcourseid; }
 7640:     if (!$domain) { $domain=$wdomain; }
 7641:     if (!$username) { $username=$wusername }
 7642:     my $which=&get_rand_alg();
 7643: 
 7644:     if (defined(&getCODE())) {
 7645: 	if ($which eq '64bit5') {
 7646: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7647: 	} elsif ($which eq '64bit4') {
 7648: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7649: 	} else {
 7650: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7651: 	}
 7652:     } elsif ($which eq '64bit5') {
 7653: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7654:     } elsif ($which eq '64bit4') {
 7655: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7656:     } elsif ($which eq '64bit3') {
 7657: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7658:     } elsif ($which eq '64bit2') {
 7659: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7660:     } elsif ($which eq '64bit') {
 7661: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7662:     }
 7663:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7664: }
 7665: 
 7666: sub rndseed_32bit {
 7667:     my ($symb,$courseid,$domain,$username)=@_;
 7668:     {
 7669: 	use integer;
 7670: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7671: 	my $symbseed=numval($symb) << 22;
 7672: 	my $namechck=unpack("%32C*",$username) << 17;
 7673: 	my $nameseed=numval($username) << 12;
 7674: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7675: 	my $courseseed=unpack("%32C*",$courseid);
 7676: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7677: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7678: 	#&logthis("rndseed :$num:$symb");
 7679: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7680: 	return $num;
 7681:     }
 7682: }
 7683: 
 7684: sub rndseed_64bit {
 7685:     my ($symb,$courseid,$domain,$username)=@_;
 7686:     {
 7687: 	use integer;
 7688: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7689: 	my $symbseed=numval($symb) << 10;
 7690: 	my $namechck=unpack("%32S*",$username);
 7691: 	
 7692: 	my $nameseed=numval($username) << 21;
 7693: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7694: 	my $courseseed=unpack("%32S*",$courseid);
 7695: 	
 7696: 	my $num1=$symbchck+$symbseed+$namechck;
 7697: 	my $num2=$nameseed+$domainseed+$courseseed;
 7698: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7699: 	#&logthis("rndseed :$num:$symb");
 7700: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7701: 	return "$num1,$num2";
 7702:     }
 7703: }
 7704: 
 7705: sub rndseed_64bit2 {
 7706:     my ($symb,$courseid,$domain,$username)=@_;
 7707:     {
 7708: 	use integer;
 7709: 	# strings need to be an even # of cahracters long, it it is odd the
 7710:         # last characters gets thrown away
 7711: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7712: 	my $symbseed=numval($symb) << 10;
 7713: 	my $namechck=unpack("%32S*",$username.' ');
 7714: 	
 7715: 	my $nameseed=numval($username) << 21;
 7716: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7717: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7718: 	
 7719: 	my $num1=$symbchck+$symbseed+$namechck;
 7720: 	my $num2=$nameseed+$domainseed+$courseseed;
 7721: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7722: 	#&logthis("rndseed :$num:$symb");
 7723: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7724: 	return "$num1,$num2";
 7725:     }
 7726: }
 7727: 
 7728: sub rndseed_64bit3 {
 7729:     my ($symb,$courseid,$domain,$username)=@_;
 7730:     {
 7731: 	use integer;
 7732: 	# strings need to be an even # of cahracters long, it it is odd the
 7733:         # last characters gets thrown away
 7734: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7735: 	my $symbseed=numval2($symb) << 10;
 7736: 	my $namechck=unpack("%32S*",$username.' ');
 7737: 	
 7738: 	my $nameseed=numval2($username) << 21;
 7739: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7740: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7741: 	
 7742: 	my $num1=$symbchck+$symbseed+$namechck;
 7743: 	my $num2=$nameseed+$domainseed+$courseseed;
 7744: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7745: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7746: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7747: 	
 7748: 	return "$num1:$num2";
 7749:     }
 7750: }
 7751: 
 7752: sub rndseed_64bit4 {
 7753:     my ($symb,$courseid,$domain,$username)=@_;
 7754:     {
 7755: 	use integer;
 7756: 	# strings need to be an even # of cahracters long, it it is odd the
 7757:         # last characters gets thrown away
 7758: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7759: 	my $symbseed=numval3($symb) << 10;
 7760: 	my $namechck=unpack("%32S*",$username.' ');
 7761: 	
 7762: 	my $nameseed=numval3($username) << 21;
 7763: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7764: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7765: 	
 7766: 	my $num1=$symbchck+$symbseed+$namechck;
 7767: 	my $num2=$nameseed+$domainseed+$courseseed;
 7768: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7769: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7770: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7771: 	
 7772: 	return "$num1:$num2";
 7773:     }
 7774: }
 7775: 
 7776: sub rndseed_64bit5 {
 7777:     my ($symb,$courseid,$domain,$username)=@_;
 7778:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7779:     return "$num1:$num2";
 7780: }
 7781: 
 7782: sub rndseed_CODE_64bit {
 7783:     my ($symb,$courseid,$domain,$username)=@_;
 7784:     {
 7785: 	use integer;
 7786: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7787: 	my $symbseed=numval2($symb);
 7788: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7789: 	my $CODEseed=numval(&getCODE());
 7790: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7791: 	my $num1=$symbseed+$CODEchck;
 7792: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7793: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7794: 	#&logthis("rndseed :$num1:$num2:$symb");
 7795: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7796: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7797: 	return "$num1:$num2";
 7798:     }
 7799: }
 7800: 
 7801: sub rndseed_CODE_64bit4 {
 7802:     my ($symb,$courseid,$domain,$username)=@_;
 7803:     {
 7804: 	use integer;
 7805: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7806: 	my $symbseed=numval3($symb);
 7807: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7808: 	my $CODEseed=numval3(&getCODE());
 7809: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7810: 	my $num1=$symbseed+$CODEchck;
 7811: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7812: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7813: 	#&logthis("rndseed :$num1:$num2:$symb");
 7814: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7815: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7816: 	return "$num1:$num2";
 7817:     }
 7818: }
 7819: 
 7820: sub rndseed_CODE_64bit5 {
 7821:     my ($symb,$courseid,$domain,$username)=@_;
 7822:     my $code = &getCODE();
 7823:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7824:     return "$num1:$num2";
 7825: }
 7826: 
 7827: sub setup_random_from_rndseed {
 7828:     my ($rndseed)=@_;
 7829:     if ($rndseed =~/([,:])/) {
 7830: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7831: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7832:     } else {
 7833: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7834:     }
 7835: }
 7836: 
 7837: sub latest_receipt_algorithm_id {
 7838:     return 'receipt3';
 7839: }
 7840: 
 7841: sub recunique {
 7842:     my $fucourseid=shift;
 7843:     my $unique;
 7844:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7845: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7846: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7847:     } else {
 7848: 	$unique=$perlvar{'lonReceipt'};
 7849:     }
 7850:     return unpack("%32C*",$unique);
 7851: }
 7852: 
 7853: sub recprefix {
 7854:     my $fucourseid=shift;
 7855:     my $prefix;
 7856:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7857: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7858: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7859:     } else {
 7860: 	$prefix=$perlvar{'lonHostID'};
 7861:     }
 7862:     return unpack("%32C*",$prefix);
 7863: }
 7864: 
 7865: sub ireceipt {
 7866:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7867: 
 7868:     my $return =&recprefix($fucourseid).'-';
 7869: 
 7870:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7871: 	$env{'request.state'} eq 'construct') {
 7872: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7873: 	return $return;
 7874:     }
 7875: 
 7876:     my $cuname=unpack("%32C*",$funame);
 7877:     my $cudom=unpack("%32C*",$fudom);
 7878:     my $cucourseid=unpack("%32C*",$fucourseid);
 7879:     my $cusymb=unpack("%32C*",$fusymb);
 7880:     my $cunique=&recunique($fucourseid);
 7881:     my $cpart=unpack("%32S*",$part);
 7882:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7883: 
 7884: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7885: 			       
 7886: 	$return.= ($cunique%$cuname+
 7887: 		   $cunique%$cudom+
 7888: 		   $cusymb%$cuname+
 7889: 		   $cusymb%$cudom+
 7890: 		   $cucourseid%$cuname+
 7891: 		   $cucourseid%$cudom+
 7892: 		   $cpart%$cuname+
 7893: 		   $cpart%$cudom);
 7894:     } else {
 7895: 	$return.= ($cunique%$cuname+
 7896: 		   $cunique%$cudom+
 7897: 		   $cusymb%$cuname+
 7898: 		   $cusymb%$cudom+
 7899: 		   $cucourseid%$cuname+
 7900: 		   $cucourseid%$cudom);
 7901:     }
 7902:     return $return;
 7903: }
 7904: 
 7905: sub receipt {
 7906:     my ($part)=@_;
 7907:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7908:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7909: }
 7910: 
 7911: sub whichuser {
 7912:     my ($passedsymb)=@_;
 7913:     my ($symb,$courseid,$domain,$name,$publicuser);
 7914:     if (defined($env{'form.grade_symb'})) {
 7915: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7916: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7917: 	if (!$allowed &&
 7918: 	    exists($env{'request.course.sec'}) &&
 7919: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7920: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7921: 			      '/'.$env{'request.course.sec'});
 7922: 	}
 7923: 	if ($allowed) {
 7924: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7925: 	    $courseid=$tmp_courseid;
 7926: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7927: 	    ($name)=&get_env_multiple('form.grade_username');
 7928: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7929: 	}
 7930:     }
 7931:     if (!$passedsymb) {
 7932: 	$symb=&symbread();
 7933:     } else {
 7934: 	$symb=$passedsymb;
 7935:     }
 7936:     $courseid=$env{'request.course.id'};
 7937:     $domain=$env{'user.domain'};
 7938:     $name=$env{'user.name'};
 7939:     if ($name eq 'public' && $domain eq 'public') {
 7940: 	if (!defined($env{'form.username'})) {
 7941: 	    $env{'form.username'}.=time.rand(10000000);
 7942: 	}
 7943: 	$name.=$env{'form.username'};
 7944:     }
 7945:     return ($symb,$courseid,$domain,$name,$publicuser);
 7946: 
 7947: }
 7948: 
 7949: # ------------------------------------------------------------ Serves up a file
 7950: # returns either the contents of the file or 
 7951: # -1 if the file doesn't exist
 7952: #
 7953: # if the target is a file that was uploaded via DOCS, 
 7954: # a check will be made to see if a current copy exists on the local server,
 7955: # if it does this will be served, otherwise a copy will be retrieved from
 7956: # the home server for the course and stored in /home/httpd/html/userfiles on
 7957: # the local server.   
 7958: 
 7959: sub getfile {
 7960:     my ($file) = @_;
 7961:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7962:     &repcopy($file);
 7963:     return &readfile($file);
 7964: }
 7965: 
 7966: sub repcopy_userfile {
 7967:     my ($file)=@_;
 7968:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7969:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7970:     my ($cdom,$cnum,$filename) = 
 7971: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7972:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7973:     if (-e "$file") {
 7974: # we already have a local copy, check it out
 7975: 	my @fileinfo = stat($file);
 7976: 	my $rtncode;
 7977: 	my $info;
 7978: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7979: 	if ($lwpresp ne 'ok') {
 7980: # there is no such file anymore, even though we had a local copy
 7981: 	    if ($rtncode eq '404') {
 7982: 		unlink($file);
 7983: 	    }
 7984: 	    return -1;
 7985: 	}
 7986: 	if ($info < $fileinfo[9]) {
 7987: # nice, the file we have is up-to-date, just say okay
 7988: 	    return 'ok';
 7989: 	} else {
 7990: # the file is outdated, get rid of it
 7991: 	    unlink($file);
 7992: 	}
 7993:     }
 7994: # one way or the other, at this point, we don't have the file
 7995: # construct the correct path for the file
 7996:     my @parts = ($cdom,$cnum); 
 7997:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7998: 	push @parts, split(/\//,$1);
 7999:     }
 8000:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8001:     foreach my $part (@parts) {
 8002: 	$path .= '/'.$part;
 8003: 	if (!-e $path) {
 8004: 	    mkdir($path,0770);
 8005: 	}
 8006:     }
 8007: # now the path exists for sure
 8008: # get a user agent
 8009:     my $ua=new LWP::UserAgent;
 8010:     my $transferfile=$file.'.in.transfer';
 8011: # FIXME: this should flock
 8012:     if (-e $transferfile) { return 'ok'; }
 8013:     my $request;
 8014:     $uri=~s/^\///;
 8015:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 8016:     my $response=$ua->request($request,$transferfile);
 8017: # did it work?
 8018:     if ($response->is_error()) {
 8019: 	unlink($transferfile);
 8020: 	&logthis("Userfile repcopy failed for $uri");
 8021: 	return -1;
 8022:     }
 8023: # worked, rename the transfer file
 8024:     rename($transferfile,$file);
 8025:     return 'ok';
 8026: }
 8027: 
 8028: sub tokenwrapper {
 8029:     my $uri=shift;
 8030:     $uri=~s|^http\://([^/]+)||;
 8031:     $uri=~s|^/||;
 8032:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8033:     my $token=$1;
 8034:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8035:     if ($udom && $uname && $file) {
 8036: 	$file=~s|(\?\.*)*$||;
 8037:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8038:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 8039:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8040:                                '&tokenissued='.$perlvar{'lonHostID'};
 8041:     } else {
 8042:         return '/adm/notfound.html';
 8043:     }
 8044: }
 8045: 
 8046: # call with reqtype HEAD: get last modification time
 8047: # call with reqtype GET: get the file contents
 8048: # Do not call this with reqtype GET for large files! It loads everything into memory
 8049: #
 8050: sub getuploaded {
 8051:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8052:     $uri=~s/^\///;
 8053:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8054:     my $ua=new LWP::UserAgent;
 8055:     my $request=new HTTP::Request($reqtype,$uri);
 8056:     my $response=$ua->request($request);
 8057:     $$rtncode = $response->code;
 8058:     if (! $response->is_success()) {
 8059: 	return 'failed';
 8060:     }      
 8061:     if ($reqtype eq 'HEAD') {
 8062: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8063:     } elsif ($reqtype eq 'GET') {
 8064: 	$$info = $response->content;
 8065:     }
 8066:     return 'ok';
 8067: }
 8068: 
 8069: sub readfile {
 8070:     my $file = shift;
 8071:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8072:     my $fh;
 8073:     open($fh,"<$file");
 8074:     my $a='';
 8075:     while (my $line = <$fh>) { $a .= $line; }
 8076:     return $a;
 8077: }
 8078: 
 8079: sub filelocation {
 8080:     my ($dir,$file) = @_;
 8081:     my $location;
 8082:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8083: 
 8084:     if ($file =~ m-^/adm/-) {
 8085: 	$file=~s-^/adm/wrapper/-/-;
 8086: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8087:     }
 8088: 
 8089:     if ($file=~m:^/~:) { # is a contruction space reference
 8090:         $location = $file;
 8091:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8092:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8093: 	# is a correct contruction space reference
 8094:         $location = $file;
 8095:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8096:         my ($udom,$uname,$filename)=
 8097:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8098:         my $home=&homeserver($uname,$udom);
 8099:         my $is_me=0;
 8100:         my @ids=&current_machine_ids();
 8101:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8102:         if ($is_me) {
 8103:   	    $location=&propath($udom,$uname).
 8104:   	      '/userfiles/'.$filename;
 8105:         } else {
 8106:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8107:   	      $udom.'/'.$uname.'/'.$filename;
 8108:         }
 8109:     } elsif ($file =~ m-^/adm/-) {
 8110: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8111:     } else {
 8112:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8113:         $file=~s:^/res/:/:;
 8114:         if ( !( $file =~ m:^/:) ) {
 8115:             $location = $dir. '/'.$file;
 8116:         } else {
 8117:             $location = '/home/httpd/html/res'.$file;
 8118:         }
 8119:     }
 8120:     $location=~s://+:/:g; # remove duplicate /
 8121:     while ($location=~m{/\.\./}) {
 8122: 	if ($location =~ m{/[^/]+/\.\./}) {
 8123: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8124: 	} else {
 8125: 	    $location=~ s{/\.\./}{/}g;
 8126: 	}
 8127:     } #remove dir/..
 8128:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8129:     return $location;
 8130: }
 8131: 
 8132: sub hreflocation {
 8133:     my ($dir,$file)=@_;
 8134:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8135: 	$file=filelocation($dir,$file);
 8136:     } elsif ($file=~m-^/adm/-) {
 8137: 	$file=~s-^/adm/wrapper/-/-;
 8138: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8139:     }
 8140:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8141: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8142:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8143: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8144:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8145: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8146: 	    -/uploaded/$1/$2/-x;
 8147:     }
 8148:     if ($file=~ m{^/userfiles/}) {
 8149: 	$file =~ s{^/userfiles/}{/uploaded/};
 8150:     }
 8151:     return $file;
 8152: }
 8153: 
 8154: sub current_machine_domains {
 8155:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8156: }
 8157: 
 8158: sub machine_domains {
 8159:     my ($hostname) = @_;
 8160:     my @domains;
 8161:     my %hostname = &all_hostnames();
 8162:     while( my($id, $name) = each(%hostname)) {
 8163: #	&logthis("-$id-$name-$hostname-");
 8164: 	if ($hostname eq $name) {
 8165: 	    push(@domains,&host_domain($id));
 8166: 	}
 8167:     }
 8168:     return @domains;
 8169: }
 8170: 
 8171: sub current_machine_ids {
 8172:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8173: }
 8174: 
 8175: sub machine_ids {
 8176:     my ($hostname) = @_;
 8177:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8178:     my @ids;
 8179:     my %name_to_host = &all_names();
 8180:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8181: 	return @{ $name_to_host{$hostname} };
 8182:     }
 8183:     return;
 8184: }
 8185: 
 8186: sub additional_machine_domains {
 8187:     my @domains;
 8188:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8189:     while( my $line = <$fh>) {
 8190:         $line =~ s/\s//g;
 8191:         push(@domains,$line);
 8192:     }
 8193:     return @domains;
 8194: }
 8195: 
 8196: sub default_login_domain {
 8197:     my $domain = $perlvar{'lonDefDomain'};
 8198:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8199:     foreach my $posdom (&current_machine_domains(),
 8200:                         &additional_machine_domains()) {
 8201:         if (lc($posdom) eq lc($testdomain)) {
 8202:             $domain=$posdom;
 8203:             last;
 8204:         }
 8205:     }
 8206:     return $domain;
 8207: }
 8208: 
 8209: # ------------------------------------------------------------- Declutters URLs
 8210: 
 8211: sub declutter {
 8212:     my $thisfn=shift;
 8213:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8214:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8215:     $thisfn=~s/^\///;
 8216:     $thisfn=~s|^adm/wrapper/||;
 8217:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8218:     $thisfn=~s/^res\///;
 8219:     $thisfn=~s/\?.+$//;
 8220:     return $thisfn;
 8221: }
 8222: 
 8223: # ------------------------------------------------------------- Clutter up URLs
 8224: 
 8225: sub clutter {
 8226:     my $thisfn='/'.&declutter(shift);
 8227:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8228: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8229:        $thisfn='/res'.$thisfn; 
 8230:     }
 8231:     if ($thisfn !~m|/adm|) {
 8232: 	if ($thisfn =~ m|/ext/|) {
 8233: 	    $thisfn='/adm/wrapper'.$thisfn;
 8234: 	} else {
 8235: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8236: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8237: 	    if ($embstyle eq 'ssi'
 8238: 		|| ($embstyle eq 'hdn')
 8239: 		|| ($embstyle eq 'rat')
 8240: 		|| ($embstyle eq 'prv')
 8241: 		|| ($embstyle eq 'ign')) {
 8242: 		#do nothing with these
 8243: 	    } elsif (($embstyle eq 'img') 
 8244: 		|| ($embstyle eq 'emb')
 8245: 		|| ($embstyle eq 'wrp')) {
 8246: 		$thisfn='/adm/wrapper'.$thisfn;
 8247: 	    } elsif ($embstyle eq 'unk'
 8248: 		     && $thisfn!~/\.(sequence|page)$/) {
 8249: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8250: 	    } else {
 8251: #		&logthis("Got a blank emb style");
 8252: 	    }
 8253: 	}
 8254:     }
 8255:     return $thisfn;
 8256: }
 8257: 
 8258: sub clutter_with_no_wrapper {
 8259:     my $uri = &clutter(shift);
 8260:     if ($uri =~ m-^/adm/-) {
 8261: 	$uri =~ s-^/adm/wrapper/-/-;
 8262: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8263:     }
 8264:     return $uri;
 8265: }
 8266: 
 8267: sub freeze_escape {
 8268:     my ($value)=@_;
 8269:     if (ref($value)) {
 8270: 	$value=&nfreeze($value);
 8271: 	return '__FROZEN__'.&escape($value);
 8272:     }
 8273:     return &escape($value);
 8274: }
 8275: 
 8276: 
 8277: sub thaw_unescape {
 8278:     my ($value)=@_;
 8279:     if ($value =~ /^__FROZEN__/) {
 8280: 	substr($value,0,10,undef);
 8281: 	$value=&unescape($value);
 8282: 	return &thaw($value);
 8283:     }
 8284:     return &unescape($value);
 8285: }
 8286: 
 8287: sub correct_line_ends {
 8288:     my ($result)=@_;
 8289:     $$result =~s/\r\n/\n/mg;
 8290:     $$result =~s/\r/\n/mg;
 8291: }
 8292: # ================================================================ Main Program
 8293: 
 8294: sub goodbye {
 8295:    &logthis("Starting Shut down");
 8296: #not converted to using infrastruture and probably shouldn't be
 8297:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8298: #converted
 8299: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8300:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8301: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8302: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8303: #1.1 only
 8304: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8305: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8306: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8307: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8308:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8309:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8310:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8311:    &flushcourselogs();
 8312:    &logthis("Shutting down");
 8313: }
 8314: 
 8315: sub get_dns {
 8316:     my ($url,$func,$ignore_cache) = @_;
 8317:     if (!$ignore_cache) {
 8318: 	my ($content,$cached)=
 8319: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8320: 	if ($cached) {
 8321: 	    &$func($content);
 8322: 	    return;
 8323: 	}
 8324:     }
 8325: 
 8326:     my %alldns;
 8327:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8328:     foreach my $dns (<$config>) {
 8329: 	next if ($dns !~ /^\^(\S*)/x);
 8330: 	$alldns{$1} = 1;
 8331:     }
 8332:     while (%alldns) {
 8333: 	my ($dns) = keys(%alldns);
 8334: 	delete($alldns{$dns});
 8335: 	my $ua=new LWP::UserAgent;
 8336: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8337: 	my $response=$ua->request($request);
 8338: 	next if ($response->is_error());
 8339: 	my @content = split("\n",$response->content);
 8340: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8341: 	&$func(\@content);
 8342: 	return;
 8343:     }
 8344:     close($config);
 8345:     my $which = (split('/',$url))[3];
 8346:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8347:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8348:     my @content = <$config>;
 8349:     &$func(\@content);
 8350:     return;
 8351: }
 8352: # ------------------------------------------------------------ Read domain file
 8353: {
 8354:     my $loaded;
 8355:     my %domain;
 8356: 
 8357:     sub parse_domain_tab {
 8358: 	my ($lines) = @_;
 8359: 	foreach my $line (@$lines) {
 8360: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8361: 
 8362: 	    chomp($line);
 8363: 	    my ($name,@elements) = split(/:/,$line,9);
 8364: 	    my %this_domain;
 8365: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8366: 			       'lang_def', 'city', 'longi', 'lati',
 8367: 			       'primary') {
 8368: 		$this_domain{$field} = shift(@elements);
 8369: 	    }
 8370: 	    $domain{$name} = \%this_domain;
 8371: 	}
 8372:     }
 8373: 
 8374:     sub reset_domain_info {
 8375: 	undef($loaded);
 8376: 	undef(%domain);
 8377:     }
 8378: 
 8379:     sub load_domain_tab {
 8380: 	my ($ignore_cache) = @_;
 8381: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8382: 	my $fh;
 8383: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8384: 	    my @lines = <$fh>;
 8385: 	    &parse_domain_tab(\@lines);
 8386: 	}
 8387: 	close($fh);
 8388: 	$loaded = 1;
 8389:     }
 8390: 
 8391:     sub domain {
 8392: 	&load_domain_tab() if (!$loaded);
 8393: 
 8394: 	my ($name,$what) = @_;
 8395: 	return if ( !exists($domain{$name}) );
 8396: 
 8397: 	if (!$what) {
 8398: 	    return $domain{$name}{'description'};
 8399: 	}
 8400: 	return $domain{$name}{$what};
 8401:     }
 8402: }
 8403: 
 8404: 
 8405: # ------------------------------------------------------------- Read hosts file
 8406: {
 8407:     my %hostname;
 8408:     my %hostdom;
 8409:     my %libserv;
 8410:     my $loaded;
 8411:     my %name_to_host;
 8412: 
 8413:     sub parse_hosts_tab {
 8414: 	my ($file) = @_;
 8415: 	foreach my $configline (@$file) {
 8416: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8417: 	    next if ($configline =~ /^\^/);
 8418: 	    chomp($configline);
 8419: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8420: 	    $name=~s/\s//g;
 8421: 	    if ($id && $domain && $role && $name) {
 8422: 		$hostname{$id}=$name;
 8423: 		push(@{$name_to_host{$name}}, $id);
 8424: 		$hostdom{$id}=$domain;
 8425: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8426: 	    }
 8427: 	}
 8428:     }
 8429:     
 8430:     sub reset_hosts_info {
 8431: 	&purge_remembered();
 8432: 	&reset_domain_info();
 8433: 	&reset_hosts_ip_info();
 8434: 	undef(%name_to_host);
 8435: 	undef(%hostname);
 8436: 	undef(%hostdom);
 8437: 	undef(%libserv);
 8438: 	undef($loaded);
 8439:     }
 8440: 
 8441:     sub load_hosts_tab {
 8442: 	my ($ignore_cache) = @_;
 8443: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8444: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8445: 	my @config = <$config>;
 8446: 	&parse_hosts_tab(\@config);
 8447: 	close($config);
 8448: 	$loaded=1;
 8449:     }
 8450: 
 8451:     sub hostname {
 8452: 	&load_hosts_tab() if (!$loaded);
 8453: 
 8454: 	my ($lonid) = @_;
 8455: 	return $hostname{$lonid};
 8456:     }
 8457: 
 8458:     sub all_hostnames {
 8459: 	&load_hosts_tab() if (!$loaded);
 8460: 
 8461: 	return %hostname;
 8462:     }
 8463: 
 8464:     sub all_names {
 8465: 	&load_hosts_tab() if (!$loaded);
 8466: 
 8467: 	return %name_to_host;
 8468:     }
 8469: 
 8470:     sub is_library {
 8471: 	&load_hosts_tab() if (!$loaded);
 8472: 
 8473: 	return exists($libserv{$_[0]});
 8474:     }
 8475: 
 8476:     sub all_library {
 8477: 	&load_hosts_tab() if (!$loaded);
 8478: 
 8479: 	return %libserv;
 8480:     }
 8481: 
 8482:     sub get_servers {
 8483: 	&load_hosts_tab() if (!$loaded);
 8484: 
 8485: 	my ($domain,$type) = @_;
 8486: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8487: 	                                          : %hostname;
 8488: 	my %result;
 8489: 	if (ref($domain) eq 'ARRAY') {
 8490: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8491: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8492: 		    $result{$host} = $hostname;
 8493: 		}
 8494: 	    }
 8495: 	} else {
 8496: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8497: 		if ($hostdom{$host} eq $domain) {
 8498: 		    $result{$host} = $hostname;
 8499: 		}
 8500: 	    }
 8501: 	}
 8502: 	return %result;
 8503:     }
 8504: 
 8505:     sub host_domain {
 8506: 	&load_hosts_tab() if (!$loaded);
 8507: 
 8508: 	my ($lonid) = @_;
 8509: 	return $hostdom{$lonid};
 8510:     }
 8511: 
 8512:     sub all_domains {
 8513: 	&load_hosts_tab() if (!$loaded);
 8514: 
 8515: 	my %seen;
 8516: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8517: 	return @uniq;
 8518:     }
 8519: }
 8520: 
 8521: { 
 8522:     my %iphost;
 8523:     my %name_to_ip;
 8524:     my %lonid_to_ip;
 8525: 
 8526:     sub get_hosts_from_ip {
 8527: 	my ($ip) = @_;
 8528: 	my %iphosts = &get_iphost();
 8529: 	if (ref($iphosts{$ip})) {
 8530: 	    return @{$iphosts{$ip}};
 8531: 	}
 8532: 	return;
 8533:     }
 8534:     
 8535:     sub reset_hosts_ip_info {
 8536: 	undef(%iphost);
 8537: 	undef(%name_to_ip);
 8538: 	undef(%lonid_to_ip);
 8539:     }
 8540: 
 8541:     sub get_host_ip {
 8542: 	my ($lonid) = @_;
 8543: 	if (exists($lonid_to_ip{$lonid})) {
 8544: 	    return $lonid_to_ip{$lonid};
 8545: 	}
 8546: 	my $name=&hostname($lonid);
 8547:    	my $ip = gethostbyname($name);
 8548: 	return if (!$ip || length($ip) ne 4);
 8549: 	$ip=inet_ntoa($ip);
 8550: 	$name_to_ip{$name}   = $ip;
 8551: 	$lonid_to_ip{$lonid} = $ip;
 8552: 	return $ip;
 8553:     }
 8554:     
 8555:     sub get_iphost {
 8556: 	my ($ignore_cache) = @_;
 8557: 
 8558: 	if (!$ignore_cache) {
 8559: 	    if (%iphost) {
 8560: 		return %iphost;
 8561: 	    }
 8562: 	    my ($ip_info,$cached)=
 8563: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8564: 	    if ($cached) {
 8565: 		%iphost      = %{$ip_info->[0]};
 8566: 		%name_to_ip  = %{$ip_info->[1]};
 8567: 		%lonid_to_ip = %{$ip_info->[2]};
 8568: 		return %iphost;
 8569: 	    }
 8570: 	}
 8571: 
 8572: 	# get yesterday's info for fallback
 8573: 	my %old_name_to_ip;
 8574: 	my ($ip_info,$cached)=
 8575: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8576: 	if ($cached) {
 8577: 	    %old_name_to_ip = %{$ip_info->[1]};
 8578: 	}
 8579: 
 8580: 	my %name_to_host = &all_names();
 8581: 	foreach my $name (keys(%name_to_host)) {
 8582: 	    my $ip;
 8583: 	    if (!exists($name_to_ip{$name})) {
 8584: 		$ip = gethostbyname($name);
 8585: 		if (!$ip || length($ip) ne 4) {
 8586: 		    if (defined($old_name_to_ip{$name})) {
 8587: 			$ip = $old_name_to_ip{$name};
 8588: 			&logthis("Can't find $name defaulting to old $ip");
 8589: 		    } else {
 8590: 			&logthis("Name $name no IP found");
 8591: 			next;
 8592: 		    }
 8593: 		} else {
 8594: 		    $ip=inet_ntoa($ip);
 8595: 		}
 8596: 		$name_to_ip{$name} = $ip;
 8597: 	    } else {
 8598: 		$ip = $name_to_ip{$name};
 8599: 	    }
 8600: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8601: 		$lonid_to_ip{$id} = $ip;
 8602: 	    }
 8603: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8604: 	}
 8605: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8606: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8607: 				      48*60*60);
 8608: 
 8609: 	return %iphost;
 8610:     }
 8611: }
 8612: 
 8613: BEGIN {
 8614: 
 8615: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8616:     unless ($readit) {
 8617: {
 8618:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8619:     %perlvar = (%perlvar,%{$configvars});
 8620: }
 8621: 
 8622: 
 8623: # ------------------------------------------------------ Read spare server file
 8624: {
 8625:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8626: 
 8627:     while (my $configline=<$config>) {
 8628:        chomp($configline);
 8629:        if ($configline) {
 8630: 	   my ($host,$type) = split(':',$configline,2);
 8631: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8632: 	   push(@{ $spareid{$type} }, $host);
 8633:        }
 8634:     }
 8635:     close($config);
 8636: }
 8637: # ------------------------------------------------------------ Read permissions
 8638: {
 8639:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8640: 
 8641:     while (my $configline=<$config>) {
 8642: 	chomp($configline);
 8643: 	if ($configline) {
 8644: 	    my ($role,$perm)=split(/ /,$configline);
 8645: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8646: 	}
 8647:     }
 8648:     close($config);
 8649: }
 8650: 
 8651: # -------------------------------------------- Read plain texts for permissions
 8652: {
 8653:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8654: 
 8655:     while (my $configline=<$config>) {
 8656: 	chomp($configline);
 8657: 	if ($configline) {
 8658: 	    my ($short,@plain)=split(/:/,$configline);
 8659:             %{$prp{$short}} = ();
 8660: 	    if (@plain > 0) {
 8661:                 $prp{$short}{'std'} = $plain[0];
 8662:                 for (my $i=1; $i<@plain; $i++) {
 8663:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8664:                 }
 8665:             }
 8666: 	}
 8667:     }
 8668:     close($config);
 8669: }
 8670: 
 8671: # ---------------------------------------------------------- Read package table
 8672: {
 8673:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8674: 
 8675:     while (my $configline=<$config>) {
 8676: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8677: 	chomp($configline);
 8678: 	my ($short,$plain)=split(/:/,$configline);
 8679: 	my ($pack,$name)=split(/\&/,$short);
 8680: 	if ($plain ne '') {
 8681: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8682: 	    $packagetab{$short}=$plain; 
 8683: 	}
 8684:     }
 8685:     close($config);
 8686: }
 8687: 
 8688: # ------------- set up temporary directory
 8689: {
 8690:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8691: 
 8692: }
 8693: 
 8694: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8695: 				'compress_threshold'=> 20_000,
 8696:  			        });
 8697: 
 8698: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8699: $dumpcount=0;
 8700: 
 8701: &logtouch();
 8702: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8703: $readit=1;
 8704:     {
 8705: 	use integer;
 8706: 	my $test=(2**32)+1;
 8707: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8708: 	&logthis(" Detected 64bit platform ($_64bit)");
 8709:     }
 8710: }
 8711: }
 8712: 
 8713: 1;
 8714: __END__
 8715: 
 8716: =pod
 8717: 
 8718: =head1 NAME
 8719: 
 8720: Apache::lonnet - Subroutines to ask questions about things in the network.
 8721: 
 8722: =head1 SYNOPSIS
 8723: 
 8724: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8725: 
 8726:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8727: 
 8728: Common parameters:
 8729: 
 8730: =over 4
 8731: 
 8732: =item *
 8733: 
 8734: $uname : an internal username (if $cname expecting a course Id specifically)
 8735: 
 8736: =item *
 8737: 
 8738: $udom : a domain (if $cdom expecting a course's domain specifically)
 8739: 
 8740: =item *
 8741: 
 8742: $symb : a resource instance identifier
 8743: 
 8744: =item *
 8745: 
 8746: $namespace : the name of a .db file that contains the data needed or
 8747: being set.
 8748: 
 8749: =back
 8750: 
 8751: =head1 OVERVIEW
 8752: 
 8753: lonnet provides subroutines which interact with the
 8754: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8755: about classes, users, and resources.
 8756: 
 8757: For many of these objects you can also use this to store data about
 8758: them or modify them in various ways.
 8759: 
 8760: =head2 Symbs
 8761: 
 8762: To identify a specific instance of a resource, LON-CAPA uses symbols
 8763: or "symbs"X<symb>. These identifiers are built from the URL of the
 8764: map, the resource number of the resource in the map, and the URL of
 8765: the resource itself. The latter is somewhat redundant, but might help
 8766: if maps change.
 8767: 
 8768: An example is
 8769: 
 8770:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8771: 
 8772: The respective map entry is
 8773: 
 8774:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8775:   title="Problem 2">
 8776:  </resource>
 8777: 
 8778: Symbs are used by the random number generator, as well as to store and
 8779: restore data specific to a certain instance of for example a problem.
 8780: 
 8781: =head2 Storing And Retrieving Data
 8782: 
 8783: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8784: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8785: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8786: is is the non-critical message twin of cstore. These functions are for
 8787: handlers to store a perl hash to a user's permanent data space in an
 8788: easy manner, and to retrieve it again on another call. It is expected
 8789: that a handler would use this once at the beginning to retrieve data,
 8790: and then again once at the end to send only the new data back.
 8791: 
 8792: The data is stored in the user's data directory on the user's
 8793: homeserver under the ID of the course.
 8794: 
 8795: The hash that is returned by restore will have all of the previous
 8796: value for all of the elements of the hash.
 8797: 
 8798: Example:
 8799: 
 8800:  #creating a hash
 8801:  my %hash;
 8802:  $hash{'foo'}='bar';
 8803: 
 8804:  #storing it
 8805:  &Apache::lonnet::cstore(\%hash);
 8806: 
 8807:  #changing a value
 8808:  $hash{'foo'}='notbar';
 8809: 
 8810:  #adding a new value
 8811:  $hash{'bar'}='foo';
 8812:  &Apache::lonnet::cstore(\%hash);
 8813: 
 8814:  #retrieving the hash
 8815:  my %history=&Apache::lonnet::restore();
 8816: 
 8817:  #print the hash
 8818:  foreach my $key (sort(keys(%history))) {
 8819:    print("\%history{$key} = $history{$key}");
 8820:  }
 8821: 
 8822: Will print out:
 8823: 
 8824:  %history{1:foo} = bar
 8825:  %history{1:keys} = foo:timestamp
 8826:  %history{1:timestamp} = 990455579
 8827:  %history{2:bar} = foo
 8828:  %history{2:foo} = notbar
 8829:  %history{2:keys} = foo:bar:timestamp
 8830:  %history{2:timestamp} = 990455580
 8831:  %history{bar} = foo
 8832:  %history{foo} = notbar
 8833:  %history{timestamp} = 990455580
 8834:  %history{version} = 2
 8835: 
 8836: Note that the special hash entries C<keys>, C<version> and
 8837: C<timestamp> were added to the hash. C<version> will be equal to the
 8838: total number of versions of the data that have been stored. The
 8839: C<timestamp> attribute will be the UNIX time the hash was
 8840: stored. C<keys> is available in every historical section to list which
 8841: keys were added or changed at a specific historical revision of a
 8842: hash.
 8843: 
 8844: B<Warning>: do not store the hash that restore returns directly. This
 8845: will cause a mess since it will restore the historical keys as if the
 8846: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8847: 
 8848: Calling convention:
 8849: 
 8850:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8851:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8852: 
 8853: For more detailed information, see lonnet specific documentation.
 8854: 
 8855: =head1 RETURN MESSAGES
 8856: 
 8857: =over 4
 8858: 
 8859: =item * B<con_lost>: unable to contact remote host
 8860: 
 8861: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8862: when the connection is brought back up
 8863: 
 8864: =item * B<con_failed>: unable to contact remote host and unable to save message
 8865: for later delivery
 8866: 
 8867: =item * B<error:>: an error a occured, a description of the error follows the :
 8868: 
 8869: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8870: that was requested
 8871: 
 8872: =back
 8873: 
 8874: =head1 PUBLIC SUBROUTINES
 8875: 
 8876: =head2 Session Environment Functions
 8877: 
 8878: =over 4
 8879: 
 8880: =item * 
 8881: X<appenv()>
 8882: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 8883: the user envirnoment file, and will be restored for each access this
 8884: user makes during this session, also modifies the %env for the current
 8885: process. Optional rolesarrayref - if defined contains a reference to an array
 8886: of roles which are exempt from the restriction on modifying user.role entries 
 8887: in the user's environment.db and in %env.    
 8888: 
 8889: =item *
 8890: X<delenv()>
 8891: B<delenv($regexp)>: removes all items from the session
 8892: environment file that matches the regular expression in $regexp. The
 8893: values are also delted from the current processes %env.
 8894: 
 8895: =item * get_env_multiple($name) 
 8896: 
 8897: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8898: values may be defined and end up as an array ref.
 8899: 
 8900: returns an array of values
 8901: 
 8902: =back
 8903: 
 8904: =head2 User Information
 8905: 
 8906: =over 4
 8907: 
 8908: =item *
 8909: X<queryauthenticate()>
 8910: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8911: authentication scheme
 8912: 
 8913: =item *
 8914: X<authenticate()>
 8915: B<authenticate($uname,$upass,$udom)>: try to
 8916: authenticate user from domain's lib servers (first use the current
 8917: one). C<$upass> should be the users password.
 8918: 
 8919: =item *
 8920: X<homeserver()>
 8921: B<homeserver($uname,$udom)>: find the server which has
 8922: the user's directory and files (there must be only one), this caches
 8923: the answer, and also caches if there is a borken connection.
 8924: 
 8925: =item *
 8926: X<idget()>
 8927: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8928: (IDs are a unique resource in a domain, there must be only 1 ID per
 8929: username, and only 1 username per ID in a specific domain) (returns
 8930: hash: id=>name,id=>name)
 8931: 
 8932: =item *
 8933: X<idrget()>
 8934: B<idrget($udom,@unames)>: find the IDs behind a list of
 8935: usernames (returns hash: name=>id,name=>id)
 8936: 
 8937: =item *
 8938: X<idput()>
 8939: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8940: 
 8941: =item *
 8942: X<rolesinit()>
 8943: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8944: 
 8945: =item *
 8946: X<getsection()>
 8947: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8948: course $cname, return section name/number or '' for "not in course"
 8949: and '-1' for "no section"
 8950: 
 8951: =item *
 8952: X<userenvironment()>
 8953: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8954: passed in @what from the requested user's environment, returns a hash
 8955: 
 8956: =item * 
 8957: X<userlog_query()>
 8958: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8959: activity.log file. %filters defines filters applied when parsing the
 8960: log file. These can be start or end timestamps, or the type of action
 8961: - log to look for Login or Logout events, check for Checkin or
 8962: Checkout, role for role selection. The response is in the form
 8963: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8964: escaped strings of the action recorded in the activity.log file.
 8965: 
 8966: =back
 8967: 
 8968: =head2 User Roles
 8969: 
 8970: =over 4
 8971: 
 8972: =item *
 8973: 
 8974: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8975:  F: full access
 8976:  U,I,K: authentication modes (cxx only)
 8977:  '': forbidden
 8978:  1: user needs to choose course
 8979:  2: browse allowed
 8980:  A: passphrase authentication needed
 8981: 
 8982: =item *
 8983: 
 8984: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8985: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8986: and course level
 8987: 
 8988: =item *
 8989: 
 8990: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8991: explanation of a user role term
 8992: 
 8993: =item *
 8994: 
 8995: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8996: All arguments are optional. Returns a hash of a roles, either for
 8997: co-author/assistant author roles for a user's Construction Space
 8998: (default), or if $context is 'userroles', roles for the user himself,
 8999: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9000: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9001: For each key, value is set to colon-separated start and end times for
 9002: the role.  If no username and domain are specified, will default to
 9003: current user/domain. Types, roles, and roledoms are references to arrays
 9004: of role statuses (active, future or previous), roles 
 9005: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9006: to restrict the list of roles reported. If no array ref is 
 9007: provided for types, will default to return only active roles.
 9008: 
 9009: =back
 9010: 
 9011: =head2 User Modification
 9012: 
 9013: =over 4
 9014: 
 9015: =item *
 9016: 
 9017: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 9018: user for the level given by URL.  Optional start and end dates (leave empty
 9019: string or zero for "no date")
 9020: 
 9021: =item *
 9022: 
 9023: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9024: change a users, password, possible return values are: ok,
 9025: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9026: refused
 9027: 
 9028: =item *
 9029: 
 9030: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9031: 
 9032: =item *
 9033: 
 9034: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 9035: modify user
 9036: 
 9037: =item *
 9038: 
 9039: modifystudent
 9040: 
 9041: modify a students enrollment and identification information.
 9042: The course id is resolved based on the current users environment.  
 9043: This means the envoking user must be a course coordinator or otherwise
 9044: associated with a course.
 9045: 
 9046: This call is essentially a wrapper for lonnet::modifyuser and
 9047: lonnet::modify_student_enrollment
 9048: 
 9049: Inputs: 
 9050: 
 9051: =over 4
 9052: 
 9053: =item B<$udom> Students loncapa domain
 9054: 
 9055: =item B<$uname> Students loncapa login name
 9056: 
 9057: =item B<$uid> Students id/student number
 9058: 
 9059: =item B<$umode> Students authentication mode
 9060: 
 9061: =item B<$upass> Students password
 9062: 
 9063: =item B<$first> Students first name
 9064: 
 9065: =item B<$middle> Students middle name
 9066: 
 9067: =item B<$last> Students last name
 9068: 
 9069: =item B<$gene> Students generation
 9070: 
 9071: =item B<$usec> Students section in course
 9072: 
 9073: =item B<$end> Unix time of the roles expiration
 9074: 
 9075: =item B<$start> Unix time of the roles start date
 9076: 
 9077: =item B<$forceid> If defined, allow $uid to be changed
 9078: 
 9079: =item B<$desiredhome> server to use as home server for student
 9080: 
 9081: =back
 9082: 
 9083: =item *
 9084: 
 9085: modify_student_enrollment
 9086: 
 9087: Change a students enrollment status in a class.  The environment variable
 9088: 'role.request.course' must be defined for this function to proceed.
 9089: 
 9090: Inputs:
 9091: 
 9092: =over 4
 9093: 
 9094: =item $udom, students domain
 9095: 
 9096: =item $uname, students name
 9097: 
 9098: =item $uid, students user id
 9099: 
 9100: =item $first, students first name
 9101: 
 9102: =item $middle
 9103: 
 9104: =item $last
 9105: 
 9106: =item $gene
 9107: 
 9108: =item $usec
 9109: 
 9110: =item $end
 9111: 
 9112: =item $start
 9113: 
 9114: =back
 9115: 
 9116: 
 9117: =item *
 9118: 
 9119: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9120: custom role; give a custom role to a user for the level given by URL.  Specify
 9121: name and domain of role author, and role name
 9122: 
 9123: =item *
 9124: 
 9125: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9126: 
 9127: =item *
 9128: 
 9129: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9130: 
 9131: =back
 9132: 
 9133: =head2 Course Infomation
 9134: 
 9135: =over 4
 9136: 
 9137: =item *
 9138: 
 9139: coursedescription($courseid) : returns a hash of information about the
 9140: specified course id, including all environment settings for the
 9141: course, the description of the course will be in the hash under the
 9142: key 'description'
 9143: 
 9144: =item *
 9145: 
 9146: resdata($name,$domain,$type,@which) : request for current parameter
 9147: setting for a specific $type, where $type is either 'course' or 'user',
 9148: @what should be a list of parameters to ask about. This routine caches
 9149: answers for 5 minutes.
 9150: 
 9151: =item *
 9152: 
 9153: get_courseresdata($courseid, $domain) : dump the entire course resource
 9154: data base, returning a hash that is keyed by the resource name and has
 9155: values that are the resource value.  I believe that the timestamps and
 9156: versions are also returned.
 9157: 
 9158: 
 9159: =back
 9160: 
 9161: =head2 Course Modification
 9162: 
 9163: =over 4
 9164: 
 9165: =item *
 9166: 
 9167: writecoursepref($courseid,%prefs) : write preferences (environment
 9168: database) for a course
 9169: 
 9170: =item *
 9171: 
 9172: createcourse($udom,$description,$url) : make/modify course
 9173: 
 9174: =back
 9175: 
 9176: =head2 Resource Subroutines
 9177: 
 9178: =over 4
 9179: 
 9180: =item *
 9181: 
 9182: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9183: 
 9184: =item *
 9185: 
 9186: repcopy($filename) : subscribes to the requested file, and attempts to
 9187: replicate from the owning library server, Might return
 9188: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9189: 'bad_request', also attempts to grab the metadata for the
 9190: resource. Expects the local filesystem pathname
 9191: (/home/httpd/html/res/....)
 9192: 
 9193: =back
 9194: 
 9195: =head2 Resource Information
 9196: 
 9197: =over 4
 9198: 
 9199: =item *
 9200: 
 9201: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9202: a vairety of different possible values, $varname should be a request
 9203: string, and the other parameters can be used to specify who and what
 9204: one is asking about.
 9205: 
 9206: Possible values for $varname are environment.lastname (or other item
 9207: from the envirnment hash), user.name (or someother aspect about the
 9208: user), resource.0.maxtries (or some other part and parameter of a
 9209: resource)
 9210: 
 9211: =item *
 9212: 
 9213: directcondval($number) : get current value of a condition; reads from a state
 9214: string
 9215: 
 9216: =item *
 9217: 
 9218: condval($condidx) : value of condition index based on state
 9219: 
 9220: =item *
 9221: 
 9222: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9223: resource's metadata, $what should be either a specific key, or either
 9224: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9225: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9226: 
 9227: this function automatically caches all requests
 9228: 
 9229: =item *
 9230: 
 9231: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9232: network of library servers; returns file handle of where SQL and regex results
 9233: will be stored for query
 9234: 
 9235: =item *
 9236: 
 9237: symbread($filename) : return symbolic list entry (filename argument optional);
 9238: returns the data handle
 9239: 
 9240: =item *
 9241: 
 9242: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9243: a possible symb for the URL in $thisfn, and if is an encryypted
 9244: resource that the user accessed using /enc/ returns a 1 on success, 0
 9245: on failure, user must be in a course, as it assumes the existance of
 9246: the course initial hash, and uses $env('request.course.id'}
 9247: 
 9248: 
 9249: =item *
 9250: 
 9251: symbclean($symb) : removes versions numbers from a symb, returns the
 9252: cleaned symb
 9253: 
 9254: =item *
 9255: 
 9256: is_on_map($uri) : checks if the $uri is somewhere on the current
 9257: course map, user must be in a course for it to work.
 9258: 
 9259: =item *
 9260: 
 9261: numval($salt) : return random seed value (addend for rndseed)
 9262: 
 9263: =item *
 9264: 
 9265: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9266: a random seed, all arguments are optional, if they aren't sent it uses the
 9267: environment to derive them. Note: if symb isn't sent and it can't get one
 9268: from &symbread it will use the current time as its return value
 9269: 
 9270: =item *
 9271: 
 9272: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9273: unfakeable, receipt
 9274: 
 9275: =item *
 9276: 
 9277: receipt() : API to ireceipt working off of env values; given out to users
 9278: 
 9279: =item *
 9280: 
 9281: countacc($url) : count the number of accesses to a given URL
 9282: 
 9283: =item *
 9284: 
 9285: 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
 9286: 
 9287: =item *
 9288: 
 9289: 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)
 9290: 
 9291: =item *
 9292: 
 9293: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9294: 
 9295: =item *
 9296: 
 9297: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9298: forcing spreadsheet to reevaluate the resource scores next time.
 9299: 
 9300: =back
 9301: 
 9302: =head2 Storing/Retreiving Data
 9303: 
 9304: =over 4
 9305: 
 9306: =item *
 9307: 
 9308: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9309: for this url; hashref needs to be given and should be a \%hashname; the
 9310: remaining args aren't required and if they aren't passed or are '' they will
 9311: be derived from the env
 9312: 
 9313: =item *
 9314: 
 9315: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9316: uses critical subroutine
 9317: 
 9318: =item *
 9319: 
 9320: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9321: all args are optional
 9322: 
 9323: =item *
 9324: 
 9325: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9326: dumps the complete (or key matching regexp) namespace into a hash
 9327: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9328: normally &store()ed into
 9329: 
 9330: $range should be either an integer '100' (give me the first 100
 9331:                                            matching records)
 9332:               or be  two integers sperated by a - with no spaces
 9333:                  '30-50' (give me the 30th through the 50th matching
 9334:                           records)
 9335: 
 9336: 
 9337: =item *
 9338: 
 9339: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9340: replaces a &store() version of data with a replacement set of data
 9341: for a particular resource in a namespace passed in the $storehash hash 
 9342: reference
 9343: 
 9344: =item *
 9345: 
 9346: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9347: works very similar to store/cstore, but all data is stored in a
 9348: temporary location and can be reset using tmpreset, $storehash should
 9349: be a hash reference, returns nothing on success
 9350: 
 9351: =item *
 9352: 
 9353: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9354: similar to restore, but all data is stored in a temporary location and
 9355: can be reset using tmpreset. Returns a hash of values on success,
 9356: error string otherwise.
 9357: 
 9358: =item *
 9359: 
 9360: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9361: deltes all keys for $symb form the temporary storage hash.
 9362: 
 9363: =item *
 9364: 
 9365: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9366: reference filled in from namesp ($udom and $uname are optional)
 9367: 
 9368: =item *
 9369: 
 9370: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9371: namesp ($udom and $uname are optional)
 9372: 
 9373: =item *
 9374: 
 9375: dump($namespace,$udom,$uname,$regexp,$range) : 
 9376: dumps the complete (or key matching regexp) namespace into a hash
 9377: ($udom, $uname, $regexp, $range are optional)
 9378: 
 9379: $range should be either an integer '100' (give me the first 100
 9380:                                            matching records)
 9381:               or be  two integers sperated by a - with no spaces
 9382:                  '30-50' (give me the 30th through the 50th matching
 9383:                           records)
 9384: =item *
 9385: 
 9386: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9387: $store can be a scalar, an array reference, or if the amount to be 
 9388: incremented is > 1, a hash reference.
 9389: 
 9390: ($udom and $uname are optional)
 9391: 
 9392: =item *
 9393: 
 9394: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9395: ($udom and $uname are optional)
 9396: 
 9397: =item *
 9398: 
 9399: cput($namespace,$storehash,$udom,$uname) : critical put
 9400: ($udom and $uname are optional)
 9401: 
 9402: =item *
 9403: 
 9404: newput($namespace,$storehash,$udom,$uname) :
 9405: 
 9406: Attempts to store the items in the $storehash, but only if they don't
 9407: currently exist, if this succeeds you can be certain that you have 
 9408: successfully created a new key value pair in the $namespace db.
 9409: 
 9410: 
 9411: Args:
 9412:  $namespace: name of database to store values to
 9413:  $storehash: hashref to store to the db
 9414:  $udom: (optional) domain of user containing the db
 9415:  $uname: (optional) name of user caontaining the db
 9416: 
 9417: Returns:
 9418:  'ok' -> succeeded in storing all keys of $storehash
 9419:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9420:                         least <key> already existed in the db (other
 9421:                         requested keys may also already exist)
 9422:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9423:  'con_lost' -> unable to contact request server
 9424:  'refused' -> action was not allowed by remote machine
 9425: 
 9426: 
 9427: =item *
 9428: 
 9429: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9430: reference filled in from namesp (encrypts the return communication)
 9431: ($udom and $uname are optional)
 9432: 
 9433: =item *
 9434: 
 9435: log($udom,$name,$home,$message) : write to permanent log for user; use
 9436: critical subroutine
 9437: 
 9438: =item *
 9439: 
 9440: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9441: array reference filled in from namespace found in domain level on either
 9442: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9443: 
 9444: =item *
 9445: 
 9446: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9447: domain level either on specified domain server ($uhome) or primary domain 
 9448: server ($udom and $uhome are optional)
 9449: 
 9450: =item * 
 9451: 
 9452: get_domain_defaults($target_domain) : returns hash with defaults for
 9453: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9454: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9455: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9456: Values are retrieved from cache (if current), or from domain's configuration.db
 9457: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9458: or lonTabs/domain.tab. 
 9459: 
 9460: %domdefaults = &get_auth_defaults($target_domain);
 9461: 
 9462: =back
 9463: 
 9464: =head2 Network Status Functions
 9465: 
 9466: =over 4
 9467: 
 9468: =item *
 9469: 
 9470: dirlist($uri) : return directory list based on URI
 9471: 
 9472: =item *
 9473: 
 9474: spareserver() : find server with least workload from spare.tab
 9475: 
 9476: =back
 9477: 
 9478: =head2 Apache Request
 9479: 
 9480: =over 4
 9481: 
 9482: =item *
 9483: 
 9484: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9485: localhost, posts hash
 9486: 
 9487: =back
 9488: 
 9489: =head2 Data to String to Data
 9490: 
 9491: =over 4
 9492: 
 9493: =item *
 9494: 
 9495: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9496: and '&' separators, supports elements that are arrayrefs and hashrefs
 9497: 
 9498: =item *
 9499: 
 9500: hashref2str($hashref) : convert a hashref into a string complete with
 9501: escaping and '=' and '&' separators, supports elements that are
 9502: arrayrefs and hashrefs
 9503: 
 9504: =item *
 9505: 
 9506: arrayref2str($arrayref) : convert an arrayref into a string complete
 9507: with escaping and '&' separators, supports elements that are arrayrefs
 9508: and hashrefs
 9509: 
 9510: =item *
 9511: 
 9512: str2hash($string) : convert string to hash using unescaping and
 9513: splitting on '=' and '&', supports elements that are arrayrefs and
 9514: hashrefs
 9515: 
 9516: =item *
 9517: 
 9518: str2array($string) : convert string to hash using unescaping and
 9519: splitting on '&', supports elements that are arrayrefs and hashrefs
 9520: 
 9521: =back
 9522: 
 9523: =head2 Logging Routines
 9524: 
 9525: =over 4
 9526: 
 9527: These routines allow one to make log messages in the lonnet.log and
 9528: lonnet.perm logfiles.
 9529: 
 9530: =item *
 9531: 
 9532: logtouch() : make sure the logfile, lonnet.log, exists
 9533: 
 9534: =item *
 9535: 
 9536: logthis() : append message to the normal lonnet.log file, it gets
 9537: preiodically rolled over and deleted.
 9538: 
 9539: =item *
 9540: 
 9541: logperm() : append a permanent message to lonnet.perm.log, this log
 9542: file never gets deleted by any automated portion of the system, only
 9543: messages of critical importance should go in here.
 9544: 
 9545: =back
 9546: 
 9547: =head2 General File Helper Routines
 9548: 
 9549: =over 4
 9550: 
 9551: =item *
 9552: 
 9553: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9554: (a) files in /uploaded
 9555:   (i) If a local copy of the file exists - 
 9556:       compares modification date of local copy with last-modified date for 
 9557:       definitive version stored on home server for course. If local copy is 
 9558:       stale, requests a new version from the home server and stores it. 
 9559:       If the original has been removed from the home server, then local copy 
 9560:       is unlinked.
 9561:   (ii) If local copy does not exist -
 9562:       requests the file from the home server and stores it. 
 9563:   
 9564:   If $caller is 'uploadrep':  
 9565:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9566:     for request for files originally uploaded via DOCS. 
 9567:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9568:   
 9569:   Otherwise:
 9570:      This indicates a call from the content generation phase of the request.
 9571:      -  returns the entire contents of the file or -1.
 9572:      
 9573: (b) files in /res
 9574:    - returns the entire contents of a file or -1; 
 9575:    it properly subscribes to and replicates the file if neccessary.
 9576: 
 9577: 
 9578: =item *
 9579: 
 9580: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9581:                   reference
 9582: 
 9583: returns either a stat() list of data about the file or an empty list
 9584: if the file doesn't exist or couldn't find out about it (connection
 9585: problems or user unknown)
 9586: 
 9587: =item *
 9588: 
 9589: filelocation($dir,$file) : returns file system location of a file
 9590: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9591: directory that relative $file lookups are to looked in ($dir of /a/dir
 9592: and a file of ../bob will become /a/bob)
 9593: 
 9594: =item *
 9595: 
 9596: hreflocation($dir,$file) : returns file system location or a URL; same as
 9597: filelocation except for hrefs
 9598: 
 9599: =item *
 9600: 
 9601: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9602: 
 9603: =back
 9604: 
 9605: =head2 Usererfile file routines (/uploaded*)
 9606: 
 9607: =over 4
 9608: 
 9609: =item *
 9610: 
 9611: userfileupload(): main rotine for putting a file in a user or course's
 9612:                   filespace, arguments are,
 9613: 
 9614:  formname - required - this is the name of the element in $env where the
 9615:            filename, and the contents of the file to create/modifed exist
 9616:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9617:            contents of the file is located in $env{'form.'.$formname}
 9618:  coursedoc - if true, store the file in the course of the active role
 9619:              of the current user
 9620:  subdir - required - subdirectory to put the file in under ../userfiles/
 9621:          if undefined, it will be placed in "unknown"
 9622: 
 9623:  (This routine calls clean_filename() to remove any dangerous
 9624:  characters from the filename, and then calls finuserfileupload() to
 9625:  complete the transaction)
 9626: 
 9627:  returns either the url of the uploaded file (/uploaded/....) if successful
 9628:  and /adm/notfound.html if unsuccessful
 9629: 
 9630: =item *
 9631: 
 9632: clean_filename(): routine for cleaing a filename up for storage in
 9633:                  userfile space, argument is:
 9634: 
 9635:  filename - proposed filename
 9636: 
 9637: returns: the new clean filename
 9638: 
 9639: =item *
 9640: 
 9641: finishuserfileupload(): routine that creaes and sends the file to
 9642: userspace, probably shouldn't be called directly
 9643: 
 9644:   docuname: username or courseid of destination for the file
 9645:   docudom: domain of user/course of destination for the file
 9646:   formname: same as for userfileupload()
 9647:   fname: filename (inculding subdirectories) for the file
 9648: 
 9649:  returns either the url of the uploaded file (/uploaded/....) if successful
 9650:  and /adm/notfound.html if unsuccessful
 9651: 
 9652: =item *
 9653: 
 9654: renameuserfile(): renames an existing userfile to a new name
 9655: 
 9656:   Args:
 9657:    docuname: username or courseid of destination for the file
 9658:    docudom: domain of user/course of destination for the file
 9659:    old: current file name (including any subdirs under userfiles)
 9660:    new: desired file name (including any subdirs under userfiles)
 9661: 
 9662: =item *
 9663: 
 9664: mkdiruserfile(): creates a directory is a userfiles dir
 9665: 
 9666:   Args:
 9667:    docuname: username or courseid of destination for the file
 9668:    docudom: domain of user/course of destination for the file
 9669:    dir: dir to create (including any subdirs under userfiles)
 9670: 
 9671: =item *
 9672: 
 9673: removeuserfile(): removes a file that exists in userfiles
 9674: 
 9675:   Args:
 9676:    docuname: username or courseid of destination for the file
 9677:    docudom: domain of user/course of destination for the file
 9678:    fname: filname to delete (including any subdirs under userfiles)
 9679: 
 9680: =item *
 9681: 
 9682: removeuploadedurl(): convience function for removeuserfile()
 9683: 
 9684:   Args:
 9685:    url:  a full /uploaded/... url to delete
 9686: 
 9687: =item * 
 9688: 
 9689: get_portfile_permissions():
 9690:   Args:
 9691:     domain: domain of user or course contain the portfolio files
 9692:     user: name of user or num of course contain the portfolio files
 9693:   Returns:
 9694:     hashref of a dump of the proper file_permissions.db
 9695:    
 9696: 
 9697: =item * 
 9698: 
 9699: get_access_controls():
 9700: 
 9701: Args:
 9702:   current_permissions: the hash ref returned from get_portfile_permissions()
 9703:   group: (optional) the group you want the files associated with
 9704:   file: (optional) the file you want access info on
 9705: 
 9706: Returns:
 9707:     a hash (keys are file names) of hashes containing
 9708:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9709:         values are XML containing access control settings (see below) 
 9710: 
 9711: Internal notes:
 9712: 
 9713:  access controls are stored in file_permissions.db as key=value pairs.
 9714:     key -> path to file/file_name\0uniqueID:scope_end_start
 9715:         where scope -> public,guest,course,group,domains or users.
 9716:               end -> UNIX time for end of access (0 -> no end date)
 9717:               start -> UNIX time for start of access
 9718: 
 9719:     value -> XML description of access control
 9720:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9721:             <start></start>
 9722:             <end></end>
 9723: 
 9724:             <password></password>  for scope type = guest
 9725: 
 9726:             <domain></domain>     for scope type = course or group
 9727:             <number></number>
 9728:             <roles id="">
 9729:              <role></role>
 9730:              <access></access>
 9731:              <section></section>
 9732:              <group></group>
 9733:             </roles>
 9734: 
 9735:             <dom></dom>         for scope type = domains
 9736: 
 9737:             <users>             for scope type = users
 9738:              <user>
 9739:               <uname></uname>
 9740:               <udom></udom>
 9741:              </user>
 9742:             </users>
 9743:            </scope> 
 9744:               
 9745:  Access data is also aggregated for each file in an additional key=value pair:
 9746:  key -> path to file/file_name\0accesscontrol 
 9747:  value -> reference to hash
 9748:           hash contains key = value pairs
 9749:           where key = uniqueID:scope_end_start
 9750:                 value = UNIX time record was last updated
 9751: 
 9752:           Used to improve speed of look-ups of access controls for each file.  
 9753:  
 9754:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9755: 
 9756: modify_access_controls():
 9757: 
 9758: Modifies access controls for a portfolio file
 9759: Args
 9760: 1. file name
 9761: 2. reference to hash of required changes,
 9762: 3. domain
 9763: 4. username
 9764:   where domain,username are the domain of the portfolio owner 
 9765:   (either a user or a course) 
 9766: 
 9767: Returns:
 9768: 1. result of additions or updates ('ok' or 'error', with error message). 
 9769: 2. result of deletions ('ok' or 'error', with error message).
 9770: 3. reference to hash of any new or updated access controls.
 9771: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9772:    key = integer (inbound ID)
 9773:    value = uniqueID  
 9774: 
 9775: =back
 9776: 
 9777: =head2 HTTP Helper Routines
 9778: 
 9779: =over 4
 9780: 
 9781: =item *
 9782: 
 9783: escape() : unpack non-word characters into CGI-compatible hex codes
 9784: 
 9785: =item *
 9786: 
 9787: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9788: 
 9789: =back
 9790: 
 9791: =head1 PRIVATE SUBROUTINES
 9792: 
 9793: =head2 Underlying communication routines (Shouldn't call)
 9794: 
 9795: =over 4
 9796: 
 9797: =item *
 9798: 
 9799: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9800: 
 9801: =item *
 9802: 
 9803: reply() : uses subreply to send a message to remote machine, logs all failures
 9804: 
 9805: =item *
 9806: 
 9807: critical() : passes a critical message to another server; if cannot
 9808: get through then place message in connection buffer directory and
 9809: returns con_delayed, if incapable of saving message, returns
 9810: con_failed
 9811: 
 9812: =item *
 9813: 
 9814: reconlonc() : tries to reconnect lonc client processes.
 9815: 
 9816: =back
 9817: 
 9818: =head2 Resource Access Logging
 9819: 
 9820: =over 4
 9821: 
 9822: =item *
 9823: 
 9824: flushcourselogs() : flush (save) buffer logs and access logs
 9825: 
 9826: =item *
 9827: 
 9828: courselog($what) : save message for course in hash
 9829: 
 9830: =item *
 9831: 
 9832: courseacclog($what) : save message for course using &courselog().  Perform
 9833: special processing for specific resource types (problems, exams, quizzes, etc).
 9834: 
 9835: =item *
 9836: 
 9837: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9838: as a PerlChildExitHandler
 9839: 
 9840: =back
 9841: 
 9842: =head2 Other
 9843: 
 9844: =over 4
 9845: 
 9846: =item *
 9847: 
 9848: symblist($mapname,%newhash) : update symbolic storage links
 9849: 
 9850: =back
 9851: 
 9852: =cut
 9853: 

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