File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.949: download - view: text, annotated - select for diffs
Wed Mar 12 02:46:27 2008 UTC (16 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Change arguments accepted by lonnet::appenv() to:
1. reference to hash
2. (optional) reference to array.

Change all instances where lonnet::appenv() is called to replace first argument passed (originally a hash) to a reference to the hash.

- Modify lonnet.pm rev 1.35 code intended to prevent "dangerous" modifications of the environment, so it will actually do this.
- Allow these modifications to be made in certain instances:
   DC switching to adhoc role
   CC switching to a different course role in the current course.
   user self-enrolling as a student

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.949 2008/03/12 02:46:27 raeburn 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)=@_;
  709:     $upass=&escape($upass);
  710:     $uname= &LONCAPA::clean_username($uname);
  711:     my $uhome=&homeserver($uname,$udom,1);
  712:     if ((!$uhome) || ($uhome eq 'no_host')) {
  713: # Maybe the machine was offline and only re-appeared again recently?
  714:         &reconlonc();
  715: # One more
  716: 	my $uhome=&homeserver($uname,$udom,1);
  717: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  718: 	    &logthis("User $uname at $udom is unknown in authenticate");
  719: 	}
  720: 	return 'no_host';
  721:     }
  722:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  723:     if ($answer eq 'authorized') {
  724: 	&logthis("User $uname at $udom authorized by $uhome"); 
  725: 	return $uhome; 
  726:     }
  727:     if ($answer eq 'non_authorized') {
  728: 	&logthis("User $uname at $udom rejected by $uhome");
  729: 	return 'no_host'; 
  730:     }
  731:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  732:     return 'no_host';
  733: }
  734: 
  735: # ---------------------- Find the homebase for a user from domain's lib servers
  736: 
  737: my %homecache;
  738: sub homeserver {
  739:     my ($uname,$udom,$ignoreBadCache)=@_;
  740:     my $index="$uname:$udom";
  741: 
  742:     if (exists($homecache{$index})) { return $homecache{$index}; }
  743: 
  744:     my %servers = &get_servers($udom,'library');
  745:     foreach my $tryserver (keys(%servers)) {
  746:         next if ($ignoreBadCache ne 'true' && 
  747: 		 exists($badServerCache{$tryserver}));
  748: 
  749: 	my $answer=reply("home:$udom:$uname",$tryserver);
  750: 	if ($answer eq 'found') {
  751: 	    delete($badServerCache{$tryserver}); 
  752: 	    return $homecache{$index}=$tryserver;
  753: 	} elsif ($answer eq 'no_host') {
  754: 	    $badServerCache{$tryserver}=1;
  755: 	}
  756:     }    
  757:     return 'no_host';
  758: }
  759: 
  760: # ------------------------------------- Find the usernames behind a list of IDs
  761: 
  762: sub idget {
  763:     my ($udom,@ids)=@_;
  764:     my %returnhash=();
  765:     
  766:     my %servers = &get_servers($udom,'library');
  767:     foreach my $tryserver (keys(%servers)) {
  768: 	my $idlist=join('&',@ids);
  769: 	$idlist=~tr/A-Z/a-z/; 
  770: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  771: 	my @answer=();
  772: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  773: 	    @answer=split(/\&/,$reply);
  774: 	}                    ;
  775: 	my $i;
  776: 	for ($i=0;$i<=$#ids;$i++) {
  777: 	    if ($answer[$i]) {
  778: 		$returnhash{$ids[$i]}=$answer[$i];
  779: 	    } 
  780: 	}
  781:     } 
  782:     return %returnhash;
  783: }
  784: 
  785: # ------------------------------------- Find the IDs behind a list of usernames
  786: 
  787: sub idrget {
  788:     my ($udom,@unames)=@_;
  789:     my %returnhash=();
  790:     foreach my $uname (@unames) {
  791:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  792:     }
  793:     return %returnhash;
  794: }
  795: 
  796: # ------------------------------- Store away a list of names and associated IDs
  797: 
  798: sub idput {
  799:     my ($udom,%ids)=@_;
  800:     my %servers=();
  801:     foreach my $uname (keys(%ids)) {
  802: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  803:         my $uhom=&homeserver($uname,$udom);
  804:         if ($uhom ne 'no_host') {
  805:             my $id=&escape($ids{$uname});
  806:             $id=~tr/A-Z/a-z/;
  807:             my $esc_unam=&escape($uname);
  808: 	    if ($servers{$uhom}) {
  809: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  810:             } else {
  811:                 $servers{$uhom}=$id.'='.$esc_unam;
  812:             }
  813:         }
  814:     }
  815:     foreach my $server (keys(%servers)) {
  816:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  817:     }
  818: }
  819: 
  820: # ------------------------------------------- get items from domain db files   
  821: 
  822: sub get_dom {
  823:     my ($namespace,$storearr,$udom,$uhome)=@_;
  824:     my $items='';
  825:     foreach my $item (@$storearr) {
  826:         $items.=&escape($item).'&';
  827:     }
  828:     $items=~s/\&$//;
  829:     if (!$udom) {
  830:         $udom=$env{'user.domain'};
  831:         if (defined(&domain($udom,'primary'))) {
  832:             $uhome=&domain($udom,'primary');
  833:         } else {
  834:             undef($uhome);
  835:         }
  836:     } else {
  837:         if (!$uhome) {
  838:             if (defined(&domain($udom,'primary'))) {
  839:                 $uhome=&domain($udom,'primary');
  840:             }
  841:         }
  842:     }
  843:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  844:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  845:         my %returnhash;
  846:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  847:             return %returnhash;
  848:         }
  849:         my @pairs=split(/\&/,$rep);
  850:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  851:             return @pairs;
  852:         }
  853:         my $i=0;
  854:         foreach my $item (@$storearr) {
  855:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  856:             $i++;
  857:         }
  858:         return %returnhash;
  859:     } else {
  860:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  861:     }
  862: }
  863: 
  864: # -------------------------------------------- put items in domain db files 
  865: 
  866: sub put_dom {
  867:     my ($namespace,$storehash,$udom,$uhome)=@_;
  868:     if (!$udom) {
  869:         $udom=$env{'user.domain'};
  870:         if (defined(&domain($udom,'primary'))) {
  871:             $uhome=&domain($udom,'primary');
  872:         } else {
  873:             undef($uhome);
  874:         }
  875:     } else {
  876:         if (!$uhome) {
  877:             if (defined(&domain($udom,'primary'))) {
  878:                 $uhome=&domain($udom,'primary');
  879:             }
  880:         }
  881:     } 
  882:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  883:         my $items='';
  884:         foreach my $item (keys(%$storehash)) {
  885:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  886:         }
  887:         $items=~s/\&$//;
  888:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  889:     } else {
  890:         &logthis("put_dom failed - no homeserver and/or domain");
  891:     }
  892: }
  893: 
  894: sub retrieve_inst_usertypes {
  895:     my ($udom) = @_;
  896:     my (%returnhash,@order);
  897:     if (defined(&domain($udom,'primary'))) {
  898:         my $uhome=&domain($udom,'primary');
  899:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  900:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  901:         my @pairs=split(/\&/,$hashitems);
  902:         foreach my $item (@pairs) {
  903:             my ($key,$value)=split(/=/,$item,2);
  904:             $key = &unescape($key);
  905:             next if ($key =~ /^error: 2 /);
  906:             $returnhash{$key}=&thaw_unescape($value);
  907:         }
  908:         my @esc_order = split(/\&/,$orderitems);
  909:         foreach my $item (@esc_order) {
  910:             push(@order,&unescape($item));
  911:         }
  912:     } else {
  913:         &logthis("get_dom failed - no primary domain server for $udom");
  914:     }
  915:     return (\%returnhash,\@order);
  916: }
  917: 
  918: sub is_domainimage {
  919:     my ($url) = @_;
  920:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  921:         if (&domain($1) ne '') {
  922:             return '1';
  923:         }
  924:     }
  925:     return;
  926: }
  927: 
  928: sub inst_directory_query {
  929:     my ($srch) = @_;
  930:     my $udom = $srch->{'srchdomain'};
  931:     my %results;
  932:     my $homeserver = &domain($udom,'primary');
  933:     my $outcome;
  934:     if ($homeserver ne '') {
  935: 	my $queryid=&reply("querysend:instdirsearch:".
  936: 			   &escape($srch->{'srchby'}).':'.
  937: 			   &escape($srch->{'srchterm'}).':'.
  938: 			   &escape($srch->{'srchtype'}),$homeserver);
  939: 	my $host=&hostname($homeserver);
  940: 	if ($queryid !~/^\Q$host\E\_/) {
  941: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  942: 	    return;
  943: 	}
  944: 	my $response = &get_query_reply($queryid);
  945: 	my $maxtries = 5;
  946: 	my $tries = 1;
  947: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  948: 	    $response = &get_query_reply($queryid);
  949: 	    $tries ++;
  950: 	}
  951: 
  952:         if (!&error($response) && $response ne 'refused') {
  953:             if ($response eq 'unavailable') {
  954:                 $outcome = $response;
  955:             } else {
  956:                 $outcome = 'ok';
  957:                 my @matches = split(/\n/,$response);
  958:                 foreach my $match (@matches) {
  959:                     my ($key,$value) = split(/=/,$match);
  960:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  961:                 }
  962:             }
  963:         }
  964:     }
  965:     return ($outcome,%results);
  966: }
  967: 
  968: sub usersearch {
  969:     my ($srch) = @_;
  970:     my $dom = $srch->{'srchdomain'};
  971:     my %results;
  972:     my %libserv = &all_library();
  973:     my $query = 'usersearch';
  974:     foreach my $tryserver (keys(%libserv)) {
  975:         if (&host_domain($tryserver) eq $dom) {
  976:             my $host=&hostname($tryserver);
  977:             my $queryid=
  978:                 &reply("querysend:".&escape($query).':'.
  979:                        &escape($srch->{'srchby'}).':'.
  980:                        &escape($srch->{'srchtype'}).':'.
  981:                        &escape($srch->{'srchterm'}),$tryserver);
  982:             if ($queryid !~/^\Q$host\E\_/) {
  983:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  984:                 next;
  985:             }
  986:             my $reply = &get_query_reply($queryid);
  987:             my $maxtries = 1;
  988:             my $tries = 1;
  989:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
  990:                 $reply = &get_query_reply($queryid);
  991:                 $tries ++;
  992:             }
  993:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
  994:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
  995:             } else {
  996:                 my @matches;
  997:                 if ($reply =~ /\n/) {
  998:                     @matches = split(/\n/,$reply);
  999:                 } else {
 1000:                     @matches = split(/\&/,$reply);
 1001:                 }
 1002:                 foreach my $match (@matches) {
 1003:                     my ($uname,$udom,%userhash);
 1004:                     foreach my $entry (split(/:/,$match)) {
 1005:                         my ($key,$value) =
 1006:                             map {&unescape($_);} split(/=/,$entry);
 1007:                         $userhash{$key} = $value;
 1008:                         if ($key eq 'username') {
 1009:                             $uname = $value;
 1010:                         } elsif ($key eq 'domain') {
 1011:                             $udom = $value;
 1012:                         }
 1013:                     }
 1014:                     $results{$uname.':'.$udom} = \%userhash;
 1015:                 }
 1016:             }
 1017:         }
 1018:     }
 1019:     return %results;
 1020: }
 1021: 
 1022: sub get_instuser {
 1023:     my ($udom,$uname,$id) = @_;
 1024:     my $homeserver = &domain($udom,'primary');
 1025:     my ($outcome,%results);
 1026:     if ($homeserver ne '') {
 1027:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1028:                            &escape($id).':'.&escape($udom),$homeserver);
 1029:         my $host=&hostname($homeserver);
 1030:         if ($queryid !~/^\Q$host\E\_/) {
 1031:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1032:             return;
 1033:         }
 1034:         my $response = &get_query_reply($queryid);
 1035:         my $maxtries = 5;
 1036:         my $tries = 1;
 1037:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1038:             $response = &get_query_reply($queryid);
 1039:             $tries ++;
 1040:         }
 1041:         if (!&error($response) && $response ne 'refused') {
 1042:             if ($response eq 'unavailable') {
 1043:                 $outcome = $response;
 1044:             } else {
 1045:                 $outcome = 'ok';
 1046:                 my @matches = split(/\n/,$response);
 1047:                 foreach my $match (@matches) {
 1048:                     my ($key,$value) = split(/=/,$match);
 1049:                     $results{&unescape($key)} = &thaw_unescape($value);
 1050:                 }
 1051:             }
 1052:         }
 1053:     }
 1054:     my %userinfo;
 1055:     if (ref($results{$uname}) eq 'HASH') {
 1056:         %userinfo = %{$results{$uname}};
 1057:     } 
 1058:     return ($outcome,%userinfo);
 1059: }
 1060: 
 1061: sub inst_rulecheck {
 1062:     my ($udom,$uname,$id,$item,$rules) = @_;
 1063:     my %returnhash;
 1064:     if ($udom ne '') {
 1065:         if (ref($rules) eq 'ARRAY') {
 1066:             @{$rules} = map {&escape($_);} (@{$rules});
 1067:             my $rulestr = join(':',@{$rules});
 1068:             my $homeserver=&domain($udom,'primary');
 1069:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1070:                 my $response;
 1071:                 if ($item eq 'username') {                
 1072:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1073:                                               ':'.&escape($uname).':'.$rulestr,
 1074:                                               $homeserver));
 1075:                 } elsif ($item eq 'id') {
 1076:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1077:                                               ':'.&escape($id).':'.$rulestr,
 1078:                                               $homeserver));
 1079:                 } elsif ($item eq 'selfcreate') {
 1080:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1081:                                                &escape($udom).':'.&escape($uname).
 1082:                                               ':'.$rulestr,$homeserver));
 1083:                 }
 1084:                 if ($response ne 'refused') {
 1085:                     my @pairs=split(/\&/,$response);
 1086:                     foreach my $item (@pairs) {
 1087:                         my ($key,$value)=split(/=/,$item,2);
 1088:                         $key = &unescape($key);
 1089:                         next if ($key =~ /^error: 2 /);
 1090:                         $returnhash{$key}=&thaw_unescape($value);
 1091:                     }
 1092:                 }
 1093:             }
 1094:         }
 1095:     }
 1096:     return %returnhash;
 1097: }
 1098: 
 1099: sub inst_userrules {
 1100:     my ($udom,$check) = @_;
 1101:     my (%ruleshash,@ruleorder);
 1102:     if ($udom ne '') {
 1103:         my $homeserver=&domain($udom,'primary');
 1104:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1105:             my $response;
 1106:             if ($check eq 'id') {
 1107:                 $response=&reply('instidrules:'.&escape($udom),
 1108:                                  $homeserver);
 1109:             } elsif ($check eq 'email') {
 1110:                 $response=&reply('instemailrules:'.&escape($udom),
 1111:                                  $homeserver);
 1112:             } else {
 1113:                 $response=&reply('instuserrules:'.&escape($udom),
 1114:                                  $homeserver);
 1115:             }
 1116:             if (($response ne 'refused') && ($response ne 'error') && 
 1117:                 ($response ne 'unknown_cmd') && 
 1118:                 ($response ne 'no_such_host')) {
 1119:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1120:                 my @pairs=split(/\&/,$hashitems);
 1121:                 foreach my $item (@pairs) {
 1122:                     my ($key,$value)=split(/=/,$item,2);
 1123:                     $key = &unescape($key);
 1124:                     next if ($key =~ /^error: 2 /);
 1125:                     $ruleshash{$key}=&thaw_unescape($value);
 1126:                 }
 1127:                 my @esc_order = split(/\&/,$orderitems);
 1128:                 foreach my $item (@esc_order) {
 1129:                     push(@ruleorder,&unescape($item));
 1130:                 }
 1131:             }
 1132:         }
 1133:     }
 1134:     return (\%ruleshash,\@ruleorder);
 1135: }
 1136: 
 1137: # ------------------------- Get Authentication and Language Defaults for Domain
 1138: 
 1139: sub get_domain_defaults {
 1140:     my ($domain) = @_;
 1141:     my $cachetime = 60*60*24;
 1142:     my ($defauthtype,$defautharg,$deflang);
 1143:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1144:     if (defined($cached)) {
 1145:         if (ref($result) eq 'HASH') {
 1146:             return %{$result};
 1147:         }
 1148:     }
 1149:     my %domdefaults;
 1150:     my %domconfig =
 1151:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
 1152:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1153:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1154:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1155:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1156:     } else {
 1157:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1158:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1159:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1160:     }
 1161:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1162:                                   $cachetime);
 1163:     return %domdefaults;
 1164: }
 1165: 
 1166: # --------------------------------------------------- Assign a key to a student
 1167: 
 1168: sub assign_access_key {
 1169: #
 1170: # a valid key looks like uname:udom#comments
 1171: # comments are being appended
 1172: #
 1173:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1174:     $kdom=
 1175:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1176:     $knum=
 1177:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1178:     $cdom=
 1179:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1180:     $cnum=
 1181:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1182:     $udom=$env{'user.name'} unless (defined($udom));
 1183:     $uname=$env{'user.domain'} unless (defined($uname));
 1184:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1185:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1186:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1187:                                                   # assigned to this person
 1188:                                                   # - this should not happen,
 1189:                                                   # unless something went wrong
 1190:                                                   # the first time around
 1191: # ready to assign
 1192:         $logentry=$1.'; '.$logentry;
 1193:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1194:                                                  $kdom,$knum) eq 'ok') {
 1195: # key now belongs to user
 1196: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1197:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1198:                 &appenv({'environment.'.$envkey => $ckey});
 1199:                 return 'ok';
 1200:             } else {
 1201:                 return 
 1202:   'error: Count not permanently assign key, will need to be re-entered later.';
 1203: 	    }
 1204:         } else {
 1205:             return 'error: Could not assign key, try again later.';
 1206:         }
 1207:     } elsif (!$existing{$ckey}) {
 1208: # the key does not exist
 1209: 	return 'error: The key does not exist';
 1210:     } else {
 1211: # the key is somebody else's
 1212: 	return 'error: The key is already in use';
 1213:     }
 1214: }
 1215: 
 1216: # ------------------------------------------ put an additional comment on a key
 1217: 
 1218: sub comment_access_key {
 1219: #
 1220: # a valid key looks like uname:udom#comments
 1221: # comments are being appended
 1222: #
 1223:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1224:     $cdom=
 1225:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1226:     $cnum=
 1227:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1228:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1229:     if ($existing{$ckey}) {
 1230:         $existing{$ckey}.='; '.$logentry;
 1231: # ready to assign
 1232:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1233:                                                  $cdom,$cnum) eq 'ok') {
 1234: 	    return 'ok';
 1235:         } else {
 1236: 	    return 'error: Count not store comment.';
 1237:         }
 1238:     } else {
 1239: # the key does not exist
 1240: 	return 'error: The key does not exist';
 1241:     }
 1242: }
 1243: 
 1244: # ------------------------------------------------------ Generate a set of keys
 1245: 
 1246: sub generate_access_keys {
 1247:     my ($number,$cdom,$cnum,$logentry)=@_;
 1248:     $cdom=
 1249:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1250:     $cnum=
 1251:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1252:     unless (&allowed('mky',$cdom)) { return 0; }
 1253:     unless (($cdom) && ($cnum)) { return 0; }
 1254:     if ($number>10000) { return 0; }
 1255:     sleep(2); # make sure don't get same seed twice
 1256:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1257:     my $total=0;
 1258:     for (my $i=1;$i<=$number;$i++) {
 1259:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1260:                   sprintf("%lx",int(100000*rand)).'-'.
 1261:                   sprintf("%lx",int(100000*rand));
 1262:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1263:        $newkey=~s/0/h/g; # and also 0 and O
 1264:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1265:        if ($existing{$newkey}) {
 1266:            $i--;
 1267:        } else {
 1268: 	  if (&put('accesskeys',
 1269:               { $newkey => '# generated '.localtime().
 1270:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1271:                            '; '.$logentry },
 1272: 		   $cdom,$cnum) eq 'ok') {
 1273:               $total++;
 1274: 	  }
 1275:        }
 1276:     }
 1277:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1278:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1279:     return $total;
 1280: }
 1281: 
 1282: # ------------------------------------------------------- Validate an accesskey
 1283: 
 1284: sub validate_access_key {
 1285:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1286:     $cdom=
 1287:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1288:     $cnum=
 1289:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1290:     $udom=$env{'user.domain'} unless (defined($udom));
 1291:     $uname=$env{'user.name'} unless (defined($uname));
 1292:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1293:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1294: }
 1295: 
 1296: # ------------------------------------- Find the section of student in a course
 1297: sub devalidate_getsection_cache {
 1298:     my ($udom,$unam,$courseid)=@_;
 1299:     my $hashid="$udom:$unam:$courseid";
 1300:     &devalidate_cache_new('getsection',$hashid);
 1301: }
 1302: 
 1303: sub courseid_to_courseurl {
 1304:     my ($courseid) = @_;
 1305:     #already url style courseid
 1306:     return $courseid if ($courseid =~ m{^/});
 1307: 
 1308:     if (exists($env{'course.'.$courseid.'.num'})) {
 1309: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1310: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1311: 	return "/$cdom/$cnum";
 1312:     }
 1313: 
 1314:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1315:     if (exists($courseinfo{'num'})) {
 1316: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1317:     }
 1318: 
 1319:     return undef;
 1320: }
 1321: 
 1322: sub getsection {
 1323:     my ($udom,$unam,$courseid)=@_;
 1324:     my $cachetime=1800;
 1325: 
 1326:     my $hashid="$udom:$unam:$courseid";
 1327:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1328:     if (defined($cached)) { return $result; }
 1329: 
 1330:     my %Pending; 
 1331:     my %Expired;
 1332:     #
 1333:     # Each role can either have not started yet (pending), be active, 
 1334:     #    or have expired.
 1335:     #
 1336:     # If there is an active role, we are done.
 1337:     #
 1338:     # If there is more than one role which has not started yet, 
 1339:     #     choose the one which will start sooner
 1340:     # If there is one role which has not started yet, return it.
 1341:     #
 1342:     # If there is more than one expired role, choose the one which ended last.
 1343:     # If there is a role which has expired, return it.
 1344:     #
 1345:     $courseid = &courseid_to_courseurl($courseid);
 1346:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1347:     foreach my $key (keys(%roleshash)) {
 1348:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1349:         my $section=$1;
 1350:         if ($key eq $courseid.'_st') { $section=''; }
 1351:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1352:         my $now=time;
 1353:         if (defined($end) && $end && ($now > $end)) {
 1354:             $Expired{$end}=$section;
 1355:             next;
 1356:         }
 1357:         if (defined($start) && $start && ($now < $start)) {
 1358:             $Pending{$start}=$section;
 1359:             next;
 1360:         }
 1361:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1362:     }
 1363:     #
 1364:     # Presumedly there will be few matching roles from the above
 1365:     # loop and the sorting time will be negligible.
 1366:     if (scalar(keys(%Pending))) {
 1367:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1368:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1369:     } 
 1370:     if (scalar(keys(%Expired))) {
 1371:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1372:         my $time = pop(@sorted);
 1373:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1374:     }
 1375:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1376: }
 1377: 
 1378: sub save_cache {
 1379:     &purge_remembered();
 1380:     #&Apache::loncommon::validate_page();
 1381:     undef(%env);
 1382:     undef($env_loaded);
 1383: }
 1384: 
 1385: my $to_remember=-1;
 1386: my %remembered;
 1387: my %accessed;
 1388: my $kicks=0;
 1389: my $hits=0;
 1390: sub make_key {
 1391:     my ($name,$id) = @_;
 1392:     if (length($id) > 65 
 1393: 	&& length(&escape($id)) > 200) {
 1394: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1395:     }
 1396:     return &escape($name.':'.$id);
 1397: }
 1398: 
 1399: sub devalidate_cache_new {
 1400:     my ($name,$id,$debug) = @_;
 1401:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1402:     $id=&make_key($name,$id);
 1403:     $memcache->delete($id);
 1404:     delete($remembered{$id});
 1405:     delete($accessed{$id});
 1406: }
 1407: 
 1408: sub is_cached_new {
 1409:     my ($name,$id,$debug) = @_;
 1410:     $id=&make_key($name,$id);
 1411:     if (exists($remembered{$id})) {
 1412: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1413: 	$accessed{$id}=[&gettimeofday()];
 1414: 	$hits++;
 1415: 	return ($remembered{$id},1);
 1416:     }
 1417:     my $value = $memcache->get($id);
 1418:     if (!(defined($value))) {
 1419: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1420: 	return (undef,undef);
 1421:     }
 1422:     if ($value eq '__undef__') {
 1423: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1424: 	$value=undef;
 1425:     }
 1426:     &make_room($id,$value,$debug);
 1427:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1428:     return ($value,1);
 1429: }
 1430: 
 1431: sub do_cache_new {
 1432:     my ($name,$id,$value,$time,$debug) = @_;
 1433:     $id=&make_key($name,$id);
 1434:     my $setvalue=$value;
 1435:     if (!defined($setvalue)) {
 1436: 	$setvalue='__undef__';
 1437:     }
 1438:     if (!defined($time) ) {
 1439: 	$time=600;
 1440:     }
 1441:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1442:     my $result = $memcache->set($id,$setvalue,$time);
 1443:     if (! $result) {
 1444: 	&logthis("caching of id -> $id  failed");
 1445: 	$memcache->disconnect_all();
 1446:     }
 1447:     # need to make a copy of $value
 1448:     &make_room($id,$value,$debug);
 1449:     return $value;
 1450: }
 1451: 
 1452: sub make_room {
 1453:     my ($id,$value,$debug)=@_;
 1454: 
 1455:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1456:                                     : $value;
 1457:     if ($to_remember<0) { return; }
 1458:     $accessed{$id}=[&gettimeofday()];
 1459:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1460:     my $to_kick;
 1461:     my $max_time=0;
 1462:     foreach my $other (keys(%accessed)) {
 1463: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1464: 	    $to_kick=$other;
 1465: 	    $max_time=&tv_interval($accessed{$other});
 1466: 	}
 1467:     }
 1468:     delete($remembered{$to_kick});
 1469:     delete($accessed{$to_kick});
 1470:     $kicks++;
 1471:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1472:     return;
 1473: }
 1474: 
 1475: sub purge_remembered {
 1476:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1477:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1478:     undef(%remembered);
 1479:     undef(%accessed);
 1480: }
 1481: # ------------------------------------- Read an entry from a user's environment
 1482: 
 1483: sub userenvironment {
 1484:     my ($udom,$unam,@what)=@_;
 1485:     my %returnhash=();
 1486:     my @answer=split(/\&/,
 1487:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1488:                       &homeserver($unam,$udom)));
 1489:     my $i;
 1490:     for ($i=0;$i<=$#what;$i++) {
 1491: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1492:     }
 1493:     return %returnhash;
 1494: }
 1495: 
 1496: # ---------------------------------------------------------- Get a studentphoto
 1497: sub studentphoto {
 1498:     my ($udom,$unam,$ext) = @_;
 1499:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1500:     if (defined($env{'request.course.id'})) {
 1501:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1502:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1503:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1504:             } else {
 1505:                 my ($result,$perm_reqd)=
 1506: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1507:                 if ($result eq 'ok') {
 1508:                     if (!($perm_reqd eq 'yes')) {
 1509:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1510:                     }
 1511:                 }
 1512:             }
 1513:         }
 1514:     } else {
 1515:         my ($result,$perm_reqd) = 
 1516: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1517:         if ($result eq 'ok') {
 1518:             if (!($perm_reqd eq 'yes')) {
 1519:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1520:             }
 1521:         }
 1522:     }
 1523:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1524: }
 1525: 
 1526: sub retrievestudentphoto {
 1527:     my ($udom,$unam,$ext,$type) = @_;
 1528:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1529:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1530:     if ($ret eq 'ok') {
 1531:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1532:         if ($type eq 'thumbnail') {
 1533:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1534:         }
 1535:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1536:         return $tokenurl;
 1537:     } else {
 1538:         if ($type eq 'thumbnail') {
 1539:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1540:         } else { 
 1541:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1542:         }
 1543:     }
 1544: }
 1545: 
 1546: # -------------------------------------------------------------------- New chat
 1547: 
 1548: sub chatsend {
 1549:     my ($newentry,$anon,$group)=@_;
 1550:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1551:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1552:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1553:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1554: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1555: 		   &escape($newentry)).':'.$group,$chome);
 1556: }
 1557: 
 1558: # ------------------------------------------ Find current version of a resource
 1559: 
 1560: sub getversion {
 1561:     my $fname=&clutter(shift);
 1562:     unless ($fname=~/^\/res\//) { return -1; }
 1563:     return &currentversion(&filelocation('',$fname));
 1564: }
 1565: 
 1566: sub currentversion {
 1567:     my $fname=shift;
 1568:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1569:     if (defined($cached)) { return $result; }
 1570:     my $author=$fname;
 1571:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1572:     my ($udom,$uname)=split(/\//,$author);
 1573:     my $home=homeserver($uname,$udom);
 1574:     if ($home eq 'no_host') { 
 1575:         return -1; 
 1576:     }
 1577:     my $answer=reply("currentversion:$fname",$home);
 1578:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1579: 	return -1;
 1580:     }
 1581:     return &do_cache_new('resversion',$fname,$answer,600);
 1582: }
 1583: 
 1584: # ----------------------------- Subscribe to a resource, return URL if possible
 1585: 
 1586: sub subscribe {
 1587:     my $fname=shift;
 1588:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1589:     $fname=~s/[\n\r]//g;
 1590:     my $author=$fname;
 1591:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1592:     my ($udom,$uname)=split(/\//,$author);
 1593:     my $home=homeserver($uname,$udom);
 1594:     if ($home eq 'no_host') {
 1595:         return 'not_found';
 1596:     }
 1597:     my $answer=reply("sub:$fname",$home);
 1598:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1599: 	$answer.=' by '.$home;
 1600:     }
 1601:     return $answer;
 1602: }
 1603:     
 1604: # -------------------------------------------------------------- Replicate file
 1605: 
 1606: sub repcopy {
 1607:     my $filename=shift;
 1608:     $filename=~s/\/+/\//g;
 1609:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1610:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1611:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1612: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1613: 	return &repcopy_userfile($filename);
 1614:     }
 1615:     $filename=~s/[\n\r]//g;
 1616:     my $transname="$filename.in.transfer";
 1617: # FIXME: this should flock
 1618:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1619:     my $remoteurl=subscribe($filename);
 1620:     if ($remoteurl =~ /^con_lost by/) {
 1621: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1622:            return 'unavailable';
 1623:     } elsif ($remoteurl eq 'not_found') {
 1624: 	   #&logthis("Subscribe returned not_found: $filename");
 1625: 	   return 'not_found';
 1626:     } elsif ($remoteurl =~ /^rejected by/) {
 1627: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1628:            return 'forbidden';
 1629:     } elsif ($remoteurl eq 'directory') {
 1630:            return 'ok';
 1631:     } else {
 1632:         my $author=$filename;
 1633:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1634:         my ($udom,$uname)=split(/\//,$author);
 1635:         my $home=homeserver($uname,$udom);
 1636:         unless ($home eq $perlvar{'lonHostID'}) {
 1637:            my @parts=split(/\//,$filename);
 1638:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1639:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1640:                &logthis("Malconfiguration for replication: $filename");
 1641: 	       return 'bad_request';
 1642:            }
 1643:            my $count;
 1644:            for ($count=5;$count<$#parts;$count++) {
 1645:                $path.="/$parts[$count]";
 1646:                if ((-e $path)!=1) {
 1647: 		   mkdir($path,0777);
 1648:                }
 1649:            }
 1650:            my $ua=new LWP::UserAgent;
 1651:            my $request=new HTTP::Request('GET',"$remoteurl");
 1652:            my $response=$ua->request($request,$transname);
 1653:            if ($response->is_error()) {
 1654: 	       unlink($transname);
 1655:                my $message=$response->status_line;
 1656:                &logthis("<font color=\"blue\">WARNING:"
 1657:                        ." LWP get: $message: $filename</font>");
 1658:                return 'unavailable';
 1659:            } else {
 1660: 	       if ($remoteurl!~/\.meta$/) {
 1661:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1662:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1663:                   if ($mresponse->is_error()) {
 1664: 		      unlink($filename.'.meta');
 1665:                       &logthis(
 1666:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1667:                   }
 1668: 	       }
 1669:                rename($transname,$filename);
 1670:                return 'ok';
 1671:            }
 1672:        }
 1673:     }
 1674: }
 1675: 
 1676: # ------------------------------------------------ Get server side include body
 1677: sub ssi_body {
 1678:     my ($filelink,%form)=@_;
 1679:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1680:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1681:     }
 1682:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1683:                                      &ssi($filelink,%form));
 1684:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1685:     $output=~s/^.*?\<body[^\>]*\>//si;
 1686:     $output=~s/\<\/body\s*\>.*?$//si;
 1687:     return $output;
 1688: }
 1689: 
 1690: # --------------------------------------------------------- Server Side Include
 1691: 
 1692: sub absolute_url {
 1693:     my ($host_name) = @_;
 1694:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1695:     if ($host_name eq '') {
 1696: 	$host_name = $ENV{'SERVER_NAME'};
 1697:     }
 1698:     return $protocol.$host_name;
 1699: }
 1700: 
 1701: #
 1702: #   Server side include.
 1703: # Parameters:
 1704: #  fn     Possibly encrypted resource name/id.
 1705: #  form   Hash that describes how the rendering should be done
 1706: #         and other things.
 1707: # Returns:
 1708: #   Scalar context: The content of the reply.
 1709: #   Array context:  2 element list of the content and the full response variable.
 1710: #     
 1711: # Returns:
 1712: #    The content of the response.
 1713: sub ssi {
 1714: 
 1715:     my ($fn,%form)=@_;
 1716:     my $count = scalar(@_);
 1717:     
 1718: 
 1719:     my $ua=new LWP::UserAgent;
 1720:     
 1721:     my $request;
 1722: 
 1723:     $form{'no_update_last_known'}=1;
 1724:     &Apache::lonenc::check_encrypt(\$fn);
 1725:     if (%form) {
 1726:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1727:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1728:     } else {
 1729:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1730:     }
 1731: 
 1732:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1733:     my $response=$ua->request($request);
 1734:     my $status = $response->code;
 1735: 
 1736:     if (wantarray) {
 1737: 	return ($response->content, $response);
 1738:     } else {
 1739: 	return $response->content;
 1740:     }
 1741: }
 1742: 
 1743: sub externalssi {
 1744:     my ($url)=@_;
 1745:     my $ua=new LWP::UserAgent;
 1746:     my $request=new HTTP::Request('GET',$url);
 1747:     my $response=$ua->request($request);
 1748:     return $response->content;
 1749: }
 1750: 
 1751: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1752: 
 1753: sub allowuploaded {
 1754:     my ($srcurl,$url)=@_;
 1755:     $url=&clutter(&declutter($url));
 1756:     my $dir=$url;
 1757:     $dir=~s/\/[^\/]+$//;
 1758:     my %httpref=();
 1759:     my $httpurl=&hreflocation('',$url);
 1760:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1761:     &Apache::lonnet::appenv(\%httpref);
 1762: }
 1763: 
 1764: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1765: # input: action, courseID, current domain, intended
 1766: #        path to file, source of file, instruction to parse file for objects,
 1767: #        ref to hash for embedded objects,
 1768: #        ref to hash for codebase of java objects.
 1769: #
 1770: # output: url to file (if action was uploaddoc), 
 1771: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1772: #
 1773: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1774: # course.
 1775: #
 1776: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1777: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1778: #          course's home server.
 1779: #
 1780: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1781: #          be copied from $source (current location) to 
 1782: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1783: #         and will then be copied to
 1784: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1785: #         course's home server.
 1786: #
 1787: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1788: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1789: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1790: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1791: #         in course's home server.
 1792: #
 1793: 
 1794: sub process_coursefile {
 1795:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1796:     my $fetchresult;
 1797:     my $home=&homeserver($docuname,$docudom);
 1798:     if ($action eq 'propagate') {
 1799:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1800: 			     $home);
 1801:     } else {
 1802:         my $fpath = '';
 1803:         my $fname = $file;
 1804:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1805:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1806:         my $filepath = &build_filepath($fpath);
 1807:         if ($action eq 'copy') {
 1808:             if ($source eq '') {
 1809:                 $fetchresult = 'no source file';
 1810:                 return $fetchresult;
 1811:             } else {
 1812:                 my $destination = $filepath.'/'.$fname;
 1813:                 rename($source,$destination);
 1814:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1815:                                  $home);
 1816:             }
 1817:         } elsif ($action eq 'uploaddoc') {
 1818:             open(my $fh,'>'.$filepath.'/'.$fname);
 1819:             print $fh $env{'form.'.$source};
 1820:             close($fh);
 1821:             if ($parser eq 'parse') {
 1822:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1823:                 unless ($parse_result eq 'ok') {
 1824:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1825:                 }
 1826:             }
 1827:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1828:                                  $home);
 1829:             if ($fetchresult eq 'ok') {
 1830:                 return '/uploaded/'.$fpath.'/'.$fname;
 1831:             } else {
 1832:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1833:                         ' to host '.$home.': '.$fetchresult);
 1834:                 return '/adm/notfound.html';
 1835:             }
 1836:         }
 1837:     }
 1838:     unless ( $fetchresult eq 'ok') {
 1839:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1840:              ' to host '.$home.': '.$fetchresult);
 1841:     }
 1842:     return $fetchresult;
 1843: }
 1844: 
 1845: sub build_filepath {
 1846:     my ($fpath) = @_;
 1847:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1848:     unless ($fpath eq '') {
 1849:         my @parts=split('/',$fpath);
 1850:         foreach my $part (@parts) {
 1851:             $filepath.= '/'.$part;
 1852:             if ((-e $filepath)!=1) {
 1853:                 mkdir($filepath,0777);
 1854:             }
 1855:         }
 1856:     }
 1857:     return $filepath;
 1858: }
 1859: 
 1860: sub store_edited_file {
 1861:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1862:     my $file = $primary_url;
 1863:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1864:     my $fpath = '';
 1865:     my $fname = $file;
 1866:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1867:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1868:     my $filepath = &build_filepath($fpath);
 1869:     open(my $fh,'>'.$filepath.'/'.$fname);
 1870:     print $fh $content;
 1871:     close($fh);
 1872:     my $home=&homeserver($docuname,$docudom);
 1873:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1874: 			  $home);
 1875:     if ($$fetchresult eq 'ok') {
 1876:         return '/uploaded/'.$fpath.'/'.$fname;
 1877:     } else {
 1878:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1879: 		 ' to host '.$home.': '.$$fetchresult);
 1880:         return '/adm/notfound.html';
 1881:     }
 1882: }
 1883: 
 1884: sub clean_filename {
 1885:     my ($fname,$args)=@_;
 1886: # Replace Windows backslashes by forward slashes
 1887:     $fname=~s/\\/\//g;
 1888:     if (!$args->{'keep_path'}) {
 1889:         # Get rid of everything but the actual filename
 1890: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1891:     }
 1892: # Replace spaces by underscores
 1893:     $fname=~s/\s+/\_/g;
 1894: # Replace all other weird characters by nothing
 1895:     $fname=~s{[^/\w\.\-]}{}g;
 1896: # Replace all .\d. sequences with _\d. so they no longer look like version
 1897: # numbers
 1898:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1899:     return $fname;
 1900: }
 1901: 
 1902: # --------------- Take an uploaded file and put it into the userfiles directory
 1903: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1904: #                    the desired filenam is in $env{"form.$formname.filename"}
 1905: #        $coursedoc - if true up to the current course
 1906: #                     if false
 1907: #        $subdir - directory in userfile to store the file into
 1908: #        $parser - instruction to parse file for objects ($parser = parse)    
 1909: #        $allfiles - reference to hash for embedded objects
 1910: #        $codebase - reference to hash for codebase of java objects
 1911: #        $desuname - username for permanent storage of uploaded file
 1912: #        $dsetudom - domain for permanaent storage of uploaded file
 1913: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1914: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1915: # 
 1916: # output: url of file in userspace, or error: <message> 
 1917: #             or /adm/notfound.html if failure to upload occurse
 1918: 
 1919: 
 1920: sub userfileupload {
 1921:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1922:         $destudom,$thumbwidth,$thumbheight)=@_;
 1923:     if (!defined($subdir)) { $subdir='unknown'; }
 1924:     my $fname=$env{'form.'.$formname.'.filename'};
 1925:     $fname=&clean_filename($fname);
 1926: # See if there is anything left
 1927:     unless ($fname) { return 'error: no uploaded file'; }
 1928:     chop($env{'form.'.$formname});
 1929:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1930:         my $now = time;
 1931:         my $filepath = 'tmp/helprequests/'.$now;
 1932:         my @parts=split(/\//,$filepath);
 1933:         my $fullpath = $perlvar{'lonDaemons'};
 1934:         for (my $i=0;$i<@parts;$i++) {
 1935:             $fullpath .= '/'.$parts[$i];
 1936:             if ((-e $fullpath)!=1) {
 1937:                 mkdir($fullpath,0777);
 1938:             }
 1939:         }
 1940:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1941:         print $fh $env{'form.'.$formname};
 1942:         close($fh);
 1943:         return $fullpath.'/'.$fname;
 1944:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1945:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1946:                        '_'.$env{'user.domain'}.'/pending';
 1947:         my @parts=split(/\//,$filepath);
 1948:         my $fullpath = $perlvar{'lonDaemons'};
 1949:         for (my $i=0;$i<@parts;$i++) {
 1950:             $fullpath .= '/'.$parts[$i];
 1951:             if ((-e $fullpath)!=1) {
 1952:                 mkdir($fullpath,0777);
 1953:             }
 1954:         }
 1955:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1956:         print $fh $env{'form.'.$formname};
 1957:         close($fh);
 1958:         return $fullpath.'/'.$fname;
 1959:     }
 1960:     
 1961: # Create the directory if not present
 1962:     $fname="$subdir/$fname";
 1963:     if ($coursedoc) {
 1964: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1965: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1966:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1967:             return &finishuserfileupload($docuname,$docudom,
 1968: 					 $formname,$fname,$parser,$allfiles,
 1969: 					 $codebase,$thumbwidth,$thumbheight);
 1970:         } else {
 1971:             $fname=$env{'form.folder'}.'/'.$fname;
 1972:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1973: 				       $fname,$formname,$parser,
 1974: 				       $allfiles,$codebase);
 1975:         }
 1976:     } elsif (defined($destuname)) {
 1977:         my $docuname=$destuname;
 1978:         my $docudom=$destudom;
 1979: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1980: 				     $parser,$allfiles,$codebase,
 1981:                                      $thumbwidth,$thumbheight);
 1982:         
 1983:     } else {
 1984:         my $docuname=$env{'user.name'};
 1985:         my $docudom=$env{'user.domain'};
 1986:         if (exists($env{'form.group'})) {
 1987:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1988:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1989:         }
 1990: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1991: 				     $parser,$allfiles,$codebase,
 1992:                                      $thumbwidth,$thumbheight);
 1993:     }
 1994: }
 1995: 
 1996: sub finishuserfileupload {
 1997:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1998:         $thumbwidth,$thumbheight) = @_;
 1999:     my $path=$docudom.'/'.$docuname.'/';
 2000:     my $filepath=$perlvar{'lonDocRoot'};
 2001:     my ($fnamepath,$file,$fetchthumb);
 2002:     $file=$fname;
 2003:     if ($fname=~m|/|) {
 2004:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2005: 	$path.=$fnamepath.'/';
 2006:     }
 2007:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2008:     my $count;
 2009:     for ($count=4;$count<=$#parts;$count++) {
 2010:         $filepath.="/$parts[$count]";
 2011:         if ((-e $filepath)!=1) {
 2012: 	    mkdir($filepath,0777);
 2013:         }
 2014:     }
 2015: # Save the file
 2016:     {
 2017: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2018: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2019: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2020: 	    return '/adm/notfound.html';
 2021: 	}
 2022: 	if (!print FH ($env{'form.'.$formname})) {
 2023: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2024: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2025: 	    return '/adm/notfound.html';
 2026: 	}
 2027: 	close(FH);
 2028:     }
 2029:     if ($parser eq 'parse') {
 2030:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 2031: 						   $codebase);
 2032:         unless ($parse_result eq 'ok') {
 2033:             &logthis('Failed to parse '.$filepath.$file.
 2034: 		     ' for embedded media: '.$parse_result); 
 2035:         }
 2036:     }
 2037:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2038:         my $input = $filepath.'/'.$file;
 2039:         my $output = $filepath.'/'.'tn-'.$file;
 2040:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2041:         system("convert -sample $thumbsize $input $output");
 2042:         if (-e $filepath.'/'.'tn-'.$file) {
 2043:             $fetchthumb  = 1; 
 2044:         }
 2045:     }
 2046:  
 2047: # Notify homeserver to grep it
 2048: #
 2049:     my $docuhome=&homeserver($docuname,$docudom);
 2050:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2051:     if ($fetchresult eq 'ok') {
 2052:         if ($fetchthumb) {
 2053:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2054:             if ($thumbresult ne 'ok') {
 2055:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2056:                          $docuhome.': '.$thumbresult);
 2057:             }
 2058:         }
 2059: #
 2060: # Return the URL to it
 2061:         return '/uploaded/'.$path.$file;
 2062:     } else {
 2063:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2064: 		 ': '.$fetchresult);
 2065:         return '/adm/notfound.html';
 2066:     }
 2067: }
 2068: 
 2069: sub extract_embedded_items {
 2070:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2071:     my @state = ();
 2072:     my %javafiles = (
 2073:                       codebase => '',
 2074:                       code => '',
 2075:                       archive => ''
 2076:                     );
 2077:     my %mediafiles = (
 2078:                       src => '',
 2079:                       movie => '',
 2080:                      );
 2081:     my $p;
 2082:     if ($content) {
 2083:         $p = HTML::LCParser->new($content);
 2084:     } else {
 2085:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2086:     }
 2087:     while (my $t=$p->get_token()) {
 2088: 	if ($t->[0] eq 'S') {
 2089: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2090: 	    push(@state, $tagname);
 2091:             if (lc($tagname) eq 'allow') {
 2092:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2093:             }
 2094: 	    if (lc($tagname) eq 'img') {
 2095: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2096: 	    }
 2097: 	    if (lc($tagname) eq 'a') {
 2098: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2099: 	    }
 2100:             if (lc($tagname) eq 'script') {
 2101:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2102:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2103:                 } else {
 2104:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2105:                 }
 2106:             }
 2107:             if (lc($tagname) eq 'link') {
 2108:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2109:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2110:                 }
 2111:             }
 2112: 	    if (lc($tagname) eq 'object' ||
 2113: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2114: 		foreach my $item (keys(%javafiles)) {
 2115: 		    $javafiles{$item} = '';
 2116: 		}
 2117: 	    }
 2118: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2119: 		my $name = lc($attr->{'name'});
 2120: 		foreach my $item (keys(%javafiles)) {
 2121: 		    if ($name eq $item) {
 2122: 			$javafiles{$item} = $attr->{'value'};
 2123: 			last;
 2124: 		    }
 2125: 		}
 2126: 		foreach my $item (keys(%mediafiles)) {
 2127: 		    if ($name eq $item) {
 2128: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2129: 			last;
 2130: 		    }
 2131: 		}
 2132: 	    }
 2133: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2134: 		foreach my $item (keys(%javafiles)) {
 2135: 		    if ($attr->{$item}) {
 2136: 			$javafiles{$item} = $attr->{$item};
 2137: 			last;
 2138: 		    }
 2139: 		}
 2140: 		foreach my $item (keys(%mediafiles)) {
 2141: 		    if ($attr->{$item}) {
 2142: 			&add_filetype($allfiles,$attr->{$item},$item);
 2143: 			last;
 2144: 		    }
 2145: 		}
 2146: 	    }
 2147: 	} elsif ($t->[0] eq 'E') {
 2148: 	    my ($tagname) = ($t->[1]);
 2149: 	    if ($javafiles{'codebase'} ne '') {
 2150: 		$javafiles{'codebase'} .= '/';
 2151: 	    }  
 2152: 	    if (lc($tagname) eq 'applet' ||
 2153: 		lc($tagname) eq 'object' ||
 2154: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2155: 		) {
 2156: 		foreach my $item (keys(%javafiles)) {
 2157: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2158: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2159: 			&add_filetype($allfiles,$file,$item);
 2160: 		    }
 2161: 		}
 2162: 	    } 
 2163: 	    pop @state;
 2164: 	}
 2165:     }
 2166:     return 'ok';
 2167: }
 2168: 
 2169: sub add_filetype {
 2170:     my ($allfiles,$file,$type)=@_;
 2171:     if (exists($allfiles->{$file})) {
 2172: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2173: 	    push(@{$allfiles->{$file}}, &escape($type));
 2174: 	}
 2175:     } else {
 2176: 	@{$allfiles->{$file}} = (&escape($type));
 2177:     }
 2178: }
 2179: 
 2180: sub removeuploadedurl {
 2181:     my ($url)=@_;
 2182:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2183:     return &removeuserfile($uname,$udom,$fname);
 2184: }
 2185: 
 2186: sub removeuserfile {
 2187:     my ($docuname,$docudom,$fname)=@_;
 2188:     my $home=&homeserver($docuname,$docudom);
 2189:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2190:     if ($result eq 'ok') {
 2191:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2192:             my $metafile = $fname.'.meta';
 2193:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2194: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2195:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2196:             my $sqlresult = 
 2197:                 &update_portfolio_table($docuname,$docudom,$file,
 2198:                                         'portfolio_metadata',$group,
 2199:                                         'delete');
 2200:         }
 2201:     }
 2202:     return $result;
 2203: }
 2204: 
 2205: sub mkdiruserfile {
 2206:     my ($docuname,$docudom,$dir)=@_;
 2207:     my $home=&homeserver($docuname,$docudom);
 2208:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2209: }
 2210: 
 2211: sub renameuserfile {
 2212:     my ($docuname,$docudom,$old,$new)=@_;
 2213:     my $home=&homeserver($docuname,$docudom);
 2214:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2215:                         &escape("$old").':'.&escape("$new"),$home);
 2216:     if ($result eq 'ok') {
 2217:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2218:             my $oldmeta = $old.'.meta';
 2219:             my $newmeta = $new.'.meta';
 2220:             my $metaresult = 
 2221:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2222: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2223:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2224:             my $sqlresult = 
 2225:                 &update_portfolio_table($docuname,$docudom,$file,
 2226:                                         'portfolio_metadata',$group,
 2227:                                         'delete');
 2228:         }
 2229:     }
 2230:     return $result;
 2231: }
 2232: 
 2233: # ------------------------------------------------------------------------- Log
 2234: 
 2235: sub log {
 2236:     my ($dom,$nam,$hom,$what)=@_;
 2237:     return critical("log:$dom:$nam:$what",$hom);
 2238: }
 2239: 
 2240: # ------------------------------------------------------------------ Course Log
 2241: #
 2242: # This routine flushes several buffers of non-mission-critical nature
 2243: #
 2244: 
 2245: sub flushcourselogs {
 2246:     &logthis('Flushing log buffers');
 2247: #
 2248: # course logs
 2249: # This is a log of all transactions in a course, which can be used
 2250: # for data mining purposes
 2251: #
 2252: # It also collects the courseid database, which lists last transaction
 2253: # times and course titles for all courseids
 2254: #
 2255:     my %courseidbuffer=();
 2256:     foreach my $crsid (keys(%courselogs)) {
 2257:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2258: 		          &escape($courselogs{$crsid}),
 2259: 		          $coursehombuf{$crsid}) eq 'ok') {
 2260: 	    delete $courselogs{$crsid};
 2261:         } else {
 2262:             &logthis('Failed to flush log buffer for '.$crsid);
 2263:             if (length($courselogs{$crsid})>40000) {
 2264:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2265:                         " exceeded maximum size, deleting.</font>");
 2266:                delete $courselogs{$crsid};
 2267:             }
 2268:         }
 2269:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2270:             'description' => $coursedescrbuf{$crsid},
 2271:             'inst_code'    => $courseinstcodebuf{$crsid},
 2272:             'type'        => $coursetypebuf{$crsid},
 2273:             'owner'       => $courseownerbuf{$crsid},
 2274:         };
 2275:     }
 2276: #
 2277: # Write course id database (reverse lookup) to homeserver of courses 
 2278: # Is used in pickcourse
 2279: #
 2280:     foreach my $crs_home (keys(%courseidbuffer)) {
 2281:         my $response = &courseidput(&host_domain($crs_home),
 2282:                                     $courseidbuffer{$crs_home},
 2283:                                     $crs_home,'timeonly');
 2284:     }
 2285: #
 2286: # File accesses
 2287: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2288: #
 2289:     foreach my $entry (keys(%accesshash)) {
 2290:         if ($entry =~ /___count$/) {
 2291:             my ($dom,$name);
 2292:             ($dom,$name,undef)=
 2293: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2294:             if (! defined($dom) || $dom eq '' || 
 2295:                 ! defined($name) || $name eq '') {
 2296:                 my $cid = $env{'request.course.id'};
 2297:                 $dom  = $env{'request.'.$cid.'.domain'};
 2298:                 $name = $env{'request.'.$cid.'.num'};
 2299:             }
 2300:             my $value = $accesshash{$entry};
 2301:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2302:             my %temphash=($url => $value);
 2303:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2304:             if ($result eq 'ok') {
 2305:                 delete $accesshash{$entry};
 2306:             } elsif ($result eq 'unknown_cmd') {
 2307:                 # Target server has old code running on it.
 2308:                 my %temphash=($entry => $value);
 2309:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2310:                     delete $accesshash{$entry};
 2311:                 }
 2312:             }
 2313:         } else {
 2314:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2315:             my %temphash=($entry => $accesshash{$entry});
 2316:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2317:                 delete $accesshash{$entry};
 2318:             }
 2319:         }
 2320:     }
 2321: #
 2322: # Roles
 2323: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2324: #
 2325:     foreach my $entry (keys(%userrolehash)) {
 2326:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2327: 	    split(/\:/,$entry);
 2328:         if (&Apache::lonnet::put('nohist_userroles',
 2329:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2330:                 $rudom,$runame) eq 'ok') {
 2331: 	    delete $userrolehash{$entry};
 2332:         }
 2333:     }
 2334: #
 2335: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2336: #
 2337:     my %domrolebuffer = ();
 2338:     foreach my $entry (keys %domainrolehash) {
 2339:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2340:         if ($domrolebuffer{$rudom}) {
 2341:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2342:                       '='.&escape($domainrolehash{$entry});
 2343:         } else {
 2344:             $domrolebuffer{$rudom}.=&escape($entry).
 2345:                       '='.&escape($domainrolehash{$entry});
 2346:         }
 2347:         delete $domainrolehash{$entry};
 2348:     }
 2349:     foreach my $dom (keys(%domrolebuffer)) {
 2350: 	my %servers = &get_servers($dom,'library');
 2351: 	foreach my $tryserver (keys(%servers)) {
 2352: 	    unless (&reply('domroleput:'.$dom.':'.
 2353: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2354: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2355: 	    }
 2356:         }
 2357:     }
 2358:     $dumpcount++;
 2359: }
 2360: 
 2361: sub courselog {
 2362:     my $what=shift;
 2363:     $what=time.':'.$what;
 2364:     unless ($env{'request.course.id'}) { return ''; }
 2365:     $coursedombuf{$env{'request.course.id'}}=
 2366:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2367:     $coursenumbuf{$env{'request.course.id'}}=
 2368:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2369:     $coursehombuf{$env{'request.course.id'}}=
 2370:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2371:     $coursedescrbuf{$env{'request.course.id'}}=
 2372:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2373:     $courseinstcodebuf{$env{'request.course.id'}}=
 2374:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2375:     $courseownerbuf{$env{'request.course.id'}}=
 2376:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2377:     $coursetypebuf{$env{'request.course.id'}}=
 2378:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2379:     if (defined $courselogs{$env{'request.course.id'}}) {
 2380: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2381:     } else {
 2382: 	$courselogs{$env{'request.course.id'}}.=$what;
 2383:     }
 2384:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2385: 	&flushcourselogs();
 2386:     }
 2387: }
 2388: 
 2389: sub courseacclog {
 2390:     my $fnsymb=shift;
 2391:     unless ($env{'request.course.id'}) { return ''; }
 2392:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2393:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2394:         $what.=':POST';
 2395:         # FIXME: Probably ought to escape things....
 2396: 	foreach my $key (keys(%env)) {
 2397:             if ($key=~/^form\.(.*)/) {
 2398: 		$what.=':'.$1.'='.$env{$key};
 2399:             }
 2400:         }
 2401:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2402:         # FIXME: We should not be depending on a form parameter that someone
 2403:         # editing lonsearchcat.pm might change in the future.
 2404:         if ($env{'form.phase'} eq 'course_search') {
 2405:             $what.= ':POST';
 2406:             # FIXME: Probably ought to escape things....
 2407:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2408:                                  'crsdiscuss') {
 2409:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2410:             }
 2411:         }
 2412:     }
 2413:     &courselog($what);
 2414: }
 2415: 
 2416: sub countacc {
 2417:     my $url=&declutter(shift);
 2418:     return if (! defined($url) || $url eq '');
 2419:     unless ($env{'request.course.id'}) { return ''; }
 2420:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2421:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2422:     $accesshash{$key}++;
 2423: }
 2424: 
 2425: sub linklog {
 2426:     my ($from,$to)=@_;
 2427:     $from=&declutter($from);
 2428:     $to=&declutter($to);
 2429:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2430:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2431: }
 2432:   
 2433: sub userrolelog {
 2434:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2435:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2436:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2437:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2438:         ($trole=~/^ta/)) {
 2439:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2440:        $userrolehash
 2441:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2442:                     =$tend.':'.$tstart;
 2443:     }
 2444:     if (($env{'request.role'} =~ /dc\./) &&
 2445: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2446: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2447: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2448:        $userrolehash
 2449:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2450:                     =$tend.':'.$tstart;
 2451:     }
 2452:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2453:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2454:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2455:         ($trole=~/^sc/)) {
 2456:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2457:        $domainrolehash
 2458:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2459:                     = $tend.':'.$tstart;
 2460:     }
 2461: }
 2462: 
 2463: sub get_course_adv_roles {
 2464:     my ($cid,$codes) = @_;
 2465:     $cid=$env{'request.course.id'} unless (defined($cid));
 2466:     my %coursehash=&coursedescription($cid);
 2467:     my %nothide=();
 2468:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2469:         if ($user !~ /:/) {
 2470: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2471:         } else {
 2472:             $nothide{$user}=1;
 2473:         }
 2474:     }
 2475:     my %returnhash=();
 2476:     my %dumphash=
 2477:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2478:     my $now=time;
 2479:     foreach my $entry (keys %dumphash) {
 2480: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2481:         if (($tstart) && ($tstart<0)) { next; }
 2482:         if (($tend) && ($tend<$now)) { next; }
 2483:         if (($tstart) && ($now<$tstart)) { next; }
 2484:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2485: 	if ($username eq '' || $domain eq '') { next; }
 2486: 	if ((&privileged($username,$domain)) && 
 2487: 	    (!$nothide{$username.':'.$domain})) { next; }
 2488: 	if ($role eq 'cr') { next; }
 2489:         if ($codes) {
 2490:             if ($section) { $role .= ':'.$section; }
 2491:             if ($returnhash{$role}) {
 2492:                 $returnhash{$role}.=','.$username.':'.$domain;
 2493:             } else {
 2494:                 $returnhash{$role}=$username.':'.$domain;
 2495:             }
 2496:         } else {
 2497:             my $key=&plaintext($role);
 2498:             if ($section) { $key.=' (Section '.$section.')'; }
 2499:             if ($returnhash{$key}) {
 2500: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2501:             } else {
 2502:                 $returnhash{$key}=$username.':'.$domain;
 2503:             }
 2504:         }
 2505:     }
 2506:     return %returnhash;
 2507: }
 2508: 
 2509: sub get_my_roles {
 2510:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2511:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2512:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2513:     my (%dumphash,%nothide);
 2514:     if ($context eq 'userroles') { 
 2515:         %dumphash = &dump('roles',$udom,$uname);
 2516:     } else {
 2517:         %dumphash=
 2518:             &dump('nohist_userroles',$udom,$uname);
 2519:         if ($hidepriv) {
 2520:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2521:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2522:                 if ($user !~ /:/) {
 2523:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2524:                 } else {
 2525:                     $nothide{$user} = 1;
 2526:                 }
 2527:             }
 2528:         }
 2529:     }
 2530:     my %returnhash=();
 2531:     my $now=time;
 2532:     foreach my $entry (keys(%dumphash)) {
 2533:         my ($role,$tend,$tstart);
 2534:         if ($context eq 'userroles') {
 2535: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2536:         } else {
 2537:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2538:         }
 2539:         if (($tstart) && ($tstart<0)) { next; }
 2540:         my $status = 'active';
 2541:         if (($tend) && ($tend<=$now)) {
 2542:             $status = 'previous';
 2543:         } 
 2544:         if (($tstart) && ($now<$tstart)) {
 2545:             $status = 'future';
 2546:         }
 2547:         if (ref($types) eq 'ARRAY') {
 2548:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2549:                 next;
 2550:             } 
 2551:         } else {
 2552:             if ($status ne 'active') {
 2553:                 next;
 2554:             }
 2555:         }
 2556:         my ($rolecode,$username,$domain,$section,$area);
 2557:         if ($context eq 'userroles') {
 2558:             ($area,$rolecode) = split(/_/,$entry);
 2559:             (undef,$domain,$username,$section) = split(/\//,$area);
 2560:         } else {
 2561:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2562:         }
 2563:         if (ref($roledoms) eq 'ARRAY') {
 2564:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2565:                 next;
 2566:             }
 2567:         }
 2568:         if (ref($roles) eq 'ARRAY') {
 2569:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2570:                 if ($role =~ /^cr\//) {
 2571:                     if (!grep(/^cr$/,@{$roles})) {
 2572:                         next;
 2573:                     }
 2574:                 } else {
 2575:                     next;
 2576:                 }
 2577:             }
 2578:         }
 2579:         if ($hidepriv) {
 2580:             if ((&privileged($username,$domain)) &&
 2581:                 (!$nothide{$username.':'.$domain})) { 
 2582:                 next;
 2583:             }
 2584:         }
 2585:         if ($withsec) {
 2586:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2587:                 $tstart.':'.$tend;
 2588:         } else {
 2589:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2590:         }
 2591:     }
 2592:     return %returnhash;
 2593: }
 2594: 
 2595: # ----------------------------------------------------- Frontpage Announcements
 2596: #
 2597: #
 2598: 
 2599: sub postannounce {
 2600:     my ($server,$text)=@_;
 2601:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2602:     unless ($text=~/\w/) { $text=''; }
 2603:     return &reply('setannounce:'.&escape($text),$server);
 2604: }
 2605: 
 2606: sub getannounce {
 2607: 
 2608:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2609: 	my $announcement='';
 2610: 	while (my $line = <$fh>) { $announcement .= $line; }
 2611: 	close($fh);
 2612: 	if ($announcement=~/\w/) { 
 2613: 	    return 
 2614:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2615:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2616: 	} else {
 2617: 	    return '';
 2618: 	}
 2619:     } else {
 2620: 	return '';
 2621:     }
 2622: }
 2623: 
 2624: # ---------------------------------------------------------- Course ID routines
 2625: # Deal with domain's nohist_courseid.db files
 2626: #
 2627: 
 2628: sub courseidput {
 2629:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2630:     my $outcome;
 2631:     if ($caller eq 'timeonly') {
 2632:         my $cids = '';
 2633:         foreach my $item (keys(%$storehash)) {
 2634:             $cids.=&escape($item).'&';
 2635:         }
 2636:         $cids=~s/\&$//;
 2637:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2638:                           $coursehome);       
 2639:     } else {
 2640:         my $items = '';
 2641:         foreach my $item (keys(%$storehash)) {
 2642:             $items.= &escape($item).'='.
 2643:                      &freeze_escape($$storehash{$item}).'&';
 2644:         }
 2645:         $items=~s/\&$//;
 2646:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2647:                           $coursehome);
 2648:     }
 2649:     if ($outcome eq 'unknown_cmd') {
 2650:         my $what;
 2651:         foreach my $cid (keys(%$storehash)) {
 2652:             $what .= &escape($cid).'=';
 2653:             foreach my $item ('description','inst_code','owner','type') {
 2654:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2655:             }
 2656:             $what =~ s/\:$/&/;
 2657:         }
 2658:         $what =~ s/\&$//;  
 2659:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2660:     } else {
 2661:         return $outcome;
 2662:     }
 2663: }
 2664: 
 2665: sub courseiddump {
 2666:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2667:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2668:         $selfenrollonly)=@_;
 2669:     my $as_hash = 1;
 2670:     my %returnhash;
 2671:     if (!$domfilter) { $domfilter=''; }
 2672:     my %libserv = &all_library();
 2673:     foreach my $tryserver (keys(%libserv)) {
 2674:         if ( (  $hostidflag == 1 
 2675: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2676: 	     || (!defined($hostidflag)) ) {
 2677: 
 2678: 	    if (($domfilter eq '') ||
 2679: 		(&host_domain($tryserver) eq $domfilter)) {
 2680:                 my $rep = 
 2681:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2682:                          $sincefilter.':'.&escape($descfilter).':'.
 2683:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2684:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2685:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2686:                          &escape($selfenrollonly),$tryserver);
 2687:                 my @pairs=split(/\&/,$rep);
 2688:                 foreach my $item (@pairs) {
 2689:                     my ($key,$value)=split(/\=/,$item,2);
 2690:                     $key = &unescape($key);
 2691:                     next if ($key =~ /^error: 2 /);
 2692:                     my $result = &thaw_unescape($value);
 2693:                     if (ref($result) eq 'HASH') {
 2694:                         $returnhash{$key}=$result;
 2695:                     } else {
 2696:                         my @responses = split(/:/,$value);
 2697:                         my @items = ('description','inst_code','owner','type');
 2698:                         for (my $i=0; $i<@responses; $i++) {
 2699:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2700:                         }
 2701:                     } 
 2702:                 }
 2703:             }
 2704:         }
 2705:     }
 2706:     return %returnhash;
 2707: }
 2708: 
 2709: # ---------------------------------------------------------- DC e-mail
 2710: 
 2711: sub dcmailput {
 2712:     my ($domain,$msgid,$message,$server)=@_;
 2713:     my $status = &Apache::lonnet::critical(
 2714:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2715:        &escape($message),$server);
 2716:     return $status;
 2717: }
 2718: 
 2719: sub dcmaildump {
 2720:     my ($dom,$startdate,$enddate,$senders) = @_;
 2721:     my %returnhash=();
 2722: 
 2723:     if (defined(&domain($dom,'primary'))) {
 2724:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2725:                                                          &escape($enddate).':';
 2726: 	my @esc_senders=map { &escape($_)} @$senders;
 2727: 	$cmd.=&escape(join('&',@esc_senders));
 2728: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2729:             my ($key,$value) = split(/\=/,$line,2);
 2730:             if (($key) && ($value)) {
 2731:                 $returnhash{&unescape($key)} = &unescape($value);
 2732:             }
 2733:         }
 2734:     }
 2735:     return %returnhash;
 2736: }
 2737: # ---------------------------------------------------------- Domain roles
 2738: 
 2739: sub get_domain_roles {
 2740:     my ($dom,$roles,$startdate,$enddate)=@_;
 2741:     if (undef($startdate) || $startdate eq '') {
 2742:         $startdate = '.';
 2743:     }
 2744:     if (undef($enddate) || $enddate eq '') {
 2745:         $enddate = '.';
 2746:     }
 2747:     my $rolelist;
 2748:     if (ref($roles) eq 'ARRAY') {
 2749:         $rolelist = join(':',@{$roles});
 2750:     }
 2751:     my %personnel = ();
 2752: 
 2753:     my %servers = &get_servers($dom,'library');
 2754:     foreach my $tryserver (keys(%servers)) {
 2755: 	%{$personnel{$tryserver}}=();
 2756: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2757: 					    &escape($startdate).':'.
 2758: 					    &escape($enddate).':'.
 2759: 					    &escape($rolelist), $tryserver))) {
 2760: 	    my ($key,$value) = split(/\=/,$line,2);
 2761: 	    if (($key) && ($value)) {
 2762: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2763: 	    }
 2764: 	}
 2765:     }
 2766:     return %personnel;
 2767: }
 2768: 
 2769: # ----------------------------------------------------------- Check out an item
 2770: 
 2771: sub get_first_access {
 2772:     my ($type,$argsymb)=@_;
 2773:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2774:     if ($argsymb) { $symb=$argsymb; }
 2775:     my ($map,$id,$res)=&decode_symb($symb);
 2776:     if ($type eq 'course') {
 2777: 	$res='course';
 2778:     } elsif ($type eq 'map') {
 2779: 	$res=&symbread($map);
 2780:     } else {
 2781: 	$res=$symb;
 2782:     }
 2783:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2784:     return $times{"$courseid\0$res"};
 2785: }
 2786: 
 2787: sub set_first_access {
 2788:     my ($type)=@_;
 2789:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2790:     my ($map,$id,$res)=&decode_symb($symb);
 2791:     if ($type eq 'course') {
 2792: 	$res='course';
 2793:     } elsif ($type eq 'map') {
 2794: 	$res=&symbread($map);
 2795:     } else {
 2796: 	$res=$symb;
 2797:     }
 2798:     my $firstaccess=&get_first_access($type,$symb);
 2799:     if (!$firstaccess) {
 2800: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2801:     }
 2802:     return 'already_set';
 2803: }
 2804: 
 2805: sub checkout {
 2806:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2807:     my $now=time;
 2808:     my $lonhost=$perlvar{'lonHostID'};
 2809:     my $infostr=&escape(
 2810:                  'CHECKOUTTOKEN&'.
 2811:                  $tuname.'&'.
 2812:                  $tudom.'&'.
 2813:                  $tcrsid.'&'.
 2814:                  $symb.'&'.
 2815: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2816:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2817:     if ($token=~/^error\:/) { 
 2818:         &logthis("<font color=\"blue\">WARNING: ".
 2819:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2820:                  "</font>");
 2821:         return ''; 
 2822:     }
 2823: 
 2824:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2825:     $token=~tr/a-z/A-Z/;
 2826: 
 2827:     my %infohash=('resource.0.outtoken' => $token,
 2828:                   'resource.0.checkouttime' => $now,
 2829:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2830: 
 2831:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2832:        return '';
 2833:     } else {
 2834:         &logthis("<font color=\"blue\">WARNING: ".
 2835:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2836:                  "</font>");
 2837:     }    
 2838: 
 2839:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2840:                          &escape('Checkout '.$infostr.' - '.
 2841:                                                  $token)) ne 'ok') {
 2842: 	return '';
 2843:     } else {
 2844:         &logthis("<font color=\"blue\">WARNING: ".
 2845:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2846:                  "</font>");
 2847:     }
 2848:     return $token;
 2849: }
 2850: 
 2851: # ------------------------------------------------------------ Check in an item
 2852: 
 2853: sub checkin {
 2854:     my $token=shift;
 2855:     my $now=time;
 2856:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2857:     $lonhost=~tr/A-Z/a-z/;
 2858:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2859:     $dtoken=~s/\W/\_/g;
 2860:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2861:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2862: 
 2863:     unless (($tuname) && ($tudom)) {
 2864:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2865:         return '';
 2866:     }
 2867:     
 2868:     unless (&allowed('mgr',$tcrsid)) {
 2869:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2870:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2871:         return '';
 2872:     }
 2873: 
 2874:     my %infohash=('resource.0.intoken' => $token,
 2875:                   'resource.0.checkintime' => $now,
 2876:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2877: 
 2878:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2879:        return '';
 2880:     }    
 2881: 
 2882:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2883:                          &escape('Checkin - '.$token)) ne 'ok') {
 2884: 	return '';
 2885:     }
 2886: 
 2887:     return ($symb,$tuname,$tudom,$tcrsid);    
 2888: }
 2889: 
 2890: # --------------------------------------------- Set Expire Date for Spreadsheet
 2891: 
 2892: sub expirespread {
 2893:     my ($uname,$udom,$stype,$usymb)=@_;
 2894:     my $cid=$env{'request.course.id'}; 
 2895:     if ($cid) {
 2896:        my $now=time;
 2897:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2898:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2899:                             $env{'course.'.$cid.'.num'}.
 2900: 	        	    ':nohist_expirationdates:'.
 2901:                             &escape($key).'='.$now,
 2902:                             $env{'course.'.$cid.'.home'})
 2903:     }
 2904:     return 'ok';
 2905: }
 2906: 
 2907: # ----------------------------------------------------- Devalidate Spreadsheets
 2908: 
 2909: sub devalidate {
 2910:     my ($symb,$uname,$udom)=@_;
 2911:     my $cid=$env{'request.course.id'}; 
 2912:     if ($cid) {
 2913:         # delete the stored spreadsheets for
 2914:         # - the student level sheet of this user in course's homespace
 2915:         # - the assessment level sheet for this resource 
 2916:         #   for this user in user's homespace
 2917: 	# - current conditional state info
 2918: 	my $key=$uname.':'.$udom.':';
 2919:         my $status=
 2920: 	    &del('nohist_calculatedsheets',
 2921: 		 [$key.'studentcalc:'],
 2922: 		 $env{'course.'.$cid.'.domain'},
 2923: 		 $env{'course.'.$cid.'.num'})
 2924: 		.' '.
 2925: 	    &del('nohist_calculatedsheets_'.$cid,
 2926: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2927:         unless ($status eq 'ok ok') {
 2928:            &logthis('Could not devalidate spreadsheet '.
 2929:                     $uname.' at '.$udom.' for '.
 2930: 		    $symb.': '.$status);
 2931:         }
 2932: 	&delenv('user.state.'.$cid);
 2933:     }
 2934: }
 2935: 
 2936: sub get_scalar {
 2937:     my ($string,$end) = @_;
 2938:     my $value;
 2939:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2940: 	$value = $1;
 2941:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2942: 	$value = $1;
 2943:     }
 2944:     return &unescape($value);
 2945: }
 2946: 
 2947: sub array2str {
 2948:   my (@array) = @_;
 2949:   my $result=&arrayref2str(\@array);
 2950:   $result=~s/^__ARRAY_REF__//;
 2951:   $result=~s/__END_ARRAY_REF__$//;
 2952:   return $result;
 2953: }
 2954: 
 2955: sub arrayref2str {
 2956:   my ($arrayref) = @_;
 2957:   my $result='__ARRAY_REF__';
 2958:   foreach my $elem (@$arrayref) {
 2959:     if(ref($elem) eq 'ARRAY') {
 2960:       $result.=&arrayref2str($elem).'&';
 2961:     } elsif(ref($elem) eq 'HASH') {
 2962:       $result.=&hashref2str($elem).'&';
 2963:     } elsif(ref($elem)) {
 2964:       #print("Got a ref of ".(ref($elem))." skipping.");
 2965:     } else {
 2966:       $result.=&escape($elem).'&';
 2967:     }
 2968:   }
 2969:   $result=~s/\&$//;
 2970:   $result .= '__END_ARRAY_REF__';
 2971:   return $result;
 2972: }
 2973: 
 2974: sub hash2str {
 2975:   my (%hash) = @_;
 2976:   my $result=&hashref2str(\%hash);
 2977:   $result=~s/^__HASH_REF__//;
 2978:   $result=~s/__END_HASH_REF__$//;
 2979:   return $result;
 2980: }
 2981: 
 2982: sub hashref2str {
 2983:   my ($hashref)=@_;
 2984:   my $result='__HASH_REF__';
 2985:   foreach my $key (sort(keys(%$hashref))) {
 2986:     if (ref($key) eq 'ARRAY') {
 2987:       $result.=&arrayref2str($key).'=';
 2988:     } elsif (ref($key) eq 'HASH') {
 2989:       $result.=&hashref2str($key).'=';
 2990:     } elsif (ref($key)) {
 2991:       $result.='=';
 2992:       #print("Got a ref of ".(ref($key))." skipping.");
 2993:     } else {
 2994: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2995:     }
 2996: 
 2997:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2998:       $result.=&arrayref2str($hashref->{$key}).'&';
 2999:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3000:       $result.=&hashref2str($hashref->{$key}).'&';
 3001:     } elsif(ref($hashref->{$key})) {
 3002:        $result.='&';
 3003:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3004:     } else {
 3005:       $result.=&escape($hashref->{$key}).'&';
 3006:     }
 3007:   }
 3008:   $result=~s/\&$//;
 3009:   $result .= '__END_HASH_REF__';
 3010:   return $result;
 3011: }
 3012: 
 3013: sub str2hash {
 3014:     my ($string)=@_;
 3015:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3016:     return %$hash;
 3017: }
 3018: 
 3019: sub str2hashref {
 3020:   my ($string) = @_;
 3021: 
 3022:   my %hash;
 3023: 
 3024:   if($string !~ /^__HASH_REF__/) {
 3025:       if (! ($string eq '' || !defined($string))) {
 3026: 	  $hash{'error'}='Not hash reference';
 3027:       }
 3028:       return (\%hash, $string);
 3029:   }
 3030: 
 3031:   $string =~ s/^__HASH_REF__//;
 3032: 
 3033:   while($string !~ /^__END_HASH_REF__/) {
 3034:       #key
 3035:       my $key='';
 3036:       if($string =~ /^__HASH_REF__/) {
 3037:           ($key, $string)=&str2hashref($string);
 3038:           if(defined($key->{'error'})) {
 3039:               $hash{'error'}='Bad data';
 3040:               return (\%hash, $string);
 3041:           }
 3042:       } elsif($string =~ /^__ARRAY_REF__/) {
 3043:           ($key, $string)=&str2arrayref($string);
 3044:           if($key->[0] eq 'Array reference error') {
 3045:               $hash{'error'}='Bad data';
 3046:               return (\%hash, $string);
 3047:           }
 3048:       } else {
 3049:           $string =~ s/^(.*?)=//;
 3050: 	  $key=&unescape($1);
 3051:       }
 3052:       $string =~ s/^=//;
 3053: 
 3054:       #value
 3055:       my $value='';
 3056:       if($string =~ /^__HASH_REF__/) {
 3057:           ($value, $string)=&str2hashref($string);
 3058:           if(defined($value->{'error'})) {
 3059:               $hash{'error'}='Bad data';
 3060:               return (\%hash, $string);
 3061:           }
 3062:       } elsif($string =~ /^__ARRAY_REF__/) {
 3063:           ($value, $string)=&str2arrayref($string);
 3064:           if($value->[0] eq 'Array reference error') {
 3065:               $hash{'error'}='Bad data';
 3066:               return (\%hash, $string);
 3067:           }
 3068:       } else {
 3069: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3070:       }
 3071:       $string =~ s/^&//;
 3072: 
 3073:       $hash{$key}=$value;
 3074:   }
 3075: 
 3076:   $string =~ s/^__END_HASH_REF__//;
 3077: 
 3078:   return (\%hash, $string);
 3079: }
 3080: 
 3081: sub str2array {
 3082:     my ($string)=@_;
 3083:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3084:     return @$array;
 3085: }
 3086: 
 3087: sub str2arrayref {
 3088:   my ($string) = @_;
 3089:   my @array;
 3090: 
 3091:   if($string !~ /^__ARRAY_REF__/) {
 3092:       if (! ($string eq '' || !defined($string))) {
 3093: 	  $array[0]='Array reference error';
 3094:       }
 3095:       return (\@array, $string);
 3096:   }
 3097: 
 3098:   $string =~ s/^__ARRAY_REF__//;
 3099: 
 3100:   while($string !~ /^__END_ARRAY_REF__/) {
 3101:       my $value='';
 3102:       if($string =~ /^__HASH_REF__/) {
 3103:           ($value, $string)=&str2hashref($string);
 3104:           if(defined($value->{'error'})) {
 3105:               $array[0] ='Array reference error';
 3106:               return (\@array, $string);
 3107:           }
 3108:       } elsif($string =~ /^__ARRAY_REF__/) {
 3109:           ($value, $string)=&str2arrayref($string);
 3110:           if($value->[0] eq 'Array reference error') {
 3111:               $array[0] ='Array reference error';
 3112:               return (\@array, $string);
 3113:           }
 3114:       } else {
 3115: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3116:       }
 3117:       $string =~ s/^&//;
 3118: 
 3119:       push(@array, $value);
 3120:   }
 3121: 
 3122:   $string =~ s/^__END_ARRAY_REF__//;
 3123: 
 3124:   return (\@array, $string);
 3125: }
 3126: 
 3127: # -------------------------------------------------------------------Temp Store
 3128: 
 3129: sub tmpreset {
 3130:   my ($symb,$namespace,$domain,$stuname) = @_;
 3131:   if (!$symb) {
 3132:     $symb=&symbread();
 3133:     if (!$symb) { $symb= $env{'request.url'}; }
 3134:   }
 3135:   $symb=escape($symb);
 3136: 
 3137:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3138:   $namespace=~s/\//\_/g;
 3139:   $namespace=~s/\W//g;
 3140: 
 3141:   if (!$domain) { $domain=$env{'user.domain'}; }
 3142:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3143:   if ($domain eq 'public' && $stuname eq 'public') {
 3144:       $stuname=$ENV{'REMOTE_ADDR'};
 3145:   }
 3146:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3147:   my %hash;
 3148:   if (tie(%hash,'GDBM_File',
 3149: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3150: 	  &GDBM_WRCREAT(),0640)) {
 3151:     foreach my $key (keys %hash) {
 3152:       if ($key=~ /:$symb/) {
 3153: 	delete($hash{$key});
 3154:       }
 3155:     }
 3156:   }
 3157: }
 3158: 
 3159: sub tmpstore {
 3160:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3161: 
 3162:   if (!$symb) {
 3163:     $symb=&symbread();
 3164:     if (!$symb) { $symb= $env{'request.url'}; }
 3165:   }
 3166:   $symb=escape($symb);
 3167: 
 3168:   if (!$namespace) {
 3169:     # I don't think we would ever want to store this for a course.
 3170:     # it seems this will only be used if we don't have a course.
 3171:     #$namespace=$env{'request.course.id'};
 3172:     #if (!$namespace) {
 3173:       $namespace=$env{'request.state'};
 3174:     #}
 3175:   }
 3176:   $namespace=~s/\//\_/g;
 3177:   $namespace=~s/\W//g;
 3178:   if (!$domain) { $domain=$env{'user.domain'}; }
 3179:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3180:   if ($domain eq 'public' && $stuname eq 'public') {
 3181:       $stuname=$ENV{'REMOTE_ADDR'};
 3182:   }
 3183:   my $now=time;
 3184:   my %hash;
 3185:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3186:   if (tie(%hash,'GDBM_File',
 3187: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3188: 	  &GDBM_WRCREAT(),0640)) {
 3189:     $hash{"version:$symb"}++;
 3190:     my $version=$hash{"version:$symb"};
 3191:     my $allkeys=''; 
 3192:     foreach my $key (keys(%$storehash)) {
 3193:       $allkeys.=$key.':';
 3194:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3195:     }
 3196:     $hash{"$version:$symb:timestamp"}=$now;
 3197:     $allkeys.='timestamp';
 3198:     $hash{"$version:keys:$symb"}=$allkeys;
 3199:     if (untie(%hash)) {
 3200:       return 'ok';
 3201:     } else {
 3202:       return "error:$!";
 3203:     }
 3204:   } else {
 3205:     return "error:$!";
 3206:   }
 3207: }
 3208: 
 3209: # -----------------------------------------------------------------Temp Restore
 3210: 
 3211: sub tmprestore {
 3212:   my ($symb,$namespace,$domain,$stuname) = @_;
 3213: 
 3214:   if (!$symb) {
 3215:     $symb=&symbread();
 3216:     if (!$symb) { $symb= $env{'request.url'}; }
 3217:   }
 3218:   $symb=escape($symb);
 3219: 
 3220:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3221: 
 3222:   if (!$domain) { $domain=$env{'user.domain'}; }
 3223:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3224:   if ($domain eq 'public' && $stuname eq 'public') {
 3225:       $stuname=$ENV{'REMOTE_ADDR'};
 3226:   }
 3227:   my %returnhash;
 3228:   $namespace=~s/\//\_/g;
 3229:   $namespace=~s/\W//g;
 3230:   my %hash;
 3231:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3232:   if (tie(%hash,'GDBM_File',
 3233: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3234: 	  &GDBM_READER(),0640)) {
 3235:     my $version=$hash{"version:$symb"};
 3236:     $returnhash{'version'}=$version;
 3237:     my $scope;
 3238:     for ($scope=1;$scope<=$version;$scope++) {
 3239:       my $vkeys=$hash{"$scope:keys:$symb"};
 3240:       my @keys=split(/:/,$vkeys);
 3241:       my $key;
 3242:       $returnhash{"$scope:keys"}=$vkeys;
 3243:       foreach $key (@keys) {
 3244: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3245: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3246:       }
 3247:     }
 3248:     if (!(untie(%hash))) {
 3249:       return "error:$!";
 3250:     }
 3251:   } else {
 3252:     return "error:$!";
 3253:   }
 3254:   return %returnhash;
 3255: }
 3256: 
 3257: # ----------------------------------------------------------------------- Store
 3258: 
 3259: sub store {
 3260:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3261:     my $home='';
 3262: 
 3263:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3264: 
 3265:     $symb=&symbclean($symb);
 3266:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3267: 
 3268:     if (!$domain) { $domain=$env{'user.domain'}; }
 3269:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3270: 
 3271:     &devalidate($symb,$stuname,$domain);
 3272: 
 3273:     $symb=escape($symb);
 3274:     if (!$namespace) { 
 3275:        unless ($namespace=$env{'request.course.id'}) { 
 3276:           return ''; 
 3277:        } 
 3278:     }
 3279:     if (!$home) { $home=$env{'user.home'}; }
 3280: 
 3281:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3282:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3283: 
 3284:     my $namevalue='';
 3285:     foreach my $key (keys(%$storehash)) {
 3286:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3287:     }
 3288:     $namevalue=~s/\&$//;
 3289:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3290:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3291: }
 3292: 
 3293: # -------------------------------------------------------------- Critical Store
 3294: 
 3295: sub cstore {
 3296:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3297:     my $home='';
 3298: 
 3299:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3300: 
 3301:     $symb=&symbclean($symb);
 3302:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3303: 
 3304:     if (!$domain) { $domain=$env{'user.domain'}; }
 3305:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3306: 
 3307:     &devalidate($symb,$stuname,$domain);
 3308: 
 3309:     $symb=escape($symb);
 3310:     if (!$namespace) { 
 3311:        unless ($namespace=$env{'request.course.id'}) { 
 3312:           return ''; 
 3313:        } 
 3314:     }
 3315:     if (!$home) { $home=$env{'user.home'}; }
 3316: 
 3317:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3318:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3319: 
 3320:     my $namevalue='';
 3321:     foreach my $key (keys(%$storehash)) {
 3322:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3323:     }
 3324:     $namevalue=~s/\&$//;
 3325:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3326:     return critical
 3327:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3328: }
 3329: 
 3330: # --------------------------------------------------------------------- Restore
 3331: 
 3332: sub restore {
 3333:     my ($symb,$namespace,$domain,$stuname) = @_;
 3334:     my $home='';
 3335: 
 3336:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3337: 
 3338:     if (!$symb) {
 3339:       unless ($symb=escape(&symbread())) { return ''; }
 3340:     } else {
 3341:       $symb=&escape(&symbclean($symb));
 3342:     }
 3343:     if (!$namespace) { 
 3344:        unless ($namespace=$env{'request.course.id'}) { 
 3345:           return ''; 
 3346:        } 
 3347:     }
 3348:     if (!$domain) { $domain=$env{'user.domain'}; }
 3349:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3350:     if (!$home) { $home=$env{'user.home'}; }
 3351:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3352: 
 3353:     my %returnhash=();
 3354:     foreach my $line (split(/\&/,$answer)) {
 3355: 	my ($name,$value)=split(/\=/,$line);
 3356:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3357:     }
 3358:     my $version;
 3359:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3360:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3361:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3362:        }
 3363:     }
 3364:     return %returnhash;
 3365: }
 3366: 
 3367: # ---------------------------------------------------------- Course Description
 3368: 
 3369: sub coursedescription {
 3370:     my ($courseid,$args)=@_;
 3371:     $courseid=~s/^\///;
 3372:     $courseid=~s/\_/\//g;
 3373:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3374:     my $chome=&homeserver($cnum,$cdomain);
 3375:     my $normalid=$cdomain.'_'.$cnum;
 3376:     # need to always cache even if we get errors otherwise we keep 
 3377:     # trying and trying and trying to get the course description.
 3378:     my %envhash=();
 3379:     my %returnhash=();
 3380:     
 3381:     my $expiretime=600;
 3382:     if ($env{'request.course.id'} eq $normalid) {
 3383: 	$expiretime=120;
 3384:     }
 3385: 
 3386:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3387:     if (!$args->{'freshen_cache'}
 3388: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3389: 	foreach my $key (keys(%env)) {
 3390: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3391: 	    my ($setting) = $1;
 3392: 	    $returnhash{$setting} = $env{$key};
 3393: 	}
 3394: 	return %returnhash;
 3395:     }
 3396: 
 3397:     # get the data agin
 3398:     if (!$args->{'one_time'}) {
 3399: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3400:     }
 3401: 
 3402:     if ($chome ne 'no_host') {
 3403:        %returnhash=&dump('environment',$cdomain,$cnum);
 3404:        if (!exists($returnhash{'con_lost'})) {
 3405:            $returnhash{'home'}= $chome;
 3406: 	   $returnhash{'domain'} = $cdomain;
 3407: 	   $returnhash{'num'} = $cnum;
 3408:            if (!defined($returnhash{'type'})) {
 3409:                $returnhash{'type'} = 'Course';
 3410:            }
 3411:            while (my ($name,$value) = each %returnhash) {
 3412:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3413:            }
 3414:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3415:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3416: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3417:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3418:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3419:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3420:        }
 3421:     }
 3422:     if (!$args->{'one_time'}) {
 3423: 	&appenv(\%envhash);
 3424:     }
 3425:     return %returnhash;
 3426: }
 3427: 
 3428: # -------------------------------------------------See if a user is privileged
 3429: 
 3430: sub privileged {
 3431:     my ($username,$domain)=@_;
 3432:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3433: 			&homeserver($username,$domain));
 3434:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3435:     my $now=time;
 3436:     if ($rolesdump ne '') {
 3437:         foreach my $entry (split(/&/,$rolesdump)) {
 3438: 	    if ($entry!~/^rolesdef_/) {
 3439: 		my ($area,$role)=split(/=/,$entry);
 3440: 		$area=~s/\_\w\w$//;
 3441: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3442: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3443: 		    my $active=1;
 3444: 		    if ($tend) {
 3445: 			if ($tend<$now) { $active=0; }
 3446: 		    }
 3447: 		    if ($tstart) {
 3448: 			if ($tstart>$now) { $active=0; }
 3449: 		    }
 3450: 		    if ($active) { return 1; }
 3451: 		}
 3452: 	    }
 3453: 	}
 3454:     }
 3455:     return 0;
 3456: }
 3457: 
 3458: # -------------------------------------------------------- Get user privileges
 3459: 
 3460: sub rolesinit {
 3461:     my ($domain,$username,$authhost)=@_;
 3462:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3463:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3464:     my %allroles=();
 3465:     my %allgroups=();   
 3466:     my $now=time;
 3467:     my %userroles = ('user.login.time' => $now);
 3468:     my $group_privs;
 3469: 
 3470:     if ($rolesdump ne '') {
 3471:         foreach my $entry (split(/&/,$rolesdump)) {
 3472: 	  if ($entry!~/^rolesdef_/) {
 3473:             my ($area,$role)=split(/=/,$entry);
 3474: 	    $area=~s/\_\w\w$//;
 3475:             my ($trole,$tend,$tstart,$group_privs);
 3476: 	    if ($role=~/^cr/) { 
 3477: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3478: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3479: 		    ($tend,$tstart)=split('_',$trest);
 3480: 		} else {
 3481: 		    $trole=$role;
 3482: 		}
 3483:             } elsif ($role =~ m|^gr/|) {
 3484:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3485:                 ($trole,$group_privs) = split(/\//,$trole);
 3486:                 $group_privs = &unescape($group_privs);
 3487: 	    } else {
 3488: 		($trole,$tend,$tstart)=split(/_/,$role);
 3489: 	    }
 3490: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3491: 					 $username);
 3492: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3493:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3494:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3495:             if (($area ne '') && ($trole ne '')) {
 3496: 		my $spec=$trole.'.'.$area;
 3497: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3498: 		if ($trole =~ /^cr\//) {
 3499:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3500:                 } elsif ($trole eq 'gr') {
 3501:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3502: 		} else {
 3503:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3504: 		}
 3505:             }
 3506:           }
 3507:         }
 3508:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3509:         $userroles{'user.adv'}    = $adv;
 3510: 	$userroles{'user.author'} = $author;
 3511:         $env{'user.adv'}=$adv;
 3512:     }
 3513:     return \%userroles;  
 3514: }
 3515: 
 3516: sub set_arearole {
 3517:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3518: # log the associated role with the area
 3519:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3520:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3521: }
 3522: 
 3523: sub custom_roleprivs {
 3524:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3525:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3526:     my $homsvr=homeserver($rauthor,$rdomain);
 3527:     if (&hostname($homsvr) ne '') {
 3528:         my ($rdummy,$roledef)=
 3529:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3530:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3531:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3532:             if (defined($syspriv)) {
 3533:                 $$allroles{'cm./'}.=':'.$syspriv;
 3534:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3535:             }
 3536:             if ($tdomain ne '') {
 3537:                 if (defined($dompriv)) {
 3538:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3539:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3540:                 }
 3541:                 if (($trest ne '') && (defined($coursepriv))) {
 3542:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3543:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3544:                 }
 3545:             }
 3546:         }
 3547:     }
 3548: }
 3549: 
 3550: sub group_roleprivs {
 3551:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3552:     my $access = 1;
 3553:     my $now = time;
 3554:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3555:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3556:     if ($access) {
 3557:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3558:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3559:     }
 3560: }
 3561: 
 3562: sub standard_roleprivs {
 3563:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3564:     if (defined($pr{$trole.':s'})) {
 3565:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3566:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3567:     }
 3568:     if ($tdomain ne '') {
 3569:         if (defined($pr{$trole.':d'})) {
 3570:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3571:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3572:         }
 3573:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3574:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3575:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3576:         }
 3577:     }
 3578: }
 3579: 
 3580: sub set_userprivs {
 3581:     my ($userroles,$allroles,$allgroups) = @_; 
 3582:     my $author=0;
 3583:     my $adv=0;
 3584:     my %grouproles = ();
 3585:     if (keys(%{$allgroups}) > 0) {
 3586:         foreach my $role (keys %{$allroles}) {
 3587:             my ($trole,$area,$sec,$extendedarea);
 3588:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3589:                 $trole = $1;
 3590:                 $area = $2;
 3591:                 $sec = $3;
 3592:                 $extendedarea = $area.$sec;
 3593:                 if (exists($$allgroups{$area})) {
 3594:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3595:                         my $spec = $trole.'.'.$extendedarea;
 3596:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3597:                                                 $$allgroups{$area}{$group};
 3598:                     }
 3599:                 }
 3600:             }
 3601:         }
 3602:     }
 3603:     foreach my $group (keys(%grouproles)) {
 3604:         $$allroles{$group} = $grouproles{$group};
 3605:     }
 3606:     foreach my $role (keys(%{$allroles})) {
 3607:         my %thesepriv;
 3608:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3609:         foreach my $item (split(/:/,$$allroles{$role})) {
 3610:             if ($item ne '') {
 3611:                 my ($privilege,$restrictions)=split(/&/,$item);
 3612:                 if ($restrictions eq '') {
 3613:                     $thesepriv{$privilege}='F';
 3614:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3615:                     $thesepriv{$privilege}.=$restrictions;
 3616:                 }
 3617:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3618:             }
 3619:         }
 3620:         my $thesestr='';
 3621:         foreach my $priv (keys(%thesepriv)) {
 3622: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3623: 	}
 3624:         $userroles->{'user.priv.'.$role} = $thesestr;
 3625:     }
 3626:     return ($author,$adv);
 3627: }
 3628: 
 3629: # --------------------------------------------------------------- get interface
 3630: 
 3631: sub get {
 3632:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3633:    my $items='';
 3634:    foreach my $item (@$storearr) {
 3635:        $items.=&escape($item).'&';
 3636:    }
 3637:    $items=~s/\&$//;
 3638:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3639:    if (!$uname) { $uname=$env{'user.name'}; }
 3640:    my $uhome=&homeserver($uname,$udomain);
 3641: 
 3642:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3643:    my @pairs=split(/\&/,$rep);
 3644:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3645:      return @pairs;
 3646:    }
 3647:    my %returnhash=();
 3648:    my $i=0;
 3649:    foreach my $item (@$storearr) {
 3650:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3651:       $i++;
 3652:    }
 3653:    return %returnhash;
 3654: }
 3655: 
 3656: # --------------------------------------------------------------- del interface
 3657: 
 3658: sub del {
 3659:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3660:    my $items='';
 3661:    foreach my $item (@$storearr) {
 3662:        $items.=&escape($item).'&';
 3663:    }
 3664:    $items=~s/\&$//;
 3665:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3666:    if (!$uname) { $uname=$env{'user.name'}; }
 3667:    my $uhome=&homeserver($uname,$udomain);
 3668: 
 3669:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3670: }
 3671: 
 3672: # -------------------------------------------------------------- dump interface
 3673: 
 3674: sub dump {
 3675:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3676:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3677:     if (!$uname) { $uname=$env{'user.name'}; }
 3678:     my $uhome=&homeserver($uname,$udomain);
 3679:     if ($regexp) {
 3680: 	$regexp=&escape($regexp);
 3681:     } else {
 3682: 	$regexp='.';
 3683:     }
 3684:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3685:     my @pairs=split(/\&/,$rep);
 3686:     my %returnhash=();
 3687:     foreach my $item (@pairs) {
 3688: 	my ($key,$value)=split(/=/,$item,2);
 3689: 	$key = &unescape($key);
 3690: 	next if ($key =~ /^error: 2 /);
 3691: 	$returnhash{$key}=&thaw_unescape($value);
 3692:     }
 3693:     return %returnhash;
 3694: }
 3695: 
 3696: # --------------------------------------------------------- dumpstore interface
 3697: 
 3698: sub dumpstore {
 3699:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3700:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3701:    if (!$uname) { $uname=$env{'user.name'}; }
 3702:    my $uhome=&homeserver($uname,$udomain);
 3703:    if ($regexp) {
 3704:        $regexp=&escape($regexp);
 3705:    } else {
 3706:        $regexp='.';
 3707:    }
 3708:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3709:    my @pairs=split(/\&/,$rep);
 3710:    my %returnhash=();
 3711:    foreach my $item (@pairs) {
 3712:        my ($key,$value)=split(/=/,$item,2);
 3713:        next if ($key =~ /^error: 2 /);
 3714:        $returnhash{$key}=&thaw_unescape($value);
 3715:    }
 3716:    return %returnhash;
 3717: }
 3718: 
 3719: # -------------------------------------------------------------- keys interface
 3720: 
 3721: sub getkeys {
 3722:    my ($namespace,$udomain,$uname)=@_;
 3723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3724:    if (!$uname) { $uname=$env{'user.name'}; }
 3725:    my $uhome=&homeserver($uname,$udomain);
 3726:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3727:    my @keyarray=();
 3728:    foreach my $key (split(/\&/,$rep)) {
 3729:       next if ($key =~ /^error: 2 /);
 3730:       push(@keyarray,&unescape($key));
 3731:    }
 3732:    return @keyarray;
 3733: }
 3734: 
 3735: # --------------------------------------------------------------- currentdump
 3736: sub currentdump {
 3737:    my ($courseid,$sdom,$sname)=@_;
 3738:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3739:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3740:    $sname    = $env{'user.name'}         if (! defined($sname));
 3741:    my $uhome = &homeserver($sname,$sdom);
 3742:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3743:    return if ($rep =~ /^(error:|no_such_host)/);
 3744:    #
 3745:    my %returnhash=();
 3746:    #
 3747:    if ($rep eq "unknown_cmd") { 
 3748:        # an old lond will not know currentdump
 3749:        # Do a dump and make it look like a currentdump
 3750:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3751:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3752:        my %hash = @tmp;
 3753:        @tmp=();
 3754:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3755:    } else {
 3756:        my @pairs=split(/\&/,$rep);
 3757:        foreach my $pair (@pairs) {
 3758:            my ($key,$value)=split(/=/,$pair,2);
 3759:            my ($symb,$param) = split(/:/,$key);
 3760:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3761:                                                         &thaw_unescape($value);
 3762:        }
 3763:    }
 3764:    return %returnhash;
 3765: }
 3766: 
 3767: sub convert_dump_to_currentdump{
 3768:     my %hash = %{shift()};
 3769:     my %returnhash;
 3770:     # Code ripped from lond, essentially.  The only difference
 3771:     # here is the unescaping done by lonnet::dump().  Conceivably
 3772:     # we might run in to problems with parameter names =~ /^v\./
 3773:     while (my ($key,$value) = each(%hash)) {
 3774:         my ($v,$symb,$param) = split(/:/,$key);
 3775: 	$symb  = &unescape($symb);
 3776: 	$param = &unescape($param);
 3777:         next if ($v eq 'version' || $symb eq 'keys');
 3778:         next if (exists($returnhash{$symb}) &&
 3779:                  exists($returnhash{$symb}->{$param}) &&
 3780:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3781:         $returnhash{$symb}->{$param}=$value;
 3782:         $returnhash{$symb}->{'v.'.$param}=$v;
 3783:     }
 3784:     #
 3785:     # Remove all of the keys in the hashes which keep track of
 3786:     # the version of the parameter.
 3787:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3788:         # use a foreach because we are going to delete from the hash.
 3789:         foreach my $key (keys(%$param_hash)) {
 3790:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3791:         }
 3792:     }
 3793:     return \%returnhash;
 3794: }
 3795: 
 3796: # ------------------------------------------------------ critical inc interface
 3797: 
 3798: sub cinc {
 3799:     return &inc(@_,'critical');
 3800: }
 3801: 
 3802: # --------------------------------------------------------------- inc interface
 3803: 
 3804: sub inc {
 3805:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3806:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3807:     if (!$uname) { $uname=$env{'user.name'}; }
 3808:     my $uhome=&homeserver($uname,$udomain);
 3809:     my $items='';
 3810:     if (! ref($store)) {
 3811:         # got a single value, so use that instead
 3812:         $items = &escape($store).'=&';
 3813:     } elsif (ref($store) eq 'SCALAR') {
 3814:         $items = &escape($$store).'=&';        
 3815:     } elsif (ref($store) eq 'ARRAY') {
 3816:         $items = join('=&',map {&escape($_);} @{$store});
 3817:     } elsif (ref($store) eq 'HASH') {
 3818:         while (my($key,$value) = each(%{$store})) {
 3819:             $items.= &escape($key).'='.&escape($value).'&';
 3820:         }
 3821:     }
 3822:     $items=~s/\&$//;
 3823:     if ($critical) {
 3824: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3825:     } else {
 3826: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3827:     }
 3828: }
 3829: 
 3830: # --------------------------------------------------------------- put interface
 3831: 
 3832: sub put {
 3833:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3834:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3835:    if (!$uname) { $uname=$env{'user.name'}; }
 3836:    my $uhome=&homeserver($uname,$udomain);
 3837:    my $items='';
 3838:    foreach my $item (keys(%$storehash)) {
 3839:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3840:    }
 3841:    $items=~s/\&$//;
 3842:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3843: }
 3844: 
 3845: # ------------------------------------------------------------ newput interface
 3846: 
 3847: sub newput {
 3848:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3849:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3850:    if (!$uname) { $uname=$env{'user.name'}; }
 3851:    my $uhome=&homeserver($uname,$udomain);
 3852:    my $items='';
 3853:    foreach my $key (keys(%$storehash)) {
 3854:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3855:    }
 3856:    $items=~s/\&$//;
 3857:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3858: }
 3859: 
 3860: # ---------------------------------------------------------  putstore interface
 3861: 
 3862: sub putstore {
 3863:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3864:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3865:    if (!$uname) { $uname=$env{'user.name'}; }
 3866:    my $uhome=&homeserver($uname,$udomain);
 3867:    my $items='';
 3868:    foreach my $key (keys(%$storehash)) {
 3869:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3870:    }
 3871:    $items=~s/\&$//;
 3872:    my $esc_symb=&escape($symb);
 3873:    my $esc_v=&escape($version);
 3874:    my $reply =
 3875:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3876: 	      $uhome);
 3877:    if ($reply eq 'unknown_cmd') {
 3878:        # gfall back to way things use to be done
 3879:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3880: 			    $uname);
 3881:    }
 3882:    return $reply;
 3883: }
 3884: 
 3885: sub old_putstore {
 3886:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3887:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3888:     if (!$uname) { $uname=$env{'user.name'}; }
 3889:     my $uhome=&homeserver($uname,$udomain);
 3890:     my %newstorehash;
 3891:     foreach my $item (keys(%$storehash)) {
 3892: 	my $key = $version.':'.&escape($symb).':'.$item;
 3893: 	$newstorehash{$key} = $storehash->{$item};
 3894:     }
 3895:     my $items='';
 3896:     my %allitems = ();
 3897:     foreach my $item (keys(%newstorehash)) {
 3898: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3899: 	    my $key = $1.':keys:'.$2;
 3900: 	    $allitems{$key} .= $3.':';
 3901: 	}
 3902: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3903:     }
 3904:     foreach my $item (keys(%allitems)) {
 3905: 	$allitems{$item} =~ s/\:$//;
 3906: 	$items.= $item.'='.$allitems{$item}.'&';
 3907:     }
 3908:     $items=~s/\&$//;
 3909:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3910: }
 3911: 
 3912: # ------------------------------------------------------ critical put interface
 3913: 
 3914: sub cput {
 3915:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3916:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3917:    if (!$uname) { $uname=$env{'user.name'}; }
 3918:    my $uhome=&homeserver($uname,$udomain);
 3919:    my $items='';
 3920:    foreach my $item (keys(%$storehash)) {
 3921:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3922:    }
 3923:    $items=~s/\&$//;
 3924:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3925: }
 3926: 
 3927: # -------------------------------------------------------------- eget interface
 3928: 
 3929: sub eget {
 3930:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3931:    my $items='';
 3932:    foreach my $item (@$storearr) {
 3933:        $items.=&escape($item).'&';
 3934:    }
 3935:    $items=~s/\&$//;
 3936:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3937:    if (!$uname) { $uname=$env{'user.name'}; }
 3938:    my $uhome=&homeserver($uname,$udomain);
 3939:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3940:    my @pairs=split(/\&/,$rep);
 3941:    my %returnhash=();
 3942:    my $i=0;
 3943:    foreach my $item (@$storearr) {
 3944:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3945:       $i++;
 3946:    }
 3947:    return %returnhash;
 3948: }
 3949: 
 3950: # ------------------------------------------------------------ tmpput interface
 3951: sub tmpput {
 3952:     my ($storehash,$server,$context)=@_;
 3953:     my $items='';
 3954:     foreach my $item (keys(%$storehash)) {
 3955: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3956:     }
 3957:     $items=~s/\&$//;
 3958:     if (defined($context)) {
 3959:         $items .= ':'.&escape($context);
 3960:     }
 3961:     return &reply("tmpput:$items",$server);
 3962: }
 3963: 
 3964: # ------------------------------------------------------------ tmpget interface
 3965: sub tmpget {
 3966:     my ($token,$server)=@_;
 3967:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3968:     my $rep=&reply("tmpget:$token",$server);
 3969:     my %returnhash;
 3970:     foreach my $item (split(/\&/,$rep)) {
 3971: 	my ($key,$value)=split(/=/,$item);
 3972: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3973:     }
 3974:     return %returnhash;
 3975: }
 3976: 
 3977: # ------------------------------------------------------------ tmpget interface
 3978: sub tmpdel {
 3979:     my ($token,$server)=@_;
 3980:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3981:     return &reply("tmpdel:$token",$server);
 3982: }
 3983: 
 3984: # -------------------------------------------------- portfolio access checking
 3985: 
 3986: sub portfolio_access {
 3987:     my ($requrl) = @_;
 3988:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3989:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3990:     if ($result) {
 3991:         my %setters;
 3992:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3993:             my ($startblock,$endblock) =
 3994:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3995:             if ($startblock && $endblock) {
 3996:                 return 'B';
 3997:             }
 3998:         } else {
 3999:             my ($startblock,$endblock) =
 4000:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4001:             if ($startblock && $endblock) {
 4002:                 return 'B';
 4003:             }
 4004:         }
 4005:     }
 4006:     if ($result eq 'ok') {
 4007:        return 'F';
 4008:     } elsif ($result =~ /^[^:]+:guest_/) {
 4009:        return 'A';
 4010:     }
 4011:     return '';
 4012: }
 4013: 
 4014: sub get_portfolio_access {
 4015:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4016: 
 4017:     if (!ref($access_hash)) {
 4018: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4019: 	my %access_controls = &get_access_controls($current_perms,$group,
 4020: 						   $file_name);
 4021: 	$access_hash = $access_controls{$file_name};
 4022:     }
 4023: 
 4024:     my ($public,$guest,@domains,@users,@courses,@groups);
 4025:     my $now = time;
 4026:     if (ref($access_hash) eq 'HASH') {
 4027:         foreach my $key (keys(%{$access_hash})) {
 4028:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4029:             if ($start > $now) {
 4030:                 next;
 4031:             }
 4032:             if ($end && $end<$now) {
 4033:                 next;
 4034:             }
 4035:             if ($scope eq 'public') {
 4036:                 $public = $key;
 4037:                 last;
 4038:             } elsif ($scope eq 'guest') {
 4039:                 $guest = $key;
 4040:             } elsif ($scope eq 'domains') {
 4041:                 push(@domains,$key);
 4042:             } elsif ($scope eq 'users') {
 4043:                 push(@users,$key);
 4044:             } elsif ($scope eq 'course') {
 4045:                 push(@courses,$key);
 4046:             } elsif ($scope eq 'group') {
 4047:                 push(@groups,$key);
 4048:             }
 4049:         }
 4050:         if ($public) {
 4051:             return 'ok';
 4052:         }
 4053:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4054:             if ($guest) {
 4055:                 return $guest;
 4056:             }
 4057:         } else {
 4058:             if (@domains > 0) {
 4059:                 foreach my $domkey (@domains) {
 4060:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4061:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4062:                             return 'ok';
 4063:                         }
 4064:                     }
 4065:                 }
 4066:             }
 4067:             if (@users > 0) {
 4068:                 foreach my $userkey (@users) {
 4069:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4070:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4071:                             if (ref($item) eq 'HASH') {
 4072:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4073:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4074:                                     return 'ok';
 4075:                                 }
 4076:                             }
 4077:                         }
 4078:                     } 
 4079:                 }
 4080:             }
 4081:             my %roleshash;
 4082:             my @courses_and_groups = @courses;
 4083:             push(@courses_and_groups,@groups); 
 4084:             if (@courses_and_groups > 0) {
 4085:                 my (%allgroups,%allroles); 
 4086:                 my ($start,$end,$role,$sec,$group);
 4087:                 foreach my $envkey (%env) {
 4088:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4089:                         my $cid = $2.'_'.$3; 
 4090:                         if ($1 eq 'gr') {
 4091:                             $group = $4;
 4092:                             $allgroups{$cid}{$group} = $env{$envkey};
 4093:                         } else {
 4094:                             if ($4 eq '') {
 4095:                                 $sec = 'none';
 4096:                             } else {
 4097:                                 $sec = $4;
 4098:                             }
 4099:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4100:                         }
 4101:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4102:                         my $cid = $2.'_'.$3;
 4103:                         if ($4 eq '') {
 4104:                             $sec = 'none';
 4105:                         } else {
 4106:                             $sec = $4;
 4107:                         }
 4108:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4109:                     }
 4110:                 }
 4111:                 if (keys(%allroles) == 0) {
 4112:                     return;
 4113:                 }
 4114:                 foreach my $key (@courses_and_groups) {
 4115:                     my %content = %{$$access_hash{$key}};
 4116:                     my $cnum = $content{'number'};
 4117:                     my $cdom = $content{'domain'};
 4118:                     my $cid = $cdom.'_'.$cnum;
 4119:                     if (!exists($allroles{$cid})) {
 4120:                         next;
 4121:                     }    
 4122:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4123:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4124:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4125:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4126:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4127:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4128:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4129:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4130:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4131:                                         if (grep/^all$/,@sections) {
 4132:                                             return 'ok';
 4133:                                         } else {
 4134:                                             if (grep/^$sec$/,@sections) {
 4135:                                                 return 'ok';
 4136:                                             }
 4137:                                         }
 4138:                                     }
 4139:                                 }
 4140:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4141:                                     if (grep/^none$/,@groups) {
 4142:                                         return 'ok';
 4143:                                     }
 4144:                                 } else {
 4145:                                     if (grep/^all$/,@groups) {
 4146:                                         return 'ok';
 4147:                                     } 
 4148:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4149:                                         if (grep/^$group$/,@groups) {
 4150:                                             return 'ok';
 4151:                                         }
 4152:                                     }
 4153:                                 } 
 4154:                             }
 4155:                         }
 4156:                     }
 4157:                 }
 4158:             }
 4159:             if ($guest) {
 4160:                 return $guest;
 4161:             }
 4162:         }
 4163:     }
 4164:     return;
 4165: }
 4166: 
 4167: sub course_group_datechecker {
 4168:     my ($dates,$now,$status) = @_;
 4169:     my ($start,$end) = split(/\./,$dates);
 4170:     if (!$start && !$end) {
 4171:         return 'ok';
 4172:     }
 4173:     if (grep/^active$/,@{$status}) {
 4174:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4175:             return 'ok';
 4176:         }
 4177:     }
 4178:     if (grep/^previous$/,@{$status}) {
 4179:         if ($end > $now ) {
 4180:             return 'ok';
 4181:         }
 4182:     }
 4183:     if (grep/^future$/,@{$status}) {
 4184:         if ($start > $now) {
 4185:             return 'ok';
 4186:         }
 4187:     }
 4188:     return; 
 4189: }
 4190: 
 4191: sub parse_portfolio_url {
 4192:     my ($url) = @_;
 4193: 
 4194:     my ($type,$udom,$unum,$group,$file_name);
 4195:     
 4196:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4197: 	$type = 1;
 4198:         $udom = $1;
 4199:         $unum = $2;
 4200:         $file_name = $3;
 4201:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4202: 	$type = 2;
 4203:         $udom = $1;
 4204:         $unum = $2;
 4205:         $group = $3;
 4206:         $file_name = $3.'/'.$4;
 4207:     }
 4208:     if (wantarray) {
 4209: 	return ($type,$udom,$unum,$file_name,$group);
 4210:     }
 4211:     return $type;
 4212: }
 4213: 
 4214: sub is_portfolio_url {
 4215:     my ($url) = @_;
 4216:     return scalar(&parse_portfolio_url($url));
 4217: }
 4218: 
 4219: sub is_portfolio_file {
 4220:     my ($file) = @_;
 4221:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4222:         return 1;
 4223:     }
 4224:     return;
 4225: }
 4226: 
 4227: 
 4228: # ---------------------------------------------- Custom access rule evaluation
 4229: 
 4230: sub customaccess {
 4231:     my ($priv,$uri)=@_;
 4232:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4233:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4234:     $udom = &LONCAPA::clean_domain($udom);
 4235:     $ucrs = &LONCAPA::clean_username($ucrs);
 4236:     my $access=0;
 4237:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4238: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4239: 	if ($type eq 'user') {
 4240: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4241: 		my ($tdom,$tuname)=split(m{/},$scope);
 4242: 		if ($tdom) {
 4243: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4244: 		}
 4245: 		if ($tuname) {
 4246: 		    if ($tuname ne $env{'user.name'}) { next; }
 4247: 		}
 4248: 		$access=($effect eq 'allow');
 4249: 		last;
 4250: 	    }
 4251: 	} else {
 4252: 	    if ($role) {
 4253: 		if ($role ne $urole) { next; }
 4254: 	    }
 4255: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4256: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4257: 		if ($tdom) {
 4258: 		    if ($tdom ne $udom) { next; }
 4259: 		}
 4260: 		if ($tcrs) {
 4261: 		    if ($tcrs ne $ucrs) { next; }
 4262: 		}
 4263: 		if ($tsec) {
 4264: 		    if ($tsec ne $usec) { next; }
 4265: 		}
 4266: 		$access=($effect eq 'allow');
 4267: 		last;
 4268: 	    }
 4269: 	    if ($realm eq '' && $role eq '') {
 4270: 		$access=($effect eq 'allow');
 4271: 	    }
 4272: 	}
 4273:     }
 4274:     return $access;
 4275: }
 4276: 
 4277: # ------------------------------------------------- Check for a user privilege
 4278: 
 4279: sub allowed {
 4280:     my ($priv,$uri,$symb,$role)=@_;
 4281:     my $ver_orguri=$uri;
 4282:     $uri=&deversion($uri);
 4283:     my $orguri=$uri;
 4284:     $uri=&declutter($uri);
 4285: 
 4286:     if ($priv eq 'evb') {
 4287: # Evade communication block restrictions for specified role in a course
 4288:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4289:             return $1;
 4290:         } else {
 4291:             return;
 4292:         }
 4293:     }
 4294: 
 4295:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4296: # Free bre access to adm and meta resources
 4297:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4298: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4299: 	&& ($priv eq 'bre')) {
 4300: 	return 'F';
 4301:     }
 4302: 
 4303: # Free bre access to user's own portfolio contents
 4304:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4305:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4306: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4307:         my %setters;
 4308:         my ($startblock,$endblock) = 
 4309:             &Apache::loncommon::blockcheck(\%setters,'port');
 4310:         if ($startblock && $endblock) {
 4311:             return 'B';
 4312:         } else {
 4313:             return 'F';
 4314:         }
 4315:     }
 4316: 
 4317: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4318:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4319:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4320:         if (exists($env{'request.course.id'})) {
 4321:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4322:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4323:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4324:                 my $courseprivid=$env{'request.course.id'};
 4325:                 $courseprivid=~s/\_/\//;
 4326:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4327:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4328:                     return $1; 
 4329:                 } else {
 4330:                     if ($env{'request.course.sec'}) {
 4331:                         $courseprivid.='/'.$env{'request.course.sec'};
 4332:                     }
 4333:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4334:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4335:                         return $2;
 4336:                     }
 4337:                 }
 4338:             }
 4339:         }
 4340:     }
 4341: 
 4342: # Free bre to public access
 4343: 
 4344:     if ($priv eq 'bre') {
 4345:         my $copyright=&metadata($uri,'copyright');
 4346: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4347:            return 'F'; 
 4348:         }
 4349:         if ($copyright eq 'priv') {
 4350:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4351: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4352: 		return '';
 4353:             }
 4354:         }
 4355:         if ($copyright eq 'domain') {
 4356:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4357: 	    unless (($env{'user.domain'} eq $1) ||
 4358:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4359: 		return '';
 4360:             }
 4361:         }
 4362:         if ($env{'request.role'}=~ /li\.\//) {
 4363:             # Library role, so allow browsing of resources in this domain.
 4364:             return 'F';
 4365:         }
 4366:         if ($copyright eq 'custom') {
 4367: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4368:         }
 4369:     }
 4370:     # Domain coordinator is trying to create a course
 4371:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4372:         # uri is the requested domain in this case.
 4373:         # comparison to 'request.role.domain' shows if the user has selected
 4374:         # a role of dc for the domain in question.
 4375:         return 'F' if ($uri eq $env{'request.role.domain'});
 4376:     }
 4377: 
 4378:     my $thisallowed='';
 4379:     my $statecond=0;
 4380:     my $courseprivid='';
 4381: 
 4382: # Course
 4383: 
 4384:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4385:        $thisallowed.=$1;
 4386:     }
 4387: 
 4388: # Domain
 4389: 
 4390:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4391:        =~/\Q$priv\E\&([^\:]*)/) {
 4392:        $thisallowed.=$1;
 4393:     }
 4394: 
 4395: # Course: uri itself is a course
 4396:     my $courseuri=$uri;
 4397:     $courseuri=~s/\_(\d)/\/$1/;
 4398:     $courseuri=~s/^([^\/])/\/$1/;
 4399: 
 4400:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4401:        =~/\Q$priv\E\&([^\:]*)/) {
 4402:        $thisallowed.=$1;
 4403:     }
 4404: 
 4405: # URI is an uploaded document for this course, default permissions don't matter
 4406: # not allowing 'edit' access (editupload) to uploaded course docs
 4407:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4408: 	$thisallowed='';
 4409:         my ($match)=&is_on_map($uri);
 4410:         if ($match) {
 4411:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4412:                   =~/\Q$priv\E\&([^\:]*)/) {
 4413:                 $thisallowed.=$1;
 4414:             }
 4415:         } else {
 4416:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4417:             if ($refuri) {
 4418:                 if ($refuri =~ m|^/adm/|) {
 4419:                     $thisallowed='F';
 4420:                 } else {
 4421:                     $refuri=&declutter($refuri);
 4422:                     my ($match) = &is_on_map($refuri);
 4423:                     if ($match) {
 4424:                         $thisallowed='F';
 4425:                     }
 4426:                 }
 4427:             }
 4428:         }
 4429:     }
 4430: 
 4431:     if ($priv eq 'bre'
 4432: 	&& $thisallowed ne 'F' 
 4433: 	&& $thisallowed ne '2'
 4434: 	&& &is_portfolio_url($uri)) {
 4435: 	$thisallowed = &portfolio_access($uri);
 4436:     }
 4437:     
 4438: # Full access at system, domain or course-wide level? Exit.
 4439: 
 4440:     if ($thisallowed=~/F/) {
 4441: 	return 'F';
 4442:     }
 4443: 
 4444: # If this is generating or modifying users, exit with special codes
 4445: 
 4446:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4447: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4448: 	    my ($audom,$auname)=split('/',$uri);
 4449: # no author name given, so this just checks on the general right to make a co-author in this domain
 4450: 	    unless ($auname) { return $thisallowed; }
 4451: # an author name is given, so we are about to actually make a co-author for a certain account
 4452: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4453: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4454: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4455: 	}
 4456: 	return $thisallowed;
 4457:     }
 4458: #
 4459: # Gathered so far: system, domain and course wide privileges
 4460: #
 4461: # Course: See if uri or referer is an individual resource that is part of 
 4462: # the course
 4463: 
 4464:     if ($env{'request.course.id'}) {
 4465: 
 4466:        $courseprivid=$env{'request.course.id'};
 4467:        if ($env{'request.course.sec'}) {
 4468:           $courseprivid.='/'.$env{'request.course.sec'};
 4469:        }
 4470:        $courseprivid=~s/\_/\//;
 4471:        my $checkreferer=1;
 4472:        my ($match,$cond)=&is_on_map($uri);
 4473:        if ($match) {
 4474:            $statecond=$cond;
 4475:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4476:                =~/\Q$priv\E\&([^\:]*)/) {
 4477:                $thisallowed.=$1;
 4478:                $checkreferer=0;
 4479:            }
 4480:        }
 4481:        
 4482:        if ($checkreferer) {
 4483: 	  my $refuri=$env{'httpref.'.$orguri};
 4484:             unless ($refuri) {
 4485:                 foreach my $key (keys(%env)) {
 4486: 		    if ($key=~/^httpref\..*\*/) {
 4487: 			my $pattern=$key;
 4488:                         $pattern=~s/^httpref\.\/res\///;
 4489:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4490:                         $pattern=~s/\//\\\//g;
 4491:                         if ($orguri=~/$pattern/) {
 4492: 			    $refuri=$env{$key};
 4493:                         }
 4494:                     }
 4495:                 }
 4496:             }
 4497: 
 4498:          if ($refuri) { 
 4499: 	  $refuri=&declutter($refuri);
 4500:           my ($match,$cond)=&is_on_map($refuri);
 4501:             if ($match) {
 4502:               my $refstatecond=$cond;
 4503:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4504:                   =~/\Q$priv\E\&([^\:]*)/) {
 4505:                   $thisallowed.=$1;
 4506:                   $uri=$refuri;
 4507:                   $statecond=$refstatecond;
 4508:               }
 4509:           }
 4510:         }
 4511:        }
 4512:    }
 4513: 
 4514: #
 4515: # Gathered now: all privileges that could apply, and condition number
 4516: # 
 4517: #
 4518: # Full or no access?
 4519: #
 4520: 
 4521:     if ($thisallowed=~/F/) {
 4522: 	return 'F';
 4523:     }
 4524: 
 4525:     unless ($thisallowed) {
 4526:         return '';
 4527:     }
 4528: 
 4529: # Restrictions exist, deal with them
 4530: #
 4531: #   C:according to course preferences
 4532: #   R:according to resource settings
 4533: #   L:unless locked
 4534: #   X:according to user session state
 4535: #
 4536: 
 4537: # Possibly locked functionality, check all courses
 4538: # Locks might take effect only after 10 minutes cache expiration for other
 4539: # courses, and 2 minutes for current course
 4540: 
 4541:     my $envkey;
 4542:     if ($thisallowed=~/L/) {
 4543:         foreach $envkey (keys %env) {
 4544:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4545:                my $courseid=$2;
 4546:                my $roleid=$1.'.'.$2;
 4547:                $courseid=~s/^\///;
 4548:                my $expiretime=600;
 4549:                if ($env{'request.role'} eq $roleid) {
 4550: 		  $expiretime=120;
 4551:                }
 4552: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4553:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4554:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4555: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4556:                }
 4557:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4558:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4559: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4560:                        &log($env{'user.domain'},$env{'user.name'},
 4561:                             $env{'user.home'},
 4562:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4563:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4564:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4565: 		       return '';
 4566:                    }
 4567:                }
 4568:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4569:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4570: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4571:                        &log($env{'user.domain'},$env{'user.name'},
 4572:                             $env{'user.home'},
 4573:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4574:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4575:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4576: 		       return '';
 4577:                    }
 4578:                }
 4579: 	   }
 4580:        }
 4581:     }
 4582:    
 4583: #
 4584: # Rest of the restrictions depend on selected course
 4585: #
 4586: 
 4587:     unless ($env{'request.course.id'}) {
 4588: 	if ($thisallowed eq 'A') {
 4589: 	    return 'A';
 4590:         } elsif ($thisallowed eq 'B') {
 4591:             return 'B';
 4592: 	} else {
 4593: 	    return '1';
 4594: 	}
 4595:     }
 4596: 
 4597: #
 4598: # Now user is definitely in a course
 4599: #
 4600: 
 4601: 
 4602: # Course preferences
 4603: 
 4604:    if ($thisallowed=~/C/) {
 4605:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4606:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4607:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4608: 	   =~/\Q$rolecode\E/) {
 4609: 	   if ($priv ne 'pch') { 
 4610: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4611: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4612: 			$env{'request.course.id'});
 4613: 	   }
 4614:            return '';
 4615:        }
 4616: 
 4617:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4618: 	   =~/\Q$unamedom\E/) {
 4619: 	   if ($priv ne 'pch') { 
 4620: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4621: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4622: 			$env{'request.course.id'});
 4623: 	   }
 4624:            return '';
 4625:        }
 4626:    }
 4627: 
 4628: # Resource preferences
 4629: 
 4630:    if ($thisallowed=~/R/) {
 4631:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4632:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4633: 	   if ($priv ne 'pch') { 
 4634: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4635: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4636: 	   }
 4637: 	   return '';
 4638:        }
 4639:    }
 4640: 
 4641: # Restricted by state or randomout?
 4642: 
 4643:    if ($thisallowed=~/X/) {
 4644:       if ($env{'acc.randomout'}) {
 4645: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4646:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4647:             return ''; 
 4648:          }
 4649:       }
 4650:       if (&condval($statecond)) {
 4651: 	 return '2';
 4652:       } else {
 4653:          return '';
 4654:       }
 4655:    }
 4656: 
 4657:     if ($thisallowed eq 'A') {
 4658: 	return 'A';
 4659:     } elsif ($thisallowed eq 'B') {
 4660:         return 'B';
 4661:     }
 4662:    return 'F';
 4663: }
 4664: 
 4665: sub split_uri_for_cond {
 4666:     my $uri=&deversion(&declutter(shift));
 4667:     my @uriparts=split(/\//,$uri);
 4668:     my $filename=pop(@uriparts);
 4669:     my $pathname=join('/',@uriparts);
 4670:     return ($pathname,$filename);
 4671: }
 4672: # --------------------------------------------------- Is a resource on the map?
 4673: 
 4674: sub is_on_map {
 4675:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4676:     #Trying to find the conditional for the file
 4677:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4678: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4679:     if ($match) {
 4680: 	return (1,$1);
 4681:     } else {
 4682: 	return (0,0);
 4683:     }
 4684: }
 4685: 
 4686: # --------------------------------------------------------- Get symb from alias
 4687: 
 4688: sub get_symb_from_alias {
 4689:     my $symb=shift;
 4690:     my ($map,$resid,$url)=&decode_symb($symb);
 4691: # Already is a symb
 4692:     if ($url) { return $symb; }
 4693: # Must be an alias
 4694:     my $aliassymb='';
 4695:     my %bighash;
 4696:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4697:                             &GDBM_READER(),0640)) {
 4698:         my $rid=$bighash{'mapalias_'.$symb};
 4699: 	if ($rid) {
 4700: 	    my ($mapid,$resid)=split(/\./,$rid);
 4701: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4702: 				    $resid,$bighash{'src_'.$rid});
 4703: 	}
 4704:         untie %bighash;
 4705:     }
 4706:     return $aliassymb;
 4707: }
 4708: 
 4709: # ----------------------------------------------------------------- Define Role
 4710: 
 4711: sub definerole {
 4712:   if (allowed('mcr','/')) {
 4713:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4714:     foreach my $role (split(':',$sysrole)) {
 4715: 	my ($crole,$cqual)=split(/\&/,$role);
 4716:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4717:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4718: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4719:                return "refused:s:$crole&$cqual"; 
 4720:             }
 4721:         }
 4722:     }
 4723:     foreach my $role (split(':',$domrole)) {
 4724: 	my ($crole,$cqual)=split(/\&/,$role);
 4725:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4726:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4727: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4728:                return "refused:d:$crole&$cqual"; 
 4729:             }
 4730:         }
 4731:     }
 4732:     foreach my $role (split(':',$courole)) {
 4733: 	my ($crole,$cqual)=split(/\&/,$role);
 4734:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4735:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4736: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4737:                return "refused:c:$crole&$cqual"; 
 4738:             }
 4739:         }
 4740:     }
 4741:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4742:                 "$env{'user.domain'}:$env{'user.name'}:".
 4743: 	        "rolesdef_$rolename=".
 4744:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4745:     return reply($command,$env{'user.home'});
 4746:   } else {
 4747:     return 'refused';
 4748:   }
 4749: }
 4750: 
 4751: # ---------------- Make a metadata query against the network of library servers
 4752: 
 4753: sub metadata_query {
 4754:     my ($query,$custom,$customshow,$server_array)=@_;
 4755:     my %rhash;
 4756:     my %libserv = &all_library();
 4757:     my @server_list = (defined($server_array) ? @$server_array
 4758:                                               : keys(%libserv) );
 4759:     for my $server (@server_list) {
 4760: 	unless ($custom or $customshow) {
 4761: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4762: 	    $rhash{$server}=$reply;
 4763: 	}
 4764: 	else {
 4765: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4766: 			     &escape($custom).':'.&escape($customshow),
 4767: 			     $server);
 4768: 	    $rhash{$server}=$reply;
 4769: 	}
 4770:     }
 4771:     return \%rhash;
 4772: }
 4773: 
 4774: # ----------------------------------------- Send log queries and wait for reply
 4775: 
 4776: sub log_query {
 4777:     my ($uname,$udom,$query,%filters)=@_;
 4778:     my $uhome=&homeserver($uname,$udom);
 4779:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4780:     my $uhost=&hostname($uhome);
 4781:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4782:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4783:                        $uhome);
 4784:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4785:     return get_query_reply($queryid);
 4786: }
 4787: 
 4788: # -------------------------- Update MySQL table for portfolio file
 4789: 
 4790: sub update_portfolio_table {
 4791:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4792:     my $homeserver = &homeserver($uname,$udom);
 4793:     my $queryid=
 4794:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4795:                ':'.&escape($file_name).':'.$action,$homeserver);
 4796:     my $reply = &get_query_reply($queryid);
 4797:     return $reply;
 4798: }
 4799: 
 4800: # -------------------------- Update MySQL allusers table
 4801: 
 4802: sub update_allusers_table {
 4803:     my ($uname,$udom,$names) = @_;
 4804:     my $homeserver = &homeserver($uname,$udom);
 4805:     my $queryid=
 4806:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4807:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4808:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4809:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4810:                'generation='.&escape($names->{'generation'}).'%%'.
 4811:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4812:                'id='.&escape($names->{'id'}),$homeserver);
 4813:     my $reply = &get_query_reply($queryid);
 4814:     return $reply;
 4815: }
 4816: 
 4817: # ------- Request retrieval of institutional classlists for course(s)
 4818: 
 4819: sub fetch_enrollment_query {
 4820:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4821:     my $homeserver;
 4822:     my $maxtries = 1;
 4823:     if ($context eq 'automated') {
 4824:         $homeserver = $perlvar{'lonHostID'};
 4825:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4826:     } else {
 4827:         $homeserver = &homeserver($cnum,$dom);
 4828:     }
 4829:     my $host=&hostname($homeserver);
 4830:     my $cmd = '';
 4831:     foreach my $affiliate (keys %{$affiliatesref}) {
 4832:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4833:     }
 4834:     $cmd =~ s/%%$//;
 4835:     $cmd = &escape($cmd);
 4836:     my $query = 'fetchenrollment';
 4837:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4838:     unless ($queryid=~/^\Q$host\E\_/) { 
 4839:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4840:         return 'error: '.$queryid;
 4841:     }
 4842:     my $reply = &get_query_reply($queryid);
 4843:     my $tries = 1;
 4844:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4845:         $reply = &get_query_reply($queryid);
 4846:         $tries ++;
 4847:     }
 4848:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4849:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4850:     } else {
 4851:         my @responses = split(/:/,$reply);
 4852:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4853:             foreach my $line (@responses) {
 4854:                 my ($key,$value) = split(/=/,$line,2);
 4855:                 $$replyref{$key} = $value;
 4856:             }
 4857:         } else {
 4858:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4859:             foreach my $line (@responses) {
 4860:                 my ($key,$value) = split(/=/,$line);
 4861:                 $$replyref{$key} = $value;
 4862:                 if ($value > 0) {
 4863:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4864:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4865:                         my $destname = $pathname.'/'.$filename;
 4866:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4867:                         if ($xml_classlist =~ /^error/) {
 4868:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4869:                         } else {
 4870:                             if ( open(FILE,">$destname") ) {
 4871:                                 print FILE &unescape($xml_classlist);
 4872:                                 close(FILE);
 4873:                             } else {
 4874:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4875:                             }
 4876:                         }
 4877:                     }
 4878:                 }
 4879:             }
 4880:         }
 4881:         return 'ok';
 4882:     }
 4883:     return 'error';
 4884: }
 4885: 
 4886: sub get_query_reply {
 4887:     my $queryid=shift;
 4888:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4889:     my $reply='';
 4890:     for (1..100) {
 4891: 	sleep 2;
 4892:         if (-e $replyfile.'.end') {
 4893: 	    if (open(my $fh,$replyfile)) {
 4894: 		$reply = join('',<$fh>);
 4895: 		close($fh);
 4896: 	   } else { return 'error: reply_file_error'; }
 4897:            return &unescape($reply);
 4898: 	}
 4899:     }
 4900:     return 'timeout:'.$queryid;
 4901: }
 4902: 
 4903: sub courselog_query {
 4904: #
 4905: # possible filters:
 4906: # url: url or symb
 4907: # username
 4908: # domain
 4909: # action: view, submit, grade
 4910: # start: timestamp
 4911: # end: timestamp
 4912: #
 4913:     my (%filters)=@_;
 4914:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4915:     if ($filters{'url'}) {
 4916: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4917:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4918:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4919:     }
 4920:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4921:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4922:     return &log_query($cname,$cdom,'courselog',%filters);
 4923: }
 4924: 
 4925: sub userlog_query {
 4926: #
 4927: # possible filters:
 4928: # action: log check role
 4929: # start: timestamp
 4930: # end: timestamp
 4931: #
 4932:     my ($uname,$udom,%filters)=@_;
 4933:     return &log_query($uname,$udom,'userlog',%filters);
 4934: }
 4935: 
 4936: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4937: 
 4938: sub auto_run {
 4939:     my ($cnum,$cdom) = @_;
 4940:     my $response = 0;
 4941:     my $settings;
 4942:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4943:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4944:         $settings = $domconfig{'autoenroll'};
 4945:         if ($settings->{'run'} eq '1') {
 4946:             $response = 1;
 4947:         }
 4948:     } else {
 4949:         my $homeserver;
 4950:         if (&is_course($cdom,$cnum)) {
 4951:             $homeserver = &homeserver($cnum,$cdom);
 4952:         } else {
 4953:             $homeserver = &domain($cdom,'primary');
 4954:         }
 4955:         if ($homeserver ne 'no_host') {
 4956:             $response = &reply('autorun:'.$cdom,$homeserver);
 4957:         }
 4958:     }
 4959:     return $response;
 4960: }
 4961: 
 4962: sub auto_get_sections {
 4963:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4964:     my $homeserver = &homeserver($cnum,$cdom);
 4965:     my @secs = ();
 4966:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4967:     unless ($response eq 'refused') {
 4968:         @secs = split(/:/,$response);
 4969:     }
 4970:     return @secs;
 4971: }
 4972: 
 4973: sub auto_new_course {
 4974:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4975:     my $homeserver = &homeserver($cnum,$cdom);
 4976:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4977:     return $response;
 4978: }
 4979: 
 4980: sub auto_validate_courseID {
 4981:     my ($cnum,$cdom,$inst_course_id) = @_;
 4982:     my $homeserver = &homeserver($cnum,$cdom);
 4983:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4984:     return $response;
 4985: }
 4986: 
 4987: sub auto_create_password {
 4988:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4989:     my ($homeserver,$response);
 4990:     my $create_passwd = 0;
 4991:     my $authchk = '';
 4992:     if ($udom =~ /^$match_domain$/) {
 4993:         $homeserver = &domain($udom,'primary');
 4994:     }
 4995:     if ($homeserver eq '') {
 4996:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4997:             $homeserver = &homeserver($cnum,$cdom);
 4998:         }
 4999:     }
 5000:     if ($homeserver eq '') {
 5001:         $authchk = 'nodomain';
 5002:     } else {
 5003:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5004:         if ($response eq 'refused') {
 5005:             $authchk = 'refused';
 5006:         } else {
 5007:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5008:         }
 5009:     }
 5010:     return ($authparam,$create_passwd,$authchk);
 5011: }
 5012: 
 5013: sub auto_photo_permission {
 5014:     my ($cnum,$cdom,$students) = @_;
 5015:     my $homeserver = &homeserver($cnum,$cdom);
 5016:     my ($outcome,$perm_reqd,$conditions) = 
 5017: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5018:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5019: 	return (undef,undef);
 5020:     }
 5021:     return ($outcome,$perm_reqd,$conditions);
 5022: }
 5023: 
 5024: sub auto_checkphotos {
 5025:     my ($uname,$udom,$pid) = @_;
 5026:     my $homeserver = &homeserver($uname,$udom);
 5027:     my ($result,$resulttype);
 5028:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5029: 				   &escape($uname).':'.&escape($pid),
 5030: 				   $homeserver));
 5031:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5032: 	return (undef,undef);
 5033:     }
 5034:     if ($outcome) {
 5035:         ($result,$resulttype) = split(/:/,$outcome);
 5036:     } 
 5037:     return ($result,$resulttype);
 5038: }
 5039: 
 5040: sub auto_photochoice {
 5041:     my ($cnum,$cdom) = @_;
 5042:     my $homeserver = &homeserver($cnum,$cdom);
 5043:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5044: 						       &escape($cdom),
 5045: 						       $homeserver)));
 5046:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5047: 	return (undef,undef);
 5048:     }
 5049:     return ($update,$comment);
 5050: }
 5051: 
 5052: sub auto_photoupdate {
 5053:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5054:     my $homeserver = &homeserver($cnum,$dom);
 5055:     my $host=&hostname($homeserver);
 5056:     my $cmd = '';
 5057:     my $maxtries = 1;
 5058:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5059:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5060:     }
 5061:     $cmd =~ s/%%$//;
 5062:     $cmd = &escape($cmd);
 5063:     my $query = 'institutionalphotos';
 5064:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5065:     unless ($queryid=~/^\Q$host\E\_/) {
 5066:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5067:         return 'error: '.$queryid;
 5068:     }
 5069:     my $reply = &get_query_reply($queryid);
 5070:     my $tries = 1;
 5071:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5072:         $reply = &get_query_reply($queryid);
 5073:         $tries ++;
 5074:     }
 5075:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5076:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5077:     } else {
 5078:         my @responses = split(/:/,$reply);
 5079:         my $outcome = shift(@responses); 
 5080:         foreach my $item (@responses) {
 5081:             my ($key,$value) = split(/=/,$item);
 5082:             $$photo{$key} = $value;
 5083:         }
 5084:         return $outcome;
 5085:     }
 5086:     return 'error';
 5087: }
 5088: 
 5089: sub auto_instcode_format {
 5090:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5091: 	$cat_order) = @_;
 5092:     my $courses = '';
 5093:     my @homeservers;
 5094:     if ($caller eq 'global') {
 5095: 	my %servers = &get_servers($codedom,'library');
 5096: 	foreach my $tryserver (keys(%servers)) {
 5097: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5098: 		push(@homeservers,$tryserver);
 5099: 	    }
 5100:         }
 5101:     } else {
 5102:         push(@homeservers,&homeserver($caller,$codedom));
 5103:     }
 5104:     foreach my $code (keys(%{$instcodes})) {
 5105:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5106:     }
 5107:     chop($courses);
 5108:     my $ok_response = 0;
 5109:     my $response;
 5110:     while (@homeservers > 0 && $ok_response == 0) {
 5111:         my $server = shift(@homeservers); 
 5112:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5113:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5114:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5115: 		split(/:/,$response);
 5116:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5117:             push(@{$codetitles},&str2array($codetitles_str));
 5118:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5119:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5120:             $ok_response = 1;
 5121:         }
 5122:     }
 5123:     if ($ok_response) {
 5124:         return 'ok';
 5125:     } else {
 5126:         return $response;
 5127:     }
 5128: }
 5129: 
 5130: sub auto_instcode_defaults {
 5131:     my ($domain,$returnhash,$code_order) = @_;
 5132:     my @homeservers;
 5133: 
 5134:     my %servers = &get_servers($domain,'library');
 5135:     foreach my $tryserver (keys(%servers)) {
 5136: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5137: 	    push(@homeservers,$tryserver);
 5138: 	}
 5139:     }
 5140: 
 5141:     my $response;
 5142:     foreach my $server (@homeservers) {
 5143:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5144:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5145: 	
 5146: 	foreach my $pair (split(/\&/,$response)) {
 5147: 	    my ($name,$value)=split(/\=/,$pair);
 5148: 	    if ($name eq 'code_order') {
 5149: 		@{$code_order} = split(/\&/,&unescape($value));
 5150: 	    } else {
 5151: 		$returnhash->{&unescape($name)}=&unescape($value);
 5152: 	    }
 5153: 	}
 5154: 	return 'ok';
 5155:     }
 5156: 
 5157:     return $response;
 5158: } 
 5159: 
 5160: sub auto_validate_class_sec {
 5161:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5162:     my $homeserver = &homeserver($cnum,$cdom);
 5163:     my $ownerlist;
 5164:     if (ref($owners) eq 'ARRAY') {
 5165:         $ownerlist = join(',',@{$owners});
 5166:     } else {
 5167:         $ownerlist = $owners;
 5168:     }
 5169:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5170:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5171:     return $response;
 5172: }
 5173: 
 5174: # ------------------------------------------------------- Course Group routines
 5175: 
 5176: sub get_coursegroups {
 5177:     my ($cdom,$cnum,$group,$namespace) = @_;
 5178:     return(&dump($namespace,$cdom,$cnum,$group));
 5179: }
 5180: 
 5181: sub modify_coursegroup {
 5182:     my ($cdom,$cnum,$groupsettings) = @_;
 5183:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5184: }
 5185: 
 5186: sub toggle_coursegroup_status {
 5187:     my ($cdom,$cnum,$group,$action) = @_;
 5188:     my ($from_namespace,$to_namespace);
 5189:     if ($action eq 'delete') {
 5190:         $from_namespace = 'coursegroups';
 5191:         $to_namespace = 'deleted_groups';
 5192:     } else {
 5193:         $from_namespace = 'deleted_groups';
 5194:         $to_namespace = 'coursegroups';
 5195:     }
 5196:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5197:     if (my $tmp = &error(%curr_group)) {
 5198:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5199:         return ('read error',$tmp);
 5200:     } else {
 5201:         my %savedsettings = %curr_group; 
 5202:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5203:         my $deloutcome;
 5204:         if ($result eq 'ok') {
 5205:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5206:         } else {
 5207:             return ('write error',$result);
 5208:         }
 5209:         if ($deloutcome eq 'ok') {
 5210:             return 'ok';
 5211:         } else {
 5212:             return ('delete error',$deloutcome);
 5213:         }
 5214:     }
 5215: }
 5216: 
 5217: sub modify_group_roles {
 5218:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5219:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5220:     my $role = 'gr/'.&escape($userprivs);
 5221:     my ($uname,$udom) = split(/:/,$user);
 5222:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5223:     if ($result eq 'ok') {
 5224:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5225:     }
 5226:     return $result;
 5227: }
 5228: 
 5229: sub modify_coursegroup_membership {
 5230:     my ($cdom,$cnum,$membership) = @_;
 5231:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5232:     return $result;
 5233: }
 5234: 
 5235: sub get_active_groups {
 5236:     my ($udom,$uname,$cdom,$cnum) = @_;
 5237:     my $now = time;
 5238:     my %groups = ();
 5239:     foreach my $key (keys(%env)) {
 5240:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5241:             my ($start,$end) = split(/\./,$env{$key});
 5242:             if (($end!=0) && ($end<$now)) { next; }
 5243:             if (($start!=0) && ($start>$now)) { next; }
 5244:             if ($1 eq $cdom && $2 eq $cnum) {
 5245:                 $groups{$3} = $env{$key} ;
 5246:             }
 5247:         }
 5248:     }
 5249:     return %groups;
 5250: }
 5251: 
 5252: sub get_group_membership {
 5253:     my ($cdom,$cnum,$group) = @_;
 5254:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5255: }
 5256: 
 5257: sub get_users_groups {
 5258:     my ($udom,$uname,$courseid) = @_;
 5259:     my @usersgroups;
 5260:     my $cachetime=1800;
 5261: 
 5262:     my $hashid="$udom:$uname:$courseid";
 5263:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5264:     if (defined($cached)) {
 5265:         @usersgroups = split(/:/,$grouplist);
 5266:     } else {  
 5267:         $grouplist = '';
 5268:         my $courseurl = &courseid_to_courseurl($courseid);
 5269:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5270:         my $access_end = $env{'course.'.$courseid.
 5271:                               '.default_enrollment_end_date'};
 5272:         my $now = time;
 5273:         foreach my $key (keys(%roleshash)) {
 5274:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5275:                 my $group = $1;
 5276:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5277:                     my $start = $2;
 5278:                     my $end = $1;
 5279:                     if ($start == -1) { next; } # deleted from group
 5280:                     if (($start!=0) && ($start>$now)) { next; }
 5281:                     if (($end!=0) && ($end<$now)) {
 5282:                         if ($access_end && $access_end < $now) {
 5283:                             if ($access_end - $end < 86400) {
 5284:                                 push(@usersgroups,$group);
 5285:                             }
 5286:                         }
 5287:                         next;
 5288:                     }
 5289:                     push(@usersgroups,$group);
 5290:                 }
 5291:             }
 5292:         }
 5293:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5294:         $grouplist = join(':',@usersgroups);
 5295:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5296:     }
 5297:     return @usersgroups;
 5298: }
 5299: 
 5300: sub devalidate_getgroups_cache {
 5301:     my ($udom,$uname,$cdom,$cnum)=@_;
 5302:     my $courseid = $cdom.'_'.$cnum;
 5303: 
 5304:     my $hashid="$udom:$uname:$courseid";
 5305:     &devalidate_cache_new('getgroups',$hashid);
 5306: }
 5307: 
 5308: # ------------------------------------------------------------------ Plain Text
 5309: 
 5310: sub plaintext {
 5311:     my ($short,$type,$cid) = @_;
 5312:     if ($short =~ /^cr/) {
 5313: 	return (split('/',$short))[-1];
 5314:     }
 5315:     if (!defined($cid)) {
 5316:         $cid = $env{'request.course.id'};
 5317:     }
 5318:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5319:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5320:                                           '.plaintext'});
 5321:     }
 5322:     my %rolenames = (
 5323:                       Course => 'std',
 5324:                       Group => 'alt1',
 5325:                     );
 5326:     if (defined($type) && 
 5327:          defined($rolenames{$type}) && 
 5328:          defined($prp{$short}{$rolenames{$type}})) {
 5329:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5330:     } else {
 5331:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5332:     }
 5333: }
 5334: 
 5335: # ----------------------------------------------------------------- Assign Role
 5336: 
 5337: sub assignrole {
 5338:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll)=@_;
 5339:     my $mrole;
 5340:     if ($role =~ /^cr\//) {
 5341:         my $cwosec=$url;
 5342:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5343: 	unless (&allowed('ccr',$cwosec)) {
 5344:            &logthis('Refused custom assignrole: '.
 5345:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5346: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5347:            return 'refused'; 
 5348:         }
 5349:         $mrole='cr';
 5350:     } elsif ($role =~ /^gr\//) {
 5351:         my $cwogrp=$url;
 5352:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5353:         unless (&allowed('mdg',$cwogrp)) {
 5354:             &logthis('Refused group assignrole: '.
 5355:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5356:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5357:             return 'refused';
 5358:         }
 5359:         $mrole='gr';
 5360:     } else {
 5361:         my $cwosec=$url;
 5362:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5363:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5364:             my $refused;
 5365:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5366:                 if (!(&allowed('c'.$role,$url))) {
 5367:                     $refused = 1;
 5368:                 }
 5369:             } else {
 5370:                 $refused = 1;
 5371:             }
 5372:             if ($refused) {
 5373:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5374:                     $refused = '';
 5375:                 } else {
 5376:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5377:                              ' '.$role.' '.$end.' '.$start.' by '.
 5378: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5379:                     return 'refused';
 5380:                 }
 5381:             }
 5382:         }
 5383:         $mrole=$role;
 5384:     }
 5385:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5386:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5387:     if ($end) { $command.='_'.$end; }
 5388:     if ($start) {
 5389: 	if ($end) { 
 5390:            $command.='_'.$start; 
 5391:         } else {
 5392:            $command.='_0_'.$start;
 5393:         }
 5394:     }
 5395:     my $origstart = $start;
 5396:     my $origend = $end;
 5397: # actually delete
 5398:     if ($deleteflag) {
 5399: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5400: # modify command to delete the role
 5401:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5402:                 "$udom:$uname:$url".'_'."$mrole";
 5403: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5404: # set start and finish to negative values for userrolelog
 5405:            $start=-1;
 5406:            $end=-1;
 5407:         }
 5408:     }
 5409: # send command
 5410:     my $answer=&reply($command,&homeserver($uname,$udom));
 5411: # log new user role if status is ok
 5412:     if ($answer eq 'ok') {
 5413: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5414: # for course roles, perform group memberships changes triggered by role change.
 5415:         unless ($role =~ /^gr/) {
 5416:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5417:                                              $origstart);
 5418:         }
 5419:     }
 5420:     return $answer;
 5421: }
 5422: 
 5423: # -------------------------------------------------- Modify user authentication
 5424: # Overrides without validation
 5425: 
 5426: sub modifyuserauth {
 5427:     my ($udom,$uname,$umode,$upass)=@_;
 5428:     my $uhome=&homeserver($uname,$udom);
 5429:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5430:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5431:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5432:              ' in domain '.$env{'request.role.domain'});  
 5433:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5434: 		     &escape($upass),$uhome);
 5435:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5436:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5437:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5438:     &log($udom,,$uname,$uhome,
 5439:         'Authentication changed by '.$env{'user.domain'}.', '.
 5440:                                      $env{'user.name'}.', '.$umode.
 5441:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5442:     unless ($reply eq 'ok') {
 5443:         &logthis('Authentication mode error: '.$reply);
 5444: 	return 'error: '.$reply;
 5445:     }   
 5446:     return 'ok';
 5447: }
 5448: 
 5449: # --------------------------------------------------------------- Modify a user
 5450: 
 5451: sub modifyuser {
 5452:     my ($udom,    $uname, $uid,
 5453:         $umode,   $upass, $first,
 5454:         $middle,  $last,  $gene,
 5455:         $forceid, $desiredhome, $email)=@_;
 5456:     $udom= &LONCAPA::clean_domain($udom);
 5457:     $uname=&LONCAPA::clean_username($uname);
 5458:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5459:              $umode.', '.$first.', '.$middle.', '.
 5460: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5461:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5462:                                      ' desiredhome not specified'). 
 5463:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5464:              ' in domain '.$env{'request.role.domain'});
 5465:     my $uhome=&homeserver($uname,$udom,'true');
 5466: # ----------------------------------------------------------------- Create User
 5467:     if (($uhome eq 'no_host') && 
 5468: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5469:         my $unhome='';
 5470:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5471:             $unhome = $desiredhome;
 5472: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5473: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5474:         } else { # load balancing routine for determining $unhome
 5475:             my $loadm=10000000;
 5476: 	    my %servers = &get_servers($udom,'library');
 5477: 	    foreach my $tryserver (keys(%servers)) {
 5478: 		my $answer=reply('load',$tryserver);
 5479: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5480: 		    $loadm=$answer;
 5481: 		    $unhome=$tryserver;
 5482: 		}
 5483: 	    }
 5484:         }
 5485:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5486: 	    return 'error: unable to find a home server for '.$uname.
 5487:                    ' in domain '.$udom;
 5488:         }
 5489:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5490:                          &escape($upass),$unhome);
 5491: 	unless ($reply eq 'ok') {
 5492:             return 'error: '.$reply;
 5493:         }   
 5494:         $uhome=&homeserver($uname,$udom,'true');
 5495:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5496: 	    return 'error: unable verify users home machine.';
 5497:         }
 5498:     }   # End of creation of new user
 5499: # ---------------------------------------------------------------------- Add ID
 5500:     if ($uid) {
 5501:        $uid=~tr/A-Z/a-z/;
 5502:        my %uidhash=&idrget($udom,$uname);
 5503:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5504:          && (!$forceid)) {
 5505: 	  unless ($uid eq $uidhash{$uname}) {
 5506: 	      return 'error: user id "'.$uid.'" does not match '.
 5507:                   'current user id "'.$uidhash{$uname}.'".';
 5508:           }
 5509:        } else {
 5510: 	  &idput($udom,($uname => $uid));
 5511:        }
 5512:     }
 5513: # -------------------------------------------------------------- Add names, etc
 5514:     my @tmp=&get('environment',
 5515: 		   ['firstname','middlename','lastname','generation','id',
 5516:                     'permanentemail'],
 5517: 		   $udom,$uname);
 5518:     my %names;
 5519:     if ($tmp[0] =~ m/^error:.*/) { 
 5520:         %names=(); 
 5521:     } else {
 5522:         %names = @tmp;
 5523:     }
 5524: #
 5525: # Make sure to not trash student environment if instructor does not bother
 5526: # to supply name and email information
 5527: #
 5528:     if ($first)  { $names{'firstname'}  = $first; }
 5529:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5530:     if ($last)   { $names{'lastname'}   = $last; }
 5531:     if (defined($gene))   { $names{'generation'} = $gene; }
 5532:     if ($email) {
 5533:        $email=~s/[^\w\@\.\-\,]//gs;
 5534:        if ($email=~/\@/) { $names{'notification'} = $email;
 5535: 			   $names{'critnotification'} = $email;
 5536: 			   $names{'permanentemail'} = $email; }
 5537:     }
 5538:     if ($uid) { $names{'id'}  = $uid; }
 5539:     my $reply = &put('environment', \%names, $udom,$uname);
 5540:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5541:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5542:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5543:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5544:              $umode.', '.$first.', '.$middle.', '.
 5545: 	     $last.', '.$gene.' by '.
 5546:              $env{'user.name'}.' at '.$env{'user.domain'});
 5547:     return 'ok';
 5548: }
 5549: 
 5550: # -------------------------------------------------------------- Modify student
 5551: 
 5552: sub modifystudent {
 5553:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5554:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5555:     if (!$cid) {
 5556: 	unless ($cid=$env{'request.course.id'}) {
 5557: 	    return 'not_in_class';
 5558: 	}
 5559:     }
 5560: # --------------------------------------------------------------- Make the user
 5561:     my $reply=&modifyuser
 5562: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5563:          $desiredhome,$email);
 5564:     unless ($reply eq 'ok') { return $reply; }
 5565:     # This will cause &modify_student_enrollment to get the uid from the
 5566:     # students environment
 5567:     $uid = undef if (!$forceid);
 5568:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5569: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5570:     return $reply;
 5571: }
 5572: 
 5573: sub modify_student_enrollment {
 5574:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll) = @_;
 5575:     my ($cdom,$cnum,$chome);
 5576:     if (!$cid) {
 5577: 	unless ($cid=$env{'request.course.id'}) {
 5578: 	    return 'not_in_class';
 5579: 	}
 5580: 	$cdom=$env{'course.'.$cid.'.domain'};
 5581: 	$cnum=$env{'course.'.$cid.'.num'};
 5582:     } else {
 5583: 	($cdom,$cnum)=split(/_/,$cid);
 5584:     }
 5585:     $chome=$env{'course.'.$cid.'.home'};
 5586:     if (!$chome) {
 5587: 	$chome=&homeserver($cnum,$cdom);
 5588:     }
 5589:     if (!$chome) { return 'unknown_course'; }
 5590:     # Make sure the user exists
 5591:     my $uhome=&homeserver($uname,$udom);
 5592:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5593: 	return 'error: no such user';
 5594:     }
 5595:     # Get student data if we were not given enough information
 5596:     if (!defined($first)  || $first  eq '' || 
 5597:         !defined($last)   || $last   eq '' || 
 5598:         !defined($uid)    || $uid    eq '' || 
 5599:         !defined($middle) || $middle eq '' || 
 5600:         !defined($gene)   || $gene   eq '') {
 5601:         # They did not supply us with enough data to enroll the student, so
 5602:         # we need to pick up more information.
 5603:         my %tmp = &get('environment',
 5604:                        ['firstname','middlename','lastname', 'generation','id']
 5605:                        ,$udom,$uname);
 5606: 
 5607:         #foreach my $key (keys(%tmp)) {
 5608:         #    &logthis("key $key = ".$tmp{$key});
 5609:         #}
 5610:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5611:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5612:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5613:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5614:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5615:     }
 5616:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5617:     my $reply=cput('classlist',
 5618: 		   {"$uname:$udom" => 
 5619: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5620: 		   $cdom,$cnum);
 5621:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5622: 	return 'error: '.$reply;
 5623:     } else {
 5624: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5625:     }
 5626:     # Add student role to user
 5627:     my $uurl='/'.$cid;
 5628:     $uurl=~s/\_/\//g;
 5629:     if ($usec) {
 5630: 	$uurl.='/'.$usec;
 5631:     }
 5632:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll);
 5633: }
 5634: 
 5635: sub format_name {
 5636:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5637:     my $name;
 5638:     if ($first ne 'lastname') {
 5639: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5640:     } else {
 5641: 	if ($lastname=~/\S/) {
 5642: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5643: 	    $name=~s/\s+,/,/;
 5644: 	} else {
 5645: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5646: 	}
 5647:     }
 5648:     $name=~s/^\s+//;
 5649:     $name=~s/\s+$//;
 5650:     $name=~s/\s+/ /g;
 5651:     return $name;
 5652: }
 5653: 
 5654: # ------------------------------------------------- Write to course preferences
 5655: 
 5656: sub writecoursepref {
 5657:     my ($courseid,%prefs)=@_;
 5658:     $courseid=~s/^\///;
 5659:     $courseid=~s/\_/\//g;
 5660:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5661:     my $chome=homeserver($cnum,$cdomain);
 5662:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5663: 	return 'error: no such course';
 5664:     }
 5665:     my $cstring='';
 5666:     foreach my $pref (keys(%prefs)) {
 5667: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5668:     }
 5669:     $cstring=~s/\&$//;
 5670:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5671: }
 5672: 
 5673: # ---------------------------------------------------------- Make/modify course
 5674: 
 5675: sub createcourse {
 5676:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5677:         $course_owner,$crstype)=@_;
 5678:     $url=&declutter($url);
 5679:     my $cid='';
 5680:     unless (&allowed('ccc',$udom)) {
 5681:         return 'refused';
 5682:     }
 5683: # ------------------------------------------------------------------- Create ID
 5684:    my $uname=int(1+rand(9)).
 5685:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5686:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5687:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5688: # ----------------------------------------------- Make sure that does not exist
 5689:    my $uhome=&homeserver($uname,$udom,'true');
 5690:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5691:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5692:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5693:        $uhome=&homeserver($uname,$udom,'true');       
 5694:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5695:            return 'error: unable to generate unique course-ID';
 5696:        } 
 5697:    }
 5698: # ------------------------------------------------ Check supplied server name
 5699:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5700:     if (! &is_library($course_server)) {
 5701:         return 'error:bad server name '.$course_server;
 5702:     }
 5703: # ------------------------------------------------------------- Make the course
 5704:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5705:                       $course_server);
 5706:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5707:     $uhome=&homeserver($uname,$udom,'true');
 5708:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5709: 	return 'error: no such course';
 5710:     }
 5711: # ----------------------------------------------------------------- Course made
 5712: # log existence
 5713:     my $newcourse = {
 5714:                     $udom.'_'.$uname => {
 5715:                                      description => $description,
 5716:                                      inst_code   => $inst_code,
 5717:                                      owner       => $course_owner,
 5718:                                      type        => $crstype,
 5719:                                                 },
 5720:                     };
 5721:     &courseidput($udom,$newcourse,$uhome,'notime');
 5722: # set toplevel url
 5723:     my $topurl=$url;
 5724:     unless ($nonstandard) {
 5725: # ------------------------------------------ For standard courses, make top url
 5726:         my $mapurl=&clutter($url);
 5727:         if ($mapurl eq '/res/') { $mapurl=''; }
 5728:         $env{'form.initmap'}=(<<ENDINITMAP);
 5729: <map>
 5730: <resource id="1" type="start"></resource>
 5731: <resource id="2" src="$mapurl"></resource>
 5732: <resource id="3" type="finish"></resource>
 5733: <link index="1" from="1" to="2"></link>
 5734: <link index="2" from="2" to="3"></link>
 5735: </map>
 5736: ENDINITMAP
 5737:         $topurl=&declutter(
 5738:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5739:                           );
 5740:     }
 5741: # ----------------------------------------------------------- Write preferences
 5742:     &writecoursepref($udom.'_'.$uname,
 5743:                      ('description' => $description,
 5744:                       'url'         => $topurl));
 5745:     return '/'.$udom.'/'.$uname;
 5746: }
 5747: 
 5748: sub is_course {
 5749:     my ($cdom,$cnum) = @_;
 5750:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5751: 				undef,'.');
 5752:     if (exists($courses{$cdom.'_'.$cnum})) {
 5753:         return 1;
 5754:     }
 5755:     return 0;
 5756: }
 5757: 
 5758: # ---------------------------------------------------------- Assign Custom Role
 5759: 
 5760: sub assigncustomrole {
 5761:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5762:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5763:                        $end,$start,$deleteflag);
 5764: }
 5765: 
 5766: # ----------------------------------------------------------------- Revoke Role
 5767: 
 5768: sub revokerole {
 5769:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5770:     my $now=time;
 5771:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5772: }
 5773: 
 5774: # ---------------------------------------------------------- Revoke Custom Role
 5775: 
 5776: sub revokecustomrole {
 5777:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5778:     my $now=time;
 5779:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5780:            $deleteflag);
 5781: }
 5782: 
 5783: # ------------------------------------------------------------ Disk usage
 5784: sub diskusage {
 5785:     my ($udom,$uname,$directoryRoot)=@_;
 5786:     $directoryRoot =~ s/\/$//;
 5787:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5788:     return $listing;
 5789: }
 5790: 
 5791: sub is_locked {
 5792:     my ($file_name, $domain, $user) = @_;
 5793:     my @check;
 5794:     my $is_locked;
 5795:     push @check, $file_name;
 5796:     my %locked = &get('file_permissions',\@check,
 5797: 		      $env{'user.domain'},$env{'user.name'});
 5798:     my ($tmp)=keys(%locked);
 5799:     if ($tmp=~/^error:/) { undef(%locked); }
 5800:     
 5801:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5802:         $is_locked = 'false';
 5803:         foreach my $entry (@{$locked{$file_name}}) {
 5804:            if (ref($entry) eq 'ARRAY') { 
 5805:                $is_locked = 'true';
 5806:                last;
 5807:            }
 5808:        }
 5809:     } else {
 5810:         $is_locked = 'false';
 5811:     }
 5812: }
 5813: 
 5814: sub declutter_portfile {
 5815:     my ($file) = @_;
 5816:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5817:     return $file;
 5818: }
 5819: 
 5820: # ------------------------------------------------------------- Mark as Read Only
 5821: 
 5822: sub mark_as_readonly {
 5823:     my ($domain,$user,$files,$what) = @_;
 5824:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5825:     my ($tmp)=keys(%current_permissions);
 5826:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5827:     foreach my $file (@{$files}) {
 5828: 	$file = &declutter_portfile($file);
 5829:         push(@{$current_permissions{$file}},$what);
 5830:     }
 5831:     &put('file_permissions',\%current_permissions,$domain,$user);
 5832:     return;
 5833: }
 5834: 
 5835: # ------------------------------------------------------------Save Selected Files
 5836: 
 5837: sub save_selected_files {
 5838:     my ($user, $path, @files) = @_;
 5839:     my $filename = $user."savedfiles";
 5840:     my @other_files = &files_not_in_path($user, $path);
 5841:     open (OUT, '>'.$tmpdir.$filename);
 5842:     foreach my $file (@files) {
 5843:         print (OUT $env{'form.currentpath'}.$file."\n");
 5844:     }
 5845:     foreach my $file (@other_files) {
 5846:         print (OUT $file."\n");
 5847:     }
 5848:     close (OUT);
 5849:     return 'ok';
 5850: }
 5851: 
 5852: sub clear_selected_files {
 5853:     my ($user) = @_;
 5854:     my $filename = $user."savedfiles";
 5855:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5856:     print (OUT undef);
 5857:     close (OUT);
 5858:     return ("ok");    
 5859: }
 5860: 
 5861: sub files_in_path {
 5862:     my ($user, $path) = @_;
 5863:     my $filename = $user."savedfiles";
 5864:     my %return_files;
 5865:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5866:     while (my $line_in = <IN>) {
 5867:         chomp ($line_in);
 5868:         my @paths_and_file = split (m!/!, $line_in);
 5869:         my $file_part = pop (@paths_and_file);
 5870:         my $path_part = join ('/', @paths_and_file);
 5871:         $path_part.='/';
 5872:         my $path_and_file = $path_part.$file_part;
 5873:         if ($path_part eq $path) {
 5874:             $return_files{$file_part}= 'selected';
 5875:         }
 5876:     }
 5877:     close (IN);
 5878:     return (\%return_files);
 5879: }
 5880: 
 5881: # called in portfolio select mode, to show files selected NOT in current directory
 5882: sub files_not_in_path {
 5883:     my ($user, $path) = @_;
 5884:     my $filename = $user."savedfiles";
 5885:     my @return_files;
 5886:     my $path_part;
 5887:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5888:     while (my $line = <IN>) {
 5889:         #ok, I know it's clunky, but I want it to work
 5890:         my @paths_and_file = split(m|/|, $line);
 5891:         my $file_part = pop(@paths_and_file);
 5892:         chomp($file_part);
 5893:         my $path_part = join('/', @paths_and_file);
 5894:         $path_part .= '/';
 5895:         my $path_and_file = $path_part.$file_part;
 5896:         if ($path_part ne $path) {
 5897:             push(@return_files, ($path_and_file));
 5898:         }
 5899:     }
 5900:     close(OUT);
 5901:     return (@return_files);
 5902: }
 5903: 
 5904: #----------------------------------------------Get portfolio file permissions
 5905: 
 5906: sub get_portfile_permissions {
 5907:     my ($domain,$user) = @_;
 5908:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5909:     my ($tmp)=keys(%current_permissions);
 5910:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5911:     return \%current_permissions;
 5912: }
 5913: 
 5914: #---------------------------------------------Get portfolio file access controls
 5915: 
 5916: sub get_access_controls {
 5917:     my ($current_permissions,$group,$file) = @_;
 5918:     my %access;
 5919:     my $real_file = $file;
 5920:     $file =~ s/\.meta$//;
 5921:     if (defined($file)) {
 5922:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5923:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5924:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5925:             }
 5926:         }
 5927:     } else {
 5928:         foreach my $key (keys(%{$current_permissions})) {
 5929:             if ($key =~ /\0accesscontrol$/) {
 5930:                 if (defined($group)) {
 5931:                     if ($key !~ m-^\Q$group\E/-) {
 5932:                         next;
 5933:                     }
 5934:                 }
 5935:                 my ($fullpath) = split(/\0/,$key);
 5936:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5937:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5938:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5939:                     }
 5940:                 }
 5941:             }
 5942:         }
 5943:     }
 5944:     return %access;
 5945: }
 5946: 
 5947: sub modify_access_controls {
 5948:     my ($file_name,$changes,$domain,$user)=@_;
 5949:     my ($outcome,$deloutcome);
 5950:     my %store_permissions;
 5951:     my %new_values;
 5952:     my %new_control;
 5953:     my %translation;
 5954:     my @deletions = ();
 5955:     my $now = time;
 5956:     if (exists($$changes{'activate'})) {
 5957:         if (ref($$changes{'activate'}) eq 'HASH') {
 5958:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5959:             my $numnew = scalar(@newitems);
 5960:             for (my $i=0; $i<$numnew; $i++) {
 5961:                 my $newkey = $newitems[$i];
 5962:                 my $newid = &Apache::loncommon::get_cgi_id();
 5963:                 if ($newkey =~ /^\d+:/) { 
 5964:                     $newkey =~ s/^(\d+)/$newid/;
 5965:                     $translation{$1} = $newid;
 5966:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5967:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5968:                     $translation{$1} = $newid;
 5969:                 }
 5970:                 $new_values{$file_name."\0".$newkey} = 
 5971:                                           $$changes{'activate'}{$newitems[$i]};
 5972:                 $new_control{$newkey} = $now;
 5973:             }
 5974:         }
 5975:     }
 5976:     my %todelete;
 5977:     my %changed_items;
 5978:     foreach my $action ('delete','update') {
 5979:         if (exists($$changes{$action})) {
 5980:             if (ref($$changes{$action}) eq 'HASH') {
 5981:                 foreach my $key (keys(%{$$changes{$action}})) {
 5982:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5983:                     if ($action eq 'delete') { 
 5984:                         $todelete{$itemnum} = 1;
 5985:                     } else {
 5986:                         $changed_items{$itemnum} = $key;
 5987:                     }
 5988:                 }
 5989:             }
 5990:         }
 5991:     }
 5992:     # get lock on access controls for file.
 5993:     my $lockhash = {
 5994:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5995:                                                        ':'.$env{'user.domain'},
 5996:                    }; 
 5997:     my $tries = 0;
 5998:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5999:    
 6000:     while (($gotlock ne 'ok') && $tries <3) {
 6001:         $tries ++;
 6002:         sleep 1;
 6003:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6004:     }
 6005:     if ($gotlock eq 'ok') {
 6006:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6007:         my ($tmp)=keys(%curr_permissions);
 6008:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6009:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6010:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6011:             if (ref($curr_controls) eq 'HASH') {
 6012:                 foreach my $control_item (keys(%{$curr_controls})) {
 6013:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6014:                     if (defined($todelete{$itemnum})) {
 6015:                         push(@deletions,$file_name."\0".$control_item);
 6016:                     } else {
 6017:                         if (defined($changed_items{$itemnum})) {
 6018:                             $new_control{$changed_items{$itemnum}} = $now;
 6019:                             push(@deletions,$file_name."\0".$control_item);
 6020:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6021:                         } else {
 6022:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6023:                         }
 6024:                     }
 6025:                 }
 6026:             }
 6027:         }
 6028:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6029:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6030:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6031:         #  remove lock
 6032:         my @del_lock = ($file_name."\0".'locked_access_records');
 6033:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6034:         my ($file,$group);
 6035:         if (&is_course($domain,$user)) {
 6036:             ($group,$file) = split(/\//,$file_name,2);
 6037:         } else {
 6038:             $file = $file_name;
 6039:         }
 6040:         my $sqlresult =
 6041:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 6042:                                     $group);
 6043:     } else {
 6044:         $outcome = "error: could not obtain lockfile\n";  
 6045:     }
 6046:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6047: }
 6048: 
 6049: sub make_public_indefinitely {
 6050:     my ($requrl) = @_;
 6051:     my $now = time;
 6052:     my $action = 'activate';
 6053:     my $aclnum = 0;
 6054:     if (&is_portfolio_url($requrl)) {
 6055:         my (undef,$udom,$unum,$file_name,$group) =
 6056:             &parse_portfolio_url($requrl);
 6057:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6058:         my %access_controls = &get_access_controls($current_perms,
 6059:                                                    $group,$file_name);
 6060:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6061:             my ($num,$scope,$end,$start) = 
 6062:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6063:             if ($scope eq 'public') {
 6064:                 if ($start <= $now && $end == 0) {
 6065:                     $action = 'none';
 6066:                 } else {
 6067:                     $action = 'update';
 6068:                     $aclnum = $num;
 6069:                 }
 6070:                 last;
 6071:             }
 6072:         }
 6073:         if ($action eq 'none') {
 6074:              return 'ok';
 6075:         } else {
 6076:             my %changes;
 6077:             my $newend = 0;
 6078:             my $newstart = $now;
 6079:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6080:             $changes{$action}{$newkey} = {
 6081:                 type => 'public',
 6082:                 time => {
 6083:                     start => $newstart,
 6084:                     end   => $newend,
 6085:                 },
 6086:             };
 6087:             my ($outcome,$deloutcome,$new_values,$translation) =
 6088:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6089:             return $outcome;
 6090:         }
 6091:     } else {
 6092:         return 'invalid';
 6093:     }
 6094: }
 6095: 
 6096: #------------------------------------------------------Get Marked as Read Only
 6097: 
 6098: sub get_marked_as_readonly {
 6099:     my ($domain,$user,$what,$group) = @_;
 6100:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6101:     my @readonly_files;
 6102:     my $cmp1=$what;
 6103:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6104:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6105:         if (defined($group)) {
 6106:             if ($file_name !~ m-^\Q$group\E/-) {
 6107:                 next;
 6108:             }
 6109:         }
 6110:         if (ref($value) eq "ARRAY"){
 6111:             foreach my $stored_what (@{$value}) {
 6112:                 my $cmp2=$stored_what;
 6113:                 if (ref($stored_what) eq 'ARRAY') {
 6114:                     $cmp2=join('',@{$stored_what});
 6115:                 }
 6116:                 if ($cmp1 eq $cmp2) {
 6117:                     push(@readonly_files, $file_name);
 6118:                     last;
 6119:                 } elsif (!defined($what)) {
 6120:                     push(@readonly_files, $file_name);
 6121:                     last;
 6122:                 }
 6123:             }
 6124:         }
 6125:     }
 6126:     return @readonly_files;
 6127: }
 6128: #-----------------------------------------------------------Get Marked as Read Only Hash
 6129: 
 6130: sub get_marked_as_readonly_hash {
 6131:     my ($current_permissions,$group,$what) = @_;
 6132:     my %readonly_files;
 6133:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6134:         if (defined($group)) {
 6135:             if ($file_name !~ m-^\Q$group\E/-) {
 6136:                 next;
 6137:             }
 6138:         }
 6139:         if (ref($value) eq "ARRAY"){
 6140:             foreach my $stored_what (@{$value}) {
 6141:                 if (ref($stored_what) eq 'ARRAY') {
 6142:                     foreach my $lock_descriptor(@{$stored_what}) {
 6143:                         if ($lock_descriptor eq 'graded') {
 6144:                             $readonly_files{$file_name} = 'graded';
 6145:                         } elsif ($lock_descriptor eq 'handback') {
 6146:                             $readonly_files{$file_name} = 'handback';
 6147:                         } else {
 6148:                             if (!exists($readonly_files{$file_name})) {
 6149:                                 $readonly_files{$file_name} = 'locked';
 6150:                             }
 6151:                         }
 6152:                     }
 6153:                 } 
 6154:             }
 6155:         } 
 6156:     }
 6157:     return %readonly_files;
 6158: }
 6159: # ------------------------------------------------------------ Unmark as Read Only
 6160: 
 6161: sub unmark_as_readonly {
 6162:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6163:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6164:     my ($domain,$user,$what,$file_name,$group) = @_;
 6165:     $file_name = &declutter_portfile($file_name);
 6166:     my $symb_crs = $what;
 6167:     if (ref($what)) { $symb_crs=join('',@$what); }
 6168:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6169:     my ($tmp)=keys(%current_permissions);
 6170:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6171:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6172:     foreach my $file (@readonly_files) {
 6173: 	my $clean_file = &declutter_portfile($file);
 6174: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6175: 	my $current_locks = $current_permissions{$file};
 6176:         my @new_locks;
 6177:         my @del_keys;
 6178:         if (ref($current_locks) eq "ARRAY"){
 6179:             foreach my $locker (@{$current_locks}) {
 6180:                 my $compare=$locker;
 6181:                 if (ref($locker) eq 'ARRAY') {
 6182:                     $compare=join('',@{$locker});
 6183:                     if ($compare ne $symb_crs) {
 6184:                         push(@new_locks, $locker);
 6185:                     }
 6186:                 }
 6187:             }
 6188:             if (scalar(@new_locks) > 0) {
 6189:                 $current_permissions{$file} = \@new_locks;
 6190:             } else {
 6191:                 push(@del_keys, $file);
 6192:                 &del('file_permissions',\@del_keys, $domain, $user);
 6193:                 delete($current_permissions{$file});
 6194:             }
 6195:         }
 6196:     }
 6197:     &put('file_permissions',\%current_permissions,$domain,$user);
 6198:     return;
 6199: }
 6200: 
 6201: # ------------------------------------------------------------ Directory lister
 6202: 
 6203: sub dirlist {
 6204:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6205: 
 6206:     $uri=~s/^\///;
 6207:     $uri=~s/\/$//;
 6208:     my ($udom, $uname);
 6209:     (undef,$udom,$uname)=split(/\//,$uri);
 6210:     if(defined($userdomain)) {
 6211:         $udom = $userdomain;
 6212:     }
 6213:     if(defined($username)) {
 6214:         $uname = $username;
 6215:     }
 6216: 
 6217:     my $dirRoot = $perlvar{'lonDocRoot'};
 6218:     if(defined($alternateDirectoryRoot)) {
 6219:         $dirRoot = $alternateDirectoryRoot;
 6220:         $dirRoot =~ s/\/$//;
 6221:     }
 6222: 
 6223:     if($udom) {
 6224:         if($uname) {
 6225:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6226: 				 &homeserver($uname,$udom));
 6227:             my @listing_results;
 6228:             if ($listing eq 'unknown_cmd') {
 6229:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6230: 				  &homeserver($uname,$udom));
 6231:                 @listing_results = split(/:/,$listing);
 6232:             } else {
 6233:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6234:             }
 6235:             return @listing_results;
 6236:         } elsif(!defined($alternateDirectoryRoot)) {
 6237:             my %allusers;
 6238: 	    my %servers = &get_servers($udom,'library');
 6239: 	    foreach my $tryserver (keys(%servers)) {
 6240: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6241: 				     $udom, $tryserver);
 6242: 		my @listing_results;
 6243: 		if ($listing eq 'unknown_cmd') {
 6244: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6245: 				      $udom, $tryserver);
 6246: 		    @listing_results = split(/:/,$listing);
 6247: 		} else {
 6248: 		    @listing_results =
 6249: 			map { &unescape($_); } split(/:/,$listing);
 6250: 		}
 6251: 		if ($listing_results[0] ne 'no_such_dir' && 
 6252: 		    $listing_results[0] ne 'empty'       &&
 6253: 		    $listing_results[0] ne 'con_lost') {
 6254: 		    foreach my $line (@listing_results) {
 6255: 			my ($entry) = split(/&/,$line,2);
 6256: 			$allusers{$entry} = 1;
 6257: 		    }
 6258: 		}
 6259:             }
 6260:             my $alluserstr='';
 6261:             foreach my $user (sort(keys(%allusers))) {
 6262:                 $alluserstr.=$user.'&user:';
 6263:             }
 6264:             $alluserstr=~s/:$//;
 6265:             return split(/:/,$alluserstr);
 6266:         } else {
 6267:             return ('missing user name');
 6268:         }
 6269:     } elsif(!defined($alternateDirectoryRoot)) {
 6270:         my @all_domains = sort(&all_domains());
 6271:          foreach my $domain (@all_domains) {
 6272:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6273:          }
 6274:          return @all_domains;
 6275:      } else {
 6276:         return ('missing domain');
 6277:     }
 6278: }
 6279: 
 6280: # --------------------------------------------- GetFileTimestamp
 6281: # This function utilizes dirlist and returns the date stamp for
 6282: # when it was last modified.  It will also return an error of -1
 6283: # if an error occurs
 6284: 
 6285: ##
 6286: ## FIXME: This subroutine assumes its caller knows something about the
 6287: ## directory structure of the home server for the student ($root).
 6288: ## Not a good assumption to make.  Since this is for looking up files
 6289: ## in user directories, the full path should be constructed by lond, not
 6290: ## whatever machine we request data from.
 6291: ##
 6292: sub GetFileTimestamp {
 6293:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6294:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6295:     $studentName   = &LONCAPA::clean_username($studentName);
 6296:     my $subdir=$studentName.'__';
 6297:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6298:     my $proname="$studentDomain/$subdir/$studentName";
 6299:     $proname .= '/'.$filename;
 6300:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6301:                                               $studentName, $root);
 6302:     my @stats = split('&', $fileStat);
 6303:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6304:         # @stats contains first the filename, then the stat output
 6305:         return $stats[10]; # so this is 10 instead of 9.
 6306:     } else {
 6307:         return -1;
 6308:     }
 6309: }
 6310: 
 6311: sub stat_file {
 6312:     my ($uri) = @_;
 6313:     $uri = &clutter_with_no_wrapper($uri);
 6314: 
 6315:     my ($udom,$uname,$file,$dir);
 6316:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6317: 	($udom,$uname,$file) =
 6318: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6319: 	$file = 'userfiles/'.$file;
 6320: 	$dir = &propath($udom,$uname);
 6321:     }
 6322:     if ($uri =~ m-^/res/-) {
 6323: 	($udom,$uname) = 
 6324: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6325: 	$file = $uri;
 6326:     }
 6327: 
 6328:     if (!$udom || !$uname || !$file) {
 6329: 	# unable to handle the uri
 6330: 	return ();
 6331:     }
 6332: 
 6333:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6334:     my @stats = split('&', $result);
 6335:     
 6336:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6337: 	shift(@stats); #filename is first
 6338: 	return @stats;
 6339:     }
 6340:     return ();
 6341: }
 6342: 
 6343: # -------------------------------------------------------- Value of a Condition
 6344: 
 6345: # gets the value of a specific preevaluated condition
 6346: #    stored in the string  $env{user.state.<cid>}
 6347: # or looks up a condition reference in the bighash and if if hasn't
 6348: # already been evaluated recurses into docondval to get the value of
 6349: # the condition, then memoizing it to 
 6350: #   $env{user.state.<cid>.<condition>}
 6351: sub directcondval {
 6352:     my $number=shift;
 6353:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6354: 	&Apache::lonuserstate::evalstate();
 6355:     }
 6356:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6357: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6358:     } elsif ($number =~ /^_/) {
 6359: 	my $sub_condition;
 6360: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6361: 		&GDBM_READER(),0640)) {
 6362: 	    $sub_condition=$bighash{'conditions'.$number};
 6363: 	    untie(%bighash);
 6364: 	}
 6365: 	my $value = &docondval($sub_condition);
 6366: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6367: 	return $value;
 6368:     }
 6369:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6370:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6371:     } else {
 6372:        return 2;
 6373:     }
 6374: }
 6375: 
 6376: # get the collection of conditions for this resource
 6377: sub condval {
 6378:     my $condidx=shift;
 6379:     my $allpathcond='';
 6380:     foreach my $cond (split(/\|/,$condidx)) {
 6381: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6382: 	    $allpathcond.=
 6383: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6384: 	}
 6385:     }
 6386:     $allpathcond=~s/\|$//;
 6387:     return &docondval($allpathcond);
 6388: }
 6389: 
 6390: #evaluates an expression of conditions
 6391: sub docondval {
 6392:     my ($allpathcond) = @_;
 6393:     my $result=0;
 6394:     if ($env{'request.course.id'}
 6395: 	&& defined($allpathcond)) {
 6396: 	my $operand='|';
 6397: 	my @stack;
 6398: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6399: 	    if ($chunk eq '(') {
 6400: 		push @stack,($operand,$result);
 6401: 	    } elsif ($chunk eq ')') {
 6402: 		my $before=pop @stack;
 6403: 		if (pop @stack eq '&') {
 6404: 		    $result=$result>$before?$before:$result;
 6405: 		} else {
 6406: 		    $result=$result>$before?$result:$before;
 6407: 		}
 6408: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6409: 		$operand=$chunk;
 6410: 	    } else {
 6411: 		my $new=directcondval($chunk);
 6412: 		if ($operand eq '&') {
 6413: 		    $result=$result>$new?$new:$result;
 6414: 		} else {
 6415: 		    $result=$result>$new?$result:$new;
 6416: 		}
 6417: 	    }
 6418: 	}
 6419:     }
 6420:     return $result;
 6421: }
 6422: 
 6423: # ---------------------------------------------------- Devalidate courseresdata
 6424: 
 6425: sub devalidatecourseresdata {
 6426:     my ($coursenum,$coursedomain)=@_;
 6427:     my $hashid=$coursenum.':'.$coursedomain;
 6428:     &devalidate_cache_new('courseres',$hashid);
 6429: }
 6430: 
 6431: 
 6432: # --------------------------------------------------- Course Resourcedata Query
 6433: #
 6434: #  Parameters:
 6435: #      $coursenum    - Number of the course.
 6436: #      $coursedomain - Domain at which the course was created.
 6437: #  Returns:
 6438: #     A hash of the course parameters along (I think) with timestamps
 6439: #     and version info.
 6440: 
 6441: sub get_courseresdata {
 6442:     my ($coursenum,$coursedomain)=@_;
 6443:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6444:     my $hashid=$coursenum.':'.$coursedomain;
 6445:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6446:     my %dumpreply;
 6447:     unless (defined($cached)) {
 6448: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6449: 	$result=\%dumpreply;
 6450: 	my ($tmp) = keys(%dumpreply);
 6451: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6452: 	    &do_cache_new('courseres',$hashid,$result,600);
 6453: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6454: 	    return $tmp;
 6455: 	} elsif ($tmp =~ /^(error)/) {
 6456: 	    $result=undef;
 6457: 	    &do_cache_new('courseres',$hashid,$result,600);
 6458: 	}
 6459:     }
 6460:     return $result;
 6461: }
 6462: 
 6463: sub devalidateuserresdata {
 6464:     my ($uname,$udom)=@_;
 6465:     my $hashid="$udom:$uname";
 6466:     &devalidate_cache_new('userres',$hashid);
 6467: }
 6468: 
 6469: sub get_userresdata {
 6470:     my ($uname,$udom)=@_;
 6471:     #most student don\'t have any data set, check if there is some data
 6472:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6473: 
 6474:     my $hashid="$udom:$uname";
 6475:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6476:     if (!defined($cached)) {
 6477: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6478: 	$result=\%resourcedata;
 6479: 	&do_cache_new('userres',$hashid,$result,600);
 6480:     }
 6481:     my ($tmp)=keys(%$result);
 6482:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6483: 	return $result;
 6484:     }
 6485:     #error 2 occurs when the .db doesn't exist
 6486:     if ($tmp!~/error: 2 /) {
 6487: 	&logthis("<font color=\"blue\">WARNING:".
 6488: 		 " Trying to get resource data for ".
 6489: 		 $uname." at ".$udom.": ".
 6490: 		 $tmp."</font>");
 6491:     } elsif ($tmp=~/error: 2 /) {
 6492: 	#&EXT_cache_set($udom,$uname);
 6493: 	&do_cache_new('userres',$hashid,undef,600);
 6494: 	undef($tmp); # not really an error so don't send it back
 6495:     }
 6496:     return $tmp;
 6497: }
 6498: #----------------------------------------------- resdata - return resource data
 6499: #  Purpose:
 6500: #    Return resource data for either users or for a course.
 6501: #  Parameters:
 6502: #     $name      - Course/user name.
 6503: #     $domain    - Name of the domain the user/course is registered on.
 6504: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6505: #     @which     - Array of names of resources desired.
 6506: #  Returns:
 6507: #     The value of the first reasource in @which that is found in the
 6508: #     resource hash.
 6509: #  Exceptional Conditions:
 6510: #     If the $type passed in is not valid (not the string 'course' or 
 6511: #     'user', an undefined  reference is returned.
 6512: #     If none of the resources are found, an undef is returned
 6513: sub resdata {
 6514:     my ($name,$domain,$type,@which)=@_;
 6515:     my $result;
 6516:     if ($type eq 'course') {
 6517: 	$result=&get_courseresdata($name,$domain);
 6518:     } elsif ($type eq 'user') {
 6519: 	$result=&get_userresdata($name,$domain);
 6520:     }
 6521:     if (!ref($result)) { return $result; }    
 6522:     foreach my $item (@which) {
 6523: 	if (defined($result->{$item->[0]})) {
 6524: 	    return [$result->{$item->[0]},$item->[1]];
 6525: 	}
 6526:     }
 6527:     return undef;
 6528: }
 6529: 
 6530: #
 6531: # EXT resource caching routines
 6532: #
 6533: 
 6534: sub clear_EXT_cache_status {
 6535:     &delenv('cache.EXT.');
 6536: }
 6537: 
 6538: sub EXT_cache_status {
 6539:     my ($target_domain,$target_user) = @_;
 6540:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6541:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6542:         # We know already the user has no data
 6543:         return 1;
 6544:     } else {
 6545:         return 0;
 6546:     }
 6547: }
 6548: 
 6549: sub EXT_cache_set {
 6550:     my ($target_domain,$target_user) = @_;
 6551:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6552:     #&appenv({$cachename => time});
 6553: }
 6554: 
 6555: # --------------------------------------------------------- Value of a Variable
 6556: sub EXT {
 6557: 
 6558:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6559:     unless ($varname) { return ''; }
 6560:     #get real user name/domain, courseid and symb
 6561:     my $courseid;
 6562:     my $publicuser;
 6563:     if ($symbparm) {
 6564: 	$symbparm=&get_symb_from_alias($symbparm);
 6565:     }
 6566:     if (!($uname && $udom)) {
 6567:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6568:       if (!$symbparm) {	$symbparm=$cursymb; }
 6569:     } else {
 6570: 	$courseid=$env{'request.course.id'};
 6571:     }
 6572:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6573:     my $rest;
 6574:     if (defined($therest[0])) {
 6575:        $rest=join('.',@therest);
 6576:     } else {
 6577:        $rest='';
 6578:     }
 6579: 
 6580:     my $qualifierrest=$qualifier;
 6581:     if ($rest) { $qualifierrest.='.'.$rest; }
 6582:     my $spacequalifierrest=$space;
 6583:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6584:     if ($realm eq 'user') {
 6585: # --------------------------------------------------------------- user.resource
 6586: 	if ($space eq 'resource') {
 6587: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6588: 		  || defined($Apache::lonhomework::parsing_a_task))
 6589: 		 &&
 6590: 		 ($symbparm eq &symbread()) ) {	
 6591: 		# if we are in the middle of processing the resource the
 6592: 		# get the value we are planning on committing
 6593:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6594:                     return $Apache::lonhomework::results{$qualifierrest};
 6595:                 } else {
 6596:                     return $Apache::lonhomework::history{$qualifierrest};
 6597:                 }
 6598: 	    } else {
 6599: 		my %restored;
 6600: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6601: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6602: 		} else {
 6603: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6604: 		}
 6605: 		return $restored{$qualifierrest};
 6606: 	    }
 6607: # ----------------------------------------------------------------- user.access
 6608:         } elsif ($space eq 'access') {
 6609: 	    # FIXME - not supporting calls for a specific user
 6610:             return &allowed($qualifier,$rest);
 6611: # ------------------------------------------ user.preferences, user.environment
 6612:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6613: 	    if (($uname eq $env{'user.name'}) &&
 6614: 		($udom eq $env{'user.domain'})) {
 6615: 		return $env{join('.',('environment',$qualifierrest))};
 6616: 	    } else {
 6617: 		my %returnhash;
 6618: 		if (!$publicuser) {
 6619: 		    %returnhash=&userenvironment($udom,$uname,
 6620: 						 $qualifierrest);
 6621: 		}
 6622: 		return $returnhash{$qualifierrest};
 6623: 	    }
 6624: # ----------------------------------------------------------------- user.course
 6625:         } elsif ($space eq 'course') {
 6626: 	    # FIXME - not supporting calls for a specific user
 6627:             return $env{join('.',('request.course',$qualifier))};
 6628: # ------------------------------------------------------------------- user.role
 6629:         } elsif ($space eq 'role') {
 6630: 	    # FIXME - not supporting calls for a specific user
 6631:             my ($role,$where)=split(/\./,$env{'request.role'});
 6632:             if ($qualifier eq 'value') {
 6633: 		return $role;
 6634:             } elsif ($qualifier eq 'extent') {
 6635:                 return $where;
 6636:             }
 6637: # ----------------------------------------------------------------- user.domain
 6638:         } elsif ($space eq 'domain') {
 6639:             return $udom;
 6640: # ------------------------------------------------------------------- user.name
 6641:         } elsif ($space eq 'name') {
 6642:             return $uname;
 6643: # ---------------------------------------------------- Any other user namespace
 6644:         } else {
 6645: 	    my %reply;
 6646: 	    if (!$publicuser) {
 6647: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6648: 	    }
 6649: 	    return $reply{$qualifierrest};
 6650:         }
 6651:     } elsif ($realm eq 'query') {
 6652: # ---------------------------------------------- pull stuff out of query string
 6653:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6654: 						[$spacequalifierrest]);
 6655: 	return $env{'form.'.$spacequalifierrest}; 
 6656:    } elsif ($realm eq 'request') {
 6657: # ------------------------------------------------------------- request.browser
 6658:         if ($space eq 'browser') {
 6659: 	    if ($qualifier eq 'textremote') {
 6660: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6661: 		    return 1;
 6662: 		} else {
 6663: 		    return 0;
 6664: 		}
 6665: 	    } else {
 6666: 		return $env{'browser.'.$qualifier};
 6667: 	    }
 6668: # ------------------------------------------------------------ request.filename
 6669:         } else {
 6670:             return $env{'request.'.$spacequalifierrest};
 6671:         }
 6672:     } elsif ($realm eq 'course') {
 6673: # ---------------------------------------------------------- course.description
 6674:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6675:     } elsif ($realm eq 'resource') {
 6676: 
 6677: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6678: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6679: 	}
 6680: 
 6681: 	if ($space eq 'title') {
 6682: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6683: 	    return &gettitle($symbparm);
 6684: 	}
 6685: 	
 6686: 	if ($space eq 'map') {
 6687: 	    my ($map) = &decode_symb($symbparm);
 6688: 	    return &symbread($map);
 6689: 	}
 6690: 	if ($space eq 'filename') {
 6691: 	    if ($symbparm) {
 6692: 		return &clutter((&decode_symb($symbparm))[2]);
 6693: 	    }
 6694: 	    return &hreflocation('',$env{'request.filename'});
 6695: 	}
 6696: 
 6697: 	my ($section, $group, @groups);
 6698: 	my ($courselevelm,$courselevel);
 6699: 	if ($symbparm && defined($courseid) && 
 6700: 	    $courseid eq $env{'request.course.id'}) {
 6701: 
 6702: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6703: 
 6704: # ----------------------------------------------------- Cascading lookup scheme
 6705: 	    my $symbp=$symbparm;
 6706: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6707: 
 6708: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6709: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6710: 
 6711: 	    if (($env{'user.name'} eq $uname) &&
 6712: 		($env{'user.domain'} eq $udom)) {
 6713: 		$section=$env{'request.course.sec'};
 6714:                 @groups = split(/:/,$env{'request.course.groups'});  
 6715:                 @groups=&sort_course_groups($courseid,@groups); 
 6716: 	    } else {
 6717: 		if (! defined($usection)) {
 6718: 		    $section=&getsection($udom,$uname,$courseid);
 6719: 		} else {
 6720: 		    $section = $usection;
 6721: 		}
 6722:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6723: 	    }
 6724: 
 6725: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6726: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6727: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6728: 
 6729: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6730: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6731: 	    $courselevelm=$courseid.'.'.$mapparm;
 6732: 
 6733: # ----------------------------------------------------------- first, check user
 6734: 
 6735: 	    my $userreply=&resdata($uname,$udom,'user',
 6736: 				       ([$courselevelr,'resource'],
 6737: 					[$courselevelm,'map'     ],
 6738: 					[$courselevel, 'course'  ]));
 6739: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6740: 
 6741: # ------------------------------------------------ second, check some of course
 6742:             my $coursereply;
 6743:             if (@groups > 0) {
 6744:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6745:                                        $mapparm,$spacequalifierrest);
 6746:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6747:             }
 6748: 
 6749: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6750: 				  $env{'course.'.$courseid.'.domain'},
 6751: 				  'course',
 6752: 				  ([$seclevelr,   'resource'],
 6753: 				   [$seclevelm,   'map'     ],
 6754: 				   [$seclevel,    'course'  ],
 6755: 				   [$courselevelr,'resource']));
 6756: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6757: 
 6758: # ------------------------------------------------------ third, check map parms
 6759: 	    my %parmhash=();
 6760: 	    my $thisparm='';
 6761: 	    if (tie(%parmhash,'GDBM_File',
 6762: 		    $env{'request.course.fn'}.'_parms.db',
 6763: 		    &GDBM_READER(),0640)) {
 6764: 		$thisparm=$parmhash{$symbparm};
 6765: 		untie(%parmhash);
 6766: 	    }
 6767: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6768: 	}
 6769: # ------------------------------------------ fourth, look in resource metadata
 6770: 
 6771: 	$spacequalifierrest=~s/\./\_/;
 6772: 	my $filename;
 6773: 	if (!$symbparm) { $symbparm=&symbread(); }
 6774: 	if ($symbparm) {
 6775: 	    $filename=(&decode_symb($symbparm))[2];
 6776: 	} else {
 6777: 	    $filename=$env{'request.filename'};
 6778: 	}
 6779: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6780: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6781: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6782: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6783: 
 6784: # ---------------------------------------------- fourth, look in rest of course
 6785: 	if ($symbparm && defined($courseid) && 
 6786: 	    $courseid eq $env{'request.course.id'}) {
 6787: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6788: 				     $env{'course.'.$courseid.'.domain'},
 6789: 				     'course',
 6790: 				     ([$courselevelm,'map'   ],
 6791: 				      [$courselevel, 'course']));
 6792: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6793: 	}
 6794: # ------------------------------------------------------------------ Cascade up
 6795: 	unless ($space eq '0') {
 6796: 	    my @parts=split(/_/,$space);
 6797: 	    my $id=pop(@parts);
 6798: 	    my $part=join('_',@parts);
 6799: 	    if ($part eq '') { $part='0'; }
 6800: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6801: 				 $symbparm,$udom,$uname,$section,1);
 6802: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6803: 	}
 6804: 	if ($recurse) { return undef; }
 6805: 	my $pack_def=&packages_tab_default($filename,$varname);
 6806: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6807: # ---------------------------------------------------- Any other user namespace
 6808:     } elsif ($realm eq 'environment') {
 6809: # ----------------------------------------------------------------- environment
 6810: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6811: 	    return $env{'environment.'.$spacequalifierrest};
 6812: 	} else {
 6813: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6814: 		return '';
 6815: 	    }
 6816: 	    my %returnhash=&userenvironment($udom,$uname,
 6817: 					    $spacequalifierrest);
 6818: 	    return $returnhash{$spacequalifierrest};
 6819: 	}
 6820:     } elsif ($realm eq 'system') {
 6821: # ----------------------------------------------------------------- system.time
 6822: 	if ($space eq 'time') {
 6823: 	    return time;
 6824:         }
 6825:     } elsif ($realm eq 'server') {
 6826: # ----------------------------------------------------------------- system.time
 6827: 	if ($space eq 'name') {
 6828: 	    return $ENV{'SERVER_NAME'};
 6829:         }
 6830:     }
 6831:     return '';
 6832: }
 6833: 
 6834: sub get_reply {
 6835:     my ($reply_value) = @_;
 6836:     if (ref($reply_value) eq 'ARRAY') {
 6837:         if (wantarray) {
 6838: 	    return @$reply_value;
 6839:         }
 6840:         return $reply_value->[0];
 6841:     } else {
 6842:         return $reply_value;
 6843:     }
 6844: }
 6845: 
 6846: sub check_group_parms {
 6847:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6848:     my @groupitems = ();
 6849:     my $resultitem;
 6850:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6851:     foreach my $group (@{$groups}) {
 6852:         foreach my $level (@levels) {
 6853:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6854:              push(@groupitems,[$item,$level->[1]]);
 6855:         }
 6856:     }
 6857:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6858:                             $env{'course.'.$courseid.'.domain'},
 6859:                                      'course',@groupitems);
 6860:     return $coursereply;
 6861: }
 6862: 
 6863: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6864:     my ($courseid,@groups) = @_;
 6865:     @groups = sort(@groups);
 6866:     return @groups;
 6867: }
 6868: 
 6869: sub packages_tab_default {
 6870:     my ($uri,$varname)=@_;
 6871:     my (undef,$part,$name)=split(/\./,$varname);
 6872: 
 6873:     my (@extension,@specifics,$do_default);
 6874:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6875: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6876: 	if ($pack_type eq 'default') {
 6877: 	    $do_default=1;
 6878: 	} elsif ($pack_type eq 'extension') {
 6879: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6880: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6881: 	    # only look at packages defaults for packages that this id is
 6882: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6883: 	}
 6884:     }
 6885:     # first look for a package that matches the requested part id
 6886:     foreach my $package (@specifics) {
 6887: 	my (undef,$pack_type,$pack_part)=@{$package};
 6888: 	next if ($pack_part ne $part);
 6889: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6890: 	    return $packagetab{"$pack_type&$name&default"};
 6891: 	}
 6892:     }
 6893:     # look for any possible matching non extension_ package
 6894:     foreach my $package (@specifics) {
 6895: 	my (undef,$pack_type,$pack_part)=@{$package};
 6896: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6897: 	    return $packagetab{"$pack_type&$name&default"};
 6898: 	}
 6899: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6900: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6901: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6902: 	}
 6903:     }
 6904:     # look for any posible extension_ match
 6905:     foreach my $package (@extension) {
 6906: 	my ($package,$pack_type)=@{$package};
 6907: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6908: 	    return $packagetab{"$pack_type&$name&default"};
 6909: 	}
 6910: 	if (defined($packagetab{$package."&$name&default"})) {
 6911: 	    return $packagetab{$package."&$name&default"};
 6912: 	}
 6913:     }
 6914:     # look for a global default setting
 6915:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6916: 	return $packagetab{"default&$name&default"};
 6917:     }
 6918:     return undef;
 6919: }
 6920: 
 6921: sub add_prefix_and_part {
 6922:     my ($prefix,$part)=@_;
 6923:     my $keyroot;
 6924:     if (defined($prefix) && $prefix !~ /^__/) {
 6925: 	# prefix that has a part already
 6926: 	$keyroot=$prefix;
 6927:     } elsif (defined($prefix)) {
 6928: 	# prefix that is missing a part
 6929: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6930:     } else {
 6931: 	# no prefix at all
 6932: 	if (defined($part)) { $keyroot='_'.$part; }
 6933:     }
 6934:     return $keyroot;
 6935: }
 6936: 
 6937: # ---------------------------------------------------------------- Get metadata
 6938: 
 6939: my %metaentry;
 6940: sub metadata {
 6941:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6942:     $uri=&declutter($uri);
 6943:     # if it is a non metadata possible uri return quickly
 6944:     if (($uri eq '') || 
 6945: 	(($uri =~ m|^/*adm/|) && 
 6946: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6947:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6948: 	return undef;
 6949:     }
 6950:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6951: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6952: 	return undef;
 6953:     }
 6954:     my $filename=$uri;
 6955:     $uri=~s/\.meta$//;
 6956: #
 6957: # Is the metadata already cached?
 6958: # Look at timestamp of caching
 6959: # Everything is cached by the main uri, libraries are never directly cached
 6960: #
 6961:     if (!defined($liburi)) {
 6962: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6963: 	if (defined($cached)) { return $result->{':'.$what}; }
 6964:     }
 6965:     {
 6966: #
 6967: # Is this a recursive call for a library?
 6968: #
 6969: #	if (! exists($metacache{$uri})) {
 6970: #	    $metacache{$uri}={};
 6971: #	}
 6972: 	my $cachetime = 60*60;
 6973:         if ($liburi) {
 6974: 	    $liburi=&declutter($liburi);
 6975:             $filename=$liburi;
 6976:         } else {
 6977: 	    &devalidate_cache_new('meta',$uri);
 6978: 	    undef(%metaentry);
 6979: 	}
 6980:         my %metathesekeys=();
 6981:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6982: 	my $metastring;
 6983: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6984: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6985: 	    $metastring = 
 6986: 		&Apache::lonnet::ssi_body($which,
 6987: 					  ('grade_target' => 'meta'));
 6988: 	    $cachetime = 1; # only want this cached in the child not long term
 6989: 	} elsif ($uri !~ m -^(editupload)/-) {
 6990: 	    my $file=&filelocation('',&clutter($filename));
 6991: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6992: 	    $metastring=&getfile($file);
 6993: 	}
 6994:         my $parser=HTML::LCParser->new(\$metastring);
 6995:         my $token;
 6996:         undef %metathesekeys;
 6997:         while ($token=$parser->get_token) {
 6998: 	    if ($token->[0] eq 'S') {
 6999: 		if (defined($token->[2]->{'package'})) {
 7000: #
 7001: # This is a package - get package info
 7002: #
 7003: 		    my $package=$token->[2]->{'package'};
 7004: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7005: 		    if (defined($token->[2]->{'id'})) { 
 7006: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7007: 		    }
 7008: 		    if ($metaentry{':packages'}) {
 7009: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7010: 		    } else {
 7011: 			$metaentry{':packages'}=$package.$keyroot;
 7012: 		    }
 7013: 		    foreach my $pack_entry (keys(%packagetab)) {
 7014: 			my $part=$keyroot;
 7015: 			$part=~s/^\_//;
 7016: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7017: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7018: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7019: 			    # ignore package.tab specified default values
 7020:                             # here &package_tab_default() will fetch those
 7021: 			    if ($subp eq 'default') { next; }
 7022: 			    my $value=$packagetab{$pack_entry};
 7023: 			    my $unikey;
 7024: 			    if ($pack =~ /_0$/) {
 7025: 				$unikey='parameter_0_'.$name;
 7026: 				$part=0;
 7027: 			    } else {
 7028: 				$unikey='parameter'.$keyroot.'_'.$name;
 7029: 			    }
 7030: 			    if ($subp eq 'display') {
 7031: 				$value.=' [Part: '.$part.']';
 7032: 			    }
 7033: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7034: 			    $metathesekeys{$unikey}=1;
 7035: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7036: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7037: 			    }
 7038: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7039: 				$metaentry{':'.$unikey}=
 7040: 				    $metaentry{':'.$unikey.'.default'};
 7041: 			    }
 7042: 			}
 7043: 		    }
 7044: 		} else {
 7045: #
 7046: # This is not a package - some other kind of start tag
 7047: #
 7048: 		    my $entry=$token->[1];
 7049: 		    my $unikey;
 7050: 		    if ($entry eq 'import') {
 7051: 			$unikey='';
 7052: 		    } else {
 7053: 			$unikey=$entry;
 7054: 		    }
 7055: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7056: 
 7057: 		    if (defined($token->[2]->{'id'})) { 
 7058: 			$unikey.='_'.$token->[2]->{'id'}; 
 7059: 		    }
 7060: 
 7061: 		    if ($entry eq 'import') {
 7062: #
 7063: # Importing a library here
 7064: #
 7065: 			if ($depthcount<20) {
 7066: 			    my $location=$parser->get_text('/import');
 7067: 			    my $dir=$filename;
 7068: 			    $dir=~s|[^/]*$||;
 7069: 			    $location=&filelocation($dir,$location);
 7070: 			    my $metadata = 
 7071: 				&metadata($uri,'keys', $location,$unikey,
 7072: 					  $depthcount+1);
 7073: 			    foreach my $meta (split(',',$metadata)) {
 7074: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7075: 				$metathesekeys{$meta}=1;
 7076: 			    }
 7077: 			}
 7078: 		    } else { 
 7079: 			
 7080: 			if (defined($token->[2]->{'name'})) { 
 7081: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7082: 			}
 7083: 			$metathesekeys{$unikey}=1;
 7084: 			foreach my $param (@{$token->[3]}) {
 7085: 			    $metaentry{':'.$unikey.'.'.$param} =
 7086: 				$token->[2]->{$param};
 7087: 			}
 7088: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7089: 			my $default=$metaentry{':'.$unikey.'.default'};
 7090: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7091: 		 # only ws inside the tag, and not in default, so use default
 7092: 		 # as value
 7093: 			    $metaentry{':'.$unikey}=$default;
 7094: 			} elsif ( $internaltext =~ /\S/ ) {
 7095: 		  # something interesting inside the tag
 7096: 			    $metaentry{':'.$unikey}=$internaltext;
 7097: 			} else {
 7098: 		  # no interesting values, don't set a default
 7099: 			}
 7100: # end of not-a-package not-a-library import
 7101: 		    }
 7102: # end of not-a-package start tag
 7103: 		}
 7104: # the next is the end of "start tag"
 7105: 	    }
 7106: 	}
 7107: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7108: 	$extension = lc($extension);
 7109: 	if ($extension eq 'htm') { $extension='html'; }
 7110: 
 7111: 	foreach my $key (keys(%packagetab)) {
 7112: 	    #no specific packages #how's our extension
 7113: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7114: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7115: 					 \%metathesekeys);
 7116: 	}
 7117: 
 7118: 	if (!exists($metaentry{':packages'})
 7119: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7120: 	    foreach my $key (keys(%packagetab)) {
 7121: 		#no specific packages well let's get default then
 7122: 		if ($key!~/^default&/) { next; }
 7123: 		&metadata_create_package_def($uri,$key,'default',
 7124: 					     \%metathesekeys);
 7125: 	    }
 7126: 	}
 7127: # are there custom rights to evaluate
 7128: 	if ($metaentry{':copyright'} eq 'custom') {
 7129: 
 7130:     #
 7131:     # Importing a rights file here
 7132:     #
 7133: 	    unless ($depthcount) {
 7134: 		my $location=$metaentry{':customdistributionfile'};
 7135: 		my $dir=$filename;
 7136: 		$dir=~s|[^/]*$||;
 7137: 		$location=&filelocation($dir,$location);
 7138: 		my $rights_metadata =
 7139: 		    &metadata($uri,'keys',$location,'_rights',
 7140: 			      $depthcount+1);
 7141: 		foreach my $rights (split(',',$rights_metadata)) {
 7142: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7143: 		    $metathesekeys{$rights}=1;
 7144: 		}
 7145: 	    }
 7146: 	}
 7147: 	# uniqifiy package listing
 7148: 	my %seen;
 7149: 	my @uniq_packages =
 7150: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7151: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7152: 
 7153: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7154: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7155: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7156: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7157: # this is the end of "was not already recently cached
 7158:     }
 7159:     return $metaentry{':'.$what};
 7160: }
 7161: 
 7162: sub metadata_create_package_def {
 7163:     my ($uri,$key,$package,$metathesekeys)=@_;
 7164:     my ($pack,$name,$subp)=split(/\&/,$key);
 7165:     if ($subp eq 'default') { next; }
 7166:     
 7167:     if (defined($metaentry{':packages'})) {
 7168: 	$metaentry{':packages'}.=','.$package;
 7169:     } else {
 7170: 	$metaentry{':packages'}=$package;
 7171:     }
 7172:     my $value=$packagetab{$key};
 7173:     my $unikey;
 7174:     $unikey='parameter_0_'.$name;
 7175:     $metaentry{':'.$unikey.'.part'}=0;
 7176:     $$metathesekeys{$unikey}=1;
 7177:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7178: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7179:     }
 7180:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7181: 	$metaentry{':'.$unikey}=
 7182: 	    $metaentry{':'.$unikey.'.default'};
 7183:     }
 7184: }
 7185: 
 7186: sub metadata_generate_part0 {
 7187:     my ($metadata,$metacache,$uri) = @_;
 7188:     my %allnames;
 7189:     foreach my $metakey (keys(%$metadata)) {
 7190: 	if ($metakey=~/^parameter\_(.*)/) {
 7191: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7192: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7193: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7194: 	    $allnames{$name}=$part;
 7195: 	  }
 7196: 	}
 7197:     }
 7198:     foreach my $name (keys(%allnames)) {
 7199:       $$metadata{"parameter_0_$name"}=1;
 7200:       my $key=":parameter_0_$name";
 7201:       $$metacache{"$key.part"}='0';
 7202:       $$metacache{"$key.name"}=$name;
 7203:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7204: 					   $allnames{$name}.'_'.$name.
 7205: 					   '.type'};
 7206:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7207: 			     '.display'};
 7208:       my $expr='[Part: '.$allnames{$name}.']';
 7209:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7210:       $$metacache{"$key.display"}=$olddis;
 7211:     }
 7212: }
 7213: 
 7214: # ------------------------------------------------------ Devalidate title cache
 7215: 
 7216: sub devalidate_title_cache {
 7217:     my ($url)=@_;
 7218:     if (!$env{'request.course.id'}) { return; }
 7219:     my $symb=&symbread($url);
 7220:     if (!$symb) { return; }
 7221:     my $key=$env{'request.course.id'}."\0".$symb;
 7222:     &devalidate_cache_new('title',$key);
 7223: }
 7224: 
 7225: # ------------------------------------------------- Get the title of a resource
 7226: 
 7227: sub gettitle {
 7228:     my $urlsymb=shift;
 7229:     my $symb=&symbread($urlsymb);
 7230:     if ($symb) {
 7231: 	my $key=$env{'request.course.id'}."\0".$symb;
 7232: 	my ($result,$cached)=&is_cached_new('title',$key);
 7233: 	if (defined($cached)) { 
 7234: 	    return $result;
 7235: 	}
 7236: 	my ($map,$resid,$url)=&decode_symb($symb);
 7237: 	my $title='';
 7238: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7239: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7240: 	} else {
 7241: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7242: 		    &GDBM_READER(),0640)) {
 7243: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7244: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7245: 		untie(%bighash);
 7246: 	    }
 7247: 	}
 7248: 	$title=~s/\&colon\;/\:/gs;
 7249: 	if ($title) {
 7250: 	    return &do_cache_new('title',$key,$title,600);
 7251: 	}
 7252: 	$urlsymb=$url;
 7253:     }
 7254:     my $title=&metadata($urlsymb,'title');
 7255:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7256:     return $title;
 7257: }
 7258: 
 7259: sub get_slot {
 7260:     my ($which,$cnum,$cdom)=@_;
 7261:     if (!$cnum || !$cdom) {
 7262: 	(undef,my $courseid)=&whichuser();
 7263: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7264: 	$cnum=$env{'course.'.$courseid.'.num'};
 7265:     }
 7266:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7267:     my %slotinfo;
 7268:     if (exists($remembered{$key})) {
 7269: 	$slotinfo{$which} = $remembered{$key};
 7270:     } else {
 7271: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7272: 	&Apache::lonhomework::showhash(%slotinfo);
 7273: 	my ($tmp)=keys(%slotinfo);
 7274: 	if ($tmp=~/^error:/) { return (); }
 7275: 	$remembered{$key} = $slotinfo{$which};
 7276:     }
 7277:     if (ref($slotinfo{$which}) eq 'HASH') {
 7278: 	return %{$slotinfo{$which}};
 7279:     }
 7280:     return $slotinfo{$which};
 7281: }
 7282: # ------------------------------------------------- Update symbolic store links
 7283: 
 7284: sub symblist {
 7285:     my ($mapname,%newhash)=@_;
 7286:     $mapname=&deversion(&declutter($mapname));
 7287:     my %hash;
 7288:     if (($env{'request.course.fn'}) && (%newhash)) {
 7289:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7290:                       &GDBM_WRCREAT(),0640)) {
 7291: 	    foreach my $url (keys %newhash) {
 7292: 		next if ($url eq 'last_known'
 7293: 			 && $env{'form.no_update_last_known'});
 7294: 		$hash{declutter($url)}=&encode_symb($mapname,
 7295: 						    $newhash{$url}->[1],
 7296: 						    $newhash{$url}->[0]);
 7297:             }
 7298:             if (untie(%hash)) {
 7299: 		return 'ok';
 7300:             }
 7301:         }
 7302:     }
 7303:     return 'error';
 7304: }
 7305: 
 7306: # --------------------------------------------------------------- Verify a symb
 7307: 
 7308: sub symbverify {
 7309:     my ($symb,$thisurl)=@_;
 7310:     my $thisfn=$thisurl;
 7311:     $thisfn=&declutter($thisfn);
 7312: # direct jump to resource in page or to a sequence - will construct own symbs
 7313:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7314: # check URL part
 7315:     my ($map,$resid,$url)=&decode_symb($symb);
 7316: 
 7317:     unless ($url eq $thisfn) { return 0; }
 7318: 
 7319:     $symb=&symbclean($symb);
 7320:     $thisurl=&deversion($thisurl);
 7321:     $thisfn=&deversion($thisfn);
 7322: 
 7323:     my %bighash;
 7324:     my $okay=0;
 7325: 
 7326:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7327:                             &GDBM_READER(),0640)) {
 7328:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7329:         unless ($ids) { 
 7330:            $ids=$bighash{'ids_/'.$thisurl};
 7331:         }
 7332:         if ($ids) {
 7333: # ------------------------------------------------------------------- Has ID(s)
 7334: 	    foreach my $id (split(/\,/,$ids)) {
 7335: 	       my ($mapid,$resid)=split(/\./,$id);
 7336:                if (
 7337:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7338:    eq $symb) { 
 7339: 		   if (($env{'request.role.adv'}) ||
 7340: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7341: 		       $okay=1; 
 7342: 		   }
 7343: 	       }
 7344: 	   }
 7345:         }
 7346: 	untie(%bighash);
 7347:     }
 7348:     return $okay;
 7349: }
 7350: 
 7351: # --------------------------------------------------------------- Clean-up symb
 7352: 
 7353: sub symbclean {
 7354:     my $symb=shift;
 7355:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7356: # remove version from map
 7357:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7358: 
 7359: # remove version from URL
 7360:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7361: 
 7362: # remove wrapper
 7363: 
 7364:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7365:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7366:     return $symb;
 7367: }
 7368: 
 7369: # ---------------------------------------------- Split symb to find map and url
 7370: 
 7371: sub encode_symb {
 7372:     my ($map,$resid,$url)=@_;
 7373:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7374: }
 7375: 
 7376: sub decode_symb {
 7377:     my $symb=shift;
 7378:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7379:     my ($map,$resid,$url)=split(/___/,$symb);
 7380:     return (&fixversion($map),$resid,&fixversion($url));
 7381: }
 7382: 
 7383: sub fixversion {
 7384:     my $fn=shift;
 7385:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7386:     my %bighash;
 7387:     my $uri=&clutter($fn);
 7388:     my $key=$env{'request.course.id'}.'_'.$uri;
 7389: # is this cached?
 7390:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7391:     if (defined($cached)) { return $result; }
 7392: # unfortunately not cached, or expired
 7393:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7394: 	    &GDBM_READER(),0640)) {
 7395:  	if ($bighash{'version_'.$uri}) {
 7396:  	    my $version=$bighash{'version_'.$uri};
 7397:  	    unless (($version eq 'mostrecent') || 
 7398: 		    ($version==&getversion($uri))) {
 7399:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7400:  	    }
 7401:  	}
 7402:  	untie %bighash;
 7403:     }
 7404:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7405: }
 7406: 
 7407: sub deversion {
 7408:     my $url=shift;
 7409:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7410:     return $url;
 7411: }
 7412: 
 7413: # ------------------------------------------------------ Return symb list entry
 7414: 
 7415: sub symbread {
 7416:     my ($thisfn,$donotrecurse)=@_;
 7417:     my $cache_str='request.symbread.cached.'.$thisfn;
 7418:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7419: # no filename provided? try from environment
 7420:     unless ($thisfn) {
 7421:         if ($env{'request.symb'}) {
 7422: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7423: 	}
 7424: 	$thisfn=$env{'request.filename'};
 7425:     }
 7426:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7427: # is that filename actually a symb? Verify, clean, and return
 7428:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7429: 	if (&symbverify($thisfn,$1)) {
 7430: 	    return $env{$cache_str}=&symbclean($thisfn);
 7431: 	}
 7432:     }
 7433:     $thisfn=declutter($thisfn);
 7434:     my %hash;
 7435:     my %bighash;
 7436:     my $syval='';
 7437:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7438:         my $targetfn = $thisfn;
 7439:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7440:             $targetfn = 'adm/wrapper/'.$thisfn;
 7441:         }
 7442: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7443: 	    $targetfn=$1;
 7444: 	}
 7445:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7446:                       &GDBM_READER(),0640)) {
 7447: 	    $syval=$hash{$targetfn};
 7448:             untie(%hash);
 7449:         }
 7450: # ---------------------------------------------------------- There was an entry
 7451:         if ($syval) {
 7452: 	    #unless ($syval=~/\_\d+$/) {
 7453: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7454: 		    #&appenv({'request.ambiguous' => $thisfn});
 7455: 		    #return $env{$cache_str}='';
 7456: 		#}    
 7457: 		#$syval.=$1;
 7458: 	    #}
 7459:         } else {
 7460: # ------------------------------------------------------- Was not in symb table
 7461:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7462:                             &GDBM_READER(),0640)) {
 7463: # ---------------------------------------------- Get ID(s) for current resource
 7464:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7465:               unless ($ids) { 
 7466:                  $ids=$bighash{'ids_/'.$thisfn};
 7467:               }
 7468:               unless ($ids) {
 7469: # alias?
 7470: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7471:               }
 7472:               if ($ids) {
 7473: # ------------------------------------------------------------------- Has ID(s)
 7474:                  my @possibilities=split(/\,/,$ids);
 7475:                  if ($#possibilities==0) {
 7476: # ----------------------------------------------- There is only one possibility
 7477: 		     my ($mapid,$resid)=split(/\./,$ids);
 7478: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7479: 						    $resid,$thisfn);
 7480:                  } elsif (!$donotrecurse) {
 7481: # ------------------------------------------ There is more than one possibility
 7482:                      my $realpossible=0;
 7483:                      foreach my $id (@possibilities) {
 7484: 			 my $file=$bighash{'src_'.$id};
 7485:                          if (&allowed('bre',$file)) {
 7486:          		    my ($mapid,$resid)=split(/\./,$id);
 7487:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7488: 				$realpossible++;
 7489:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7490: 						    $resid,$thisfn);
 7491:                             }
 7492: 			 }
 7493:                      }
 7494: 		     if ($realpossible!=1) { $syval=''; }
 7495:                  } else {
 7496:                      $syval='';
 7497:                  }
 7498: 	      }
 7499:               untie(%bighash)
 7500:            }
 7501:         }
 7502:         if ($syval) {
 7503: 	    return $env{$cache_str}=$syval;
 7504:         }
 7505:     }
 7506:     &appenv({'request.ambiguous' => $thisfn});
 7507:     return $env{$cache_str}='';
 7508: }
 7509: 
 7510: # ---------------------------------------------------------- Return random seed
 7511: 
 7512: sub numval {
 7513:     my $txt=shift;
 7514:     $txt=~tr/A-J/0-9/;
 7515:     $txt=~tr/a-j/0-9/;
 7516:     $txt=~tr/K-T/0-9/;
 7517:     $txt=~tr/k-t/0-9/;
 7518:     $txt=~tr/U-Z/0-5/;
 7519:     $txt=~tr/u-z/0-5/;
 7520:     $txt=~s/\D//g;
 7521:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7522:     return int($txt);
 7523: }
 7524: 
 7525: sub numval2 {
 7526:     my $txt=shift;
 7527:     $txt=~tr/A-J/0-9/;
 7528:     $txt=~tr/a-j/0-9/;
 7529:     $txt=~tr/K-T/0-9/;
 7530:     $txt=~tr/k-t/0-9/;
 7531:     $txt=~tr/U-Z/0-5/;
 7532:     $txt=~tr/u-z/0-5/;
 7533:     $txt=~s/\D//g;
 7534:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7535:     my $total;
 7536:     foreach my $val (@txts) { $total+=$val; }
 7537:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7538:     return int($total);
 7539: }
 7540: 
 7541: sub numval3 {
 7542:     use integer;
 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) { $total=(($total<<32)>>32); }
 7555:     return $total;
 7556: }
 7557: 
 7558: sub digest {
 7559:     my ($data)=@_;
 7560:     my $digest=&Digest::MD5::md5($data);
 7561:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7562:     my ($e,$f);
 7563:     {
 7564:         use integer;
 7565:         $e=($a+$b);
 7566:         $f=($c+$d);
 7567:         if ($_64bit) {
 7568:             $e=(($e<<32)>>32);
 7569:             $f=(($f<<32)>>32);
 7570:         }
 7571:     }
 7572:     if (wantarray) {
 7573: 	return ($e,$f);
 7574:     } else {
 7575: 	my $g;
 7576: 	{
 7577: 	    use integer;
 7578: 	    $g=($e+$f);
 7579: 	    if ($_64bit) {
 7580: 		$g=(($g<<32)>>32);
 7581: 	    }
 7582: 	}
 7583: 	return $g;
 7584:     }
 7585: }
 7586: 
 7587: sub latest_rnd_algorithm_id {
 7588:     return '64bit5';
 7589: }
 7590: 
 7591: sub get_rand_alg {
 7592:     my ($courseid)=@_;
 7593:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7594:     if ($courseid) {
 7595: 	return $env{"course.$courseid.rndseed"};
 7596:     }
 7597:     return &latest_rnd_algorithm_id();
 7598: }
 7599: 
 7600: sub validCODE {
 7601:     my ($CODE)=@_;
 7602:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7603:     return 0;
 7604: }
 7605: 
 7606: sub getCODE {
 7607:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7608:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7609: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7610: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7611: 	return $Apache::lonhomework::history{'resource.CODE'};
 7612:     }
 7613:     return undef;
 7614: }
 7615: 
 7616: sub rndseed {
 7617:     my ($symb,$courseid,$domain,$username)=@_;
 7618:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7619:     if (!defined($symb)) {
 7620: 	unless ($symb=$wsymb) { return time; }
 7621:     }
 7622:     if (!$courseid) { $courseid=$wcourseid; }
 7623:     if (!$domain) { $domain=$wdomain; }
 7624:     if (!$username) { $username=$wusername }
 7625:     my $which=&get_rand_alg();
 7626: 
 7627:     if (defined(&getCODE())) {
 7628: 	if ($which eq '64bit5') {
 7629: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7630: 	} elsif ($which eq '64bit4') {
 7631: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7632: 	} else {
 7633: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7634: 	}
 7635:     } elsif ($which eq '64bit5') {
 7636: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7637:     } elsif ($which eq '64bit4') {
 7638: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7639:     } elsif ($which eq '64bit3') {
 7640: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7641:     } elsif ($which eq '64bit2') {
 7642: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7643:     } elsif ($which eq '64bit') {
 7644: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7645:     }
 7646:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7647: }
 7648: 
 7649: sub rndseed_32bit {
 7650:     my ($symb,$courseid,$domain,$username)=@_;
 7651:     {
 7652: 	use integer;
 7653: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7654: 	my $symbseed=numval($symb) << 22;
 7655: 	my $namechck=unpack("%32C*",$username) << 17;
 7656: 	my $nameseed=numval($username) << 12;
 7657: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7658: 	my $courseseed=unpack("%32C*",$courseid);
 7659: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7660: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7661: 	#&logthis("rndseed :$num:$symb");
 7662: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7663: 	return $num;
 7664:     }
 7665: }
 7666: 
 7667: sub rndseed_64bit {
 7668:     my ($symb,$courseid,$domain,$username)=@_;
 7669:     {
 7670: 	use integer;
 7671: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7672: 	my $symbseed=numval($symb) << 10;
 7673: 	my $namechck=unpack("%32S*",$username);
 7674: 	
 7675: 	my $nameseed=numval($username) << 21;
 7676: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7677: 	my $courseseed=unpack("%32S*",$courseid);
 7678: 	
 7679: 	my $num1=$symbchck+$symbseed+$namechck;
 7680: 	my $num2=$nameseed+$domainseed+$courseseed;
 7681: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7682: 	#&logthis("rndseed :$num:$symb");
 7683: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7684: 	return "$num1,$num2";
 7685:     }
 7686: }
 7687: 
 7688: sub rndseed_64bit2 {
 7689:     my ($symb,$courseid,$domain,$username)=@_;
 7690:     {
 7691: 	use integer;
 7692: 	# strings need to be an even # of cahracters long, it it is odd the
 7693:         # last characters gets thrown away
 7694: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7695: 	my $symbseed=numval($symb) << 10;
 7696: 	my $namechck=unpack("%32S*",$username.' ');
 7697: 	
 7698: 	my $nameseed=numval($username) << 21;
 7699: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7700: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7701: 	
 7702: 	my $num1=$symbchck+$symbseed+$namechck;
 7703: 	my $num2=$nameseed+$domainseed+$courseseed;
 7704: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7705: 	#&logthis("rndseed :$num:$symb");
 7706: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7707: 	return "$num1,$num2";
 7708:     }
 7709: }
 7710: 
 7711: sub rndseed_64bit3 {
 7712:     my ($symb,$courseid,$domain,$username)=@_;
 7713:     {
 7714: 	use integer;
 7715: 	# strings need to be an even # of cahracters long, it it is odd the
 7716:         # last characters gets thrown away
 7717: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7718: 	my $symbseed=numval2($symb) << 10;
 7719: 	my $namechck=unpack("%32S*",$username.' ');
 7720: 	
 7721: 	my $nameseed=numval2($username) << 21;
 7722: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7723: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7724: 	
 7725: 	my $num1=$symbchck+$symbseed+$namechck;
 7726: 	my $num2=$nameseed+$domainseed+$courseseed;
 7727: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7728: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7729: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7730: 	
 7731: 	return "$num1:$num2";
 7732:     }
 7733: }
 7734: 
 7735: sub rndseed_64bit4 {
 7736:     my ($symb,$courseid,$domain,$username)=@_;
 7737:     {
 7738: 	use integer;
 7739: 	# strings need to be an even # of cahracters long, it it is odd the
 7740:         # last characters gets thrown away
 7741: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7742: 	my $symbseed=numval3($symb) << 10;
 7743: 	my $namechck=unpack("%32S*",$username.' ');
 7744: 	
 7745: 	my $nameseed=numval3($username) << 21;
 7746: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7747: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7748: 	
 7749: 	my $num1=$symbchck+$symbseed+$namechck;
 7750: 	my $num2=$nameseed+$domainseed+$courseseed;
 7751: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7752: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7753: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7754: 	
 7755: 	return "$num1:$num2";
 7756:     }
 7757: }
 7758: 
 7759: sub rndseed_64bit5 {
 7760:     my ($symb,$courseid,$domain,$username)=@_;
 7761:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7762:     return "$num1:$num2";
 7763: }
 7764: 
 7765: sub rndseed_CODE_64bit {
 7766:     my ($symb,$courseid,$domain,$username)=@_;
 7767:     {
 7768: 	use integer;
 7769: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7770: 	my $symbseed=numval2($symb);
 7771: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7772: 	my $CODEseed=numval(&getCODE());
 7773: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7774: 	my $num1=$symbseed+$CODEchck;
 7775: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7776: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7777: 	#&logthis("rndseed :$num1:$num2:$symb");
 7778: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7779: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7780: 	return "$num1:$num2";
 7781:     }
 7782: }
 7783: 
 7784: sub rndseed_CODE_64bit4 {
 7785:     my ($symb,$courseid,$domain,$username)=@_;
 7786:     {
 7787: 	use integer;
 7788: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7789: 	my $symbseed=numval3($symb);
 7790: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7791: 	my $CODEseed=numval3(&getCODE());
 7792: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7793: 	my $num1=$symbseed+$CODEchck;
 7794: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7795: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7796: 	#&logthis("rndseed :$num1:$num2:$symb");
 7797: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7798: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7799: 	return "$num1:$num2";
 7800:     }
 7801: }
 7802: 
 7803: sub rndseed_CODE_64bit5 {
 7804:     my ($symb,$courseid,$domain,$username)=@_;
 7805:     my $code = &getCODE();
 7806:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7807:     return "$num1:$num2";
 7808: }
 7809: 
 7810: sub setup_random_from_rndseed {
 7811:     my ($rndseed)=@_;
 7812:     if ($rndseed =~/([,:])/) {
 7813: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7814: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7815:     } else {
 7816: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7817:     }
 7818: }
 7819: 
 7820: sub latest_receipt_algorithm_id {
 7821:     return 'receipt3';
 7822: }
 7823: 
 7824: sub recunique {
 7825:     my $fucourseid=shift;
 7826:     my $unique;
 7827:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7828: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7829: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7830:     } else {
 7831: 	$unique=$perlvar{'lonReceipt'};
 7832:     }
 7833:     return unpack("%32C*",$unique);
 7834: }
 7835: 
 7836: sub recprefix {
 7837:     my $fucourseid=shift;
 7838:     my $prefix;
 7839:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7840: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7841: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7842:     } else {
 7843: 	$prefix=$perlvar{'lonHostID'};
 7844:     }
 7845:     return unpack("%32C*",$prefix);
 7846: }
 7847: 
 7848: sub ireceipt {
 7849:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7850: 
 7851:     my $return =&recprefix($fucourseid).'-';
 7852: 
 7853:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7854: 	$env{'request.state'} eq 'construct') {
 7855: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7856: 	return $return;
 7857:     }
 7858: 
 7859:     my $cuname=unpack("%32C*",$funame);
 7860:     my $cudom=unpack("%32C*",$fudom);
 7861:     my $cucourseid=unpack("%32C*",$fucourseid);
 7862:     my $cusymb=unpack("%32C*",$fusymb);
 7863:     my $cunique=&recunique($fucourseid);
 7864:     my $cpart=unpack("%32S*",$part);
 7865:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7866: 
 7867: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7868: 			       
 7869: 	$return.= ($cunique%$cuname+
 7870: 		   $cunique%$cudom+
 7871: 		   $cusymb%$cuname+
 7872: 		   $cusymb%$cudom+
 7873: 		   $cucourseid%$cuname+
 7874: 		   $cucourseid%$cudom+
 7875: 		   $cpart%$cuname+
 7876: 		   $cpart%$cudom);
 7877:     } else {
 7878: 	$return.= ($cunique%$cuname+
 7879: 		   $cunique%$cudom+
 7880: 		   $cusymb%$cuname+
 7881: 		   $cusymb%$cudom+
 7882: 		   $cucourseid%$cuname+
 7883: 		   $cucourseid%$cudom);
 7884:     }
 7885:     return $return;
 7886: }
 7887: 
 7888: sub receipt {
 7889:     my ($part)=@_;
 7890:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7891:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7892: }
 7893: 
 7894: sub whichuser {
 7895:     my ($passedsymb)=@_;
 7896:     my ($symb,$courseid,$domain,$name,$publicuser);
 7897:     if (defined($env{'form.grade_symb'})) {
 7898: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7899: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7900: 	if (!$allowed &&
 7901: 	    exists($env{'request.course.sec'}) &&
 7902: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7903: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7904: 			      '/'.$env{'request.course.sec'});
 7905: 	}
 7906: 	if ($allowed) {
 7907: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7908: 	    $courseid=$tmp_courseid;
 7909: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7910: 	    ($name)=&get_env_multiple('form.grade_username');
 7911: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7912: 	}
 7913:     }
 7914:     if (!$passedsymb) {
 7915: 	$symb=&symbread();
 7916:     } else {
 7917: 	$symb=$passedsymb;
 7918:     }
 7919:     $courseid=$env{'request.course.id'};
 7920:     $domain=$env{'user.domain'};
 7921:     $name=$env{'user.name'};
 7922:     if ($name eq 'public' && $domain eq 'public') {
 7923: 	if (!defined($env{'form.username'})) {
 7924: 	    $env{'form.username'}.=time.rand(10000000);
 7925: 	}
 7926: 	$name.=$env{'form.username'};
 7927:     }
 7928:     return ($symb,$courseid,$domain,$name,$publicuser);
 7929: 
 7930: }
 7931: 
 7932: # ------------------------------------------------------------ Serves up a file
 7933: # returns either the contents of the file or 
 7934: # -1 if the file doesn't exist
 7935: #
 7936: # if the target is a file that was uploaded via DOCS, 
 7937: # a check will be made to see if a current copy exists on the local server,
 7938: # if it does this will be served, otherwise a copy will be retrieved from
 7939: # the home server for the course and stored in /home/httpd/html/userfiles on
 7940: # the local server.   
 7941: 
 7942: sub getfile {
 7943:     my ($file) = @_;
 7944:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7945:     &repcopy($file);
 7946:     return &readfile($file);
 7947: }
 7948: 
 7949: sub repcopy_userfile {
 7950:     my ($file)=@_;
 7951:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7952:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7953:     my ($cdom,$cnum,$filename) = 
 7954: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7955:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7956:     if (-e "$file") {
 7957: # we already have a local copy, check it out
 7958: 	my @fileinfo = stat($file);
 7959: 	my $rtncode;
 7960: 	my $info;
 7961: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7962: 	if ($lwpresp ne 'ok') {
 7963: # there is no such file anymore, even though we had a local copy
 7964: 	    if ($rtncode eq '404') {
 7965: 		unlink($file);
 7966: 	    }
 7967: 	    return -1;
 7968: 	}
 7969: 	if ($info < $fileinfo[9]) {
 7970: # nice, the file we have is up-to-date, just say okay
 7971: 	    return 'ok';
 7972: 	} else {
 7973: # the file is outdated, get rid of it
 7974: 	    unlink($file);
 7975: 	}
 7976:     }
 7977: # one way or the other, at this point, we don't have the file
 7978: # construct the correct path for the file
 7979:     my @parts = ($cdom,$cnum); 
 7980:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7981: 	push @parts, split(/\//,$1);
 7982:     }
 7983:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7984:     foreach my $part (@parts) {
 7985: 	$path .= '/'.$part;
 7986: 	if (!-e $path) {
 7987: 	    mkdir($path,0770);
 7988: 	}
 7989:     }
 7990: # now the path exists for sure
 7991: # get a user agent
 7992:     my $ua=new LWP::UserAgent;
 7993:     my $transferfile=$file.'.in.transfer';
 7994: # FIXME: this should flock
 7995:     if (-e $transferfile) { return 'ok'; }
 7996:     my $request;
 7997:     $uri=~s/^\///;
 7998:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7999:     my $response=$ua->request($request,$transferfile);
 8000: # did it work?
 8001:     if ($response->is_error()) {
 8002: 	unlink($transferfile);
 8003: 	&logthis("Userfile repcopy failed for $uri");
 8004: 	return -1;
 8005:     }
 8006: # worked, rename the transfer file
 8007:     rename($transferfile,$file);
 8008:     return 'ok';
 8009: }
 8010: 
 8011: sub tokenwrapper {
 8012:     my $uri=shift;
 8013:     $uri=~s|^http\://([^/]+)||;
 8014:     $uri=~s|^/||;
 8015:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8016:     my $token=$1;
 8017:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8018:     if ($udom && $uname && $file) {
 8019: 	$file=~s|(\?\.*)*$||;
 8020:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8021:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 8022:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8023:                                '&tokenissued='.$perlvar{'lonHostID'};
 8024:     } else {
 8025:         return '/adm/notfound.html';
 8026:     }
 8027: }
 8028: 
 8029: # call with reqtype HEAD: get last modification time
 8030: # call with reqtype GET: get the file contents
 8031: # Do not call this with reqtype GET for large files! It loads everything into memory
 8032: #
 8033: sub getuploaded {
 8034:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8035:     $uri=~s/^\///;
 8036:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8037:     my $ua=new LWP::UserAgent;
 8038:     my $request=new HTTP::Request($reqtype,$uri);
 8039:     my $response=$ua->request($request);
 8040:     $$rtncode = $response->code;
 8041:     if (! $response->is_success()) {
 8042: 	return 'failed';
 8043:     }      
 8044:     if ($reqtype eq 'HEAD') {
 8045: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8046:     } elsif ($reqtype eq 'GET') {
 8047: 	$$info = $response->content;
 8048:     }
 8049:     return 'ok';
 8050: }
 8051: 
 8052: sub readfile {
 8053:     my $file = shift;
 8054:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8055:     my $fh;
 8056:     open($fh,"<$file");
 8057:     my $a='';
 8058:     while (my $line = <$fh>) { $a .= $line; }
 8059:     return $a;
 8060: }
 8061: 
 8062: sub filelocation {
 8063:     my ($dir,$file) = @_;
 8064:     my $location;
 8065:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8066: 
 8067:     if ($file =~ m-^/adm/-) {
 8068: 	$file=~s-^/adm/wrapper/-/-;
 8069: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8070:     }
 8071: 
 8072:     if ($file=~m:^/~:) { # is a contruction space reference
 8073:         $location = $file;
 8074:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8075:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8076: 	# is a correct contruction space reference
 8077:         $location = $file;
 8078:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8079:         my ($udom,$uname,$filename)=
 8080:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8081:         my $home=&homeserver($uname,$udom);
 8082:         my $is_me=0;
 8083:         my @ids=&current_machine_ids();
 8084:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8085:         if ($is_me) {
 8086:   	    $location=&propath($udom,$uname).
 8087:   	      '/userfiles/'.$filename;
 8088:         } else {
 8089:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8090:   	      $udom.'/'.$uname.'/'.$filename;
 8091:         }
 8092:     } elsif ($file =~ m-^/adm/-) {
 8093: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8094:     } else {
 8095:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8096:         $file=~s:^/res/:/:;
 8097:         if ( !( $file =~ m:^/:) ) {
 8098:             $location = $dir. '/'.$file;
 8099:         } else {
 8100:             $location = '/home/httpd/html/res'.$file;
 8101:         }
 8102:     }
 8103:     $location=~s://+:/:g; # remove duplicate /
 8104:     while ($location=~m{/\.\./}) {
 8105: 	if ($location =~ m{/[^/]+/\.\./}) {
 8106: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8107: 	} else {
 8108: 	    $location=~ s{/\.\./}{/}g;
 8109: 	}
 8110:     } #remove dir/..
 8111:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8112:     return $location;
 8113: }
 8114: 
 8115: sub hreflocation {
 8116:     my ($dir,$file)=@_;
 8117:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8118: 	$file=filelocation($dir,$file);
 8119:     } elsif ($file=~m-^/adm/-) {
 8120: 	$file=~s-^/adm/wrapper/-/-;
 8121: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8122:     }
 8123:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8124: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8125:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8126: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8127:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8128: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8129: 	    -/uploaded/$1/$2/-x;
 8130:     }
 8131:     if ($file=~ m{^/userfiles/}) {
 8132: 	$file =~ s{^/userfiles/}{/uploaded/};
 8133:     }
 8134:     return $file;
 8135: }
 8136: 
 8137: sub current_machine_domains {
 8138:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8139: }
 8140: 
 8141: sub machine_domains {
 8142:     my ($hostname) = @_;
 8143:     my @domains;
 8144:     my %hostname = &all_hostnames();
 8145:     while( my($id, $name) = each(%hostname)) {
 8146: #	&logthis("-$id-$name-$hostname-");
 8147: 	if ($hostname eq $name) {
 8148: 	    push(@domains,&host_domain($id));
 8149: 	}
 8150:     }
 8151:     return @domains;
 8152: }
 8153: 
 8154: sub current_machine_ids {
 8155:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8156: }
 8157: 
 8158: sub machine_ids {
 8159:     my ($hostname) = @_;
 8160:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8161:     my @ids;
 8162:     my %name_to_host = &all_names();
 8163:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8164: 	return @{ $name_to_host{$hostname} };
 8165:     }
 8166:     return;
 8167: }
 8168: 
 8169: sub additional_machine_domains {
 8170:     my @domains;
 8171:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8172:     while( my $line = <$fh>) {
 8173:         $line =~ s/\s//g;
 8174:         push(@domains,$line);
 8175:     }
 8176:     return @domains;
 8177: }
 8178: 
 8179: sub default_login_domain {
 8180:     my $domain = $perlvar{'lonDefDomain'};
 8181:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8182:     foreach my $posdom (&current_machine_domains(),
 8183:                         &additional_machine_domains()) {
 8184:         if (lc($posdom) eq lc($testdomain)) {
 8185:             $domain=$posdom;
 8186:             last;
 8187:         }
 8188:     }
 8189:     return $domain;
 8190: }
 8191: 
 8192: # ------------------------------------------------------------- Declutters URLs
 8193: 
 8194: sub declutter {
 8195:     my $thisfn=shift;
 8196:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8197:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8198:     $thisfn=~s/^\///;
 8199:     $thisfn=~s|^adm/wrapper/||;
 8200:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8201:     $thisfn=~s/^res\///;
 8202:     $thisfn=~s/\?.+$//;
 8203:     return $thisfn;
 8204: }
 8205: 
 8206: # ------------------------------------------------------------- Clutter up URLs
 8207: 
 8208: sub clutter {
 8209:     my $thisfn='/'.&declutter(shift);
 8210:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8211: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8212:        $thisfn='/res'.$thisfn; 
 8213:     }
 8214:     if ($thisfn !~m|/adm|) {
 8215: 	if ($thisfn =~ m|/ext/|) {
 8216: 	    $thisfn='/adm/wrapper'.$thisfn;
 8217: 	} else {
 8218: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8219: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8220: 	    if ($embstyle eq 'ssi'
 8221: 		|| ($embstyle eq 'hdn')
 8222: 		|| ($embstyle eq 'rat')
 8223: 		|| ($embstyle eq 'prv')
 8224: 		|| ($embstyle eq 'ign')) {
 8225: 		#do nothing with these
 8226: 	    } elsif (($embstyle eq 'img') 
 8227: 		|| ($embstyle eq 'emb')
 8228: 		|| ($embstyle eq 'wrp')) {
 8229: 		$thisfn='/adm/wrapper'.$thisfn;
 8230: 	    } elsif ($embstyle eq 'unk'
 8231: 		     && $thisfn!~/\.(sequence|page)$/) {
 8232: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8233: 	    } else {
 8234: #		&logthis("Got a blank emb style");
 8235: 	    }
 8236: 	}
 8237:     }
 8238:     return $thisfn;
 8239: }
 8240: 
 8241: sub clutter_with_no_wrapper {
 8242:     my $uri = &clutter(shift);
 8243:     if ($uri =~ m-^/adm/-) {
 8244: 	$uri =~ s-^/adm/wrapper/-/-;
 8245: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8246:     }
 8247:     return $uri;
 8248: }
 8249: 
 8250: sub freeze_escape {
 8251:     my ($value)=@_;
 8252:     if (ref($value)) {
 8253: 	$value=&nfreeze($value);
 8254: 	return '__FROZEN__'.&escape($value);
 8255:     }
 8256:     return &escape($value);
 8257: }
 8258: 
 8259: 
 8260: sub thaw_unescape {
 8261:     my ($value)=@_;
 8262:     if ($value =~ /^__FROZEN__/) {
 8263: 	substr($value,0,10,undef);
 8264: 	$value=&unescape($value);
 8265: 	return &thaw($value);
 8266:     }
 8267:     return &unescape($value);
 8268: }
 8269: 
 8270: sub correct_line_ends {
 8271:     my ($result)=@_;
 8272:     $$result =~s/\r\n/\n/mg;
 8273:     $$result =~s/\r/\n/mg;
 8274: }
 8275: # ================================================================ Main Program
 8276: 
 8277: sub goodbye {
 8278:    &logthis("Starting Shut down");
 8279: #not converted to using infrastruture and probably shouldn't be
 8280:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8281: #converted
 8282: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8283:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8284: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8285: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8286: #1.1 only
 8287: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8288: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8289: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8290: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8291:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8292:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8293:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8294:    &flushcourselogs();
 8295:    &logthis("Shutting down");
 8296: }
 8297: 
 8298: sub get_dns {
 8299:     my ($url,$func,$ignore_cache) = @_;
 8300:     if (!$ignore_cache) {
 8301: 	my ($content,$cached)=
 8302: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8303: 	if ($cached) {
 8304: 	    &$func($content);
 8305: 	    return;
 8306: 	}
 8307:     }
 8308: 
 8309:     my %alldns;
 8310:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8311:     foreach my $dns (<$config>) {
 8312: 	next if ($dns !~ /^\^(\S*)/x);
 8313: 	$alldns{$1} = 1;
 8314:     }
 8315:     while (%alldns) {
 8316: 	my ($dns) = keys(%alldns);
 8317: 	delete($alldns{$dns});
 8318: 	my $ua=new LWP::UserAgent;
 8319: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8320: 	my $response=$ua->request($request);
 8321: 	next if ($response->is_error());
 8322: 	my @content = split("\n",$response->content);
 8323: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8324: 	&$func(\@content);
 8325: 	return;
 8326:     }
 8327:     close($config);
 8328:     my $which = (split('/',$url))[3];
 8329:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8330:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8331:     my @content = <$config>;
 8332:     &$func(\@content);
 8333:     return;
 8334: }
 8335: # ------------------------------------------------------------ Read domain file
 8336: {
 8337:     my $loaded;
 8338:     my %domain;
 8339: 
 8340:     sub parse_domain_tab {
 8341: 	my ($lines) = @_;
 8342: 	foreach my $line (@$lines) {
 8343: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8344: 
 8345: 	    chomp($line);
 8346: 	    my ($name,@elements) = split(/:/,$line,9);
 8347: 	    my %this_domain;
 8348: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8349: 			       'lang_def', 'city', 'longi', 'lati',
 8350: 			       'primary') {
 8351: 		$this_domain{$field} = shift(@elements);
 8352: 	    }
 8353: 	    $domain{$name} = \%this_domain;
 8354: 	}
 8355:     }
 8356: 
 8357:     sub reset_domain_info {
 8358: 	undef($loaded);
 8359: 	undef(%domain);
 8360:     }
 8361: 
 8362:     sub load_domain_tab {
 8363: 	my ($ignore_cache) = @_;
 8364: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8365: 	my $fh;
 8366: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8367: 	    my @lines = <$fh>;
 8368: 	    &parse_domain_tab(\@lines);
 8369: 	}
 8370: 	close($fh);
 8371: 	$loaded = 1;
 8372:     }
 8373: 
 8374:     sub domain {
 8375: 	&load_domain_tab() if (!$loaded);
 8376: 
 8377: 	my ($name,$what) = @_;
 8378: 	return if ( !exists($domain{$name}) );
 8379: 
 8380: 	if (!$what) {
 8381: 	    return $domain{$name}{'description'};
 8382: 	}
 8383: 	return $domain{$name}{$what};
 8384:     }
 8385: }
 8386: 
 8387: 
 8388: # ------------------------------------------------------------- Read hosts file
 8389: {
 8390:     my %hostname;
 8391:     my %hostdom;
 8392:     my %libserv;
 8393:     my $loaded;
 8394:     my %name_to_host;
 8395: 
 8396:     sub parse_hosts_tab {
 8397: 	my ($file) = @_;
 8398: 	foreach my $configline (@$file) {
 8399: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8400: 	    next if ($configline =~ /^\^/);
 8401: 	    chomp($configline);
 8402: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8403: 	    $name=~s/\s//g;
 8404: 	    if ($id && $domain && $role && $name) {
 8405: 		$hostname{$id}=$name;
 8406: 		push(@{$name_to_host{$name}}, $id);
 8407: 		$hostdom{$id}=$domain;
 8408: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8409: 	    }
 8410: 	}
 8411:     }
 8412:     
 8413:     sub reset_hosts_info {
 8414: 	&purge_remembered();
 8415: 	&reset_domain_info();
 8416: 	&reset_hosts_ip_info();
 8417: 	undef(%name_to_host);
 8418: 	undef(%hostname);
 8419: 	undef(%hostdom);
 8420: 	undef(%libserv);
 8421: 	undef($loaded);
 8422:     }
 8423: 
 8424:     sub load_hosts_tab {
 8425: 	my ($ignore_cache) = @_;
 8426: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8427: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8428: 	my @config = <$config>;
 8429: 	&parse_hosts_tab(\@config);
 8430: 	close($config);
 8431: 	$loaded=1;
 8432:     }
 8433: 
 8434:     sub hostname {
 8435: 	&load_hosts_tab() if (!$loaded);
 8436: 
 8437: 	my ($lonid) = @_;
 8438: 	return $hostname{$lonid};
 8439:     }
 8440: 
 8441:     sub all_hostnames {
 8442: 	&load_hosts_tab() if (!$loaded);
 8443: 
 8444: 	return %hostname;
 8445:     }
 8446: 
 8447:     sub all_names {
 8448: 	&load_hosts_tab() if (!$loaded);
 8449: 
 8450: 	return %name_to_host;
 8451:     }
 8452: 
 8453:     sub is_library {
 8454: 	&load_hosts_tab() if (!$loaded);
 8455: 
 8456: 	return exists($libserv{$_[0]});
 8457:     }
 8458: 
 8459:     sub all_library {
 8460: 	&load_hosts_tab() if (!$loaded);
 8461: 
 8462: 	return %libserv;
 8463:     }
 8464: 
 8465:     sub get_servers {
 8466: 	&load_hosts_tab() if (!$loaded);
 8467: 
 8468: 	my ($domain,$type) = @_;
 8469: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8470: 	                                          : %hostname;
 8471: 	my %result;
 8472: 	if (ref($domain) eq 'ARRAY') {
 8473: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8474: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8475: 		    $result{$host} = $hostname;
 8476: 		}
 8477: 	    }
 8478: 	} else {
 8479: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8480: 		if ($hostdom{$host} eq $domain) {
 8481: 		    $result{$host} = $hostname;
 8482: 		}
 8483: 	    }
 8484: 	}
 8485: 	return %result;
 8486:     }
 8487: 
 8488:     sub host_domain {
 8489: 	&load_hosts_tab() if (!$loaded);
 8490: 
 8491: 	my ($lonid) = @_;
 8492: 	return $hostdom{$lonid};
 8493:     }
 8494: 
 8495:     sub all_domains {
 8496: 	&load_hosts_tab() if (!$loaded);
 8497: 
 8498: 	my %seen;
 8499: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8500: 	return @uniq;
 8501:     }
 8502: }
 8503: 
 8504: { 
 8505:     my %iphost;
 8506:     my %name_to_ip;
 8507:     my %lonid_to_ip;
 8508: 
 8509:     sub get_hosts_from_ip {
 8510: 	my ($ip) = @_;
 8511: 	my %iphosts = &get_iphost();
 8512: 	if (ref($iphosts{$ip})) {
 8513: 	    return @{$iphosts{$ip}};
 8514: 	}
 8515: 	return;
 8516:     }
 8517:     
 8518:     sub reset_hosts_ip_info {
 8519: 	undef(%iphost);
 8520: 	undef(%name_to_ip);
 8521: 	undef(%lonid_to_ip);
 8522:     }
 8523: 
 8524:     sub get_host_ip {
 8525: 	my ($lonid) = @_;
 8526: 	if (exists($lonid_to_ip{$lonid})) {
 8527: 	    return $lonid_to_ip{$lonid};
 8528: 	}
 8529: 	my $name=&hostname($lonid);
 8530:    	my $ip = gethostbyname($name);
 8531: 	return if (!$ip || length($ip) ne 4);
 8532: 	$ip=inet_ntoa($ip);
 8533: 	$name_to_ip{$name}   = $ip;
 8534: 	$lonid_to_ip{$lonid} = $ip;
 8535: 	return $ip;
 8536:     }
 8537:     
 8538:     sub get_iphost {
 8539: 	my ($ignore_cache) = @_;
 8540: 
 8541: 	if (!$ignore_cache) {
 8542: 	    if (%iphost) {
 8543: 		return %iphost;
 8544: 	    }
 8545: 	    my ($ip_info,$cached)=
 8546: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8547: 	    if ($cached) {
 8548: 		%iphost      = %{$ip_info->[0]};
 8549: 		%name_to_ip  = %{$ip_info->[1]};
 8550: 		%lonid_to_ip = %{$ip_info->[2]};
 8551: 		return %iphost;
 8552: 	    }
 8553: 	}
 8554: 
 8555: 	# get yesterday's info for fallback
 8556: 	my %old_name_to_ip;
 8557: 	my ($ip_info,$cached)=
 8558: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8559: 	if ($cached) {
 8560: 	    %old_name_to_ip = %{$ip_info->[1]};
 8561: 	}
 8562: 
 8563: 	my %name_to_host = &all_names();
 8564: 	foreach my $name (keys(%name_to_host)) {
 8565: 	    my $ip;
 8566: 	    if (!exists($name_to_ip{$name})) {
 8567: 		$ip = gethostbyname($name);
 8568: 		if (!$ip || length($ip) ne 4) {
 8569: 		    if (defined($old_name_to_ip{$name})) {
 8570: 			$ip = $old_name_to_ip{$name};
 8571: 			&logthis("Can't find $name defaulting to old $ip");
 8572: 		    } else {
 8573: 			&logthis("Name $name no IP found");
 8574: 			next;
 8575: 		    }
 8576: 		} else {
 8577: 		    $ip=inet_ntoa($ip);
 8578: 		}
 8579: 		$name_to_ip{$name} = $ip;
 8580: 	    } else {
 8581: 		$ip = $name_to_ip{$name};
 8582: 	    }
 8583: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8584: 		$lonid_to_ip{$id} = $ip;
 8585: 	    }
 8586: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8587: 	}
 8588: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8589: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8590: 				      48*60*60);
 8591: 
 8592: 	return %iphost;
 8593:     }
 8594: }
 8595: 
 8596: BEGIN {
 8597: 
 8598: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8599:     unless ($readit) {
 8600: {
 8601:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8602:     %perlvar = (%perlvar,%{$configvars});
 8603: }
 8604: 
 8605: 
 8606: # ------------------------------------------------------ Read spare server file
 8607: {
 8608:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8609: 
 8610:     while (my $configline=<$config>) {
 8611:        chomp($configline);
 8612:        if ($configline) {
 8613: 	   my ($host,$type) = split(':',$configline,2);
 8614: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8615: 	   push(@{ $spareid{$type} }, $host);
 8616:        }
 8617:     }
 8618:     close($config);
 8619: }
 8620: # ------------------------------------------------------------ Read permissions
 8621: {
 8622:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8623: 
 8624:     while (my $configline=<$config>) {
 8625: 	chomp($configline);
 8626: 	if ($configline) {
 8627: 	    my ($role,$perm)=split(/ /,$configline);
 8628: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8629: 	}
 8630:     }
 8631:     close($config);
 8632: }
 8633: 
 8634: # -------------------------------------------- Read plain texts for permissions
 8635: {
 8636:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8637: 
 8638:     while (my $configline=<$config>) {
 8639: 	chomp($configline);
 8640: 	if ($configline) {
 8641: 	    my ($short,@plain)=split(/:/,$configline);
 8642:             %{$prp{$short}} = ();
 8643: 	    if (@plain > 0) {
 8644:                 $prp{$short}{'std'} = $plain[0];
 8645:                 for (my $i=1; $i<@plain; $i++) {
 8646:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8647:                 }
 8648:             }
 8649: 	}
 8650:     }
 8651:     close($config);
 8652: }
 8653: 
 8654: # ---------------------------------------------------------- Read package table
 8655: {
 8656:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8657: 
 8658:     while (my $configline=<$config>) {
 8659: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8660: 	chomp($configline);
 8661: 	my ($short,$plain)=split(/:/,$configline);
 8662: 	my ($pack,$name)=split(/\&/,$short);
 8663: 	if ($plain ne '') {
 8664: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8665: 	    $packagetab{$short}=$plain; 
 8666: 	}
 8667:     }
 8668:     close($config);
 8669: }
 8670: 
 8671: # ------------- set up temporary directory
 8672: {
 8673:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8674: 
 8675: }
 8676: 
 8677: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8678: 				'compress_threshold'=> 20_000,
 8679:  			        });
 8680: 
 8681: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8682: $dumpcount=0;
 8683: 
 8684: &logtouch();
 8685: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8686: $readit=1;
 8687:     {
 8688: 	use integer;
 8689: 	my $test=(2**32)+1;
 8690: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8691: 	&logthis(" Detected 64bit platform ($_64bit)");
 8692:     }
 8693: }
 8694: }
 8695: 
 8696: 1;
 8697: __END__
 8698: 
 8699: =pod
 8700: 
 8701: =head1 NAME
 8702: 
 8703: Apache::lonnet - Subroutines to ask questions about things in the network.
 8704: 
 8705: =head1 SYNOPSIS
 8706: 
 8707: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8708: 
 8709:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8710: 
 8711: Common parameters:
 8712: 
 8713: =over 4
 8714: 
 8715: =item *
 8716: 
 8717: $uname : an internal username (if $cname expecting a course Id specifically)
 8718: 
 8719: =item *
 8720: 
 8721: $udom : a domain (if $cdom expecting a course's domain specifically)
 8722: 
 8723: =item *
 8724: 
 8725: $symb : a resource instance identifier
 8726: 
 8727: =item *
 8728: 
 8729: $namespace : the name of a .db file that contains the data needed or
 8730: being set.
 8731: 
 8732: =back
 8733: 
 8734: =head1 OVERVIEW
 8735: 
 8736: lonnet provides subroutines which interact with the
 8737: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8738: about classes, users, and resources.
 8739: 
 8740: For many of these objects you can also use this to store data about
 8741: them or modify them in various ways.
 8742: 
 8743: =head2 Symbs
 8744: 
 8745: To identify a specific instance of a resource, LON-CAPA uses symbols
 8746: or "symbs"X<symb>. These identifiers are built from the URL of the
 8747: map, the resource number of the resource in the map, and the URL of
 8748: the resource itself. The latter is somewhat redundant, but might help
 8749: if maps change.
 8750: 
 8751: An example is
 8752: 
 8753:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8754: 
 8755: The respective map entry is
 8756: 
 8757:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8758:   title="Problem 2">
 8759:  </resource>
 8760: 
 8761: Symbs are used by the random number generator, as well as to store and
 8762: restore data specific to a certain instance of for example a problem.
 8763: 
 8764: =head2 Storing And Retrieving Data
 8765: 
 8766: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8767: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8768: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8769: is is the non-critical message twin of cstore. These functions are for
 8770: handlers to store a perl hash to a user's permanent data space in an
 8771: easy manner, and to retrieve it again on another call. It is expected
 8772: that a handler would use this once at the beginning to retrieve data,
 8773: and then again once at the end to send only the new data back.
 8774: 
 8775: The data is stored in the user's data directory on the user's
 8776: homeserver under the ID of the course.
 8777: 
 8778: The hash that is returned by restore will have all of the previous
 8779: value for all of the elements of the hash.
 8780: 
 8781: Example:
 8782: 
 8783:  #creating a hash
 8784:  my %hash;
 8785:  $hash{'foo'}='bar';
 8786: 
 8787:  #storing it
 8788:  &Apache::lonnet::cstore(\%hash);
 8789: 
 8790:  #changing a value
 8791:  $hash{'foo'}='notbar';
 8792: 
 8793:  #adding a new value
 8794:  $hash{'bar'}='foo';
 8795:  &Apache::lonnet::cstore(\%hash);
 8796: 
 8797:  #retrieving the hash
 8798:  my %history=&Apache::lonnet::restore();
 8799: 
 8800:  #print the hash
 8801:  foreach my $key (sort(keys(%history))) {
 8802:    print("\%history{$key} = $history{$key}");
 8803:  }
 8804: 
 8805: Will print out:
 8806: 
 8807:  %history{1:foo} = bar
 8808:  %history{1:keys} = foo:timestamp
 8809:  %history{1:timestamp} = 990455579
 8810:  %history{2:bar} = foo
 8811:  %history{2:foo} = notbar
 8812:  %history{2:keys} = foo:bar:timestamp
 8813:  %history{2:timestamp} = 990455580
 8814:  %history{bar} = foo
 8815:  %history{foo} = notbar
 8816:  %history{timestamp} = 990455580
 8817:  %history{version} = 2
 8818: 
 8819: Note that the special hash entries C<keys>, C<version> and
 8820: C<timestamp> were added to the hash. C<version> will be equal to the
 8821: total number of versions of the data that have been stored. The
 8822: C<timestamp> attribute will be the UNIX time the hash was
 8823: stored. C<keys> is available in every historical section to list which
 8824: keys were added or changed at a specific historical revision of a
 8825: hash.
 8826: 
 8827: B<Warning>: do not store the hash that restore returns directly. This
 8828: will cause a mess since it will restore the historical keys as if the
 8829: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8830: 
 8831: Calling convention:
 8832: 
 8833:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8834:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8835: 
 8836: For more detailed information, see lonnet specific documentation.
 8837: 
 8838: =head1 RETURN MESSAGES
 8839: 
 8840: =over 4
 8841: 
 8842: =item * B<con_lost>: unable to contact remote host
 8843: 
 8844: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8845: when the connection is brought back up
 8846: 
 8847: =item * B<con_failed>: unable to contact remote host and unable to save message
 8848: for later delivery
 8849: 
 8850: =item * B<error:>: an error a occured, a description of the error follows the :
 8851: 
 8852: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8853: that was requested
 8854: 
 8855: =back
 8856: 
 8857: =head1 PUBLIC SUBROUTINES
 8858: 
 8859: =head2 Session Environment Functions
 8860: 
 8861: =over 4
 8862: 
 8863: =item * 
 8864: X<appenv()>
 8865: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 8866: the user envirnoment file, and will be restored for each access this
 8867: user makes during this session, also modifies the %env for the current
 8868: process. Optional rolesarrayref - if defined contains a reference to an array
 8869: of roles which are exempt from the restriction on modifying user.role entries 
 8870: in the user's environment.db and in %env.    
 8871: 
 8872: =item *
 8873: X<delenv()>
 8874: B<delenv($regexp)>: removes all items from the session
 8875: environment file that matches the regular expression in $regexp. The
 8876: values are also delted from the current processes %env.
 8877: 
 8878: =item * get_env_multiple($name) 
 8879: 
 8880: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8881: values may be defined and end up as an array ref.
 8882: 
 8883: returns an array of values
 8884: 
 8885: =back
 8886: 
 8887: =head2 User Information
 8888: 
 8889: =over 4
 8890: 
 8891: =item *
 8892: X<queryauthenticate()>
 8893: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8894: authentication scheme
 8895: 
 8896: =item *
 8897: X<authenticate()>
 8898: B<authenticate($uname,$upass,$udom)>: try to
 8899: authenticate user from domain's lib servers (first use the current
 8900: one). C<$upass> should be the users password.
 8901: 
 8902: =item *
 8903: X<homeserver()>
 8904: B<homeserver($uname,$udom)>: find the server which has
 8905: the user's directory and files (there must be only one), this caches
 8906: the answer, and also caches if there is a borken connection.
 8907: 
 8908: =item *
 8909: X<idget()>
 8910: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8911: (IDs are a unique resource in a domain, there must be only 1 ID per
 8912: username, and only 1 username per ID in a specific domain) (returns
 8913: hash: id=>name,id=>name)
 8914: 
 8915: =item *
 8916: X<idrget()>
 8917: B<idrget($udom,@unames)>: find the IDs behind a list of
 8918: usernames (returns hash: name=>id,name=>id)
 8919: 
 8920: =item *
 8921: X<idput()>
 8922: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8923: 
 8924: =item *
 8925: X<rolesinit()>
 8926: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8927: 
 8928: =item *
 8929: X<getsection()>
 8930: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8931: course $cname, return section name/number or '' for "not in course"
 8932: and '-1' for "no section"
 8933: 
 8934: =item *
 8935: X<userenvironment()>
 8936: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8937: passed in @what from the requested user's environment, returns a hash
 8938: 
 8939: =item * 
 8940: X<userlog_query()>
 8941: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8942: activity.log file. %filters defines filters applied when parsing the
 8943: log file. These can be start or end timestamps, or the type of action
 8944: - log to look for Login or Logout events, check for Checkin or
 8945: Checkout, role for role selection. The response is in the form
 8946: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8947: escaped strings of the action recorded in the activity.log file.
 8948: 
 8949: =back
 8950: 
 8951: =head2 User Roles
 8952: 
 8953: =over 4
 8954: 
 8955: =item *
 8956: 
 8957: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8958:  F: full access
 8959:  U,I,K: authentication modes (cxx only)
 8960:  '': forbidden
 8961:  1: user needs to choose course
 8962:  2: browse allowed
 8963:  A: passphrase authentication needed
 8964: 
 8965: =item *
 8966: 
 8967: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8968: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8969: and course level
 8970: 
 8971: =item *
 8972: 
 8973: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8974: explanation of a user role term
 8975: 
 8976: =item *
 8977: 
 8978: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8979: All arguments are optional. Returns a hash of a roles, either for
 8980: co-author/assistant author roles for a user's Construction Space
 8981: (default), or if $context is 'userroles', roles for the user himself,
 8982: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8983: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8984: For each key, value is set to colon-separated start and end times for
 8985: the role.  If no username and domain are specified, will default to
 8986: current user/domain. Types, roles, and roledoms are references to arrays
 8987: of role statuses (active, future or previous), roles 
 8988: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8989: to restrict the list of roles reported. If no array ref is 
 8990: provided for types, will default to return only active roles.
 8991: 
 8992: =back
 8993: 
 8994: =head2 User Modification
 8995: 
 8996: =over 4
 8997: 
 8998: =item *
 8999: 
 9000: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 9001: user for the level given by URL.  Optional start and end dates (leave empty
 9002: string or zero for "no date")
 9003: 
 9004: =item *
 9005: 
 9006: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9007: change a users, password, possible return values are: ok,
 9008: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9009: refused
 9010: 
 9011: =item *
 9012: 
 9013: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9014: 
 9015: =item *
 9016: 
 9017: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 9018: modify user
 9019: 
 9020: =item *
 9021: 
 9022: modifystudent
 9023: 
 9024: modify a students enrollment and identification information.
 9025: The course id is resolved based on the current users environment.  
 9026: This means the envoking user must be a course coordinator or otherwise
 9027: associated with a course.
 9028: 
 9029: This call is essentially a wrapper for lonnet::modifyuser and
 9030: lonnet::modify_student_enrollment
 9031: 
 9032: Inputs: 
 9033: 
 9034: =over 4
 9035: 
 9036: =item B<$udom> Students loncapa domain
 9037: 
 9038: =item B<$uname> Students loncapa login name
 9039: 
 9040: =item B<$uid> Students id/student number
 9041: 
 9042: =item B<$umode> Students authentication mode
 9043: 
 9044: =item B<$upass> Students password
 9045: 
 9046: =item B<$first> Students first name
 9047: 
 9048: =item B<$middle> Students middle name
 9049: 
 9050: =item B<$last> Students last name
 9051: 
 9052: =item B<$gene> Students generation
 9053: 
 9054: =item B<$usec> Students section in course
 9055: 
 9056: =item B<$end> Unix time of the roles expiration
 9057: 
 9058: =item B<$start> Unix time of the roles start date
 9059: 
 9060: =item B<$forceid> If defined, allow $uid to be changed
 9061: 
 9062: =item B<$desiredhome> server to use as home server for student
 9063: 
 9064: =back
 9065: 
 9066: =item *
 9067: 
 9068: modify_student_enrollment
 9069: 
 9070: Change a students enrollment status in a class.  The environment variable
 9071: 'role.request.course' must be defined for this function to proceed.
 9072: 
 9073: Inputs:
 9074: 
 9075: =over 4
 9076: 
 9077: =item $udom, students domain
 9078: 
 9079: =item $uname, students name
 9080: 
 9081: =item $uid, students user id
 9082: 
 9083: =item $first, students first name
 9084: 
 9085: =item $middle
 9086: 
 9087: =item $last
 9088: 
 9089: =item $gene
 9090: 
 9091: =item $usec
 9092: 
 9093: =item $end
 9094: 
 9095: =item $start
 9096: 
 9097: =back
 9098: 
 9099: 
 9100: =item *
 9101: 
 9102: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9103: custom role; give a custom role to a user for the level given by URL.  Specify
 9104: name and domain of role author, and role name
 9105: 
 9106: =item *
 9107: 
 9108: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9109: 
 9110: =item *
 9111: 
 9112: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9113: 
 9114: =back
 9115: 
 9116: =head2 Course Infomation
 9117: 
 9118: =over 4
 9119: 
 9120: =item *
 9121: 
 9122: coursedescription($courseid) : returns a hash of information about the
 9123: specified course id, including all environment settings for the
 9124: course, the description of the course will be in the hash under the
 9125: key 'description'
 9126: 
 9127: =item *
 9128: 
 9129: resdata($name,$domain,$type,@which) : request for current parameter
 9130: setting for a specific $type, where $type is either 'course' or 'user',
 9131: @what should be a list of parameters to ask about. This routine caches
 9132: answers for 5 minutes.
 9133: 
 9134: =item *
 9135: 
 9136: get_courseresdata($courseid, $domain) : dump the entire course resource
 9137: data base, returning a hash that is keyed by the resource name and has
 9138: values that are the resource value.  I believe that the timestamps and
 9139: versions are also returned.
 9140: 
 9141: 
 9142: =back
 9143: 
 9144: =head2 Course Modification
 9145: 
 9146: =over 4
 9147: 
 9148: =item *
 9149: 
 9150: writecoursepref($courseid,%prefs) : write preferences (environment
 9151: database) for a course
 9152: 
 9153: =item *
 9154: 
 9155: createcourse($udom,$description,$url) : make/modify course
 9156: 
 9157: =back
 9158: 
 9159: =head2 Resource Subroutines
 9160: 
 9161: =over 4
 9162: 
 9163: =item *
 9164: 
 9165: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9166: 
 9167: =item *
 9168: 
 9169: repcopy($filename) : subscribes to the requested file, and attempts to
 9170: replicate from the owning library server, Might return
 9171: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9172: 'bad_request', also attempts to grab the metadata for the
 9173: resource. Expects the local filesystem pathname
 9174: (/home/httpd/html/res/....)
 9175: 
 9176: =back
 9177: 
 9178: =head2 Resource Information
 9179: 
 9180: =over 4
 9181: 
 9182: =item *
 9183: 
 9184: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9185: a vairety of different possible values, $varname should be a request
 9186: string, and the other parameters can be used to specify who and what
 9187: one is asking about.
 9188: 
 9189: Possible values for $varname are environment.lastname (or other item
 9190: from the envirnment hash), user.name (or someother aspect about the
 9191: user), resource.0.maxtries (or some other part and parameter of a
 9192: resource)
 9193: 
 9194: =item *
 9195: 
 9196: directcondval($number) : get current value of a condition; reads from a state
 9197: string
 9198: 
 9199: =item *
 9200: 
 9201: condval($condidx) : value of condition index based on state
 9202: 
 9203: =item *
 9204: 
 9205: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9206: resource's metadata, $what should be either a specific key, or either
 9207: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9208: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9209: 
 9210: this function automatically caches all requests
 9211: 
 9212: =item *
 9213: 
 9214: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9215: network of library servers; returns file handle of where SQL and regex results
 9216: will be stored for query
 9217: 
 9218: =item *
 9219: 
 9220: symbread($filename) : return symbolic list entry (filename argument optional);
 9221: returns the data handle
 9222: 
 9223: =item *
 9224: 
 9225: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9226: a possible symb for the URL in $thisfn, and if is an encryypted
 9227: resource that the user accessed using /enc/ returns a 1 on success, 0
 9228: on failure, user must be in a course, as it assumes the existance of
 9229: the course initial hash, and uses $env('request.course.id'}
 9230: 
 9231: 
 9232: =item *
 9233: 
 9234: symbclean($symb) : removes versions numbers from a symb, returns the
 9235: cleaned symb
 9236: 
 9237: =item *
 9238: 
 9239: is_on_map($uri) : checks if the $uri is somewhere on the current
 9240: course map, user must be in a course for it to work.
 9241: 
 9242: =item *
 9243: 
 9244: numval($salt) : return random seed value (addend for rndseed)
 9245: 
 9246: =item *
 9247: 
 9248: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9249: a random seed, all arguments are optional, if they aren't sent it uses the
 9250: environment to derive them. Note: if symb isn't sent and it can't get one
 9251: from &symbread it will use the current time as its return value
 9252: 
 9253: =item *
 9254: 
 9255: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9256: unfakeable, receipt
 9257: 
 9258: =item *
 9259: 
 9260: receipt() : API to ireceipt working off of env values; given out to users
 9261: 
 9262: =item *
 9263: 
 9264: countacc($url) : count the number of accesses to a given URL
 9265: 
 9266: =item *
 9267: 
 9268: 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
 9269: 
 9270: =item *
 9271: 
 9272: 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)
 9273: 
 9274: =item *
 9275: 
 9276: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9277: 
 9278: =item *
 9279: 
 9280: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9281: forcing spreadsheet to reevaluate the resource scores next time.
 9282: 
 9283: =back
 9284: 
 9285: =head2 Storing/Retreiving Data
 9286: 
 9287: =over 4
 9288: 
 9289: =item *
 9290: 
 9291: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9292: for this url; hashref needs to be given and should be a \%hashname; the
 9293: remaining args aren't required and if they aren't passed or are '' they will
 9294: be derived from the env
 9295: 
 9296: =item *
 9297: 
 9298: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9299: uses critical subroutine
 9300: 
 9301: =item *
 9302: 
 9303: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9304: all args are optional
 9305: 
 9306: =item *
 9307: 
 9308: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9309: dumps the complete (or key matching regexp) namespace into a hash
 9310: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9311: normally &store()ed into
 9312: 
 9313: $range should be either an integer '100' (give me the first 100
 9314:                                            matching records)
 9315:               or be  two integers sperated by a - with no spaces
 9316:                  '30-50' (give me the 30th through the 50th matching
 9317:                           records)
 9318: 
 9319: 
 9320: =item *
 9321: 
 9322: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9323: replaces a &store() version of data with a replacement set of data
 9324: for a particular resource in a namespace passed in the $storehash hash 
 9325: reference
 9326: 
 9327: =item *
 9328: 
 9329: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9330: works very similar to store/cstore, but all data is stored in a
 9331: temporary location and can be reset using tmpreset, $storehash should
 9332: be a hash reference, returns nothing on success
 9333: 
 9334: =item *
 9335: 
 9336: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9337: similar to restore, but all data is stored in a temporary location and
 9338: can be reset using tmpreset. Returns a hash of values on success,
 9339: error string otherwise.
 9340: 
 9341: =item *
 9342: 
 9343: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9344: deltes all keys for $symb form the temporary storage hash.
 9345: 
 9346: =item *
 9347: 
 9348: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9349: reference filled in from namesp ($udom and $uname are optional)
 9350: 
 9351: =item *
 9352: 
 9353: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9354: namesp ($udom and $uname are optional)
 9355: 
 9356: =item *
 9357: 
 9358: dump($namespace,$udom,$uname,$regexp,$range) : 
 9359: dumps the complete (or key matching regexp) namespace into a hash
 9360: ($udom, $uname, $regexp, $range are optional)
 9361: 
 9362: $range should be either an integer '100' (give me the first 100
 9363:                                            matching records)
 9364:               or be  two integers sperated by a - with no spaces
 9365:                  '30-50' (give me the 30th through the 50th matching
 9366:                           records)
 9367: =item *
 9368: 
 9369: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9370: $store can be a scalar, an array reference, or if the amount to be 
 9371: incremented is > 1, a hash reference.
 9372: 
 9373: ($udom and $uname are optional)
 9374: 
 9375: =item *
 9376: 
 9377: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9378: ($udom and $uname are optional)
 9379: 
 9380: =item *
 9381: 
 9382: cput($namespace,$storehash,$udom,$uname) : critical put
 9383: ($udom and $uname are optional)
 9384: 
 9385: =item *
 9386: 
 9387: newput($namespace,$storehash,$udom,$uname) :
 9388: 
 9389: Attempts to store the items in the $storehash, but only if they don't
 9390: currently exist, if this succeeds you can be certain that you have 
 9391: successfully created a new key value pair in the $namespace db.
 9392: 
 9393: 
 9394: Args:
 9395:  $namespace: name of database to store values to
 9396:  $storehash: hashref to store to the db
 9397:  $udom: (optional) domain of user containing the db
 9398:  $uname: (optional) name of user caontaining the db
 9399: 
 9400: Returns:
 9401:  'ok' -> succeeded in storing all keys of $storehash
 9402:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9403:                         least <key> already existed in the db (other
 9404:                         requested keys may also already exist)
 9405:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9406:  'con_lost' -> unable to contact request server
 9407:  'refused' -> action was not allowed by remote machine
 9408: 
 9409: 
 9410: =item *
 9411: 
 9412: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9413: reference filled in from namesp (encrypts the return communication)
 9414: ($udom and $uname are optional)
 9415: 
 9416: =item *
 9417: 
 9418: log($udom,$name,$home,$message) : write to permanent log for user; use
 9419: critical subroutine
 9420: 
 9421: =item *
 9422: 
 9423: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9424: array reference filled in from namespace found in domain level on either
 9425: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9426: 
 9427: =item *
 9428: 
 9429: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9430: domain level either on specified domain server ($uhome) or primary domain 
 9431: server ($udom and $uhome are optional)
 9432: 
 9433: =item * 
 9434: 
 9435: get_domain_defaults($target_domain) : returns hash with defaults for
 9436: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9437: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9438: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9439: Values are retrieved from cache (if current), or from domain's configuration.db
 9440: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9441: or lonTabs/domain.tab. 
 9442: 
 9443: %domdefaults = &get_auth_defaults($target_domain);
 9444: 
 9445: =back
 9446: 
 9447: =head2 Network Status Functions
 9448: 
 9449: =over 4
 9450: 
 9451: =item *
 9452: 
 9453: dirlist($uri) : return directory list based on URI
 9454: 
 9455: =item *
 9456: 
 9457: spareserver() : find server with least workload from spare.tab
 9458: 
 9459: =back
 9460: 
 9461: =head2 Apache Request
 9462: 
 9463: =over 4
 9464: 
 9465: =item *
 9466: 
 9467: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9468: localhost, posts hash
 9469: 
 9470: =back
 9471: 
 9472: =head2 Data to String to Data
 9473: 
 9474: =over 4
 9475: 
 9476: =item *
 9477: 
 9478: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9479: and '&' separators, supports elements that are arrayrefs and hashrefs
 9480: 
 9481: =item *
 9482: 
 9483: hashref2str($hashref) : convert a hashref into a string complete with
 9484: escaping and '=' and '&' separators, supports elements that are
 9485: arrayrefs and hashrefs
 9486: 
 9487: =item *
 9488: 
 9489: arrayref2str($arrayref) : convert an arrayref into a string complete
 9490: with escaping and '&' separators, supports elements that are arrayrefs
 9491: and hashrefs
 9492: 
 9493: =item *
 9494: 
 9495: str2hash($string) : convert string to hash using unescaping and
 9496: splitting on '=' and '&', supports elements that are arrayrefs and
 9497: hashrefs
 9498: 
 9499: =item *
 9500: 
 9501: str2array($string) : convert string to hash using unescaping and
 9502: splitting on '&', supports elements that are arrayrefs and hashrefs
 9503: 
 9504: =back
 9505: 
 9506: =head2 Logging Routines
 9507: 
 9508: =over 4
 9509: 
 9510: These routines allow one to make log messages in the lonnet.log and
 9511: lonnet.perm logfiles.
 9512: 
 9513: =item *
 9514: 
 9515: logtouch() : make sure the logfile, lonnet.log, exists
 9516: 
 9517: =item *
 9518: 
 9519: logthis() : append message to the normal lonnet.log file, it gets
 9520: preiodically rolled over and deleted.
 9521: 
 9522: =item *
 9523: 
 9524: logperm() : append a permanent message to lonnet.perm.log, this log
 9525: file never gets deleted by any automated portion of the system, only
 9526: messages of critical importance should go in here.
 9527: 
 9528: =back
 9529: 
 9530: =head2 General File Helper Routines
 9531: 
 9532: =over 4
 9533: 
 9534: =item *
 9535: 
 9536: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9537: (a) files in /uploaded
 9538:   (i) If a local copy of the file exists - 
 9539:       compares modification date of local copy with last-modified date for 
 9540:       definitive version stored on home server for course. If local copy is 
 9541:       stale, requests a new version from the home server and stores it. 
 9542:       If the original has been removed from the home server, then local copy 
 9543:       is unlinked.
 9544:   (ii) If local copy does not exist -
 9545:       requests the file from the home server and stores it. 
 9546:   
 9547:   If $caller is 'uploadrep':  
 9548:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9549:     for request for files originally uploaded via DOCS. 
 9550:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9551:   
 9552:   Otherwise:
 9553:      This indicates a call from the content generation phase of the request.
 9554:      -  returns the entire contents of the file or -1.
 9555:      
 9556: (b) files in /res
 9557:    - returns the entire contents of a file or -1; 
 9558:    it properly subscribes to and replicates the file if neccessary.
 9559: 
 9560: 
 9561: =item *
 9562: 
 9563: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9564:                   reference
 9565: 
 9566: returns either a stat() list of data about the file or an empty list
 9567: if the file doesn't exist or couldn't find out about it (connection
 9568: problems or user unknown)
 9569: 
 9570: =item *
 9571: 
 9572: filelocation($dir,$file) : returns file system location of a file
 9573: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9574: directory that relative $file lookups are to looked in ($dir of /a/dir
 9575: and a file of ../bob will become /a/bob)
 9576: 
 9577: =item *
 9578: 
 9579: hreflocation($dir,$file) : returns file system location or a URL; same as
 9580: filelocation except for hrefs
 9581: 
 9582: =item *
 9583: 
 9584: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9585: 
 9586: =back
 9587: 
 9588: =head2 Usererfile file routines (/uploaded*)
 9589: 
 9590: =over 4
 9591: 
 9592: =item *
 9593: 
 9594: userfileupload(): main rotine for putting a file in a user or course's
 9595:                   filespace, arguments are,
 9596: 
 9597:  formname - required - this is the name of the element in $env where the
 9598:            filename, and the contents of the file to create/modifed exist
 9599:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9600:            contents of the file is located in $env{'form.'.$formname}
 9601:  coursedoc - if true, store the file in the course of the active role
 9602:              of the current user
 9603:  subdir - required - subdirectory to put the file in under ../userfiles/
 9604:          if undefined, it will be placed in "unknown"
 9605: 
 9606:  (This routine calls clean_filename() to remove any dangerous
 9607:  characters from the filename, and then calls finuserfileupload() to
 9608:  complete the transaction)
 9609: 
 9610:  returns either the url of the uploaded file (/uploaded/....) if successful
 9611:  and /adm/notfound.html if unsuccessful
 9612: 
 9613: =item *
 9614: 
 9615: clean_filename(): routine for cleaing a filename up for storage in
 9616:                  userfile space, argument is:
 9617: 
 9618:  filename - proposed filename
 9619: 
 9620: returns: the new clean filename
 9621: 
 9622: =item *
 9623: 
 9624: finishuserfileupload(): routine that creaes and sends the file to
 9625: userspace, probably shouldn't be called directly
 9626: 
 9627:   docuname: username or courseid of destination for the file
 9628:   docudom: domain of user/course of destination for the file
 9629:   formname: same as for userfileupload()
 9630:   fname: filename (inculding subdirectories) for the file
 9631: 
 9632:  returns either the url of the uploaded file (/uploaded/....) if successful
 9633:  and /adm/notfound.html if unsuccessful
 9634: 
 9635: =item *
 9636: 
 9637: renameuserfile(): renames an existing userfile to a new name
 9638: 
 9639:   Args:
 9640:    docuname: username or courseid of destination for the file
 9641:    docudom: domain of user/course of destination for the file
 9642:    old: current file name (including any subdirs under userfiles)
 9643:    new: desired file name (including any subdirs under userfiles)
 9644: 
 9645: =item *
 9646: 
 9647: mkdiruserfile(): creates a directory is a userfiles dir
 9648: 
 9649:   Args:
 9650:    docuname: username or courseid of destination for the file
 9651:    docudom: domain of user/course of destination for the file
 9652:    dir: dir to create (including any subdirs under userfiles)
 9653: 
 9654: =item *
 9655: 
 9656: removeuserfile(): removes a file that exists in userfiles
 9657: 
 9658:   Args:
 9659:    docuname: username or courseid of destination for the file
 9660:    docudom: domain of user/course of destination for the file
 9661:    fname: filname to delete (including any subdirs under userfiles)
 9662: 
 9663: =item *
 9664: 
 9665: removeuploadedurl(): convience function for removeuserfile()
 9666: 
 9667:   Args:
 9668:    url:  a full /uploaded/... url to delete
 9669: 
 9670: =item * 
 9671: 
 9672: get_portfile_permissions():
 9673:   Args:
 9674:     domain: domain of user or course contain the portfolio files
 9675:     user: name of user or num of course contain the portfolio files
 9676:   Returns:
 9677:     hashref of a dump of the proper file_permissions.db
 9678:    
 9679: 
 9680: =item * 
 9681: 
 9682: get_access_controls():
 9683: 
 9684: Args:
 9685:   current_permissions: the hash ref returned from get_portfile_permissions()
 9686:   group: (optional) the group you want the files associated with
 9687:   file: (optional) the file you want access info on
 9688: 
 9689: Returns:
 9690:     a hash (keys are file names) of hashes containing
 9691:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9692:         values are XML containing access control settings (see below) 
 9693: 
 9694: Internal notes:
 9695: 
 9696:  access controls are stored in file_permissions.db as key=value pairs.
 9697:     key -> path to file/file_name\0uniqueID:scope_end_start
 9698:         where scope -> public,guest,course,group,domains or users.
 9699:               end -> UNIX time for end of access (0 -> no end date)
 9700:               start -> UNIX time for start of access
 9701: 
 9702:     value -> XML description of access control
 9703:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9704:             <start></start>
 9705:             <end></end>
 9706: 
 9707:             <password></password>  for scope type = guest
 9708: 
 9709:             <domain></domain>     for scope type = course or group
 9710:             <number></number>
 9711:             <roles id="">
 9712:              <role></role>
 9713:              <access></access>
 9714:              <section></section>
 9715:              <group></group>
 9716:             </roles>
 9717: 
 9718:             <dom></dom>         for scope type = domains
 9719: 
 9720:             <users>             for scope type = users
 9721:              <user>
 9722:               <uname></uname>
 9723:               <udom></udom>
 9724:              </user>
 9725:             </users>
 9726:            </scope> 
 9727:               
 9728:  Access data is also aggregated for each file in an additional key=value pair:
 9729:  key -> path to file/file_name\0accesscontrol 
 9730:  value -> reference to hash
 9731:           hash contains key = value pairs
 9732:           where key = uniqueID:scope_end_start
 9733:                 value = UNIX time record was last updated
 9734: 
 9735:           Used to improve speed of look-ups of access controls for each file.  
 9736:  
 9737:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9738: 
 9739: modify_access_controls():
 9740: 
 9741: Modifies access controls for a portfolio file
 9742: Args
 9743: 1. file name
 9744: 2. reference to hash of required changes,
 9745: 3. domain
 9746: 4. username
 9747:   where domain,username are the domain of the portfolio owner 
 9748:   (either a user or a course) 
 9749: 
 9750: Returns:
 9751: 1. result of additions or updates ('ok' or 'error', with error message). 
 9752: 2. result of deletions ('ok' or 'error', with error message).
 9753: 3. reference to hash of any new or updated access controls.
 9754: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9755:    key = integer (inbound ID)
 9756:    value = uniqueID  
 9757: 
 9758: =back
 9759: 
 9760: =head2 HTTP Helper Routines
 9761: 
 9762: =over 4
 9763: 
 9764: =item *
 9765: 
 9766: escape() : unpack non-word characters into CGI-compatible hex codes
 9767: 
 9768: =item *
 9769: 
 9770: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9771: 
 9772: =back
 9773: 
 9774: =head1 PRIVATE SUBROUTINES
 9775: 
 9776: =head2 Underlying communication routines (Shouldn't call)
 9777: 
 9778: =over 4
 9779: 
 9780: =item *
 9781: 
 9782: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9783: 
 9784: =item *
 9785: 
 9786: reply() : uses subreply to send a message to remote machine, logs all failures
 9787: 
 9788: =item *
 9789: 
 9790: critical() : passes a critical message to another server; if cannot
 9791: get through then place message in connection buffer directory and
 9792: returns con_delayed, if incapable of saving message, returns
 9793: con_failed
 9794: 
 9795: =item *
 9796: 
 9797: reconlonc() : tries to reconnect lonc client processes.
 9798: 
 9799: =back
 9800: 
 9801: =head2 Resource Access Logging
 9802: 
 9803: =over 4
 9804: 
 9805: =item *
 9806: 
 9807: flushcourselogs() : flush (save) buffer logs and access logs
 9808: 
 9809: =item *
 9810: 
 9811: courselog($what) : save message for course in hash
 9812: 
 9813: =item *
 9814: 
 9815: courseacclog($what) : save message for course using &courselog().  Perform
 9816: special processing for specific resource types (problems, exams, quizzes, etc).
 9817: 
 9818: =item *
 9819: 
 9820: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9821: as a PerlChildExitHandler
 9822: 
 9823: =back
 9824: 
 9825: =head2 Other
 9826: 
 9827: =over 4
 9828: 
 9829: =item *
 9830: 
 9831: symblist($mapname,%newhash) : update symbolic storage links
 9832: 
 9833: =back
 9834: 
 9835: =cut
 9836: 

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