File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.941: download - view: text, annotated - select for diffs
Sun Feb 3 05:08:05 2008 UTC (16 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_6_X, version_2_6_2, HEAD
bug 5608.  CSTR icon/button/link in Main Menu for Assistant Co-author.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.941 2008/02/03 05:08:05 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=@_;
  452:     foreach my $key (keys(%newenv)) {
  453: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  454:             &logthis("<font color=\"blue\">WARNING: ".
  455:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  456:                 .'</font>');
  457: 	    delete($newenv{$key});
  458:         } else {
  459:             $env{$key}=$newenv{$key};
  460:         }
  461:     }
  462:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  463:     if ($opened
  464: 	&& &timed_flock($env_file,LOCK_EX)
  465: 	&&
  466: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  467: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  468: 	while (my ($key,$value) = each(%newenv)) {
  469: 	    $disk_env{$key} = $value;
  470: 	}
  471: 	untie(%disk_env);
  472:     }
  473:     return 'ok';
  474: }
  475: # ----------------------------------------------------- Delete from Environment
  476: 
  477: sub delenv {
  478:     my $delthis=shift;
  479:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  480:         &logthis("<font color=\"blue\">WARNING: ".
  481:                 "Attempt to delete from environment ".$delthis);
  482:         return 'error';
  483:     }
  484:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  485:     if ($opened
  486: 	&& &timed_flock($env_file,LOCK_EX)
  487: 	&&
  488: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  489: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  490: 	foreach my $key (keys(%disk_env)) {
  491: 	    if ($key=~/^$delthis/) { 
  492: 		delete($env{$key});
  493: 		delete($disk_env{$key});
  494: 	    }
  495: 	}
  496: 	untie(%disk_env);
  497:     }
  498:     return 'ok';
  499: }
  500: 
  501: sub get_env_multiple {
  502:     my ($name) = @_;
  503:     my @values;
  504:     if (defined($env{$name})) {
  505:         # exists is it an array
  506:         if (ref($env{$name})) {
  507:             @values=@{ $env{$name} };
  508:         } else {
  509:             $values[0]=$env{$name};
  510:         }
  511:     }
  512:     return(@values);
  513: }
  514: 
  515: # ------------------------------------------ Find out current server userload
  516: sub userload {
  517:     my $numusers=0;
  518:     {
  519: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  520: 	my $filename;
  521: 	my $curtime=time;
  522: 	while ($filename=readdir(LONIDS)) {
  523: 	    next if ($filename eq '.' || $filename eq '..');
  524: 	    next if ($filename =~ /publicuser_\d+\.id/);
  525: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  526: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  527: 	}
  528: 	closedir(LONIDS);
  529:     }
  530:     my $userloadpercent=0;
  531:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  532:     if ($maxuserload) {
  533: 	$userloadpercent=100*$numusers/$maxuserload;
  534:     }
  535:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  536:     return $userloadpercent;
  537: }
  538: 
  539: # ------------------------------------------ Fight off request when overloaded
  540: 
  541: sub overloaderror {
  542:     my ($r,$checkserver)=@_;
  543:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  544:     my $loadavg;
  545:     if ($checkserver eq $perlvar{'lonHostID'}) {
  546:        open(my $loadfile,'/proc/loadavg');
  547:        $loadavg=<$loadfile>;
  548:        $loadavg =~ s/\s.*//g;
  549:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  550:        close($loadfile);
  551:     } else {
  552:        $loadavg=&reply('load',$checkserver);
  553:     }
  554:     my $overload=$loadavg-100;
  555:     if ($overload>0) {
  556: 	$r->err_headers_out->{'Retry-After'}=$overload;
  557:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  558:         return 413;
  559:     }    
  560:     return '';
  561: }
  562: 
  563: # ------------------------------ Find server with least workload from spare.tab
  564: 
  565: sub spareserver {
  566:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  567:     my $spare_server;
  568:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  569:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  570:                                                      :  $userloadpercent;
  571:     
  572:     foreach my $try_server (@{ $spareid{'primary'} }) {
  573: 	($spare_server, $lowest_load) =
  574: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  575:     }
  576: 
  577:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  578: 
  579:     if (!$found_server) {
  580: 	foreach my $try_server (@{ $spareid{'default'} }) {
  581: 	    ($spare_server, $lowest_load) =
  582: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  583: 	}
  584:     }
  585: 
  586:     if (!$want_server_name) {
  587: 	$spare_server="http://".&hostname($spare_server);
  588:     }
  589:     return $spare_server;
  590: }
  591: 
  592: sub compare_server_load {
  593:     my ($try_server, $spare_server, $lowest_load) = @_;
  594: 
  595:     my $loadans     = &reply('load',    $try_server);
  596:     my $userloadans = &reply('userload',$try_server);
  597: 
  598:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  599: 	next; #didn't get a number from the server
  600:     }
  601: 
  602:     my $load;
  603:     if ($loadans =~ /\d/) {
  604: 	if ($userloadans =~ /\d/) {
  605: 	    #both are numbers, pick the bigger one
  606: 	    $load = ($loadans > $userloadans) ? $loadans 
  607: 		                              : $userloadans;
  608: 	} else {
  609: 	    $load = $loadans;
  610: 	}
  611:     } else {
  612: 	$load = $userloadans;
  613:     }
  614: 
  615:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  616: 	$spare_server = $try_server;
  617: 	$lowest_load  = $load;
  618:     }
  619:     return ($spare_server,$lowest_load);
  620: }
  621: 
  622: # --------------------------- ask offload servers if user already has a session
  623: sub find_existing_session {
  624:     my ($udom,$uname) = @_;
  625:     foreach my $try_server (@{ $spareid{'primary'} },
  626: 			    @{ $spareid{'default'} }) {
  627: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  628:     }
  629:     return;
  630: }
  631: 
  632: # -------------------------------- ask if server already has a session for user
  633: sub has_user_session {
  634:     my ($lonid,$udom,$uname) = @_;
  635:     my $result = &reply(join(':','userhassession',
  636: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  637:     return 1 if ($result eq 'ok');
  638: 
  639:     return 0;
  640: }
  641: 
  642: # --------------------------------------------- Try to change a user's password
  643: 
  644: sub changepass {
  645:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  646:     $currentpass = &escape($currentpass);
  647:     $newpass     = &escape($newpass);
  648:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  649: 		       $server);
  650:     if (! $answer) {
  651: 	&logthis("No reply on password change request to $server ".
  652: 		 "by $uname in domain $udom.");
  653:     } elsif ($answer =~ "^ok") {
  654:         &logthis("$uname in $udom successfully changed their password ".
  655: 		 "on $server.");
  656:     } elsif ($answer =~ "^pwchange_failure") {
  657: 	&logthis("$uname in $udom was unable to change their password ".
  658: 		 "on $server.  The action was blocked by either lcpasswd ".
  659: 		 "or pwchange");
  660:     } elsif ($answer =~ "^non_authorized") {
  661:         &logthis("$uname in $udom did not get their password correct when ".
  662: 		 "attempting to change it on $server.");
  663:     } elsif ($answer =~ "^auth_mode_error") {
  664:         &logthis("$uname in $udom attempted to change their password despite ".
  665: 		 "not being locally or internally authenticated on $server.");
  666:     } elsif ($answer =~ "^unknown_user") {
  667:         &logthis("$uname in $udom attempted to change their password ".
  668: 		 "on $server but were unable to because $server is not ".
  669: 		 "their home server.");
  670:     } elsif ($answer =~ "^refused") {
  671: 	&logthis("$server refused to change $uname in $udom password because ".
  672: 		 "it was sent an unencrypted request to change the password.");
  673:     }
  674:     return $answer;
  675: }
  676: 
  677: # ----------------------- Try to determine user's current authentication scheme
  678: 
  679: sub queryauthenticate {
  680:     my ($uname,$udom)=@_;
  681:     my $uhome=&homeserver($uname,$udom);
  682:     if (!$uhome) {
  683: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  684: 	return 'no_host';
  685:     }
  686:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  687:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  688: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  689:     }
  690:     return $answer;
  691: }
  692: 
  693: # --------- Try to authenticate user from domain's lib servers (first this one)
  694: 
  695: sub authenticate {
  696:     my ($uname,$upass,$udom)=@_;
  697:     $upass=&escape($upass);
  698:     $uname= &LONCAPA::clean_username($uname);
  699:     my $uhome=&homeserver($uname,$udom,1);
  700:     if ((!$uhome) || ($uhome eq 'no_host')) {
  701: # Maybe the machine was offline and only re-appeared again recently?
  702:         &reconlonc();
  703: # One more
  704: 	my $uhome=&homeserver($uname,$udom,1);
  705: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  706: 	    &logthis("User $uname at $udom is unknown in authenticate");
  707: 	}
  708: 	return 'no_host';
  709:     }
  710:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  711:     if ($answer eq 'authorized') {
  712: 	&logthis("User $uname at $udom authorized by $uhome"); 
  713: 	return $uhome; 
  714:     }
  715:     if ($answer eq 'non_authorized') {
  716: 	&logthis("User $uname at $udom rejected by $uhome");
  717: 	return 'no_host'; 
  718:     }
  719:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  720:     return 'no_host';
  721: }
  722: 
  723: # ---------------------- Find the homebase for a user from domain's lib servers
  724: 
  725: my %homecache;
  726: sub homeserver {
  727:     my ($uname,$udom,$ignoreBadCache)=@_;
  728:     my $index="$uname:$udom";
  729: 
  730:     if (exists($homecache{$index})) { return $homecache{$index}; }
  731: 
  732:     my %servers = &get_servers($udom,'library');
  733:     foreach my $tryserver (keys(%servers)) {
  734:         next if ($ignoreBadCache ne 'true' && 
  735: 		 exists($badServerCache{$tryserver}));
  736: 
  737: 	my $answer=reply("home:$udom:$uname",$tryserver);
  738: 	if ($answer eq 'found') {
  739: 	    delete($badServerCache{$tryserver}); 
  740: 	    return $homecache{$index}=$tryserver;
  741: 	} elsif ($answer eq 'no_host') {
  742: 	    $badServerCache{$tryserver}=1;
  743: 	}
  744:     }    
  745:     return 'no_host';
  746: }
  747: 
  748: # ------------------------------------- Find the usernames behind a list of IDs
  749: 
  750: sub idget {
  751:     my ($udom,@ids)=@_;
  752:     my %returnhash=();
  753:     
  754:     my %servers = &get_servers($udom,'library');
  755:     foreach my $tryserver (keys(%servers)) {
  756: 	my $idlist=join('&',@ids);
  757: 	$idlist=~tr/A-Z/a-z/; 
  758: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  759: 	my @answer=();
  760: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  761: 	    @answer=split(/\&/,$reply);
  762: 	}                    ;
  763: 	my $i;
  764: 	for ($i=0;$i<=$#ids;$i++) {
  765: 	    if ($answer[$i]) {
  766: 		$returnhash{$ids[$i]}=$answer[$i];
  767: 	    } 
  768: 	}
  769:     } 
  770:     return %returnhash;
  771: }
  772: 
  773: # ------------------------------------- Find the IDs behind a list of usernames
  774: 
  775: sub idrget {
  776:     my ($udom,@unames)=@_;
  777:     my %returnhash=();
  778:     foreach my $uname (@unames) {
  779:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  780:     }
  781:     return %returnhash;
  782: }
  783: 
  784: # ------------------------------- Store away a list of names and associated IDs
  785: 
  786: sub idput {
  787:     my ($udom,%ids)=@_;
  788:     my %servers=();
  789:     foreach my $uname (keys(%ids)) {
  790: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  791:         my $uhom=&homeserver($uname,$udom);
  792:         if ($uhom ne 'no_host') {
  793:             my $id=&escape($ids{$uname});
  794:             $id=~tr/A-Z/a-z/;
  795:             my $esc_unam=&escape($uname);
  796: 	    if ($servers{$uhom}) {
  797: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  798:             } else {
  799:                 $servers{$uhom}=$id.'='.$esc_unam;
  800:             }
  801:         }
  802:     }
  803:     foreach my $server (keys(%servers)) {
  804:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  805:     }
  806: }
  807: 
  808: # ------------------------------------------- get items from domain db files   
  809: 
  810: sub get_dom {
  811:     my ($namespace,$storearr,$udom,$uhome)=@_;
  812:     my $items='';
  813:     foreach my $item (@$storearr) {
  814:         $items.=&escape($item).'&';
  815:     }
  816:     $items=~s/\&$//;
  817:     if (!$udom) {
  818:         $udom=$env{'user.domain'};
  819:         if (defined(&domain($udom,'primary'))) {
  820:             $uhome=&domain($udom,'primary');
  821:         } else {
  822:             undef($uhome);
  823:         }
  824:     } else {
  825:         if (!$uhome) {
  826:             if (defined(&domain($udom,'primary'))) {
  827:                 $uhome=&domain($udom,'primary');
  828:             }
  829:         }
  830:     }
  831:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  832:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  833:         my %returnhash;
  834:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  835:             return %returnhash;
  836:         }
  837:         my @pairs=split(/\&/,$rep);
  838:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  839:             return @pairs;
  840:         }
  841:         my $i=0;
  842:         foreach my $item (@$storearr) {
  843:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  844:             $i++;
  845:         }
  846:         return %returnhash;
  847:     } else {
  848:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  849:     }
  850: }
  851: 
  852: # -------------------------------------------- put items in domain db files 
  853: 
  854: sub put_dom {
  855:     my ($namespace,$storehash,$udom,$uhome)=@_;
  856:     if (!$udom) {
  857:         $udom=$env{'user.domain'};
  858:         if (defined(&domain($udom,'primary'))) {
  859:             $uhome=&domain($udom,'primary');
  860:         } else {
  861:             undef($uhome);
  862:         }
  863:     } else {
  864:         if (!$uhome) {
  865:             if (defined(&domain($udom,'primary'))) {
  866:                 $uhome=&domain($udom,'primary');
  867:             }
  868:         }
  869:     } 
  870:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  871:         my $items='';
  872:         foreach my $item (keys(%$storehash)) {
  873:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  874:         }
  875:         $items=~s/\&$//;
  876:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  877:     } else {
  878:         &logthis("put_dom failed - no homeserver and/or domain");
  879:     }
  880: }
  881: 
  882: sub retrieve_inst_usertypes {
  883:     my ($udom) = @_;
  884:     my (%returnhash,@order);
  885:     if (defined(&domain($udom,'primary'))) {
  886:         my $uhome=&domain($udom,'primary');
  887:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  888:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  889:         my @pairs=split(/\&/,$hashitems);
  890:         foreach my $item (@pairs) {
  891:             my ($key,$value)=split(/=/,$item,2);
  892:             $key = &unescape($key);
  893:             next if ($key =~ /^error: 2 /);
  894:             $returnhash{$key}=&thaw_unescape($value);
  895:         }
  896:         my @esc_order = split(/\&/,$orderitems);
  897:         foreach my $item (@esc_order) {
  898:             push(@order,&unescape($item));
  899:         }
  900:     } else {
  901:         &logthis("get_dom failed - no primary domain server for $udom");
  902:     }
  903:     return (\%returnhash,\@order);
  904: }
  905: 
  906: sub is_domainimage {
  907:     my ($url) = @_;
  908:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  909:         if (&domain($1) ne '') {
  910:             return '1';
  911:         }
  912:     }
  913:     return;
  914: }
  915: 
  916: sub inst_directory_query {
  917:     my ($srch) = @_;
  918:     my $udom = $srch->{'srchdomain'};
  919:     my %results;
  920:     my $homeserver = &domain($udom,'primary');
  921:     my $outcome;
  922:     if ($homeserver ne '') {
  923: 	my $queryid=&reply("querysend:instdirsearch:".
  924: 			   &escape($srch->{'srchby'}).':'.
  925: 			   &escape($srch->{'srchterm'}).':'.
  926: 			   &escape($srch->{'srchtype'}),$homeserver);
  927: 	my $host=&hostname($homeserver);
  928: 	if ($queryid !~/^\Q$host\E\_/) {
  929: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  930: 	    return;
  931: 	}
  932: 	my $response = &get_query_reply($queryid);
  933: 	my $maxtries = 5;
  934: 	my $tries = 1;
  935: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  936: 	    $response = &get_query_reply($queryid);
  937: 	    $tries ++;
  938: 	}
  939: 
  940:         if (!&error($response) && $response ne 'refused') {
  941:             if ($response eq 'unavailable') {
  942:                 $outcome = $response;
  943:             } else {
  944:                 $outcome = 'ok';
  945:                 my @matches = split(/\n/,$response);
  946:                 foreach my $match (@matches) {
  947:                     my ($key,$value) = split(/=/,$match);
  948:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  949:                 }
  950:             }
  951:         }
  952:     }
  953:     return ($outcome,%results);
  954: }
  955: 
  956: sub usersearch {
  957:     my ($srch) = @_;
  958:     my $dom = $srch->{'srchdomain'};
  959:     my %results;
  960:     my %libserv = &all_library();
  961:     my $query = 'usersearch';
  962:     foreach my $tryserver (keys(%libserv)) {
  963:         if (&host_domain($tryserver) eq $dom) {
  964:             my $host=&hostname($tryserver);
  965:             my $queryid=
  966:                 &reply("querysend:".&escape($query).':'.
  967:                        &escape($srch->{'srchby'}).':'.
  968:                        &escape($srch->{'srchtype'}).':'.
  969:                        &escape($srch->{'srchterm'}),$tryserver);
  970:             if ($queryid !~/^\Q$host\E\_/) {
  971:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  972:                 next;
  973:             }
  974:             my $reply = &get_query_reply($queryid);
  975:             my $maxtries = 1;
  976:             my $tries = 1;
  977:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
  978:                 $reply = &get_query_reply($queryid);
  979:                 $tries ++;
  980:             }
  981:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
  982:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
  983:             } else {
  984:                 my @matches;
  985:                 if ($reply =~ /\n/) {
  986:                     @matches = split(/\n/,$reply);
  987:                 } else {
  988:                     @matches = split(/\&/,$reply);
  989:                 }
  990:                 foreach my $match (@matches) {
  991:                     my ($uname,$udom,%userhash);
  992:                     foreach my $entry (split(/:/,$match)) {
  993:                         my ($key,$value) =
  994:                             map {&unescape($_);} split(/=/,$entry);
  995:                         $userhash{$key} = $value;
  996:                         if ($key eq 'username') {
  997:                             $uname = $value;
  998:                         } elsif ($key eq 'domain') {
  999:                             $udom = $value;
 1000:                         }
 1001:                     }
 1002:                     $results{$uname.':'.$udom} = \%userhash;
 1003:                 }
 1004:             }
 1005:         }
 1006:     }
 1007:     return %results;
 1008: }
 1009: 
 1010: sub get_instuser {
 1011:     my ($udom,$uname,$id) = @_;
 1012:     my $homeserver = &domain($udom,'primary');
 1013:     my ($outcome,%results);
 1014:     if ($homeserver ne '') {
 1015:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1016:                            &escape($id).':'.&escape($udom),$homeserver);
 1017:         my $host=&hostname($homeserver);
 1018:         if ($queryid !~/^\Q$host\E\_/) {
 1019:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1020:             return;
 1021:         }
 1022:         my $response = &get_query_reply($queryid);
 1023:         my $maxtries = 5;
 1024:         my $tries = 1;
 1025:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1026:             $response = &get_query_reply($queryid);
 1027:             $tries ++;
 1028:         }
 1029:         if (!&error($response) && $response ne 'refused') {
 1030:             if ($response eq 'unavailable') {
 1031:                 $outcome = $response;
 1032:             } else {
 1033:                 $outcome = 'ok';
 1034:                 my @matches = split(/\n/,$response);
 1035:                 foreach my $match (@matches) {
 1036:                     my ($key,$value) = split(/=/,$match);
 1037:                     $results{&unescape($key)} = &thaw_unescape($value);
 1038:                 }
 1039:             }
 1040:         }
 1041:     }
 1042:     my %userinfo;
 1043:     if (ref($results{$uname}) eq 'HASH') {
 1044:         %userinfo = %{$results{$uname}};
 1045:     } 
 1046:     return ($outcome,%userinfo);
 1047: }
 1048: 
 1049: sub inst_rulecheck {
 1050:     my ($udom,$uname,$id,$item,$rules) = @_;
 1051:     my %returnhash;
 1052:     if ($udom ne '') {
 1053:         if (ref($rules) eq 'ARRAY') {
 1054:             @{$rules} = map {&escape($_);} (@{$rules});
 1055:             my $rulestr = join(':',@{$rules});
 1056:             my $homeserver=&domain($udom,'primary');
 1057:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1058:                 my $response;
 1059:                 if ($item eq 'username') {                
 1060:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1061:                                               ':'.&escape($uname).':'.$rulestr,
 1062:                                               $homeserver));
 1063:                 } elsif ($item eq 'id') {
 1064:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1065:                                               ':'.&escape($id).':'.$rulestr,
 1066:                                               $homeserver));
 1067:                 }
 1068:                 if ($response ne 'refused') {
 1069:                     my @pairs=split(/\&/,$response);
 1070:                     foreach my $item (@pairs) {
 1071:                         my ($key,$value)=split(/=/,$item,2);
 1072:                         $key = &unescape($key);
 1073:                         next if ($key =~ /^error: 2 /);
 1074:                         $returnhash{$key}=&thaw_unescape($value);
 1075:                     }
 1076:                 }
 1077:             }
 1078:         }
 1079:     }
 1080:     return %returnhash;
 1081: }
 1082: 
 1083: sub inst_userrules {
 1084:     my ($udom,$check) = @_;
 1085:     my (%ruleshash,@ruleorder);
 1086:     if ($udom ne '') {
 1087:         my $homeserver=&domain($udom,'primary');
 1088:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1089:             my $response;
 1090:             if ($check eq 'id') {
 1091:                 $response=&reply('instidrules:'.&escape($udom),
 1092:                                  $homeserver);
 1093:             } else {
 1094:                 $response=&reply('instuserrules:'.&escape($udom),
 1095:                                  $homeserver);
 1096:             }
 1097:             if (($response ne 'refused') && ($response ne 'error') && 
 1098:                 ($response ne 'unknown_cmd') && 
 1099:                 ($response ne 'no_such_host')) {
 1100:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1101:                 my @pairs=split(/\&/,$hashitems);
 1102:                 foreach my $item (@pairs) {
 1103:                     my ($key,$value)=split(/=/,$item,2);
 1104:                     $key = &unescape($key);
 1105:                     next if ($key =~ /^error: 2 /);
 1106:                     $ruleshash{$key}=&thaw_unescape($value);
 1107:                 }
 1108:                 my @esc_order = split(/\&/,$orderitems);
 1109:                 foreach my $item (@esc_order) {
 1110:                     push(@ruleorder,&unescape($item));
 1111:                 }
 1112:             }
 1113:         }
 1114:     }
 1115:     return (\%ruleshash,\@ruleorder);
 1116: }
 1117: 
 1118: # --------------------------------------------------- Assign a key to a student
 1119: 
 1120: sub assign_access_key {
 1121: #
 1122: # a valid key looks like uname:udom#comments
 1123: # comments are being appended
 1124: #
 1125:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1126:     $kdom=
 1127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1128:     $knum=
 1129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1130:     $cdom=
 1131:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1132:     $cnum=
 1133:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1134:     $udom=$env{'user.name'} unless (defined($udom));
 1135:     $uname=$env{'user.domain'} unless (defined($uname));
 1136:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1137:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1138:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1139:                                                   # assigned to this person
 1140:                                                   # - this should not happen,
 1141:                                                   # unless something went wrong
 1142:                                                   # the first time around
 1143: # ready to assign
 1144:         $logentry=$1.'; '.$logentry;
 1145:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1146:                                                  $kdom,$knum) eq 'ok') {
 1147: # key now belongs to user
 1148: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1149:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1150:                 &appenv('environment.'.$envkey => $ckey);
 1151:                 return 'ok';
 1152:             } else {
 1153:                 return 
 1154:   'error: Count not permanently assign key, will need to be re-entered later.';
 1155: 	    }
 1156:         } else {
 1157:             return 'error: Could not assign key, try again later.';
 1158:         }
 1159:     } elsif (!$existing{$ckey}) {
 1160: # the key does not exist
 1161: 	return 'error: The key does not exist';
 1162:     } else {
 1163: # the key is somebody else's
 1164: 	return 'error: The key is already in use';
 1165:     }
 1166: }
 1167: 
 1168: # ------------------------------------------ put an additional comment on a key
 1169: 
 1170: sub comment_access_key {
 1171: #
 1172: # a valid key looks like uname:udom#comments
 1173: # comments are being appended
 1174: #
 1175:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1176:     $cdom=
 1177:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1178:     $cnum=
 1179:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1180:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1181:     if ($existing{$ckey}) {
 1182:         $existing{$ckey}.='; '.$logentry;
 1183: # ready to assign
 1184:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1185:                                                  $cdom,$cnum) eq 'ok') {
 1186: 	    return 'ok';
 1187:         } else {
 1188: 	    return 'error: Count not store comment.';
 1189:         }
 1190:     } else {
 1191: # the key does not exist
 1192: 	return 'error: The key does not exist';
 1193:     }
 1194: }
 1195: 
 1196: # ------------------------------------------------------ Generate a set of keys
 1197: 
 1198: sub generate_access_keys {
 1199:     my ($number,$cdom,$cnum,$logentry)=@_;
 1200:     $cdom=
 1201:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1202:     $cnum=
 1203:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1204:     unless (&allowed('mky',$cdom)) { return 0; }
 1205:     unless (($cdom) && ($cnum)) { return 0; }
 1206:     if ($number>10000) { return 0; }
 1207:     sleep(2); # make sure don't get same seed twice
 1208:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1209:     my $total=0;
 1210:     for (my $i=1;$i<=$number;$i++) {
 1211:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1212:                   sprintf("%lx",int(100000*rand)).'-'.
 1213:                   sprintf("%lx",int(100000*rand));
 1214:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1215:        $newkey=~s/0/h/g; # and also 0 and O
 1216:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1217:        if ($existing{$newkey}) {
 1218:            $i--;
 1219:        } else {
 1220: 	  if (&put('accesskeys',
 1221:               { $newkey => '# generated '.localtime().
 1222:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1223:                            '; '.$logentry },
 1224: 		   $cdom,$cnum) eq 'ok') {
 1225:               $total++;
 1226: 	  }
 1227:        }
 1228:     }
 1229:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1230:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1231:     return $total;
 1232: }
 1233: 
 1234: # ------------------------------------------------------- Validate an accesskey
 1235: 
 1236: sub validate_access_key {
 1237:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1238:     $cdom=
 1239:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1240:     $cnum=
 1241:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1242:     $udom=$env{'user.domain'} unless (defined($udom));
 1243:     $uname=$env{'user.name'} unless (defined($uname));
 1244:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1245:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1246: }
 1247: 
 1248: # ------------------------------------- Find the section of student in a course
 1249: sub devalidate_getsection_cache {
 1250:     my ($udom,$unam,$courseid)=@_;
 1251:     my $hashid="$udom:$unam:$courseid";
 1252:     &devalidate_cache_new('getsection',$hashid);
 1253: }
 1254: 
 1255: sub courseid_to_courseurl {
 1256:     my ($courseid) = @_;
 1257:     #already url style courseid
 1258:     return $courseid if ($courseid =~ m{^/});
 1259: 
 1260:     if (exists($env{'course.'.$courseid.'.num'})) {
 1261: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1262: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1263: 	return "/$cdom/$cnum";
 1264:     }
 1265: 
 1266:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1267:     if (exists($courseinfo{'num'})) {
 1268: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1269:     }
 1270: 
 1271:     return undef;
 1272: }
 1273: 
 1274: sub getsection {
 1275:     my ($udom,$unam,$courseid)=@_;
 1276:     my $cachetime=1800;
 1277: 
 1278:     my $hashid="$udom:$unam:$courseid";
 1279:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1280:     if (defined($cached)) { return $result; }
 1281: 
 1282:     my %Pending; 
 1283:     my %Expired;
 1284:     #
 1285:     # Each role can either have not started yet (pending), be active, 
 1286:     #    or have expired.
 1287:     #
 1288:     # If there is an active role, we are done.
 1289:     #
 1290:     # If there is more than one role which has not started yet, 
 1291:     #     choose the one which will start sooner
 1292:     # If there is one role which has not started yet, return it.
 1293:     #
 1294:     # If there is more than one expired role, choose the one which ended last.
 1295:     # If there is a role which has expired, return it.
 1296:     #
 1297:     $courseid = &courseid_to_courseurl($courseid);
 1298:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1299:     foreach my $key (keys(%roleshash)) {
 1300:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1301:         my $section=$1;
 1302:         if ($key eq $courseid.'_st') { $section=''; }
 1303:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1304:         my $now=time;
 1305:         if (defined($end) && $end && ($now > $end)) {
 1306:             $Expired{$end}=$section;
 1307:             next;
 1308:         }
 1309:         if (defined($start) && $start && ($now < $start)) {
 1310:             $Pending{$start}=$section;
 1311:             next;
 1312:         }
 1313:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1314:     }
 1315:     #
 1316:     # Presumedly there will be few matching roles from the above
 1317:     # loop and the sorting time will be negligible.
 1318:     if (scalar(keys(%Pending))) {
 1319:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1320:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1321:     } 
 1322:     if (scalar(keys(%Expired))) {
 1323:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1324:         my $time = pop(@sorted);
 1325:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1326:     }
 1327:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1328: }
 1329: 
 1330: sub save_cache {
 1331:     &purge_remembered();
 1332:     #&Apache::loncommon::validate_page();
 1333:     undef(%env);
 1334:     undef($env_loaded);
 1335: }
 1336: 
 1337: my $to_remember=-1;
 1338: my %remembered;
 1339: my %accessed;
 1340: my $kicks=0;
 1341: my $hits=0;
 1342: sub make_key {
 1343:     my ($name,$id) = @_;
 1344:     if (length($id) > 65 
 1345: 	&& length(&escape($id)) > 200) {
 1346: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1347:     }
 1348:     return &escape($name.':'.$id);
 1349: }
 1350: 
 1351: sub devalidate_cache_new {
 1352:     my ($name,$id,$debug) = @_;
 1353:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1354:     $id=&make_key($name,$id);
 1355:     $memcache->delete($id);
 1356:     delete($remembered{$id});
 1357:     delete($accessed{$id});
 1358: }
 1359: 
 1360: sub is_cached_new {
 1361:     my ($name,$id,$debug) = @_;
 1362:     $id=&make_key($name,$id);
 1363:     if (exists($remembered{$id})) {
 1364: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1365: 	$accessed{$id}=[&gettimeofday()];
 1366: 	$hits++;
 1367: 	return ($remembered{$id},1);
 1368:     }
 1369:     my $value = $memcache->get($id);
 1370:     if (!(defined($value))) {
 1371: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1372: 	return (undef,undef);
 1373:     }
 1374:     if ($value eq '__undef__') {
 1375: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1376: 	$value=undef;
 1377:     }
 1378:     &make_room($id,$value,$debug);
 1379:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1380:     return ($value,1);
 1381: }
 1382: 
 1383: sub do_cache_new {
 1384:     my ($name,$id,$value,$time,$debug) = @_;
 1385:     $id=&make_key($name,$id);
 1386:     my $setvalue=$value;
 1387:     if (!defined($setvalue)) {
 1388: 	$setvalue='__undef__';
 1389:     }
 1390:     if (!defined($time) ) {
 1391: 	$time=600;
 1392:     }
 1393:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1394:     my $result = $memcache->set($id,$setvalue,$time);
 1395:     if (! $result) {
 1396: 	&logthis("caching of id -> $id  failed");
 1397: 	$memcache->disconnect_all();
 1398:     }
 1399:     # need to make a copy of $value
 1400:     &make_room($id,$value,$debug);
 1401:     return $value;
 1402: }
 1403: 
 1404: sub make_room {
 1405:     my ($id,$value,$debug)=@_;
 1406: 
 1407:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1408:                                     : $value;
 1409:     if ($to_remember<0) { return; }
 1410:     $accessed{$id}=[&gettimeofday()];
 1411:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1412:     my $to_kick;
 1413:     my $max_time=0;
 1414:     foreach my $other (keys(%accessed)) {
 1415: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1416: 	    $to_kick=$other;
 1417: 	    $max_time=&tv_interval($accessed{$other});
 1418: 	}
 1419:     }
 1420:     delete($remembered{$to_kick});
 1421:     delete($accessed{$to_kick});
 1422:     $kicks++;
 1423:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1424:     return;
 1425: }
 1426: 
 1427: sub purge_remembered {
 1428:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1429:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1430:     undef(%remembered);
 1431:     undef(%accessed);
 1432: }
 1433: # ------------------------------------- Read an entry from a user's environment
 1434: 
 1435: sub userenvironment {
 1436:     my ($udom,$unam,@what)=@_;
 1437:     my %returnhash=();
 1438:     my @answer=split(/\&/,
 1439:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1440:                       &homeserver($unam,$udom)));
 1441:     my $i;
 1442:     for ($i=0;$i<=$#what;$i++) {
 1443: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1444:     }
 1445:     return %returnhash;
 1446: }
 1447: 
 1448: # ---------------------------------------------------------- Get a studentphoto
 1449: sub studentphoto {
 1450:     my ($udom,$unam,$ext) = @_;
 1451:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1452:     if (defined($env{'request.course.id'})) {
 1453:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1454:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1455:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1456:             } else {
 1457:                 my ($result,$perm_reqd)=
 1458: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1459:                 if ($result eq 'ok') {
 1460:                     if (!($perm_reqd eq 'yes')) {
 1461:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1462:                     }
 1463:                 }
 1464:             }
 1465:         }
 1466:     } else {
 1467:         my ($result,$perm_reqd) = 
 1468: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1469:         if ($result eq 'ok') {
 1470:             if (!($perm_reqd eq 'yes')) {
 1471:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1472:             }
 1473:         }
 1474:     }
 1475:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1476: }
 1477: 
 1478: sub retrievestudentphoto {
 1479:     my ($udom,$unam,$ext,$type) = @_;
 1480:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1481:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1482:     if ($ret eq 'ok') {
 1483:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1484:         if ($type eq 'thumbnail') {
 1485:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1486:         }
 1487:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1488:         return $tokenurl;
 1489:     } else {
 1490:         if ($type eq 'thumbnail') {
 1491:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1492:         } else { 
 1493:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1494:         }
 1495:     }
 1496: }
 1497: 
 1498: # -------------------------------------------------------------------- New chat
 1499: 
 1500: sub chatsend {
 1501:     my ($newentry,$anon,$group)=@_;
 1502:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1503:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1504:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1505:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1506: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1507: 		   &escape($newentry)).':'.$group,$chome);
 1508: }
 1509: 
 1510: # ------------------------------------------ Find current version of a resource
 1511: 
 1512: sub getversion {
 1513:     my $fname=&clutter(shift);
 1514:     unless ($fname=~/^\/res\//) { return -1; }
 1515:     return &currentversion(&filelocation('',$fname));
 1516: }
 1517: 
 1518: sub currentversion {
 1519:     my $fname=shift;
 1520:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1521:     if (defined($cached)) { return $result; }
 1522:     my $author=$fname;
 1523:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1524:     my ($udom,$uname)=split(/\//,$author);
 1525:     my $home=homeserver($uname,$udom);
 1526:     if ($home eq 'no_host') { 
 1527:         return -1; 
 1528:     }
 1529:     my $answer=reply("currentversion:$fname",$home);
 1530:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1531: 	return -1;
 1532:     }
 1533:     return &do_cache_new('resversion',$fname,$answer,600);
 1534: }
 1535: 
 1536: # ----------------------------- Subscribe to a resource, return URL if possible
 1537: 
 1538: sub subscribe {
 1539:     my $fname=shift;
 1540:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1541:     $fname=~s/[\n\r]//g;
 1542:     my $author=$fname;
 1543:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1544:     my ($udom,$uname)=split(/\//,$author);
 1545:     my $home=homeserver($uname,$udom);
 1546:     if ($home eq 'no_host') {
 1547:         return 'not_found';
 1548:     }
 1549:     my $answer=reply("sub:$fname",$home);
 1550:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1551: 	$answer.=' by '.$home;
 1552:     }
 1553:     return $answer;
 1554: }
 1555:     
 1556: # -------------------------------------------------------------- Replicate file
 1557: 
 1558: sub repcopy {
 1559:     my $filename=shift;
 1560:     $filename=~s/\/+/\//g;
 1561:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1562:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1563:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1564: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1565: 	return &repcopy_userfile($filename);
 1566:     }
 1567:     $filename=~s/[\n\r]//g;
 1568:     my $transname="$filename.in.transfer";
 1569: # FIXME: this should flock
 1570:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1571:     my $remoteurl=subscribe($filename);
 1572:     if ($remoteurl =~ /^con_lost by/) {
 1573: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1574:            return 'unavailable';
 1575:     } elsif ($remoteurl eq 'not_found') {
 1576: 	   #&logthis("Subscribe returned not_found: $filename");
 1577: 	   return 'not_found';
 1578:     } elsif ($remoteurl =~ /^rejected by/) {
 1579: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1580:            return 'forbidden';
 1581:     } elsif ($remoteurl eq 'directory') {
 1582:            return 'ok';
 1583:     } else {
 1584:         my $author=$filename;
 1585:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1586:         my ($udom,$uname)=split(/\//,$author);
 1587:         my $home=homeserver($uname,$udom);
 1588:         unless ($home eq $perlvar{'lonHostID'}) {
 1589:            my @parts=split(/\//,$filename);
 1590:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1591:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1592:                &logthis("Malconfiguration for replication: $filename");
 1593: 	       return 'bad_request';
 1594:            }
 1595:            my $count;
 1596:            for ($count=5;$count<$#parts;$count++) {
 1597:                $path.="/$parts[$count]";
 1598:                if ((-e $path)!=1) {
 1599: 		   mkdir($path,0777);
 1600:                }
 1601:            }
 1602:            my $ua=new LWP::UserAgent;
 1603:            my $request=new HTTP::Request('GET',"$remoteurl");
 1604:            my $response=$ua->request($request,$transname);
 1605:            if ($response->is_error()) {
 1606: 	       unlink($transname);
 1607:                my $message=$response->status_line;
 1608:                &logthis("<font color=\"blue\">WARNING:"
 1609:                        ." LWP get: $message: $filename</font>");
 1610:                return 'unavailable';
 1611:            } else {
 1612: 	       if ($remoteurl!~/\.meta$/) {
 1613:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1614:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1615:                   if ($mresponse->is_error()) {
 1616: 		      unlink($filename.'.meta');
 1617:                       &logthis(
 1618:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1619:                   }
 1620: 	       }
 1621:                rename($transname,$filename);
 1622:                return 'ok';
 1623:            }
 1624:        }
 1625:     }
 1626: }
 1627: 
 1628: # ------------------------------------------------ Get server side include body
 1629: sub ssi_body {
 1630:     my ($filelink,%form)=@_;
 1631:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1632:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1633:     }
 1634:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1635:                                      &ssi($filelink,%form));
 1636:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1637:     $output=~s/^.*?\<body[^\>]*\>//si;
 1638:     $output=~s/\<\/body\s*\>.*?$//si;
 1639:     return $output;
 1640: }
 1641: 
 1642: # --------------------------------------------------------- Server Side Include
 1643: 
 1644: sub absolute_url {
 1645:     my ($host_name) = @_;
 1646:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1647:     if ($host_name eq '') {
 1648: 	$host_name = $ENV{'SERVER_NAME'};
 1649:     }
 1650:     return $protocol.$host_name;
 1651: }
 1652: 
 1653: sub ssi {
 1654: 
 1655:     my ($fn,%form)=@_;
 1656: 
 1657:     my $ua=new LWP::UserAgent;
 1658:     
 1659:     my $request;
 1660: 
 1661:     $form{'no_update_last_known'}=1;
 1662:     &Apache::lonenc::check_encrypt(\$fn);
 1663:     if (%form) {
 1664:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1665:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1666:     } else {
 1667:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1668:     }
 1669: 
 1670:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1671:     my $response=$ua->request($request);
 1672: 
 1673:     return $response->content;
 1674: }
 1675: 
 1676: sub externalssi {
 1677:     my ($url)=@_;
 1678:     my $ua=new LWP::UserAgent;
 1679:     my $request=new HTTP::Request('GET',$url);
 1680:     my $response=$ua->request($request);
 1681:     return $response->content;
 1682: }
 1683: 
 1684: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1685: 
 1686: sub allowuploaded {
 1687:     my ($srcurl,$url)=@_;
 1688:     $url=&clutter(&declutter($url));
 1689:     my $dir=$url;
 1690:     $dir=~s/\/[^\/]+$//;
 1691:     my %httpref=();
 1692:     my $httpurl=&hreflocation('',$url);
 1693:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1694:     &Apache::lonnet::appenv(%httpref);
 1695: }
 1696: 
 1697: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1698: # input: action, courseID, current domain, intended
 1699: #        path to file, source of file, instruction to parse file for objects,
 1700: #        ref to hash for embedded objects,
 1701: #        ref to hash for codebase of java objects.
 1702: #
 1703: # output: url to file (if action was uploaddoc), 
 1704: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1705: #
 1706: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1707: # course.
 1708: #
 1709: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1710: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1711: #          course's home server.
 1712: #
 1713: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1714: #          be copied from $source (current location) to 
 1715: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1716: #         and will then be copied to
 1717: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1718: #         course's home server.
 1719: #
 1720: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1721: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1722: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1723: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1724: #         in course's home server.
 1725: #
 1726: 
 1727: sub process_coursefile {
 1728:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1729:     my $fetchresult;
 1730:     my $home=&homeserver($docuname,$docudom);
 1731:     if ($action eq 'propagate') {
 1732:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1733: 			     $home);
 1734:     } else {
 1735:         my $fpath = '';
 1736:         my $fname = $file;
 1737:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1738:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1739:         my $filepath = &build_filepath($fpath);
 1740:         if ($action eq 'copy') {
 1741:             if ($source eq '') {
 1742:                 $fetchresult = 'no source file';
 1743:                 return $fetchresult;
 1744:             } else {
 1745:                 my $destination = $filepath.'/'.$fname;
 1746:                 rename($source,$destination);
 1747:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1748:                                  $home);
 1749:             }
 1750:         } elsif ($action eq 'uploaddoc') {
 1751:             open(my $fh,'>'.$filepath.'/'.$fname);
 1752:             print $fh $env{'form.'.$source};
 1753:             close($fh);
 1754:             if ($parser eq 'parse') {
 1755:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1756:                 unless ($parse_result eq 'ok') {
 1757:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1758:                 }
 1759:             }
 1760:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1761:                                  $home);
 1762:             if ($fetchresult eq 'ok') {
 1763:                 return '/uploaded/'.$fpath.'/'.$fname;
 1764:             } else {
 1765:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1766:                         ' to host '.$home.': '.$fetchresult);
 1767:                 return '/adm/notfound.html';
 1768:             }
 1769:         }
 1770:     }
 1771:     unless ( $fetchresult eq 'ok') {
 1772:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1773:              ' to host '.$home.': '.$fetchresult);
 1774:     }
 1775:     return $fetchresult;
 1776: }
 1777: 
 1778: sub build_filepath {
 1779:     my ($fpath) = @_;
 1780:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1781:     unless ($fpath eq '') {
 1782:         my @parts=split('/',$fpath);
 1783:         foreach my $part (@parts) {
 1784:             $filepath.= '/'.$part;
 1785:             if ((-e $filepath)!=1) {
 1786:                 mkdir($filepath,0777);
 1787:             }
 1788:         }
 1789:     }
 1790:     return $filepath;
 1791: }
 1792: 
 1793: sub store_edited_file {
 1794:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1795:     my $file = $primary_url;
 1796:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1797:     my $fpath = '';
 1798:     my $fname = $file;
 1799:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1800:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1801:     my $filepath = &build_filepath($fpath);
 1802:     open(my $fh,'>'.$filepath.'/'.$fname);
 1803:     print $fh $content;
 1804:     close($fh);
 1805:     my $home=&homeserver($docuname,$docudom);
 1806:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1807: 			  $home);
 1808:     if ($$fetchresult eq 'ok') {
 1809:         return '/uploaded/'.$fpath.'/'.$fname;
 1810:     } else {
 1811:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1812: 		 ' to host '.$home.': '.$$fetchresult);
 1813:         return '/adm/notfound.html';
 1814:     }
 1815: }
 1816: 
 1817: sub clean_filename {
 1818:     my ($fname,$args)=@_;
 1819: # Replace Windows backslashes by forward slashes
 1820:     $fname=~s/\\/\//g;
 1821:     if (!$args->{'keep_path'}) {
 1822:         # Get rid of everything but the actual filename
 1823: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1824:     }
 1825: # Replace spaces by underscores
 1826:     $fname=~s/\s+/\_/g;
 1827: # Replace all other weird characters by nothing
 1828:     $fname=~s{[^/\w\.\-]}{}g;
 1829: # Replace all .\d. sequences with _\d. so they no longer look like version
 1830: # numbers
 1831:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1832:     return $fname;
 1833: }
 1834: 
 1835: # --------------- Take an uploaded file and put it into the userfiles directory
 1836: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1837: #                    the desired filenam is in $env{"form.$formname.filename"}
 1838: #        $coursedoc - if true up to the current course
 1839: #                     if false
 1840: #        $subdir - directory in userfile to store the file into
 1841: #        $parser - instruction to parse file for objects ($parser = parse)    
 1842: #        $allfiles - reference to hash for embedded objects
 1843: #        $codebase - reference to hash for codebase of java objects
 1844: #        $desuname - username for permanent storage of uploaded file
 1845: #        $dsetudom - domain for permanaent storage of uploaded file
 1846: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1847: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1848: # 
 1849: # output: url of file in userspace, or error: <message> 
 1850: #             or /adm/notfound.html if failure to upload occurse
 1851: 
 1852: 
 1853: sub userfileupload {
 1854:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1855:         $destudom,$thumbwidth,$thumbheight)=@_;
 1856:     if (!defined($subdir)) { $subdir='unknown'; }
 1857:     my $fname=$env{'form.'.$formname.'.filename'};
 1858:     $fname=&clean_filename($fname);
 1859: # See if there is anything left
 1860:     unless ($fname) { return 'error: no uploaded file'; }
 1861:     chop($env{'form.'.$formname});
 1862:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1863:         my $now = time;
 1864:         my $filepath = 'tmp/helprequests/'.$now;
 1865:         my @parts=split(/\//,$filepath);
 1866:         my $fullpath = $perlvar{'lonDaemons'};
 1867:         for (my $i=0;$i<@parts;$i++) {
 1868:             $fullpath .= '/'.$parts[$i];
 1869:             if ((-e $fullpath)!=1) {
 1870:                 mkdir($fullpath,0777);
 1871:             }
 1872:         }
 1873:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1874:         print $fh $env{'form.'.$formname};
 1875:         close($fh);
 1876:         return $fullpath.'/'.$fname;
 1877:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1878:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1879:                        '_'.$env{'user.domain'}.'/pending';
 1880:         my @parts=split(/\//,$filepath);
 1881:         my $fullpath = $perlvar{'lonDaemons'};
 1882:         for (my $i=0;$i<@parts;$i++) {
 1883:             $fullpath .= '/'.$parts[$i];
 1884:             if ((-e $fullpath)!=1) {
 1885:                 mkdir($fullpath,0777);
 1886:             }
 1887:         }
 1888:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1889:         print $fh $env{'form.'.$formname};
 1890:         close($fh);
 1891:         return $fullpath.'/'.$fname;
 1892:     }
 1893:     
 1894: # Create the directory if not present
 1895:     $fname="$subdir/$fname";
 1896:     if ($coursedoc) {
 1897: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1898: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1899:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1900:             return &finishuserfileupload($docuname,$docudom,
 1901: 					 $formname,$fname,$parser,$allfiles,
 1902: 					 $codebase,$thumbwidth,$thumbheight);
 1903:         } else {
 1904:             $fname=$env{'form.folder'}.'/'.$fname;
 1905:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1906: 				       $fname,$formname,$parser,
 1907: 				       $allfiles,$codebase);
 1908:         }
 1909:     } elsif (defined($destuname)) {
 1910:         my $docuname=$destuname;
 1911:         my $docudom=$destudom;
 1912: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1913: 				     $parser,$allfiles,$codebase,
 1914:                                      $thumbwidth,$thumbheight);
 1915:         
 1916:     } else {
 1917:         my $docuname=$env{'user.name'};
 1918:         my $docudom=$env{'user.domain'};
 1919:         if (exists($env{'form.group'})) {
 1920:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1921:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1922:         }
 1923: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1924: 				     $parser,$allfiles,$codebase,
 1925:                                      $thumbwidth,$thumbheight);
 1926:     }
 1927: }
 1928: 
 1929: sub finishuserfileupload {
 1930:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1931:         $thumbwidth,$thumbheight) = @_;
 1932:     my $path=$docudom.'/'.$docuname.'/';
 1933:     my $filepath=$perlvar{'lonDocRoot'};
 1934:     my ($fnamepath,$file,$fetchthumb);
 1935:     $file=$fname;
 1936:     if ($fname=~m|/|) {
 1937:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1938: 	$path.=$fnamepath.'/';
 1939:     }
 1940:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1941:     my $count;
 1942:     for ($count=4;$count<=$#parts;$count++) {
 1943:         $filepath.="/$parts[$count]";
 1944:         if ((-e $filepath)!=1) {
 1945: 	    mkdir($filepath,0777);
 1946:         }
 1947:     }
 1948: # Save the file
 1949:     {
 1950: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1951: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1952: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1953: 	    return '/adm/notfound.html';
 1954: 	}
 1955: 	if (!print FH ($env{'form.'.$formname})) {
 1956: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1957: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1958: 	    return '/adm/notfound.html';
 1959: 	}
 1960: 	close(FH);
 1961:     }
 1962:     if ($parser eq 'parse') {
 1963:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1964: 						   $codebase);
 1965:         unless ($parse_result eq 'ok') {
 1966:             &logthis('Failed to parse '.$filepath.$file.
 1967: 		     ' for embedded media: '.$parse_result); 
 1968:         }
 1969:     }
 1970:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1971:         my $input = $filepath.'/'.$file;
 1972:         my $output = $filepath.'/'.'tn-'.$file;
 1973:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1974:         system("convert -sample $thumbsize $input $output");
 1975:         if (-e $filepath.'/'.'tn-'.$file) {
 1976:             $fetchthumb  = 1; 
 1977:         }
 1978:     }
 1979:  
 1980: # Notify homeserver to grep it
 1981: #
 1982:     my $docuhome=&homeserver($docuname,$docudom);
 1983:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1984:     if ($fetchresult eq 'ok') {
 1985:         if ($fetchthumb) {
 1986:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1987:             if ($thumbresult ne 'ok') {
 1988:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1989:                          $docuhome.': '.$thumbresult);
 1990:             }
 1991:         }
 1992: #
 1993: # Return the URL to it
 1994:         return '/uploaded/'.$path.$file;
 1995:     } else {
 1996:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1997: 		 ': '.$fetchresult);
 1998:         return '/adm/notfound.html';
 1999:     }
 2000: }
 2001: 
 2002: sub extract_embedded_items {
 2003:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2004:     my @state = ();
 2005:     my %javafiles = (
 2006:                       codebase => '',
 2007:                       code => '',
 2008:                       archive => ''
 2009:                     );
 2010:     my %mediafiles = (
 2011:                       src => '',
 2012:                       movie => '',
 2013:                      );
 2014:     my $p;
 2015:     if ($content) {
 2016:         $p = HTML::LCParser->new($content);
 2017:     } else {
 2018:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2019:     }
 2020:     while (my $t=$p->get_token()) {
 2021: 	if ($t->[0] eq 'S') {
 2022: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2023: 	    push(@state, $tagname);
 2024:             if (lc($tagname) eq 'allow') {
 2025:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2026:             }
 2027: 	    if (lc($tagname) eq 'img') {
 2028: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2029: 	    }
 2030: 	    if (lc($tagname) eq 'a') {
 2031: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2032: 	    }
 2033:             if (lc($tagname) eq 'script') {
 2034:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2035:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2036:                 } else {
 2037:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2038:                 }
 2039:             }
 2040:             if (lc($tagname) eq 'link') {
 2041:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2042:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2043:                 }
 2044:             }
 2045: 	    if (lc($tagname) eq 'object' ||
 2046: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2047: 		foreach my $item (keys(%javafiles)) {
 2048: 		    $javafiles{$item} = '';
 2049: 		}
 2050: 	    }
 2051: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2052: 		my $name = lc($attr->{'name'});
 2053: 		foreach my $item (keys(%javafiles)) {
 2054: 		    if ($name eq $item) {
 2055: 			$javafiles{$item} = $attr->{'value'};
 2056: 			last;
 2057: 		    }
 2058: 		}
 2059: 		foreach my $item (keys(%mediafiles)) {
 2060: 		    if ($name eq $item) {
 2061: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2062: 			last;
 2063: 		    }
 2064: 		}
 2065: 	    }
 2066: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2067: 		foreach my $item (keys(%javafiles)) {
 2068: 		    if ($attr->{$item}) {
 2069: 			$javafiles{$item} = $attr->{$item};
 2070: 			last;
 2071: 		    }
 2072: 		}
 2073: 		foreach my $item (keys(%mediafiles)) {
 2074: 		    if ($attr->{$item}) {
 2075: 			&add_filetype($allfiles,$attr->{$item},$item);
 2076: 			last;
 2077: 		    }
 2078: 		}
 2079: 	    }
 2080: 	} elsif ($t->[0] eq 'E') {
 2081: 	    my ($tagname) = ($t->[1]);
 2082: 	    if ($javafiles{'codebase'} ne '') {
 2083: 		$javafiles{'codebase'} .= '/';
 2084: 	    }  
 2085: 	    if (lc($tagname) eq 'applet' ||
 2086: 		lc($tagname) eq 'object' ||
 2087: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2088: 		) {
 2089: 		foreach my $item (keys(%javafiles)) {
 2090: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2091: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2092: 			&add_filetype($allfiles,$file,$item);
 2093: 		    }
 2094: 		}
 2095: 	    } 
 2096: 	    pop @state;
 2097: 	}
 2098:     }
 2099:     return 'ok';
 2100: }
 2101: 
 2102: sub add_filetype {
 2103:     my ($allfiles,$file,$type)=@_;
 2104:     if (exists($allfiles->{$file})) {
 2105: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2106: 	    push(@{$allfiles->{$file}}, &escape($type));
 2107: 	}
 2108:     } else {
 2109: 	@{$allfiles->{$file}} = (&escape($type));
 2110:     }
 2111: }
 2112: 
 2113: sub removeuploadedurl {
 2114:     my ($url)=@_;
 2115:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2116:     return &removeuserfile($uname,$udom,$fname);
 2117: }
 2118: 
 2119: sub removeuserfile {
 2120:     my ($docuname,$docudom,$fname)=@_;
 2121:     my $home=&homeserver($docuname,$docudom);
 2122:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2123:     if ($result eq 'ok') {
 2124:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2125:             my $metafile = $fname.'.meta';
 2126:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2127: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2128:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2129:             my $sqlresult = 
 2130:                 &update_portfolio_table($docuname,$docudom,$file,
 2131:                                         'portfolio_metadata',$group,
 2132:                                         'delete');
 2133:         }
 2134:     }
 2135:     return $result;
 2136: }
 2137: 
 2138: sub mkdiruserfile {
 2139:     my ($docuname,$docudom,$dir)=@_;
 2140:     my $home=&homeserver($docuname,$docudom);
 2141:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2142: }
 2143: 
 2144: sub renameuserfile {
 2145:     my ($docuname,$docudom,$old,$new)=@_;
 2146:     my $home=&homeserver($docuname,$docudom);
 2147:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2148:                         &escape("$old").':'.&escape("$new"),$home);
 2149:     if ($result eq 'ok') {
 2150:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2151:             my $oldmeta = $old.'.meta';
 2152:             my $newmeta = $new.'.meta';
 2153:             my $metaresult = 
 2154:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2155: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2156:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2157:             my $sqlresult = 
 2158:                 &update_portfolio_table($docuname,$docudom,$file,
 2159:                                         'portfolio_metadata',$group,
 2160:                                         'delete');
 2161:         }
 2162:     }
 2163:     return $result;
 2164: }
 2165: 
 2166: # ------------------------------------------------------------------------- Log
 2167: 
 2168: sub log {
 2169:     my ($dom,$nam,$hom,$what)=@_;
 2170:     return critical("log:$dom:$nam:$what",$hom);
 2171: }
 2172: 
 2173: # ------------------------------------------------------------------ Course Log
 2174: #
 2175: # This routine flushes several buffers of non-mission-critical nature
 2176: #
 2177: 
 2178: sub flushcourselogs {
 2179:     &logthis('Flushing log buffers');
 2180: #
 2181: # course logs
 2182: # This is a log of all transactions in a course, which can be used
 2183: # for data mining purposes
 2184: #
 2185: # It also collects the courseid database, which lists last transaction
 2186: # times and course titles for all courseids
 2187: #
 2188:     my %courseidbuffer=();
 2189:     foreach my $crsid (keys(%courselogs)) {
 2190:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2191: 		          &escape($courselogs{$crsid}),
 2192: 		          $coursehombuf{$crsid}) eq 'ok') {
 2193: 	    delete $courselogs{$crsid};
 2194:         } else {
 2195:             &logthis('Failed to flush log buffer for '.$crsid);
 2196:             if (length($courselogs{$crsid})>40000) {
 2197:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2198:                         " exceeded maximum size, deleting.</font>");
 2199:                delete $courselogs{$crsid};
 2200:             }
 2201:         }
 2202:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2203:             'description' => $coursedescrbuf{$crsid},
 2204:             'inst_code'    => $courseinstcodebuf{$crsid},
 2205:             'type'        => $coursetypebuf{$crsid},
 2206:             'owner'       => $courseownerbuf{$crsid},
 2207:         };
 2208:     }
 2209: #
 2210: # Write course id database (reverse lookup) to homeserver of courses 
 2211: # Is used in pickcourse
 2212: #
 2213:     foreach my $crs_home (keys(%courseidbuffer)) {
 2214:         my $response = &courseidput(&host_domain($crs_home),
 2215:                                     $courseidbuffer{$crs_home},
 2216:                                     $crs_home,'timeonly');
 2217:     }
 2218: #
 2219: # File accesses
 2220: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2221: #
 2222:     foreach my $entry (keys(%accesshash)) {
 2223:         if ($entry =~ /___count$/) {
 2224:             my ($dom,$name);
 2225:             ($dom,$name,undef)=
 2226: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2227:             if (! defined($dom) || $dom eq '' || 
 2228:                 ! defined($name) || $name eq '') {
 2229:                 my $cid = $env{'request.course.id'};
 2230:                 $dom  = $env{'request.'.$cid.'.domain'};
 2231:                 $name = $env{'request.'.$cid.'.num'};
 2232:             }
 2233:             my $value = $accesshash{$entry};
 2234:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2235:             my %temphash=($url => $value);
 2236:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2237:             if ($result eq 'ok') {
 2238:                 delete $accesshash{$entry};
 2239:             } elsif ($result eq 'unknown_cmd') {
 2240:                 # Target server has old code running on it.
 2241:                 my %temphash=($entry => $value);
 2242:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2243:                     delete $accesshash{$entry};
 2244:                 }
 2245:             }
 2246:         } else {
 2247:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2248:             my %temphash=($entry => $accesshash{$entry});
 2249:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2250:                 delete $accesshash{$entry};
 2251:             }
 2252:         }
 2253:     }
 2254: #
 2255: # Roles
 2256: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2257: #
 2258:     foreach my $entry (keys(%userrolehash)) {
 2259:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2260: 	    split(/\:/,$entry);
 2261:         if (&Apache::lonnet::put('nohist_userroles',
 2262:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2263:                 $rudom,$runame) eq 'ok') {
 2264: 	    delete $userrolehash{$entry};
 2265:         }
 2266:     }
 2267: #
 2268: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2269: #
 2270:     my %domrolebuffer = ();
 2271:     foreach my $entry (keys %domainrolehash) {
 2272:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2273:         if ($domrolebuffer{$rudom}) {
 2274:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2275:                       '='.&escape($domainrolehash{$entry});
 2276:         } else {
 2277:             $domrolebuffer{$rudom}.=&escape($entry).
 2278:                       '='.&escape($domainrolehash{$entry});
 2279:         }
 2280:         delete $domainrolehash{$entry};
 2281:     }
 2282:     foreach my $dom (keys(%domrolebuffer)) {
 2283: 	my %servers = &get_servers($dom,'library');
 2284: 	foreach my $tryserver (keys(%servers)) {
 2285: 	    unless (&reply('domroleput:'.$dom.':'.
 2286: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2287: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2288: 	    }
 2289:         }
 2290:     }
 2291:     $dumpcount++;
 2292: }
 2293: 
 2294: sub courselog {
 2295:     my $what=shift;
 2296:     $what=time.':'.$what;
 2297:     unless ($env{'request.course.id'}) { return ''; }
 2298:     $coursedombuf{$env{'request.course.id'}}=
 2299:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2300:     $coursenumbuf{$env{'request.course.id'}}=
 2301:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2302:     $coursehombuf{$env{'request.course.id'}}=
 2303:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2304:     $coursedescrbuf{$env{'request.course.id'}}=
 2305:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2306:     $courseinstcodebuf{$env{'request.course.id'}}=
 2307:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2308:     $courseownerbuf{$env{'request.course.id'}}=
 2309:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2310:     $coursetypebuf{$env{'request.course.id'}}=
 2311:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2312:     if (defined $courselogs{$env{'request.course.id'}}) {
 2313: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2314:     } else {
 2315: 	$courselogs{$env{'request.course.id'}}.=$what;
 2316:     }
 2317:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2318: 	&flushcourselogs();
 2319:     }
 2320: }
 2321: 
 2322: sub courseacclog {
 2323:     my $fnsymb=shift;
 2324:     unless ($env{'request.course.id'}) { return ''; }
 2325:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2326:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2327:         $what.=':POST';
 2328:         # FIXME: Probably ought to escape things....
 2329: 	foreach my $key (keys(%env)) {
 2330:             if ($key=~/^form\.(.*)/) {
 2331: 		$what.=':'.$1.'='.$env{$key};
 2332:             }
 2333:         }
 2334:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2335:         # FIXME: We should not be depending on a form parameter that someone
 2336:         # editing lonsearchcat.pm might change in the future.
 2337:         if ($env{'form.phase'} eq 'course_search') {
 2338:             $what.= ':POST';
 2339:             # FIXME: Probably ought to escape things....
 2340:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2341:                                  'crsdiscuss') {
 2342:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2343:             }
 2344:         }
 2345:     }
 2346:     &courselog($what);
 2347: }
 2348: 
 2349: sub countacc {
 2350:     my $url=&declutter(shift);
 2351:     return if (! defined($url) || $url eq '');
 2352:     unless ($env{'request.course.id'}) { return ''; }
 2353:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2354:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2355:     $accesshash{$key}++;
 2356: }
 2357: 
 2358: sub linklog {
 2359:     my ($from,$to)=@_;
 2360:     $from=&declutter($from);
 2361:     $to=&declutter($to);
 2362:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2363:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2364: }
 2365:   
 2366: sub userrolelog {
 2367:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2368:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2369:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2370:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2371:         ($trole=~/^ta/)) {
 2372:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2373:        $userrolehash
 2374:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2375:                     =$tend.':'.$tstart;
 2376:     }
 2377:     if (($env{'request.role'} =~ /dc\./) &&
 2378: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2379: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2380: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2381:        $userrolehash
 2382:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2383:                     =$tend.':'.$tstart;
 2384:     }
 2385:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2386:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2387:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2388:         ($trole=~/^sc/)) {
 2389:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2390:        $domainrolehash
 2391:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2392:                     = $tend.':'.$tstart;
 2393:     }
 2394: }
 2395: 
 2396: sub get_course_adv_roles {
 2397:     my $cid=shift;
 2398:     $cid=$env{'request.course.id'} unless (defined($cid));
 2399:     my %coursehash=&coursedescription($cid);
 2400:     my %nothide=();
 2401:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2402:         if ($user !~ /:/) {
 2403: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2404:         } else {
 2405:             $nothide{$user}=1;
 2406:         }
 2407:     }
 2408:     my %returnhash=();
 2409:     my %dumphash=
 2410:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2411:     my $now=time;
 2412:     foreach my $entry (keys %dumphash) {
 2413: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2414:         if (($tstart) && ($tstart<0)) { next; }
 2415:         if (($tend) && ($tend<$now)) { next; }
 2416:         if (($tstart) && ($now<$tstart)) { next; }
 2417:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2418: 	if ($username eq '' || $domain eq '') { next; }
 2419: 	if ((&privileged($username,$domain)) && 
 2420: 	    (!$nothide{$username.':'.$domain})) { next; }
 2421: 	if ($role eq 'cr') { next; }
 2422:         my $key=&plaintext($role);
 2423:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2424:         if ($returnhash{$key}) {
 2425: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2426:         } else {
 2427:             $returnhash{$key}=$username.':'.$domain;
 2428:         }
 2429:      }
 2430:     return %returnhash;
 2431: }
 2432: 
 2433: sub get_my_roles {
 2434:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2435:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2436:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2437:     my (%dumphash,%nothide);
 2438:     if ($context eq 'userroles') { 
 2439:         %dumphash = &dump('roles',$udom,$uname);
 2440:     } else {
 2441:         %dumphash=
 2442:             &dump('nohist_userroles',$udom,$uname);
 2443:         if ($hidepriv) {
 2444:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2445:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2446:                 if ($user !~ /:/) {
 2447:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2448:                 } else {
 2449:                     $nothide{$user} = 1;
 2450:                 }
 2451:             }
 2452:         }
 2453:     }
 2454:     my %returnhash=();
 2455:     my $now=time;
 2456:     foreach my $entry (keys(%dumphash)) {
 2457:         my ($role,$tend,$tstart);
 2458:         if ($context eq 'userroles') {
 2459: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2460:         } else {
 2461:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2462:         }
 2463:         if (($tstart) && ($tstart<0)) { next; }
 2464:         my $status = 'active';
 2465:         if (($tend) && ($tend<=$now)) {
 2466:             $status = 'previous';
 2467:         } 
 2468:         if (($tstart) && ($now<$tstart)) {
 2469:             $status = 'future';
 2470:         }
 2471:         if (ref($types) eq 'ARRAY') {
 2472:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2473:                 next;
 2474:             } 
 2475:         } else {
 2476:             if ($status ne 'active') {
 2477:                 next;
 2478:             }
 2479:         }
 2480:         my ($rolecode,$username,$domain,$section,$area);
 2481:         if ($context eq 'userroles') {
 2482:             ($area,$rolecode) = split(/_/,$entry);
 2483:             (undef,$domain,$username,$section) = split(/\//,$area);
 2484:         } else {
 2485:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2486:         }
 2487:         if (ref($roledoms) eq 'ARRAY') {
 2488:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2489:                 next;
 2490:             }
 2491:         }
 2492:         if (ref($roles) eq 'ARRAY') {
 2493:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2494:                 if ($role =~ /^cr\//) {
 2495:                     if (!grep(/^cr$/,@{$roles})) {
 2496:                         next;
 2497:                     }
 2498:                 } else {
 2499:                     next;
 2500:                 }
 2501:             }
 2502:         }
 2503:         if ($hidepriv) {
 2504:             if ((&privileged($username,$domain)) &&
 2505:                 (!$nothide{$username.':'.$domain})) { 
 2506:                 next;
 2507:             }
 2508:         }
 2509:         if ($withsec) {
 2510:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2511:                 $tstart.':'.$tend;
 2512:         } else {
 2513:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2514:         }
 2515:     }
 2516:     return %returnhash;
 2517: }
 2518: 
 2519: # ----------------------------------------------------- Frontpage Announcements
 2520: #
 2521: #
 2522: 
 2523: sub postannounce {
 2524:     my ($server,$text)=@_;
 2525:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2526:     unless ($text=~/\w/) { $text=''; }
 2527:     return &reply('setannounce:'.&escape($text),$server);
 2528: }
 2529: 
 2530: sub getannounce {
 2531: 
 2532:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2533: 	my $announcement='';
 2534: 	while (my $line = <$fh>) { $announcement .= $line; }
 2535: 	close($fh);
 2536: 	if ($announcement=~/\w/) { 
 2537: 	    return 
 2538:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2539:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2540: 	} else {
 2541: 	    return '';
 2542: 	}
 2543:     } else {
 2544: 	return '';
 2545:     }
 2546: }
 2547: 
 2548: # ---------------------------------------------------------- Course ID routines
 2549: # Deal with domain's nohist_courseid.db files
 2550: #
 2551: 
 2552: sub courseidput {
 2553:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2554:     my $outcome;
 2555:     if ($caller eq 'timeonly') {
 2556:         my $cids = '';
 2557:         foreach my $item (keys(%$storehash)) {
 2558:             $cids.=&escape($item).'&';
 2559:         }
 2560:         $cids=~s/\&$//;
 2561:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2562:                           $coursehome);       
 2563:     } else {
 2564:         my $items = '';
 2565:         foreach my $item (keys(%$storehash)) {
 2566:             $items.= &escape($item).'='.
 2567:                      &freeze_escape($$storehash{$item}).'&';
 2568:         }
 2569:         $items=~s/\&$//;
 2570:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2571:                           $coursehome);
 2572:     }
 2573:     if ($outcome eq 'unknown_cmd') {
 2574:         my $what;
 2575:         foreach my $cid (keys(%$storehash)) {
 2576:             $what .= &escape($cid).'=';
 2577:             foreach my $item ('description','inst_code','owner','type') {
 2578:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2579:             }
 2580:             $what =~ s/\:$/&/;
 2581:         }
 2582:         $what =~ s/\&$//;  
 2583:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2584:     } else {
 2585:         return $outcome;
 2586:     }
 2587: }
 2588: 
 2589: sub courseiddump {
 2590:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2591:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2592:     my $as_hash = 1;
 2593:     my %returnhash;
 2594:     if (!$domfilter) { $domfilter=''; }
 2595:     my %libserv = &all_library();
 2596:     foreach my $tryserver (keys(%libserv)) {
 2597:         if ( (  $hostidflag == 1 
 2598: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2599: 	     || (!defined($hostidflag)) ) {
 2600: 
 2601: 	    if (($domfilter eq '') ||
 2602: 		(&host_domain($tryserver) eq $domfilter)) {
 2603:                 my $rep = 
 2604:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2605:                          $sincefilter.':'.&escape($descfilter).':'.
 2606:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2607:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2608:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
 2609:                 my @pairs=split(/\&/,$rep);
 2610:                 foreach my $item (@pairs) {
 2611:                     my ($key,$value)=split(/\=/,$item,2);
 2612:                     $key = &unescape($key);
 2613:                     next if ($key =~ /^error: 2 /);
 2614:                     my $result = &thaw_unescape($value);
 2615:                     if (ref($result) eq 'HASH') {
 2616:                         $returnhash{$key}=$result;
 2617:                     } else {
 2618:                         my @responses = split(/:/,$value);
 2619:                         my @items = ('description','inst_code','owner','type');
 2620:                         for (my $i=0; $i<@responses; $i++) {
 2621:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2622:                         }
 2623:                     } 
 2624:                 }
 2625:             }
 2626:         }
 2627:     }
 2628:     return %returnhash;
 2629: }
 2630: 
 2631: # ---------------------------------------------------------- DC e-mail
 2632: 
 2633: sub dcmailput {
 2634:     my ($domain,$msgid,$message,$server)=@_;
 2635:     my $status = &Apache::lonnet::critical(
 2636:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2637:        &escape($message),$server);
 2638:     return $status;
 2639: }
 2640: 
 2641: sub dcmaildump {
 2642:     my ($dom,$startdate,$enddate,$senders) = @_;
 2643:     my %returnhash=();
 2644: 
 2645:     if (defined(&domain($dom,'primary'))) {
 2646:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2647:                                                          &escape($enddate).':';
 2648: 	my @esc_senders=map { &escape($_)} @$senders;
 2649: 	$cmd.=&escape(join('&',@esc_senders));
 2650: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2651:             my ($key,$value) = split(/\=/,$line,2);
 2652:             if (($key) && ($value)) {
 2653:                 $returnhash{&unescape($key)} = &unescape($value);
 2654:             }
 2655:         }
 2656:     }
 2657:     return %returnhash;
 2658: }
 2659: # ---------------------------------------------------------- Domain roles
 2660: 
 2661: sub get_domain_roles {
 2662:     my ($dom,$roles,$startdate,$enddate)=@_;
 2663:     if (undef($startdate) || $startdate eq '') {
 2664:         $startdate = '.';
 2665:     }
 2666:     if (undef($enddate) || $enddate eq '') {
 2667:         $enddate = '.';
 2668:     }
 2669:     my $rolelist;
 2670:     if (ref($roles) eq 'ARRAY') {
 2671:         $rolelist = join(':',@{$roles});
 2672:     }
 2673:     my %personnel = ();
 2674: 
 2675:     my %servers = &get_servers($dom,'library');
 2676:     foreach my $tryserver (keys(%servers)) {
 2677: 	%{$personnel{$tryserver}}=();
 2678: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2679: 					    &escape($startdate).':'.
 2680: 					    &escape($enddate).':'.
 2681: 					    &escape($rolelist), $tryserver))) {
 2682: 	    my ($key,$value) = split(/\=/,$line,2);
 2683: 	    if (($key) && ($value)) {
 2684: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2685: 	    }
 2686: 	}
 2687:     }
 2688:     return %personnel;
 2689: }
 2690: 
 2691: # ----------------------------------------------------------- Check out an item
 2692: 
 2693: sub get_first_access {
 2694:     my ($type,$argsymb)=@_;
 2695:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2696:     if ($argsymb) { $symb=$argsymb; }
 2697:     my ($map,$id,$res)=&decode_symb($symb);
 2698:     if ($type eq 'course') {
 2699: 	$res='course';
 2700:     } elsif ($type eq 'map') {
 2701: 	$res=&symbread($map);
 2702:     } else {
 2703: 	$res=$symb;
 2704:     }
 2705:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2706:     return $times{"$courseid\0$res"};
 2707: }
 2708: 
 2709: sub set_first_access {
 2710:     my ($type)=@_;
 2711:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2712:     my ($map,$id,$res)=&decode_symb($symb);
 2713:     if ($type eq 'course') {
 2714: 	$res='course';
 2715:     } elsif ($type eq 'map') {
 2716: 	$res=&symbread($map);
 2717:     } else {
 2718: 	$res=$symb;
 2719:     }
 2720:     my $firstaccess=&get_first_access($type,$symb);
 2721:     if (!$firstaccess) {
 2722: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2723:     }
 2724:     return 'already_set';
 2725: }
 2726: 
 2727: sub checkout {
 2728:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2729:     my $now=time;
 2730:     my $lonhost=$perlvar{'lonHostID'};
 2731:     my $infostr=&escape(
 2732:                  'CHECKOUTTOKEN&'.
 2733:                  $tuname.'&'.
 2734:                  $tudom.'&'.
 2735:                  $tcrsid.'&'.
 2736:                  $symb.'&'.
 2737: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2738:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2739:     if ($token=~/^error\:/) { 
 2740:         &logthis("<font color=\"blue\">WARNING: ".
 2741:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2742:                  "</font>");
 2743:         return ''; 
 2744:     }
 2745: 
 2746:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2747:     $token=~tr/a-z/A-Z/;
 2748: 
 2749:     my %infohash=('resource.0.outtoken' => $token,
 2750:                   'resource.0.checkouttime' => $now,
 2751:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2752: 
 2753:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2754:        return '';
 2755:     } else {
 2756:         &logthis("<font color=\"blue\">WARNING: ".
 2757:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2758:                  "</font>");
 2759:     }    
 2760: 
 2761:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2762:                          &escape('Checkout '.$infostr.' - '.
 2763:                                                  $token)) ne 'ok') {
 2764: 	return '';
 2765:     } else {
 2766:         &logthis("<font color=\"blue\">WARNING: ".
 2767:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2768:                  "</font>");
 2769:     }
 2770:     return $token;
 2771: }
 2772: 
 2773: # ------------------------------------------------------------ Check in an item
 2774: 
 2775: sub checkin {
 2776:     my $token=shift;
 2777:     my $now=time;
 2778:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2779:     $lonhost=~tr/A-Z/a-z/;
 2780:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2781:     $dtoken=~s/\W/\_/g;
 2782:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2783:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2784: 
 2785:     unless (($tuname) && ($tudom)) {
 2786:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2787:         return '';
 2788:     }
 2789:     
 2790:     unless (&allowed('mgr',$tcrsid)) {
 2791:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2792:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2793:         return '';
 2794:     }
 2795: 
 2796:     my %infohash=('resource.0.intoken' => $token,
 2797:                   'resource.0.checkintime' => $now,
 2798:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2799: 
 2800:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2801:        return '';
 2802:     }    
 2803: 
 2804:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2805:                          &escape('Checkin - '.$token)) ne 'ok') {
 2806: 	return '';
 2807:     }
 2808: 
 2809:     return ($symb,$tuname,$tudom,$tcrsid);    
 2810: }
 2811: 
 2812: # --------------------------------------------- Set Expire Date for Spreadsheet
 2813: 
 2814: sub expirespread {
 2815:     my ($uname,$udom,$stype,$usymb)=@_;
 2816:     my $cid=$env{'request.course.id'}; 
 2817:     if ($cid) {
 2818:        my $now=time;
 2819:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2820:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2821:                             $env{'course.'.$cid.'.num'}.
 2822: 	        	    ':nohist_expirationdates:'.
 2823:                             &escape($key).'='.$now,
 2824:                             $env{'course.'.$cid.'.home'})
 2825:     }
 2826:     return 'ok';
 2827: }
 2828: 
 2829: # ----------------------------------------------------- Devalidate Spreadsheets
 2830: 
 2831: sub devalidate {
 2832:     my ($symb,$uname,$udom)=@_;
 2833:     my $cid=$env{'request.course.id'}; 
 2834:     if ($cid) {
 2835:         # delete the stored spreadsheets for
 2836:         # - the student level sheet of this user in course's homespace
 2837:         # - the assessment level sheet for this resource 
 2838:         #   for this user in user's homespace
 2839: 	# - current conditional state info
 2840: 	my $key=$uname.':'.$udom.':';
 2841:         my $status=
 2842: 	    &del('nohist_calculatedsheets',
 2843: 		 [$key.'studentcalc:'],
 2844: 		 $env{'course.'.$cid.'.domain'},
 2845: 		 $env{'course.'.$cid.'.num'})
 2846: 		.' '.
 2847: 	    &del('nohist_calculatedsheets_'.$cid,
 2848: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2849:         unless ($status eq 'ok ok') {
 2850:            &logthis('Could not devalidate spreadsheet '.
 2851:                     $uname.' at '.$udom.' for '.
 2852: 		    $symb.': '.$status);
 2853:         }
 2854: 	&delenv('user.state.'.$cid);
 2855:     }
 2856: }
 2857: 
 2858: sub get_scalar {
 2859:     my ($string,$end) = @_;
 2860:     my $value;
 2861:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2862: 	$value = $1;
 2863:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2864: 	$value = $1;
 2865:     }
 2866:     return &unescape($value);
 2867: }
 2868: 
 2869: sub array2str {
 2870:   my (@array) = @_;
 2871:   my $result=&arrayref2str(\@array);
 2872:   $result=~s/^__ARRAY_REF__//;
 2873:   $result=~s/__END_ARRAY_REF__$//;
 2874:   return $result;
 2875: }
 2876: 
 2877: sub arrayref2str {
 2878:   my ($arrayref) = @_;
 2879:   my $result='__ARRAY_REF__';
 2880:   foreach my $elem (@$arrayref) {
 2881:     if(ref($elem) eq 'ARRAY') {
 2882:       $result.=&arrayref2str($elem).'&';
 2883:     } elsif(ref($elem) eq 'HASH') {
 2884:       $result.=&hashref2str($elem).'&';
 2885:     } elsif(ref($elem)) {
 2886:       #print("Got a ref of ".(ref($elem))." skipping.");
 2887:     } else {
 2888:       $result.=&escape($elem).'&';
 2889:     }
 2890:   }
 2891:   $result=~s/\&$//;
 2892:   $result .= '__END_ARRAY_REF__';
 2893:   return $result;
 2894: }
 2895: 
 2896: sub hash2str {
 2897:   my (%hash) = @_;
 2898:   my $result=&hashref2str(\%hash);
 2899:   $result=~s/^__HASH_REF__//;
 2900:   $result=~s/__END_HASH_REF__$//;
 2901:   return $result;
 2902: }
 2903: 
 2904: sub hashref2str {
 2905:   my ($hashref)=@_;
 2906:   my $result='__HASH_REF__';
 2907:   foreach my $key (sort(keys(%$hashref))) {
 2908:     if (ref($key) eq 'ARRAY') {
 2909:       $result.=&arrayref2str($key).'=';
 2910:     } elsif (ref($key) eq 'HASH') {
 2911:       $result.=&hashref2str($key).'=';
 2912:     } elsif (ref($key)) {
 2913:       $result.='=';
 2914:       #print("Got a ref of ".(ref($key))." skipping.");
 2915:     } else {
 2916: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2917:     }
 2918: 
 2919:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2920:       $result.=&arrayref2str($hashref->{$key}).'&';
 2921:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2922:       $result.=&hashref2str($hashref->{$key}).'&';
 2923:     } elsif(ref($hashref->{$key})) {
 2924:        $result.='&';
 2925:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2926:     } else {
 2927:       $result.=&escape($hashref->{$key}).'&';
 2928:     }
 2929:   }
 2930:   $result=~s/\&$//;
 2931:   $result .= '__END_HASH_REF__';
 2932:   return $result;
 2933: }
 2934: 
 2935: sub str2hash {
 2936:     my ($string)=@_;
 2937:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2938:     return %$hash;
 2939: }
 2940: 
 2941: sub str2hashref {
 2942:   my ($string) = @_;
 2943: 
 2944:   my %hash;
 2945: 
 2946:   if($string !~ /^__HASH_REF__/) {
 2947:       if (! ($string eq '' || !defined($string))) {
 2948: 	  $hash{'error'}='Not hash reference';
 2949:       }
 2950:       return (\%hash, $string);
 2951:   }
 2952: 
 2953:   $string =~ s/^__HASH_REF__//;
 2954: 
 2955:   while($string !~ /^__END_HASH_REF__/) {
 2956:       #key
 2957:       my $key='';
 2958:       if($string =~ /^__HASH_REF__/) {
 2959:           ($key, $string)=&str2hashref($string);
 2960:           if(defined($key->{'error'})) {
 2961:               $hash{'error'}='Bad data';
 2962:               return (\%hash, $string);
 2963:           }
 2964:       } elsif($string =~ /^__ARRAY_REF__/) {
 2965:           ($key, $string)=&str2arrayref($string);
 2966:           if($key->[0] eq 'Array reference error') {
 2967:               $hash{'error'}='Bad data';
 2968:               return (\%hash, $string);
 2969:           }
 2970:       } else {
 2971:           $string =~ s/^(.*?)=//;
 2972: 	  $key=&unescape($1);
 2973:       }
 2974:       $string =~ s/^=//;
 2975: 
 2976:       #value
 2977:       my $value='';
 2978:       if($string =~ /^__HASH_REF__/) {
 2979:           ($value, $string)=&str2hashref($string);
 2980:           if(defined($value->{'error'})) {
 2981:               $hash{'error'}='Bad data';
 2982:               return (\%hash, $string);
 2983:           }
 2984:       } elsif($string =~ /^__ARRAY_REF__/) {
 2985:           ($value, $string)=&str2arrayref($string);
 2986:           if($value->[0] eq 'Array reference error') {
 2987:               $hash{'error'}='Bad data';
 2988:               return (\%hash, $string);
 2989:           }
 2990:       } else {
 2991: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2992:       }
 2993:       $string =~ s/^&//;
 2994: 
 2995:       $hash{$key}=$value;
 2996:   }
 2997: 
 2998:   $string =~ s/^__END_HASH_REF__//;
 2999: 
 3000:   return (\%hash, $string);
 3001: }
 3002: 
 3003: sub str2array {
 3004:     my ($string)=@_;
 3005:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3006:     return @$array;
 3007: }
 3008: 
 3009: sub str2arrayref {
 3010:   my ($string) = @_;
 3011:   my @array;
 3012: 
 3013:   if($string !~ /^__ARRAY_REF__/) {
 3014:       if (! ($string eq '' || !defined($string))) {
 3015: 	  $array[0]='Array reference error';
 3016:       }
 3017:       return (\@array, $string);
 3018:   }
 3019: 
 3020:   $string =~ s/^__ARRAY_REF__//;
 3021: 
 3022:   while($string !~ /^__END_ARRAY_REF__/) {
 3023:       my $value='';
 3024:       if($string =~ /^__HASH_REF__/) {
 3025:           ($value, $string)=&str2hashref($string);
 3026:           if(defined($value->{'error'})) {
 3027:               $array[0] ='Array reference error';
 3028:               return (\@array, $string);
 3029:           }
 3030:       } elsif($string =~ /^__ARRAY_REF__/) {
 3031:           ($value, $string)=&str2arrayref($string);
 3032:           if($value->[0] eq 'Array reference error') {
 3033:               $array[0] ='Array reference error';
 3034:               return (\@array, $string);
 3035:           }
 3036:       } else {
 3037: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3038:       }
 3039:       $string =~ s/^&//;
 3040: 
 3041:       push(@array, $value);
 3042:   }
 3043: 
 3044:   $string =~ s/^__END_ARRAY_REF__//;
 3045: 
 3046:   return (\@array, $string);
 3047: }
 3048: 
 3049: # -------------------------------------------------------------------Temp Store
 3050: 
 3051: sub tmpreset {
 3052:   my ($symb,$namespace,$domain,$stuname) = @_;
 3053:   if (!$symb) {
 3054:     $symb=&symbread();
 3055:     if (!$symb) { $symb= $env{'request.url'}; }
 3056:   }
 3057:   $symb=escape($symb);
 3058: 
 3059:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3060:   $namespace=~s/\//\_/g;
 3061:   $namespace=~s/\W//g;
 3062: 
 3063:   if (!$domain) { $domain=$env{'user.domain'}; }
 3064:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3065:   if ($domain eq 'public' && $stuname eq 'public') {
 3066:       $stuname=$ENV{'REMOTE_ADDR'};
 3067:   }
 3068:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3069:   my %hash;
 3070:   if (tie(%hash,'GDBM_File',
 3071: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3072: 	  &GDBM_WRCREAT(),0640)) {
 3073:     foreach my $key (keys %hash) {
 3074:       if ($key=~ /:$symb/) {
 3075: 	delete($hash{$key});
 3076:       }
 3077:     }
 3078:   }
 3079: }
 3080: 
 3081: sub tmpstore {
 3082:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3083: 
 3084:   if (!$symb) {
 3085:     $symb=&symbread();
 3086:     if (!$symb) { $symb= $env{'request.url'}; }
 3087:   }
 3088:   $symb=escape($symb);
 3089: 
 3090:   if (!$namespace) {
 3091:     # I don't think we would ever want to store this for a course.
 3092:     # it seems this will only be used if we don't have a course.
 3093:     #$namespace=$env{'request.course.id'};
 3094:     #if (!$namespace) {
 3095:       $namespace=$env{'request.state'};
 3096:     #}
 3097:   }
 3098:   $namespace=~s/\//\_/g;
 3099:   $namespace=~s/\W//g;
 3100:   if (!$domain) { $domain=$env{'user.domain'}; }
 3101:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3102:   if ($domain eq 'public' && $stuname eq 'public') {
 3103:       $stuname=$ENV{'REMOTE_ADDR'};
 3104:   }
 3105:   my $now=time;
 3106:   my %hash;
 3107:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3108:   if (tie(%hash,'GDBM_File',
 3109: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3110: 	  &GDBM_WRCREAT(),0640)) {
 3111:     $hash{"version:$symb"}++;
 3112:     my $version=$hash{"version:$symb"};
 3113:     my $allkeys=''; 
 3114:     foreach my $key (keys(%$storehash)) {
 3115:       $allkeys.=$key.':';
 3116:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3117:     }
 3118:     $hash{"$version:$symb:timestamp"}=$now;
 3119:     $allkeys.='timestamp';
 3120:     $hash{"$version:keys:$symb"}=$allkeys;
 3121:     if (untie(%hash)) {
 3122:       return 'ok';
 3123:     } else {
 3124:       return "error:$!";
 3125:     }
 3126:   } else {
 3127:     return "error:$!";
 3128:   }
 3129: }
 3130: 
 3131: # -----------------------------------------------------------------Temp Restore
 3132: 
 3133: sub tmprestore {
 3134:   my ($symb,$namespace,$domain,$stuname) = @_;
 3135: 
 3136:   if (!$symb) {
 3137:     $symb=&symbread();
 3138:     if (!$symb) { $symb= $env{'request.url'}; }
 3139:   }
 3140:   $symb=escape($symb);
 3141: 
 3142:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3143: 
 3144:   if (!$domain) { $domain=$env{'user.domain'}; }
 3145:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3146:   if ($domain eq 'public' && $stuname eq 'public') {
 3147:       $stuname=$ENV{'REMOTE_ADDR'};
 3148:   }
 3149:   my %returnhash;
 3150:   $namespace=~s/\//\_/g;
 3151:   $namespace=~s/\W//g;
 3152:   my %hash;
 3153:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3154:   if (tie(%hash,'GDBM_File',
 3155: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3156: 	  &GDBM_READER(),0640)) {
 3157:     my $version=$hash{"version:$symb"};
 3158:     $returnhash{'version'}=$version;
 3159:     my $scope;
 3160:     for ($scope=1;$scope<=$version;$scope++) {
 3161:       my $vkeys=$hash{"$scope:keys:$symb"};
 3162:       my @keys=split(/:/,$vkeys);
 3163:       my $key;
 3164:       $returnhash{"$scope:keys"}=$vkeys;
 3165:       foreach $key (@keys) {
 3166: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3167: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3168:       }
 3169:     }
 3170:     if (!(untie(%hash))) {
 3171:       return "error:$!";
 3172:     }
 3173:   } else {
 3174:     return "error:$!";
 3175:   }
 3176:   return %returnhash;
 3177: }
 3178: 
 3179: # ----------------------------------------------------------------------- Store
 3180: 
 3181: sub store {
 3182:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3183:     my $home='';
 3184: 
 3185:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3186: 
 3187:     $symb=&symbclean($symb);
 3188:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3189: 
 3190:     if (!$domain) { $domain=$env{'user.domain'}; }
 3191:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3192: 
 3193:     &devalidate($symb,$stuname,$domain);
 3194: 
 3195:     $symb=escape($symb);
 3196:     if (!$namespace) { 
 3197:        unless ($namespace=$env{'request.course.id'}) { 
 3198:           return ''; 
 3199:        } 
 3200:     }
 3201:     if (!$home) { $home=$env{'user.home'}; }
 3202: 
 3203:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3204:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3205: 
 3206:     my $namevalue='';
 3207:     foreach my $key (keys(%$storehash)) {
 3208:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3209:     }
 3210:     $namevalue=~s/\&$//;
 3211:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3212:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3213: }
 3214: 
 3215: # -------------------------------------------------------------- Critical Store
 3216: 
 3217: sub cstore {
 3218:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3219:     my $home='';
 3220: 
 3221:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3222: 
 3223:     $symb=&symbclean($symb);
 3224:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3225: 
 3226:     if (!$domain) { $domain=$env{'user.domain'}; }
 3227:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3228: 
 3229:     &devalidate($symb,$stuname,$domain);
 3230: 
 3231:     $symb=escape($symb);
 3232:     if (!$namespace) { 
 3233:        unless ($namespace=$env{'request.course.id'}) { 
 3234:           return ''; 
 3235:        } 
 3236:     }
 3237:     if (!$home) { $home=$env{'user.home'}; }
 3238: 
 3239:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3240:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3241: 
 3242:     my $namevalue='';
 3243:     foreach my $key (keys(%$storehash)) {
 3244:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3245:     }
 3246:     $namevalue=~s/\&$//;
 3247:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3248:     return critical
 3249:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3250: }
 3251: 
 3252: # --------------------------------------------------------------------- Restore
 3253: 
 3254: sub restore {
 3255:     my ($symb,$namespace,$domain,$stuname) = @_;
 3256:     my $home='';
 3257: 
 3258:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3259: 
 3260:     if (!$symb) {
 3261:       unless ($symb=escape(&symbread())) { return ''; }
 3262:     } else {
 3263:       $symb=&escape(&symbclean($symb));
 3264:     }
 3265:     if (!$namespace) { 
 3266:        unless ($namespace=$env{'request.course.id'}) { 
 3267:           return ''; 
 3268:        } 
 3269:     }
 3270:     if (!$domain) { $domain=$env{'user.domain'}; }
 3271:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3272:     if (!$home) { $home=$env{'user.home'}; }
 3273:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3274: 
 3275:     my %returnhash=();
 3276:     foreach my $line (split(/\&/,$answer)) {
 3277: 	my ($name,$value)=split(/\=/,$line);
 3278:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3279:     }
 3280:     my $version;
 3281:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3282:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3283:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3284:        }
 3285:     }
 3286:     return %returnhash;
 3287: }
 3288: 
 3289: # ---------------------------------------------------------- Course Description
 3290: 
 3291: sub coursedescription {
 3292:     my ($courseid,$args)=@_;
 3293:     $courseid=~s/^\///;
 3294:     $courseid=~s/\_/\//g;
 3295:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3296:     my $chome=&homeserver($cnum,$cdomain);
 3297:     my $normalid=$cdomain.'_'.$cnum;
 3298:     # need to always cache even if we get errors otherwise we keep 
 3299:     # trying and trying and trying to get the course description.
 3300:     my %envhash=();
 3301:     my %returnhash=();
 3302:     
 3303:     my $expiretime=600;
 3304:     if ($env{'request.course.id'} eq $normalid) {
 3305: 	$expiretime=120;
 3306:     }
 3307: 
 3308:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3309:     if (!$args->{'freshen_cache'}
 3310: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3311: 	foreach my $key (keys(%env)) {
 3312: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3313: 	    my ($setting) = $1;
 3314: 	    $returnhash{$setting} = $env{$key};
 3315: 	}
 3316: 	return %returnhash;
 3317:     }
 3318: 
 3319:     # get the data agin
 3320:     if (!$args->{'one_time'}) {
 3321: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3322:     }
 3323: 
 3324:     if ($chome ne 'no_host') {
 3325:        %returnhash=&dump('environment',$cdomain,$cnum);
 3326:        if (!exists($returnhash{'con_lost'})) {
 3327:            $returnhash{'home'}= $chome;
 3328: 	   $returnhash{'domain'} = $cdomain;
 3329: 	   $returnhash{'num'} = $cnum;
 3330:            if (!defined($returnhash{'type'})) {
 3331:                $returnhash{'type'} = 'Course';
 3332:            }
 3333:            while (my ($name,$value) = each %returnhash) {
 3334:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3335:            }
 3336:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3337:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3338: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3339:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3340:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3341:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3342:        }
 3343:     }
 3344:     if (!$args->{'one_time'}) {
 3345: 	&appenv(%envhash);
 3346:     }
 3347:     return %returnhash;
 3348: }
 3349: 
 3350: # -------------------------------------------------See if a user is privileged
 3351: 
 3352: sub privileged {
 3353:     my ($username,$domain)=@_;
 3354:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3355: 			&homeserver($username,$domain));
 3356:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3357:     my $now=time;
 3358:     if ($rolesdump ne '') {
 3359:         foreach my $entry (split(/&/,$rolesdump)) {
 3360: 	    if ($entry!~/^rolesdef_/) {
 3361: 		my ($area,$role)=split(/=/,$entry);
 3362: 		$area=~s/\_\w\w$//;
 3363: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3364: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3365: 		    my $active=1;
 3366: 		    if ($tend) {
 3367: 			if ($tend<$now) { $active=0; }
 3368: 		    }
 3369: 		    if ($tstart) {
 3370: 			if ($tstart>$now) { $active=0; }
 3371: 		    }
 3372: 		    if ($active) { return 1; }
 3373: 		}
 3374: 	    }
 3375: 	}
 3376:     }
 3377:     return 0;
 3378: }
 3379: 
 3380: # -------------------------------------------------------- Get user privileges
 3381: 
 3382: sub rolesinit {
 3383:     my ($domain,$username,$authhost)=@_;
 3384:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3385:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3386:     my %allroles=();
 3387:     my %allgroups=();   
 3388:     my $now=time;
 3389:     my %userroles = ('user.login.time' => $now);
 3390:     my $group_privs;
 3391: 
 3392:     if ($rolesdump ne '') {
 3393:         foreach my $entry (split(/&/,$rolesdump)) {
 3394: 	  if ($entry!~/^rolesdef_/) {
 3395:             my ($area,$role)=split(/=/,$entry);
 3396: 	    $area=~s/\_\w\w$//;
 3397:             my ($trole,$tend,$tstart,$group_privs);
 3398: 	    if ($role=~/^cr/) { 
 3399: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3400: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3401: 		    ($tend,$tstart)=split('_',$trest);
 3402: 		} else {
 3403: 		    $trole=$role;
 3404: 		}
 3405:             } elsif ($role =~ m|^gr/|) {
 3406:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3407:                 ($trole,$group_privs) = split(/\//,$trole);
 3408:                 $group_privs = &unescape($group_privs);
 3409: 	    } else {
 3410: 		($trole,$tend,$tstart)=split(/_/,$role);
 3411: 	    }
 3412: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3413: 					 $username);
 3414: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3415:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3416:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3417:             if (($area ne '') && ($trole ne '')) {
 3418: 		my $spec=$trole.'.'.$area;
 3419: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3420: 		if ($trole =~ /^cr\//) {
 3421:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3422:                 } elsif ($trole eq 'gr') {
 3423:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3424: 		} else {
 3425:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3426: 		}
 3427:             }
 3428:           }
 3429:         }
 3430:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3431:         $userroles{'user.adv'}    = $adv;
 3432: 	$userroles{'user.author'} = $author;
 3433:         $env{'user.adv'}=$adv;
 3434:     }
 3435:     return \%userroles;  
 3436: }
 3437: 
 3438: sub set_arearole {
 3439:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3440: # log the associated role with the area
 3441:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3442:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3443: }
 3444: 
 3445: sub custom_roleprivs {
 3446:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3447:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3448:     my $homsvr=homeserver($rauthor,$rdomain);
 3449:     if (&hostname($homsvr) ne '') {
 3450:         my ($rdummy,$roledef)=
 3451:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3452:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3453:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3454:             if (defined($syspriv)) {
 3455:                 $$allroles{'cm./'}.=':'.$syspriv;
 3456:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3457:             }
 3458:             if ($tdomain ne '') {
 3459:                 if (defined($dompriv)) {
 3460:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3461:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3462:                 }
 3463:                 if (($trest ne '') && (defined($coursepriv))) {
 3464:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3465:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3466:                 }
 3467:             }
 3468:         }
 3469:     }
 3470: }
 3471: 
 3472: sub group_roleprivs {
 3473:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3474:     my $access = 1;
 3475:     my $now = time;
 3476:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3477:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3478:     if ($access) {
 3479:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3480:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3481:     }
 3482: }
 3483: 
 3484: sub standard_roleprivs {
 3485:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3486:     if (defined($pr{$trole.':s'})) {
 3487:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3488:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3489:     }
 3490:     if ($tdomain ne '') {
 3491:         if (defined($pr{$trole.':d'})) {
 3492:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3493:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3494:         }
 3495:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3496:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3497:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3498:         }
 3499:     }
 3500: }
 3501: 
 3502: sub set_userprivs {
 3503:     my ($userroles,$allroles,$allgroups) = @_; 
 3504:     my $author=0;
 3505:     my $adv=0;
 3506:     my %grouproles = ();
 3507:     if (keys(%{$allgroups}) > 0) {
 3508:         foreach my $role (keys %{$allroles}) {
 3509:             my ($trole,$area,$sec,$extendedarea);
 3510:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3511:                 $trole = $1;
 3512:                 $area = $2;
 3513:                 $sec = $3;
 3514:                 $extendedarea = $area.$sec;
 3515:                 if (exists($$allgroups{$area})) {
 3516:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3517:                         my $spec = $trole.'.'.$extendedarea;
 3518:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3519:                                                 $$allgroups{$area}{$group};
 3520:                     }
 3521:                 }
 3522:             }
 3523:         }
 3524:     }
 3525:     foreach my $group (keys(%grouproles)) {
 3526:         $$allroles{$group} = $grouproles{$group};
 3527:     }
 3528:     foreach my $role (keys(%{$allroles})) {
 3529:         my %thesepriv;
 3530:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3531:         foreach my $item (split(/:/,$$allroles{$role})) {
 3532:             if ($item ne '') {
 3533:                 my ($privilege,$restrictions)=split(/&/,$item);
 3534:                 if ($restrictions eq '') {
 3535:                     $thesepriv{$privilege}='F';
 3536:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3537:                     $thesepriv{$privilege}.=$restrictions;
 3538:                 }
 3539:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3540:             }
 3541:         }
 3542:         my $thesestr='';
 3543:         foreach my $priv (keys(%thesepriv)) {
 3544: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3545: 	}
 3546:         $userroles->{'user.priv.'.$role} = $thesestr;
 3547:     }
 3548:     return ($author,$adv);
 3549: }
 3550: 
 3551: # --------------------------------------------------------------- get interface
 3552: 
 3553: sub get {
 3554:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3555:    my $items='';
 3556:    foreach my $item (@$storearr) {
 3557:        $items.=&escape($item).'&';
 3558:    }
 3559:    $items=~s/\&$//;
 3560:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3561:    if (!$uname) { $uname=$env{'user.name'}; }
 3562:    my $uhome=&homeserver($uname,$udomain);
 3563: 
 3564:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3565:    my @pairs=split(/\&/,$rep);
 3566:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3567:      return @pairs;
 3568:    }
 3569:    my %returnhash=();
 3570:    my $i=0;
 3571:    foreach my $item (@$storearr) {
 3572:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3573:       $i++;
 3574:    }
 3575:    return %returnhash;
 3576: }
 3577: 
 3578: # --------------------------------------------------------------- del interface
 3579: 
 3580: sub del {
 3581:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3582:    my $items='';
 3583:    foreach my $item (@$storearr) {
 3584:        $items.=&escape($item).'&';
 3585:    }
 3586:    $items=~s/\&$//;
 3587:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3588:    if (!$uname) { $uname=$env{'user.name'}; }
 3589:    my $uhome=&homeserver($uname,$udomain);
 3590: 
 3591:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3592: }
 3593: 
 3594: # -------------------------------------------------------------- dump interface
 3595: 
 3596: sub dump {
 3597:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3598:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3599:     if (!$uname) { $uname=$env{'user.name'}; }
 3600:     my $uhome=&homeserver($uname,$udomain);
 3601:     if ($regexp) {
 3602: 	$regexp=&escape($regexp);
 3603:     } else {
 3604: 	$regexp='.';
 3605:     }
 3606:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3607:     my @pairs=split(/\&/,$rep);
 3608:     my %returnhash=();
 3609:     foreach my $item (@pairs) {
 3610: 	my ($key,$value)=split(/=/,$item,2);
 3611: 	$key = &unescape($key);
 3612: 	next if ($key =~ /^error: 2 /);
 3613: 	$returnhash{$key}=&thaw_unescape($value);
 3614:     }
 3615:     return %returnhash;
 3616: }
 3617: 
 3618: # --------------------------------------------------------- dumpstore interface
 3619: 
 3620: sub dumpstore {
 3621:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3622:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3623:    if (!$uname) { $uname=$env{'user.name'}; }
 3624:    my $uhome=&homeserver($uname,$udomain);
 3625:    if ($regexp) {
 3626:        $regexp=&escape($regexp);
 3627:    } else {
 3628:        $regexp='.';
 3629:    }
 3630:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3631:    my @pairs=split(/\&/,$rep);
 3632:    my %returnhash=();
 3633:    foreach my $item (@pairs) {
 3634:        my ($key,$value)=split(/=/,$item,2);
 3635:        next if ($key =~ /^error: 2 /);
 3636:        $returnhash{$key}=&thaw_unescape($value);
 3637:    }
 3638:    return %returnhash;
 3639: }
 3640: 
 3641: # -------------------------------------------------------------- keys interface
 3642: 
 3643: sub getkeys {
 3644:    my ($namespace,$udomain,$uname)=@_;
 3645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3646:    if (!$uname) { $uname=$env{'user.name'}; }
 3647:    my $uhome=&homeserver($uname,$udomain);
 3648:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3649:    my @keyarray=();
 3650:    foreach my $key (split(/\&/,$rep)) {
 3651:       next if ($key =~ /^error: 2 /);
 3652:       push(@keyarray,&unescape($key));
 3653:    }
 3654:    return @keyarray;
 3655: }
 3656: 
 3657: # --------------------------------------------------------------- currentdump
 3658: sub currentdump {
 3659:    my ($courseid,$sdom,$sname)=@_;
 3660:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3661:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3662:    $sname    = $env{'user.name'}         if (! defined($sname));
 3663:    my $uhome = &homeserver($sname,$sdom);
 3664:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3665:    return if ($rep =~ /^(error:|no_such_host)/);
 3666:    #
 3667:    my %returnhash=();
 3668:    #
 3669:    if ($rep eq "unknown_cmd") { 
 3670:        # an old lond will not know currentdump
 3671:        # Do a dump and make it look like a currentdump
 3672:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3673:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3674:        my %hash = @tmp;
 3675:        @tmp=();
 3676:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3677:    } else {
 3678:        my @pairs=split(/\&/,$rep);
 3679:        foreach my $pair (@pairs) {
 3680:            my ($key,$value)=split(/=/,$pair,2);
 3681:            my ($symb,$param) = split(/:/,$key);
 3682:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3683:                                                         &thaw_unescape($value);
 3684:        }
 3685:    }
 3686:    return %returnhash;
 3687: }
 3688: 
 3689: sub convert_dump_to_currentdump{
 3690:     my %hash = %{shift()};
 3691:     my %returnhash;
 3692:     # Code ripped from lond, essentially.  The only difference
 3693:     # here is the unescaping done by lonnet::dump().  Conceivably
 3694:     # we might run in to problems with parameter names =~ /^v\./
 3695:     while (my ($key,$value) = each(%hash)) {
 3696:         my ($v,$symb,$param) = split(/:/,$key);
 3697: 	$symb  = &unescape($symb);
 3698: 	$param = &unescape($param);
 3699:         next if ($v eq 'version' || $symb eq 'keys');
 3700:         next if (exists($returnhash{$symb}) &&
 3701:                  exists($returnhash{$symb}->{$param}) &&
 3702:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3703:         $returnhash{$symb}->{$param}=$value;
 3704:         $returnhash{$symb}->{'v.'.$param}=$v;
 3705:     }
 3706:     #
 3707:     # Remove all of the keys in the hashes which keep track of
 3708:     # the version of the parameter.
 3709:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3710:         # use a foreach because we are going to delete from the hash.
 3711:         foreach my $key (keys(%$param_hash)) {
 3712:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3713:         }
 3714:     }
 3715:     return \%returnhash;
 3716: }
 3717: 
 3718: # ------------------------------------------------------ critical inc interface
 3719: 
 3720: sub cinc {
 3721:     return &inc(@_,'critical');
 3722: }
 3723: 
 3724: # --------------------------------------------------------------- inc interface
 3725: 
 3726: sub inc {
 3727:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3728:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3729:     if (!$uname) { $uname=$env{'user.name'}; }
 3730:     my $uhome=&homeserver($uname,$udomain);
 3731:     my $items='';
 3732:     if (! ref($store)) {
 3733:         # got a single value, so use that instead
 3734:         $items = &escape($store).'=&';
 3735:     } elsif (ref($store) eq 'SCALAR') {
 3736:         $items = &escape($$store).'=&';        
 3737:     } elsif (ref($store) eq 'ARRAY') {
 3738:         $items = join('=&',map {&escape($_);} @{$store});
 3739:     } elsif (ref($store) eq 'HASH') {
 3740:         while (my($key,$value) = each(%{$store})) {
 3741:             $items.= &escape($key).'='.&escape($value).'&';
 3742:         }
 3743:     }
 3744:     $items=~s/\&$//;
 3745:     if ($critical) {
 3746: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3747:     } else {
 3748: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3749:     }
 3750: }
 3751: 
 3752: # --------------------------------------------------------------- put interface
 3753: 
 3754: sub put {
 3755:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3756:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3757:    if (!$uname) { $uname=$env{'user.name'}; }
 3758:    my $uhome=&homeserver($uname,$udomain);
 3759:    my $items='';
 3760:    foreach my $item (keys(%$storehash)) {
 3761:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3762:    }
 3763:    $items=~s/\&$//;
 3764:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3765: }
 3766: 
 3767: # ------------------------------------------------------------ newput interface
 3768: 
 3769: sub newput {
 3770:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3771:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3772:    if (!$uname) { $uname=$env{'user.name'}; }
 3773:    my $uhome=&homeserver($uname,$udomain);
 3774:    my $items='';
 3775:    foreach my $key (keys(%$storehash)) {
 3776:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3777:    }
 3778:    $items=~s/\&$//;
 3779:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3780: }
 3781: 
 3782: # ---------------------------------------------------------  putstore interface
 3783: 
 3784: sub putstore {
 3785:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3787:    if (!$uname) { $uname=$env{'user.name'}; }
 3788:    my $uhome=&homeserver($uname,$udomain);
 3789:    my $items='';
 3790:    foreach my $key (keys(%$storehash)) {
 3791:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3792:    }
 3793:    $items=~s/\&$//;
 3794:    my $esc_symb=&escape($symb);
 3795:    my $esc_v=&escape($version);
 3796:    my $reply =
 3797:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3798: 	      $uhome);
 3799:    if ($reply eq 'unknown_cmd') {
 3800:        # gfall back to way things use to be done
 3801:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3802: 			    $uname);
 3803:    }
 3804:    return $reply;
 3805: }
 3806: 
 3807: sub old_putstore {
 3808:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3809:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3810:     if (!$uname) { $uname=$env{'user.name'}; }
 3811:     my $uhome=&homeserver($uname,$udomain);
 3812:     my %newstorehash;
 3813:     foreach my $item (keys(%$storehash)) {
 3814: 	my $key = $version.':'.&escape($symb).':'.$item;
 3815: 	$newstorehash{$key} = $storehash->{$item};
 3816:     }
 3817:     my $items='';
 3818:     my %allitems = ();
 3819:     foreach my $item (keys(%newstorehash)) {
 3820: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3821: 	    my $key = $1.':keys:'.$2;
 3822: 	    $allitems{$key} .= $3.':';
 3823: 	}
 3824: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3825:     }
 3826:     foreach my $item (keys(%allitems)) {
 3827: 	$allitems{$item} =~ s/\:$//;
 3828: 	$items.= $item.'='.$allitems{$item}.'&';
 3829:     }
 3830:     $items=~s/\&$//;
 3831:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3832: }
 3833: 
 3834: # ------------------------------------------------------ critical put interface
 3835: 
 3836: sub cput {
 3837:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3838:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3839:    if (!$uname) { $uname=$env{'user.name'}; }
 3840:    my $uhome=&homeserver($uname,$udomain);
 3841:    my $items='';
 3842:    foreach my $item (keys(%$storehash)) {
 3843:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3844:    }
 3845:    $items=~s/\&$//;
 3846:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3847: }
 3848: 
 3849: # -------------------------------------------------------------- eget interface
 3850: 
 3851: sub eget {
 3852:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3853:    my $items='';
 3854:    foreach my $item (@$storearr) {
 3855:        $items.=&escape($item).'&';
 3856:    }
 3857:    $items=~s/\&$//;
 3858:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3859:    if (!$uname) { $uname=$env{'user.name'}; }
 3860:    my $uhome=&homeserver($uname,$udomain);
 3861:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3862:    my @pairs=split(/\&/,$rep);
 3863:    my %returnhash=();
 3864:    my $i=0;
 3865:    foreach my $item (@$storearr) {
 3866:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3867:       $i++;
 3868:    }
 3869:    return %returnhash;
 3870: }
 3871: 
 3872: # ------------------------------------------------------------ tmpput interface
 3873: sub tmpput {
 3874:     my ($storehash,$server,$context)=@_;
 3875:     my $items='';
 3876:     foreach my $item (keys(%$storehash)) {
 3877: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3878:     }
 3879:     $items=~s/\&$//;
 3880:     if (defined($context)) {
 3881:         $items .= ':'.&escape($context);
 3882:     }
 3883:     return &reply("tmpput:$items",$server);
 3884: }
 3885: 
 3886: # ------------------------------------------------------------ tmpget interface
 3887: sub tmpget {
 3888:     my ($token,$server)=@_;
 3889:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3890:     my $rep=&reply("tmpget:$token",$server);
 3891:     my %returnhash;
 3892:     foreach my $item (split(/\&/,$rep)) {
 3893: 	my ($key,$value)=split(/=/,$item);
 3894: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3895:     }
 3896:     return %returnhash;
 3897: }
 3898: 
 3899: # ------------------------------------------------------------ tmpget interface
 3900: sub tmpdel {
 3901:     my ($token,$server)=@_;
 3902:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3903:     return &reply("tmpdel:$token",$server);
 3904: }
 3905: 
 3906: # -------------------------------------------------- portfolio access checking
 3907: 
 3908: sub portfolio_access {
 3909:     my ($requrl) = @_;
 3910:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3911:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3912:     if ($result) {
 3913:         my %setters;
 3914:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3915:             my ($startblock,$endblock) =
 3916:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3917:             if ($startblock && $endblock) {
 3918:                 return 'B';
 3919:             }
 3920:         } else {
 3921:             my ($startblock,$endblock) =
 3922:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3923:             if ($startblock && $endblock) {
 3924:                 return 'B';
 3925:             }
 3926:         }
 3927:     }
 3928:     if ($result eq 'ok') {
 3929:        return 'F';
 3930:     } elsif ($result =~ /^[^:]+:guest_/) {
 3931:        return 'A';
 3932:     }
 3933:     return '';
 3934: }
 3935: 
 3936: sub get_portfolio_access {
 3937:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3938: 
 3939:     if (!ref($access_hash)) {
 3940: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3941: 	my %access_controls = &get_access_controls($current_perms,$group,
 3942: 						   $file_name);
 3943: 	$access_hash = $access_controls{$file_name};
 3944:     }
 3945: 
 3946:     my ($public,$guest,@domains,@users,@courses,@groups);
 3947:     my $now = time;
 3948:     if (ref($access_hash) eq 'HASH') {
 3949:         foreach my $key (keys(%{$access_hash})) {
 3950:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3951:             if ($start > $now) {
 3952:                 next;
 3953:             }
 3954:             if ($end && $end<$now) {
 3955:                 next;
 3956:             }
 3957:             if ($scope eq 'public') {
 3958:                 $public = $key;
 3959:                 last;
 3960:             } elsif ($scope eq 'guest') {
 3961:                 $guest = $key;
 3962:             } elsif ($scope eq 'domains') {
 3963:                 push(@domains,$key);
 3964:             } elsif ($scope eq 'users') {
 3965:                 push(@users,$key);
 3966:             } elsif ($scope eq 'course') {
 3967:                 push(@courses,$key);
 3968:             } elsif ($scope eq 'group') {
 3969:                 push(@groups,$key);
 3970:             }
 3971:         }
 3972:         if ($public) {
 3973:             return 'ok';
 3974:         }
 3975:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3976:             if ($guest) {
 3977:                 return $guest;
 3978:             }
 3979:         } else {
 3980:             if (@domains > 0) {
 3981:                 foreach my $domkey (@domains) {
 3982:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3983:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3984:                             return 'ok';
 3985:                         }
 3986:                     }
 3987:                 }
 3988:             }
 3989:             if (@users > 0) {
 3990:                 foreach my $userkey (@users) {
 3991:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3992:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3993:                             if (ref($item) eq 'HASH') {
 3994:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3995:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3996:                                     return 'ok';
 3997:                                 }
 3998:                             }
 3999:                         }
 4000:                     } 
 4001:                 }
 4002:             }
 4003:             my %roleshash;
 4004:             my @courses_and_groups = @courses;
 4005:             push(@courses_and_groups,@groups); 
 4006:             if (@courses_and_groups > 0) {
 4007:                 my (%allgroups,%allroles); 
 4008:                 my ($start,$end,$role,$sec,$group);
 4009:                 foreach my $envkey (%env) {
 4010:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4011:                         my $cid = $2.'_'.$3; 
 4012:                         if ($1 eq 'gr') {
 4013:                             $group = $4;
 4014:                             $allgroups{$cid}{$group} = $env{$envkey};
 4015:                         } else {
 4016:                             if ($4 eq '') {
 4017:                                 $sec = 'none';
 4018:                             } else {
 4019:                                 $sec = $4;
 4020:                             }
 4021:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4022:                         }
 4023:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4024:                         my $cid = $2.'_'.$3;
 4025:                         if ($4 eq '') {
 4026:                             $sec = 'none';
 4027:                         } else {
 4028:                             $sec = $4;
 4029:                         }
 4030:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4031:                     }
 4032:                 }
 4033:                 if (keys(%allroles) == 0) {
 4034:                     return;
 4035:                 }
 4036:                 foreach my $key (@courses_and_groups) {
 4037:                     my %content = %{$$access_hash{$key}};
 4038:                     my $cnum = $content{'number'};
 4039:                     my $cdom = $content{'domain'};
 4040:                     my $cid = $cdom.'_'.$cnum;
 4041:                     if (!exists($allroles{$cid})) {
 4042:                         next;
 4043:                     }    
 4044:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4045:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4046:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4047:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4048:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4049:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4050:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4051:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4052:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4053:                                         if (grep/^all$/,@sections) {
 4054:                                             return 'ok';
 4055:                                         } else {
 4056:                                             if (grep/^$sec$/,@sections) {
 4057:                                                 return 'ok';
 4058:                                             }
 4059:                                         }
 4060:                                     }
 4061:                                 }
 4062:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4063:                                     if (grep/^none$/,@groups) {
 4064:                                         return 'ok';
 4065:                                     }
 4066:                                 } else {
 4067:                                     if (grep/^all$/,@groups) {
 4068:                                         return 'ok';
 4069:                                     } 
 4070:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4071:                                         if (grep/^$group$/,@groups) {
 4072:                                             return 'ok';
 4073:                                         }
 4074:                                     }
 4075:                                 } 
 4076:                             }
 4077:                         }
 4078:                     }
 4079:                 }
 4080:             }
 4081:             if ($guest) {
 4082:                 return $guest;
 4083:             }
 4084:         }
 4085:     }
 4086:     return;
 4087: }
 4088: 
 4089: sub course_group_datechecker {
 4090:     my ($dates,$now,$status) = @_;
 4091:     my ($start,$end) = split(/\./,$dates);
 4092:     if (!$start && !$end) {
 4093:         return 'ok';
 4094:     }
 4095:     if (grep/^active$/,@{$status}) {
 4096:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4097:             return 'ok';
 4098:         }
 4099:     }
 4100:     if (grep/^previous$/,@{$status}) {
 4101:         if ($end > $now ) {
 4102:             return 'ok';
 4103:         }
 4104:     }
 4105:     if (grep/^future$/,@{$status}) {
 4106:         if ($start > $now) {
 4107:             return 'ok';
 4108:         }
 4109:     }
 4110:     return; 
 4111: }
 4112: 
 4113: sub parse_portfolio_url {
 4114:     my ($url) = @_;
 4115: 
 4116:     my ($type,$udom,$unum,$group,$file_name);
 4117:     
 4118:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4119: 	$type = 1;
 4120:         $udom = $1;
 4121:         $unum = $2;
 4122:         $file_name = $3;
 4123:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4124: 	$type = 2;
 4125:         $udom = $1;
 4126:         $unum = $2;
 4127:         $group = $3;
 4128:         $file_name = $3.'/'.$4;
 4129:     }
 4130:     if (wantarray) {
 4131: 	return ($type,$udom,$unum,$file_name,$group);
 4132:     }
 4133:     return $type;
 4134: }
 4135: 
 4136: sub is_portfolio_url {
 4137:     my ($url) = @_;
 4138:     return scalar(&parse_portfolio_url($url));
 4139: }
 4140: 
 4141: sub is_portfolio_file {
 4142:     my ($file) = @_;
 4143:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4144:         return 1;
 4145:     }
 4146:     return;
 4147: }
 4148: 
 4149: 
 4150: # ---------------------------------------------- Custom access rule evaluation
 4151: 
 4152: sub customaccess {
 4153:     my ($priv,$uri)=@_;
 4154:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4155:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4156:     $udom = &LONCAPA::clean_domain($udom);
 4157:     $ucrs = &LONCAPA::clean_username($ucrs);
 4158:     my $access=0;
 4159:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4160: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4161: 	if ($type eq 'user') {
 4162: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4163: 		my ($tdom,$tuname)=split(m{/},$scope);
 4164: 		if ($tdom) {
 4165: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4166: 		}
 4167: 		if ($tuname) {
 4168: 		    if ($tuname ne $env{'user.name'}) { next; }
 4169: 		}
 4170: 		$access=($effect eq 'allow');
 4171: 		last;
 4172: 	    }
 4173: 	} else {
 4174: 	    if ($role) {
 4175: 		if ($role ne $urole) { next; }
 4176: 	    }
 4177: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4178: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4179: 		if ($tdom) {
 4180: 		    if ($tdom ne $udom) { next; }
 4181: 		}
 4182: 		if ($tcrs) {
 4183: 		    if ($tcrs ne $ucrs) { next; }
 4184: 		}
 4185: 		if ($tsec) {
 4186: 		    if ($tsec ne $usec) { next; }
 4187: 		}
 4188: 		$access=($effect eq 'allow');
 4189: 		last;
 4190: 	    }
 4191: 	    if ($realm eq '' && $role eq '') {
 4192: 		$access=($effect eq 'allow');
 4193: 	    }
 4194: 	}
 4195:     }
 4196:     return $access;
 4197: }
 4198: 
 4199: # ------------------------------------------------- Check for a user privilege
 4200: 
 4201: sub allowed {
 4202:     my ($priv,$uri,$symb,$role)=@_;
 4203:     my $ver_orguri=$uri;
 4204:     $uri=&deversion($uri);
 4205:     my $orguri=$uri;
 4206:     $uri=&declutter($uri);
 4207: 
 4208:     if ($priv eq 'evb') {
 4209: # Evade communication block restrictions for specified role in a course
 4210:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4211:             return $1;
 4212:         } else {
 4213:             return;
 4214:         }
 4215:     }
 4216: 
 4217:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4218: # Free bre access to adm and meta resources
 4219:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4220: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4221: 	&& ($priv eq 'bre')) {
 4222: 	return 'F';
 4223:     }
 4224: 
 4225: # Free bre access to user's own portfolio contents
 4226:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4227:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4228: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4229:         my %setters;
 4230:         my ($startblock,$endblock) = 
 4231:             &Apache::loncommon::blockcheck(\%setters,'port');
 4232:         if ($startblock && $endblock) {
 4233:             return 'B';
 4234:         } else {
 4235:             return 'F';
 4236:         }
 4237:     }
 4238: 
 4239: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4240:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4241:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4242:         if (exists($env{'request.course.id'})) {
 4243:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4244:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4245:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4246:                 my $courseprivid=$env{'request.course.id'};
 4247:                 $courseprivid=~s/\_/\//;
 4248:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4249:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4250:                     return $1; 
 4251:                 } else {
 4252:                     if ($env{'request.course.sec'}) {
 4253:                         $courseprivid.='/'.$env{'request.course.sec'};
 4254:                     }
 4255:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4256:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4257:                         return $2;
 4258:                     }
 4259:                 }
 4260:             }
 4261:         }
 4262:     }
 4263: 
 4264: # Free bre to public access
 4265: 
 4266:     if ($priv eq 'bre') {
 4267:         my $copyright=&metadata($uri,'copyright');
 4268: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4269:            return 'F'; 
 4270:         }
 4271:         if ($copyright eq 'priv') {
 4272:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4273: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4274: 		return '';
 4275:             }
 4276:         }
 4277:         if ($copyright eq 'domain') {
 4278:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4279: 	    unless (($env{'user.domain'} eq $1) ||
 4280:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4281: 		return '';
 4282:             }
 4283:         }
 4284:         if ($env{'request.role'}=~ /li\.\//) {
 4285:             # Library role, so allow browsing of resources in this domain.
 4286:             return 'F';
 4287:         }
 4288:         if ($copyright eq 'custom') {
 4289: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4290:         }
 4291:     }
 4292:     # Domain coordinator is trying to create a course
 4293:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4294:         # uri is the requested domain in this case.
 4295:         # comparison to 'request.role.domain' shows if the user has selected
 4296:         # a role of dc for the domain in question.
 4297:         return 'F' if ($uri eq $env{'request.role.domain'});
 4298:     }
 4299: 
 4300:     my $thisallowed='';
 4301:     my $statecond=0;
 4302:     my $courseprivid='';
 4303: 
 4304: # Course
 4305: 
 4306:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4307:        $thisallowed.=$1;
 4308:     }
 4309: 
 4310: # Domain
 4311: 
 4312:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4313:        =~/\Q$priv\E\&([^\:]*)/) {
 4314:        $thisallowed.=$1;
 4315:     }
 4316: 
 4317: # Course: uri itself is a course
 4318:     my $courseuri=$uri;
 4319:     $courseuri=~s/\_(\d)/\/$1/;
 4320:     $courseuri=~s/^([^\/])/\/$1/;
 4321: 
 4322:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4323:        =~/\Q$priv\E\&([^\:]*)/) {
 4324:        $thisallowed.=$1;
 4325:     }
 4326: 
 4327: # URI is an uploaded document for this course, default permissions don't matter
 4328: # not allowing 'edit' access (editupload) to uploaded course docs
 4329:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4330: 	$thisallowed='';
 4331:         my ($match)=&is_on_map($uri);
 4332:         if ($match) {
 4333:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4334:                   =~/\Q$priv\E\&([^\:]*)/) {
 4335:                 $thisallowed.=$1;
 4336:             }
 4337:         } else {
 4338:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4339:             if ($refuri) {
 4340:                 if ($refuri =~ m|^/adm/|) {
 4341:                     $thisallowed='F';
 4342:                 } else {
 4343:                     $refuri=&declutter($refuri);
 4344:                     my ($match) = &is_on_map($refuri);
 4345:                     if ($match) {
 4346:                         $thisallowed='F';
 4347:                     }
 4348:                 }
 4349:             }
 4350:         }
 4351:     }
 4352: 
 4353:     if ($priv eq 'bre'
 4354: 	&& $thisallowed ne 'F' 
 4355: 	&& $thisallowed ne '2'
 4356: 	&& &is_portfolio_url($uri)) {
 4357: 	$thisallowed = &portfolio_access($uri);
 4358:     }
 4359:     
 4360: # Full access at system, domain or course-wide level? Exit.
 4361: 
 4362:     if ($thisallowed=~/F/) {
 4363: 	return 'F';
 4364:     }
 4365: 
 4366: # If this is generating or modifying users, exit with special codes
 4367: 
 4368:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4369: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4370: 	    my ($audom,$auname)=split('/',$uri);
 4371: # no author name given, so this just checks on the general right to make a co-author in this domain
 4372: 	    unless ($auname) { return $thisallowed; }
 4373: # an author name is given, so we are about to actually make a co-author for a certain account
 4374: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4375: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4376: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4377: 	}
 4378: 	return $thisallowed;
 4379:     }
 4380: #
 4381: # Gathered so far: system, domain and course wide privileges
 4382: #
 4383: # Course: See if uri or referer is an individual resource that is part of 
 4384: # the course
 4385: 
 4386:     if ($env{'request.course.id'}) {
 4387: 
 4388:        $courseprivid=$env{'request.course.id'};
 4389:        if ($env{'request.course.sec'}) {
 4390:           $courseprivid.='/'.$env{'request.course.sec'};
 4391:        }
 4392:        $courseprivid=~s/\_/\//;
 4393:        my $checkreferer=1;
 4394:        my ($match,$cond)=&is_on_map($uri);
 4395:        if ($match) {
 4396:            $statecond=$cond;
 4397:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4398:                =~/\Q$priv\E\&([^\:]*)/) {
 4399:                $thisallowed.=$1;
 4400:                $checkreferer=0;
 4401:            }
 4402:        }
 4403:        
 4404:        if ($checkreferer) {
 4405: 	  my $refuri=$env{'httpref.'.$orguri};
 4406:             unless ($refuri) {
 4407:                 foreach my $key (keys(%env)) {
 4408: 		    if ($key=~/^httpref\..*\*/) {
 4409: 			my $pattern=$key;
 4410:                         $pattern=~s/^httpref\.\/res\///;
 4411:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4412:                         $pattern=~s/\//\\\//g;
 4413:                         if ($orguri=~/$pattern/) {
 4414: 			    $refuri=$env{$key};
 4415:                         }
 4416:                     }
 4417:                 }
 4418:             }
 4419: 
 4420:          if ($refuri) { 
 4421: 	  $refuri=&declutter($refuri);
 4422:           my ($match,$cond)=&is_on_map($refuri);
 4423:             if ($match) {
 4424:               my $refstatecond=$cond;
 4425:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4426:                   =~/\Q$priv\E\&([^\:]*)/) {
 4427:                   $thisallowed.=$1;
 4428:                   $uri=$refuri;
 4429:                   $statecond=$refstatecond;
 4430:               }
 4431:           }
 4432:         }
 4433:        }
 4434:    }
 4435: 
 4436: #
 4437: # Gathered now: all privileges that could apply, and condition number
 4438: # 
 4439: #
 4440: # Full or no access?
 4441: #
 4442: 
 4443:     if ($thisallowed=~/F/) {
 4444: 	return 'F';
 4445:     }
 4446: 
 4447:     unless ($thisallowed) {
 4448:         return '';
 4449:     }
 4450: 
 4451: # Restrictions exist, deal with them
 4452: #
 4453: #   C:according to course preferences
 4454: #   R:according to resource settings
 4455: #   L:unless locked
 4456: #   X:according to user session state
 4457: #
 4458: 
 4459: # Possibly locked functionality, check all courses
 4460: # Locks might take effect only after 10 minutes cache expiration for other
 4461: # courses, and 2 minutes for current course
 4462: 
 4463:     my $envkey;
 4464:     if ($thisallowed=~/L/) {
 4465:         foreach $envkey (keys %env) {
 4466:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4467:                my $courseid=$2;
 4468:                my $roleid=$1.'.'.$2;
 4469:                $courseid=~s/^\///;
 4470:                my $expiretime=600;
 4471:                if ($env{'request.role'} eq $roleid) {
 4472: 		  $expiretime=120;
 4473:                }
 4474: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4475:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4476:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4477: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4478:                }
 4479:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4480:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4481: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4482:                        &log($env{'user.domain'},$env{'user.name'},
 4483:                             $env{'user.home'},
 4484:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4485:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4486:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4487: 		       return '';
 4488:                    }
 4489:                }
 4490:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4491:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4492: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4493:                        &log($env{'user.domain'},$env{'user.name'},
 4494:                             $env{'user.home'},
 4495:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4496:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4497:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4498: 		       return '';
 4499:                    }
 4500:                }
 4501: 	   }
 4502:        }
 4503:     }
 4504:    
 4505: #
 4506: # Rest of the restrictions depend on selected course
 4507: #
 4508: 
 4509:     unless ($env{'request.course.id'}) {
 4510: 	if ($thisallowed eq 'A') {
 4511: 	    return 'A';
 4512:         } elsif ($thisallowed eq 'B') {
 4513:             return 'B';
 4514: 	} else {
 4515: 	    return '1';
 4516: 	}
 4517:     }
 4518: 
 4519: #
 4520: # Now user is definitely in a course
 4521: #
 4522: 
 4523: 
 4524: # Course preferences
 4525: 
 4526:    if ($thisallowed=~/C/) {
 4527:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4528:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4529:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4530: 	   =~/\Q$rolecode\E/) {
 4531: 	   if ($priv ne 'pch') { 
 4532: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4533: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4534: 			$env{'request.course.id'});
 4535: 	   }
 4536:            return '';
 4537:        }
 4538: 
 4539:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4540: 	   =~/\Q$unamedom\E/) {
 4541: 	   if ($priv ne 'pch') { 
 4542: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4543: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4544: 			$env{'request.course.id'});
 4545: 	   }
 4546:            return '';
 4547:        }
 4548:    }
 4549: 
 4550: # Resource preferences
 4551: 
 4552:    if ($thisallowed=~/R/) {
 4553:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4554:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4555: 	   if ($priv ne 'pch') { 
 4556: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4557: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4558: 	   }
 4559: 	   return '';
 4560:        }
 4561:    }
 4562: 
 4563: # Restricted by state or randomout?
 4564: 
 4565:    if ($thisallowed=~/X/) {
 4566:       if ($env{'acc.randomout'}) {
 4567: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4568:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4569:             return ''; 
 4570:          }
 4571:       }
 4572:       if (&condval($statecond)) {
 4573: 	 return '2';
 4574:       } else {
 4575:          return '';
 4576:       }
 4577:    }
 4578: 
 4579:     if ($thisallowed eq 'A') {
 4580: 	return 'A';
 4581:     } elsif ($thisallowed eq 'B') {
 4582:         return 'B';
 4583:     }
 4584:    return 'F';
 4585: }
 4586: 
 4587: sub split_uri_for_cond {
 4588:     my $uri=&deversion(&declutter(shift));
 4589:     my @uriparts=split(/\//,$uri);
 4590:     my $filename=pop(@uriparts);
 4591:     my $pathname=join('/',@uriparts);
 4592:     return ($pathname,$filename);
 4593: }
 4594: # --------------------------------------------------- Is a resource on the map?
 4595: 
 4596: sub is_on_map {
 4597:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4598:     #Trying to find the conditional for the file
 4599:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4600: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4601:     if ($match) {
 4602: 	return (1,$1);
 4603:     } else {
 4604: 	return (0,0);
 4605:     }
 4606: }
 4607: 
 4608: # --------------------------------------------------------- Get symb from alias
 4609: 
 4610: sub get_symb_from_alias {
 4611:     my $symb=shift;
 4612:     my ($map,$resid,$url)=&decode_symb($symb);
 4613: # Already is a symb
 4614:     if ($url) { return $symb; }
 4615: # Must be an alias
 4616:     my $aliassymb='';
 4617:     my %bighash;
 4618:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4619:                             &GDBM_READER(),0640)) {
 4620:         my $rid=$bighash{'mapalias_'.$symb};
 4621: 	if ($rid) {
 4622: 	    my ($mapid,$resid)=split(/\./,$rid);
 4623: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4624: 				    $resid,$bighash{'src_'.$rid});
 4625: 	}
 4626:         untie %bighash;
 4627:     }
 4628:     return $aliassymb;
 4629: }
 4630: 
 4631: # ----------------------------------------------------------------- Define Role
 4632: 
 4633: sub definerole {
 4634:   if (allowed('mcr','/')) {
 4635:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4636:     foreach my $role (split(':',$sysrole)) {
 4637: 	my ($crole,$cqual)=split(/\&/,$role);
 4638:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4639:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4640: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4641:                return "refused:s:$crole&$cqual"; 
 4642:             }
 4643:         }
 4644:     }
 4645:     foreach my $role (split(':',$domrole)) {
 4646: 	my ($crole,$cqual)=split(/\&/,$role);
 4647:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4648:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4649: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4650:                return "refused:d:$crole&$cqual"; 
 4651:             }
 4652:         }
 4653:     }
 4654:     foreach my $role (split(':',$courole)) {
 4655: 	my ($crole,$cqual)=split(/\&/,$role);
 4656:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4657:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4658: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4659:                return "refused:c:$crole&$cqual"; 
 4660:             }
 4661:         }
 4662:     }
 4663:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4664:                 "$env{'user.domain'}:$env{'user.name'}:".
 4665: 	        "rolesdef_$rolename=".
 4666:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4667:     return reply($command,$env{'user.home'});
 4668:   } else {
 4669:     return 'refused';
 4670:   }
 4671: }
 4672: 
 4673: # ---------------- Make a metadata query against the network of library servers
 4674: 
 4675: sub metadata_query {
 4676:     my ($query,$custom,$customshow,$server_array)=@_;
 4677:     my %rhash;
 4678:     my %libserv = &all_library();
 4679:     my @server_list = (defined($server_array) ? @$server_array
 4680:                                               : keys(%libserv) );
 4681:     for my $server (@server_list) {
 4682: 	unless ($custom or $customshow) {
 4683: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4684: 	    $rhash{$server}=$reply;
 4685: 	}
 4686: 	else {
 4687: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4688: 			     &escape($custom).':'.&escape($customshow),
 4689: 			     $server);
 4690: 	    $rhash{$server}=$reply;
 4691: 	}
 4692:     }
 4693:     return \%rhash;
 4694: }
 4695: 
 4696: # ----------------------------------------- Send log queries and wait for reply
 4697: 
 4698: sub log_query {
 4699:     my ($uname,$udom,$query,%filters)=@_;
 4700:     my $uhome=&homeserver($uname,$udom);
 4701:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4702:     my $uhost=&hostname($uhome);
 4703:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4704:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4705:                        $uhome);
 4706:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4707:     return get_query_reply($queryid);
 4708: }
 4709: 
 4710: # -------------------------- Update MySQL table for portfolio file
 4711: 
 4712: sub update_portfolio_table {
 4713:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4714:     my $homeserver = &homeserver($uname,$udom);
 4715:     my $queryid=
 4716:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4717:                ':'.&escape($file_name).':'.$action,$homeserver);
 4718:     my $reply = &get_query_reply($queryid);
 4719:     return $reply;
 4720: }
 4721: 
 4722: # -------------------------- Update MySQL allusers table
 4723: 
 4724: sub update_allusers_table {
 4725:     my ($uname,$udom,$names) = @_;
 4726:     my $homeserver = &homeserver($uname,$udom);
 4727:     my $queryid=
 4728:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4729:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4730:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4731:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4732:                'generation='.&escape($names->{'generation'}).'%%'.
 4733:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4734:                'id='.&escape($names->{'id'}),$homeserver);
 4735:     my $reply = &get_query_reply($queryid);
 4736:     return $reply;
 4737: }
 4738: 
 4739: # ------- Request retrieval of institutional classlists for course(s)
 4740: 
 4741: sub fetch_enrollment_query {
 4742:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4743:     my $homeserver;
 4744:     my $maxtries = 1;
 4745:     if ($context eq 'automated') {
 4746:         $homeserver = $perlvar{'lonHostID'};
 4747:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4748:     } else {
 4749:         $homeserver = &homeserver($cnum,$dom);
 4750:     }
 4751:     my $host=&hostname($homeserver);
 4752:     my $cmd = '';
 4753:     foreach my $affiliate (keys %{$affiliatesref}) {
 4754:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4755:     }
 4756:     $cmd =~ s/%%$//;
 4757:     $cmd = &escape($cmd);
 4758:     my $query = 'fetchenrollment';
 4759:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4760:     unless ($queryid=~/^\Q$host\E\_/) { 
 4761:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4762:         return 'error: '.$queryid;
 4763:     }
 4764:     my $reply = &get_query_reply($queryid);
 4765:     my $tries = 1;
 4766:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4767:         $reply = &get_query_reply($queryid);
 4768:         $tries ++;
 4769:     }
 4770:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4771:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4772:     } else {
 4773:         my @responses = split(/:/,$reply);
 4774:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4775:             foreach my $line (@responses) {
 4776:                 my ($key,$value) = split(/=/,$line,2);
 4777:                 $$replyref{$key} = $value;
 4778:             }
 4779:         } else {
 4780:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4781:             foreach my $line (@responses) {
 4782:                 my ($key,$value) = split(/=/,$line);
 4783:                 $$replyref{$key} = $value;
 4784:                 if ($value > 0) {
 4785:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4786:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4787:                         my $destname = $pathname.'/'.$filename;
 4788:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4789:                         if ($xml_classlist =~ /^error/) {
 4790:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4791:                         } else {
 4792:                             if ( open(FILE,">$destname") ) {
 4793:                                 print FILE &unescape($xml_classlist);
 4794:                                 close(FILE);
 4795:                             } else {
 4796:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4797:                             }
 4798:                         }
 4799:                     }
 4800:                 }
 4801:             }
 4802:         }
 4803:         return 'ok';
 4804:     }
 4805:     return 'error';
 4806: }
 4807: 
 4808: sub get_query_reply {
 4809:     my $queryid=shift;
 4810:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4811:     my $reply='';
 4812:     for (1..100) {
 4813: 	sleep 2;
 4814:         if (-e $replyfile.'.end') {
 4815: 	    if (open(my $fh,$replyfile)) {
 4816: 		$reply = join('',<$fh>);
 4817: 		close($fh);
 4818: 	   } else { return 'error: reply_file_error'; }
 4819:            return &unescape($reply);
 4820: 	}
 4821:     }
 4822:     return 'timeout:'.$queryid;
 4823: }
 4824: 
 4825: sub courselog_query {
 4826: #
 4827: # possible filters:
 4828: # url: url or symb
 4829: # username
 4830: # domain
 4831: # action: view, submit, grade
 4832: # start: timestamp
 4833: # end: timestamp
 4834: #
 4835:     my (%filters)=@_;
 4836:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4837:     if ($filters{'url'}) {
 4838: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4839:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4840:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4841:     }
 4842:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4843:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4844:     return &log_query($cname,$cdom,'courselog',%filters);
 4845: }
 4846: 
 4847: sub userlog_query {
 4848: #
 4849: # possible filters:
 4850: # action: log check role
 4851: # start: timestamp
 4852: # end: timestamp
 4853: #
 4854:     my ($uname,$udom,%filters)=@_;
 4855:     return &log_query($uname,$udom,'userlog',%filters);
 4856: }
 4857: 
 4858: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4859: 
 4860: sub auto_run {
 4861:     my ($cnum,$cdom) = @_;
 4862:     my $response = 0;
 4863:     my $settings;
 4864:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4865:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4866:         $settings = $domconfig{'autoenroll'};
 4867:         if ($settings->{'run'} eq '1') {
 4868:             $response = 1;
 4869:         }
 4870:     } else {
 4871:         my $homeserver;
 4872:         if (&is_course($cdom,$cnum)) {
 4873:             $homeserver = &homeserver($cnum,$cdom);
 4874:         } else {
 4875:             $homeserver = &domain($cdom,'primary');
 4876:         }
 4877:         if ($homeserver ne 'no_host') {
 4878:             $response = &reply('autorun:'.$cdom,$homeserver);
 4879:         }
 4880:     }
 4881:     return $response;
 4882: }
 4883: 
 4884: sub auto_get_sections {
 4885:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4886:     my $homeserver = &homeserver($cnum,$cdom);
 4887:     my @secs = ();
 4888:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4889:     unless ($response eq 'refused') {
 4890:         @secs = split(/:/,$response);
 4891:     }
 4892:     return @secs;
 4893: }
 4894: 
 4895: sub auto_new_course {
 4896:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4897:     my $homeserver = &homeserver($cnum,$cdom);
 4898:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4899:     return $response;
 4900: }
 4901: 
 4902: sub auto_validate_courseID {
 4903:     my ($cnum,$cdom,$inst_course_id) = @_;
 4904:     my $homeserver = &homeserver($cnum,$cdom);
 4905:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4906:     return $response;
 4907: }
 4908: 
 4909: sub auto_create_password {
 4910:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4911:     my ($homeserver,$response);
 4912:     my $create_passwd = 0;
 4913:     my $authchk = '';
 4914:     if ($udom =~ /^$match_domain$/) {
 4915:         $homeserver = &domain($udom,'primary');
 4916:     }
 4917:     if ($homeserver eq '') {
 4918:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4919:             $homeserver = &homeserver($cnum,$cdom);
 4920:         }
 4921:     }
 4922:     if ($homeserver eq '') {
 4923:         $authchk = 'nodomain';
 4924:     } else {
 4925:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4926:         if ($response eq 'refused') {
 4927:             $authchk = 'refused';
 4928:         } else {
 4929:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 4930:         }
 4931:     }
 4932:     return ($authparam,$create_passwd,$authchk);
 4933: }
 4934: 
 4935: sub auto_photo_permission {
 4936:     my ($cnum,$cdom,$students) = @_;
 4937:     my $homeserver = &homeserver($cnum,$cdom);
 4938:     my ($outcome,$perm_reqd,$conditions) = 
 4939: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4940:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4941: 	return (undef,undef);
 4942:     }
 4943:     return ($outcome,$perm_reqd,$conditions);
 4944: }
 4945: 
 4946: sub auto_checkphotos {
 4947:     my ($uname,$udom,$pid) = @_;
 4948:     my $homeserver = &homeserver($uname,$udom);
 4949:     my ($result,$resulttype);
 4950:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4951: 				   &escape($uname).':'.&escape($pid),
 4952: 				   $homeserver));
 4953:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4954: 	return (undef,undef);
 4955:     }
 4956:     if ($outcome) {
 4957:         ($result,$resulttype) = split(/:/,$outcome);
 4958:     } 
 4959:     return ($result,$resulttype);
 4960: }
 4961: 
 4962: sub auto_photochoice {
 4963:     my ($cnum,$cdom) = @_;
 4964:     my $homeserver = &homeserver($cnum,$cdom);
 4965:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4966: 						       &escape($cdom),
 4967: 						       $homeserver)));
 4968:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4969: 	return (undef,undef);
 4970:     }
 4971:     return ($update,$comment);
 4972: }
 4973: 
 4974: sub auto_photoupdate {
 4975:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4976:     my $homeserver = &homeserver($cnum,$dom);
 4977:     my $host=&hostname($homeserver);
 4978:     my $cmd = '';
 4979:     my $maxtries = 1;
 4980:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4981:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4982:     }
 4983:     $cmd =~ s/%%$//;
 4984:     $cmd = &escape($cmd);
 4985:     my $query = 'institutionalphotos';
 4986:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4987:     unless ($queryid=~/^\Q$host\E\_/) {
 4988:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4989:         return 'error: '.$queryid;
 4990:     }
 4991:     my $reply = &get_query_reply($queryid);
 4992:     my $tries = 1;
 4993:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4994:         $reply = &get_query_reply($queryid);
 4995:         $tries ++;
 4996:     }
 4997:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4998:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4999:     } else {
 5000:         my @responses = split(/:/,$reply);
 5001:         my $outcome = shift(@responses); 
 5002:         foreach my $item (@responses) {
 5003:             my ($key,$value) = split(/=/,$item);
 5004:             $$photo{$key} = $value;
 5005:         }
 5006:         return $outcome;
 5007:     }
 5008:     return 'error';
 5009: }
 5010: 
 5011: sub auto_instcode_format {
 5012:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5013: 	$cat_order) = @_;
 5014:     my $courses = '';
 5015:     my @homeservers;
 5016:     if ($caller eq 'global') {
 5017: 	my %servers = &get_servers($codedom,'library');
 5018: 	foreach my $tryserver (keys(%servers)) {
 5019: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5020: 		push(@homeservers,$tryserver);
 5021: 	    }
 5022:         }
 5023:     } else {
 5024:         push(@homeservers,&homeserver($caller,$codedom));
 5025:     }
 5026:     foreach my $code (keys(%{$instcodes})) {
 5027:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5028:     }
 5029:     chop($courses);
 5030:     my $ok_response = 0;
 5031:     my $response;
 5032:     while (@homeservers > 0 && $ok_response == 0) {
 5033:         my $server = shift(@homeservers); 
 5034:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5035:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5036:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5037: 		split(/:/,$response);
 5038:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5039:             push(@{$codetitles},&str2array($codetitles_str));
 5040:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5041:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5042:             $ok_response = 1;
 5043:         }
 5044:     }
 5045:     if ($ok_response) {
 5046:         return 'ok';
 5047:     } else {
 5048:         return $response;
 5049:     }
 5050: }
 5051: 
 5052: sub auto_instcode_defaults {
 5053:     my ($domain,$returnhash,$code_order) = @_;
 5054:     my @homeservers;
 5055: 
 5056:     my %servers = &get_servers($domain,'library');
 5057:     foreach my $tryserver (keys(%servers)) {
 5058: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5059: 	    push(@homeservers,$tryserver);
 5060: 	}
 5061:     }
 5062: 
 5063:     my $response;
 5064:     foreach my $server (@homeservers) {
 5065:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5066:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5067: 	
 5068: 	foreach my $pair (split(/\&/,$response)) {
 5069: 	    my ($name,$value)=split(/\=/,$pair);
 5070: 	    if ($name eq 'code_order') {
 5071: 		@{$code_order} = split(/\&/,&unescape($value));
 5072: 	    } else {
 5073: 		$returnhash->{&unescape($name)}=&unescape($value);
 5074: 	    }
 5075: 	}
 5076: 	return 'ok';
 5077:     }
 5078: 
 5079:     return $response;
 5080: } 
 5081: 
 5082: sub auto_validate_class_sec {
 5083:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5084:     my $homeserver = &homeserver($cnum,$cdom);
 5085:     my $ownerlist;
 5086:     if (ref($owners) eq 'ARRAY') {
 5087:         $ownerlist = join(',',@{$owners});
 5088:     } else {
 5089:         $ownerlist = $owners;
 5090:     }
 5091:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5092:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5093:     return $response;
 5094: }
 5095: 
 5096: # ------------------------------------------------------- Course Group routines
 5097: 
 5098: sub get_coursegroups {
 5099:     my ($cdom,$cnum,$group,$namespace) = @_;
 5100:     return(&dump($namespace,$cdom,$cnum,$group));
 5101: }
 5102: 
 5103: sub modify_coursegroup {
 5104:     my ($cdom,$cnum,$groupsettings) = @_;
 5105:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5106: }
 5107: 
 5108: sub toggle_coursegroup_status {
 5109:     my ($cdom,$cnum,$group,$action) = @_;
 5110:     my ($from_namespace,$to_namespace);
 5111:     if ($action eq 'delete') {
 5112:         $from_namespace = 'coursegroups';
 5113:         $to_namespace = 'deleted_groups';
 5114:     } else {
 5115:         $from_namespace = 'deleted_groups';
 5116:         $to_namespace = 'coursegroups';
 5117:     }
 5118:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5119:     if (my $tmp = &error(%curr_group)) {
 5120:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5121:         return ('read error',$tmp);
 5122:     } else {
 5123:         my %savedsettings = %curr_group; 
 5124:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5125:         my $deloutcome;
 5126:         if ($result eq 'ok') {
 5127:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5128:         } else {
 5129:             return ('write error',$result);
 5130:         }
 5131:         if ($deloutcome eq 'ok') {
 5132:             return 'ok';
 5133:         } else {
 5134:             return ('delete error',$deloutcome);
 5135:         }
 5136:     }
 5137: }
 5138: 
 5139: sub modify_group_roles {
 5140:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5141:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5142:     my $role = 'gr/'.&escape($userprivs);
 5143:     my ($uname,$udom) = split(/:/,$user);
 5144:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5145:     if ($result eq 'ok') {
 5146:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5147:     }
 5148:     return $result;
 5149: }
 5150: 
 5151: sub modify_coursegroup_membership {
 5152:     my ($cdom,$cnum,$membership) = @_;
 5153:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5154:     return $result;
 5155: }
 5156: 
 5157: sub get_active_groups {
 5158:     my ($udom,$uname,$cdom,$cnum) = @_;
 5159:     my $now = time;
 5160:     my %groups = ();
 5161:     foreach my $key (keys(%env)) {
 5162:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5163:             my ($start,$end) = split(/\./,$env{$key});
 5164:             if (($end!=0) && ($end<$now)) { next; }
 5165:             if (($start!=0) && ($start>$now)) { next; }
 5166:             if ($1 eq $cdom && $2 eq $cnum) {
 5167:                 $groups{$3} = $env{$key} ;
 5168:             }
 5169:         }
 5170:     }
 5171:     return %groups;
 5172: }
 5173: 
 5174: sub get_group_membership {
 5175:     my ($cdom,$cnum,$group) = @_;
 5176:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5177: }
 5178: 
 5179: sub get_users_groups {
 5180:     my ($udom,$uname,$courseid) = @_;
 5181:     my @usersgroups;
 5182:     my $cachetime=1800;
 5183: 
 5184:     my $hashid="$udom:$uname:$courseid";
 5185:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5186:     if (defined($cached)) {
 5187:         @usersgroups = split(/:/,$grouplist);
 5188:     } else {  
 5189:         $grouplist = '';
 5190:         my $courseurl = &courseid_to_courseurl($courseid);
 5191:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5192:         my $access_end = $env{'course.'.$courseid.
 5193:                               '.default_enrollment_end_date'};
 5194:         my $now = time;
 5195:         foreach my $key (keys(%roleshash)) {
 5196:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5197:                 my $group = $1;
 5198:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5199:                     my $start = $2;
 5200:                     my $end = $1;
 5201:                     if ($start == -1) { next; } # deleted from group
 5202:                     if (($start!=0) && ($start>$now)) { next; }
 5203:                     if (($end!=0) && ($end<$now)) {
 5204:                         if ($access_end && $access_end < $now) {
 5205:                             if ($access_end - $end < 86400) {
 5206:                                 push(@usersgroups,$group);
 5207:                             }
 5208:                         }
 5209:                         next;
 5210:                     }
 5211:                     push(@usersgroups,$group);
 5212:                 }
 5213:             }
 5214:         }
 5215:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5216:         $grouplist = join(':',@usersgroups);
 5217:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5218:     }
 5219:     return @usersgroups;
 5220: }
 5221: 
 5222: sub devalidate_getgroups_cache {
 5223:     my ($udom,$uname,$cdom,$cnum)=@_;
 5224:     my $courseid = $cdom.'_'.$cnum;
 5225: 
 5226:     my $hashid="$udom:$uname:$courseid";
 5227:     &devalidate_cache_new('getgroups',$hashid);
 5228: }
 5229: 
 5230: # ------------------------------------------------------------------ Plain Text
 5231: 
 5232: sub plaintext {
 5233:     my ($short,$type,$cid) = @_;
 5234:     if ($short =~ /^cr/) {
 5235: 	return (split('/',$short))[-1];
 5236:     }
 5237:     if (!defined($cid)) {
 5238:         $cid = $env{'request.course.id'};
 5239:     }
 5240:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5241:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5242:                                           '.plaintext'});
 5243:     }
 5244:     my %rolenames = (
 5245:                       Course => 'std',
 5246:                       Group => 'alt1',
 5247:                     );
 5248:     if (defined($type) && 
 5249:          defined($rolenames{$type}) && 
 5250:          defined($prp{$short}{$rolenames{$type}})) {
 5251:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5252:     } else {
 5253:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5254:     }
 5255: }
 5256: 
 5257: # ----------------------------------------------------------------- Assign Role
 5258: 
 5259: sub assignrole {
 5260:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 5261:     my $mrole;
 5262:     if ($role =~ /^cr\//) {
 5263:         my $cwosec=$url;
 5264:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5265: 	unless (&allowed('ccr',$cwosec)) {
 5266:            &logthis('Refused custom assignrole: '.
 5267:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5268: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5269:            return 'refused'; 
 5270:         }
 5271:         $mrole='cr';
 5272:     } elsif ($role =~ /^gr\//) {
 5273:         my $cwogrp=$url;
 5274:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5275:         unless (&allowed('mdg',$cwogrp)) {
 5276:             &logthis('Refused group assignrole: '.
 5277:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5278:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5279:             return 'refused';
 5280:         }
 5281:         $mrole='gr';
 5282:     } else {
 5283:         my $cwosec=$url;
 5284:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5285:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5286:             my $refused;
 5287:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5288:                 if (!(&allowed('c'.$role,$url))) {
 5289:                     $refused = 1;
 5290:                 }
 5291:             } else {
 5292:                 $refused = 1;
 5293:             }
 5294:             if ($refused) { 
 5295:                 &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5296:                          ' '.$role.' '.$end.' '.$start.' by '.
 5297: 	  	         $env{'user.name'}.' at '.$env{'user.domain'});
 5298:                 return 'refused';
 5299:             }
 5300:         }
 5301:         $mrole=$role;
 5302:     }
 5303:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5304:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5305:     if ($end) { $command.='_'.$end; }
 5306:     if ($start) {
 5307: 	if ($end) { 
 5308:            $command.='_'.$start; 
 5309:         } else {
 5310:            $command.='_0_'.$start;
 5311:         }
 5312:     }
 5313:     my $origstart = $start;
 5314:     my $origend = $end;
 5315: # actually delete
 5316:     if ($deleteflag) {
 5317: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5318: # modify command to delete the role
 5319:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5320:                 "$udom:$uname:$url".'_'."$mrole";
 5321: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5322: # set start and finish to negative values for userrolelog
 5323:            $start=-1;
 5324:            $end=-1;
 5325:         }
 5326:     }
 5327: # send command
 5328:     my $answer=&reply($command,&homeserver($uname,$udom));
 5329: # log new user role if status is ok
 5330:     if ($answer eq 'ok') {
 5331: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5332: # for course roles, perform group memberships changes triggered by role change.
 5333:         unless ($role =~ /^gr/) {
 5334:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5335:                                              $origstart);
 5336:         }
 5337:     }
 5338:     return $answer;
 5339: }
 5340: 
 5341: # -------------------------------------------------- Modify user authentication
 5342: # Overrides without validation
 5343: 
 5344: sub modifyuserauth {
 5345:     my ($udom,$uname,$umode,$upass)=@_;
 5346:     my $uhome=&homeserver($uname,$udom);
 5347:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5348:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5349:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5350:              ' in domain '.$env{'request.role.domain'});  
 5351:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5352: 		     &escape($upass),$uhome);
 5353:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5354:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5355:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5356:     &log($udom,,$uname,$uhome,
 5357:         'Authentication changed by '.$env{'user.domain'}.', '.
 5358:                                      $env{'user.name'}.', '.$umode.
 5359:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5360:     unless ($reply eq 'ok') {
 5361:         &logthis('Authentication mode error: '.$reply);
 5362: 	return 'error: '.$reply;
 5363:     }   
 5364:     return 'ok';
 5365: }
 5366: 
 5367: # --------------------------------------------------------------- Modify a user
 5368: 
 5369: sub modifyuser {
 5370:     my ($udom,    $uname, $uid,
 5371:         $umode,   $upass, $first,
 5372:         $middle,  $last,  $gene,
 5373:         $forceid, $desiredhome, $email)=@_;
 5374:     $udom= &LONCAPA::clean_domain($udom);
 5375:     $uname=&LONCAPA::clean_username($uname);
 5376:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5377:              $umode.', '.$first.', '.$middle.', '.
 5378: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5379:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5380:                                      ' desiredhome not specified'). 
 5381:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5382:              ' in domain '.$env{'request.role.domain'});
 5383:     my $uhome=&homeserver($uname,$udom,'true');
 5384: # ----------------------------------------------------------------- Create User
 5385:     if (($uhome eq 'no_host') && 
 5386: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5387:         my $unhome='';
 5388:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5389:             $unhome = $desiredhome;
 5390: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5391: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5392:         } else { # load balancing routine for determining $unhome
 5393:             my $loadm=10000000;
 5394: 	    my %servers = &get_servers($udom,'library');
 5395: 	    foreach my $tryserver (keys(%servers)) {
 5396: 		my $answer=reply('load',$tryserver);
 5397: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5398: 		    $loadm=$answer;
 5399: 		    $unhome=$tryserver;
 5400: 		}
 5401: 	    }
 5402:         }
 5403:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5404: 	    return 'error: unable to find a home server for '.$uname.
 5405:                    ' in domain '.$udom;
 5406:         }
 5407:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5408:                          &escape($upass),$unhome);
 5409: 	unless ($reply eq 'ok') {
 5410:             return 'error: '.$reply;
 5411:         }   
 5412:         $uhome=&homeserver($uname,$udom,'true');
 5413:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5414: 	    return 'error: unable verify users home machine.';
 5415:         }
 5416:     }   # End of creation of new user
 5417: # ---------------------------------------------------------------------- Add ID
 5418:     if ($uid) {
 5419:        $uid=~tr/A-Z/a-z/;
 5420:        my %uidhash=&idrget($udom,$uname);
 5421:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5422:          && (!$forceid)) {
 5423: 	  unless ($uid eq $uidhash{$uname}) {
 5424: 	      return 'error: user id "'.$uid.'" does not match '.
 5425:                   'current user id "'.$uidhash{$uname}.'".';
 5426:           }
 5427:        } else {
 5428: 	  &idput($udom,($uname => $uid));
 5429:        }
 5430:     }
 5431: # -------------------------------------------------------------- Add names, etc
 5432:     my @tmp=&get('environment',
 5433: 		   ['firstname','middlename','lastname','generation','id',
 5434:                     'permanentemail'],
 5435: 		   $udom,$uname);
 5436:     my %names;
 5437:     if ($tmp[0] =~ m/^error:.*/) { 
 5438:         %names=(); 
 5439:     } else {
 5440:         %names = @tmp;
 5441:     }
 5442: #
 5443: # Make sure to not trash student environment if instructor does not bother
 5444: # to supply name and email information
 5445: #
 5446:     if ($first)  { $names{'firstname'}  = $first; }
 5447:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5448:     if ($last)   { $names{'lastname'}   = $last; }
 5449:     if (defined($gene))   { $names{'generation'} = $gene; }
 5450:     if ($email) {
 5451:        $email=~s/[^\w\@\.\-\,]//gs;
 5452:        if ($email=~/\@/) { $names{'notification'} = $email;
 5453: 			   $names{'critnotification'} = $email;
 5454: 			   $names{'permanentemail'} = $email; }
 5455:     }
 5456:     if ($uid) { $names{'id'}  = $uid; }
 5457:     my $reply = &put('environment', \%names, $udom,$uname);
 5458:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5459:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5460:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5461:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5462:              $umode.', '.$first.', '.$middle.', '.
 5463: 	     $last.', '.$gene.' by '.
 5464:              $env{'user.name'}.' at '.$env{'user.domain'});
 5465:     return 'ok';
 5466: }
 5467: 
 5468: # -------------------------------------------------------------- Modify student
 5469: 
 5470: sub modifystudent {
 5471:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5472:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5473:     if (!$cid) {
 5474: 	unless ($cid=$env{'request.course.id'}) {
 5475: 	    return 'not_in_class';
 5476: 	}
 5477:     }
 5478: # --------------------------------------------------------------- Make the user
 5479:     my $reply=&modifyuser
 5480: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5481:          $desiredhome,$email);
 5482:     unless ($reply eq 'ok') { return $reply; }
 5483:     # This will cause &modify_student_enrollment to get the uid from the
 5484:     # students environment
 5485:     $uid = undef if (!$forceid);
 5486:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5487: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5488:     return $reply;
 5489: }
 5490: 
 5491: sub modify_student_enrollment {
 5492:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5493:     my ($cdom,$cnum,$chome);
 5494:     if (!$cid) {
 5495: 	unless ($cid=$env{'request.course.id'}) {
 5496: 	    return 'not_in_class';
 5497: 	}
 5498: 	$cdom=$env{'course.'.$cid.'.domain'};
 5499: 	$cnum=$env{'course.'.$cid.'.num'};
 5500:     } else {
 5501: 	($cdom,$cnum)=split(/_/,$cid);
 5502:     }
 5503:     $chome=$env{'course.'.$cid.'.home'};
 5504:     if (!$chome) {
 5505: 	$chome=&homeserver($cnum,$cdom);
 5506:     }
 5507:     if (!$chome) { return 'unknown_course'; }
 5508:     # Make sure the user exists
 5509:     my $uhome=&homeserver($uname,$udom);
 5510:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5511: 	return 'error: no such user';
 5512:     }
 5513:     # Get student data if we were not given enough information
 5514:     if (!defined($first)  || $first  eq '' || 
 5515:         !defined($last)   || $last   eq '' || 
 5516:         !defined($uid)    || $uid    eq '' || 
 5517:         !defined($middle) || $middle eq '' || 
 5518:         !defined($gene)   || $gene   eq '') {
 5519:         # They did not supply us with enough data to enroll the student, so
 5520:         # we need to pick up more information.
 5521:         my %tmp = &get('environment',
 5522:                        ['firstname','middlename','lastname', 'generation','id']
 5523:                        ,$udom,$uname);
 5524: 
 5525:         #foreach my $key (keys(%tmp)) {
 5526:         #    &logthis("key $key = ".$tmp{$key});
 5527:         #}
 5528:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5529:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5530:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5531:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5532:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5533:     }
 5534:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5535:     my $reply=cput('classlist',
 5536: 		   {"$uname:$udom" => 
 5537: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5538: 		   $cdom,$cnum);
 5539:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5540: 	return 'error: '.$reply;
 5541:     } else {
 5542: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5543:     }
 5544:     # Add student role to user
 5545:     my $uurl='/'.$cid;
 5546:     $uurl=~s/\_/\//g;
 5547:     if ($usec) {
 5548: 	$uurl.='/'.$usec;
 5549:     }
 5550:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5551: }
 5552: 
 5553: sub format_name {
 5554:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5555:     my $name;
 5556:     if ($first ne 'lastname') {
 5557: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5558:     } else {
 5559: 	if ($lastname=~/\S/) {
 5560: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5561: 	    $name=~s/\s+,/,/;
 5562: 	} else {
 5563: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5564: 	}
 5565:     }
 5566:     $name=~s/^\s+//;
 5567:     $name=~s/\s+$//;
 5568:     $name=~s/\s+/ /g;
 5569:     return $name;
 5570: }
 5571: 
 5572: # ------------------------------------------------- Write to course preferences
 5573: 
 5574: sub writecoursepref {
 5575:     my ($courseid,%prefs)=@_;
 5576:     $courseid=~s/^\///;
 5577:     $courseid=~s/\_/\//g;
 5578:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5579:     my $chome=homeserver($cnum,$cdomain);
 5580:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5581: 	return 'error: no such course';
 5582:     }
 5583:     my $cstring='';
 5584:     foreach my $pref (keys(%prefs)) {
 5585: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5586:     }
 5587:     $cstring=~s/\&$//;
 5588:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5589: }
 5590: 
 5591: # ---------------------------------------------------------- Make/modify course
 5592: 
 5593: sub createcourse {
 5594:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5595:         $course_owner,$crstype)=@_;
 5596:     $url=&declutter($url);
 5597:     my $cid='';
 5598:     unless (&allowed('ccc',$udom)) {
 5599:         return 'refused';
 5600:     }
 5601: # ------------------------------------------------------------------- Create ID
 5602:    my $uname=int(1+rand(9)).
 5603:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5604:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5605:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5606: # ----------------------------------------------- Make sure that does not exist
 5607:    my $uhome=&homeserver($uname,$udom,'true');
 5608:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5609:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5610:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5611:        $uhome=&homeserver($uname,$udom,'true');       
 5612:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5613:            return 'error: unable to generate unique course-ID';
 5614:        } 
 5615:    }
 5616: # ------------------------------------------------ Check supplied server name
 5617:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5618:     if (! &is_library($course_server)) {
 5619:         return 'error:bad server name '.$course_server;
 5620:     }
 5621: # ------------------------------------------------------------- Make the course
 5622:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5623:                       $course_server);
 5624:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5625:     $uhome=&homeserver($uname,$udom,'true');
 5626:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5627: 	return 'error: no such course';
 5628:     }
 5629: # ----------------------------------------------------------------- Course made
 5630: # log existence
 5631:     my $newcourse = {
 5632:                     $udom.'_'.$uname => {
 5633:                                      description => $description,
 5634:                                      inst_code   => $inst_code,
 5635:                                      owner       => $course_owner,
 5636:                                      type        => $crstype,
 5637:                                                 },
 5638:                     };
 5639:     &courseidput($udom,$newcourse,$uhome,'notime');
 5640: # set toplevel url
 5641:     my $topurl=$url;
 5642:     unless ($nonstandard) {
 5643: # ------------------------------------------ For standard courses, make top url
 5644:         my $mapurl=&clutter($url);
 5645:         if ($mapurl eq '/res/') { $mapurl=''; }
 5646:         $env{'form.initmap'}=(<<ENDINITMAP);
 5647: <map>
 5648: <resource id="1" type="start"></resource>
 5649: <resource id="2" src="$mapurl"></resource>
 5650: <resource id="3" type="finish"></resource>
 5651: <link index="1" from="1" to="2"></link>
 5652: <link index="2" from="2" to="3"></link>
 5653: </map>
 5654: ENDINITMAP
 5655:         $topurl=&declutter(
 5656:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5657:                           );
 5658:     }
 5659: # ----------------------------------------------------------- Write preferences
 5660:     &writecoursepref($udom.'_'.$uname,
 5661:                      ('description' => $description,
 5662:                       'url'         => $topurl));
 5663:     return '/'.$udom.'/'.$uname;
 5664: }
 5665: 
 5666: sub is_course {
 5667:     my ($cdom,$cnum) = @_;
 5668:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5669: 				undef,'.',undef,1);
 5670:     if (exists($courses{$cdom.'_'.$cnum})) {
 5671:         return 1;
 5672:     }
 5673:     return 0;
 5674: }
 5675: 
 5676: # ---------------------------------------------------------- Assign Custom Role
 5677: 
 5678: sub assigncustomrole {
 5679:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5680:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5681:                        $end,$start,$deleteflag);
 5682: }
 5683: 
 5684: # ----------------------------------------------------------------- Revoke Role
 5685: 
 5686: sub revokerole {
 5687:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5688:     my $now=time;
 5689:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5690: }
 5691: 
 5692: # ---------------------------------------------------------- Revoke Custom Role
 5693: 
 5694: sub revokecustomrole {
 5695:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5696:     my $now=time;
 5697:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5698:            $deleteflag);
 5699: }
 5700: 
 5701: # ------------------------------------------------------------ Disk usage
 5702: sub diskusage {
 5703:     my ($udom,$uname,$directoryRoot)=@_;
 5704:     $directoryRoot =~ s/\/$//;
 5705:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5706:     return $listing;
 5707: }
 5708: 
 5709: sub is_locked {
 5710:     my ($file_name, $domain, $user) = @_;
 5711:     my @check;
 5712:     my $is_locked;
 5713:     push @check, $file_name;
 5714:     my %locked = &get('file_permissions',\@check,
 5715: 		      $env{'user.domain'},$env{'user.name'});
 5716:     my ($tmp)=keys(%locked);
 5717:     if ($tmp=~/^error:/) { undef(%locked); }
 5718:     
 5719:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5720:         $is_locked = 'false';
 5721:         foreach my $entry (@{$locked{$file_name}}) {
 5722:            if (ref($entry) eq 'ARRAY') { 
 5723:                $is_locked = 'true';
 5724:                last;
 5725:            }
 5726:        }
 5727:     } else {
 5728:         $is_locked = 'false';
 5729:     }
 5730: }
 5731: 
 5732: sub declutter_portfile {
 5733:     my ($file) = @_;
 5734:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5735:     return $file;
 5736: }
 5737: 
 5738: # ------------------------------------------------------------- Mark as Read Only
 5739: 
 5740: sub mark_as_readonly {
 5741:     my ($domain,$user,$files,$what) = @_;
 5742:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5743:     my ($tmp)=keys(%current_permissions);
 5744:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5745:     foreach my $file (@{$files}) {
 5746: 	$file = &declutter_portfile($file);
 5747:         push(@{$current_permissions{$file}},$what);
 5748:     }
 5749:     &put('file_permissions',\%current_permissions,$domain,$user);
 5750:     return;
 5751: }
 5752: 
 5753: # ------------------------------------------------------------Save Selected Files
 5754: 
 5755: sub save_selected_files {
 5756:     my ($user, $path, @files) = @_;
 5757:     my $filename = $user."savedfiles";
 5758:     my @other_files = &files_not_in_path($user, $path);
 5759:     open (OUT, '>'.$tmpdir.$filename);
 5760:     foreach my $file (@files) {
 5761:         print (OUT $env{'form.currentpath'}.$file."\n");
 5762:     }
 5763:     foreach my $file (@other_files) {
 5764:         print (OUT $file."\n");
 5765:     }
 5766:     close (OUT);
 5767:     return 'ok';
 5768: }
 5769: 
 5770: sub clear_selected_files {
 5771:     my ($user) = @_;
 5772:     my $filename = $user."savedfiles";
 5773:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5774:     print (OUT undef);
 5775:     close (OUT);
 5776:     return ("ok");    
 5777: }
 5778: 
 5779: sub files_in_path {
 5780:     my ($user, $path) = @_;
 5781:     my $filename = $user."savedfiles";
 5782:     my %return_files;
 5783:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5784:     while (my $line_in = <IN>) {
 5785:         chomp ($line_in);
 5786:         my @paths_and_file = split (m!/!, $line_in);
 5787:         my $file_part = pop (@paths_and_file);
 5788:         my $path_part = join ('/', @paths_and_file);
 5789:         $path_part.='/';
 5790:         my $path_and_file = $path_part.$file_part;
 5791:         if ($path_part eq $path) {
 5792:             $return_files{$file_part}= 'selected';
 5793:         }
 5794:     }
 5795:     close (IN);
 5796:     return (\%return_files);
 5797: }
 5798: 
 5799: # called in portfolio select mode, to show files selected NOT in current directory
 5800: sub files_not_in_path {
 5801:     my ($user, $path) = @_;
 5802:     my $filename = $user."savedfiles";
 5803:     my @return_files;
 5804:     my $path_part;
 5805:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5806:     while (my $line = <IN>) {
 5807:         #ok, I know it's clunky, but I want it to work
 5808:         my @paths_and_file = split(m|/|, $line);
 5809:         my $file_part = pop(@paths_and_file);
 5810:         chomp($file_part);
 5811:         my $path_part = join('/', @paths_and_file);
 5812:         $path_part .= '/';
 5813:         my $path_and_file = $path_part.$file_part;
 5814:         if ($path_part ne $path) {
 5815:             push(@return_files, ($path_and_file));
 5816:         }
 5817:     }
 5818:     close(OUT);
 5819:     return (@return_files);
 5820: }
 5821: 
 5822: #----------------------------------------------Get portfolio file permissions
 5823: 
 5824: sub get_portfile_permissions {
 5825:     my ($domain,$user) = @_;
 5826:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5827:     my ($tmp)=keys(%current_permissions);
 5828:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5829:     return \%current_permissions;
 5830: }
 5831: 
 5832: #---------------------------------------------Get portfolio file access controls
 5833: 
 5834: sub get_access_controls {
 5835:     my ($current_permissions,$group,$file) = @_;
 5836:     my %access;
 5837:     my $real_file = $file;
 5838:     $file =~ s/\.meta$//;
 5839:     if (defined($file)) {
 5840:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5841:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5842:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5843:             }
 5844:         }
 5845:     } else {
 5846:         foreach my $key (keys(%{$current_permissions})) {
 5847:             if ($key =~ /\0accesscontrol$/) {
 5848:                 if (defined($group)) {
 5849:                     if ($key !~ m-^\Q$group\E/-) {
 5850:                         next;
 5851:                     }
 5852:                 }
 5853:                 my ($fullpath) = split(/\0/,$key);
 5854:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5855:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5856:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5857:                     }
 5858:                 }
 5859:             }
 5860:         }
 5861:     }
 5862:     return %access;
 5863: }
 5864: 
 5865: sub modify_access_controls {
 5866:     my ($file_name,$changes,$domain,$user)=@_;
 5867:     my ($outcome,$deloutcome);
 5868:     my %store_permissions;
 5869:     my %new_values;
 5870:     my %new_control;
 5871:     my %translation;
 5872:     my @deletions = ();
 5873:     my $now = time;
 5874:     if (exists($$changes{'activate'})) {
 5875:         if (ref($$changes{'activate'}) eq 'HASH') {
 5876:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5877:             my $numnew = scalar(@newitems);
 5878:             for (my $i=0; $i<$numnew; $i++) {
 5879:                 my $newkey = $newitems[$i];
 5880:                 my $newid = &Apache::loncommon::get_cgi_id();
 5881:                 if ($newkey =~ /^\d+:/) { 
 5882:                     $newkey =~ s/^(\d+)/$newid/;
 5883:                     $translation{$1} = $newid;
 5884:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5885:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5886:                     $translation{$1} = $newid;
 5887:                 }
 5888:                 $new_values{$file_name."\0".$newkey} = 
 5889:                                           $$changes{'activate'}{$newitems[$i]};
 5890:                 $new_control{$newkey} = $now;
 5891:             }
 5892:         }
 5893:     }
 5894:     my %todelete;
 5895:     my %changed_items;
 5896:     foreach my $action ('delete','update') {
 5897:         if (exists($$changes{$action})) {
 5898:             if (ref($$changes{$action}) eq 'HASH') {
 5899:                 foreach my $key (keys(%{$$changes{$action}})) {
 5900:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5901:                     if ($action eq 'delete') { 
 5902:                         $todelete{$itemnum} = 1;
 5903:                     } else {
 5904:                         $changed_items{$itemnum} = $key;
 5905:                     }
 5906:                 }
 5907:             }
 5908:         }
 5909:     }
 5910:     # get lock on access controls for file.
 5911:     my $lockhash = {
 5912:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5913:                                                        ':'.$env{'user.domain'},
 5914:                    }; 
 5915:     my $tries = 0;
 5916:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5917:    
 5918:     while (($gotlock ne 'ok') && $tries <3) {
 5919:         $tries ++;
 5920:         sleep 1;
 5921:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5922:     }
 5923:     if ($gotlock eq 'ok') {
 5924:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5925:         my ($tmp)=keys(%curr_permissions);
 5926:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5927:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5928:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5929:             if (ref($curr_controls) eq 'HASH') {
 5930:                 foreach my $control_item (keys(%{$curr_controls})) {
 5931:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5932:                     if (defined($todelete{$itemnum})) {
 5933:                         push(@deletions,$file_name."\0".$control_item);
 5934:                     } else {
 5935:                         if (defined($changed_items{$itemnum})) {
 5936:                             $new_control{$changed_items{$itemnum}} = $now;
 5937:                             push(@deletions,$file_name."\0".$control_item);
 5938:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5939:                         } else {
 5940:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5941:                         }
 5942:                     }
 5943:                 }
 5944:             }
 5945:         }
 5946:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5947:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5948:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5949:         #  remove lock
 5950:         my @del_lock = ($file_name."\0".'locked_access_records');
 5951:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5952:         my ($file,$group);
 5953:         if (&is_course($domain,$user)) {
 5954:             ($group,$file) = split(/\//,$file_name,2);
 5955:         } else {
 5956:             $file = $file_name;
 5957:         }
 5958:         my $sqlresult =
 5959:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5960:                                     $group);
 5961:     } else {
 5962:         $outcome = "error: could not obtain lockfile\n";  
 5963:     }
 5964:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5965: }
 5966: 
 5967: sub make_public_indefinitely {
 5968:     my ($requrl) = @_;
 5969:     my $now = time;
 5970:     my $action = 'activate';
 5971:     my $aclnum = 0;
 5972:     if (&is_portfolio_url($requrl)) {
 5973:         my (undef,$udom,$unum,$file_name,$group) =
 5974:             &parse_portfolio_url($requrl);
 5975:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5976:         my %access_controls = &get_access_controls($current_perms,
 5977:                                                    $group,$file_name);
 5978:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5979:             my ($num,$scope,$end,$start) = 
 5980:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5981:             if ($scope eq 'public') {
 5982:                 if ($start <= $now && $end == 0) {
 5983:                     $action = 'none';
 5984:                 } else {
 5985:                     $action = 'update';
 5986:                     $aclnum = $num;
 5987:                 }
 5988:                 last;
 5989:             }
 5990:         }
 5991:         if ($action eq 'none') {
 5992:              return 'ok';
 5993:         } else {
 5994:             my %changes;
 5995:             my $newend = 0;
 5996:             my $newstart = $now;
 5997:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5998:             $changes{$action}{$newkey} = {
 5999:                 type => 'public',
 6000:                 time => {
 6001:                     start => $newstart,
 6002:                     end   => $newend,
 6003:                 },
 6004:             };
 6005:             my ($outcome,$deloutcome,$new_values,$translation) =
 6006:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6007:             return $outcome;
 6008:         }
 6009:     } else {
 6010:         return 'invalid';
 6011:     }
 6012: }
 6013: 
 6014: #------------------------------------------------------Get Marked as Read Only
 6015: 
 6016: sub get_marked_as_readonly {
 6017:     my ($domain,$user,$what,$group) = @_;
 6018:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6019:     my @readonly_files;
 6020:     my $cmp1=$what;
 6021:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6022:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6023:         if (defined($group)) {
 6024:             if ($file_name !~ m-^\Q$group\E/-) {
 6025:                 next;
 6026:             }
 6027:         }
 6028:         if (ref($value) eq "ARRAY"){
 6029:             foreach my $stored_what (@{$value}) {
 6030:                 my $cmp2=$stored_what;
 6031:                 if (ref($stored_what) eq 'ARRAY') {
 6032:                     $cmp2=join('',@{$stored_what});
 6033:                 }
 6034:                 if ($cmp1 eq $cmp2) {
 6035:                     push(@readonly_files, $file_name);
 6036:                     last;
 6037:                 } elsif (!defined($what)) {
 6038:                     push(@readonly_files, $file_name);
 6039:                     last;
 6040:                 }
 6041:             }
 6042:         }
 6043:     }
 6044:     return @readonly_files;
 6045: }
 6046: #-----------------------------------------------------------Get Marked as Read Only Hash
 6047: 
 6048: sub get_marked_as_readonly_hash {
 6049:     my ($current_permissions,$group,$what) = @_;
 6050:     my %readonly_files;
 6051:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6052:         if (defined($group)) {
 6053:             if ($file_name !~ m-^\Q$group\E/-) {
 6054:                 next;
 6055:             }
 6056:         }
 6057:         if (ref($value) eq "ARRAY"){
 6058:             foreach my $stored_what (@{$value}) {
 6059:                 if (ref($stored_what) eq 'ARRAY') {
 6060:                     foreach my $lock_descriptor(@{$stored_what}) {
 6061:                         if ($lock_descriptor eq 'graded') {
 6062:                             $readonly_files{$file_name} = 'graded';
 6063:                         } elsif ($lock_descriptor eq 'handback') {
 6064:                             $readonly_files{$file_name} = 'handback';
 6065:                         } else {
 6066:                             if (!exists($readonly_files{$file_name})) {
 6067:                                 $readonly_files{$file_name} = 'locked';
 6068:                             }
 6069:                         }
 6070:                     }
 6071:                 } 
 6072:             }
 6073:         } 
 6074:     }
 6075:     return %readonly_files;
 6076: }
 6077: # ------------------------------------------------------------ Unmark as Read Only
 6078: 
 6079: sub unmark_as_readonly {
 6080:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6081:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6082:     my ($domain,$user,$what,$file_name,$group) = @_;
 6083:     $file_name = &declutter_portfile($file_name);
 6084:     my $symb_crs = $what;
 6085:     if (ref($what)) { $symb_crs=join('',@$what); }
 6086:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6087:     my ($tmp)=keys(%current_permissions);
 6088:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6089:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6090:     foreach my $file (@readonly_files) {
 6091: 	my $clean_file = &declutter_portfile($file);
 6092: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6093: 	my $current_locks = $current_permissions{$file};
 6094:         my @new_locks;
 6095:         my @del_keys;
 6096:         if (ref($current_locks) eq "ARRAY"){
 6097:             foreach my $locker (@{$current_locks}) {
 6098:                 my $compare=$locker;
 6099:                 if (ref($locker) eq 'ARRAY') {
 6100:                     $compare=join('',@{$locker});
 6101:                     if ($compare ne $symb_crs) {
 6102:                         push(@new_locks, $locker);
 6103:                     }
 6104:                 }
 6105:             }
 6106:             if (scalar(@new_locks) > 0) {
 6107:                 $current_permissions{$file} = \@new_locks;
 6108:             } else {
 6109:                 push(@del_keys, $file);
 6110:                 &del('file_permissions',\@del_keys, $domain, $user);
 6111:                 delete($current_permissions{$file});
 6112:             }
 6113:         }
 6114:     }
 6115:     &put('file_permissions',\%current_permissions,$domain,$user);
 6116:     return;
 6117: }
 6118: 
 6119: # ------------------------------------------------------------ Directory lister
 6120: 
 6121: sub dirlist {
 6122:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6123: 
 6124:     $uri=~s/^\///;
 6125:     $uri=~s/\/$//;
 6126:     my ($udom, $uname);
 6127:     (undef,$udom,$uname)=split(/\//,$uri);
 6128:     if(defined($userdomain)) {
 6129:         $udom = $userdomain;
 6130:     }
 6131:     if(defined($username)) {
 6132:         $uname = $username;
 6133:     }
 6134: 
 6135:     my $dirRoot = $perlvar{'lonDocRoot'};
 6136:     if(defined($alternateDirectoryRoot)) {
 6137:         $dirRoot = $alternateDirectoryRoot;
 6138:         $dirRoot =~ s/\/$//;
 6139:     }
 6140: 
 6141:     if($udom) {
 6142:         if($uname) {
 6143:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6144: 				 &homeserver($uname,$udom));
 6145:             my @listing_results;
 6146:             if ($listing eq 'unknown_cmd') {
 6147:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6148: 				  &homeserver($uname,$udom));
 6149:                 @listing_results = split(/:/,$listing);
 6150:             } else {
 6151:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6152:             }
 6153:             return @listing_results;
 6154:         } elsif(!defined($alternateDirectoryRoot)) {
 6155:             my %allusers;
 6156: 	    my %servers = &get_servers($udom,'library');
 6157: 	    foreach my $tryserver (keys(%servers)) {
 6158: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6159: 				     $udom, $tryserver);
 6160: 		my @listing_results;
 6161: 		if ($listing eq 'unknown_cmd') {
 6162: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6163: 				      $udom, $tryserver);
 6164: 		    @listing_results = split(/:/,$listing);
 6165: 		} else {
 6166: 		    @listing_results =
 6167: 			map { &unescape($_); } split(/:/,$listing);
 6168: 		}
 6169: 		if ($listing_results[0] ne 'no_such_dir' && 
 6170: 		    $listing_results[0] ne 'empty'       &&
 6171: 		    $listing_results[0] ne 'con_lost') {
 6172: 		    foreach my $line (@listing_results) {
 6173: 			my ($entry) = split(/&/,$line,2);
 6174: 			$allusers{$entry} = 1;
 6175: 		    }
 6176: 		}
 6177:             }
 6178:             my $alluserstr='';
 6179:             foreach my $user (sort(keys(%allusers))) {
 6180:                 $alluserstr.=$user.'&user:';
 6181:             }
 6182:             $alluserstr=~s/:$//;
 6183:             return split(/:/,$alluserstr);
 6184:         } else {
 6185:             return ('missing user name');
 6186:         }
 6187:     } elsif(!defined($alternateDirectoryRoot)) {
 6188:         my @all_domains = sort(&all_domains());
 6189:          foreach my $domain (@all_domains) {
 6190:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6191:          }
 6192:          return @all_domains;
 6193:      } else {
 6194:         return ('missing domain');
 6195:     }
 6196: }
 6197: 
 6198: # --------------------------------------------- GetFileTimestamp
 6199: # This function utilizes dirlist and returns the date stamp for
 6200: # when it was last modified.  It will also return an error of -1
 6201: # if an error occurs
 6202: 
 6203: ##
 6204: ## FIXME: This subroutine assumes its caller knows something about the
 6205: ## directory structure of the home server for the student ($root).
 6206: ## Not a good assumption to make.  Since this is for looking up files
 6207: ## in user directories, the full path should be constructed by lond, not
 6208: ## whatever machine we request data from.
 6209: ##
 6210: sub GetFileTimestamp {
 6211:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6212:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6213:     $studentName   = &LONCAPA::clean_username($studentName);
 6214:     my $subdir=$studentName.'__';
 6215:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6216:     my $proname="$studentDomain/$subdir/$studentName";
 6217:     $proname .= '/'.$filename;
 6218:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6219:                                               $studentName, $root);
 6220:     my @stats = split('&', $fileStat);
 6221:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6222:         # @stats contains first the filename, then the stat output
 6223:         return $stats[10]; # so this is 10 instead of 9.
 6224:     } else {
 6225:         return -1;
 6226:     }
 6227: }
 6228: 
 6229: sub stat_file {
 6230:     my ($uri) = @_;
 6231:     $uri = &clutter_with_no_wrapper($uri);
 6232: 
 6233:     my ($udom,$uname,$file,$dir);
 6234:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6235: 	($udom,$uname,$file) =
 6236: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6237: 	$file = 'userfiles/'.$file;
 6238: 	$dir = &propath($udom,$uname);
 6239:     }
 6240:     if ($uri =~ m-^/res/-) {
 6241: 	($udom,$uname) = 
 6242: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6243: 	$file = $uri;
 6244:     }
 6245: 
 6246:     if (!$udom || !$uname || !$file) {
 6247: 	# unable to handle the uri
 6248: 	return ();
 6249:     }
 6250: 
 6251:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6252:     my @stats = split('&', $result);
 6253:     
 6254:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6255: 	shift(@stats); #filename is first
 6256: 	return @stats;
 6257:     }
 6258:     return ();
 6259: }
 6260: 
 6261: # -------------------------------------------------------- Value of a Condition
 6262: 
 6263: # gets the value of a specific preevaluated condition
 6264: #    stored in the string  $env{user.state.<cid>}
 6265: # or looks up a condition reference in the bighash and if if hasn't
 6266: # already been evaluated recurses into docondval to get the value of
 6267: # the condition, then memoizing it to 
 6268: #   $env{user.state.<cid>.<condition>}
 6269: sub directcondval {
 6270:     my $number=shift;
 6271:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6272: 	&Apache::lonuserstate::evalstate();
 6273:     }
 6274:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6275: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6276:     } elsif ($number =~ /^_/) {
 6277: 	my $sub_condition;
 6278: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6279: 		&GDBM_READER(),0640)) {
 6280: 	    $sub_condition=$bighash{'conditions'.$number};
 6281: 	    untie(%bighash);
 6282: 	}
 6283: 	my $value = &docondval($sub_condition);
 6284: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 6285: 	return $value;
 6286:     }
 6287:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6288:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6289:     } else {
 6290:        return 2;
 6291:     }
 6292: }
 6293: 
 6294: # get the collection of conditions for this resource
 6295: sub condval {
 6296:     my $condidx=shift;
 6297:     my $allpathcond='';
 6298:     foreach my $cond (split(/\|/,$condidx)) {
 6299: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6300: 	    $allpathcond.=
 6301: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6302: 	}
 6303:     }
 6304:     $allpathcond=~s/\|$//;
 6305:     return &docondval($allpathcond);
 6306: }
 6307: 
 6308: #evaluates an expression of conditions
 6309: sub docondval {
 6310:     my ($allpathcond) = @_;
 6311:     my $result=0;
 6312:     if ($env{'request.course.id'}
 6313: 	&& defined($allpathcond)) {
 6314: 	my $operand='|';
 6315: 	my @stack;
 6316: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6317: 	    if ($chunk eq '(') {
 6318: 		push @stack,($operand,$result);
 6319: 	    } elsif ($chunk eq ')') {
 6320: 		my $before=pop @stack;
 6321: 		if (pop @stack eq '&') {
 6322: 		    $result=$result>$before?$before:$result;
 6323: 		} else {
 6324: 		    $result=$result>$before?$result:$before;
 6325: 		}
 6326: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6327: 		$operand=$chunk;
 6328: 	    } else {
 6329: 		my $new=directcondval($chunk);
 6330: 		if ($operand eq '&') {
 6331: 		    $result=$result>$new?$new:$result;
 6332: 		} else {
 6333: 		    $result=$result>$new?$result:$new;
 6334: 		}
 6335: 	    }
 6336: 	}
 6337:     }
 6338:     return $result;
 6339: }
 6340: 
 6341: # ---------------------------------------------------- Devalidate courseresdata
 6342: 
 6343: sub devalidatecourseresdata {
 6344:     my ($coursenum,$coursedomain)=@_;
 6345:     my $hashid=$coursenum.':'.$coursedomain;
 6346:     &devalidate_cache_new('courseres',$hashid);
 6347: }
 6348: 
 6349: 
 6350: # --------------------------------------------------- Course Resourcedata Query
 6351: #
 6352: #  Parameters:
 6353: #      $coursenum    - Number of the course.
 6354: #      $coursedomain - Domain at which the course was created.
 6355: #  Returns:
 6356: #     A hash of the course parameters along (I think) with timestamps
 6357: #     and version info.
 6358: 
 6359: sub get_courseresdata {
 6360:     my ($coursenum,$coursedomain)=@_;
 6361:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6362:     my $hashid=$coursenum.':'.$coursedomain;
 6363:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6364:     my %dumpreply;
 6365:     unless (defined($cached)) {
 6366: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6367: 	$result=\%dumpreply;
 6368: 	my ($tmp) = keys(%dumpreply);
 6369: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6370: 	    &do_cache_new('courseres',$hashid,$result,600);
 6371: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6372: 	    return $tmp;
 6373: 	} elsif ($tmp =~ /^(error)/) {
 6374: 	    $result=undef;
 6375: 	    &do_cache_new('courseres',$hashid,$result,600);
 6376: 	}
 6377:     }
 6378:     return $result;
 6379: }
 6380: 
 6381: sub devalidateuserresdata {
 6382:     my ($uname,$udom)=@_;
 6383:     my $hashid="$udom:$uname";
 6384:     &devalidate_cache_new('userres',$hashid);
 6385: }
 6386: 
 6387: sub get_userresdata {
 6388:     my ($uname,$udom)=@_;
 6389:     #most student don\'t have any data set, check if there is some data
 6390:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6391: 
 6392:     my $hashid="$udom:$uname";
 6393:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6394:     if (!defined($cached)) {
 6395: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6396: 	$result=\%resourcedata;
 6397: 	&do_cache_new('userres',$hashid,$result,600);
 6398:     }
 6399:     my ($tmp)=keys(%$result);
 6400:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6401: 	return $result;
 6402:     }
 6403:     #error 2 occurs when the .db doesn't exist
 6404:     if ($tmp!~/error: 2 /) {
 6405: 	&logthis("<font color=\"blue\">WARNING:".
 6406: 		 " Trying to get resource data for ".
 6407: 		 $uname." at ".$udom.": ".
 6408: 		 $tmp."</font>");
 6409:     } elsif ($tmp=~/error: 2 /) {
 6410: 	#&EXT_cache_set($udom,$uname);
 6411: 	&do_cache_new('userres',$hashid,undef,600);
 6412: 	undef($tmp); # not really an error so don't send it back
 6413:     }
 6414:     return $tmp;
 6415: }
 6416: #----------------------------------------------- resdata - return resource data
 6417: #  Purpose:
 6418: #    Return resource data for either users or for a course.
 6419: #  Parameters:
 6420: #     $name      - Course/user name.
 6421: #     $domain    - Name of the domain the user/course is registered on.
 6422: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6423: #     @which     - Array of names of resources desired.
 6424: #  Returns:
 6425: #     The value of the first reasource in @which that is found in the
 6426: #     resource hash.
 6427: #  Exceptional Conditions:
 6428: #     If the $type passed in is not valid (not the string 'course' or 
 6429: #     'user', an undefined  reference is returned.
 6430: #     If none of the resources are found, an undef is returned
 6431: sub resdata {
 6432:     my ($name,$domain,$type,@which)=@_;
 6433:     my $result;
 6434:     if ($type eq 'course') {
 6435: 	$result=&get_courseresdata($name,$domain);
 6436:     } elsif ($type eq 'user') {
 6437: 	$result=&get_userresdata($name,$domain);
 6438:     }
 6439:     if (!ref($result)) { return $result; }    
 6440:     foreach my $item (@which) {
 6441: 	if (defined($result->{$item->[0]})) {
 6442: 	    return [$result->{$item->[0]},$item->[1]];
 6443: 	}
 6444:     }
 6445:     return undef;
 6446: }
 6447: 
 6448: #
 6449: # EXT resource caching routines
 6450: #
 6451: 
 6452: sub clear_EXT_cache_status {
 6453:     &delenv('cache.EXT.');
 6454: }
 6455: 
 6456: sub EXT_cache_status {
 6457:     my ($target_domain,$target_user) = @_;
 6458:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6459:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6460:         # We know already the user has no data
 6461:         return 1;
 6462:     } else {
 6463:         return 0;
 6464:     }
 6465: }
 6466: 
 6467: sub EXT_cache_set {
 6468:     my ($target_domain,$target_user) = @_;
 6469:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6470:     #&appenv($cachename => time);
 6471: }
 6472: 
 6473: # --------------------------------------------------------- Value of a Variable
 6474: sub EXT {
 6475: 
 6476:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6477:     unless ($varname) { return ''; }
 6478:     #get real user name/domain, courseid and symb
 6479:     my $courseid;
 6480:     my $publicuser;
 6481:     if ($symbparm) {
 6482: 	$symbparm=&get_symb_from_alias($symbparm);
 6483:     }
 6484:     if (!($uname && $udom)) {
 6485:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6486:       if (!$symbparm) {	$symbparm=$cursymb; }
 6487:     } else {
 6488: 	$courseid=$env{'request.course.id'};
 6489:     }
 6490:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6491:     my $rest;
 6492:     if (defined($therest[0])) {
 6493:        $rest=join('.',@therest);
 6494:     } else {
 6495:        $rest='';
 6496:     }
 6497: 
 6498:     my $qualifierrest=$qualifier;
 6499:     if ($rest) { $qualifierrest.='.'.$rest; }
 6500:     my $spacequalifierrest=$space;
 6501:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6502:     if ($realm eq 'user') {
 6503: # --------------------------------------------------------------- user.resource
 6504: 	if ($space eq 'resource') {
 6505: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6506: 		  || defined($Apache::lonhomework::parsing_a_task))
 6507: 		 &&
 6508: 		 ($symbparm eq &symbread()) ) {	
 6509: 		# if we are in the middle of processing the resource the
 6510: 		# get the value we are planning on committing
 6511:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6512:                     return $Apache::lonhomework::results{$qualifierrest};
 6513:                 } else {
 6514:                     return $Apache::lonhomework::history{$qualifierrest};
 6515:                 }
 6516: 	    } else {
 6517: 		my %restored;
 6518: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6519: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6520: 		} else {
 6521: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6522: 		}
 6523: 		return $restored{$qualifierrest};
 6524: 	    }
 6525: # ----------------------------------------------------------------- user.access
 6526:         } elsif ($space eq 'access') {
 6527: 	    # FIXME - not supporting calls for a specific user
 6528:             return &allowed($qualifier,$rest);
 6529: # ------------------------------------------ user.preferences, user.environment
 6530:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6531: 	    if (($uname eq $env{'user.name'}) &&
 6532: 		($udom eq $env{'user.domain'})) {
 6533: 		return $env{join('.',('environment',$qualifierrest))};
 6534: 	    } else {
 6535: 		my %returnhash;
 6536: 		if (!$publicuser) {
 6537: 		    %returnhash=&userenvironment($udom,$uname,
 6538: 						 $qualifierrest);
 6539: 		}
 6540: 		return $returnhash{$qualifierrest};
 6541: 	    }
 6542: # ----------------------------------------------------------------- user.course
 6543:         } elsif ($space eq 'course') {
 6544: 	    # FIXME - not supporting calls for a specific user
 6545:             return $env{join('.',('request.course',$qualifier))};
 6546: # ------------------------------------------------------------------- user.role
 6547:         } elsif ($space eq 'role') {
 6548: 	    # FIXME - not supporting calls for a specific user
 6549:             my ($role,$where)=split(/\./,$env{'request.role'});
 6550:             if ($qualifier eq 'value') {
 6551: 		return $role;
 6552:             } elsif ($qualifier eq 'extent') {
 6553:                 return $where;
 6554:             }
 6555: # ----------------------------------------------------------------- user.domain
 6556:         } elsif ($space eq 'domain') {
 6557:             return $udom;
 6558: # ------------------------------------------------------------------- user.name
 6559:         } elsif ($space eq 'name') {
 6560:             return $uname;
 6561: # ---------------------------------------------------- Any other user namespace
 6562:         } else {
 6563: 	    my %reply;
 6564: 	    if (!$publicuser) {
 6565: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6566: 	    }
 6567: 	    return $reply{$qualifierrest};
 6568:         }
 6569:     } elsif ($realm eq 'query') {
 6570: # ---------------------------------------------- pull stuff out of query string
 6571:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6572: 						[$spacequalifierrest]);
 6573: 	return $env{'form.'.$spacequalifierrest}; 
 6574:    } elsif ($realm eq 'request') {
 6575: # ------------------------------------------------------------- request.browser
 6576:         if ($space eq 'browser') {
 6577: 	    if ($qualifier eq 'textremote') {
 6578: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6579: 		    return 1;
 6580: 		} else {
 6581: 		    return 0;
 6582: 		}
 6583: 	    } else {
 6584: 		return $env{'browser.'.$qualifier};
 6585: 	    }
 6586: # ------------------------------------------------------------ request.filename
 6587:         } else {
 6588:             return $env{'request.'.$spacequalifierrest};
 6589:         }
 6590:     } elsif ($realm eq 'course') {
 6591: # ---------------------------------------------------------- course.description
 6592:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6593:     } elsif ($realm eq 'resource') {
 6594: 
 6595: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6596: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6597: 	}
 6598: 
 6599: 	if ($space eq 'title') {
 6600: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6601: 	    return &gettitle($symbparm);
 6602: 	}
 6603: 	
 6604: 	if ($space eq 'map') {
 6605: 	    my ($map) = &decode_symb($symbparm);
 6606: 	    return &symbread($map);
 6607: 	}
 6608: 	if ($space eq 'filename') {
 6609: 	    if ($symbparm) {
 6610: 		return &clutter((&decode_symb($symbparm))[2]);
 6611: 	    }
 6612: 	    return &hreflocation('',$env{'request.filename'});
 6613: 	}
 6614: 
 6615: 	my ($section, $group, @groups);
 6616: 	my ($courselevelm,$courselevel);
 6617: 	if ($symbparm && defined($courseid) && 
 6618: 	    $courseid eq $env{'request.course.id'}) {
 6619: 
 6620: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6621: 
 6622: # ----------------------------------------------------- Cascading lookup scheme
 6623: 	    my $symbp=$symbparm;
 6624: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6625: 
 6626: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6627: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6628: 
 6629: 	    if (($env{'user.name'} eq $uname) &&
 6630: 		($env{'user.domain'} eq $udom)) {
 6631: 		$section=$env{'request.course.sec'};
 6632:                 @groups = split(/:/,$env{'request.course.groups'});  
 6633:                 @groups=&sort_course_groups($courseid,@groups); 
 6634: 	    } else {
 6635: 		if (! defined($usection)) {
 6636: 		    $section=&getsection($udom,$uname,$courseid);
 6637: 		} else {
 6638: 		    $section = $usection;
 6639: 		}
 6640:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6641: 	    }
 6642: 
 6643: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6644: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6645: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6646: 
 6647: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6648: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6649: 	    $courselevelm=$courseid.'.'.$mapparm;
 6650: 
 6651: # ----------------------------------------------------------- first, check user
 6652: 
 6653: 	    my $userreply=&resdata($uname,$udom,'user',
 6654: 				       ([$courselevelr,'resource'],
 6655: 					[$courselevelm,'map'     ],
 6656: 					[$courselevel, 'course'  ]));
 6657: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6658: 
 6659: # ------------------------------------------------ second, check some of course
 6660:             my $coursereply;
 6661:             if (@groups > 0) {
 6662:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6663:                                        $mapparm,$spacequalifierrest);
 6664:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6665:             }
 6666: 
 6667: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6668: 				  $env{'course.'.$courseid.'.domain'},
 6669: 				  'course',
 6670: 				  ([$seclevelr,   'resource'],
 6671: 				   [$seclevelm,   'map'     ],
 6672: 				   [$seclevel,    'course'  ],
 6673: 				   [$courselevelr,'resource']));
 6674: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6675: 
 6676: # ------------------------------------------------------ third, check map parms
 6677: 	    my %parmhash=();
 6678: 	    my $thisparm='';
 6679: 	    if (tie(%parmhash,'GDBM_File',
 6680: 		    $env{'request.course.fn'}.'_parms.db',
 6681: 		    &GDBM_READER(),0640)) {
 6682: 		$thisparm=$parmhash{$symbparm};
 6683: 		untie(%parmhash);
 6684: 	    }
 6685: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6686: 	}
 6687: # ------------------------------------------ fourth, look in resource metadata
 6688: 
 6689: 	$spacequalifierrest=~s/\./\_/;
 6690: 	my $filename;
 6691: 	if (!$symbparm) { $symbparm=&symbread(); }
 6692: 	if ($symbparm) {
 6693: 	    $filename=(&decode_symb($symbparm))[2];
 6694: 	} else {
 6695: 	    $filename=$env{'request.filename'};
 6696: 	}
 6697: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6698: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6699: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6700: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6701: 
 6702: # ---------------------------------------------- fourth, look in rest of course
 6703: 	if ($symbparm && defined($courseid) && 
 6704: 	    $courseid eq $env{'request.course.id'}) {
 6705: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6706: 				     $env{'course.'.$courseid.'.domain'},
 6707: 				     'course',
 6708: 				     ([$courselevelm,'map'   ],
 6709: 				      [$courselevel, 'course']));
 6710: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6711: 	}
 6712: # ------------------------------------------------------------------ Cascade up
 6713: 	unless ($space eq '0') {
 6714: 	    my @parts=split(/_/,$space);
 6715: 	    my $id=pop(@parts);
 6716: 	    my $part=join('_',@parts);
 6717: 	    if ($part eq '') { $part='0'; }
 6718: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6719: 				 $symbparm,$udom,$uname,$section,1);
 6720: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6721: 	}
 6722: 	if ($recurse) { return undef; }
 6723: 	my $pack_def=&packages_tab_default($filename,$varname);
 6724: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6725: # ---------------------------------------------------- Any other user namespace
 6726:     } elsif ($realm eq 'environment') {
 6727: # ----------------------------------------------------------------- environment
 6728: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6729: 	    return $env{'environment.'.$spacequalifierrest};
 6730: 	} else {
 6731: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6732: 		return '';
 6733: 	    }
 6734: 	    my %returnhash=&userenvironment($udom,$uname,
 6735: 					    $spacequalifierrest);
 6736: 	    return $returnhash{$spacequalifierrest};
 6737: 	}
 6738:     } elsif ($realm eq 'system') {
 6739: # ----------------------------------------------------------------- system.time
 6740: 	if ($space eq 'time') {
 6741: 	    return time;
 6742:         }
 6743:     } elsif ($realm eq 'server') {
 6744: # ----------------------------------------------------------------- system.time
 6745: 	if ($space eq 'name') {
 6746: 	    return $ENV{'SERVER_NAME'};
 6747:         }
 6748:     }
 6749:     return '';
 6750: }
 6751: 
 6752: sub get_reply {
 6753:     my ($reply_value) = @_;
 6754:     if (ref($reply_value) eq 'ARRAY') {
 6755:         if (wantarray) {
 6756: 	    return @$reply_value;
 6757:         }
 6758:         return $reply_value->[0];
 6759:     } else {
 6760:         return $reply_value;
 6761:     }
 6762: }
 6763: 
 6764: sub check_group_parms {
 6765:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6766:     my @groupitems = ();
 6767:     my $resultitem;
 6768:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6769:     foreach my $group (@{$groups}) {
 6770:         foreach my $level (@levels) {
 6771:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6772:              push(@groupitems,[$item,$level->[1]]);
 6773:         }
 6774:     }
 6775:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6776:                             $env{'course.'.$courseid.'.domain'},
 6777:                                      'course',@groupitems);
 6778:     return $coursereply;
 6779: }
 6780: 
 6781: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6782:     my ($courseid,@groups) = @_;
 6783:     @groups = sort(@groups);
 6784:     return @groups;
 6785: }
 6786: 
 6787: sub packages_tab_default {
 6788:     my ($uri,$varname)=@_;
 6789:     my (undef,$part,$name)=split(/\./,$varname);
 6790: 
 6791:     my (@extension,@specifics,$do_default);
 6792:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6793: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6794: 	if ($pack_type eq 'default') {
 6795: 	    $do_default=1;
 6796: 	} elsif ($pack_type eq 'extension') {
 6797: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6798: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6799: 	    # only look at packages defaults for packages that this id is
 6800: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6801: 	}
 6802:     }
 6803:     # first look for a package that matches the requested part id
 6804:     foreach my $package (@specifics) {
 6805: 	my (undef,$pack_type,$pack_part)=@{$package};
 6806: 	next if ($pack_part ne $part);
 6807: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6808: 	    return $packagetab{"$pack_type&$name&default"};
 6809: 	}
 6810:     }
 6811:     # look for any possible matching non extension_ package
 6812:     foreach my $package (@specifics) {
 6813: 	my (undef,$pack_type,$pack_part)=@{$package};
 6814: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6815: 	    return $packagetab{"$pack_type&$name&default"};
 6816: 	}
 6817: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6818: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6819: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6820: 	}
 6821:     }
 6822:     # look for any posible extension_ match
 6823:     foreach my $package (@extension) {
 6824: 	my ($package,$pack_type)=@{$package};
 6825: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6826: 	    return $packagetab{"$pack_type&$name&default"};
 6827: 	}
 6828: 	if (defined($packagetab{$package."&$name&default"})) {
 6829: 	    return $packagetab{$package."&$name&default"};
 6830: 	}
 6831:     }
 6832:     # look for a global default setting
 6833:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6834: 	return $packagetab{"default&$name&default"};
 6835:     }
 6836:     return undef;
 6837: }
 6838: 
 6839: sub add_prefix_and_part {
 6840:     my ($prefix,$part)=@_;
 6841:     my $keyroot;
 6842:     if (defined($prefix) && $prefix !~ /^__/) {
 6843: 	# prefix that has a part already
 6844: 	$keyroot=$prefix;
 6845:     } elsif (defined($prefix)) {
 6846: 	# prefix that is missing a part
 6847: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6848:     } else {
 6849: 	# no prefix at all
 6850: 	if (defined($part)) { $keyroot='_'.$part; }
 6851:     }
 6852:     return $keyroot;
 6853: }
 6854: 
 6855: # ---------------------------------------------------------------- Get metadata
 6856: 
 6857: my %metaentry;
 6858: sub metadata {
 6859:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6860:     $uri=&declutter($uri);
 6861:     # if it is a non metadata possible uri return quickly
 6862:     if (($uri eq '') || 
 6863: 	(($uri =~ m|^/*adm/|) && 
 6864: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6865:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6866: 	return undef;
 6867:     }
 6868:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6869: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6870: 	return undef;
 6871:     }
 6872:     my $filename=$uri;
 6873:     $uri=~s/\.meta$//;
 6874: #
 6875: # Is the metadata already cached?
 6876: # Look at timestamp of caching
 6877: # Everything is cached by the main uri, libraries are never directly cached
 6878: #
 6879:     if (!defined($liburi)) {
 6880: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6881: 	if (defined($cached)) { return $result->{':'.$what}; }
 6882:     }
 6883:     {
 6884: #
 6885: # Is this a recursive call for a library?
 6886: #
 6887: #	if (! exists($metacache{$uri})) {
 6888: #	    $metacache{$uri}={};
 6889: #	}
 6890: 	my $cachetime = 60*60;
 6891:         if ($liburi) {
 6892: 	    $liburi=&declutter($liburi);
 6893:             $filename=$liburi;
 6894:         } else {
 6895: 	    &devalidate_cache_new('meta',$uri);
 6896: 	    undef(%metaentry);
 6897: 	}
 6898:         my %metathesekeys=();
 6899:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6900: 	my $metastring;
 6901: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6902: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6903: 	    $metastring = 
 6904: 		&Apache::lonnet::ssi_body($which,
 6905: 					  ('grade_target' => 'meta'));
 6906: 	    $cachetime = 1; # only want this cached in the child not long term
 6907: 	} elsif ($uri !~ m -^(editupload)/-) {
 6908: 	    my $file=&filelocation('',&clutter($filename));
 6909: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6910: 	    $metastring=&getfile($file);
 6911: 	}
 6912:         my $parser=HTML::LCParser->new(\$metastring);
 6913:         my $token;
 6914:         undef %metathesekeys;
 6915:         while ($token=$parser->get_token) {
 6916: 	    if ($token->[0] eq 'S') {
 6917: 		if (defined($token->[2]->{'package'})) {
 6918: #
 6919: # This is a package - get package info
 6920: #
 6921: 		    my $package=$token->[2]->{'package'};
 6922: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6923: 		    if (defined($token->[2]->{'id'})) { 
 6924: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6925: 		    }
 6926: 		    if ($metaentry{':packages'}) {
 6927: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6928: 		    } else {
 6929: 			$metaentry{':packages'}=$package.$keyroot;
 6930: 		    }
 6931: 		    foreach my $pack_entry (keys(%packagetab)) {
 6932: 			my $part=$keyroot;
 6933: 			$part=~s/^\_//;
 6934: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6935: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6936: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6937: 			    # ignore package.tab specified default values
 6938:                             # here &package_tab_default() will fetch those
 6939: 			    if ($subp eq 'default') { next; }
 6940: 			    my $value=$packagetab{$pack_entry};
 6941: 			    my $unikey;
 6942: 			    if ($pack =~ /_0$/) {
 6943: 				$unikey='parameter_0_'.$name;
 6944: 				$part=0;
 6945: 			    } else {
 6946: 				$unikey='parameter'.$keyroot.'_'.$name;
 6947: 			    }
 6948: 			    if ($subp eq 'display') {
 6949: 				$value.=' [Part: '.$part.']';
 6950: 			    }
 6951: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6952: 			    $metathesekeys{$unikey}=1;
 6953: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6954: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6955: 			    }
 6956: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6957: 				$metaentry{':'.$unikey}=
 6958: 				    $metaentry{':'.$unikey.'.default'};
 6959: 			    }
 6960: 			}
 6961: 		    }
 6962: 		} else {
 6963: #
 6964: # This is not a package - some other kind of start tag
 6965: #
 6966: 		    my $entry=$token->[1];
 6967: 		    my $unikey;
 6968: 		    if ($entry eq 'import') {
 6969: 			$unikey='';
 6970: 		    } else {
 6971: 			$unikey=$entry;
 6972: 		    }
 6973: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6974: 
 6975: 		    if (defined($token->[2]->{'id'})) { 
 6976: 			$unikey.='_'.$token->[2]->{'id'}; 
 6977: 		    }
 6978: 
 6979: 		    if ($entry eq 'import') {
 6980: #
 6981: # Importing a library here
 6982: #
 6983: 			if ($depthcount<20) {
 6984: 			    my $location=$parser->get_text('/import');
 6985: 			    my $dir=$filename;
 6986: 			    $dir=~s|[^/]*$||;
 6987: 			    $location=&filelocation($dir,$location);
 6988: 			    my $metadata = 
 6989: 				&metadata($uri,'keys', $location,$unikey,
 6990: 					  $depthcount+1);
 6991: 			    foreach my $meta (split(',',$metadata)) {
 6992: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6993: 				$metathesekeys{$meta}=1;
 6994: 			    }
 6995: 			}
 6996: 		    } else { 
 6997: 			
 6998: 			if (defined($token->[2]->{'name'})) { 
 6999: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7000: 			}
 7001: 			$metathesekeys{$unikey}=1;
 7002: 			foreach my $param (@{$token->[3]}) {
 7003: 			    $metaentry{':'.$unikey.'.'.$param} =
 7004: 				$token->[2]->{$param};
 7005: 			}
 7006: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7007: 			my $default=$metaentry{':'.$unikey.'.default'};
 7008: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7009: 		 # only ws inside the tag, and not in default, so use default
 7010: 		 # as value
 7011: 			    $metaentry{':'.$unikey}=$default;
 7012: 			} elsif ( $internaltext =~ /\S/ ) {
 7013: 		  # something interesting inside the tag
 7014: 			    $metaentry{':'.$unikey}=$internaltext;
 7015: 			} else {
 7016: 		  # no interesting values, don't set a default
 7017: 			}
 7018: # end of not-a-package not-a-library import
 7019: 		    }
 7020: # end of not-a-package start tag
 7021: 		}
 7022: # the next is the end of "start tag"
 7023: 	    }
 7024: 	}
 7025: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7026: 	$extension = lc($extension);
 7027: 	if ($extension eq 'htm') { $extension='html'; }
 7028: 
 7029: 	foreach my $key (keys(%packagetab)) {
 7030: 	    #no specific packages #how's our extension
 7031: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7032: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7033: 					 \%metathesekeys);
 7034: 	}
 7035: 
 7036: 	if (!exists($metaentry{':packages'})
 7037: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7038: 	    foreach my $key (keys(%packagetab)) {
 7039: 		#no specific packages well let's get default then
 7040: 		if ($key!~/^default&/) { next; }
 7041: 		&metadata_create_package_def($uri,$key,'default',
 7042: 					     \%metathesekeys);
 7043: 	    }
 7044: 	}
 7045: # are there custom rights to evaluate
 7046: 	if ($metaentry{':copyright'} eq 'custom') {
 7047: 
 7048:     #
 7049:     # Importing a rights file here
 7050:     #
 7051: 	    unless ($depthcount) {
 7052: 		my $location=$metaentry{':customdistributionfile'};
 7053: 		my $dir=$filename;
 7054: 		$dir=~s|[^/]*$||;
 7055: 		$location=&filelocation($dir,$location);
 7056: 		my $rights_metadata =
 7057: 		    &metadata($uri,'keys',$location,'_rights',
 7058: 			      $depthcount+1);
 7059: 		foreach my $rights (split(',',$rights_metadata)) {
 7060: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7061: 		    $metathesekeys{$rights}=1;
 7062: 		}
 7063: 	    }
 7064: 	}
 7065: 	# uniqifiy package listing
 7066: 	my %seen;
 7067: 	my @uniq_packages =
 7068: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7069: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7070: 
 7071: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7072: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7073: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7074: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7075: # this is the end of "was not already recently cached
 7076:     }
 7077:     return $metaentry{':'.$what};
 7078: }
 7079: 
 7080: sub metadata_create_package_def {
 7081:     my ($uri,$key,$package,$metathesekeys)=@_;
 7082:     my ($pack,$name,$subp)=split(/\&/,$key);
 7083:     if ($subp eq 'default') { next; }
 7084:     
 7085:     if (defined($metaentry{':packages'})) {
 7086: 	$metaentry{':packages'}.=','.$package;
 7087:     } else {
 7088: 	$metaentry{':packages'}=$package;
 7089:     }
 7090:     my $value=$packagetab{$key};
 7091:     my $unikey;
 7092:     $unikey='parameter_0_'.$name;
 7093:     $metaentry{':'.$unikey.'.part'}=0;
 7094:     $$metathesekeys{$unikey}=1;
 7095:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7096: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7097:     }
 7098:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7099: 	$metaentry{':'.$unikey}=
 7100: 	    $metaentry{':'.$unikey.'.default'};
 7101:     }
 7102: }
 7103: 
 7104: sub metadata_generate_part0 {
 7105:     my ($metadata,$metacache,$uri) = @_;
 7106:     my %allnames;
 7107:     foreach my $metakey (keys(%$metadata)) {
 7108: 	if ($metakey=~/^parameter\_(.*)/) {
 7109: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7110: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7111: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7112: 	    $allnames{$name}=$part;
 7113: 	  }
 7114: 	}
 7115:     }
 7116:     foreach my $name (keys(%allnames)) {
 7117:       $$metadata{"parameter_0_$name"}=1;
 7118:       my $key=":parameter_0_$name";
 7119:       $$metacache{"$key.part"}='0';
 7120:       $$metacache{"$key.name"}=$name;
 7121:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7122: 					   $allnames{$name}.'_'.$name.
 7123: 					   '.type'};
 7124:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7125: 			     '.display'};
 7126:       my $expr='[Part: '.$allnames{$name}.']';
 7127:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7128:       $$metacache{"$key.display"}=$olddis;
 7129:     }
 7130: }
 7131: 
 7132: # ------------------------------------------------------ Devalidate title cache
 7133: 
 7134: sub devalidate_title_cache {
 7135:     my ($url)=@_;
 7136:     if (!$env{'request.course.id'}) { return; }
 7137:     my $symb=&symbread($url);
 7138:     if (!$symb) { return; }
 7139:     my $key=$env{'request.course.id'}."\0".$symb;
 7140:     &devalidate_cache_new('title',$key);
 7141: }
 7142: 
 7143: # ------------------------------------------------- Get the title of a resource
 7144: 
 7145: sub gettitle {
 7146:     my $urlsymb=shift;
 7147:     my $symb=&symbread($urlsymb);
 7148:     if ($symb) {
 7149: 	my $key=$env{'request.course.id'}."\0".$symb;
 7150: 	my ($result,$cached)=&is_cached_new('title',$key);
 7151: 	if (defined($cached)) { 
 7152: 	    return $result;
 7153: 	}
 7154: 	my ($map,$resid,$url)=&decode_symb($symb);
 7155: 	my $title='';
 7156: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7157: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7158: 	} else {
 7159: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7160: 		    &GDBM_READER(),0640)) {
 7161: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7162: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7163: 		untie(%bighash);
 7164: 	    }
 7165: 	}
 7166: 	$title=~s/\&colon\;/\:/gs;
 7167: 	if ($title) {
 7168: 	    return &do_cache_new('title',$key,$title,600);
 7169: 	}
 7170: 	$urlsymb=$url;
 7171:     }
 7172:     my $title=&metadata($urlsymb,'title');
 7173:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7174:     return $title;
 7175: }
 7176: 
 7177: sub get_slot {
 7178:     my ($which,$cnum,$cdom)=@_;
 7179:     if (!$cnum || !$cdom) {
 7180: 	(undef,my $courseid)=&whichuser();
 7181: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7182: 	$cnum=$env{'course.'.$courseid.'.num'};
 7183:     }
 7184:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7185:     my %slotinfo;
 7186:     if (exists($remembered{$key})) {
 7187: 	$slotinfo{$which} = $remembered{$key};
 7188:     } else {
 7189: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7190: 	&Apache::lonhomework::showhash(%slotinfo);
 7191: 	my ($tmp)=keys(%slotinfo);
 7192: 	if ($tmp=~/^error:/) { return (); }
 7193: 	$remembered{$key} = $slotinfo{$which};
 7194:     }
 7195:     if (ref($slotinfo{$which}) eq 'HASH') {
 7196: 	return %{$slotinfo{$which}};
 7197:     }
 7198:     return $slotinfo{$which};
 7199: }
 7200: # ------------------------------------------------- Update symbolic store links
 7201: 
 7202: sub symblist {
 7203:     my ($mapname,%newhash)=@_;
 7204:     $mapname=&deversion(&declutter($mapname));
 7205:     my %hash;
 7206:     if (($env{'request.course.fn'}) && (%newhash)) {
 7207:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7208:                       &GDBM_WRCREAT(),0640)) {
 7209: 	    foreach my $url (keys %newhash) {
 7210: 		next if ($url eq 'last_known'
 7211: 			 && $env{'form.no_update_last_known'});
 7212: 		$hash{declutter($url)}=&encode_symb($mapname,
 7213: 						    $newhash{$url}->[1],
 7214: 						    $newhash{$url}->[0]);
 7215:             }
 7216:             if (untie(%hash)) {
 7217: 		return 'ok';
 7218:             }
 7219:         }
 7220:     }
 7221:     return 'error';
 7222: }
 7223: 
 7224: # --------------------------------------------------------------- Verify a symb
 7225: 
 7226: sub symbverify {
 7227:     my ($symb,$thisurl)=@_;
 7228:     my $thisfn=$thisurl;
 7229:     $thisfn=&declutter($thisfn);
 7230: # direct jump to resource in page or to a sequence - will construct own symbs
 7231:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7232: # check URL part
 7233:     my ($map,$resid,$url)=&decode_symb($symb);
 7234: 
 7235:     unless ($url eq $thisfn) { return 0; }
 7236: 
 7237:     $symb=&symbclean($symb);
 7238:     $thisurl=&deversion($thisurl);
 7239:     $thisfn=&deversion($thisfn);
 7240: 
 7241:     my %bighash;
 7242:     my $okay=0;
 7243: 
 7244:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7245:                             &GDBM_READER(),0640)) {
 7246:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7247:         unless ($ids) { 
 7248:            $ids=$bighash{'ids_/'.$thisurl};
 7249:         }
 7250:         if ($ids) {
 7251: # ------------------------------------------------------------------- Has ID(s)
 7252: 	    foreach my $id (split(/\,/,$ids)) {
 7253: 	       my ($mapid,$resid)=split(/\./,$id);
 7254:                if (
 7255:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7256:    eq $symb) { 
 7257: 		   if (($env{'request.role.adv'}) ||
 7258: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7259: 		       $okay=1; 
 7260: 		   }
 7261: 	       }
 7262: 	   }
 7263:         }
 7264: 	untie(%bighash);
 7265:     }
 7266:     return $okay;
 7267: }
 7268: 
 7269: # --------------------------------------------------------------- Clean-up symb
 7270: 
 7271: sub symbclean {
 7272:     my $symb=shift;
 7273:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7274: # remove version from map
 7275:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7276: 
 7277: # remove version from URL
 7278:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7279: 
 7280: # remove wrapper
 7281: 
 7282:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7283:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7284:     return $symb;
 7285: }
 7286: 
 7287: # ---------------------------------------------- Split symb to find map and url
 7288: 
 7289: sub encode_symb {
 7290:     my ($map,$resid,$url)=@_;
 7291:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7292: }
 7293: 
 7294: sub decode_symb {
 7295:     my $symb=shift;
 7296:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7297:     my ($map,$resid,$url)=split(/___/,$symb);
 7298:     return (&fixversion($map),$resid,&fixversion($url));
 7299: }
 7300: 
 7301: sub fixversion {
 7302:     my $fn=shift;
 7303:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7304:     my %bighash;
 7305:     my $uri=&clutter($fn);
 7306:     my $key=$env{'request.course.id'}.'_'.$uri;
 7307: # is this cached?
 7308:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7309:     if (defined($cached)) { return $result; }
 7310: # unfortunately not cached, or expired
 7311:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7312: 	    &GDBM_READER(),0640)) {
 7313:  	if ($bighash{'version_'.$uri}) {
 7314:  	    my $version=$bighash{'version_'.$uri};
 7315:  	    unless (($version eq 'mostrecent') || 
 7316: 		    ($version==&getversion($uri))) {
 7317:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7318:  	    }
 7319:  	}
 7320:  	untie %bighash;
 7321:     }
 7322:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7323: }
 7324: 
 7325: sub deversion {
 7326:     my $url=shift;
 7327:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7328:     return $url;
 7329: }
 7330: 
 7331: # ------------------------------------------------------ Return symb list entry
 7332: 
 7333: sub symbread {
 7334:     my ($thisfn,$donotrecurse)=@_;
 7335:     my $cache_str='request.symbread.cached.'.$thisfn;
 7336:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7337: # no filename provided? try from environment
 7338:     unless ($thisfn) {
 7339:         if ($env{'request.symb'}) {
 7340: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7341: 	}
 7342: 	$thisfn=$env{'request.filename'};
 7343:     }
 7344:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7345: # is that filename actually a symb? Verify, clean, and return
 7346:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7347: 	if (&symbverify($thisfn,$1)) {
 7348: 	    return $env{$cache_str}=&symbclean($thisfn);
 7349: 	}
 7350:     }
 7351:     $thisfn=declutter($thisfn);
 7352:     my %hash;
 7353:     my %bighash;
 7354:     my $syval='';
 7355:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7356:         my $targetfn = $thisfn;
 7357:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7358:             $targetfn = 'adm/wrapper/'.$thisfn;
 7359:         }
 7360: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7361: 	    $targetfn=$1;
 7362: 	}
 7363:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7364:                       &GDBM_READER(),0640)) {
 7365: 	    $syval=$hash{$targetfn};
 7366:             untie(%hash);
 7367:         }
 7368: # ---------------------------------------------------------- There was an entry
 7369:         if ($syval) {
 7370: 	    #unless ($syval=~/\_\d+$/) {
 7371: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7372: 		    #&appenv('request.ambiguous' => $thisfn);
 7373: 		    #return $env{$cache_str}='';
 7374: 		#}    
 7375: 		#$syval.=$1;
 7376: 	    #}
 7377:         } else {
 7378: # ------------------------------------------------------- Was not in symb table
 7379:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7380:                             &GDBM_READER(),0640)) {
 7381: # ---------------------------------------------- Get ID(s) for current resource
 7382:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7383:               unless ($ids) { 
 7384:                  $ids=$bighash{'ids_/'.$thisfn};
 7385:               }
 7386:               unless ($ids) {
 7387: # alias?
 7388: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7389:               }
 7390:               if ($ids) {
 7391: # ------------------------------------------------------------------- Has ID(s)
 7392:                  my @possibilities=split(/\,/,$ids);
 7393:                  if ($#possibilities==0) {
 7394: # ----------------------------------------------- There is only one possibility
 7395: 		     my ($mapid,$resid)=split(/\./,$ids);
 7396: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7397: 						    $resid,$thisfn);
 7398:                  } elsif (!$donotrecurse) {
 7399: # ------------------------------------------ There is more than one possibility
 7400:                      my $realpossible=0;
 7401:                      foreach my $id (@possibilities) {
 7402: 			 my $file=$bighash{'src_'.$id};
 7403:                          if (&allowed('bre',$file)) {
 7404:          		    my ($mapid,$resid)=split(/\./,$id);
 7405:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7406: 				$realpossible++;
 7407:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7408: 						    $resid,$thisfn);
 7409:                             }
 7410: 			 }
 7411:                      }
 7412: 		     if ($realpossible!=1) { $syval=''; }
 7413:                  } else {
 7414:                      $syval='';
 7415:                  }
 7416: 	      }
 7417:               untie(%bighash)
 7418:            }
 7419:         }
 7420:         if ($syval) {
 7421: 	    return $env{$cache_str}=$syval;
 7422:         }
 7423:     }
 7424:     &appenv('request.ambiguous' => $thisfn);
 7425:     return $env{$cache_str}='';
 7426: }
 7427: 
 7428: # ---------------------------------------------------------- Return random seed
 7429: 
 7430: sub numval {
 7431:     my $txt=shift;
 7432:     $txt=~tr/A-J/0-9/;
 7433:     $txt=~tr/a-j/0-9/;
 7434:     $txt=~tr/K-T/0-9/;
 7435:     $txt=~tr/k-t/0-9/;
 7436:     $txt=~tr/U-Z/0-5/;
 7437:     $txt=~tr/u-z/0-5/;
 7438:     $txt=~s/\D//g;
 7439:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7440:     return int($txt);
 7441: }
 7442: 
 7443: sub numval2 {
 7444:     my $txt=shift;
 7445:     $txt=~tr/A-J/0-9/;
 7446:     $txt=~tr/a-j/0-9/;
 7447:     $txt=~tr/K-T/0-9/;
 7448:     $txt=~tr/k-t/0-9/;
 7449:     $txt=~tr/U-Z/0-5/;
 7450:     $txt=~tr/u-z/0-5/;
 7451:     $txt=~s/\D//g;
 7452:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7453:     my $total;
 7454:     foreach my $val (@txts) { $total+=$val; }
 7455:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7456:     return int($total);
 7457: }
 7458: 
 7459: sub numval3 {
 7460:     use integer;
 7461:     my $txt=shift;
 7462:     $txt=~tr/A-J/0-9/;
 7463:     $txt=~tr/a-j/0-9/;
 7464:     $txt=~tr/K-T/0-9/;
 7465:     $txt=~tr/k-t/0-9/;
 7466:     $txt=~tr/U-Z/0-5/;
 7467:     $txt=~tr/u-z/0-5/;
 7468:     $txt=~s/\D//g;
 7469:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7470:     my $total;
 7471:     foreach my $val (@txts) { $total+=$val; }
 7472:     if ($_64bit) { $total=(($total<<32)>>32); }
 7473:     return $total;
 7474: }
 7475: 
 7476: sub digest {
 7477:     my ($data)=@_;
 7478:     my $digest=&Digest::MD5::md5($data);
 7479:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7480:     my ($e,$f);
 7481:     {
 7482:         use integer;
 7483:         $e=($a+$b);
 7484:         $f=($c+$d);
 7485:         if ($_64bit) {
 7486:             $e=(($e<<32)>>32);
 7487:             $f=(($f<<32)>>32);
 7488:         }
 7489:     }
 7490:     if (wantarray) {
 7491: 	return ($e,$f);
 7492:     } else {
 7493: 	my $g;
 7494: 	{
 7495: 	    use integer;
 7496: 	    $g=($e+$f);
 7497: 	    if ($_64bit) {
 7498: 		$g=(($g<<32)>>32);
 7499: 	    }
 7500: 	}
 7501: 	return $g;
 7502:     }
 7503: }
 7504: 
 7505: sub latest_rnd_algorithm_id {
 7506:     return '64bit5';
 7507: }
 7508: 
 7509: sub get_rand_alg {
 7510:     my ($courseid)=@_;
 7511:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7512:     if ($courseid) {
 7513: 	return $env{"course.$courseid.rndseed"};
 7514:     }
 7515:     return &latest_rnd_algorithm_id();
 7516: }
 7517: 
 7518: sub validCODE {
 7519:     my ($CODE)=@_;
 7520:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7521:     return 0;
 7522: }
 7523: 
 7524: sub getCODE {
 7525:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7526:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7527: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7528: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7529: 	return $Apache::lonhomework::history{'resource.CODE'};
 7530:     }
 7531:     return undef;
 7532: }
 7533: 
 7534: sub rndseed {
 7535:     my ($symb,$courseid,$domain,$username)=@_;
 7536:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7537:     if (!defined($symb)) {
 7538: 	unless ($symb=$wsymb) { return time; }
 7539:     }
 7540:     if (!$courseid) { $courseid=$wcourseid; }
 7541:     if (!$domain) { $domain=$wdomain; }
 7542:     if (!$username) { $username=$wusername }
 7543:     my $which=&get_rand_alg();
 7544: 
 7545:     if (defined(&getCODE())) {
 7546: 	if ($which eq '64bit5') {
 7547: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7548: 	} elsif ($which eq '64bit4') {
 7549: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7550: 	} else {
 7551: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7552: 	}
 7553:     } elsif ($which eq '64bit5') {
 7554: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7555:     } elsif ($which eq '64bit4') {
 7556: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7557:     } elsif ($which eq '64bit3') {
 7558: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7559:     } elsif ($which eq '64bit2') {
 7560: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7561:     } elsif ($which eq '64bit') {
 7562: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7563:     }
 7564:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7565: }
 7566: 
 7567: sub rndseed_32bit {
 7568:     my ($symb,$courseid,$domain,$username)=@_;
 7569:     {
 7570: 	use integer;
 7571: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7572: 	my $symbseed=numval($symb) << 22;
 7573: 	my $namechck=unpack("%32C*",$username) << 17;
 7574: 	my $nameseed=numval($username) << 12;
 7575: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7576: 	my $courseseed=unpack("%32C*",$courseid);
 7577: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7578: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7579: 	#&logthis("rndseed :$num:$symb");
 7580: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7581: 	return $num;
 7582:     }
 7583: }
 7584: 
 7585: sub rndseed_64bit {
 7586:     my ($symb,$courseid,$domain,$username)=@_;
 7587:     {
 7588: 	use integer;
 7589: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7590: 	my $symbseed=numval($symb) << 10;
 7591: 	my $namechck=unpack("%32S*",$username);
 7592: 	
 7593: 	my $nameseed=numval($username) << 21;
 7594: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7595: 	my $courseseed=unpack("%32S*",$courseid);
 7596: 	
 7597: 	my $num1=$symbchck+$symbseed+$namechck;
 7598: 	my $num2=$nameseed+$domainseed+$courseseed;
 7599: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7600: 	#&logthis("rndseed :$num:$symb");
 7601: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7602: 	return "$num1,$num2";
 7603:     }
 7604: }
 7605: 
 7606: sub rndseed_64bit2 {
 7607:     my ($symb,$courseid,$domain,$username)=@_;
 7608:     {
 7609: 	use integer;
 7610: 	# strings need to be an even # of cahracters long, it it is odd the
 7611:         # last characters gets thrown away
 7612: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7613: 	my $symbseed=numval($symb) << 10;
 7614: 	my $namechck=unpack("%32S*",$username.' ');
 7615: 	
 7616: 	my $nameseed=numval($username) << 21;
 7617: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7618: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7619: 	
 7620: 	my $num1=$symbchck+$symbseed+$namechck;
 7621: 	my $num2=$nameseed+$domainseed+$courseseed;
 7622: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7623: 	#&logthis("rndseed :$num:$symb");
 7624: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7625: 	return "$num1,$num2";
 7626:     }
 7627: }
 7628: 
 7629: sub rndseed_64bit3 {
 7630:     my ($symb,$courseid,$domain,$username)=@_;
 7631:     {
 7632: 	use integer;
 7633: 	# strings need to be an even # of cahracters long, it it is odd the
 7634:         # last characters gets thrown away
 7635: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7636: 	my $symbseed=numval2($symb) << 10;
 7637: 	my $namechck=unpack("%32S*",$username.' ');
 7638: 	
 7639: 	my $nameseed=numval2($username) << 21;
 7640: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7641: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7642: 	
 7643: 	my $num1=$symbchck+$symbseed+$namechck;
 7644: 	my $num2=$nameseed+$domainseed+$courseseed;
 7645: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7646: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7647: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7648: 	
 7649: 	return "$num1:$num2";
 7650:     }
 7651: }
 7652: 
 7653: sub rndseed_64bit4 {
 7654:     my ($symb,$courseid,$domain,$username)=@_;
 7655:     {
 7656: 	use integer;
 7657: 	# strings need to be an even # of cahracters long, it it is odd the
 7658:         # last characters gets thrown away
 7659: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7660: 	my $symbseed=numval3($symb) << 10;
 7661: 	my $namechck=unpack("%32S*",$username.' ');
 7662: 	
 7663: 	my $nameseed=numval3($username) << 21;
 7664: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7665: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7666: 	
 7667: 	my $num1=$symbchck+$symbseed+$namechck;
 7668: 	my $num2=$nameseed+$domainseed+$courseseed;
 7669: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7670: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7671: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7672: 	
 7673: 	return "$num1:$num2";
 7674:     }
 7675: }
 7676: 
 7677: sub rndseed_64bit5 {
 7678:     my ($symb,$courseid,$domain,$username)=@_;
 7679:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7680:     return "$num1:$num2";
 7681: }
 7682: 
 7683: sub rndseed_CODE_64bit {
 7684:     my ($symb,$courseid,$domain,$username)=@_;
 7685:     {
 7686: 	use integer;
 7687: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7688: 	my $symbseed=numval2($symb);
 7689: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7690: 	my $CODEseed=numval(&getCODE());
 7691: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7692: 	my $num1=$symbseed+$CODEchck;
 7693: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7694: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7695: 	#&logthis("rndseed :$num1:$num2:$symb");
 7696: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7697: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7698: 	return "$num1:$num2";
 7699:     }
 7700: }
 7701: 
 7702: sub rndseed_CODE_64bit4 {
 7703:     my ($symb,$courseid,$domain,$username)=@_;
 7704:     {
 7705: 	use integer;
 7706: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7707: 	my $symbseed=numval3($symb);
 7708: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7709: 	my $CODEseed=numval3(&getCODE());
 7710: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7711: 	my $num1=$symbseed+$CODEchck;
 7712: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7713: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7714: 	#&logthis("rndseed :$num1:$num2:$symb");
 7715: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7716: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7717: 	return "$num1:$num2";
 7718:     }
 7719: }
 7720: 
 7721: sub rndseed_CODE_64bit5 {
 7722:     my ($symb,$courseid,$domain,$username)=@_;
 7723:     my $code = &getCODE();
 7724:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7725:     return "$num1:$num2";
 7726: }
 7727: 
 7728: sub setup_random_from_rndseed {
 7729:     my ($rndseed)=@_;
 7730:     if ($rndseed =~/([,:])/) {
 7731: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7732: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7733:     } else {
 7734: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7735:     }
 7736: }
 7737: 
 7738: sub latest_receipt_algorithm_id {
 7739:     return 'receipt3';
 7740: }
 7741: 
 7742: sub recunique {
 7743:     my $fucourseid=shift;
 7744:     my $unique;
 7745:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7746: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7747: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7748:     } else {
 7749: 	$unique=$perlvar{'lonReceipt'};
 7750:     }
 7751:     return unpack("%32C*",$unique);
 7752: }
 7753: 
 7754: sub recprefix {
 7755:     my $fucourseid=shift;
 7756:     my $prefix;
 7757:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7758: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7759: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7760:     } else {
 7761: 	$prefix=$perlvar{'lonHostID'};
 7762:     }
 7763:     return unpack("%32C*",$prefix);
 7764: }
 7765: 
 7766: sub ireceipt {
 7767:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7768: 
 7769:     my $return =&recprefix($fucourseid).'-';
 7770: 
 7771:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7772: 	$env{'request.state'} eq 'construct') {
 7773: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7774: 	return $return;
 7775:     }
 7776: 
 7777:     my $cuname=unpack("%32C*",$funame);
 7778:     my $cudom=unpack("%32C*",$fudom);
 7779:     my $cucourseid=unpack("%32C*",$fucourseid);
 7780:     my $cusymb=unpack("%32C*",$fusymb);
 7781:     my $cunique=&recunique($fucourseid);
 7782:     my $cpart=unpack("%32S*",$part);
 7783:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7784: 
 7785: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7786: 			       
 7787: 	$return.= ($cunique%$cuname+
 7788: 		   $cunique%$cudom+
 7789: 		   $cusymb%$cuname+
 7790: 		   $cusymb%$cudom+
 7791: 		   $cucourseid%$cuname+
 7792: 		   $cucourseid%$cudom+
 7793: 		   $cpart%$cuname+
 7794: 		   $cpart%$cudom);
 7795:     } else {
 7796: 	$return.= ($cunique%$cuname+
 7797: 		   $cunique%$cudom+
 7798: 		   $cusymb%$cuname+
 7799: 		   $cusymb%$cudom+
 7800: 		   $cucourseid%$cuname+
 7801: 		   $cucourseid%$cudom);
 7802:     }
 7803:     return $return;
 7804: }
 7805: 
 7806: sub receipt {
 7807:     my ($part)=@_;
 7808:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7809:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7810: }
 7811: 
 7812: sub whichuser {
 7813:     my ($passedsymb)=@_;
 7814:     my ($symb,$courseid,$domain,$name,$publicuser);
 7815:     if (defined($env{'form.grade_symb'})) {
 7816: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7817: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7818: 	if (!$allowed &&
 7819: 	    exists($env{'request.course.sec'}) &&
 7820: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7821: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7822: 			      '/'.$env{'request.course.sec'});
 7823: 	}
 7824: 	if ($allowed) {
 7825: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7826: 	    $courseid=$tmp_courseid;
 7827: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7828: 	    ($name)=&get_env_multiple('form.grade_username');
 7829: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7830: 	}
 7831:     }
 7832:     if (!$passedsymb) {
 7833: 	$symb=&symbread();
 7834:     } else {
 7835: 	$symb=$passedsymb;
 7836:     }
 7837:     $courseid=$env{'request.course.id'};
 7838:     $domain=$env{'user.domain'};
 7839:     $name=$env{'user.name'};
 7840:     if ($name eq 'public' && $domain eq 'public') {
 7841: 	if (!defined($env{'form.username'})) {
 7842: 	    $env{'form.username'}.=time.rand(10000000);
 7843: 	}
 7844: 	$name.=$env{'form.username'};
 7845:     }
 7846:     return ($symb,$courseid,$domain,$name,$publicuser);
 7847: 
 7848: }
 7849: 
 7850: # ------------------------------------------------------------ Serves up a file
 7851: # returns either the contents of the file or 
 7852: # -1 if the file doesn't exist
 7853: #
 7854: # if the target is a file that was uploaded via DOCS, 
 7855: # a check will be made to see if a current copy exists on the local server,
 7856: # if it does this will be served, otherwise a copy will be retrieved from
 7857: # the home server for the course and stored in /home/httpd/html/userfiles on
 7858: # the local server.   
 7859: 
 7860: sub getfile {
 7861:     my ($file) = @_;
 7862:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7863:     &repcopy($file);
 7864:     return &readfile($file);
 7865: }
 7866: 
 7867: sub repcopy_userfile {
 7868:     my ($file)=@_;
 7869:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7870:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7871:     my ($cdom,$cnum,$filename) = 
 7872: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7873:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7874:     if (-e "$file") {
 7875: # we already have a local copy, check it out
 7876: 	my @fileinfo = stat($file);
 7877: 	my $rtncode;
 7878: 	my $info;
 7879: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7880: 	if ($lwpresp ne 'ok') {
 7881: # there is no such file anymore, even though we had a local copy
 7882: 	    if ($rtncode eq '404') {
 7883: 		unlink($file);
 7884: 	    }
 7885: 	    return -1;
 7886: 	}
 7887: 	if ($info < $fileinfo[9]) {
 7888: # nice, the file we have is up-to-date, just say okay
 7889: 	    return 'ok';
 7890: 	} else {
 7891: # the file is outdated, get rid of it
 7892: 	    unlink($file);
 7893: 	}
 7894:     }
 7895: # one way or the other, at this point, we don't have the file
 7896: # construct the correct path for the file
 7897:     my @parts = ($cdom,$cnum); 
 7898:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7899: 	push @parts, split(/\//,$1);
 7900:     }
 7901:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7902:     foreach my $part (@parts) {
 7903: 	$path .= '/'.$part;
 7904: 	if (!-e $path) {
 7905: 	    mkdir($path,0770);
 7906: 	}
 7907:     }
 7908: # now the path exists for sure
 7909: # get a user agent
 7910:     my $ua=new LWP::UserAgent;
 7911:     my $transferfile=$file.'.in.transfer';
 7912: # FIXME: this should flock
 7913:     if (-e $transferfile) { return 'ok'; }
 7914:     my $request;
 7915:     $uri=~s/^\///;
 7916:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7917:     my $response=$ua->request($request,$transferfile);
 7918: # did it work?
 7919:     if ($response->is_error()) {
 7920: 	unlink($transferfile);
 7921: 	&logthis("Userfile repcopy failed for $uri");
 7922: 	return -1;
 7923:     }
 7924: # worked, rename the transfer file
 7925:     rename($transferfile,$file);
 7926:     return 'ok';
 7927: }
 7928: 
 7929: sub tokenwrapper {
 7930:     my $uri=shift;
 7931:     $uri=~s|^http\://([^/]+)||;
 7932:     $uri=~s|^/||;
 7933:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7934:     my $token=$1;
 7935:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7936:     if ($udom && $uname && $file) {
 7937: 	$file=~s|(\?\.*)*$||;
 7938:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7939:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7940:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7941:                                '&tokenissued='.$perlvar{'lonHostID'};
 7942:     } else {
 7943:         return '/adm/notfound.html';
 7944:     }
 7945: }
 7946: 
 7947: # call with reqtype HEAD: get last modification time
 7948: # call with reqtype GET: get the file contents
 7949: # Do not call this with reqtype GET for large files! It loads everything into memory
 7950: #
 7951: sub getuploaded {
 7952:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7953:     $uri=~s/^\///;
 7954:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7955:     my $ua=new LWP::UserAgent;
 7956:     my $request=new HTTP::Request($reqtype,$uri);
 7957:     my $response=$ua->request($request);
 7958:     $$rtncode = $response->code;
 7959:     if (! $response->is_success()) {
 7960: 	return 'failed';
 7961:     }      
 7962:     if ($reqtype eq 'HEAD') {
 7963: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7964:     } elsif ($reqtype eq 'GET') {
 7965: 	$$info = $response->content;
 7966:     }
 7967:     return 'ok';
 7968: }
 7969: 
 7970: sub readfile {
 7971:     my $file = shift;
 7972:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7973:     my $fh;
 7974:     open($fh,"<$file");
 7975:     my $a='';
 7976:     while (my $line = <$fh>) { $a .= $line; }
 7977:     return $a;
 7978: }
 7979: 
 7980: sub filelocation {
 7981:     my ($dir,$file) = @_;
 7982:     my $location;
 7983:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7984: 
 7985:     if ($file =~ m-^/adm/-) {
 7986: 	$file=~s-^/adm/wrapper/-/-;
 7987: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7988:     }
 7989: 
 7990:     if ($file=~m:^/~:) { # is a contruction space reference
 7991:         $location = $file;
 7992:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7993:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7994: 	# is a correct contruction space reference
 7995:         $location = $file;
 7996:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7997:         my ($udom,$uname,$filename)=
 7998:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7999:         my $home=&homeserver($uname,$udom);
 8000:         my $is_me=0;
 8001:         my @ids=&current_machine_ids();
 8002:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8003:         if ($is_me) {
 8004:   	    $location=&propath($udom,$uname).
 8005:   	      '/userfiles/'.$filename;
 8006:         } else {
 8007:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8008:   	      $udom.'/'.$uname.'/'.$filename;
 8009:         }
 8010:     } elsif ($file =~ m-^/adm/-) {
 8011: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8012:     } else {
 8013:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8014:         $file=~s:^/res/:/:;
 8015:         if ( !( $file =~ m:^/:) ) {
 8016:             $location = $dir. '/'.$file;
 8017:         } else {
 8018:             $location = '/home/httpd/html/res'.$file;
 8019:         }
 8020:     }
 8021:     $location=~s://+:/:g; # remove duplicate /
 8022:     while ($location=~m{/\.\./}) {
 8023: 	if ($location =~ m{/[^/]+/\.\./}) {
 8024: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8025: 	} else {
 8026: 	    $location=~ s{/\.\./}{/}g;
 8027: 	}
 8028:     } #remove dir/..
 8029:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8030:     return $location;
 8031: }
 8032: 
 8033: sub hreflocation {
 8034:     my ($dir,$file)=@_;
 8035:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8036: 	$file=filelocation($dir,$file);
 8037:     } elsif ($file=~m-^/adm/-) {
 8038: 	$file=~s-^/adm/wrapper/-/-;
 8039: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8040:     }
 8041:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8042: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8043:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8044: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8045:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8046: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8047: 	    -/uploaded/$1/$2/-x;
 8048:     }
 8049:     if ($file=~ m{^/userfiles/}) {
 8050: 	$file =~ s{^/userfiles/}{/uploaded/};
 8051:     }
 8052:     return $file;
 8053: }
 8054: 
 8055: sub current_machine_domains {
 8056:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8057: }
 8058: 
 8059: sub machine_domains {
 8060:     my ($hostname) = @_;
 8061:     my @domains;
 8062:     my %hostname = &all_hostnames();
 8063:     while( my($id, $name) = each(%hostname)) {
 8064: #	&logthis("-$id-$name-$hostname-");
 8065: 	if ($hostname eq $name) {
 8066: 	    push(@domains,&host_domain($id));
 8067: 	}
 8068:     }
 8069:     return @domains;
 8070: }
 8071: 
 8072: sub current_machine_ids {
 8073:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8074: }
 8075: 
 8076: sub machine_ids {
 8077:     my ($hostname) = @_;
 8078:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8079:     my @ids;
 8080:     my %name_to_host = &all_names();
 8081:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8082: 	return @{ $name_to_host{$hostname} };
 8083:     }
 8084:     return;
 8085: }
 8086: 
 8087: sub additional_machine_domains {
 8088:     my @domains;
 8089:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8090:     while( my $line = <$fh>) {
 8091:         $line =~ s/\s//g;
 8092:         push(@domains,$line);
 8093:     }
 8094:     return @domains;
 8095: }
 8096: 
 8097: sub default_login_domain {
 8098:     my $domain = $perlvar{'lonDefDomain'};
 8099:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8100:     foreach my $posdom (&current_machine_domains(),
 8101:                         &additional_machine_domains()) {
 8102:         if (lc($posdom) eq lc($testdomain)) {
 8103:             $domain=$posdom;
 8104:             last;
 8105:         }
 8106:     }
 8107:     return $domain;
 8108: }
 8109: 
 8110: # ------------------------------------------------------------- Declutters URLs
 8111: 
 8112: sub declutter {
 8113:     my $thisfn=shift;
 8114:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8115:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8116:     $thisfn=~s/^\///;
 8117:     $thisfn=~s|^adm/wrapper/||;
 8118:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8119:     $thisfn=~s/^res\///;
 8120:     $thisfn=~s/\?.+$//;
 8121:     return $thisfn;
 8122: }
 8123: 
 8124: # ------------------------------------------------------------- Clutter up URLs
 8125: 
 8126: sub clutter {
 8127:     my $thisfn='/'.&declutter(shift);
 8128:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8129: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8130:        $thisfn='/res'.$thisfn; 
 8131:     }
 8132:     if ($thisfn !~m|/adm|) {
 8133: 	if ($thisfn =~ m|/ext/|) {
 8134: 	    $thisfn='/adm/wrapper'.$thisfn;
 8135: 	} else {
 8136: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8137: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8138: 	    if ($embstyle eq 'ssi'
 8139: 		|| ($embstyle eq 'hdn')
 8140: 		|| ($embstyle eq 'rat')
 8141: 		|| ($embstyle eq 'prv')
 8142: 		|| ($embstyle eq 'ign')) {
 8143: 		#do nothing with these
 8144: 	    } elsif (($embstyle eq 'img') 
 8145: 		|| ($embstyle eq 'emb')
 8146: 		|| ($embstyle eq 'wrp')) {
 8147: 		$thisfn='/adm/wrapper'.$thisfn;
 8148: 	    } elsif ($embstyle eq 'unk'
 8149: 		     && $thisfn!~/\.(sequence|page)$/) {
 8150: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8151: 	    } else {
 8152: #		&logthis("Got a blank emb style");
 8153: 	    }
 8154: 	}
 8155:     }
 8156:     return $thisfn;
 8157: }
 8158: 
 8159: sub clutter_with_no_wrapper {
 8160:     my $uri = &clutter(shift);
 8161:     if ($uri =~ m-^/adm/-) {
 8162: 	$uri =~ s-^/adm/wrapper/-/-;
 8163: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8164:     }
 8165:     return $uri;
 8166: }
 8167: 
 8168: sub freeze_escape {
 8169:     my ($value)=@_;
 8170:     if (ref($value)) {
 8171: 	$value=&nfreeze($value);
 8172: 	return '__FROZEN__'.&escape($value);
 8173:     }
 8174:     return &escape($value);
 8175: }
 8176: 
 8177: 
 8178: sub thaw_unescape {
 8179:     my ($value)=@_;
 8180:     if ($value =~ /^__FROZEN__/) {
 8181: 	substr($value,0,10,undef);
 8182: 	$value=&unescape($value);
 8183: 	return &thaw($value);
 8184:     }
 8185:     return &unescape($value);
 8186: }
 8187: 
 8188: sub correct_line_ends {
 8189:     my ($result)=@_;
 8190:     $$result =~s/\r\n/\n/mg;
 8191:     $$result =~s/\r/\n/mg;
 8192: }
 8193: # ================================================================ Main Program
 8194: 
 8195: sub goodbye {
 8196:    &logthis("Starting Shut down");
 8197: #not converted to using infrastruture and probably shouldn't be
 8198:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8199: #converted
 8200: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8201:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8202: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8203: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8204: #1.1 only
 8205: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8206: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8207: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8208: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8209:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8210:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8211:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8212:    &flushcourselogs();
 8213:    &logthis("Shutting down");
 8214: }
 8215: 
 8216: sub get_dns {
 8217:     my ($url,$func,$ignore_cache) = @_;
 8218:     if (!$ignore_cache) {
 8219: 	my ($content,$cached)=
 8220: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8221: 	if ($cached) {
 8222: 	    &$func($content);
 8223: 	    return;
 8224: 	}
 8225:     }
 8226: 
 8227:     my %alldns;
 8228:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8229:     foreach my $dns (<$config>) {
 8230: 	next if ($dns !~ /^\^(\S*)/x);
 8231: 	$alldns{$1} = 1;
 8232:     }
 8233:     while (%alldns) {
 8234: 	my ($dns) = keys(%alldns);
 8235: 	delete($alldns{$dns});
 8236: 	my $ua=new LWP::UserAgent;
 8237: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8238: 	my $response=$ua->request($request);
 8239: 	next if ($response->is_error());
 8240: 	my @content = split("\n",$response->content);
 8241: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8242: 	&$func(\@content);
 8243: 	return;
 8244:     }
 8245:     close($config);
 8246:     my $which = (split('/',$url))[3];
 8247:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8248:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8249:     my @content = <$config>;
 8250:     &$func(\@content);
 8251:     return;
 8252: }
 8253: # ------------------------------------------------------------ Read domain file
 8254: {
 8255:     my $loaded;
 8256:     my %domain;
 8257: 
 8258:     sub parse_domain_tab {
 8259: 	my ($lines) = @_;
 8260: 	foreach my $line (@$lines) {
 8261: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8262: 
 8263: 	    chomp($line);
 8264: 	    my ($name,@elements) = split(/:/,$line,9);
 8265: 	    my %this_domain;
 8266: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8267: 			       'lang_def', 'city', 'longi', 'lati',
 8268: 			       'primary') {
 8269: 		$this_domain{$field} = shift(@elements);
 8270: 	    }
 8271: 	    $domain{$name} = \%this_domain;
 8272: 	}
 8273:     }
 8274: 
 8275:     sub reset_domain_info {
 8276: 	undef($loaded);
 8277: 	undef(%domain);
 8278:     }
 8279: 
 8280:     sub load_domain_tab {
 8281: 	my ($ignore_cache) = @_;
 8282: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8283: 	my $fh;
 8284: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8285: 	    my @lines = <$fh>;
 8286: 	    &parse_domain_tab(\@lines);
 8287: 	}
 8288: 	close($fh);
 8289: 	$loaded = 1;
 8290:     }
 8291: 
 8292:     sub domain {
 8293: 	&load_domain_tab() if (!$loaded);
 8294: 
 8295: 	my ($name,$what) = @_;
 8296: 	return if ( !exists($domain{$name}) );
 8297: 
 8298: 	if (!$what) {
 8299: 	    return $domain{$name}{'description'};
 8300: 	}
 8301: 	return $domain{$name}{$what};
 8302:     }
 8303: }
 8304: 
 8305: 
 8306: # ------------------------------------------------------------- Read hosts file
 8307: {
 8308:     my %hostname;
 8309:     my %hostdom;
 8310:     my %libserv;
 8311:     my $loaded;
 8312:     my %name_to_host;
 8313: 
 8314:     sub parse_hosts_tab {
 8315: 	my ($file) = @_;
 8316: 	foreach my $configline (@$file) {
 8317: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8318: 	    next if ($configline =~ /^\^/);
 8319: 	    chomp($configline);
 8320: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8321: 	    $name=~s/\s//g;
 8322: 	    if ($id && $domain && $role && $name) {
 8323: 		$hostname{$id}=$name;
 8324: 		push(@{$name_to_host{$name}}, $id);
 8325: 		$hostdom{$id}=$domain;
 8326: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8327: 	    }
 8328: 	}
 8329:     }
 8330:     
 8331:     sub reset_hosts_info {
 8332: 	&purge_remembered();
 8333: 	&reset_domain_info();
 8334: 	&reset_hosts_ip_info();
 8335: 	undef(%name_to_host);
 8336: 	undef(%hostname);
 8337: 	undef(%hostdom);
 8338: 	undef(%libserv);
 8339: 	undef($loaded);
 8340:     }
 8341: 
 8342:     sub load_hosts_tab {
 8343: 	my ($ignore_cache) = @_;
 8344: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8345: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8346: 	my @config = <$config>;
 8347: 	&parse_hosts_tab(\@config);
 8348: 	close($config);
 8349: 	$loaded=1;
 8350:     }
 8351: 
 8352:     sub hostname {
 8353: 	&load_hosts_tab() if (!$loaded);
 8354: 
 8355: 	my ($lonid) = @_;
 8356: 	return $hostname{$lonid};
 8357:     }
 8358: 
 8359:     sub all_hostnames {
 8360: 	&load_hosts_tab() if (!$loaded);
 8361: 
 8362: 	return %hostname;
 8363:     }
 8364: 
 8365:     sub all_names {
 8366: 	&load_hosts_tab() if (!$loaded);
 8367: 
 8368: 	return %name_to_host;
 8369:     }
 8370: 
 8371:     sub is_library {
 8372: 	&load_hosts_tab() if (!$loaded);
 8373: 
 8374: 	return exists($libserv{$_[0]});
 8375:     }
 8376: 
 8377:     sub all_library {
 8378: 	&load_hosts_tab() if (!$loaded);
 8379: 
 8380: 	return %libserv;
 8381:     }
 8382: 
 8383:     sub get_servers {
 8384: 	&load_hosts_tab() if (!$loaded);
 8385: 
 8386: 	my ($domain,$type) = @_;
 8387: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8388: 	                                          : %hostname;
 8389: 	my %result;
 8390: 	if (ref($domain) eq 'ARRAY') {
 8391: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8392: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8393: 		    $result{$host} = $hostname;
 8394: 		}
 8395: 	    }
 8396: 	} else {
 8397: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8398: 		if ($hostdom{$host} eq $domain) {
 8399: 		    $result{$host} = $hostname;
 8400: 		}
 8401: 	    }
 8402: 	}
 8403: 	return %result;
 8404:     }
 8405: 
 8406:     sub host_domain {
 8407: 	&load_hosts_tab() if (!$loaded);
 8408: 
 8409: 	my ($lonid) = @_;
 8410: 	return $hostdom{$lonid};
 8411:     }
 8412: 
 8413:     sub all_domains {
 8414: 	&load_hosts_tab() if (!$loaded);
 8415: 
 8416: 	my %seen;
 8417: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8418: 	return @uniq;
 8419:     }
 8420: }
 8421: 
 8422: { 
 8423:     my %iphost;
 8424:     my %name_to_ip;
 8425:     my %lonid_to_ip;
 8426: 
 8427:     sub get_hosts_from_ip {
 8428: 	my ($ip) = @_;
 8429: 	my %iphosts = &get_iphost();
 8430: 	if (ref($iphosts{$ip})) {
 8431: 	    return @{$iphosts{$ip}};
 8432: 	}
 8433: 	return;
 8434:     }
 8435:     
 8436:     sub reset_hosts_ip_info {
 8437: 	undef(%iphost);
 8438: 	undef(%name_to_ip);
 8439: 	undef(%lonid_to_ip);
 8440:     }
 8441: 
 8442:     sub get_host_ip {
 8443: 	my ($lonid) = @_;
 8444: 	if (exists($lonid_to_ip{$lonid})) {
 8445: 	    return $lonid_to_ip{$lonid};
 8446: 	}
 8447: 	my $name=&hostname($lonid);
 8448:    	my $ip = gethostbyname($name);
 8449: 	return if (!$ip || length($ip) ne 4);
 8450: 	$ip=inet_ntoa($ip);
 8451: 	$name_to_ip{$name}   = $ip;
 8452: 	$lonid_to_ip{$lonid} = $ip;
 8453: 	return $ip;
 8454:     }
 8455:     
 8456:     sub get_iphost {
 8457: 	my ($ignore_cache) = @_;
 8458: 
 8459: 	if (!$ignore_cache) {
 8460: 	    if (%iphost) {
 8461: 		return %iphost;
 8462: 	    }
 8463: 	    my ($ip_info,$cached)=
 8464: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8465: 	    if ($cached) {
 8466: 		%iphost      = %{$ip_info->[0]};
 8467: 		%name_to_ip  = %{$ip_info->[1]};
 8468: 		%lonid_to_ip = %{$ip_info->[2]};
 8469: 		return %iphost;
 8470: 	    }
 8471: 	}
 8472: 
 8473: 	# get yesterday's info for fallback
 8474: 	my %old_name_to_ip;
 8475: 	my ($ip_info,$cached)=
 8476: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8477: 	if ($cached) {
 8478: 	    %old_name_to_ip = %{$ip_info->[1]};
 8479: 	}
 8480: 
 8481: 	my %name_to_host = &all_names();
 8482: 	foreach my $name (keys(%name_to_host)) {
 8483: 	    my $ip;
 8484: 	    if (!exists($name_to_ip{$name})) {
 8485: 		$ip = gethostbyname($name);
 8486: 		if (!$ip || length($ip) ne 4) {
 8487: 		    if (defined($old_name_to_ip{$name})) {
 8488: 			$ip = $old_name_to_ip{$name};
 8489: 			&logthis("Can't find $name defaulting to old $ip");
 8490: 		    } else {
 8491: 			&logthis("Name $name no IP found");
 8492: 			next;
 8493: 		    }
 8494: 		} else {
 8495: 		    $ip=inet_ntoa($ip);
 8496: 		}
 8497: 		$name_to_ip{$name} = $ip;
 8498: 	    } else {
 8499: 		$ip = $name_to_ip{$name};
 8500: 	    }
 8501: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8502: 		$lonid_to_ip{$id} = $ip;
 8503: 	    }
 8504: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8505: 	}
 8506: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8507: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8508: 				      48*60*60);
 8509: 
 8510: 	return %iphost;
 8511:     }
 8512: }
 8513: 
 8514: BEGIN {
 8515: 
 8516: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8517:     unless ($readit) {
 8518: {
 8519:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8520:     %perlvar = (%perlvar,%{$configvars});
 8521: }
 8522: 
 8523: 
 8524: # ------------------------------------------------------ Read spare server file
 8525: {
 8526:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8527: 
 8528:     while (my $configline=<$config>) {
 8529:        chomp($configline);
 8530:        if ($configline) {
 8531: 	   my ($host,$type) = split(':',$configline,2);
 8532: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8533: 	   push(@{ $spareid{$type} }, $host);
 8534:        }
 8535:     }
 8536:     close($config);
 8537: }
 8538: # ------------------------------------------------------------ Read permissions
 8539: {
 8540:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8541: 
 8542:     while (my $configline=<$config>) {
 8543: 	chomp($configline);
 8544: 	if ($configline) {
 8545: 	    my ($role,$perm)=split(/ /,$configline);
 8546: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8547: 	}
 8548:     }
 8549:     close($config);
 8550: }
 8551: 
 8552: # -------------------------------------------- Read plain texts for permissions
 8553: {
 8554:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8555: 
 8556:     while (my $configline=<$config>) {
 8557: 	chomp($configline);
 8558: 	if ($configline) {
 8559: 	    my ($short,@plain)=split(/:/,$configline);
 8560:             %{$prp{$short}} = ();
 8561: 	    if (@plain > 0) {
 8562:                 $prp{$short}{'std'} = $plain[0];
 8563:                 for (my $i=1; $i<@plain; $i++) {
 8564:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8565:                 }
 8566:             }
 8567: 	}
 8568:     }
 8569:     close($config);
 8570: }
 8571: 
 8572: # ---------------------------------------------------------- Read package table
 8573: {
 8574:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8575: 
 8576:     while (my $configline=<$config>) {
 8577: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8578: 	chomp($configline);
 8579: 	my ($short,$plain)=split(/:/,$configline);
 8580: 	my ($pack,$name)=split(/\&/,$short);
 8581: 	if ($plain ne '') {
 8582: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8583: 	    $packagetab{$short}=$plain; 
 8584: 	}
 8585:     }
 8586:     close($config);
 8587: }
 8588: 
 8589: # ------------- set up temporary directory
 8590: {
 8591:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8592: 
 8593: }
 8594: 
 8595: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8596: 				'compress_threshold'=> 20_000,
 8597:  			        });
 8598: 
 8599: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8600: $dumpcount=0;
 8601: 
 8602: &logtouch();
 8603: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8604: $readit=1;
 8605:     {
 8606: 	use integer;
 8607: 	my $test=(2**32)+1;
 8608: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8609: 	&logthis(" Detected 64bit platform ($_64bit)");
 8610:     }
 8611: }
 8612: }
 8613: 
 8614: 1;
 8615: __END__
 8616: 
 8617: =pod
 8618: 
 8619: =head1 NAME
 8620: 
 8621: Apache::lonnet - Subroutines to ask questions about things in the network.
 8622: 
 8623: =head1 SYNOPSIS
 8624: 
 8625: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8626: 
 8627:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8628: 
 8629: Common parameters:
 8630: 
 8631: =over 4
 8632: 
 8633: =item *
 8634: 
 8635: $uname : an internal username (if $cname expecting a course Id specifically)
 8636: 
 8637: =item *
 8638: 
 8639: $udom : a domain (if $cdom expecting a course's domain specifically)
 8640: 
 8641: =item *
 8642: 
 8643: $symb : a resource instance identifier
 8644: 
 8645: =item *
 8646: 
 8647: $namespace : the name of a .db file that contains the data needed or
 8648: being set.
 8649: 
 8650: =back
 8651: 
 8652: =head1 OVERVIEW
 8653: 
 8654: lonnet provides subroutines which interact with the
 8655: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8656: about classes, users, and resources.
 8657: 
 8658: For many of these objects you can also use this to store data about
 8659: them or modify them in various ways.
 8660: 
 8661: =head2 Symbs
 8662: 
 8663: To identify a specific instance of a resource, LON-CAPA uses symbols
 8664: or "symbs"X<symb>. These identifiers are built from the URL of the
 8665: map, the resource number of the resource in the map, and the URL of
 8666: the resource itself. The latter is somewhat redundant, but might help
 8667: if maps change.
 8668: 
 8669: An example is
 8670: 
 8671:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8672: 
 8673: The respective map entry is
 8674: 
 8675:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8676:   title="Problem 2">
 8677:  </resource>
 8678: 
 8679: Symbs are used by the random number generator, as well as to store and
 8680: restore data specific to a certain instance of for example a problem.
 8681: 
 8682: =head2 Storing And Retrieving Data
 8683: 
 8684: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8685: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8686: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8687: is is the non-critical message twin of cstore. These functions are for
 8688: handlers to store a perl hash to a user's permanent data space in an
 8689: easy manner, and to retrieve it again on another call. It is expected
 8690: that a handler would use this once at the beginning to retrieve data,
 8691: and then again once at the end to send only the new data back.
 8692: 
 8693: The data is stored in the user's data directory on the user's
 8694: homeserver under the ID of the course.
 8695: 
 8696: The hash that is returned by restore will have all of the previous
 8697: value for all of the elements of the hash.
 8698: 
 8699: Example:
 8700: 
 8701:  #creating a hash
 8702:  my %hash;
 8703:  $hash{'foo'}='bar';
 8704: 
 8705:  #storing it
 8706:  &Apache::lonnet::cstore(\%hash);
 8707: 
 8708:  #changing a value
 8709:  $hash{'foo'}='notbar';
 8710: 
 8711:  #adding a new value
 8712:  $hash{'bar'}='foo';
 8713:  &Apache::lonnet::cstore(\%hash);
 8714: 
 8715:  #retrieving the hash
 8716:  my %history=&Apache::lonnet::restore();
 8717: 
 8718:  #print the hash
 8719:  foreach my $key (sort(keys(%history))) {
 8720:    print("\%history{$key} = $history{$key}");
 8721:  }
 8722: 
 8723: Will print out:
 8724: 
 8725:  %history{1:foo} = bar
 8726:  %history{1:keys} = foo:timestamp
 8727:  %history{1:timestamp} = 990455579
 8728:  %history{2:bar} = foo
 8729:  %history{2:foo} = notbar
 8730:  %history{2:keys} = foo:bar:timestamp
 8731:  %history{2:timestamp} = 990455580
 8732:  %history{bar} = foo
 8733:  %history{foo} = notbar
 8734:  %history{timestamp} = 990455580
 8735:  %history{version} = 2
 8736: 
 8737: Note that the special hash entries C<keys>, C<version> and
 8738: C<timestamp> were added to the hash. C<version> will be equal to the
 8739: total number of versions of the data that have been stored. The
 8740: C<timestamp> attribute will be the UNIX time the hash was
 8741: stored. C<keys> is available in every historical section to list which
 8742: keys were added or changed at a specific historical revision of a
 8743: hash.
 8744: 
 8745: B<Warning>: do not store the hash that restore returns directly. This
 8746: will cause a mess since it will restore the historical keys as if the
 8747: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8748: 
 8749: Calling convention:
 8750: 
 8751:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8752:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8753: 
 8754: For more detailed information, see lonnet specific documentation.
 8755: 
 8756: =head1 RETURN MESSAGES
 8757: 
 8758: =over 4
 8759: 
 8760: =item * B<con_lost>: unable to contact remote host
 8761: 
 8762: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8763: when the connection is brought back up
 8764: 
 8765: =item * B<con_failed>: unable to contact remote host and unable to save message
 8766: for later delivery
 8767: 
 8768: =item * B<error:>: an error a occured, a description of the error follows the :
 8769: 
 8770: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8771: that was requested
 8772: 
 8773: =back
 8774: 
 8775: =head1 PUBLIC SUBROUTINES
 8776: 
 8777: =head2 Session Environment Functions
 8778: 
 8779: =over 4
 8780: 
 8781: =item * 
 8782: X<appenv()>
 8783: B<appenv(%hash)>: the value of %hash is written to
 8784: the user envirnoment file, and will be restored for each access this
 8785: user makes during this session, also modifies the %env for the current
 8786: process
 8787: 
 8788: =item *
 8789: X<delenv()>
 8790: B<delenv($regexp)>: removes all items from the session
 8791: environment file that matches the regular expression in $regexp. The
 8792: values are also delted from the current processes %env.
 8793: 
 8794: =item * get_env_multiple($name) 
 8795: 
 8796: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8797: values may be defined and end up as an array ref.
 8798: 
 8799: returns an array of values
 8800: 
 8801: =back
 8802: 
 8803: =head2 User Information
 8804: 
 8805: =over 4
 8806: 
 8807: =item *
 8808: X<queryauthenticate()>
 8809: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8810: authentication scheme
 8811: 
 8812: =item *
 8813: X<authenticate()>
 8814: B<authenticate($uname,$upass,$udom)>: try to
 8815: authenticate user from domain's lib servers (first use the current
 8816: one). C<$upass> should be the users password.
 8817: 
 8818: =item *
 8819: X<homeserver()>
 8820: B<homeserver($uname,$udom)>: find the server which has
 8821: the user's directory and files (there must be only one), this caches
 8822: the answer, and also caches if there is a borken connection.
 8823: 
 8824: =item *
 8825: X<idget()>
 8826: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8827: (IDs are a unique resource in a domain, there must be only 1 ID per
 8828: username, and only 1 username per ID in a specific domain) (returns
 8829: hash: id=>name,id=>name)
 8830: 
 8831: =item *
 8832: X<idrget()>
 8833: B<idrget($udom,@unames)>: find the IDs behind a list of
 8834: usernames (returns hash: name=>id,name=>id)
 8835: 
 8836: =item *
 8837: X<idput()>
 8838: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8839: 
 8840: =item *
 8841: X<rolesinit()>
 8842: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8843: 
 8844: =item *
 8845: X<getsection()>
 8846: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8847: course $cname, return section name/number or '' for "not in course"
 8848: and '-1' for "no section"
 8849: 
 8850: =item *
 8851: X<userenvironment()>
 8852: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8853: passed in @what from the requested user's environment, returns a hash
 8854: 
 8855: =item * 
 8856: X<userlog_query()>
 8857: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8858: activity.log file. %filters defines filters applied when parsing the
 8859: log file. These can be start or end timestamps, or the type of action
 8860: - log to look for Login or Logout events, check for Checkin or
 8861: Checkout, role for role selection. The response is in the form
 8862: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8863: escaped strings of the action recorded in the activity.log file.
 8864: 
 8865: =back
 8866: 
 8867: =head2 User Roles
 8868: 
 8869: =over 4
 8870: 
 8871: =item *
 8872: 
 8873: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8874:  F: full access
 8875:  U,I,K: authentication modes (cxx only)
 8876:  '': forbidden
 8877:  1: user needs to choose course
 8878:  2: browse allowed
 8879:  A: passphrase authentication needed
 8880: 
 8881: =item *
 8882: 
 8883: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8884: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8885: and course level
 8886: 
 8887: =item *
 8888: 
 8889: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8890: explanation of a user role term
 8891: 
 8892: =item *
 8893: 
 8894: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8895: All arguments are optional. Returns a hash of a roles, either for
 8896: co-author/assistant author roles for a user's Construction Space
 8897: (default), or if $context is 'userroles', roles for the user himself,
 8898: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8899: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8900: For each key, value is set to colon-separated start and end times for
 8901: the role.  If no username and domain are specified, will default to
 8902: current user/domain. Types, roles, and roledoms are references to arrays
 8903: of role statuses (active, future or previous), roles 
 8904: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8905: to restrict the list of roles reported. If no array ref is 
 8906: provided for types, will default to return only active roles.
 8907: 
 8908: =back
 8909: 
 8910: =head2 User Modification
 8911: 
 8912: =over 4
 8913: 
 8914: =item *
 8915: 
 8916: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8917: user for the level given by URL.  Optional start and end dates (leave empty
 8918: string or zero for "no date")
 8919: 
 8920: =item *
 8921: 
 8922: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8923: change a users, password, possible return values are: ok,
 8924: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8925: refused
 8926: 
 8927: =item *
 8928: 
 8929: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8930: 
 8931: =item *
 8932: 
 8933: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8934: modify user
 8935: 
 8936: =item *
 8937: 
 8938: modifystudent
 8939: 
 8940: modify a students enrollment and identification information.
 8941: The course id is resolved based on the current users environment.  
 8942: This means the envoking user must be a course coordinator or otherwise
 8943: associated with a course.
 8944: 
 8945: This call is essentially a wrapper for lonnet::modifyuser and
 8946: lonnet::modify_student_enrollment
 8947: 
 8948: Inputs: 
 8949: 
 8950: =over 4
 8951: 
 8952: =item B<$udom> Students loncapa domain
 8953: 
 8954: =item B<$uname> Students loncapa login name
 8955: 
 8956: =item B<$uid> Students id/student number
 8957: 
 8958: =item B<$umode> Students authentication mode
 8959: 
 8960: =item B<$upass> Students password
 8961: 
 8962: =item B<$first> Students first name
 8963: 
 8964: =item B<$middle> Students middle name
 8965: 
 8966: =item B<$last> Students last name
 8967: 
 8968: =item B<$gene> Students generation
 8969: 
 8970: =item B<$usec> Students section in course
 8971: 
 8972: =item B<$end> Unix time of the roles expiration
 8973: 
 8974: =item B<$start> Unix time of the roles start date
 8975: 
 8976: =item B<$forceid> If defined, allow $uid to be changed
 8977: 
 8978: =item B<$desiredhome> server to use as home server for student
 8979: 
 8980: =back
 8981: 
 8982: =item *
 8983: 
 8984: modify_student_enrollment
 8985: 
 8986: Change a students enrollment status in a class.  The environment variable
 8987: 'role.request.course' must be defined for this function to proceed.
 8988: 
 8989: Inputs:
 8990: 
 8991: =over 4
 8992: 
 8993: =item $udom, students domain
 8994: 
 8995: =item $uname, students name
 8996: 
 8997: =item $uid, students user id
 8998: 
 8999: =item $first, students first name
 9000: 
 9001: =item $middle
 9002: 
 9003: =item $last
 9004: 
 9005: =item $gene
 9006: 
 9007: =item $usec
 9008: 
 9009: =item $end
 9010: 
 9011: =item $start
 9012: 
 9013: =back
 9014: 
 9015: 
 9016: =item *
 9017: 
 9018: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9019: custom role; give a custom role to a user for the level given by URL.  Specify
 9020: name and domain of role author, and role name
 9021: 
 9022: =item *
 9023: 
 9024: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9025: 
 9026: =item *
 9027: 
 9028: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9029: 
 9030: =back
 9031: 
 9032: =head2 Course Infomation
 9033: 
 9034: =over 4
 9035: 
 9036: =item *
 9037: 
 9038: coursedescription($courseid) : returns a hash of information about the
 9039: specified course id, including all environment settings for the
 9040: course, the description of the course will be in the hash under the
 9041: key 'description'
 9042: 
 9043: =item *
 9044: 
 9045: resdata($name,$domain,$type,@which) : request for current parameter
 9046: setting for a specific $type, where $type is either 'course' or 'user',
 9047: @what should be a list of parameters to ask about. This routine caches
 9048: answers for 5 minutes.
 9049: 
 9050: =item *
 9051: 
 9052: get_courseresdata($courseid, $domain) : dump the entire course resource
 9053: data base, returning a hash that is keyed by the resource name and has
 9054: values that are the resource value.  I believe that the timestamps and
 9055: versions are also returned.
 9056: 
 9057: 
 9058: =back
 9059: 
 9060: =head2 Course Modification
 9061: 
 9062: =over 4
 9063: 
 9064: =item *
 9065: 
 9066: writecoursepref($courseid,%prefs) : write preferences (environment
 9067: database) for a course
 9068: 
 9069: =item *
 9070: 
 9071: createcourse($udom,$description,$url) : make/modify course
 9072: 
 9073: =back
 9074: 
 9075: =head2 Resource Subroutines
 9076: 
 9077: =over 4
 9078: 
 9079: =item *
 9080: 
 9081: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9082: 
 9083: =item *
 9084: 
 9085: repcopy($filename) : subscribes to the requested file, and attempts to
 9086: replicate from the owning library server, Might return
 9087: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9088: 'bad_request', also attempts to grab the metadata for the
 9089: resource. Expects the local filesystem pathname
 9090: (/home/httpd/html/res/....)
 9091: 
 9092: =back
 9093: 
 9094: =head2 Resource Information
 9095: 
 9096: =over 4
 9097: 
 9098: =item *
 9099: 
 9100: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9101: a vairety of different possible values, $varname should be a request
 9102: string, and the other parameters can be used to specify who and what
 9103: one is asking about.
 9104: 
 9105: Possible values for $varname are environment.lastname (or other item
 9106: from the envirnment hash), user.name (or someother aspect about the
 9107: user), resource.0.maxtries (or some other part and parameter of a
 9108: resource)
 9109: 
 9110: =item *
 9111: 
 9112: directcondval($number) : get current value of a condition; reads from a state
 9113: string
 9114: 
 9115: =item *
 9116: 
 9117: condval($condidx) : value of condition index based on state
 9118: 
 9119: =item *
 9120: 
 9121: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9122: resource's metadata, $what should be either a specific key, or either
 9123: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9124: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9125: 
 9126: this function automatically caches all requests
 9127: 
 9128: =item *
 9129: 
 9130: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9131: network of library servers; returns file handle of where SQL and regex results
 9132: will be stored for query
 9133: 
 9134: =item *
 9135: 
 9136: symbread($filename) : return symbolic list entry (filename argument optional);
 9137: returns the data handle
 9138: 
 9139: =item *
 9140: 
 9141: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9142: a possible symb for the URL in $thisfn, and if is an encryypted
 9143: resource that the user accessed using /enc/ returns a 1 on success, 0
 9144: on failure, user must be in a course, as it assumes the existance of
 9145: the course initial hash, and uses $env('request.course.id'}
 9146: 
 9147: 
 9148: =item *
 9149: 
 9150: symbclean($symb) : removes versions numbers from a symb, returns the
 9151: cleaned symb
 9152: 
 9153: =item *
 9154: 
 9155: is_on_map($uri) : checks if the $uri is somewhere on the current
 9156: course map, user must be in a course for it to work.
 9157: 
 9158: =item *
 9159: 
 9160: numval($salt) : return random seed value (addend for rndseed)
 9161: 
 9162: =item *
 9163: 
 9164: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9165: a random seed, all arguments are optional, if they aren't sent it uses the
 9166: environment to derive them. Note: if symb isn't sent and it can't get one
 9167: from &symbread it will use the current time as its return value
 9168: 
 9169: =item *
 9170: 
 9171: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9172: unfakeable, receipt
 9173: 
 9174: =item *
 9175: 
 9176: receipt() : API to ireceipt working off of env values; given out to users
 9177: 
 9178: =item *
 9179: 
 9180: countacc($url) : count the number of accesses to a given URL
 9181: 
 9182: =item *
 9183: 
 9184: 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
 9185: 
 9186: =item *
 9187: 
 9188: 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)
 9189: 
 9190: =item *
 9191: 
 9192: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9193: 
 9194: =item *
 9195: 
 9196: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9197: forcing spreadsheet to reevaluate the resource scores next time.
 9198: 
 9199: =back
 9200: 
 9201: =head2 Storing/Retreiving Data
 9202: 
 9203: =over 4
 9204: 
 9205: =item *
 9206: 
 9207: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9208: for this url; hashref needs to be given and should be a \%hashname; the
 9209: remaining args aren't required and if they aren't passed or are '' they will
 9210: be derived from the env
 9211: 
 9212: =item *
 9213: 
 9214: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9215: uses critical subroutine
 9216: 
 9217: =item *
 9218: 
 9219: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9220: all args are optional
 9221: 
 9222: =item *
 9223: 
 9224: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9225: dumps the complete (or key matching regexp) namespace into a hash
 9226: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9227: normally &store()ed into
 9228: 
 9229: $range should be either an integer '100' (give me the first 100
 9230:                                            matching records)
 9231:               or be  two integers sperated by a - with no spaces
 9232:                  '30-50' (give me the 30th through the 50th matching
 9233:                           records)
 9234: 
 9235: 
 9236: =item *
 9237: 
 9238: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9239: replaces a &store() version of data with a replacement set of data
 9240: for a particular resource in a namespace passed in the $storehash hash 
 9241: reference
 9242: 
 9243: =item *
 9244: 
 9245: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9246: works very similar to store/cstore, but all data is stored in a
 9247: temporary location and can be reset using tmpreset, $storehash should
 9248: be a hash reference, returns nothing on success
 9249: 
 9250: =item *
 9251: 
 9252: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9253: similar to restore, but all data is stored in a temporary location and
 9254: can be reset using tmpreset. Returns a hash of values on success,
 9255: error string otherwise.
 9256: 
 9257: =item *
 9258: 
 9259: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9260: deltes all keys for $symb form the temporary storage hash.
 9261: 
 9262: =item *
 9263: 
 9264: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9265: reference filled in from namesp ($udom and $uname are optional)
 9266: 
 9267: =item *
 9268: 
 9269: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9270: namesp ($udom and $uname are optional)
 9271: 
 9272: =item *
 9273: 
 9274: dump($namespace,$udom,$uname,$regexp,$range) : 
 9275: dumps the complete (or key matching regexp) namespace into a hash
 9276: ($udom, $uname, $regexp, $range are optional)
 9277: 
 9278: $range should be either an integer '100' (give me the first 100
 9279:                                            matching records)
 9280:               or be  two integers sperated by a - with no spaces
 9281:                  '30-50' (give me the 30th through the 50th matching
 9282:                           records)
 9283: =item *
 9284: 
 9285: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9286: $store can be a scalar, an array reference, or if the amount to be 
 9287: incremented is > 1, a hash reference.
 9288: 
 9289: ($udom and $uname are optional)
 9290: 
 9291: =item *
 9292: 
 9293: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9294: ($udom and $uname are optional)
 9295: 
 9296: =item *
 9297: 
 9298: cput($namespace,$storehash,$udom,$uname) : critical put
 9299: ($udom and $uname are optional)
 9300: 
 9301: =item *
 9302: 
 9303: newput($namespace,$storehash,$udom,$uname) :
 9304: 
 9305: Attempts to store the items in the $storehash, but only if they don't
 9306: currently exist, if this succeeds you can be certain that you have 
 9307: successfully created a new key value pair in the $namespace db.
 9308: 
 9309: 
 9310: Args:
 9311:  $namespace: name of database to store values to
 9312:  $storehash: hashref to store to the db
 9313:  $udom: (optional) domain of user containing the db
 9314:  $uname: (optional) name of user caontaining the db
 9315: 
 9316: Returns:
 9317:  'ok' -> succeeded in storing all keys of $storehash
 9318:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9319:                         least <key> already existed in the db (other
 9320:                         requested keys may also already exist)
 9321:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9322:  'con_lost' -> unable to contact request server
 9323:  'refused' -> action was not allowed by remote machine
 9324: 
 9325: 
 9326: =item *
 9327: 
 9328: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9329: reference filled in from namesp (encrypts the return communication)
 9330: ($udom and $uname are optional)
 9331: 
 9332: =item *
 9333: 
 9334: log($udom,$name,$home,$message) : write to permanent log for user; use
 9335: critical subroutine
 9336: 
 9337: =item *
 9338: 
 9339: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9340: array reference filled in from namespace found in domain level on either
 9341: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9342: 
 9343: =item *
 9344: 
 9345: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9346: domain level either on specified domain server ($uhome) or primary domain 
 9347: server ($udom and $uhome are optional)
 9348: 
 9349: =back
 9350: 
 9351: =head2 Network Status Functions
 9352: 
 9353: =over 4
 9354: 
 9355: =item *
 9356: 
 9357: dirlist($uri) : return directory list based on URI
 9358: 
 9359: =item *
 9360: 
 9361: spareserver() : find server with least workload from spare.tab
 9362: 
 9363: =back
 9364: 
 9365: =head2 Apache Request
 9366: 
 9367: =over 4
 9368: 
 9369: =item *
 9370: 
 9371: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9372: localhost, posts hash
 9373: 
 9374: =back
 9375: 
 9376: =head2 Data to String to Data
 9377: 
 9378: =over 4
 9379: 
 9380: =item *
 9381: 
 9382: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9383: and '&' separators, supports elements that are arrayrefs and hashrefs
 9384: 
 9385: =item *
 9386: 
 9387: hashref2str($hashref) : convert a hashref into a string complete with
 9388: escaping and '=' and '&' separators, supports elements that are
 9389: arrayrefs and hashrefs
 9390: 
 9391: =item *
 9392: 
 9393: arrayref2str($arrayref) : convert an arrayref into a string complete
 9394: with escaping and '&' separators, supports elements that are arrayrefs
 9395: and hashrefs
 9396: 
 9397: =item *
 9398: 
 9399: str2hash($string) : convert string to hash using unescaping and
 9400: splitting on '=' and '&', supports elements that are arrayrefs and
 9401: hashrefs
 9402: 
 9403: =item *
 9404: 
 9405: str2array($string) : convert string to hash using unescaping and
 9406: splitting on '&', supports elements that are arrayrefs and hashrefs
 9407: 
 9408: =back
 9409: 
 9410: =head2 Logging Routines
 9411: 
 9412: =over 4
 9413: 
 9414: These routines allow one to make log messages in the lonnet.log and
 9415: lonnet.perm logfiles.
 9416: 
 9417: =item *
 9418: 
 9419: logtouch() : make sure the logfile, lonnet.log, exists
 9420: 
 9421: =item *
 9422: 
 9423: logthis() : append message to the normal lonnet.log file, it gets
 9424: preiodically rolled over and deleted.
 9425: 
 9426: =item *
 9427: 
 9428: logperm() : append a permanent message to lonnet.perm.log, this log
 9429: file never gets deleted by any automated portion of the system, only
 9430: messages of critical importance should go in here.
 9431: 
 9432: =back
 9433: 
 9434: =head2 General File Helper Routines
 9435: 
 9436: =over 4
 9437: 
 9438: =item *
 9439: 
 9440: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9441: (a) files in /uploaded
 9442:   (i) If a local copy of the file exists - 
 9443:       compares modification date of local copy with last-modified date for 
 9444:       definitive version stored on home server for course. If local copy is 
 9445:       stale, requests a new version from the home server and stores it. 
 9446:       If the original has been removed from the home server, then local copy 
 9447:       is unlinked.
 9448:   (ii) If local copy does not exist -
 9449:       requests the file from the home server and stores it. 
 9450:   
 9451:   If $caller is 'uploadrep':  
 9452:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9453:     for request for files originally uploaded via DOCS. 
 9454:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9455:   
 9456:   Otherwise:
 9457:      This indicates a call from the content generation phase of the request.
 9458:      -  returns the entire contents of the file or -1.
 9459:      
 9460: (b) files in /res
 9461:    - returns the entire contents of a file or -1; 
 9462:    it properly subscribes to and replicates the file if neccessary.
 9463: 
 9464: 
 9465: =item *
 9466: 
 9467: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9468:                   reference
 9469: 
 9470: returns either a stat() list of data about the file or an empty list
 9471: if the file doesn't exist or couldn't find out about it (connection
 9472: problems or user unknown)
 9473: 
 9474: =item *
 9475: 
 9476: filelocation($dir,$file) : returns file system location of a file
 9477: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9478: directory that relative $file lookups are to looked in ($dir of /a/dir
 9479: and a file of ../bob will become /a/bob)
 9480: 
 9481: =item *
 9482: 
 9483: hreflocation($dir,$file) : returns file system location or a URL; same as
 9484: filelocation except for hrefs
 9485: 
 9486: =item *
 9487: 
 9488: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9489: 
 9490: =back
 9491: 
 9492: =head2 Usererfile file routines (/uploaded*)
 9493: 
 9494: =over 4
 9495: 
 9496: =item *
 9497: 
 9498: userfileupload(): main rotine for putting a file in a user or course's
 9499:                   filespace, arguments are,
 9500: 
 9501:  formname - required - this is the name of the element in $env where the
 9502:            filename, and the contents of the file to create/modifed exist
 9503:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9504:            contents of the file is located in $env{'form.'.$formname}
 9505:  coursedoc - if true, store the file in the course of the active role
 9506:              of the current user
 9507:  subdir - required - subdirectory to put the file in under ../userfiles/
 9508:          if undefined, it will be placed in "unknown"
 9509: 
 9510:  (This routine calls clean_filename() to remove any dangerous
 9511:  characters from the filename, and then calls finuserfileupload() to
 9512:  complete the transaction)
 9513: 
 9514:  returns either the url of the uploaded file (/uploaded/....) if successful
 9515:  and /adm/notfound.html if unsuccessful
 9516: 
 9517: =item *
 9518: 
 9519: clean_filename(): routine for cleaing a filename up for storage in
 9520:                  userfile space, argument is:
 9521: 
 9522:  filename - proposed filename
 9523: 
 9524: returns: the new clean filename
 9525: 
 9526: =item *
 9527: 
 9528: finishuserfileupload(): routine that creaes and sends the file to
 9529: userspace, probably shouldn't be called directly
 9530: 
 9531:   docuname: username or courseid of destination for the file
 9532:   docudom: domain of user/course of destination for the file
 9533:   formname: same as for userfileupload()
 9534:   fname: filename (inculding subdirectories) for the file
 9535: 
 9536:  returns either the url of the uploaded file (/uploaded/....) if successful
 9537:  and /adm/notfound.html if unsuccessful
 9538: 
 9539: =item *
 9540: 
 9541: renameuserfile(): renames an existing userfile to a new name
 9542: 
 9543:   Args:
 9544:    docuname: username or courseid of destination for the file
 9545:    docudom: domain of user/course of destination for the file
 9546:    old: current file name (including any subdirs under userfiles)
 9547:    new: desired file name (including any subdirs under userfiles)
 9548: 
 9549: =item *
 9550: 
 9551: mkdiruserfile(): creates a directory is a userfiles dir
 9552: 
 9553:   Args:
 9554:    docuname: username or courseid of destination for the file
 9555:    docudom: domain of user/course of destination for the file
 9556:    dir: dir to create (including any subdirs under userfiles)
 9557: 
 9558: =item *
 9559: 
 9560: removeuserfile(): removes a file that exists in userfiles
 9561: 
 9562:   Args:
 9563:    docuname: username or courseid of destination for the file
 9564:    docudom: domain of user/course of destination for the file
 9565:    fname: filname to delete (including any subdirs under userfiles)
 9566: 
 9567: =item *
 9568: 
 9569: removeuploadedurl(): convience function for removeuserfile()
 9570: 
 9571:   Args:
 9572:    url:  a full /uploaded/... url to delete
 9573: 
 9574: =item * 
 9575: 
 9576: get_portfile_permissions():
 9577:   Args:
 9578:     domain: domain of user or course contain the portfolio files
 9579:     user: name of user or num of course contain the portfolio files
 9580:   Returns:
 9581:     hashref of a dump of the proper file_permissions.db
 9582:    
 9583: 
 9584: =item * 
 9585: 
 9586: get_access_controls():
 9587: 
 9588: Args:
 9589:   current_permissions: the hash ref returned from get_portfile_permissions()
 9590:   group: (optional) the group you want the files associated with
 9591:   file: (optional) the file you want access info on
 9592: 
 9593: Returns:
 9594:     a hash (keys are file names) of hashes containing
 9595:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9596:         values are XML containing access control settings (see below) 
 9597: 
 9598: Internal notes:
 9599: 
 9600:  access controls are stored in file_permissions.db as key=value pairs.
 9601:     key -> path to file/file_name\0uniqueID:scope_end_start
 9602:         where scope -> public,guest,course,group,domains or users.
 9603:               end -> UNIX time for end of access (0 -> no end date)
 9604:               start -> UNIX time for start of access
 9605: 
 9606:     value -> XML description of access control
 9607:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9608:             <start></start>
 9609:             <end></end>
 9610: 
 9611:             <password></password>  for scope type = guest
 9612: 
 9613:             <domain></domain>     for scope type = course or group
 9614:             <number></number>
 9615:             <roles id="">
 9616:              <role></role>
 9617:              <access></access>
 9618:              <section></section>
 9619:              <group></group>
 9620:             </roles>
 9621: 
 9622:             <dom></dom>         for scope type = domains
 9623: 
 9624:             <users>             for scope type = users
 9625:              <user>
 9626:               <uname></uname>
 9627:               <udom></udom>
 9628:              </user>
 9629:             </users>
 9630:            </scope> 
 9631:               
 9632:  Access data is also aggregated for each file in an additional key=value pair:
 9633:  key -> path to file/file_name\0accesscontrol 
 9634:  value -> reference to hash
 9635:           hash contains key = value pairs
 9636:           where key = uniqueID:scope_end_start
 9637:                 value = UNIX time record was last updated
 9638: 
 9639:           Used to improve speed of look-ups of access controls for each file.  
 9640:  
 9641:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9642: 
 9643: modify_access_controls():
 9644: 
 9645: Modifies access controls for a portfolio file
 9646: Args
 9647: 1. file name
 9648: 2. reference to hash of required changes,
 9649: 3. domain
 9650: 4. username
 9651:   where domain,username are the domain of the portfolio owner 
 9652:   (either a user or a course) 
 9653: 
 9654: Returns:
 9655: 1. result of additions or updates ('ok' or 'error', with error message). 
 9656: 2. result of deletions ('ok' or 'error', with error message).
 9657: 3. reference to hash of any new or updated access controls.
 9658: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9659:    key = integer (inbound ID)
 9660:    value = uniqueID  
 9661: 
 9662: =back
 9663: 
 9664: =head2 HTTP Helper Routines
 9665: 
 9666: =over 4
 9667: 
 9668: =item *
 9669: 
 9670: escape() : unpack non-word characters into CGI-compatible hex codes
 9671: 
 9672: =item *
 9673: 
 9674: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9675: 
 9676: =back
 9677: 
 9678: =head1 PRIVATE SUBROUTINES
 9679: 
 9680: =head2 Underlying communication routines (Shouldn't call)
 9681: 
 9682: =over 4
 9683: 
 9684: =item *
 9685: 
 9686: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9687: 
 9688: =item *
 9689: 
 9690: reply() : uses subreply to send a message to remote machine, logs all failures
 9691: 
 9692: =item *
 9693: 
 9694: critical() : passes a critical message to another server; if cannot
 9695: get through then place message in connection buffer directory and
 9696: returns con_delayed, if incapable of saving message, returns
 9697: con_failed
 9698: 
 9699: =item *
 9700: 
 9701: reconlonc() : tries to reconnect lonc client processes.
 9702: 
 9703: =back
 9704: 
 9705: =head2 Resource Access Logging
 9706: 
 9707: =over 4
 9708: 
 9709: =item *
 9710: 
 9711: flushcourselogs() : flush (save) buffer logs and access logs
 9712: 
 9713: =item *
 9714: 
 9715: courselog($what) : save message for course in hash
 9716: 
 9717: =item *
 9718: 
 9719: courseacclog($what) : save message for course using &courselog().  Perform
 9720: special processing for specific resource types (problems, exams, quizzes, etc).
 9721: 
 9722: =item *
 9723: 
 9724: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9725: as a PerlChildExitHandler
 9726: 
 9727: =back
 9728: 
 9729: =head2 Other
 9730: 
 9731: =over 4
 9732: 
 9733: =item *
 9734: 
 9735: symblist($mapname,%newhash) : update symbolic storage links
 9736: 
 9737: =back
 9738: 
 9739: =cut
 9740: 

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