File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.935: download - view: text, annotated - select for diffs
Fri Dec 21 04:34:50 2007 UTC (16 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Update documentation.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.935 2007/12/21 04:34:50 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' => &escape($coursedescrbuf{$crsid}),
 2204:             'inst_code'    => &escape($courseinstcodebuf{$crsid}),
 2205:             'type'        => &escape($coursetypebuf{$crsid}),
 2206:             'owner'       => &escape($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: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2403:     }
 2404:     my %returnhash=();
 2405:     my %dumphash=
 2406:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2407:     my $now=time;
 2408:     foreach my $entry (keys %dumphash) {
 2409: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2410:         if (($tstart) && ($tstart<0)) { next; }
 2411:         if (($tend) && ($tend<$now)) { next; }
 2412:         if (($tstart) && ($now<$tstart)) { next; }
 2413:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2414: 	if ($username eq '' || $domain eq '') { next; }
 2415: 	if ((&privileged($username,$domain)) && 
 2416: 	    (!$nothide{$username.':'.$domain})) { next; }
 2417: 	if ($role eq 'cr') { next; }
 2418:         my $key=&plaintext($role);
 2419:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2420:         if ($returnhash{$key}) {
 2421: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2422:         } else {
 2423:             $returnhash{$key}=$username.':'.$domain;
 2424:         }
 2425:      }
 2426:     return %returnhash;
 2427: }
 2428: 
 2429: sub get_my_roles {
 2430:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec)=@_;
 2431:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2432:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2433:     my %dumphash;
 2434:     if ($context eq 'userroles') { 
 2435:         %dumphash = &dump('roles',$udom,$uname);
 2436:     } else {
 2437:         %dumphash=
 2438:             &dump('nohist_userroles',$udom,$uname);
 2439:     }
 2440:     my %returnhash=();
 2441:     my $now=time;
 2442:     foreach my $entry (keys(%dumphash)) {
 2443:         my ($role,$tend,$tstart);
 2444:         if ($context eq 'userroles') {
 2445: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2446:         } else {
 2447:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2448:         }
 2449:         if (($tstart) && ($tstart<0)) { next; }
 2450:         my $status = 'active';
 2451:         if (($tend) && ($tend<$now)) {
 2452:             $status = 'previous';
 2453:         } 
 2454:         if (($tstart) && ($now<$tstart)) {
 2455:             $status = 'future';
 2456:         }
 2457:         if (ref($types) eq 'ARRAY') {
 2458:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2459:                 next;
 2460:             } 
 2461:         } else {
 2462:             if ($status ne 'active') {
 2463:                 next;
 2464:             }
 2465:         }
 2466:         my ($rolecode,$username,$domain,$section,$area);
 2467:         if ($context eq 'userroles') {
 2468:             ($area,$rolecode) = split(/_/,$entry);
 2469:             (undef,$domain,$username,$section) = split(/\//,$area);
 2470:         } else {
 2471:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2472:         }
 2473:         if (ref($roledoms) eq 'ARRAY') {
 2474:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2475:                 next;
 2476:             }
 2477:         }
 2478:         if (ref($roles) eq 'ARRAY') {
 2479:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2480:                 if ($role =~ /^cr\//) {
 2481:                     if (!grep(/^cr$/,@{$roles})) {
 2482:                         next;
 2483:                     }
 2484:                 } else {
 2485:                     next;
 2486:                 }
 2487:             }
 2488:         }
 2489:         if ($withsec) {
 2490:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2491:                 $tstart.':'.$tend;
 2492:         } else {
 2493:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2494:         }
 2495:     }
 2496:     return %returnhash;
 2497: }
 2498: 
 2499: # ----------------------------------------------------- Frontpage Announcements
 2500: #
 2501: #
 2502: 
 2503: sub postannounce {
 2504:     my ($server,$text)=@_;
 2505:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2506:     unless ($text=~/\w/) { $text=''; }
 2507:     return &reply('setannounce:'.&escape($text),$server);
 2508: }
 2509: 
 2510: sub getannounce {
 2511: 
 2512:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2513: 	my $announcement='';
 2514: 	while (my $line = <$fh>) { $announcement .= $line; }
 2515: 	close($fh);
 2516: 	if ($announcement=~/\w/) { 
 2517: 	    return 
 2518:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2519:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2520: 	} else {
 2521: 	    return '';
 2522: 	}
 2523:     } else {
 2524: 	return '';
 2525:     }
 2526: }
 2527: 
 2528: # ---------------------------------------------------------- Course ID routines
 2529: # Deal with domain's nohist_courseid.db files
 2530: #
 2531: 
 2532: sub courseidput {
 2533:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2534:     my $outcome;
 2535:     if ($caller eq 'timeonly') {
 2536:         my $cids = '';
 2537:         foreach my $item (keys(%$storehash)) {
 2538:             $cids.=&escape($item).'&';
 2539:         }
 2540:         $cids=~s/\&$//;
 2541:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2542:                           $coursehome);       
 2543:     } else {
 2544:         my $items = '';
 2545:         foreach my $item (keys(%$storehash)) {
 2546:             $items.= &escape($item).'='.
 2547:                      &freeze_escape($$storehash{$item}).'&';
 2548:         }
 2549:         $items=~s/\&$//;
 2550:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2551:                           $coursehome);
 2552:     }
 2553:     if ($outcome eq 'unknown_cmd') {
 2554:         my $what;
 2555:         foreach my $cid (keys(%$storehash)) {
 2556:             $what .= &escape($cid).'=';
 2557:             foreach my $item ('description','inst_code','owner','type') {
 2558:                 $what .= &escape($storehash->{$item}).':';
 2559:             }
 2560:             $what =~ s/\:$/&/;
 2561:         }
 2562:         $what =~ s/\&$//;  
 2563:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2564:     } else {
 2565:         return $outcome;
 2566:     }
 2567: }
 2568: 
 2569: sub courseiddump {
 2570:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2571:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2572:     my $as_hash = 1;
 2573:     my %returnhash;
 2574:     if (!$domfilter) { $domfilter=''; }
 2575:     my %libserv = &all_library();
 2576:     foreach my $tryserver (keys(%libserv)) {
 2577:         if ( (  $hostidflag == 1 
 2578: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2579: 	     || (!defined($hostidflag)) ) {
 2580: 
 2581: 	    if (($domfilter eq '') ||
 2582: 		(&host_domain($tryserver) eq $domfilter)) {
 2583:                 my $rep = 
 2584:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2585:                          $sincefilter.':'.&escape($descfilter).':'.
 2586:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2587:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2588:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
 2589:                 my @pairs=split(/\&/,$rep);
 2590:                 foreach my $item (@pairs) {
 2591:                     my ($key,$value)=split(/\=/,$item,2);
 2592:                     $key = &unescape($key);
 2593:                     next if ($key =~ /^error: 2 /);
 2594:                     my $result = &thaw_unescape($value);
 2595:                     if (ref($result) eq 'HASH') {
 2596:                         $returnhash{$key}=$result;
 2597:                     } else {
 2598:                         my @responses = split(/:/,$value);
 2599:                         my @items = ('description','inst_code','owner','type');
 2600:                         for (my $i=0; $i<@responses; $i++) {
 2601:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2602:                         }
 2603:                     } 
 2604:                 }
 2605:             }
 2606:         }
 2607:     }
 2608:     return %returnhash;
 2609: }
 2610: 
 2611: # ---------------------------------------------------------- DC e-mail
 2612: 
 2613: sub dcmailput {
 2614:     my ($domain,$msgid,$message,$server)=@_;
 2615:     my $status = &Apache::lonnet::critical(
 2616:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2617:        &escape($message),$server);
 2618:     return $status;
 2619: }
 2620: 
 2621: sub dcmaildump {
 2622:     my ($dom,$startdate,$enddate,$senders) = @_;
 2623:     my %returnhash=();
 2624: 
 2625:     if (defined(&domain($dom,'primary'))) {
 2626:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2627:                                                          &escape($enddate).':';
 2628: 	my @esc_senders=map { &escape($_)} @$senders;
 2629: 	$cmd.=&escape(join('&',@esc_senders));
 2630: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2631:             my ($key,$value) = split(/\=/,$line,2);
 2632:             if (($key) && ($value)) {
 2633:                 $returnhash{&unescape($key)} = &unescape($value);
 2634:             }
 2635:         }
 2636:     }
 2637:     return %returnhash;
 2638: }
 2639: # ---------------------------------------------------------- Domain roles
 2640: 
 2641: sub get_domain_roles {
 2642:     my ($dom,$roles,$startdate,$enddate)=@_;
 2643:     if (undef($startdate) || $startdate eq '') {
 2644:         $startdate = '.';
 2645:     }
 2646:     if (undef($enddate) || $enddate eq '') {
 2647:         $enddate = '.';
 2648:     }
 2649:     my $rolelist;
 2650:     if (ref($roles) eq 'ARRAY') {
 2651:         $rolelist = join(':',@{$roles});
 2652:     }
 2653:     my %personnel = ();
 2654: 
 2655:     my %servers = &get_servers($dom,'library');
 2656:     foreach my $tryserver (keys(%servers)) {
 2657: 	%{$personnel{$tryserver}}=();
 2658: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2659: 					    &escape($startdate).':'.
 2660: 					    &escape($enddate).':'.
 2661: 					    &escape($rolelist), $tryserver))) {
 2662: 	    my ($key,$value) = split(/\=/,$line,2);
 2663: 	    if (($key) && ($value)) {
 2664: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2665: 	    }
 2666: 	}
 2667:     }
 2668:     return %personnel;
 2669: }
 2670: 
 2671: # ----------------------------------------------------------- Check out an item
 2672: 
 2673: sub get_first_access {
 2674:     my ($type,$argsymb)=@_;
 2675:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2676:     if ($argsymb) { $symb=$argsymb; }
 2677:     my ($map,$id,$res)=&decode_symb($symb);
 2678:     if ($type eq 'course') {
 2679: 	$res='course';
 2680:     } elsif ($type eq 'map') {
 2681: 	$res=&symbread($map);
 2682:     } else {
 2683: 	$res=$symb;
 2684:     }
 2685:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2686:     return $times{"$courseid\0$res"};
 2687: }
 2688: 
 2689: sub set_first_access {
 2690:     my ($type)=@_;
 2691:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2692:     my ($map,$id,$res)=&decode_symb($symb);
 2693:     if ($type eq 'course') {
 2694: 	$res='course';
 2695:     } elsif ($type eq 'map') {
 2696: 	$res=&symbread($map);
 2697:     } else {
 2698: 	$res=$symb;
 2699:     }
 2700:     my $firstaccess=&get_first_access($type,$symb);
 2701:     if (!$firstaccess) {
 2702: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2703:     }
 2704:     return 'already_set';
 2705: }
 2706: 
 2707: sub checkout {
 2708:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2709:     my $now=time;
 2710:     my $lonhost=$perlvar{'lonHostID'};
 2711:     my $infostr=&escape(
 2712:                  'CHECKOUTTOKEN&'.
 2713:                  $tuname.'&'.
 2714:                  $tudom.'&'.
 2715:                  $tcrsid.'&'.
 2716:                  $symb.'&'.
 2717: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2718:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2719:     if ($token=~/^error\:/) { 
 2720:         &logthis("<font color=\"blue\">WARNING: ".
 2721:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2722:                  "</font>");
 2723:         return ''; 
 2724:     }
 2725: 
 2726:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2727:     $token=~tr/a-z/A-Z/;
 2728: 
 2729:     my %infohash=('resource.0.outtoken' => $token,
 2730:                   'resource.0.checkouttime' => $now,
 2731:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2732: 
 2733:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2734:        return '';
 2735:     } else {
 2736:         &logthis("<font color=\"blue\">WARNING: ".
 2737:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2738:                  "</font>");
 2739:     }    
 2740: 
 2741:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2742:                          &escape('Checkout '.$infostr.' - '.
 2743:                                                  $token)) ne 'ok') {
 2744: 	return '';
 2745:     } else {
 2746:         &logthis("<font color=\"blue\">WARNING: ".
 2747:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2748:                  "</font>");
 2749:     }
 2750:     return $token;
 2751: }
 2752: 
 2753: # ------------------------------------------------------------ Check in an item
 2754: 
 2755: sub checkin {
 2756:     my $token=shift;
 2757:     my $now=time;
 2758:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2759:     $lonhost=~tr/A-Z/a-z/;
 2760:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2761:     $dtoken=~s/\W/\_/g;
 2762:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2763:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2764: 
 2765:     unless (($tuname) && ($tudom)) {
 2766:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2767:         return '';
 2768:     }
 2769:     
 2770:     unless (&allowed('mgr',$tcrsid)) {
 2771:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2772:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2773:         return '';
 2774:     }
 2775: 
 2776:     my %infohash=('resource.0.intoken' => $token,
 2777:                   'resource.0.checkintime' => $now,
 2778:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2779: 
 2780:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2781:        return '';
 2782:     }    
 2783: 
 2784:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2785:                          &escape('Checkin - '.$token)) ne 'ok') {
 2786: 	return '';
 2787:     }
 2788: 
 2789:     return ($symb,$tuname,$tudom,$tcrsid);    
 2790: }
 2791: 
 2792: # --------------------------------------------- Set Expire Date for Spreadsheet
 2793: 
 2794: sub expirespread {
 2795:     my ($uname,$udom,$stype,$usymb)=@_;
 2796:     my $cid=$env{'request.course.id'}; 
 2797:     if ($cid) {
 2798:        my $now=time;
 2799:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2800:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2801:                             $env{'course.'.$cid.'.num'}.
 2802: 	        	    ':nohist_expirationdates:'.
 2803:                             &escape($key).'='.$now,
 2804:                             $env{'course.'.$cid.'.home'})
 2805:     }
 2806:     return 'ok';
 2807: }
 2808: 
 2809: # ----------------------------------------------------- Devalidate Spreadsheets
 2810: 
 2811: sub devalidate {
 2812:     my ($symb,$uname,$udom)=@_;
 2813:     my $cid=$env{'request.course.id'}; 
 2814:     if ($cid) {
 2815:         # delete the stored spreadsheets for
 2816:         # - the student level sheet of this user in course's homespace
 2817:         # - the assessment level sheet for this resource 
 2818:         #   for this user in user's homespace
 2819: 	# - current conditional state info
 2820: 	my $key=$uname.':'.$udom.':';
 2821:         my $status=
 2822: 	    &del('nohist_calculatedsheets',
 2823: 		 [$key.'studentcalc:'],
 2824: 		 $env{'course.'.$cid.'.domain'},
 2825: 		 $env{'course.'.$cid.'.num'})
 2826: 		.' '.
 2827: 	    &del('nohist_calculatedsheets_'.$cid,
 2828: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2829:         unless ($status eq 'ok ok') {
 2830:            &logthis('Could not devalidate spreadsheet '.
 2831:                     $uname.' at '.$udom.' for '.
 2832: 		    $symb.': '.$status);
 2833:         }
 2834: 	&delenv('user.state.'.$cid);
 2835:     }
 2836: }
 2837: 
 2838: sub get_scalar {
 2839:     my ($string,$end) = @_;
 2840:     my $value;
 2841:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2842: 	$value = $1;
 2843:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2844: 	$value = $1;
 2845:     }
 2846:     return &unescape($value);
 2847: }
 2848: 
 2849: sub array2str {
 2850:   my (@array) = @_;
 2851:   my $result=&arrayref2str(\@array);
 2852:   $result=~s/^__ARRAY_REF__//;
 2853:   $result=~s/__END_ARRAY_REF__$//;
 2854:   return $result;
 2855: }
 2856: 
 2857: sub arrayref2str {
 2858:   my ($arrayref) = @_;
 2859:   my $result='__ARRAY_REF__';
 2860:   foreach my $elem (@$arrayref) {
 2861:     if(ref($elem) eq 'ARRAY') {
 2862:       $result.=&arrayref2str($elem).'&';
 2863:     } elsif(ref($elem) eq 'HASH') {
 2864:       $result.=&hashref2str($elem).'&';
 2865:     } elsif(ref($elem)) {
 2866:       #print("Got a ref of ".(ref($elem))." skipping.");
 2867:     } else {
 2868:       $result.=&escape($elem).'&';
 2869:     }
 2870:   }
 2871:   $result=~s/\&$//;
 2872:   $result .= '__END_ARRAY_REF__';
 2873:   return $result;
 2874: }
 2875: 
 2876: sub hash2str {
 2877:   my (%hash) = @_;
 2878:   my $result=&hashref2str(\%hash);
 2879:   $result=~s/^__HASH_REF__//;
 2880:   $result=~s/__END_HASH_REF__$//;
 2881:   return $result;
 2882: }
 2883: 
 2884: sub hashref2str {
 2885:   my ($hashref)=@_;
 2886:   my $result='__HASH_REF__';
 2887:   foreach my $key (sort(keys(%$hashref))) {
 2888:     if (ref($key) eq 'ARRAY') {
 2889:       $result.=&arrayref2str($key).'=';
 2890:     } elsif (ref($key) eq 'HASH') {
 2891:       $result.=&hashref2str($key).'=';
 2892:     } elsif (ref($key)) {
 2893:       $result.='=';
 2894:       #print("Got a ref of ".(ref($key))." skipping.");
 2895:     } else {
 2896: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2897:     }
 2898: 
 2899:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2900:       $result.=&arrayref2str($hashref->{$key}).'&';
 2901:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2902:       $result.=&hashref2str($hashref->{$key}).'&';
 2903:     } elsif(ref($hashref->{$key})) {
 2904:        $result.='&';
 2905:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2906:     } else {
 2907:       $result.=&escape($hashref->{$key}).'&';
 2908:     }
 2909:   }
 2910:   $result=~s/\&$//;
 2911:   $result .= '__END_HASH_REF__';
 2912:   return $result;
 2913: }
 2914: 
 2915: sub str2hash {
 2916:     my ($string)=@_;
 2917:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2918:     return %$hash;
 2919: }
 2920: 
 2921: sub str2hashref {
 2922:   my ($string) = @_;
 2923: 
 2924:   my %hash;
 2925: 
 2926:   if($string !~ /^__HASH_REF__/) {
 2927:       if (! ($string eq '' || !defined($string))) {
 2928: 	  $hash{'error'}='Not hash reference';
 2929:       }
 2930:       return (\%hash, $string);
 2931:   }
 2932: 
 2933:   $string =~ s/^__HASH_REF__//;
 2934: 
 2935:   while($string !~ /^__END_HASH_REF__/) {
 2936:       #key
 2937:       my $key='';
 2938:       if($string =~ /^__HASH_REF__/) {
 2939:           ($key, $string)=&str2hashref($string);
 2940:           if(defined($key->{'error'})) {
 2941:               $hash{'error'}='Bad data';
 2942:               return (\%hash, $string);
 2943:           }
 2944:       } elsif($string =~ /^__ARRAY_REF__/) {
 2945:           ($key, $string)=&str2arrayref($string);
 2946:           if($key->[0] eq 'Array reference error') {
 2947:               $hash{'error'}='Bad data';
 2948:               return (\%hash, $string);
 2949:           }
 2950:       } else {
 2951:           $string =~ s/^(.*?)=//;
 2952: 	  $key=&unescape($1);
 2953:       }
 2954:       $string =~ s/^=//;
 2955: 
 2956:       #value
 2957:       my $value='';
 2958:       if($string =~ /^__HASH_REF__/) {
 2959:           ($value, $string)=&str2hashref($string);
 2960:           if(defined($value->{'error'})) {
 2961:               $hash{'error'}='Bad data';
 2962:               return (\%hash, $string);
 2963:           }
 2964:       } elsif($string =~ /^__ARRAY_REF__/) {
 2965:           ($value, $string)=&str2arrayref($string);
 2966:           if($value->[0] eq 'Array reference error') {
 2967:               $hash{'error'}='Bad data';
 2968:               return (\%hash, $string);
 2969:           }
 2970:       } else {
 2971: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2972:       }
 2973:       $string =~ s/^&//;
 2974: 
 2975:       $hash{$key}=$value;
 2976:   }
 2977: 
 2978:   $string =~ s/^__END_HASH_REF__//;
 2979: 
 2980:   return (\%hash, $string);
 2981: }
 2982: 
 2983: sub str2array {
 2984:     my ($string)=@_;
 2985:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2986:     return @$array;
 2987: }
 2988: 
 2989: sub str2arrayref {
 2990:   my ($string) = @_;
 2991:   my @array;
 2992: 
 2993:   if($string !~ /^__ARRAY_REF__/) {
 2994:       if (! ($string eq '' || !defined($string))) {
 2995: 	  $array[0]='Array reference error';
 2996:       }
 2997:       return (\@array, $string);
 2998:   }
 2999: 
 3000:   $string =~ s/^__ARRAY_REF__//;
 3001: 
 3002:   while($string !~ /^__END_ARRAY_REF__/) {
 3003:       my $value='';
 3004:       if($string =~ /^__HASH_REF__/) {
 3005:           ($value, $string)=&str2hashref($string);
 3006:           if(defined($value->{'error'})) {
 3007:               $array[0] ='Array reference error';
 3008:               return (\@array, $string);
 3009:           }
 3010:       } elsif($string =~ /^__ARRAY_REF__/) {
 3011:           ($value, $string)=&str2arrayref($string);
 3012:           if($value->[0] eq 'Array reference error') {
 3013:               $array[0] ='Array reference error';
 3014:               return (\@array, $string);
 3015:           }
 3016:       } else {
 3017: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3018:       }
 3019:       $string =~ s/^&//;
 3020: 
 3021:       push(@array, $value);
 3022:   }
 3023: 
 3024:   $string =~ s/^__END_ARRAY_REF__//;
 3025: 
 3026:   return (\@array, $string);
 3027: }
 3028: 
 3029: # -------------------------------------------------------------------Temp Store
 3030: 
 3031: sub tmpreset {
 3032:   my ($symb,$namespace,$domain,$stuname) = @_;
 3033:   if (!$symb) {
 3034:     $symb=&symbread();
 3035:     if (!$symb) { $symb= $env{'request.url'}; }
 3036:   }
 3037:   $symb=escape($symb);
 3038: 
 3039:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3040:   $namespace=~s/\//\_/g;
 3041:   $namespace=~s/\W//g;
 3042: 
 3043:   if (!$domain) { $domain=$env{'user.domain'}; }
 3044:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3045:   if ($domain eq 'public' && $stuname eq 'public') {
 3046:       $stuname=$ENV{'REMOTE_ADDR'};
 3047:   }
 3048:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3049:   my %hash;
 3050:   if (tie(%hash,'GDBM_File',
 3051: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3052: 	  &GDBM_WRCREAT(),0640)) {
 3053:     foreach my $key (keys %hash) {
 3054:       if ($key=~ /:$symb/) {
 3055: 	delete($hash{$key});
 3056:       }
 3057:     }
 3058:   }
 3059: }
 3060: 
 3061: sub tmpstore {
 3062:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3063: 
 3064:   if (!$symb) {
 3065:     $symb=&symbread();
 3066:     if (!$symb) { $symb= $env{'request.url'}; }
 3067:   }
 3068:   $symb=escape($symb);
 3069: 
 3070:   if (!$namespace) {
 3071:     # I don't think we would ever want to store this for a course.
 3072:     # it seems this will only be used if we don't have a course.
 3073:     #$namespace=$env{'request.course.id'};
 3074:     #if (!$namespace) {
 3075:       $namespace=$env{'request.state'};
 3076:     #}
 3077:   }
 3078:   $namespace=~s/\//\_/g;
 3079:   $namespace=~s/\W//g;
 3080:   if (!$domain) { $domain=$env{'user.domain'}; }
 3081:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3082:   if ($domain eq 'public' && $stuname eq 'public') {
 3083:       $stuname=$ENV{'REMOTE_ADDR'};
 3084:   }
 3085:   my $now=time;
 3086:   my %hash;
 3087:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3088:   if (tie(%hash,'GDBM_File',
 3089: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3090: 	  &GDBM_WRCREAT(),0640)) {
 3091:     $hash{"version:$symb"}++;
 3092:     my $version=$hash{"version:$symb"};
 3093:     my $allkeys=''; 
 3094:     foreach my $key (keys(%$storehash)) {
 3095:       $allkeys.=$key.':';
 3096:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3097:     }
 3098:     $hash{"$version:$symb:timestamp"}=$now;
 3099:     $allkeys.='timestamp';
 3100:     $hash{"$version:keys:$symb"}=$allkeys;
 3101:     if (untie(%hash)) {
 3102:       return 'ok';
 3103:     } else {
 3104:       return "error:$!";
 3105:     }
 3106:   } else {
 3107:     return "error:$!";
 3108:   }
 3109: }
 3110: 
 3111: # -----------------------------------------------------------------Temp Restore
 3112: 
 3113: sub tmprestore {
 3114:   my ($symb,$namespace,$domain,$stuname) = @_;
 3115: 
 3116:   if (!$symb) {
 3117:     $symb=&symbread();
 3118:     if (!$symb) { $symb= $env{'request.url'}; }
 3119:   }
 3120:   $symb=escape($symb);
 3121: 
 3122:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3123: 
 3124:   if (!$domain) { $domain=$env{'user.domain'}; }
 3125:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3126:   if ($domain eq 'public' && $stuname eq 'public') {
 3127:       $stuname=$ENV{'REMOTE_ADDR'};
 3128:   }
 3129:   my %returnhash;
 3130:   $namespace=~s/\//\_/g;
 3131:   $namespace=~s/\W//g;
 3132:   my %hash;
 3133:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3134:   if (tie(%hash,'GDBM_File',
 3135: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3136: 	  &GDBM_READER(),0640)) {
 3137:     my $version=$hash{"version:$symb"};
 3138:     $returnhash{'version'}=$version;
 3139:     my $scope;
 3140:     for ($scope=1;$scope<=$version;$scope++) {
 3141:       my $vkeys=$hash{"$scope:keys:$symb"};
 3142:       my @keys=split(/:/,$vkeys);
 3143:       my $key;
 3144:       $returnhash{"$scope:keys"}=$vkeys;
 3145:       foreach $key (@keys) {
 3146: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3147: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3148:       }
 3149:     }
 3150:     if (!(untie(%hash))) {
 3151:       return "error:$!";
 3152:     }
 3153:   } else {
 3154:     return "error:$!";
 3155:   }
 3156:   return %returnhash;
 3157: }
 3158: 
 3159: # ----------------------------------------------------------------------- Store
 3160: 
 3161: sub store {
 3162:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3163:     my $home='';
 3164: 
 3165:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3166: 
 3167:     $symb=&symbclean($symb);
 3168:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3169: 
 3170:     if (!$domain) { $domain=$env{'user.domain'}; }
 3171:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3172: 
 3173:     &devalidate($symb,$stuname,$domain);
 3174: 
 3175:     $symb=escape($symb);
 3176:     if (!$namespace) { 
 3177:        unless ($namespace=$env{'request.course.id'}) { 
 3178:           return ''; 
 3179:        } 
 3180:     }
 3181:     if (!$home) { $home=$env{'user.home'}; }
 3182: 
 3183:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3184:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3185: 
 3186:     my $namevalue='';
 3187:     foreach my $key (keys(%$storehash)) {
 3188:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3189:     }
 3190:     $namevalue=~s/\&$//;
 3191:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3192:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3193: }
 3194: 
 3195: # -------------------------------------------------------------- Critical Store
 3196: 
 3197: sub cstore {
 3198:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3199:     my $home='';
 3200: 
 3201:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3202: 
 3203:     $symb=&symbclean($symb);
 3204:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3205: 
 3206:     if (!$domain) { $domain=$env{'user.domain'}; }
 3207:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3208: 
 3209:     &devalidate($symb,$stuname,$domain);
 3210: 
 3211:     $symb=escape($symb);
 3212:     if (!$namespace) { 
 3213:        unless ($namespace=$env{'request.course.id'}) { 
 3214:           return ''; 
 3215:        } 
 3216:     }
 3217:     if (!$home) { $home=$env{'user.home'}; }
 3218: 
 3219:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3220:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3221: 
 3222:     my $namevalue='';
 3223:     foreach my $key (keys(%$storehash)) {
 3224:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3225:     }
 3226:     $namevalue=~s/\&$//;
 3227:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3228:     return critical
 3229:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3230: }
 3231: 
 3232: # --------------------------------------------------------------------- Restore
 3233: 
 3234: sub restore {
 3235:     my ($symb,$namespace,$domain,$stuname) = @_;
 3236:     my $home='';
 3237: 
 3238:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3239: 
 3240:     if (!$symb) {
 3241:       unless ($symb=escape(&symbread())) { return ''; }
 3242:     } else {
 3243:       $symb=&escape(&symbclean($symb));
 3244:     }
 3245:     if (!$namespace) { 
 3246:        unless ($namespace=$env{'request.course.id'}) { 
 3247:           return ''; 
 3248:        } 
 3249:     }
 3250:     if (!$domain) { $domain=$env{'user.domain'}; }
 3251:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3252:     if (!$home) { $home=$env{'user.home'}; }
 3253:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3254: 
 3255:     my %returnhash=();
 3256:     foreach my $line (split(/\&/,$answer)) {
 3257: 	my ($name,$value)=split(/\=/,$line);
 3258:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3259:     }
 3260:     my $version;
 3261:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3262:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3263:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3264:        }
 3265:     }
 3266:     return %returnhash;
 3267: }
 3268: 
 3269: # ---------------------------------------------------------- Course Description
 3270: 
 3271: sub coursedescription {
 3272:     my ($courseid,$args)=@_;
 3273:     $courseid=~s/^\///;
 3274:     $courseid=~s/\_/\//g;
 3275:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3276:     my $chome=&homeserver($cnum,$cdomain);
 3277:     my $normalid=$cdomain.'_'.$cnum;
 3278:     # need to always cache even if we get errors otherwise we keep 
 3279:     # trying and trying and trying to get the course description.
 3280:     my %envhash=();
 3281:     my %returnhash=();
 3282:     
 3283:     my $expiretime=600;
 3284:     if ($env{'request.course.id'} eq $normalid) {
 3285: 	$expiretime=120;
 3286:     }
 3287: 
 3288:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3289:     if (!$args->{'freshen_cache'}
 3290: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3291: 	foreach my $key (keys(%env)) {
 3292: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3293: 	    my ($setting) = $1;
 3294: 	    $returnhash{$setting} = $env{$key};
 3295: 	}
 3296: 	return %returnhash;
 3297:     }
 3298: 
 3299:     # get the data agin
 3300:     if (!$args->{'one_time'}) {
 3301: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3302:     }
 3303: 
 3304:     if ($chome ne 'no_host') {
 3305:        %returnhash=&dump('environment',$cdomain,$cnum);
 3306:        if (!exists($returnhash{'con_lost'})) {
 3307:            $returnhash{'home'}= $chome;
 3308: 	   $returnhash{'domain'} = $cdomain;
 3309: 	   $returnhash{'num'} = $cnum;
 3310:            if (!defined($returnhash{'type'})) {
 3311:                $returnhash{'type'} = 'Course';
 3312:            }
 3313:            while (my ($name,$value) = each %returnhash) {
 3314:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3315:            }
 3316:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3317:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3318: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3319:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3320:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3321:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3322:        }
 3323:     }
 3324:     if (!$args->{'one_time'}) {
 3325: 	&appenv(%envhash);
 3326:     }
 3327:     return %returnhash;
 3328: }
 3329: 
 3330: # -------------------------------------------------See if a user is privileged
 3331: 
 3332: sub privileged {
 3333:     my ($username,$domain)=@_;
 3334:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3335: 			&homeserver($username,$domain));
 3336:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3337:     my $now=time;
 3338:     if ($rolesdump ne '') {
 3339:         foreach my $entry (split(/&/,$rolesdump)) {
 3340: 	    if ($entry!~/^rolesdef_/) {
 3341: 		my ($area,$role)=split(/=/,$entry);
 3342: 		$area=~s/\_\w\w$//;
 3343: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3344: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3345: 		    my $active=1;
 3346: 		    if ($tend) {
 3347: 			if ($tend<$now) { $active=0; }
 3348: 		    }
 3349: 		    if ($tstart) {
 3350: 			if ($tstart>$now) { $active=0; }
 3351: 		    }
 3352: 		    if ($active) { return 1; }
 3353: 		}
 3354: 	    }
 3355: 	}
 3356:     }
 3357:     return 0;
 3358: }
 3359: 
 3360: # -------------------------------------------------------- Get user privileges
 3361: 
 3362: sub rolesinit {
 3363:     my ($domain,$username,$authhost)=@_;
 3364:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3365:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3366:     my %allroles=();
 3367:     my %allgroups=();   
 3368:     my $now=time;
 3369:     my %userroles = ('user.login.time' => $now);
 3370:     my $group_privs;
 3371: 
 3372:     if ($rolesdump ne '') {
 3373:         foreach my $entry (split(/&/,$rolesdump)) {
 3374: 	  if ($entry!~/^rolesdef_/) {
 3375:             my ($area,$role)=split(/=/,$entry);
 3376: 	    $area=~s/\_\w\w$//;
 3377:             my ($trole,$tend,$tstart,$group_privs);
 3378: 	    if ($role=~/^cr/) { 
 3379: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3380: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3381: 		    ($tend,$tstart)=split('_',$trest);
 3382: 		} else {
 3383: 		    $trole=$role;
 3384: 		}
 3385:             } elsif ($role =~ m|^gr/|) {
 3386:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3387:                 ($trole,$group_privs) = split(/\//,$trole);
 3388:                 $group_privs = &unescape($group_privs);
 3389: 	    } else {
 3390: 		($trole,$tend,$tstart)=split(/_/,$role);
 3391: 	    }
 3392: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3393: 					 $username);
 3394: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3395:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3396:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3397:             if (($area ne '') && ($trole ne '')) {
 3398: 		my $spec=$trole.'.'.$area;
 3399: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3400: 		if ($trole =~ /^cr\//) {
 3401:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3402:                 } elsif ($trole eq 'gr') {
 3403:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3404: 		} else {
 3405:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3406: 		}
 3407:             }
 3408:           }
 3409:         }
 3410:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3411:         $userroles{'user.adv'}    = $adv;
 3412: 	$userroles{'user.author'} = $author;
 3413:         $env{'user.adv'}=$adv;
 3414:     }
 3415:     return \%userroles;  
 3416: }
 3417: 
 3418: sub set_arearole {
 3419:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3420: # log the associated role with the area
 3421:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3422:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3423: }
 3424: 
 3425: sub custom_roleprivs {
 3426:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3427:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3428:     my $homsvr=homeserver($rauthor,$rdomain);
 3429:     if (&hostname($homsvr) ne '') {
 3430:         my ($rdummy,$roledef)=
 3431:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3432:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3433:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3434:             if (defined($syspriv)) {
 3435:                 $$allroles{'cm./'}.=':'.$syspriv;
 3436:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3437:             }
 3438:             if ($tdomain ne '') {
 3439:                 if (defined($dompriv)) {
 3440:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3441:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3442:                 }
 3443:                 if (($trest ne '') && (defined($coursepriv))) {
 3444:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3445:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3446:                 }
 3447:             }
 3448:         }
 3449:     }
 3450: }
 3451: 
 3452: sub group_roleprivs {
 3453:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3454:     my $access = 1;
 3455:     my $now = time;
 3456:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3457:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3458:     if ($access) {
 3459:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3460:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3461:     }
 3462: }
 3463: 
 3464: sub standard_roleprivs {
 3465:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3466:     if (defined($pr{$trole.':s'})) {
 3467:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3468:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3469:     }
 3470:     if ($tdomain ne '') {
 3471:         if (defined($pr{$trole.':d'})) {
 3472:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3473:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3474:         }
 3475:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3476:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3477:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3478:         }
 3479:     }
 3480: }
 3481: 
 3482: sub set_userprivs {
 3483:     my ($userroles,$allroles,$allgroups) = @_; 
 3484:     my $author=0;
 3485:     my $adv=0;
 3486:     my %grouproles = ();
 3487:     if (keys(%{$allgroups}) > 0) {
 3488:         foreach my $role (keys %{$allroles}) {
 3489:             my ($trole,$area,$sec,$extendedarea);
 3490:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3491:                 $trole = $1;
 3492:                 $area = $2;
 3493:                 $sec = $3;
 3494:                 $extendedarea = $area.$sec;
 3495:                 if (exists($$allgroups{$area})) {
 3496:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3497:                         my $spec = $trole.'.'.$extendedarea;
 3498:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3499:                                                 $$allgroups{$area}{$group};
 3500:                     }
 3501:                 }
 3502:             }
 3503:         }
 3504:     }
 3505:     foreach my $group (keys(%grouproles)) {
 3506:         $$allroles{$group} = $grouproles{$group};
 3507:     }
 3508:     foreach my $role (keys(%{$allroles})) {
 3509:         my %thesepriv;
 3510:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3511:         foreach my $item (split(/:/,$$allroles{$role})) {
 3512:             if ($item ne '') {
 3513:                 my ($privilege,$restrictions)=split(/&/,$item);
 3514:                 if ($restrictions eq '') {
 3515:                     $thesepriv{$privilege}='F';
 3516:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3517:                     $thesepriv{$privilege}.=$restrictions;
 3518:                 }
 3519:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3520:             }
 3521:         }
 3522:         my $thesestr='';
 3523:         foreach my $priv (keys(%thesepriv)) {
 3524: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3525: 	}
 3526:         $userroles->{'user.priv.'.$role} = $thesestr;
 3527:     }
 3528:     return ($author,$adv);
 3529: }
 3530: 
 3531: # --------------------------------------------------------------- get interface
 3532: 
 3533: sub get {
 3534:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3535:    my $items='';
 3536:    foreach my $item (@$storearr) {
 3537:        $items.=&escape($item).'&';
 3538:    }
 3539:    $items=~s/\&$//;
 3540:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3541:    if (!$uname) { $uname=$env{'user.name'}; }
 3542:    my $uhome=&homeserver($uname,$udomain);
 3543: 
 3544:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3545:    my @pairs=split(/\&/,$rep);
 3546:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3547:      return @pairs;
 3548:    }
 3549:    my %returnhash=();
 3550:    my $i=0;
 3551:    foreach my $item (@$storearr) {
 3552:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3553:       $i++;
 3554:    }
 3555:    return %returnhash;
 3556: }
 3557: 
 3558: # --------------------------------------------------------------- del interface
 3559: 
 3560: sub del {
 3561:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3562:    my $items='';
 3563:    foreach my $item (@$storearr) {
 3564:        $items.=&escape($item).'&';
 3565:    }
 3566:    $items=~s/\&$//;
 3567:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3568:    if (!$uname) { $uname=$env{'user.name'}; }
 3569:    my $uhome=&homeserver($uname,$udomain);
 3570: 
 3571:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3572: }
 3573: 
 3574: # -------------------------------------------------------------- dump interface
 3575: 
 3576: sub dump {
 3577:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3578:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3579:     if (!$uname) { $uname=$env{'user.name'}; }
 3580:     my $uhome=&homeserver($uname,$udomain);
 3581:     if ($regexp) {
 3582: 	$regexp=&escape($regexp);
 3583:     } else {
 3584: 	$regexp='.';
 3585:     }
 3586:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3587:     my @pairs=split(/\&/,$rep);
 3588:     my %returnhash=();
 3589:     foreach my $item (@pairs) {
 3590: 	my ($key,$value)=split(/=/,$item,2);
 3591: 	$key = &unescape($key);
 3592: 	next if ($key =~ /^error: 2 /);
 3593: 	$returnhash{$key}=&thaw_unescape($value);
 3594:     }
 3595:     return %returnhash;
 3596: }
 3597: 
 3598: # --------------------------------------------------------- dumpstore interface
 3599: 
 3600: sub dumpstore {
 3601:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3602:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3603:    if (!$uname) { $uname=$env{'user.name'}; }
 3604:    my $uhome=&homeserver($uname,$udomain);
 3605:    if ($regexp) {
 3606:        $regexp=&escape($regexp);
 3607:    } else {
 3608:        $regexp='.';
 3609:    }
 3610:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3611:    my @pairs=split(/\&/,$rep);
 3612:    my %returnhash=();
 3613:    foreach my $item (@pairs) {
 3614:        my ($key,$value)=split(/=/,$item,2);
 3615:        next if ($key =~ /^error: 2 /);
 3616:        $returnhash{$key}=&thaw_unescape($value);
 3617:    }
 3618:    return %returnhash;
 3619: }
 3620: 
 3621: # -------------------------------------------------------------- keys interface
 3622: 
 3623: sub getkeys {
 3624:    my ($namespace,$udomain,$uname)=@_;
 3625:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3626:    if (!$uname) { $uname=$env{'user.name'}; }
 3627:    my $uhome=&homeserver($uname,$udomain);
 3628:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3629:    my @keyarray=();
 3630:    foreach my $key (split(/\&/,$rep)) {
 3631:       next if ($key =~ /^error: 2 /);
 3632:       push(@keyarray,&unescape($key));
 3633:    }
 3634:    return @keyarray;
 3635: }
 3636: 
 3637: # --------------------------------------------------------------- currentdump
 3638: sub currentdump {
 3639:    my ($courseid,$sdom,$sname)=@_;
 3640:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3641:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3642:    $sname    = $env{'user.name'}         if (! defined($sname));
 3643:    my $uhome = &homeserver($sname,$sdom);
 3644:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3645:    return if ($rep =~ /^(error:|no_such_host)/);
 3646:    #
 3647:    my %returnhash=();
 3648:    #
 3649:    if ($rep eq "unknown_cmd") { 
 3650:        # an old lond will not know currentdump
 3651:        # Do a dump and make it look like a currentdump
 3652:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3653:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3654:        my %hash = @tmp;
 3655:        @tmp=();
 3656:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3657:    } else {
 3658:        my @pairs=split(/\&/,$rep);
 3659:        foreach my $pair (@pairs) {
 3660:            my ($key,$value)=split(/=/,$pair,2);
 3661:            my ($symb,$param) = split(/:/,$key);
 3662:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3663:                                                         &thaw_unescape($value);
 3664:        }
 3665:    }
 3666:    return %returnhash;
 3667: }
 3668: 
 3669: sub convert_dump_to_currentdump{
 3670:     my %hash = %{shift()};
 3671:     my %returnhash;
 3672:     # Code ripped from lond, essentially.  The only difference
 3673:     # here is the unescaping done by lonnet::dump().  Conceivably
 3674:     # we might run in to problems with parameter names =~ /^v\./
 3675:     while (my ($key,$value) = each(%hash)) {
 3676:         my ($v,$symb,$param) = split(/:/,$key);
 3677: 	$symb  = &unescape($symb);
 3678: 	$param = &unescape($param);
 3679:         next if ($v eq 'version' || $symb eq 'keys');
 3680:         next if (exists($returnhash{$symb}) &&
 3681:                  exists($returnhash{$symb}->{$param}) &&
 3682:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3683:         $returnhash{$symb}->{$param}=$value;
 3684:         $returnhash{$symb}->{'v.'.$param}=$v;
 3685:     }
 3686:     #
 3687:     # Remove all of the keys in the hashes which keep track of
 3688:     # the version of the parameter.
 3689:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3690:         # use a foreach because we are going to delete from the hash.
 3691:         foreach my $key (keys(%$param_hash)) {
 3692:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3693:         }
 3694:     }
 3695:     return \%returnhash;
 3696: }
 3697: 
 3698: # ------------------------------------------------------ critical inc interface
 3699: 
 3700: sub cinc {
 3701:     return &inc(@_,'critical');
 3702: }
 3703: 
 3704: # --------------------------------------------------------------- inc interface
 3705: 
 3706: sub inc {
 3707:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3708:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3709:     if (!$uname) { $uname=$env{'user.name'}; }
 3710:     my $uhome=&homeserver($uname,$udomain);
 3711:     my $items='';
 3712:     if (! ref($store)) {
 3713:         # got a single value, so use that instead
 3714:         $items = &escape($store).'=&';
 3715:     } elsif (ref($store) eq 'SCALAR') {
 3716:         $items = &escape($$store).'=&';        
 3717:     } elsif (ref($store) eq 'ARRAY') {
 3718:         $items = join('=&',map {&escape($_);} @{$store});
 3719:     } elsif (ref($store) eq 'HASH') {
 3720:         while (my($key,$value) = each(%{$store})) {
 3721:             $items.= &escape($key).'='.&escape($value).'&';
 3722:         }
 3723:     }
 3724:     $items=~s/\&$//;
 3725:     if ($critical) {
 3726: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3727:     } else {
 3728: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3729:     }
 3730: }
 3731: 
 3732: # --------------------------------------------------------------- put interface
 3733: 
 3734: sub put {
 3735:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3736:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3737:    if (!$uname) { $uname=$env{'user.name'}; }
 3738:    my $uhome=&homeserver($uname,$udomain);
 3739:    my $items='';
 3740:    foreach my $item (keys(%$storehash)) {
 3741:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3742:    }
 3743:    $items=~s/\&$//;
 3744:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3745: }
 3746: 
 3747: # ------------------------------------------------------------ newput interface
 3748: 
 3749: sub newput {
 3750:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3751:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3752:    if (!$uname) { $uname=$env{'user.name'}; }
 3753:    my $uhome=&homeserver($uname,$udomain);
 3754:    my $items='';
 3755:    foreach my $key (keys(%$storehash)) {
 3756:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3757:    }
 3758:    $items=~s/\&$//;
 3759:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3760: }
 3761: 
 3762: # ---------------------------------------------------------  putstore interface
 3763: 
 3764: sub putstore {
 3765:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3766:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3767:    if (!$uname) { $uname=$env{'user.name'}; }
 3768:    my $uhome=&homeserver($uname,$udomain);
 3769:    my $items='';
 3770:    foreach my $key (keys(%$storehash)) {
 3771:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3772:    }
 3773:    $items=~s/\&$//;
 3774:    my $esc_symb=&escape($symb);
 3775:    my $esc_v=&escape($version);
 3776:    my $reply =
 3777:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3778: 	      $uhome);
 3779:    if ($reply eq 'unknown_cmd') {
 3780:        # gfall back to way things use to be done
 3781:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3782: 			    $uname);
 3783:    }
 3784:    return $reply;
 3785: }
 3786: 
 3787: sub old_putstore {
 3788:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3789:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3790:     if (!$uname) { $uname=$env{'user.name'}; }
 3791:     my $uhome=&homeserver($uname,$udomain);
 3792:     my %newstorehash;
 3793:     foreach my $item (keys(%$storehash)) {
 3794: 	my $key = $version.':'.&escape($symb).':'.$item;
 3795: 	$newstorehash{$key} = $storehash->{$item};
 3796:     }
 3797:     my $items='';
 3798:     my %allitems = ();
 3799:     foreach my $item (keys(%newstorehash)) {
 3800: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3801: 	    my $key = $1.':keys:'.$2;
 3802: 	    $allitems{$key} .= $3.':';
 3803: 	}
 3804: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3805:     }
 3806:     foreach my $item (keys(%allitems)) {
 3807: 	$allitems{$item} =~ s/\:$//;
 3808: 	$items.= $item.'='.$allitems{$item}.'&';
 3809:     }
 3810:     $items=~s/\&$//;
 3811:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3812: }
 3813: 
 3814: # ------------------------------------------------------ critical put interface
 3815: 
 3816: sub cput {
 3817:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3819:    if (!$uname) { $uname=$env{'user.name'}; }
 3820:    my $uhome=&homeserver($uname,$udomain);
 3821:    my $items='';
 3822:    foreach my $item (keys(%$storehash)) {
 3823:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3824:    }
 3825:    $items=~s/\&$//;
 3826:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3827: }
 3828: 
 3829: # -------------------------------------------------------------- eget interface
 3830: 
 3831: sub eget {
 3832:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3833:    my $items='';
 3834:    foreach my $item (@$storearr) {
 3835:        $items.=&escape($item).'&';
 3836:    }
 3837:    $items=~s/\&$//;
 3838:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3839:    if (!$uname) { $uname=$env{'user.name'}; }
 3840:    my $uhome=&homeserver($uname,$udomain);
 3841:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3842:    my @pairs=split(/\&/,$rep);
 3843:    my %returnhash=();
 3844:    my $i=0;
 3845:    foreach my $item (@$storearr) {
 3846:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3847:       $i++;
 3848:    }
 3849:    return %returnhash;
 3850: }
 3851: 
 3852: # ------------------------------------------------------------ tmpput interface
 3853: sub tmpput {
 3854:     my ($storehash,$server,$context)=@_;
 3855:     my $items='';
 3856:     foreach my $item (keys(%$storehash)) {
 3857: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3858:     }
 3859:     $items=~s/\&$//;
 3860:     if (defined($context)) {
 3861:         $items .= ':'.&escape($context);
 3862:     }
 3863:     return &reply("tmpput:$items",$server);
 3864: }
 3865: 
 3866: # ------------------------------------------------------------ tmpget interface
 3867: sub tmpget {
 3868:     my ($token,$server)=@_;
 3869:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3870:     my $rep=&reply("tmpget:$token",$server);
 3871:     my %returnhash;
 3872:     foreach my $item (split(/\&/,$rep)) {
 3873: 	my ($key,$value)=split(/=/,$item);
 3874: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3875:     }
 3876:     return %returnhash;
 3877: }
 3878: 
 3879: # ------------------------------------------------------------ tmpget interface
 3880: sub tmpdel {
 3881:     my ($token,$server)=@_;
 3882:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3883:     return &reply("tmpdel:$token",$server);
 3884: }
 3885: 
 3886: # -------------------------------------------------- portfolio access checking
 3887: 
 3888: sub portfolio_access {
 3889:     my ($requrl) = @_;
 3890:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3891:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3892:     if ($result) {
 3893:         my %setters;
 3894:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3895:             my ($startblock,$endblock) =
 3896:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3897:             if ($startblock && $endblock) {
 3898:                 return 'B';
 3899:             }
 3900:         } else {
 3901:             my ($startblock,$endblock) =
 3902:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3903:             if ($startblock && $endblock) {
 3904:                 return 'B';
 3905:             }
 3906:         }
 3907:     }
 3908:     if ($result eq 'ok') {
 3909:        return 'F';
 3910:     } elsif ($result =~ /^[^:]+:guest_/) {
 3911:        return 'A';
 3912:     }
 3913:     return '';
 3914: }
 3915: 
 3916: sub get_portfolio_access {
 3917:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3918: 
 3919:     if (!ref($access_hash)) {
 3920: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3921: 	my %access_controls = &get_access_controls($current_perms,$group,
 3922: 						   $file_name);
 3923: 	$access_hash = $access_controls{$file_name};
 3924:     }
 3925: 
 3926:     my ($public,$guest,@domains,@users,@courses,@groups);
 3927:     my $now = time;
 3928:     if (ref($access_hash) eq 'HASH') {
 3929:         foreach my $key (keys(%{$access_hash})) {
 3930:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3931:             if ($start > $now) {
 3932:                 next;
 3933:             }
 3934:             if ($end && $end<$now) {
 3935:                 next;
 3936:             }
 3937:             if ($scope eq 'public') {
 3938:                 $public = $key;
 3939:                 last;
 3940:             } elsif ($scope eq 'guest') {
 3941:                 $guest = $key;
 3942:             } elsif ($scope eq 'domains') {
 3943:                 push(@domains,$key);
 3944:             } elsif ($scope eq 'users') {
 3945:                 push(@users,$key);
 3946:             } elsif ($scope eq 'course') {
 3947:                 push(@courses,$key);
 3948:             } elsif ($scope eq 'group') {
 3949:                 push(@groups,$key);
 3950:             }
 3951:         }
 3952:         if ($public) {
 3953:             return 'ok';
 3954:         }
 3955:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3956:             if ($guest) {
 3957:                 return $guest;
 3958:             }
 3959:         } else {
 3960:             if (@domains > 0) {
 3961:                 foreach my $domkey (@domains) {
 3962:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3963:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3964:                             return 'ok';
 3965:                         }
 3966:                     }
 3967:                 }
 3968:             }
 3969:             if (@users > 0) {
 3970:                 foreach my $userkey (@users) {
 3971:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3972:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3973:                             if (ref($item) eq 'HASH') {
 3974:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3975:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3976:                                     return 'ok';
 3977:                                 }
 3978:                             }
 3979:                         }
 3980:                     } 
 3981:                 }
 3982:             }
 3983:             my %roleshash;
 3984:             my @courses_and_groups = @courses;
 3985:             push(@courses_and_groups,@groups); 
 3986:             if (@courses_and_groups > 0) {
 3987:                 my (%allgroups,%allroles); 
 3988:                 my ($start,$end,$role,$sec,$group);
 3989:                 foreach my $envkey (%env) {
 3990:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3991:                         my $cid = $2.'_'.$3; 
 3992:                         if ($1 eq 'gr') {
 3993:                             $group = $4;
 3994:                             $allgroups{$cid}{$group} = $env{$envkey};
 3995:                         } else {
 3996:                             if ($4 eq '') {
 3997:                                 $sec = 'none';
 3998:                             } else {
 3999:                                 $sec = $4;
 4000:                             }
 4001:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4002:                         }
 4003:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4004:                         my $cid = $2.'_'.$3;
 4005:                         if ($4 eq '') {
 4006:                             $sec = 'none';
 4007:                         } else {
 4008:                             $sec = $4;
 4009:                         }
 4010:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4011:                     }
 4012:                 }
 4013:                 if (keys(%allroles) == 0) {
 4014:                     return;
 4015:                 }
 4016:                 foreach my $key (@courses_and_groups) {
 4017:                     my %content = %{$$access_hash{$key}};
 4018:                     my $cnum = $content{'number'};
 4019:                     my $cdom = $content{'domain'};
 4020:                     my $cid = $cdom.'_'.$cnum;
 4021:                     if (!exists($allroles{$cid})) {
 4022:                         next;
 4023:                     }    
 4024:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4025:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4026:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4027:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4028:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4029:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4030:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4031:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4032:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4033:                                         if (grep/^all$/,@sections) {
 4034:                                             return 'ok';
 4035:                                         } else {
 4036:                                             if (grep/^$sec$/,@sections) {
 4037:                                                 return 'ok';
 4038:                                             }
 4039:                                         }
 4040:                                     }
 4041:                                 }
 4042:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4043:                                     if (grep/^none$/,@groups) {
 4044:                                         return 'ok';
 4045:                                     }
 4046:                                 } else {
 4047:                                     if (grep/^all$/,@groups) {
 4048:                                         return 'ok';
 4049:                                     } 
 4050:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4051:                                         if (grep/^$group$/,@groups) {
 4052:                                             return 'ok';
 4053:                                         }
 4054:                                     }
 4055:                                 } 
 4056:                             }
 4057:                         }
 4058:                     }
 4059:                 }
 4060:             }
 4061:             if ($guest) {
 4062:                 return $guest;
 4063:             }
 4064:         }
 4065:     }
 4066:     return;
 4067: }
 4068: 
 4069: sub course_group_datechecker {
 4070:     my ($dates,$now,$status) = @_;
 4071:     my ($start,$end) = split(/\./,$dates);
 4072:     if (!$start && !$end) {
 4073:         return 'ok';
 4074:     }
 4075:     if (grep/^active$/,@{$status}) {
 4076:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4077:             return 'ok';
 4078:         }
 4079:     }
 4080:     if (grep/^previous$/,@{$status}) {
 4081:         if ($end > $now ) {
 4082:             return 'ok';
 4083:         }
 4084:     }
 4085:     if (grep/^future$/,@{$status}) {
 4086:         if ($start > $now) {
 4087:             return 'ok';
 4088:         }
 4089:     }
 4090:     return; 
 4091: }
 4092: 
 4093: sub parse_portfolio_url {
 4094:     my ($url) = @_;
 4095: 
 4096:     my ($type,$udom,$unum,$group,$file_name);
 4097:     
 4098:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4099: 	$type = 1;
 4100:         $udom = $1;
 4101:         $unum = $2;
 4102:         $file_name = $3;
 4103:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4104: 	$type = 2;
 4105:         $udom = $1;
 4106:         $unum = $2;
 4107:         $group = $3;
 4108:         $file_name = $3.'/'.$4;
 4109:     }
 4110:     if (wantarray) {
 4111: 	return ($type,$udom,$unum,$file_name,$group);
 4112:     }
 4113:     return $type;
 4114: }
 4115: 
 4116: sub is_portfolio_url {
 4117:     my ($url) = @_;
 4118:     return scalar(&parse_portfolio_url($url));
 4119: }
 4120: 
 4121: sub is_portfolio_file {
 4122:     my ($file) = @_;
 4123:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4124:         return 1;
 4125:     }
 4126:     return;
 4127: }
 4128: 
 4129: 
 4130: # ---------------------------------------------- Custom access rule evaluation
 4131: 
 4132: sub customaccess {
 4133:     my ($priv,$uri)=@_;
 4134:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4135:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4136:     $udom = &LONCAPA::clean_domain($udom);
 4137:     $ucrs = &LONCAPA::clean_username($ucrs);
 4138:     my $access=0;
 4139:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4140: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4141: 	if ($type eq 'user') {
 4142: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4143: 		my ($tdom,$tuname)=split(m{/},$scope);
 4144: 		if ($tdom) {
 4145: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4146: 		}
 4147: 		if ($tuname) {
 4148: 		    if ($tuname ne $env{'user.name'}) { next; }
 4149: 		}
 4150: 		$access=($effect eq 'allow');
 4151: 		last;
 4152: 	    }
 4153: 	} else {
 4154: 	    if ($role) {
 4155: 		if ($role ne $urole) { next; }
 4156: 	    }
 4157: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4158: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4159: 		if ($tdom) {
 4160: 		    if ($tdom ne $udom) { next; }
 4161: 		}
 4162: 		if ($tcrs) {
 4163: 		    if ($tcrs ne $ucrs) { next; }
 4164: 		}
 4165: 		if ($tsec) {
 4166: 		    if ($tsec ne $usec) { next; }
 4167: 		}
 4168: 		$access=($effect eq 'allow');
 4169: 		last;
 4170: 	    }
 4171: 	    if ($realm eq '' && $role eq '') {
 4172: 		$access=($effect eq 'allow');
 4173: 	    }
 4174: 	}
 4175:     }
 4176:     return $access;
 4177: }
 4178: 
 4179: # ------------------------------------------------- Check for a user privilege
 4180: 
 4181: sub allowed {
 4182:     my ($priv,$uri,$symb,$role)=@_;
 4183:     my $ver_orguri=$uri;
 4184:     $uri=&deversion($uri);
 4185:     my $orguri=$uri;
 4186:     $uri=&declutter($uri);
 4187: 
 4188:     if ($priv eq 'evb') {
 4189: # Evade communication block restrictions for specified role in a course
 4190:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4191:             return $1;
 4192:         } else {
 4193:             return;
 4194:         }
 4195:     }
 4196: 
 4197:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4198: # Free bre access to adm and meta resources
 4199:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4200: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4201: 	&& ($priv eq 'bre')) {
 4202: 	return 'F';
 4203:     }
 4204: 
 4205: # Free bre access to user's own portfolio contents
 4206:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4207:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4208: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4209:         my %setters;
 4210:         my ($startblock,$endblock) = 
 4211:             &Apache::loncommon::blockcheck(\%setters,'port');
 4212:         if ($startblock && $endblock) {
 4213:             return 'B';
 4214:         } else {
 4215:             return 'F';
 4216:         }
 4217:     }
 4218: 
 4219: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4220:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4221:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4222:         if (exists($env{'request.course.id'})) {
 4223:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4224:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4225:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4226:                 my $courseprivid=$env{'request.course.id'};
 4227:                 $courseprivid=~s/\_/\//;
 4228:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4229:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4230:                     return $1; 
 4231:                 } else {
 4232:                     if ($env{'request.course.sec'}) {
 4233:                         $courseprivid.='/'.$env{'request.course.sec'};
 4234:                     }
 4235:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4236:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4237:                         return $2;
 4238:                     }
 4239:                 }
 4240:             }
 4241:         }
 4242:     }
 4243: 
 4244: # Free bre to public access
 4245: 
 4246:     if ($priv eq 'bre') {
 4247:         my $copyright=&metadata($uri,'copyright');
 4248: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4249:            return 'F'; 
 4250:         }
 4251:         if ($copyright eq 'priv') {
 4252:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4253: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4254: 		return '';
 4255:             }
 4256:         }
 4257:         if ($copyright eq 'domain') {
 4258:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4259: 	    unless (($env{'user.domain'} eq $1) ||
 4260:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4261: 		return '';
 4262:             }
 4263:         }
 4264:         if ($env{'request.role'}=~ /li\.\//) {
 4265:             # Library role, so allow browsing of resources in this domain.
 4266:             return 'F';
 4267:         }
 4268:         if ($copyright eq 'custom') {
 4269: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4270:         }
 4271:     }
 4272:     # Domain coordinator is trying to create a course
 4273:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4274:         # uri is the requested domain in this case.
 4275:         # comparison to 'request.role.domain' shows if the user has selected
 4276:         # a role of dc for the domain in question.
 4277:         return 'F' if ($uri eq $env{'request.role.domain'});
 4278:     }
 4279: 
 4280:     my $thisallowed='';
 4281:     my $statecond=0;
 4282:     my $courseprivid='';
 4283: 
 4284: # Course
 4285: 
 4286:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4287:        $thisallowed.=$1;
 4288:     }
 4289: 
 4290: # Domain
 4291: 
 4292:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4293:        =~/\Q$priv\E\&([^\:]*)/) {
 4294:        $thisallowed.=$1;
 4295:     }
 4296: 
 4297: # Course: uri itself is a course
 4298:     my $courseuri=$uri;
 4299:     $courseuri=~s/\_(\d)/\/$1/;
 4300:     $courseuri=~s/^([^\/])/\/$1/;
 4301: 
 4302:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4303:        =~/\Q$priv\E\&([^\:]*)/) {
 4304:        $thisallowed.=$1;
 4305:     }
 4306: 
 4307: # URI is an uploaded document for this course, default permissions don't matter
 4308: # not allowing 'edit' access (editupload) to uploaded course docs
 4309:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4310: 	$thisallowed='';
 4311:         my ($match)=&is_on_map($uri);
 4312:         if ($match) {
 4313:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4314:                   =~/\Q$priv\E\&([^\:]*)/) {
 4315:                 $thisallowed.=$1;
 4316:             }
 4317:         } else {
 4318:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4319:             if ($refuri) {
 4320:                 if ($refuri =~ m|^/adm/|) {
 4321:                     $thisallowed='F';
 4322:                 } else {
 4323:                     $refuri=&declutter($refuri);
 4324:                     my ($match) = &is_on_map($refuri);
 4325:                     if ($match) {
 4326:                         $thisallowed='F';
 4327:                     }
 4328:                 }
 4329:             }
 4330:         }
 4331:     }
 4332: 
 4333:     if ($priv eq 'bre'
 4334: 	&& $thisallowed ne 'F' 
 4335: 	&& $thisallowed ne '2'
 4336: 	&& &is_portfolio_url($uri)) {
 4337: 	$thisallowed = &portfolio_access($uri);
 4338:     }
 4339:     
 4340: # Full access at system, domain or course-wide level? Exit.
 4341: 
 4342:     if ($thisallowed=~/F/) {
 4343: 	return 'F';
 4344:     }
 4345: 
 4346: # If this is generating or modifying users, exit with special codes
 4347: 
 4348:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4349: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4350: 	    my ($audom,$auname)=split('/',$uri);
 4351: # no author name given, so this just checks on the general right to make a co-author in this domain
 4352: 	    unless ($auname) { return $thisallowed; }
 4353: # an author name is given, so we are about to actually make a co-author for a certain account
 4354: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4355: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4356: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4357: 	}
 4358: 	return $thisallowed;
 4359:     }
 4360: #
 4361: # Gathered so far: system, domain and course wide privileges
 4362: #
 4363: # Course: See if uri or referer is an individual resource that is part of 
 4364: # the course
 4365: 
 4366:     if ($env{'request.course.id'}) {
 4367: 
 4368:        $courseprivid=$env{'request.course.id'};
 4369:        if ($env{'request.course.sec'}) {
 4370:           $courseprivid.='/'.$env{'request.course.sec'};
 4371:        }
 4372:        $courseprivid=~s/\_/\//;
 4373:        my $checkreferer=1;
 4374:        my ($match,$cond)=&is_on_map($uri);
 4375:        if ($match) {
 4376:            $statecond=$cond;
 4377:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4378:                =~/\Q$priv\E\&([^\:]*)/) {
 4379:                $thisallowed.=$1;
 4380:                $checkreferer=0;
 4381:            }
 4382:        }
 4383:        
 4384:        if ($checkreferer) {
 4385: 	  my $refuri=$env{'httpref.'.$orguri};
 4386:             unless ($refuri) {
 4387:                 foreach my $key (keys(%env)) {
 4388: 		    if ($key=~/^httpref\..*\*/) {
 4389: 			my $pattern=$key;
 4390:                         $pattern=~s/^httpref\.\/res\///;
 4391:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4392:                         $pattern=~s/\//\\\//g;
 4393:                         if ($orguri=~/$pattern/) {
 4394: 			    $refuri=$env{$key};
 4395:                         }
 4396:                     }
 4397:                 }
 4398:             }
 4399: 
 4400:          if ($refuri) { 
 4401: 	  $refuri=&declutter($refuri);
 4402:           my ($match,$cond)=&is_on_map($refuri);
 4403:             if ($match) {
 4404:               my $refstatecond=$cond;
 4405:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4406:                   =~/\Q$priv\E\&([^\:]*)/) {
 4407:                   $thisallowed.=$1;
 4408:                   $uri=$refuri;
 4409:                   $statecond=$refstatecond;
 4410:               }
 4411:           }
 4412:         }
 4413:        }
 4414:    }
 4415: 
 4416: #
 4417: # Gathered now: all privileges that could apply, and condition number
 4418: # 
 4419: #
 4420: # Full or no access?
 4421: #
 4422: 
 4423:     if ($thisallowed=~/F/) {
 4424: 	return 'F';
 4425:     }
 4426: 
 4427:     unless ($thisallowed) {
 4428:         return '';
 4429:     }
 4430: 
 4431: # Restrictions exist, deal with them
 4432: #
 4433: #   C:according to course preferences
 4434: #   R:according to resource settings
 4435: #   L:unless locked
 4436: #   X:according to user session state
 4437: #
 4438: 
 4439: # Possibly locked functionality, check all courses
 4440: # Locks might take effect only after 10 minutes cache expiration for other
 4441: # courses, and 2 minutes for current course
 4442: 
 4443:     my $envkey;
 4444:     if ($thisallowed=~/L/) {
 4445:         foreach $envkey (keys %env) {
 4446:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4447:                my $courseid=$2;
 4448:                my $roleid=$1.'.'.$2;
 4449:                $courseid=~s/^\///;
 4450:                my $expiretime=600;
 4451:                if ($env{'request.role'} eq $roleid) {
 4452: 		  $expiretime=120;
 4453:                }
 4454: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4455:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4456:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4457: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4458:                }
 4459:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4460:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4461: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4462:                        &log($env{'user.domain'},$env{'user.name'},
 4463:                             $env{'user.home'},
 4464:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4465:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4466:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4467: 		       return '';
 4468:                    }
 4469:                }
 4470:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4471:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4472: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4473:                        &log($env{'user.domain'},$env{'user.name'},
 4474:                             $env{'user.home'},
 4475:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4476:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4477:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4478: 		       return '';
 4479:                    }
 4480:                }
 4481: 	   }
 4482:        }
 4483:     }
 4484:    
 4485: #
 4486: # Rest of the restrictions depend on selected course
 4487: #
 4488: 
 4489:     unless ($env{'request.course.id'}) {
 4490: 	if ($thisallowed eq 'A') {
 4491: 	    return 'A';
 4492:         } elsif ($thisallowed eq 'B') {
 4493:             return 'B';
 4494: 	} else {
 4495: 	    return '1';
 4496: 	}
 4497:     }
 4498: 
 4499: #
 4500: # Now user is definitely in a course
 4501: #
 4502: 
 4503: 
 4504: # Course preferences
 4505: 
 4506:    if ($thisallowed=~/C/) {
 4507:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4508:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4509:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4510: 	   =~/\Q$rolecode\E/) {
 4511: 	   if ($priv ne 'pch') { 
 4512: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4513: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4514: 			$env{'request.course.id'});
 4515: 	   }
 4516:            return '';
 4517:        }
 4518: 
 4519:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4520: 	   =~/\Q$unamedom\E/) {
 4521: 	   if ($priv ne 'pch') { 
 4522: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4523: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4524: 			$env{'request.course.id'});
 4525: 	   }
 4526:            return '';
 4527:        }
 4528:    }
 4529: 
 4530: # Resource preferences
 4531: 
 4532:    if ($thisallowed=~/R/) {
 4533:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4534:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4535: 	   if ($priv ne 'pch') { 
 4536: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4537: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4538: 	   }
 4539: 	   return '';
 4540:        }
 4541:    }
 4542: 
 4543: # Restricted by state or randomout?
 4544: 
 4545:    if ($thisallowed=~/X/) {
 4546:       if ($env{'acc.randomout'}) {
 4547: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4548:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4549:             return ''; 
 4550:          }
 4551:       }
 4552:       if (&condval($statecond)) {
 4553: 	 return '2';
 4554:       } else {
 4555:          return '';
 4556:       }
 4557:    }
 4558: 
 4559:     if ($thisallowed eq 'A') {
 4560: 	return 'A';
 4561:     } elsif ($thisallowed eq 'B') {
 4562:         return 'B';
 4563:     }
 4564:    return 'F';
 4565: }
 4566: 
 4567: sub split_uri_for_cond {
 4568:     my $uri=&deversion(&declutter(shift));
 4569:     my @uriparts=split(/\//,$uri);
 4570:     my $filename=pop(@uriparts);
 4571:     my $pathname=join('/',@uriparts);
 4572:     return ($pathname,$filename);
 4573: }
 4574: # --------------------------------------------------- Is a resource on the map?
 4575: 
 4576: sub is_on_map {
 4577:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4578:     #Trying to find the conditional for the file
 4579:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4580: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4581:     if ($match) {
 4582: 	return (1,$1);
 4583:     } else {
 4584: 	return (0,0);
 4585:     }
 4586: }
 4587: 
 4588: # --------------------------------------------------------- Get symb from alias
 4589: 
 4590: sub get_symb_from_alias {
 4591:     my $symb=shift;
 4592:     my ($map,$resid,$url)=&decode_symb($symb);
 4593: # Already is a symb
 4594:     if ($url) { return $symb; }
 4595: # Must be an alias
 4596:     my $aliassymb='';
 4597:     my %bighash;
 4598:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4599:                             &GDBM_READER(),0640)) {
 4600:         my $rid=$bighash{'mapalias_'.$symb};
 4601: 	if ($rid) {
 4602: 	    my ($mapid,$resid)=split(/\./,$rid);
 4603: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4604: 				    $resid,$bighash{'src_'.$rid});
 4605: 	}
 4606:         untie %bighash;
 4607:     }
 4608:     return $aliassymb;
 4609: }
 4610: 
 4611: # ----------------------------------------------------------------- Define Role
 4612: 
 4613: sub definerole {
 4614:   if (allowed('mcr','/')) {
 4615:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4616:     foreach my $role (split(':',$sysrole)) {
 4617: 	my ($crole,$cqual)=split(/\&/,$role);
 4618:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4619:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4620: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4621:                return "refused:s:$crole&$cqual"; 
 4622:             }
 4623:         }
 4624:     }
 4625:     foreach my $role (split(':',$domrole)) {
 4626: 	my ($crole,$cqual)=split(/\&/,$role);
 4627:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4628:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4629: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4630:                return "refused:d:$crole&$cqual"; 
 4631:             }
 4632:         }
 4633:     }
 4634:     foreach my $role (split(':',$courole)) {
 4635: 	my ($crole,$cqual)=split(/\&/,$role);
 4636:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4637:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4638: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4639:                return "refused:c:$crole&$cqual"; 
 4640:             }
 4641:         }
 4642:     }
 4643:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4644:                 "$env{'user.domain'}:$env{'user.name'}:".
 4645: 	        "rolesdef_$rolename=".
 4646:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4647:     return reply($command,$env{'user.home'});
 4648:   } else {
 4649:     return 'refused';
 4650:   }
 4651: }
 4652: 
 4653: # ---------------- Make a metadata query against the network of library servers
 4654: 
 4655: sub metadata_query {
 4656:     my ($query,$custom,$customshow,$server_array)=@_;
 4657:     my %rhash;
 4658:     my %libserv = &all_library();
 4659:     my @server_list = (defined($server_array) ? @$server_array
 4660:                                               : keys(%libserv) );
 4661:     for my $server (@server_list) {
 4662: 	unless ($custom or $customshow) {
 4663: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4664: 	    $rhash{$server}=$reply;
 4665: 	}
 4666: 	else {
 4667: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4668: 			     &escape($custom).':'.&escape($customshow),
 4669: 			     $server);
 4670: 	    $rhash{$server}=$reply;
 4671: 	}
 4672:     }
 4673:     return \%rhash;
 4674: }
 4675: 
 4676: # ----------------------------------------- Send log queries and wait for reply
 4677: 
 4678: sub log_query {
 4679:     my ($uname,$udom,$query,%filters)=@_;
 4680:     my $uhome=&homeserver($uname,$udom);
 4681:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4682:     my $uhost=&hostname($uhome);
 4683:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4684:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4685:                        $uhome);
 4686:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4687:     return get_query_reply($queryid);
 4688: }
 4689: 
 4690: # -------------------------- Update MySQL table for portfolio file
 4691: 
 4692: sub update_portfolio_table {
 4693:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4694:     my $homeserver = &homeserver($uname,$udom);
 4695:     my $queryid=
 4696:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4697:                ':'.&escape($file_name).':'.$action,$homeserver);
 4698:     my $reply = &get_query_reply($queryid);
 4699:     return $reply;
 4700: }
 4701: 
 4702: # -------------------------- Update MySQL allusers table
 4703: 
 4704: sub update_allusers_table {
 4705:     my ($uname,$udom,$names) = @_;
 4706:     my $homeserver = &homeserver($uname,$udom);
 4707:     my $queryid=
 4708:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4709:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4710:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4711:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4712:                'generation='.&escape($names->{'generation'}).'%%'.
 4713:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4714:                'id='.&escape($names->{'id'}),$homeserver);
 4715:     my $reply = &get_query_reply($queryid);
 4716:     return $reply;
 4717: }
 4718: 
 4719: # ------- Request retrieval of institutional classlists for course(s)
 4720: 
 4721: sub fetch_enrollment_query {
 4722:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4723:     my $homeserver;
 4724:     my $maxtries = 1;
 4725:     if ($context eq 'automated') {
 4726:         $homeserver = $perlvar{'lonHostID'};
 4727:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4728:     } else {
 4729:         $homeserver = &homeserver($cnum,$dom);
 4730:     }
 4731:     my $host=&hostname($homeserver);
 4732:     my $cmd = '';
 4733:     foreach my $affiliate (keys %{$affiliatesref}) {
 4734:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4735:     }
 4736:     $cmd =~ s/%%$//;
 4737:     $cmd = &escape($cmd);
 4738:     my $query = 'fetchenrollment';
 4739:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4740:     unless ($queryid=~/^\Q$host\E\_/) { 
 4741:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4742:         return 'error: '.$queryid;
 4743:     }
 4744:     my $reply = &get_query_reply($queryid);
 4745:     my $tries = 1;
 4746:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4747:         $reply = &get_query_reply($queryid);
 4748:         $tries ++;
 4749:     }
 4750:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4751:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4752:     } else {
 4753:         my @responses = split(/:/,$reply);
 4754:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4755:             foreach my $line (@responses) {
 4756:                 my ($key,$value) = split(/=/,$line,2);
 4757:                 $$replyref{$key} = $value;
 4758:             }
 4759:         } else {
 4760:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4761:             foreach my $line (@responses) {
 4762:                 my ($key,$value) = split(/=/,$line);
 4763:                 $$replyref{$key} = $value;
 4764:                 if ($value > 0) {
 4765:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4766:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4767:                         my $destname = $pathname.'/'.$filename;
 4768:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4769:                         if ($xml_classlist =~ /^error/) {
 4770:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4771:                         } else {
 4772:                             if ( open(FILE,">$destname") ) {
 4773:                                 print FILE &unescape($xml_classlist);
 4774:                                 close(FILE);
 4775:                             } else {
 4776:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4777:                             }
 4778:                         }
 4779:                     }
 4780:                 }
 4781:             }
 4782:         }
 4783:         return 'ok';
 4784:     }
 4785:     return 'error';
 4786: }
 4787: 
 4788: sub get_query_reply {
 4789:     my $queryid=shift;
 4790:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4791:     my $reply='';
 4792:     for (1..100) {
 4793: 	sleep 2;
 4794:         if (-e $replyfile.'.end') {
 4795: 	    if (open(my $fh,$replyfile)) {
 4796: 		$reply = join('',<$fh>);
 4797: 		close($fh);
 4798: 	   } else { return 'error: reply_file_error'; }
 4799:            return &unescape($reply);
 4800: 	}
 4801:     }
 4802:     return 'timeout:'.$queryid;
 4803: }
 4804: 
 4805: sub courselog_query {
 4806: #
 4807: # possible filters:
 4808: # url: url or symb
 4809: # username
 4810: # domain
 4811: # action: view, submit, grade
 4812: # start: timestamp
 4813: # end: timestamp
 4814: #
 4815:     my (%filters)=@_;
 4816:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4817:     if ($filters{'url'}) {
 4818: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4819:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4820:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4821:     }
 4822:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4823:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4824:     return &log_query($cname,$cdom,'courselog',%filters);
 4825: }
 4826: 
 4827: sub userlog_query {
 4828: #
 4829: # possible filters:
 4830: # action: log check role
 4831: # start: timestamp
 4832: # end: timestamp
 4833: #
 4834:     my ($uname,$udom,%filters)=@_;
 4835:     return &log_query($uname,$udom,'userlog',%filters);
 4836: }
 4837: 
 4838: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4839: 
 4840: sub auto_run {
 4841:     my ($cnum,$cdom) = @_;
 4842:     my $response = 0;
 4843:     my $settings;
 4844:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4845:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4846:         $settings = $domconfig{'autoenroll'};
 4847:         if ($settings->{'run'} eq '1') {
 4848:             $response = 1;
 4849:         }
 4850:     } else {
 4851:         my $homeserver;
 4852:         if (&is_course($cdom,$cnum)) {
 4853:             $homeserver = &homeserver($cnum,$cdom);
 4854:         } else {
 4855:             $homeserver = &domain($cdom,'primary');
 4856:         }
 4857:         if ($homeserver ne 'no_host') {
 4858:             $response = &reply('autorun:'.$cdom,$homeserver);
 4859:         }
 4860:     }
 4861:     return $response;
 4862: }
 4863: 
 4864: sub auto_get_sections {
 4865:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4866:     my $homeserver = &homeserver($cnum,$cdom);
 4867:     my @secs = ();
 4868:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4869:     unless ($response eq 'refused') {
 4870:         @secs = split(/:/,$response);
 4871:     }
 4872:     return @secs;
 4873: }
 4874: 
 4875: sub auto_new_course {
 4876:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4877:     my $homeserver = &homeserver($cnum,$cdom);
 4878:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4879:     return $response;
 4880: }
 4881: 
 4882: sub auto_validate_courseID {
 4883:     my ($cnum,$cdom,$inst_course_id) = @_;
 4884:     my $homeserver = &homeserver($cnum,$cdom);
 4885:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4886:     return $response;
 4887: }
 4888: 
 4889: sub auto_create_password {
 4890:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4891:     my ($homeserver,$response);
 4892:     my $create_passwd = 0;
 4893:     my $authchk = '';
 4894:     if ($udom =~ /^$match_domain$/) {
 4895:         $homeserver = &domain($udom,'primary');
 4896:     }
 4897:     if ($homeserver eq '') {
 4898:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4899:             $homeserver = &homeserver($cnum,$cdom);
 4900:         }
 4901:     }
 4902:     if ($homeserver eq '') {
 4903:         $authchk = 'nodomain';
 4904:     } else {
 4905:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4906:         if ($response eq 'refused') {
 4907:             $authchk = 'refused';
 4908:         } else {
 4909:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 4910:         }
 4911:     }
 4912:     return ($authparam,$create_passwd,$authchk);
 4913: }
 4914: 
 4915: sub auto_photo_permission {
 4916:     my ($cnum,$cdom,$students) = @_;
 4917:     my $homeserver = &homeserver($cnum,$cdom);
 4918:     my ($outcome,$perm_reqd,$conditions) = 
 4919: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4920:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4921: 	return (undef,undef);
 4922:     }
 4923:     return ($outcome,$perm_reqd,$conditions);
 4924: }
 4925: 
 4926: sub auto_checkphotos {
 4927:     my ($uname,$udom,$pid) = @_;
 4928:     my $homeserver = &homeserver($uname,$udom);
 4929:     my ($result,$resulttype);
 4930:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4931: 				   &escape($uname).':'.&escape($pid),
 4932: 				   $homeserver));
 4933:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4934: 	return (undef,undef);
 4935:     }
 4936:     if ($outcome) {
 4937:         ($result,$resulttype) = split(/:/,$outcome);
 4938:     } 
 4939:     return ($result,$resulttype);
 4940: }
 4941: 
 4942: sub auto_photochoice {
 4943:     my ($cnum,$cdom) = @_;
 4944:     my $homeserver = &homeserver($cnum,$cdom);
 4945:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4946: 						       &escape($cdom),
 4947: 						       $homeserver)));
 4948:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4949: 	return (undef,undef);
 4950:     }
 4951:     return ($update,$comment);
 4952: }
 4953: 
 4954: sub auto_photoupdate {
 4955:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4956:     my $homeserver = &homeserver($cnum,$dom);
 4957:     my $host=&hostname($homeserver);
 4958:     my $cmd = '';
 4959:     my $maxtries = 1;
 4960:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4961:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4962:     }
 4963:     $cmd =~ s/%%$//;
 4964:     $cmd = &escape($cmd);
 4965:     my $query = 'institutionalphotos';
 4966:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4967:     unless ($queryid=~/^\Q$host\E\_/) {
 4968:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4969:         return 'error: '.$queryid;
 4970:     }
 4971:     my $reply = &get_query_reply($queryid);
 4972:     my $tries = 1;
 4973:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4974:         $reply = &get_query_reply($queryid);
 4975:         $tries ++;
 4976:     }
 4977:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4978:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4979:     } else {
 4980:         my @responses = split(/:/,$reply);
 4981:         my $outcome = shift(@responses); 
 4982:         foreach my $item (@responses) {
 4983:             my ($key,$value) = split(/=/,$item);
 4984:             $$photo{$key} = $value;
 4985:         }
 4986:         return $outcome;
 4987:     }
 4988:     return 'error';
 4989: }
 4990: 
 4991: sub auto_instcode_format {
 4992:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4993: 	$cat_order) = @_;
 4994:     my $courses = '';
 4995:     my @homeservers;
 4996:     if ($caller eq 'global') {
 4997: 	my %servers = &get_servers($codedom,'library');
 4998: 	foreach my $tryserver (keys(%servers)) {
 4999: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5000: 		push(@homeservers,$tryserver);
 5001: 	    }
 5002:         }
 5003:     } else {
 5004:         push(@homeservers,&homeserver($caller,$codedom));
 5005:     }
 5006:     foreach my $code (keys(%{$instcodes})) {
 5007:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5008:     }
 5009:     chop($courses);
 5010:     my $ok_response = 0;
 5011:     my $response;
 5012:     while (@homeservers > 0 && $ok_response == 0) {
 5013:         my $server = shift(@homeservers); 
 5014:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5015:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5016:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5017: 		split(/:/,$response);
 5018:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5019:             push(@{$codetitles},&str2array($codetitles_str));
 5020:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5021:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5022:             $ok_response = 1;
 5023:         }
 5024:     }
 5025:     if ($ok_response) {
 5026:         return 'ok';
 5027:     } else {
 5028:         return $response;
 5029:     }
 5030: }
 5031: 
 5032: sub auto_instcode_defaults {
 5033:     my ($domain,$returnhash,$code_order) = @_;
 5034:     my @homeservers;
 5035: 
 5036:     my %servers = &get_servers($domain,'library');
 5037:     foreach my $tryserver (keys(%servers)) {
 5038: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5039: 	    push(@homeservers,$tryserver);
 5040: 	}
 5041:     }
 5042: 
 5043:     my $response;
 5044:     foreach my $server (@homeservers) {
 5045:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5046:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5047: 	
 5048: 	foreach my $pair (split(/\&/,$response)) {
 5049: 	    my ($name,$value)=split(/\=/,$pair);
 5050: 	    if ($name eq 'code_order') {
 5051: 		@{$code_order} = split(/\&/,&unescape($value));
 5052: 	    } else {
 5053: 		$returnhash->{&unescape($name)}=&unescape($value);
 5054: 	    }
 5055: 	}
 5056: 	return 'ok';
 5057:     }
 5058: 
 5059:     return $response;
 5060: } 
 5061: 
 5062: sub auto_validate_class_sec {
 5063:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5064:     my $homeserver = &homeserver($cnum,$cdom);
 5065:     my $ownerlist;
 5066:     if (ref($owners) eq 'ARRAY') {
 5067:         $ownerlist = join(',',@{$owners});
 5068:     } else {
 5069:         $ownerlist = $owners;
 5070:     }
 5071:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5072:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5073:     return $response;
 5074: }
 5075: 
 5076: # ------------------------------------------------------- Course Group routines
 5077: 
 5078: sub get_coursegroups {
 5079:     my ($cdom,$cnum,$group,$namespace) = @_;
 5080:     return(&dump($namespace,$cdom,$cnum,$group));
 5081: }
 5082: 
 5083: sub modify_coursegroup {
 5084:     my ($cdom,$cnum,$groupsettings) = @_;
 5085:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5086: }
 5087: 
 5088: sub toggle_coursegroup_status {
 5089:     my ($cdom,$cnum,$group,$action) = @_;
 5090:     my ($from_namespace,$to_namespace);
 5091:     if ($action eq 'delete') {
 5092:         $from_namespace = 'coursegroups';
 5093:         $to_namespace = 'deleted_groups';
 5094:     } else {
 5095:         $from_namespace = 'deleted_groups';
 5096:         $to_namespace = 'coursegroups';
 5097:     }
 5098:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5099:     if (my $tmp = &error(%curr_group)) {
 5100:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5101:         return ('read error',$tmp);
 5102:     } else {
 5103:         my %savedsettings = %curr_group; 
 5104:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5105:         my $deloutcome;
 5106:         if ($result eq 'ok') {
 5107:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5108:         } else {
 5109:             return ('write error',$result);
 5110:         }
 5111:         if ($deloutcome eq 'ok') {
 5112:             return 'ok';
 5113:         } else {
 5114:             return ('delete error',$deloutcome);
 5115:         }
 5116:     }
 5117: }
 5118: 
 5119: sub modify_group_roles {
 5120:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5121:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5122:     my $role = 'gr/'.&escape($userprivs);
 5123:     my ($uname,$udom) = split(/:/,$user);
 5124:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5125:     if ($result eq 'ok') {
 5126:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5127:     }
 5128:     return $result;
 5129: }
 5130: 
 5131: sub modify_coursegroup_membership {
 5132:     my ($cdom,$cnum,$membership) = @_;
 5133:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5134:     return $result;
 5135: }
 5136: 
 5137: sub get_active_groups {
 5138:     my ($udom,$uname,$cdom,$cnum) = @_;
 5139:     my $now = time;
 5140:     my %groups = ();
 5141:     foreach my $key (keys(%env)) {
 5142:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5143:             my ($start,$end) = split(/\./,$env{$key});
 5144:             if (($end!=0) && ($end<$now)) { next; }
 5145:             if (($start!=0) && ($start>$now)) { next; }
 5146:             if ($1 eq $cdom && $2 eq $cnum) {
 5147:                 $groups{$3} = $env{$key} ;
 5148:             }
 5149:         }
 5150:     }
 5151:     return %groups;
 5152: }
 5153: 
 5154: sub get_group_membership {
 5155:     my ($cdom,$cnum,$group) = @_;
 5156:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5157: }
 5158: 
 5159: sub get_users_groups {
 5160:     my ($udom,$uname,$courseid) = @_;
 5161:     my @usersgroups;
 5162:     my $cachetime=1800;
 5163: 
 5164:     my $hashid="$udom:$uname:$courseid";
 5165:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5166:     if (defined($cached)) {
 5167:         @usersgroups = split(/:/,$grouplist);
 5168:     } else {  
 5169:         $grouplist = '';
 5170:         my $courseurl = &courseid_to_courseurl($courseid);
 5171:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5172:         my $access_end = $env{'course.'.$courseid.
 5173:                               '.default_enrollment_end_date'};
 5174:         my $now = time;
 5175:         foreach my $key (keys(%roleshash)) {
 5176:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5177:                 my $group = $1;
 5178:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5179:                     my $start = $2;
 5180:                     my $end = $1;
 5181:                     if ($start == -1) { next; } # deleted from group
 5182:                     if (($start!=0) && ($start>$now)) { next; }
 5183:                     if (($end!=0) && ($end<$now)) {
 5184:                         if ($access_end && $access_end < $now) {
 5185:                             if ($access_end - $end < 86400) {
 5186:                                 push(@usersgroups,$group);
 5187:                             }
 5188:                         }
 5189:                         next;
 5190:                     }
 5191:                     push(@usersgroups,$group);
 5192:                 }
 5193:             }
 5194:         }
 5195:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5196:         $grouplist = join(':',@usersgroups);
 5197:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5198:     }
 5199:     return @usersgroups;
 5200: }
 5201: 
 5202: sub devalidate_getgroups_cache {
 5203:     my ($udom,$uname,$cdom,$cnum)=@_;
 5204:     my $courseid = $cdom.'_'.$cnum;
 5205: 
 5206:     my $hashid="$udom:$uname:$courseid";
 5207:     &devalidate_cache_new('getgroups',$hashid);
 5208: }
 5209: 
 5210: # ------------------------------------------------------------------ Plain Text
 5211: 
 5212: sub plaintext {
 5213:     my ($short,$type,$cid) = @_;
 5214:     if ($short =~ /^cr/) {
 5215: 	return (split('/',$short))[-1];
 5216:     }
 5217:     if (!defined($cid)) {
 5218:         $cid = $env{'request.course.id'};
 5219:     }
 5220:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5221:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5222:                                           '.plaintext'});
 5223:     }
 5224:     my %rolenames = (
 5225:                       Course => 'std',
 5226:                       Group => 'alt1',
 5227:                     );
 5228:     if (defined($type) && 
 5229:          defined($rolenames{$type}) && 
 5230:          defined($prp{$short}{$rolenames{$type}})) {
 5231:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5232:     } else {
 5233:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5234:     }
 5235: }
 5236: 
 5237: # ----------------------------------------------------------------- Assign Role
 5238: 
 5239: sub assignrole {
 5240:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 5241:     my $mrole;
 5242:     if ($role =~ /^cr\//) {
 5243:         my $cwosec=$url;
 5244:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5245: 	unless (&allowed('ccr',$cwosec)) {
 5246:            &logthis('Refused custom assignrole: '.
 5247:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5248: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5249:            return 'refused'; 
 5250:         }
 5251:         $mrole='cr';
 5252:     } elsif ($role =~ /^gr\//) {
 5253:         my $cwogrp=$url;
 5254:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5255:         unless (&allowed('mdg',$cwogrp)) {
 5256:             &logthis('Refused group assignrole: '.
 5257:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5258:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5259:             return 'refused';
 5260:         }
 5261:         $mrole='gr';
 5262:     } else {
 5263:         my $cwosec=$url;
 5264:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5265:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5266:             my $refused;
 5267:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5268:                 if (!(&allowed('c'.$role,$url))) {
 5269:                     $refused = 1;
 5270:                 }
 5271:             } else {
 5272:                 $refused = 1;
 5273:             }
 5274:             if ($refused) { 
 5275:                 &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5276:                          ' '.$role.' '.$end.' '.$start.' by '.
 5277: 	  	         $env{'user.name'}.' at '.$env{'user.domain'});
 5278:                 return 'refused';
 5279:             }
 5280:         }
 5281:         $mrole=$role;
 5282:     }
 5283:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5284:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5285:     if ($end) { $command.='_'.$end; }
 5286:     if ($start) {
 5287: 	if ($end) { 
 5288:            $command.='_'.$start; 
 5289:         } else {
 5290:            $command.='_0_'.$start;
 5291:         }
 5292:     }
 5293:     my $origstart = $start;
 5294:     my $origend = $end;
 5295: # actually delete
 5296:     if ($deleteflag) {
 5297: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5298: # modify command to delete the role
 5299:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5300:                 "$udom:$uname:$url".'_'."$mrole";
 5301: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5302: # set start and finish to negative values for userrolelog
 5303:            $start=-1;
 5304:            $end=-1;
 5305:         }
 5306:     }
 5307: # send command
 5308:     my $answer=&reply($command,&homeserver($uname,$udom));
 5309: # log new user role if status is ok
 5310:     if ($answer eq 'ok') {
 5311: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5312: # for course roles, perform group memberships changes triggered by role change.
 5313:         unless ($role =~ /^gr/) {
 5314:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5315:                                              $origstart);
 5316:         }
 5317:     }
 5318:     return $answer;
 5319: }
 5320: 
 5321: # -------------------------------------------------- Modify user authentication
 5322: # Overrides without validation
 5323: 
 5324: sub modifyuserauth {
 5325:     my ($udom,$uname,$umode,$upass)=@_;
 5326:     my $uhome=&homeserver($uname,$udom);
 5327:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5328:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5329:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5330:              ' in domain '.$env{'request.role.domain'});  
 5331:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5332: 		     &escape($upass),$uhome);
 5333:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5334:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5335:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5336:     &log($udom,,$uname,$uhome,
 5337:         'Authentication changed by '.$env{'user.domain'}.', '.
 5338:                                      $env{'user.name'}.', '.$umode.
 5339:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5340:     unless ($reply eq 'ok') {
 5341:         &logthis('Authentication mode error: '.$reply);
 5342: 	return 'error: '.$reply;
 5343:     }   
 5344:     return 'ok';
 5345: }
 5346: 
 5347: # --------------------------------------------------------------- Modify a user
 5348: 
 5349: sub modifyuser {
 5350:     my ($udom,    $uname, $uid,
 5351:         $umode,   $upass, $first,
 5352:         $middle,  $last,  $gene,
 5353:         $forceid, $desiredhome, $email)=@_;
 5354:     $udom= &LONCAPA::clean_domain($udom);
 5355:     $uname=&LONCAPA::clean_username($uname);
 5356:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5357:              $umode.', '.$first.', '.$middle.', '.
 5358: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5359:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5360:                                      ' desiredhome not specified'). 
 5361:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5362:              ' in domain '.$env{'request.role.domain'});
 5363:     my $uhome=&homeserver($uname,$udom,'true');
 5364: # ----------------------------------------------------------------- Create User
 5365:     if (($uhome eq 'no_host') && 
 5366: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5367:         my $unhome='';
 5368:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5369:             $unhome = $desiredhome;
 5370: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5371: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5372:         } else { # load balancing routine for determining $unhome
 5373:             my $loadm=10000000;
 5374: 	    my %servers = &get_servers($udom,'library');
 5375: 	    foreach my $tryserver (keys(%servers)) {
 5376: 		my $answer=reply('load',$tryserver);
 5377: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5378: 		    $loadm=$answer;
 5379: 		    $unhome=$tryserver;
 5380: 		}
 5381: 	    }
 5382:         }
 5383:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5384: 	    return 'error: unable to find a home server for '.$uname.
 5385:                    ' in domain '.$udom;
 5386:         }
 5387:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5388:                          &escape($upass),$unhome);
 5389: 	unless ($reply eq 'ok') {
 5390:             return 'error: '.$reply;
 5391:         }   
 5392:         $uhome=&homeserver($uname,$udom,'true');
 5393:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5394: 	    return 'error: unable verify users home machine.';
 5395:         }
 5396:     }   # End of creation of new user
 5397: # ---------------------------------------------------------------------- Add ID
 5398:     if ($uid) {
 5399:        $uid=~tr/A-Z/a-z/;
 5400:        my %uidhash=&idrget($udom,$uname);
 5401:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5402:          && (!$forceid)) {
 5403: 	  unless ($uid eq $uidhash{$uname}) {
 5404: 	      return 'error: user id "'.$uid.'" does not match '.
 5405:                   'current user id "'.$uidhash{$uname}.'".';
 5406:           }
 5407:        } else {
 5408: 	  &idput($udom,($uname => $uid));
 5409:        }
 5410:     }
 5411: # -------------------------------------------------------------- Add names, etc
 5412:     my @tmp=&get('environment',
 5413: 		   ['firstname','middlename','lastname','generation','id',
 5414:                     'permanentemail'],
 5415: 		   $udom,$uname);
 5416:     my %names;
 5417:     if ($tmp[0] =~ m/^error:.*/) { 
 5418:         %names=(); 
 5419:     } else {
 5420:         %names = @tmp;
 5421:     }
 5422: #
 5423: # Make sure to not trash student environment if instructor does not bother
 5424: # to supply name and email information
 5425: #
 5426:     if ($first)  { $names{'firstname'}  = $first; }
 5427:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5428:     if ($last)   { $names{'lastname'}   = $last; }
 5429:     if (defined($gene))   { $names{'generation'} = $gene; }
 5430:     if ($email) {
 5431:        $email=~s/[^\w\@\.\-\,]//gs;
 5432:        if ($email=~/\@/) { $names{'notification'} = $email;
 5433: 			   $names{'critnotification'} = $email;
 5434: 			   $names{'permanentemail'} = $email; }
 5435:     }
 5436:     if ($uid) { $names{'id'}  = $uid; }
 5437:     my $reply = &put('environment', \%names, $udom,$uname);
 5438:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5439:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5440:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5441:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5442:              $umode.', '.$first.', '.$middle.', '.
 5443: 	     $last.', '.$gene.' by '.
 5444:              $env{'user.name'}.' at '.$env{'user.domain'});
 5445:     return 'ok';
 5446: }
 5447: 
 5448: # -------------------------------------------------------------- Modify student
 5449: 
 5450: sub modifystudent {
 5451:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5452:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5453:     if (!$cid) {
 5454: 	unless ($cid=$env{'request.course.id'}) {
 5455: 	    return 'not_in_class';
 5456: 	}
 5457:     }
 5458: # --------------------------------------------------------------- Make the user
 5459:     my $reply=&modifyuser
 5460: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5461:          $desiredhome,$email);
 5462:     unless ($reply eq 'ok') { return $reply; }
 5463:     # This will cause &modify_student_enrollment to get the uid from the
 5464:     # students environment
 5465:     $uid = undef if (!$forceid);
 5466:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5467: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5468:     return $reply;
 5469: }
 5470: 
 5471: sub modify_student_enrollment {
 5472:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5473:     my ($cdom,$cnum,$chome);
 5474:     if (!$cid) {
 5475: 	unless ($cid=$env{'request.course.id'}) {
 5476: 	    return 'not_in_class';
 5477: 	}
 5478: 	$cdom=$env{'course.'.$cid.'.domain'};
 5479: 	$cnum=$env{'course.'.$cid.'.num'};
 5480:     } else {
 5481: 	($cdom,$cnum)=split(/_/,$cid);
 5482:     }
 5483:     $chome=$env{'course.'.$cid.'.home'};
 5484:     if (!$chome) {
 5485: 	$chome=&homeserver($cnum,$cdom);
 5486:     }
 5487:     if (!$chome) { return 'unknown_course'; }
 5488:     # Make sure the user exists
 5489:     my $uhome=&homeserver($uname,$udom);
 5490:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5491: 	return 'error: no such user';
 5492:     }
 5493:     # Get student data if we were not given enough information
 5494:     if (!defined($first)  || $first  eq '' || 
 5495:         !defined($last)   || $last   eq '' || 
 5496:         !defined($uid)    || $uid    eq '' || 
 5497:         !defined($middle) || $middle eq '' || 
 5498:         !defined($gene)   || $gene   eq '') {
 5499:         # They did not supply us with enough data to enroll the student, so
 5500:         # we need to pick up more information.
 5501:         my %tmp = &get('environment',
 5502:                        ['firstname','middlename','lastname', 'generation','id']
 5503:                        ,$udom,$uname);
 5504: 
 5505:         #foreach my $key (keys(%tmp)) {
 5506:         #    &logthis("key $key = ".$tmp{$key});
 5507:         #}
 5508:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5509:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5510:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5511:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5512:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5513:     }
 5514:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5515:     my $reply=cput('classlist',
 5516: 		   {"$uname:$udom" => 
 5517: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5518: 		   $cdom,$cnum);
 5519:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5520: 	return 'error: '.$reply;
 5521:     } else {
 5522: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5523:     }
 5524:     # Add student role to user
 5525:     my $uurl='/'.$cid;
 5526:     $uurl=~s/\_/\//g;
 5527:     if ($usec) {
 5528: 	$uurl.='/'.$usec;
 5529:     }
 5530:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5531: }
 5532: 
 5533: sub format_name {
 5534:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5535:     my $name;
 5536:     if ($first ne 'lastname') {
 5537: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5538:     } else {
 5539: 	if ($lastname=~/\S/) {
 5540: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5541: 	    $name=~s/\s+,/,/;
 5542: 	} else {
 5543: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5544: 	}
 5545:     }
 5546:     $name=~s/^\s+//;
 5547:     $name=~s/\s+$//;
 5548:     $name=~s/\s+/ /g;
 5549:     return $name;
 5550: }
 5551: 
 5552: # ------------------------------------------------- Write to course preferences
 5553: 
 5554: sub writecoursepref {
 5555:     my ($courseid,%prefs)=@_;
 5556:     $courseid=~s/^\///;
 5557:     $courseid=~s/\_/\//g;
 5558:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5559:     my $chome=homeserver($cnum,$cdomain);
 5560:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5561: 	return 'error: no such course';
 5562:     }
 5563:     my $cstring='';
 5564:     foreach my $pref (keys(%prefs)) {
 5565: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5566:     }
 5567:     $cstring=~s/\&$//;
 5568:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5569: }
 5570: 
 5571: # ---------------------------------------------------------- Make/modify course
 5572: 
 5573: sub createcourse {
 5574:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5575:         $course_owner,$crstype)=@_;
 5576:     $url=&declutter($url);
 5577:     my $cid='';
 5578:     unless (&allowed('ccc',$udom)) {
 5579:         return 'refused';
 5580:     }
 5581: # ------------------------------------------------------------------- Create ID
 5582:    my $uname=int(1+rand(9)).
 5583:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5584:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5585:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5586: # ----------------------------------------------- Make sure that does not exist
 5587:    my $uhome=&homeserver($uname,$udom,'true');
 5588:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5589:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5590:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5591:        $uhome=&homeserver($uname,$udom,'true');       
 5592:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5593:            return 'error: unable to generate unique course-ID';
 5594:        } 
 5595:    }
 5596: # ------------------------------------------------ Check supplied server name
 5597:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5598:     if (! &is_library($course_server)) {
 5599:         return 'error:bad server name '.$course_server;
 5600:     }
 5601: # ------------------------------------------------------------- Make the course
 5602:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5603:                       $course_server);
 5604:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5605:     $uhome=&homeserver($uname,$udom,'true');
 5606:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5607: 	return 'error: no such course';
 5608:     }
 5609: # ----------------------------------------------------------------- Course made
 5610: # log existence
 5611:     my $newcourse = {
 5612:                     $udom.'_'.$uname => {
 5613:                                      description => $description,
 5614:                                      inst_code   => $inst_code,
 5615:                                      owner       => $course_owner,
 5616:                                      type        => $crstype,
 5617:                                                 },
 5618:                     };
 5619:     &courseidput($udom,$newcourse,$uhome,'notime');
 5620: # set toplevel url
 5621:     my $topurl=$url;
 5622:     unless ($nonstandard) {
 5623: # ------------------------------------------ For standard courses, make top url
 5624:         my $mapurl=&clutter($url);
 5625:         if ($mapurl eq '/res/') { $mapurl=''; }
 5626:         $env{'form.initmap'}=(<<ENDINITMAP);
 5627: <map>
 5628: <resource id="1" type="start"></resource>
 5629: <resource id="2" src="$mapurl"></resource>
 5630: <resource id="3" type="finish"></resource>
 5631: <link index="1" from="1" to="2"></link>
 5632: <link index="2" from="2" to="3"></link>
 5633: </map>
 5634: ENDINITMAP
 5635:         $topurl=&declutter(
 5636:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5637:                           );
 5638:     }
 5639: # ----------------------------------------------------------- Write preferences
 5640:     &writecoursepref($udom.'_'.$uname,
 5641:                      ('description' => $description,
 5642:                       'url'         => $topurl));
 5643:     return '/'.$udom.'/'.$uname;
 5644: }
 5645: 
 5646: sub is_course {
 5647:     my ($cdom,$cnum) = @_;
 5648:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5649: 				undef,'.',undef,1);
 5650:     if (exists($courses{$cdom.'_'.$cnum})) {
 5651:         return 1;
 5652:     }
 5653:     return 0;
 5654: }
 5655: 
 5656: # ---------------------------------------------------------- Assign Custom Role
 5657: 
 5658: sub assigncustomrole {
 5659:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5660:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5661:                        $end,$start,$deleteflag);
 5662: }
 5663: 
 5664: # ----------------------------------------------------------------- Revoke Role
 5665: 
 5666: sub revokerole {
 5667:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5668:     my $now=time;
 5669:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5670: }
 5671: 
 5672: # ---------------------------------------------------------- Revoke Custom Role
 5673: 
 5674: sub revokecustomrole {
 5675:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5676:     my $now=time;
 5677:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5678:            $deleteflag);
 5679: }
 5680: 
 5681: # ------------------------------------------------------------ Disk usage
 5682: sub diskusage {
 5683:     my ($udom,$uname,$directoryRoot)=@_;
 5684:     $directoryRoot =~ s/\/$//;
 5685:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5686:     return $listing;
 5687: }
 5688: 
 5689: sub is_locked {
 5690:     my ($file_name, $domain, $user) = @_;
 5691:     my @check;
 5692:     my $is_locked;
 5693:     push @check, $file_name;
 5694:     my %locked = &get('file_permissions',\@check,
 5695: 		      $env{'user.domain'},$env{'user.name'});
 5696:     my ($tmp)=keys(%locked);
 5697:     if ($tmp=~/^error:/) { undef(%locked); }
 5698:     
 5699:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5700:         $is_locked = 'false';
 5701:         foreach my $entry (@{$locked{$file_name}}) {
 5702:            if (ref($entry) eq 'ARRAY') { 
 5703:                $is_locked = 'true';
 5704:                last;
 5705:            }
 5706:        }
 5707:     } else {
 5708:         $is_locked = 'false';
 5709:     }
 5710: }
 5711: 
 5712: sub declutter_portfile {
 5713:     my ($file) = @_;
 5714:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5715:     return $file;
 5716: }
 5717: 
 5718: # ------------------------------------------------------------- Mark as Read Only
 5719: 
 5720: sub mark_as_readonly {
 5721:     my ($domain,$user,$files,$what) = @_;
 5722:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5723:     my ($tmp)=keys(%current_permissions);
 5724:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5725:     foreach my $file (@{$files}) {
 5726: 	$file = &declutter_portfile($file);
 5727:         push(@{$current_permissions{$file}},$what);
 5728:     }
 5729:     &put('file_permissions',\%current_permissions,$domain,$user);
 5730:     return;
 5731: }
 5732: 
 5733: # ------------------------------------------------------------Save Selected Files
 5734: 
 5735: sub save_selected_files {
 5736:     my ($user, $path, @files) = @_;
 5737:     my $filename = $user."savedfiles";
 5738:     my @other_files = &files_not_in_path($user, $path);
 5739:     open (OUT, '>'.$tmpdir.$filename);
 5740:     foreach my $file (@files) {
 5741:         print (OUT $env{'form.currentpath'}.$file."\n");
 5742:     }
 5743:     foreach my $file (@other_files) {
 5744:         print (OUT $file."\n");
 5745:     }
 5746:     close (OUT);
 5747:     return 'ok';
 5748: }
 5749: 
 5750: sub clear_selected_files {
 5751:     my ($user) = @_;
 5752:     my $filename = $user."savedfiles";
 5753:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5754:     print (OUT undef);
 5755:     close (OUT);
 5756:     return ("ok");    
 5757: }
 5758: 
 5759: sub files_in_path {
 5760:     my ($user, $path) = @_;
 5761:     my $filename = $user."savedfiles";
 5762:     my %return_files;
 5763:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5764:     while (my $line_in = <IN>) {
 5765:         chomp ($line_in);
 5766:         my @paths_and_file = split (m!/!, $line_in);
 5767:         my $file_part = pop (@paths_and_file);
 5768:         my $path_part = join ('/', @paths_and_file);
 5769:         $path_part.='/';
 5770:         my $path_and_file = $path_part.$file_part;
 5771:         if ($path_part eq $path) {
 5772:             $return_files{$file_part}= 'selected';
 5773:         }
 5774:     }
 5775:     close (IN);
 5776:     return (\%return_files);
 5777: }
 5778: 
 5779: # called in portfolio select mode, to show files selected NOT in current directory
 5780: sub files_not_in_path {
 5781:     my ($user, $path) = @_;
 5782:     my $filename = $user."savedfiles";
 5783:     my @return_files;
 5784:     my $path_part;
 5785:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5786:     while (my $line = <IN>) {
 5787:         #ok, I know it's clunky, but I want it to work
 5788:         my @paths_and_file = split(m|/|, $line);
 5789:         my $file_part = pop(@paths_and_file);
 5790:         chomp($file_part);
 5791:         my $path_part = join('/', @paths_and_file);
 5792:         $path_part .= '/';
 5793:         my $path_and_file = $path_part.$file_part;
 5794:         if ($path_part ne $path) {
 5795:             push(@return_files, ($path_and_file));
 5796:         }
 5797:     }
 5798:     close(OUT);
 5799:     return (@return_files);
 5800: }
 5801: 
 5802: #----------------------------------------------Get portfolio file permissions
 5803: 
 5804: sub get_portfile_permissions {
 5805:     my ($domain,$user) = @_;
 5806:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5807:     my ($tmp)=keys(%current_permissions);
 5808:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5809:     return \%current_permissions;
 5810: }
 5811: 
 5812: #---------------------------------------------Get portfolio file access controls
 5813: 
 5814: sub get_access_controls {
 5815:     my ($current_permissions,$group,$file) = @_;
 5816:     my %access;
 5817:     my $real_file = $file;
 5818:     $file =~ s/\.meta$//;
 5819:     if (defined($file)) {
 5820:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5821:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5822:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5823:             }
 5824:         }
 5825:     } else {
 5826:         foreach my $key (keys(%{$current_permissions})) {
 5827:             if ($key =~ /\0accesscontrol$/) {
 5828:                 if (defined($group)) {
 5829:                     if ($key !~ m-^\Q$group\E/-) {
 5830:                         next;
 5831:                     }
 5832:                 }
 5833:                 my ($fullpath) = split(/\0/,$key);
 5834:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5835:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5836:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5837:                     }
 5838:                 }
 5839:             }
 5840:         }
 5841:     }
 5842:     return %access;
 5843: }
 5844: 
 5845: sub modify_access_controls {
 5846:     my ($file_name,$changes,$domain,$user)=@_;
 5847:     my ($outcome,$deloutcome);
 5848:     my %store_permissions;
 5849:     my %new_values;
 5850:     my %new_control;
 5851:     my %translation;
 5852:     my @deletions = ();
 5853:     my $now = time;
 5854:     if (exists($$changes{'activate'})) {
 5855:         if (ref($$changes{'activate'}) eq 'HASH') {
 5856:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5857:             my $numnew = scalar(@newitems);
 5858:             for (my $i=0; $i<$numnew; $i++) {
 5859:                 my $newkey = $newitems[$i];
 5860:                 my $newid = &Apache::loncommon::get_cgi_id();
 5861:                 if ($newkey =~ /^\d+:/) { 
 5862:                     $newkey =~ s/^(\d+)/$newid/;
 5863:                     $translation{$1} = $newid;
 5864:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5865:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5866:                     $translation{$1} = $newid;
 5867:                 }
 5868:                 $new_values{$file_name."\0".$newkey} = 
 5869:                                           $$changes{'activate'}{$newitems[$i]};
 5870:                 $new_control{$newkey} = $now;
 5871:             }
 5872:         }
 5873:     }
 5874:     my %todelete;
 5875:     my %changed_items;
 5876:     foreach my $action ('delete','update') {
 5877:         if (exists($$changes{$action})) {
 5878:             if (ref($$changes{$action}) eq 'HASH') {
 5879:                 foreach my $key (keys(%{$$changes{$action}})) {
 5880:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5881:                     if ($action eq 'delete') { 
 5882:                         $todelete{$itemnum} = 1;
 5883:                     } else {
 5884:                         $changed_items{$itemnum} = $key;
 5885:                     }
 5886:                 }
 5887:             }
 5888:         }
 5889:     }
 5890:     # get lock on access controls for file.
 5891:     my $lockhash = {
 5892:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5893:                                                        ':'.$env{'user.domain'},
 5894:                    }; 
 5895:     my $tries = 0;
 5896:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5897:    
 5898:     while (($gotlock ne 'ok') && $tries <3) {
 5899:         $tries ++;
 5900:         sleep 1;
 5901:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5902:     }
 5903:     if ($gotlock eq 'ok') {
 5904:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5905:         my ($tmp)=keys(%curr_permissions);
 5906:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5907:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5908:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5909:             if (ref($curr_controls) eq 'HASH') {
 5910:                 foreach my $control_item (keys(%{$curr_controls})) {
 5911:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5912:                     if (defined($todelete{$itemnum})) {
 5913:                         push(@deletions,$file_name."\0".$control_item);
 5914:                     } else {
 5915:                         if (defined($changed_items{$itemnum})) {
 5916:                             $new_control{$changed_items{$itemnum}} = $now;
 5917:                             push(@deletions,$file_name."\0".$control_item);
 5918:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5919:                         } else {
 5920:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5921:                         }
 5922:                     }
 5923:                 }
 5924:             }
 5925:         }
 5926:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5927:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5928:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5929:         #  remove lock
 5930:         my @del_lock = ($file_name."\0".'locked_access_records');
 5931:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5932:         my ($file,$group);
 5933:         if (&is_course($domain,$user)) {
 5934:             ($group,$file) = split(/\//,$file_name,2);
 5935:         } else {
 5936:             $file = $file_name;
 5937:         }
 5938:         my $sqlresult =
 5939:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5940:                                     $group);
 5941:     } else {
 5942:         $outcome = "error: could not obtain lockfile\n";  
 5943:     }
 5944:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5945: }
 5946: 
 5947: sub make_public_indefinitely {
 5948:     my ($requrl) = @_;
 5949:     my $now = time;
 5950:     my $action = 'activate';
 5951:     my $aclnum = 0;
 5952:     if (&is_portfolio_url($requrl)) {
 5953:         my (undef,$udom,$unum,$file_name,$group) =
 5954:             &parse_portfolio_url($requrl);
 5955:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5956:         my %access_controls = &get_access_controls($current_perms,
 5957:                                                    $group,$file_name);
 5958:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5959:             my ($num,$scope,$end,$start) = 
 5960:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5961:             if ($scope eq 'public') {
 5962:                 if ($start <= $now && $end == 0) {
 5963:                     $action = 'none';
 5964:                 } else {
 5965:                     $action = 'update';
 5966:                     $aclnum = $num;
 5967:                 }
 5968:                 last;
 5969:             }
 5970:         }
 5971:         if ($action eq 'none') {
 5972:              return 'ok';
 5973:         } else {
 5974:             my %changes;
 5975:             my $newend = 0;
 5976:             my $newstart = $now;
 5977:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5978:             $changes{$action}{$newkey} = {
 5979:                 type => 'public',
 5980:                 time => {
 5981:                     start => $newstart,
 5982:                     end   => $newend,
 5983:                 },
 5984:             };
 5985:             my ($outcome,$deloutcome,$new_values,$translation) =
 5986:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5987:             return $outcome;
 5988:         }
 5989:     } else {
 5990:         return 'invalid';
 5991:     }
 5992: }
 5993: 
 5994: #------------------------------------------------------Get Marked as Read Only
 5995: 
 5996: sub get_marked_as_readonly {
 5997:     my ($domain,$user,$what,$group) = @_;
 5998:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5999:     my @readonly_files;
 6000:     my $cmp1=$what;
 6001:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6002:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6003:         if (defined($group)) {
 6004:             if ($file_name !~ m-^\Q$group\E/-) {
 6005:                 next;
 6006:             }
 6007:         }
 6008:         if (ref($value) eq "ARRAY"){
 6009:             foreach my $stored_what (@{$value}) {
 6010:                 my $cmp2=$stored_what;
 6011:                 if (ref($stored_what) eq 'ARRAY') {
 6012:                     $cmp2=join('',@{$stored_what});
 6013:                 }
 6014:                 if ($cmp1 eq $cmp2) {
 6015:                     push(@readonly_files, $file_name);
 6016:                     last;
 6017:                 } elsif (!defined($what)) {
 6018:                     push(@readonly_files, $file_name);
 6019:                     last;
 6020:                 }
 6021:             }
 6022:         }
 6023:     }
 6024:     return @readonly_files;
 6025: }
 6026: #-----------------------------------------------------------Get Marked as Read Only Hash
 6027: 
 6028: sub get_marked_as_readonly_hash {
 6029:     my ($current_permissions,$group,$what) = @_;
 6030:     my %readonly_files;
 6031:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6032:         if (defined($group)) {
 6033:             if ($file_name !~ m-^\Q$group\E/-) {
 6034:                 next;
 6035:             }
 6036:         }
 6037:         if (ref($value) eq "ARRAY"){
 6038:             foreach my $stored_what (@{$value}) {
 6039:                 if (ref($stored_what) eq 'ARRAY') {
 6040:                     foreach my $lock_descriptor(@{$stored_what}) {
 6041:                         if ($lock_descriptor eq 'graded') {
 6042:                             $readonly_files{$file_name} = 'graded';
 6043:                         } elsif ($lock_descriptor eq 'handback') {
 6044:                             $readonly_files{$file_name} = 'handback';
 6045:                         } else {
 6046:                             if (!exists($readonly_files{$file_name})) {
 6047:                                 $readonly_files{$file_name} = 'locked';
 6048:                             }
 6049:                         }
 6050:                     }
 6051:                 } 
 6052:             }
 6053:         } 
 6054:     }
 6055:     return %readonly_files;
 6056: }
 6057: # ------------------------------------------------------------ Unmark as Read Only
 6058: 
 6059: sub unmark_as_readonly {
 6060:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6061:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6062:     my ($domain,$user,$what,$file_name,$group) = @_;
 6063:     $file_name = &declutter_portfile($file_name);
 6064:     my $symb_crs = $what;
 6065:     if (ref($what)) { $symb_crs=join('',@$what); }
 6066:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6067:     my ($tmp)=keys(%current_permissions);
 6068:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6069:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6070:     foreach my $file (@readonly_files) {
 6071: 	my $clean_file = &declutter_portfile($file);
 6072: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6073: 	my $current_locks = $current_permissions{$file};
 6074:         my @new_locks;
 6075:         my @del_keys;
 6076:         if (ref($current_locks) eq "ARRAY"){
 6077:             foreach my $locker (@{$current_locks}) {
 6078:                 my $compare=$locker;
 6079:                 if (ref($locker) eq 'ARRAY') {
 6080:                     $compare=join('',@{$locker});
 6081:                     if ($compare ne $symb_crs) {
 6082:                         push(@new_locks, $locker);
 6083:                     }
 6084:                 }
 6085:             }
 6086:             if (scalar(@new_locks) > 0) {
 6087:                 $current_permissions{$file} = \@new_locks;
 6088:             } else {
 6089:                 push(@del_keys, $file);
 6090:                 &del('file_permissions',\@del_keys, $domain, $user);
 6091:                 delete($current_permissions{$file});
 6092:             }
 6093:         }
 6094:     }
 6095:     &put('file_permissions',\%current_permissions,$domain,$user);
 6096:     return;
 6097: }
 6098: 
 6099: # ------------------------------------------------------------ Directory lister
 6100: 
 6101: sub dirlist {
 6102:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6103: 
 6104:     $uri=~s/^\///;
 6105:     $uri=~s/\/$//;
 6106:     my ($udom, $uname);
 6107:     (undef,$udom,$uname)=split(/\//,$uri);
 6108:     if(defined($userdomain)) {
 6109:         $udom = $userdomain;
 6110:     }
 6111:     if(defined($username)) {
 6112:         $uname = $username;
 6113:     }
 6114: 
 6115:     my $dirRoot = $perlvar{'lonDocRoot'};
 6116:     if(defined($alternateDirectoryRoot)) {
 6117:         $dirRoot = $alternateDirectoryRoot;
 6118:         $dirRoot =~ s/\/$//;
 6119:     }
 6120: 
 6121:     if($udom) {
 6122:         if($uname) {
 6123:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6124: 				 &homeserver($uname,$udom));
 6125:             my @listing_results;
 6126:             if ($listing eq 'unknown_cmd') {
 6127:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6128: 				  &homeserver($uname,$udom));
 6129:                 @listing_results = split(/:/,$listing);
 6130:             } else {
 6131:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6132:             }
 6133:             return @listing_results;
 6134:         } elsif(!defined($alternateDirectoryRoot)) {
 6135:             my %allusers;
 6136: 	    my %servers = &get_servers($udom,'library');
 6137: 	    foreach my $tryserver (keys(%servers)) {
 6138: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6139: 				     $udom, $tryserver);
 6140: 		my @listing_results;
 6141: 		if ($listing eq 'unknown_cmd') {
 6142: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6143: 				      $udom, $tryserver);
 6144: 		    @listing_results = split(/:/,$listing);
 6145: 		} else {
 6146: 		    @listing_results =
 6147: 			map { &unescape($_); } split(/:/,$listing);
 6148: 		}
 6149: 		if ($listing_results[0] ne 'no_such_dir' && 
 6150: 		    $listing_results[0] ne 'empty'       &&
 6151: 		    $listing_results[0] ne 'con_lost') {
 6152: 		    foreach my $line (@listing_results) {
 6153: 			my ($entry) = split(/&/,$line,2);
 6154: 			$allusers{$entry} = 1;
 6155: 		    }
 6156: 		}
 6157:             }
 6158:             my $alluserstr='';
 6159:             foreach my $user (sort(keys(%allusers))) {
 6160:                 $alluserstr.=$user.'&user:';
 6161:             }
 6162:             $alluserstr=~s/:$//;
 6163:             return split(/:/,$alluserstr);
 6164:         } else {
 6165:             return ('missing user name');
 6166:         }
 6167:     } elsif(!defined($alternateDirectoryRoot)) {
 6168:         my @all_domains = sort(&all_domains());
 6169:          foreach my $domain (@all_domains) {
 6170:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6171:          }
 6172:          return @all_domains;
 6173:      } else {
 6174:         return ('missing domain');
 6175:     }
 6176: }
 6177: 
 6178: # --------------------------------------------- GetFileTimestamp
 6179: # This function utilizes dirlist and returns the date stamp for
 6180: # when it was last modified.  It will also return an error of -1
 6181: # if an error occurs
 6182: 
 6183: ##
 6184: ## FIXME: This subroutine assumes its caller knows something about the
 6185: ## directory structure of the home server for the student ($root).
 6186: ## Not a good assumption to make.  Since this is for looking up files
 6187: ## in user directories, the full path should be constructed by lond, not
 6188: ## whatever machine we request data from.
 6189: ##
 6190: sub GetFileTimestamp {
 6191:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6192:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6193:     $studentName   = &LONCAPA::clean_username($studentName);
 6194:     my $subdir=$studentName.'__';
 6195:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6196:     my $proname="$studentDomain/$subdir/$studentName";
 6197:     $proname .= '/'.$filename;
 6198:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6199:                                               $studentName, $root);
 6200:     my @stats = split('&', $fileStat);
 6201:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6202:         # @stats contains first the filename, then the stat output
 6203:         return $stats[10]; # so this is 10 instead of 9.
 6204:     } else {
 6205:         return -1;
 6206:     }
 6207: }
 6208: 
 6209: sub stat_file {
 6210:     my ($uri) = @_;
 6211:     $uri = &clutter_with_no_wrapper($uri);
 6212: 
 6213:     my ($udom,$uname,$file,$dir);
 6214:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6215: 	($udom,$uname,$file) =
 6216: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6217: 	$file = 'userfiles/'.$file;
 6218: 	$dir = &propath($udom,$uname);
 6219:     }
 6220:     if ($uri =~ m-^/res/-) {
 6221: 	($udom,$uname) = 
 6222: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6223: 	$file = $uri;
 6224:     }
 6225: 
 6226:     if (!$udom || !$uname || !$file) {
 6227: 	# unable to handle the uri
 6228: 	return ();
 6229:     }
 6230: 
 6231:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6232:     my @stats = split('&', $result);
 6233:     
 6234:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6235: 	shift(@stats); #filename is first
 6236: 	return @stats;
 6237:     }
 6238:     return ();
 6239: }
 6240: 
 6241: # -------------------------------------------------------- Value of a Condition
 6242: 
 6243: # gets the value of a specific preevaluated condition
 6244: #    stored in the string  $env{user.state.<cid>}
 6245: # or looks up a condition reference in the bighash and if if hasn't
 6246: # already been evaluated recurses into docondval to get the value of
 6247: # the condition, then memoizing it to 
 6248: #   $env{user.state.<cid>.<condition>}
 6249: sub directcondval {
 6250:     my $number=shift;
 6251:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6252: 	&Apache::lonuserstate::evalstate();
 6253:     }
 6254:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6255: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6256:     } elsif ($number =~ /^_/) {
 6257: 	my $sub_condition;
 6258: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6259: 		&GDBM_READER(),0640)) {
 6260: 	    $sub_condition=$bighash{'conditions'.$number};
 6261: 	    untie(%bighash);
 6262: 	}
 6263: 	my $value = &docondval($sub_condition);
 6264: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 6265: 	return $value;
 6266:     }
 6267:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6268:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6269:     } else {
 6270:        return 2;
 6271:     }
 6272: }
 6273: 
 6274: # get the collection of conditions for this resource
 6275: sub condval {
 6276:     my $condidx=shift;
 6277:     my $allpathcond='';
 6278:     foreach my $cond (split(/\|/,$condidx)) {
 6279: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6280: 	    $allpathcond.=
 6281: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6282: 	}
 6283:     }
 6284:     $allpathcond=~s/\|$//;
 6285:     return &docondval($allpathcond);
 6286: }
 6287: 
 6288: #evaluates an expression of conditions
 6289: sub docondval {
 6290:     my ($allpathcond) = @_;
 6291:     my $result=0;
 6292:     if ($env{'request.course.id'}
 6293: 	&& defined($allpathcond)) {
 6294: 	my $operand='|';
 6295: 	my @stack;
 6296: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6297: 	    if ($chunk eq '(') {
 6298: 		push @stack,($operand,$result);
 6299: 	    } elsif ($chunk eq ')') {
 6300: 		my $before=pop @stack;
 6301: 		if (pop @stack eq '&') {
 6302: 		    $result=$result>$before?$before:$result;
 6303: 		} else {
 6304: 		    $result=$result>$before?$result:$before;
 6305: 		}
 6306: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6307: 		$operand=$chunk;
 6308: 	    } else {
 6309: 		my $new=directcondval($chunk);
 6310: 		if ($operand eq '&') {
 6311: 		    $result=$result>$new?$new:$result;
 6312: 		} else {
 6313: 		    $result=$result>$new?$result:$new;
 6314: 		}
 6315: 	    }
 6316: 	}
 6317:     }
 6318:     return $result;
 6319: }
 6320: 
 6321: # ---------------------------------------------------- Devalidate courseresdata
 6322: 
 6323: sub devalidatecourseresdata {
 6324:     my ($coursenum,$coursedomain)=@_;
 6325:     my $hashid=$coursenum.':'.$coursedomain;
 6326:     &devalidate_cache_new('courseres',$hashid);
 6327: }
 6328: 
 6329: 
 6330: # --------------------------------------------------- Course Resourcedata Query
 6331: #
 6332: #  Parameters:
 6333: #      $coursenum    - Number of the course.
 6334: #      $coursedomain - Domain at which the course was created.
 6335: #  Returns:
 6336: #     A hash of the course parameters along (I think) with timestamps
 6337: #     and version info.
 6338: 
 6339: sub get_courseresdata {
 6340:     my ($coursenum,$coursedomain)=@_;
 6341:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6342:     my $hashid=$coursenum.':'.$coursedomain;
 6343:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6344:     my %dumpreply;
 6345:     unless (defined($cached)) {
 6346: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6347: 	$result=\%dumpreply;
 6348: 	my ($tmp) = keys(%dumpreply);
 6349: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6350: 	    &do_cache_new('courseres',$hashid,$result,600);
 6351: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6352: 	    return $tmp;
 6353: 	} elsif ($tmp =~ /^(error)/) {
 6354: 	    $result=undef;
 6355: 	    &do_cache_new('courseres',$hashid,$result,600);
 6356: 	}
 6357:     }
 6358:     return $result;
 6359: }
 6360: 
 6361: sub devalidateuserresdata {
 6362:     my ($uname,$udom)=@_;
 6363:     my $hashid="$udom:$uname";
 6364:     &devalidate_cache_new('userres',$hashid);
 6365: }
 6366: 
 6367: sub get_userresdata {
 6368:     my ($uname,$udom)=@_;
 6369:     #most student don\'t have any data set, check if there is some data
 6370:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6371: 
 6372:     my $hashid="$udom:$uname";
 6373:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6374:     if (!defined($cached)) {
 6375: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6376: 	$result=\%resourcedata;
 6377: 	&do_cache_new('userres',$hashid,$result,600);
 6378:     }
 6379:     my ($tmp)=keys(%$result);
 6380:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6381: 	return $result;
 6382:     }
 6383:     #error 2 occurs when the .db doesn't exist
 6384:     if ($tmp!~/error: 2 /) {
 6385: 	&logthis("<font color=\"blue\">WARNING:".
 6386: 		 " Trying to get resource data for ".
 6387: 		 $uname." at ".$udom.": ".
 6388: 		 $tmp."</font>");
 6389:     } elsif ($tmp=~/error: 2 /) {
 6390: 	#&EXT_cache_set($udom,$uname);
 6391: 	&do_cache_new('userres',$hashid,undef,600);
 6392: 	undef($tmp); # not really an error so don't send it back
 6393:     }
 6394:     return $tmp;
 6395: }
 6396: #----------------------------------------------- resdata - return resource data
 6397: #  Purpose:
 6398: #    Return resource data for either users or for a course.
 6399: #  Parameters:
 6400: #     $name      - Course/user name.
 6401: #     $domain    - Name of the domain the user/course is registered on.
 6402: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6403: #     @which     - Array of names of resources desired.
 6404: #  Returns:
 6405: #     The value of the first reasource in @which that is found in the
 6406: #     resource hash.
 6407: #  Exceptional Conditions:
 6408: #     If the $type passed in is not valid (not the string 'course' or 
 6409: #     'user', an undefined  reference is returned.
 6410: #     If none of the resources are found, an undef is returned
 6411: sub resdata {
 6412:     my ($name,$domain,$type,@which)=@_;
 6413:     my $result;
 6414:     if ($type eq 'course') {
 6415: 	$result=&get_courseresdata($name,$domain);
 6416:     } elsif ($type eq 'user') {
 6417: 	$result=&get_userresdata($name,$domain);
 6418:     }
 6419:     if (!ref($result)) { return $result; }    
 6420:     foreach my $item (@which) {
 6421: 	if (defined($result->{$item->[0]})) {
 6422: 	    return [$result->{$item->[0]},$item->[1]];
 6423: 	}
 6424:     }
 6425:     return undef;
 6426: }
 6427: 
 6428: #
 6429: # EXT resource caching routines
 6430: #
 6431: 
 6432: sub clear_EXT_cache_status {
 6433:     &delenv('cache.EXT.');
 6434: }
 6435: 
 6436: sub EXT_cache_status {
 6437:     my ($target_domain,$target_user) = @_;
 6438:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6439:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6440:         # We know already the user has no data
 6441:         return 1;
 6442:     } else {
 6443:         return 0;
 6444:     }
 6445: }
 6446: 
 6447: sub EXT_cache_set {
 6448:     my ($target_domain,$target_user) = @_;
 6449:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6450:     #&appenv($cachename => time);
 6451: }
 6452: 
 6453: # --------------------------------------------------------- Value of a Variable
 6454: sub EXT {
 6455: 
 6456:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6457:     unless ($varname) { return ''; }
 6458:     #get real user name/domain, courseid and symb
 6459:     my $courseid;
 6460:     my $publicuser;
 6461:     if ($symbparm) {
 6462: 	$symbparm=&get_symb_from_alias($symbparm);
 6463:     }
 6464:     if (!($uname && $udom)) {
 6465:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6466:       if (!$symbparm) {	$symbparm=$cursymb; }
 6467:     } else {
 6468: 	$courseid=$env{'request.course.id'};
 6469:     }
 6470:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6471:     my $rest;
 6472:     if (defined($therest[0])) {
 6473:        $rest=join('.',@therest);
 6474:     } else {
 6475:        $rest='';
 6476:     }
 6477: 
 6478:     my $qualifierrest=$qualifier;
 6479:     if ($rest) { $qualifierrest.='.'.$rest; }
 6480:     my $spacequalifierrest=$space;
 6481:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6482:     if ($realm eq 'user') {
 6483: # --------------------------------------------------------------- user.resource
 6484: 	if ($space eq 'resource') {
 6485: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6486: 		  || defined($Apache::lonhomework::parsing_a_task))
 6487: 		 &&
 6488: 		 ($symbparm eq &symbread()) ) {	
 6489: 		# if we are in the middle of processing the resource the
 6490: 		# get the value we are planning on committing
 6491:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6492:                     return $Apache::lonhomework::results{$qualifierrest};
 6493:                 } else {
 6494:                     return $Apache::lonhomework::history{$qualifierrest};
 6495:                 }
 6496: 	    } else {
 6497: 		my %restored;
 6498: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6499: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6500: 		} else {
 6501: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6502: 		}
 6503: 		return $restored{$qualifierrest};
 6504: 	    }
 6505: # ----------------------------------------------------------------- user.access
 6506:         } elsif ($space eq 'access') {
 6507: 	    # FIXME - not supporting calls for a specific user
 6508:             return &allowed($qualifier,$rest);
 6509: # ------------------------------------------ user.preferences, user.environment
 6510:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6511: 	    if (($uname eq $env{'user.name'}) &&
 6512: 		($udom eq $env{'user.domain'})) {
 6513: 		return $env{join('.',('environment',$qualifierrest))};
 6514: 	    } else {
 6515: 		my %returnhash;
 6516: 		if (!$publicuser) {
 6517: 		    %returnhash=&userenvironment($udom,$uname,
 6518: 						 $qualifierrest);
 6519: 		}
 6520: 		return $returnhash{$qualifierrest};
 6521: 	    }
 6522: # ----------------------------------------------------------------- user.course
 6523:         } elsif ($space eq 'course') {
 6524: 	    # FIXME - not supporting calls for a specific user
 6525:             return $env{join('.',('request.course',$qualifier))};
 6526: # ------------------------------------------------------------------- user.role
 6527:         } elsif ($space eq 'role') {
 6528: 	    # FIXME - not supporting calls for a specific user
 6529:             my ($role,$where)=split(/\./,$env{'request.role'});
 6530:             if ($qualifier eq 'value') {
 6531: 		return $role;
 6532:             } elsif ($qualifier eq 'extent') {
 6533:                 return $where;
 6534:             }
 6535: # ----------------------------------------------------------------- user.domain
 6536:         } elsif ($space eq 'domain') {
 6537:             return $udom;
 6538: # ------------------------------------------------------------------- user.name
 6539:         } elsif ($space eq 'name') {
 6540:             return $uname;
 6541: # ---------------------------------------------------- Any other user namespace
 6542:         } else {
 6543: 	    my %reply;
 6544: 	    if (!$publicuser) {
 6545: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6546: 	    }
 6547: 	    return $reply{$qualifierrest};
 6548:         }
 6549:     } elsif ($realm eq 'query') {
 6550: # ---------------------------------------------- pull stuff out of query string
 6551:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6552: 						[$spacequalifierrest]);
 6553: 	return $env{'form.'.$spacequalifierrest}; 
 6554:    } elsif ($realm eq 'request') {
 6555: # ------------------------------------------------------------- request.browser
 6556:         if ($space eq 'browser') {
 6557: 	    if ($qualifier eq 'textremote') {
 6558: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6559: 		    return 1;
 6560: 		} else {
 6561: 		    return 0;
 6562: 		}
 6563: 	    } else {
 6564: 		return $env{'browser.'.$qualifier};
 6565: 	    }
 6566: # ------------------------------------------------------------ request.filename
 6567:         } else {
 6568:             return $env{'request.'.$spacequalifierrest};
 6569:         }
 6570:     } elsif ($realm eq 'course') {
 6571: # ---------------------------------------------------------- course.description
 6572:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6573:     } elsif ($realm eq 'resource') {
 6574: 
 6575: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6576: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6577: 	}
 6578: 
 6579: 	if ($space eq 'title') {
 6580: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6581: 	    return &gettitle($symbparm);
 6582: 	}
 6583: 	
 6584: 	if ($space eq 'map') {
 6585: 	    my ($map) = &decode_symb($symbparm);
 6586: 	    return &symbread($map);
 6587: 	}
 6588: 	if ($space eq 'filename') {
 6589: 	    if ($symbparm) {
 6590: 		return &clutter((&decode_symb($symbparm))[2]);
 6591: 	    }
 6592: 	    return &hreflocation('',$env{'request.filename'});
 6593: 	}
 6594: 
 6595: 	my ($section, $group, @groups);
 6596: 	my ($courselevelm,$courselevel);
 6597: 	if ($symbparm && defined($courseid) && 
 6598: 	    $courseid eq $env{'request.course.id'}) {
 6599: 
 6600: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6601: 
 6602: # ----------------------------------------------------- Cascading lookup scheme
 6603: 	    my $symbp=$symbparm;
 6604: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6605: 
 6606: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6607: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6608: 
 6609: 	    if (($env{'user.name'} eq $uname) &&
 6610: 		($env{'user.domain'} eq $udom)) {
 6611: 		$section=$env{'request.course.sec'};
 6612:                 @groups = split(/:/,$env{'request.course.groups'});  
 6613:                 @groups=&sort_course_groups($courseid,@groups); 
 6614: 	    } else {
 6615: 		if (! defined($usection)) {
 6616: 		    $section=&getsection($udom,$uname,$courseid);
 6617: 		} else {
 6618: 		    $section = $usection;
 6619: 		}
 6620:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6621: 	    }
 6622: 
 6623: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6624: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6625: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6626: 
 6627: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6628: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6629: 	    $courselevelm=$courseid.'.'.$mapparm;
 6630: 
 6631: # ----------------------------------------------------------- first, check user
 6632: 
 6633: 	    my $userreply=&resdata($uname,$udom,'user',
 6634: 				       ([$courselevelr,'resource'],
 6635: 					[$courselevelm,'map'     ],
 6636: 					[$courselevel, 'course'  ]));
 6637: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6638: 
 6639: # ------------------------------------------------ second, check some of course
 6640:             my $coursereply;
 6641:             if (@groups > 0) {
 6642:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6643:                                        $mapparm,$spacequalifierrest);
 6644:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6645:             }
 6646: 
 6647: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6648: 				  $env{'course.'.$courseid.'.domain'},
 6649: 				  'course',
 6650: 				  ([$seclevelr,   'resource'],
 6651: 				   [$seclevelm,   'map'     ],
 6652: 				   [$seclevel,    'course'  ],
 6653: 				   [$courselevelr,'resource']));
 6654: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6655: 
 6656: # ------------------------------------------------------ third, check map parms
 6657: 	    my %parmhash=();
 6658: 	    my $thisparm='';
 6659: 	    if (tie(%parmhash,'GDBM_File',
 6660: 		    $env{'request.course.fn'}.'_parms.db',
 6661: 		    &GDBM_READER(),0640)) {
 6662: 		$thisparm=$parmhash{$symbparm};
 6663: 		untie(%parmhash);
 6664: 	    }
 6665: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6666: 	}
 6667: # ------------------------------------------ fourth, look in resource metadata
 6668: 
 6669: 	$spacequalifierrest=~s/\./\_/;
 6670: 	my $filename;
 6671: 	if (!$symbparm) { $symbparm=&symbread(); }
 6672: 	if ($symbparm) {
 6673: 	    $filename=(&decode_symb($symbparm))[2];
 6674: 	} else {
 6675: 	    $filename=$env{'request.filename'};
 6676: 	}
 6677: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6678: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6679: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6680: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6681: 
 6682: # ---------------------------------------------- fourth, look in rest of course
 6683: 	if ($symbparm && defined($courseid) && 
 6684: 	    $courseid eq $env{'request.course.id'}) {
 6685: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6686: 				     $env{'course.'.$courseid.'.domain'},
 6687: 				     'course',
 6688: 				     ([$courselevelm,'map'   ],
 6689: 				      [$courselevel, 'course']));
 6690: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6691: 	}
 6692: # ------------------------------------------------------------------ Cascade up
 6693: 	unless ($space eq '0') {
 6694: 	    my @parts=split(/_/,$space);
 6695: 	    my $id=pop(@parts);
 6696: 	    my $part=join('_',@parts);
 6697: 	    if ($part eq '') { $part='0'; }
 6698: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6699: 				 $symbparm,$udom,$uname,$section,1);
 6700: 	    if (@partgeneral) { return &get_reply(\@partgeneral); }
 6701: 	}
 6702: 	if ($recurse) { return undef; }
 6703: 	my $pack_def=&packages_tab_default($filename,$varname);
 6704: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6705: # ---------------------------------------------------- Any other user namespace
 6706:     } elsif ($realm eq 'environment') {
 6707: # ----------------------------------------------------------------- environment
 6708: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6709: 	    return $env{'environment.'.$spacequalifierrest};
 6710: 	} else {
 6711: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6712: 		return '';
 6713: 	    }
 6714: 	    my %returnhash=&userenvironment($udom,$uname,
 6715: 					    $spacequalifierrest);
 6716: 	    return $returnhash{$spacequalifierrest};
 6717: 	}
 6718:     } elsif ($realm eq 'system') {
 6719: # ----------------------------------------------------------------- system.time
 6720: 	if ($space eq 'time') {
 6721: 	    return time;
 6722:         }
 6723:     } elsif ($realm eq 'server') {
 6724: # ----------------------------------------------------------------- system.time
 6725: 	if ($space eq 'name') {
 6726: 	    return $ENV{'SERVER_NAME'};
 6727:         }
 6728:     }
 6729:     return '';
 6730: }
 6731: 
 6732: sub get_reply {
 6733:     my ($reply_value) = @_;
 6734:     if (wantarray) {
 6735: 	return @$reply_value;
 6736:     }
 6737:     return $reply_value->[0];
 6738: }
 6739: 
 6740: sub check_group_parms {
 6741:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6742:     my @groupitems = ();
 6743:     my $resultitem;
 6744:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6745:     foreach my $group (@{$groups}) {
 6746:         foreach my $level (@levels) {
 6747:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6748:              push(@groupitems,[$item,$level->[1]]);
 6749:         }
 6750:     }
 6751:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6752:                             $env{'course.'.$courseid.'.domain'},
 6753:                                      'course',@groupitems);
 6754:     return $coursereply;
 6755: }
 6756: 
 6757: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6758:     my ($courseid,@groups) = @_;
 6759:     @groups = sort(@groups);
 6760:     return @groups;
 6761: }
 6762: 
 6763: sub packages_tab_default {
 6764:     my ($uri,$varname)=@_;
 6765:     my (undef,$part,$name)=split(/\./,$varname);
 6766: 
 6767:     my (@extension,@specifics,$do_default);
 6768:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6769: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6770: 	if ($pack_type eq 'default') {
 6771: 	    $do_default=1;
 6772: 	} elsif ($pack_type eq 'extension') {
 6773: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6774: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6775: 	    # only look at packages defaults for packages that this id is
 6776: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6777: 	}
 6778:     }
 6779:     # first look for a package that matches the requested part id
 6780:     foreach my $package (@specifics) {
 6781: 	my (undef,$pack_type,$pack_part)=@{$package};
 6782: 	next if ($pack_part ne $part);
 6783: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6784: 	    return $packagetab{"$pack_type&$name&default"};
 6785: 	}
 6786:     }
 6787:     # look for any possible matching non extension_ package
 6788:     foreach my $package (@specifics) {
 6789: 	my (undef,$pack_type,$pack_part)=@{$package};
 6790: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6791: 	    return $packagetab{"$pack_type&$name&default"};
 6792: 	}
 6793: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6794: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6795: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6796: 	}
 6797:     }
 6798:     # look for any posible extension_ match
 6799:     foreach my $package (@extension) {
 6800: 	my ($package,$pack_type)=@{$package};
 6801: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6802: 	    return $packagetab{"$pack_type&$name&default"};
 6803: 	}
 6804: 	if (defined($packagetab{$package."&$name&default"})) {
 6805: 	    return $packagetab{$package."&$name&default"};
 6806: 	}
 6807:     }
 6808:     # look for a global default setting
 6809:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6810: 	return $packagetab{"default&$name&default"};
 6811:     }
 6812:     return undef;
 6813: }
 6814: 
 6815: sub add_prefix_and_part {
 6816:     my ($prefix,$part)=@_;
 6817:     my $keyroot;
 6818:     if (defined($prefix) && $prefix !~ /^__/) {
 6819: 	# prefix that has a part already
 6820: 	$keyroot=$prefix;
 6821:     } elsif (defined($prefix)) {
 6822: 	# prefix that is missing a part
 6823: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6824:     } else {
 6825: 	# no prefix at all
 6826: 	if (defined($part)) { $keyroot='_'.$part; }
 6827:     }
 6828:     return $keyroot;
 6829: }
 6830: 
 6831: # ---------------------------------------------------------------- Get metadata
 6832: 
 6833: my %metaentry;
 6834: sub metadata {
 6835:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6836:     $uri=&declutter($uri);
 6837:     # if it is a non metadata possible uri return quickly
 6838:     if (($uri eq '') || 
 6839: 	(($uri =~ m|^/*adm/|) && 
 6840: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6841:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6842: 	return undef;
 6843:     }
 6844:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6845: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6846: 	return undef;
 6847:     }
 6848:     my $filename=$uri;
 6849:     $uri=~s/\.meta$//;
 6850: #
 6851: # Is the metadata already cached?
 6852: # Look at timestamp of caching
 6853: # Everything is cached by the main uri, libraries are never directly cached
 6854: #
 6855:     if (!defined($liburi)) {
 6856: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6857: 	if (defined($cached)) { return $result->{':'.$what}; }
 6858:     }
 6859:     {
 6860: #
 6861: # Is this a recursive call for a library?
 6862: #
 6863: #	if (! exists($metacache{$uri})) {
 6864: #	    $metacache{$uri}={};
 6865: #	}
 6866: 	my $cachetime = 60*60;
 6867:         if ($liburi) {
 6868: 	    $liburi=&declutter($liburi);
 6869:             $filename=$liburi;
 6870:         } else {
 6871: 	    &devalidate_cache_new('meta',$uri);
 6872: 	    undef(%metaentry);
 6873: 	}
 6874:         my %metathesekeys=();
 6875:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6876: 	my $metastring;
 6877: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6878: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6879: 	    $metastring = 
 6880: 		&Apache::lonnet::ssi_body($which,
 6881: 					  ('grade_target' => 'meta'));
 6882: 	    $cachetime = 1; # only want this cached in the child not long term
 6883: 	} elsif ($uri !~ m -^(editupload)/-) {
 6884: 	    my $file=&filelocation('',&clutter($filename));
 6885: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6886: 	    $metastring=&getfile($file);
 6887: 	}
 6888:         my $parser=HTML::LCParser->new(\$metastring);
 6889:         my $token;
 6890:         undef %metathesekeys;
 6891:         while ($token=$parser->get_token) {
 6892: 	    if ($token->[0] eq 'S') {
 6893: 		if (defined($token->[2]->{'package'})) {
 6894: #
 6895: # This is a package - get package info
 6896: #
 6897: 		    my $package=$token->[2]->{'package'};
 6898: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6899: 		    if (defined($token->[2]->{'id'})) { 
 6900: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6901: 		    }
 6902: 		    if ($metaentry{':packages'}) {
 6903: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6904: 		    } else {
 6905: 			$metaentry{':packages'}=$package.$keyroot;
 6906: 		    }
 6907: 		    foreach my $pack_entry (keys(%packagetab)) {
 6908: 			my $part=$keyroot;
 6909: 			$part=~s/^\_//;
 6910: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6911: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6912: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6913: 			    # ignore package.tab specified default values
 6914:                             # here &package_tab_default() will fetch those
 6915: 			    if ($subp eq 'default') { next; }
 6916: 			    my $value=$packagetab{$pack_entry};
 6917: 			    my $unikey;
 6918: 			    if ($pack =~ /_0$/) {
 6919: 				$unikey='parameter_0_'.$name;
 6920: 				$part=0;
 6921: 			    } else {
 6922: 				$unikey='parameter'.$keyroot.'_'.$name;
 6923: 			    }
 6924: 			    if ($subp eq 'display') {
 6925: 				$value.=' [Part: '.$part.']';
 6926: 			    }
 6927: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6928: 			    $metathesekeys{$unikey}=1;
 6929: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6930: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6931: 			    }
 6932: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6933: 				$metaentry{':'.$unikey}=
 6934: 				    $metaentry{':'.$unikey.'.default'};
 6935: 			    }
 6936: 			}
 6937: 		    }
 6938: 		} else {
 6939: #
 6940: # This is not a package - some other kind of start tag
 6941: #
 6942: 		    my $entry=$token->[1];
 6943: 		    my $unikey;
 6944: 		    if ($entry eq 'import') {
 6945: 			$unikey='';
 6946: 		    } else {
 6947: 			$unikey=$entry;
 6948: 		    }
 6949: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6950: 
 6951: 		    if (defined($token->[2]->{'id'})) { 
 6952: 			$unikey.='_'.$token->[2]->{'id'}; 
 6953: 		    }
 6954: 
 6955: 		    if ($entry eq 'import') {
 6956: #
 6957: # Importing a library here
 6958: #
 6959: 			if ($depthcount<20) {
 6960: 			    my $location=$parser->get_text('/import');
 6961: 			    my $dir=$filename;
 6962: 			    $dir=~s|[^/]*$||;
 6963: 			    $location=&filelocation($dir,$location);
 6964: 			    my $metadata = 
 6965: 				&metadata($uri,'keys', $location,$unikey,
 6966: 					  $depthcount+1);
 6967: 			    foreach my $meta (split(',',$metadata)) {
 6968: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6969: 				$metathesekeys{$meta}=1;
 6970: 			    }
 6971: 			}
 6972: 		    } else { 
 6973: 			
 6974: 			if (defined($token->[2]->{'name'})) { 
 6975: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6976: 			}
 6977: 			$metathesekeys{$unikey}=1;
 6978: 			foreach my $param (@{$token->[3]}) {
 6979: 			    $metaentry{':'.$unikey.'.'.$param} =
 6980: 				$token->[2]->{$param};
 6981: 			}
 6982: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6983: 			my $default=$metaentry{':'.$unikey.'.default'};
 6984: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6985: 		 # only ws inside the tag, and not in default, so use default
 6986: 		 # as value
 6987: 			    $metaentry{':'.$unikey}=$default;
 6988: 			} elsif ( $internaltext =~ /\S/ ) {
 6989: 		  # something interesting inside the tag
 6990: 			    $metaentry{':'.$unikey}=$internaltext;
 6991: 			} else {
 6992: 		  # no interesting values, don't set a default
 6993: 			}
 6994: # end of not-a-package not-a-library import
 6995: 		    }
 6996: # end of not-a-package start tag
 6997: 		}
 6998: # the next is the end of "start tag"
 6999: 	    }
 7000: 	}
 7001: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7002: 	$extension = lc($extension);
 7003: 	if ($extension eq 'htm') { $extension='html'; }
 7004: 
 7005: 	foreach my $key (keys(%packagetab)) {
 7006: 	    #no specific packages #how's our extension
 7007: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7008: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7009: 					 \%metathesekeys);
 7010: 	}
 7011: 
 7012: 	if (!exists($metaentry{':packages'})
 7013: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7014: 	    foreach my $key (keys(%packagetab)) {
 7015: 		#no specific packages well let's get default then
 7016: 		if ($key!~/^default&/) { next; }
 7017: 		&metadata_create_package_def($uri,$key,'default',
 7018: 					     \%metathesekeys);
 7019: 	    }
 7020: 	}
 7021: # are there custom rights to evaluate
 7022: 	if ($metaentry{':copyright'} eq 'custom') {
 7023: 
 7024:     #
 7025:     # Importing a rights file here
 7026:     #
 7027: 	    unless ($depthcount) {
 7028: 		my $location=$metaentry{':customdistributionfile'};
 7029: 		my $dir=$filename;
 7030: 		$dir=~s|[^/]*$||;
 7031: 		$location=&filelocation($dir,$location);
 7032: 		my $rights_metadata =
 7033: 		    &metadata($uri,'keys',$location,'_rights',
 7034: 			      $depthcount+1);
 7035: 		foreach my $rights (split(',',$rights_metadata)) {
 7036: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7037: 		    $metathesekeys{$rights}=1;
 7038: 		}
 7039: 	    }
 7040: 	}
 7041: 	# uniqifiy package listing
 7042: 	my %seen;
 7043: 	my @uniq_packages =
 7044: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7045: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7046: 
 7047: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7048: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7049: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7050: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7051: # this is the end of "was not already recently cached
 7052:     }
 7053:     return $metaentry{':'.$what};
 7054: }
 7055: 
 7056: sub metadata_create_package_def {
 7057:     my ($uri,$key,$package,$metathesekeys)=@_;
 7058:     my ($pack,$name,$subp)=split(/\&/,$key);
 7059:     if ($subp eq 'default') { next; }
 7060:     
 7061:     if (defined($metaentry{':packages'})) {
 7062: 	$metaentry{':packages'}.=','.$package;
 7063:     } else {
 7064: 	$metaentry{':packages'}=$package;
 7065:     }
 7066:     my $value=$packagetab{$key};
 7067:     my $unikey;
 7068:     $unikey='parameter_0_'.$name;
 7069:     $metaentry{':'.$unikey.'.part'}=0;
 7070:     $$metathesekeys{$unikey}=1;
 7071:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7072: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7073:     }
 7074:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7075: 	$metaentry{':'.$unikey}=
 7076: 	    $metaentry{':'.$unikey.'.default'};
 7077:     }
 7078: }
 7079: 
 7080: sub metadata_generate_part0 {
 7081:     my ($metadata,$metacache,$uri) = @_;
 7082:     my %allnames;
 7083:     foreach my $metakey (keys(%$metadata)) {
 7084: 	if ($metakey=~/^parameter\_(.*)/) {
 7085: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7086: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7087: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7088: 	    $allnames{$name}=$part;
 7089: 	  }
 7090: 	}
 7091:     }
 7092:     foreach my $name (keys(%allnames)) {
 7093:       $$metadata{"parameter_0_$name"}=1;
 7094:       my $key=":parameter_0_$name";
 7095:       $$metacache{"$key.part"}='0';
 7096:       $$metacache{"$key.name"}=$name;
 7097:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7098: 					   $allnames{$name}.'_'.$name.
 7099: 					   '.type'};
 7100:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7101: 			     '.display'};
 7102:       my $expr='[Part: '.$allnames{$name}.']';
 7103:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7104:       $$metacache{"$key.display"}=$olddis;
 7105:     }
 7106: }
 7107: 
 7108: # ------------------------------------------------------ Devalidate title cache
 7109: 
 7110: sub devalidate_title_cache {
 7111:     my ($url)=@_;
 7112:     if (!$env{'request.course.id'}) { return; }
 7113:     my $symb=&symbread($url);
 7114:     if (!$symb) { return; }
 7115:     my $key=$env{'request.course.id'}."\0".$symb;
 7116:     &devalidate_cache_new('title',$key);
 7117: }
 7118: 
 7119: # ------------------------------------------------- Get the title of a resource
 7120: 
 7121: sub gettitle {
 7122:     my $urlsymb=shift;
 7123:     my $symb=&symbread($urlsymb);
 7124:     if ($symb) {
 7125: 	my $key=$env{'request.course.id'}."\0".$symb;
 7126: 	my ($result,$cached)=&is_cached_new('title',$key);
 7127: 	if (defined($cached)) { 
 7128: 	    return $result;
 7129: 	}
 7130: 	my ($map,$resid,$url)=&decode_symb($symb);
 7131: 	my $title='';
 7132: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7133: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7134: 	} else {
 7135: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7136: 		    &GDBM_READER(),0640)) {
 7137: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7138: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7139: 		untie(%bighash);
 7140: 	    }
 7141: 	}
 7142: 	$title=~s/\&colon\;/\:/gs;
 7143: 	if ($title) {
 7144: 	    return &do_cache_new('title',$key,$title,600);
 7145: 	}
 7146: 	$urlsymb=$url;
 7147:     }
 7148:     my $title=&metadata($urlsymb,'title');
 7149:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7150:     return $title;
 7151: }
 7152: 
 7153: sub get_slot {
 7154:     my ($which,$cnum,$cdom)=@_;
 7155:     if (!$cnum || !$cdom) {
 7156: 	(undef,my $courseid)=&whichuser();
 7157: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7158: 	$cnum=$env{'course.'.$courseid.'.num'};
 7159:     }
 7160:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7161:     my %slotinfo;
 7162:     if (exists($remembered{$key})) {
 7163: 	$slotinfo{$which} = $remembered{$key};
 7164:     } else {
 7165: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7166: 	&Apache::lonhomework::showhash(%slotinfo);
 7167: 	my ($tmp)=keys(%slotinfo);
 7168: 	if ($tmp=~/^error:/) { return (); }
 7169: 	$remembered{$key} = $slotinfo{$which};
 7170:     }
 7171:     if (ref($slotinfo{$which}) eq 'HASH') {
 7172: 	return %{$slotinfo{$which}};
 7173:     }
 7174:     return $slotinfo{$which};
 7175: }
 7176: # ------------------------------------------------- Update symbolic store links
 7177: 
 7178: sub symblist {
 7179:     my ($mapname,%newhash)=@_;
 7180:     $mapname=&deversion(&declutter($mapname));
 7181:     my %hash;
 7182:     if (($env{'request.course.fn'}) && (%newhash)) {
 7183:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7184:                       &GDBM_WRCREAT(),0640)) {
 7185: 	    foreach my $url (keys %newhash) {
 7186: 		next if ($url eq 'last_known'
 7187: 			 && $env{'form.no_update_last_known'});
 7188: 		$hash{declutter($url)}=&encode_symb($mapname,
 7189: 						    $newhash{$url}->[1],
 7190: 						    $newhash{$url}->[0]);
 7191:             }
 7192:             if (untie(%hash)) {
 7193: 		return 'ok';
 7194:             }
 7195:         }
 7196:     }
 7197:     return 'error';
 7198: }
 7199: 
 7200: # --------------------------------------------------------------- Verify a symb
 7201: 
 7202: sub symbverify {
 7203:     my ($symb,$thisurl)=@_;
 7204:     my $thisfn=$thisurl;
 7205:     $thisfn=&declutter($thisfn);
 7206: # direct jump to resource in page or to a sequence - will construct own symbs
 7207:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7208: # check URL part
 7209:     my ($map,$resid,$url)=&decode_symb($symb);
 7210: 
 7211:     unless ($url eq $thisfn) { return 0; }
 7212: 
 7213:     $symb=&symbclean($symb);
 7214:     $thisurl=&deversion($thisurl);
 7215:     $thisfn=&deversion($thisfn);
 7216: 
 7217:     my %bighash;
 7218:     my $okay=0;
 7219: 
 7220:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7221:                             &GDBM_READER(),0640)) {
 7222:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7223:         unless ($ids) { 
 7224:            $ids=$bighash{'ids_/'.$thisurl};
 7225:         }
 7226:         if ($ids) {
 7227: # ------------------------------------------------------------------- Has ID(s)
 7228: 	    foreach my $id (split(/\,/,$ids)) {
 7229: 	       my ($mapid,$resid)=split(/\./,$id);
 7230:                if (
 7231:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7232:    eq $symb) { 
 7233: 		   if (($env{'request.role.adv'}) ||
 7234: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7235: 		       $okay=1; 
 7236: 		   }
 7237: 	       }
 7238: 	   }
 7239:         }
 7240: 	untie(%bighash);
 7241:     }
 7242:     return $okay;
 7243: }
 7244: 
 7245: # --------------------------------------------------------------- Clean-up symb
 7246: 
 7247: sub symbclean {
 7248:     my $symb=shift;
 7249:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7250: # remove version from map
 7251:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7252: 
 7253: # remove version from URL
 7254:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7255: 
 7256: # remove wrapper
 7257: 
 7258:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7259:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7260:     return $symb;
 7261: }
 7262: 
 7263: # ---------------------------------------------- Split symb to find map and url
 7264: 
 7265: sub encode_symb {
 7266:     my ($map,$resid,$url)=@_;
 7267:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7268: }
 7269: 
 7270: sub decode_symb {
 7271:     my $symb=shift;
 7272:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7273:     my ($map,$resid,$url)=split(/___/,$symb);
 7274:     return (&fixversion($map),$resid,&fixversion($url));
 7275: }
 7276: 
 7277: sub fixversion {
 7278:     my $fn=shift;
 7279:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7280:     my %bighash;
 7281:     my $uri=&clutter($fn);
 7282:     my $key=$env{'request.course.id'}.'_'.$uri;
 7283: # is this cached?
 7284:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7285:     if (defined($cached)) { return $result; }
 7286: # unfortunately not cached, or expired
 7287:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7288: 	    &GDBM_READER(),0640)) {
 7289:  	if ($bighash{'version_'.$uri}) {
 7290:  	    my $version=$bighash{'version_'.$uri};
 7291:  	    unless (($version eq 'mostrecent') || 
 7292: 		    ($version==&getversion($uri))) {
 7293:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7294:  	    }
 7295:  	}
 7296:  	untie %bighash;
 7297:     }
 7298:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7299: }
 7300: 
 7301: sub deversion {
 7302:     my $url=shift;
 7303:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7304:     return $url;
 7305: }
 7306: 
 7307: # ------------------------------------------------------ Return symb list entry
 7308: 
 7309: sub symbread {
 7310:     my ($thisfn,$donotrecurse)=@_;
 7311:     my $cache_str='request.symbread.cached.'.$thisfn;
 7312:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7313: # no filename provided? try from environment
 7314:     unless ($thisfn) {
 7315:         if ($env{'request.symb'}) {
 7316: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7317: 	}
 7318: 	$thisfn=$env{'request.filename'};
 7319:     }
 7320:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7321: # is that filename actually a symb? Verify, clean, and return
 7322:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7323: 	if (&symbverify($thisfn,$1)) {
 7324: 	    return $env{$cache_str}=&symbclean($thisfn);
 7325: 	}
 7326:     }
 7327:     $thisfn=declutter($thisfn);
 7328:     my %hash;
 7329:     my %bighash;
 7330:     my $syval='';
 7331:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7332:         my $targetfn = $thisfn;
 7333:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7334:             $targetfn = 'adm/wrapper/'.$thisfn;
 7335:         }
 7336: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7337: 	    $targetfn=$1;
 7338: 	}
 7339:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7340:                       &GDBM_READER(),0640)) {
 7341: 	    $syval=$hash{$targetfn};
 7342:             untie(%hash);
 7343:         }
 7344: # ---------------------------------------------------------- There was an entry
 7345:         if ($syval) {
 7346: 	    #unless ($syval=~/\_\d+$/) {
 7347: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7348: 		    #&appenv('request.ambiguous' => $thisfn);
 7349: 		    #return $env{$cache_str}='';
 7350: 		#}    
 7351: 		#$syval.=$1;
 7352: 	    #}
 7353:         } else {
 7354: # ------------------------------------------------------- Was not in symb table
 7355:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7356:                             &GDBM_READER(),0640)) {
 7357: # ---------------------------------------------- Get ID(s) for current resource
 7358:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7359:               unless ($ids) { 
 7360:                  $ids=$bighash{'ids_/'.$thisfn};
 7361:               }
 7362:               unless ($ids) {
 7363: # alias?
 7364: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7365:               }
 7366:               if ($ids) {
 7367: # ------------------------------------------------------------------- Has ID(s)
 7368:                  my @possibilities=split(/\,/,$ids);
 7369:                  if ($#possibilities==0) {
 7370: # ----------------------------------------------- There is only one possibility
 7371: 		     my ($mapid,$resid)=split(/\./,$ids);
 7372: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7373: 						    $resid,$thisfn);
 7374:                  } elsif (!$donotrecurse) {
 7375: # ------------------------------------------ There is more than one possibility
 7376:                      my $realpossible=0;
 7377:                      foreach my $id (@possibilities) {
 7378: 			 my $file=$bighash{'src_'.$id};
 7379:                          if (&allowed('bre',$file)) {
 7380:          		    my ($mapid,$resid)=split(/\./,$id);
 7381:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7382: 				$realpossible++;
 7383:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7384: 						    $resid,$thisfn);
 7385:                             }
 7386: 			 }
 7387:                      }
 7388: 		     if ($realpossible!=1) { $syval=''; }
 7389:                  } else {
 7390:                      $syval='';
 7391:                  }
 7392: 	      }
 7393:               untie(%bighash)
 7394:            }
 7395:         }
 7396:         if ($syval) {
 7397: 	    return $env{$cache_str}=$syval;
 7398:         }
 7399:     }
 7400:     &appenv('request.ambiguous' => $thisfn);
 7401:     return $env{$cache_str}='';
 7402: }
 7403: 
 7404: # ---------------------------------------------------------- Return random seed
 7405: 
 7406: sub numval {
 7407:     my $txt=shift;
 7408:     $txt=~tr/A-J/0-9/;
 7409:     $txt=~tr/a-j/0-9/;
 7410:     $txt=~tr/K-T/0-9/;
 7411:     $txt=~tr/k-t/0-9/;
 7412:     $txt=~tr/U-Z/0-5/;
 7413:     $txt=~tr/u-z/0-5/;
 7414:     $txt=~s/\D//g;
 7415:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7416:     return int($txt);
 7417: }
 7418: 
 7419: sub numval2 {
 7420:     my $txt=shift;
 7421:     $txt=~tr/A-J/0-9/;
 7422:     $txt=~tr/a-j/0-9/;
 7423:     $txt=~tr/K-T/0-9/;
 7424:     $txt=~tr/k-t/0-9/;
 7425:     $txt=~tr/U-Z/0-5/;
 7426:     $txt=~tr/u-z/0-5/;
 7427:     $txt=~s/\D//g;
 7428:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7429:     my $total;
 7430:     foreach my $val (@txts) { $total+=$val; }
 7431:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7432:     return int($total);
 7433: }
 7434: 
 7435: sub numval3 {
 7436:     use integer;
 7437:     my $txt=shift;
 7438:     $txt=~tr/A-J/0-9/;
 7439:     $txt=~tr/a-j/0-9/;
 7440:     $txt=~tr/K-T/0-9/;
 7441:     $txt=~tr/k-t/0-9/;
 7442:     $txt=~tr/U-Z/0-5/;
 7443:     $txt=~tr/u-z/0-5/;
 7444:     $txt=~s/\D//g;
 7445:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7446:     my $total;
 7447:     foreach my $val (@txts) { $total+=$val; }
 7448:     if ($_64bit) { $total=(($total<<32)>>32); }
 7449:     return $total;
 7450: }
 7451: 
 7452: sub digest {
 7453:     my ($data)=@_;
 7454:     my $digest=&Digest::MD5::md5($data);
 7455:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7456:     my ($e,$f);
 7457:     {
 7458:         use integer;
 7459:         $e=($a+$b);
 7460:         $f=($c+$d);
 7461:         if ($_64bit) {
 7462:             $e=(($e<<32)>>32);
 7463:             $f=(($f<<32)>>32);
 7464:         }
 7465:     }
 7466:     if (wantarray) {
 7467: 	return ($e,$f);
 7468:     } else {
 7469: 	my $g;
 7470: 	{
 7471: 	    use integer;
 7472: 	    $g=($e+$f);
 7473: 	    if ($_64bit) {
 7474: 		$g=(($g<<32)>>32);
 7475: 	    }
 7476: 	}
 7477: 	return $g;
 7478:     }
 7479: }
 7480: 
 7481: sub latest_rnd_algorithm_id {
 7482:     return '64bit5';
 7483: }
 7484: 
 7485: sub get_rand_alg {
 7486:     my ($courseid)=@_;
 7487:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7488:     if ($courseid) {
 7489: 	return $env{"course.$courseid.rndseed"};
 7490:     }
 7491:     return &latest_rnd_algorithm_id();
 7492: }
 7493: 
 7494: sub validCODE {
 7495:     my ($CODE)=@_;
 7496:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7497:     return 0;
 7498: }
 7499: 
 7500: sub getCODE {
 7501:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7502:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7503: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7504: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7505: 	return $Apache::lonhomework::history{'resource.CODE'};
 7506:     }
 7507:     return undef;
 7508: }
 7509: 
 7510: sub rndseed {
 7511:     my ($symb,$courseid,$domain,$username)=@_;
 7512:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7513:     if (!defined($symb)) {
 7514: 	unless ($symb=$wsymb) { return time; }
 7515:     }
 7516:     if (!$courseid) { $courseid=$wcourseid; }
 7517:     if (!$domain) { $domain=$wdomain; }
 7518:     if (!$username) { $username=$wusername }
 7519:     my $which=&get_rand_alg();
 7520: 
 7521:     if (defined(&getCODE())) {
 7522: 	if ($which eq '64bit5') {
 7523: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7524: 	} elsif ($which eq '64bit4') {
 7525: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7526: 	} else {
 7527: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7528: 	}
 7529:     } elsif ($which eq '64bit5') {
 7530: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7531:     } elsif ($which eq '64bit4') {
 7532: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7533:     } elsif ($which eq '64bit3') {
 7534: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7535:     } elsif ($which eq '64bit2') {
 7536: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7537:     } elsif ($which eq '64bit') {
 7538: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7539:     }
 7540:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7541: }
 7542: 
 7543: sub rndseed_32bit {
 7544:     my ($symb,$courseid,$domain,$username)=@_;
 7545:     {
 7546: 	use integer;
 7547: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7548: 	my $symbseed=numval($symb) << 22;
 7549: 	my $namechck=unpack("%32C*",$username) << 17;
 7550: 	my $nameseed=numval($username) << 12;
 7551: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7552: 	my $courseseed=unpack("%32C*",$courseid);
 7553: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7554: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7555: 	#&logthis("rndseed :$num:$symb");
 7556: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7557: 	return $num;
 7558:     }
 7559: }
 7560: 
 7561: sub rndseed_64bit {
 7562:     my ($symb,$courseid,$domain,$username)=@_;
 7563:     {
 7564: 	use integer;
 7565: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7566: 	my $symbseed=numval($symb) << 10;
 7567: 	my $namechck=unpack("%32S*",$username);
 7568: 	
 7569: 	my $nameseed=numval($username) << 21;
 7570: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7571: 	my $courseseed=unpack("%32S*",$courseid);
 7572: 	
 7573: 	my $num1=$symbchck+$symbseed+$namechck;
 7574: 	my $num2=$nameseed+$domainseed+$courseseed;
 7575: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7576: 	#&logthis("rndseed :$num:$symb");
 7577: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7578: 	return "$num1,$num2";
 7579:     }
 7580: }
 7581: 
 7582: sub rndseed_64bit2 {
 7583:     my ($symb,$courseid,$domain,$username)=@_;
 7584:     {
 7585: 	use integer;
 7586: 	# strings need to be an even # of cahracters long, it it is odd the
 7587:         # last characters gets thrown away
 7588: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7589: 	my $symbseed=numval($symb) << 10;
 7590: 	my $namechck=unpack("%32S*",$username.' ');
 7591: 	
 7592: 	my $nameseed=numval($username) << 21;
 7593: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7594: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7595: 	
 7596: 	my $num1=$symbchck+$symbseed+$namechck;
 7597: 	my $num2=$nameseed+$domainseed+$courseseed;
 7598: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7599: 	#&logthis("rndseed :$num:$symb");
 7600: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7601: 	return "$num1,$num2";
 7602:     }
 7603: }
 7604: 
 7605: sub rndseed_64bit3 {
 7606:     my ($symb,$courseid,$domain,$username)=@_;
 7607:     {
 7608: 	use integer;
 7609: 	# strings need to be an even # of cahracters long, it it is odd the
 7610:         # last characters gets thrown away
 7611: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7612: 	my $symbseed=numval2($symb) << 10;
 7613: 	my $namechck=unpack("%32S*",$username.' ');
 7614: 	
 7615: 	my $nameseed=numval2($username) << 21;
 7616: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7617: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7618: 	
 7619: 	my $num1=$symbchck+$symbseed+$namechck;
 7620: 	my $num2=$nameseed+$domainseed+$courseseed;
 7621: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7622: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7623: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7624: 	
 7625: 	return "$num1:$num2";
 7626:     }
 7627: }
 7628: 
 7629: sub rndseed_64bit4 {
 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=numval3($symb) << 10;
 7637: 	my $namechck=unpack("%32S*",$username.' ');
 7638: 	
 7639: 	my $nameseed=numval3($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_64bit5 {
 7654:     my ($symb,$courseid,$domain,$username)=@_;
 7655:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7656:     return "$num1:$num2";
 7657: }
 7658: 
 7659: sub rndseed_CODE_64bit {
 7660:     my ($symb,$courseid,$domain,$username)=@_;
 7661:     {
 7662: 	use integer;
 7663: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7664: 	my $symbseed=numval2($symb);
 7665: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7666: 	my $CODEseed=numval(&getCODE());
 7667: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7668: 	my $num1=$symbseed+$CODEchck;
 7669: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7670: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7671: 	#&logthis("rndseed :$num1:$num2:$symb");
 7672: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7673: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7674: 	return "$num1:$num2";
 7675:     }
 7676: }
 7677: 
 7678: sub rndseed_CODE_64bit4 {
 7679:     my ($symb,$courseid,$domain,$username)=@_;
 7680:     {
 7681: 	use integer;
 7682: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7683: 	my $symbseed=numval3($symb);
 7684: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7685: 	my $CODEseed=numval3(&getCODE());
 7686: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7687: 	my $num1=$symbseed+$CODEchck;
 7688: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7689: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7690: 	#&logthis("rndseed :$num1:$num2:$symb");
 7691: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7692: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7693: 	return "$num1:$num2";
 7694:     }
 7695: }
 7696: 
 7697: sub rndseed_CODE_64bit5 {
 7698:     my ($symb,$courseid,$domain,$username)=@_;
 7699:     my $code = &getCODE();
 7700:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7701:     return "$num1:$num2";
 7702: }
 7703: 
 7704: sub setup_random_from_rndseed {
 7705:     my ($rndseed)=@_;
 7706:     if ($rndseed =~/([,:])/) {
 7707: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7708: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7709:     } else {
 7710: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7711:     }
 7712: }
 7713: 
 7714: sub latest_receipt_algorithm_id {
 7715:     return 'receipt3';
 7716: }
 7717: 
 7718: sub recunique {
 7719:     my $fucourseid=shift;
 7720:     my $unique;
 7721:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7722: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7723: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7724:     } else {
 7725: 	$unique=$perlvar{'lonReceipt'};
 7726:     }
 7727:     return unpack("%32C*",$unique);
 7728: }
 7729: 
 7730: sub recprefix {
 7731:     my $fucourseid=shift;
 7732:     my $prefix;
 7733:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7734: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7735: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7736:     } else {
 7737: 	$prefix=$perlvar{'lonHostID'};
 7738:     }
 7739:     return unpack("%32C*",$prefix);
 7740: }
 7741: 
 7742: sub ireceipt {
 7743:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7744: 
 7745:     my $return =&recprefix($fucourseid).'-';
 7746: 
 7747:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7748: 	$env{'request.state'} eq 'construct') {
 7749: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7750: 	return $return;
 7751:     }
 7752: 
 7753:     my $cuname=unpack("%32C*",$funame);
 7754:     my $cudom=unpack("%32C*",$fudom);
 7755:     my $cucourseid=unpack("%32C*",$fucourseid);
 7756:     my $cusymb=unpack("%32C*",$fusymb);
 7757:     my $cunique=&recunique($fucourseid);
 7758:     my $cpart=unpack("%32S*",$part);
 7759:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7760: 
 7761: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7762: 			       
 7763: 	$return.= ($cunique%$cuname+
 7764: 		   $cunique%$cudom+
 7765: 		   $cusymb%$cuname+
 7766: 		   $cusymb%$cudom+
 7767: 		   $cucourseid%$cuname+
 7768: 		   $cucourseid%$cudom+
 7769: 		   $cpart%$cuname+
 7770: 		   $cpart%$cudom);
 7771:     } else {
 7772: 	$return.= ($cunique%$cuname+
 7773: 		   $cunique%$cudom+
 7774: 		   $cusymb%$cuname+
 7775: 		   $cusymb%$cudom+
 7776: 		   $cucourseid%$cuname+
 7777: 		   $cucourseid%$cudom);
 7778:     }
 7779:     return $return;
 7780: }
 7781: 
 7782: sub receipt {
 7783:     my ($part)=@_;
 7784:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7785:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7786: }
 7787: 
 7788: sub whichuser {
 7789:     my ($passedsymb)=@_;
 7790:     my ($symb,$courseid,$domain,$name,$publicuser);
 7791:     if (defined($env{'form.grade_symb'})) {
 7792: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7793: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7794: 	if (!$allowed &&
 7795: 	    exists($env{'request.course.sec'}) &&
 7796: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7797: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7798: 			      '/'.$env{'request.course.sec'});
 7799: 	}
 7800: 	if ($allowed) {
 7801: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7802: 	    $courseid=$tmp_courseid;
 7803: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7804: 	    ($name)=&get_env_multiple('form.grade_username');
 7805: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7806: 	}
 7807:     }
 7808:     if (!$passedsymb) {
 7809: 	$symb=&symbread();
 7810:     } else {
 7811: 	$symb=$passedsymb;
 7812:     }
 7813:     $courseid=$env{'request.course.id'};
 7814:     $domain=$env{'user.domain'};
 7815:     $name=$env{'user.name'};
 7816:     if ($name eq 'public' && $domain eq 'public') {
 7817: 	if (!defined($env{'form.username'})) {
 7818: 	    $env{'form.username'}.=time.rand(10000000);
 7819: 	}
 7820: 	$name.=$env{'form.username'};
 7821:     }
 7822:     return ($symb,$courseid,$domain,$name,$publicuser);
 7823: 
 7824: }
 7825: 
 7826: # ------------------------------------------------------------ Serves up a file
 7827: # returns either the contents of the file or 
 7828: # -1 if the file doesn't exist
 7829: #
 7830: # if the target is a file that was uploaded via DOCS, 
 7831: # a check will be made to see if a current copy exists on the local server,
 7832: # if it does this will be served, otherwise a copy will be retrieved from
 7833: # the home server for the course and stored in /home/httpd/html/userfiles on
 7834: # the local server.   
 7835: 
 7836: sub getfile {
 7837:     my ($file) = @_;
 7838:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7839:     &repcopy($file);
 7840:     return &readfile($file);
 7841: }
 7842: 
 7843: sub repcopy_userfile {
 7844:     my ($file)=@_;
 7845:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7846:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7847:     my ($cdom,$cnum,$filename) = 
 7848: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7849:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7850:     if (-e "$file") {
 7851: # we already have a local copy, check it out
 7852: 	my @fileinfo = stat($file);
 7853: 	my $rtncode;
 7854: 	my $info;
 7855: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7856: 	if ($lwpresp ne 'ok') {
 7857: # there is no such file anymore, even though we had a local copy
 7858: 	    if ($rtncode eq '404') {
 7859: 		unlink($file);
 7860: 	    }
 7861: 	    return -1;
 7862: 	}
 7863: 	if ($info < $fileinfo[9]) {
 7864: # nice, the file we have is up-to-date, just say okay
 7865: 	    return 'ok';
 7866: 	} else {
 7867: # the file is outdated, get rid of it
 7868: 	    unlink($file);
 7869: 	}
 7870:     }
 7871: # one way or the other, at this point, we don't have the file
 7872: # construct the correct path for the file
 7873:     my @parts = ($cdom,$cnum); 
 7874:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7875: 	push @parts, split(/\//,$1);
 7876:     }
 7877:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7878:     foreach my $part (@parts) {
 7879: 	$path .= '/'.$part;
 7880: 	if (!-e $path) {
 7881: 	    mkdir($path,0770);
 7882: 	}
 7883:     }
 7884: # now the path exists for sure
 7885: # get a user agent
 7886:     my $ua=new LWP::UserAgent;
 7887:     my $transferfile=$file.'.in.transfer';
 7888: # FIXME: this should flock
 7889:     if (-e $transferfile) { return 'ok'; }
 7890:     my $request;
 7891:     $uri=~s/^\///;
 7892:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7893:     my $response=$ua->request($request,$transferfile);
 7894: # did it work?
 7895:     if ($response->is_error()) {
 7896: 	unlink($transferfile);
 7897: 	&logthis("Userfile repcopy failed for $uri");
 7898: 	return -1;
 7899:     }
 7900: # worked, rename the transfer file
 7901:     rename($transferfile,$file);
 7902:     return 'ok';
 7903: }
 7904: 
 7905: sub tokenwrapper {
 7906:     my $uri=shift;
 7907:     $uri=~s|^http\://([^/]+)||;
 7908:     $uri=~s|^/||;
 7909:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7910:     my $token=$1;
 7911:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7912:     if ($udom && $uname && $file) {
 7913: 	$file=~s|(\?\.*)*$||;
 7914:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7915:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7916:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7917:                                '&tokenissued='.$perlvar{'lonHostID'};
 7918:     } else {
 7919:         return '/adm/notfound.html';
 7920:     }
 7921: }
 7922: 
 7923: # call with reqtype HEAD: get last modification time
 7924: # call with reqtype GET: get the file contents
 7925: # Do not call this with reqtype GET for large files! It loads everything into memory
 7926: #
 7927: sub getuploaded {
 7928:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7929:     $uri=~s/^\///;
 7930:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7931:     my $ua=new LWP::UserAgent;
 7932:     my $request=new HTTP::Request($reqtype,$uri);
 7933:     my $response=$ua->request($request);
 7934:     $$rtncode = $response->code;
 7935:     if (! $response->is_success()) {
 7936: 	return 'failed';
 7937:     }      
 7938:     if ($reqtype eq 'HEAD') {
 7939: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7940:     } elsif ($reqtype eq 'GET') {
 7941: 	$$info = $response->content;
 7942:     }
 7943:     return 'ok';
 7944: }
 7945: 
 7946: sub readfile {
 7947:     my $file = shift;
 7948:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7949:     my $fh;
 7950:     open($fh,"<$file");
 7951:     my $a='';
 7952:     while (my $line = <$fh>) { $a .= $line; }
 7953:     return $a;
 7954: }
 7955: 
 7956: sub filelocation {
 7957:     my ($dir,$file) = @_;
 7958:     my $location;
 7959:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7960: 
 7961:     if ($file =~ m-^/adm/-) {
 7962: 	$file=~s-^/adm/wrapper/-/-;
 7963: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7964:     }
 7965: 
 7966:     if ($file=~m:^/~:) { # is a contruction space reference
 7967:         $location = $file;
 7968:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7969:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7970: 	# is a correct contruction space reference
 7971:         $location = $file;
 7972:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7973:         my ($udom,$uname,$filename)=
 7974:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7975:         my $home=&homeserver($uname,$udom);
 7976:         my $is_me=0;
 7977:         my @ids=&current_machine_ids();
 7978:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7979:         if ($is_me) {
 7980:   	    $location=&propath($udom,$uname).
 7981:   	      '/userfiles/'.$filename;
 7982:         } else {
 7983:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7984:   	      $udom.'/'.$uname.'/'.$filename;
 7985:         }
 7986:     } elsif ($file =~ m-^/adm/-) {
 7987: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 7988:     } else {
 7989:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7990:         $file=~s:^/res/:/:;
 7991:         if ( !( $file =~ m:^/:) ) {
 7992:             $location = $dir. '/'.$file;
 7993:         } else {
 7994:             $location = '/home/httpd/html/res'.$file;
 7995:         }
 7996:     }
 7997:     $location=~s://+:/:g; # remove duplicate /
 7998:     while ($location=~m{/\.\./}) {
 7999: 	if ($location =~ m{/[^/]+/\.\./}) {
 8000: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8001: 	} else {
 8002: 	    $location=~ s{/\.\./}{/}g;
 8003: 	}
 8004:     } #remove dir/..
 8005:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8006:     return $location;
 8007: }
 8008: 
 8009: sub hreflocation {
 8010:     my ($dir,$file)=@_;
 8011:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8012: 	$file=filelocation($dir,$file);
 8013:     } elsif ($file=~m-^/adm/-) {
 8014: 	$file=~s-^/adm/wrapper/-/-;
 8015: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8016:     }
 8017:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8018: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8019:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8020: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8021:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8022: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8023: 	    -/uploaded/$1/$2/-x;
 8024:     }
 8025:     if ($file=~ m{^/userfiles/}) {
 8026: 	$file =~ s{^/userfiles/}{/uploaded/};
 8027:     }
 8028:     return $file;
 8029: }
 8030: 
 8031: sub current_machine_domains {
 8032:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8033: }
 8034: 
 8035: sub machine_domains {
 8036:     my ($hostname) = @_;
 8037:     my @domains;
 8038:     my %hostname = &all_hostnames();
 8039:     while( my($id, $name) = each(%hostname)) {
 8040: #	&logthis("-$id-$name-$hostname-");
 8041: 	if ($hostname eq $name) {
 8042: 	    push(@domains,&host_domain($id));
 8043: 	}
 8044:     }
 8045:     return @domains;
 8046: }
 8047: 
 8048: sub current_machine_ids {
 8049:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8050: }
 8051: 
 8052: sub machine_ids {
 8053:     my ($hostname) = @_;
 8054:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8055:     my @ids;
 8056:     my %name_to_host = &all_names();
 8057:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8058: 	return @{ $name_to_host{$hostname} };
 8059:     }
 8060:     return;
 8061: }
 8062: 
 8063: sub additional_machine_domains {
 8064:     my @domains;
 8065:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8066:     while( my $line = <$fh>) {
 8067:         $line =~ s/\s//g;
 8068:         push(@domains,$line);
 8069:     }
 8070:     return @domains;
 8071: }
 8072: 
 8073: sub default_login_domain {
 8074:     my $domain = $perlvar{'lonDefDomain'};
 8075:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8076:     foreach my $posdom (&current_machine_domains(),
 8077:                         &additional_machine_domains()) {
 8078:         if (lc($posdom) eq lc($testdomain)) {
 8079:             $domain=$posdom;
 8080:             last;
 8081:         }
 8082:     }
 8083:     return $domain;
 8084: }
 8085: 
 8086: # ------------------------------------------------------------- Declutters URLs
 8087: 
 8088: sub declutter {
 8089:     my $thisfn=shift;
 8090:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8091:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8092:     $thisfn=~s/^\///;
 8093:     $thisfn=~s|^adm/wrapper/||;
 8094:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8095:     $thisfn=~s/^res\///;
 8096:     $thisfn=~s/\?.+$//;
 8097:     return $thisfn;
 8098: }
 8099: 
 8100: # ------------------------------------------------------------- Clutter up URLs
 8101: 
 8102: sub clutter {
 8103:     my $thisfn='/'.&declutter(shift);
 8104:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8105: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8106:        $thisfn='/res'.$thisfn; 
 8107:     }
 8108:     if ($thisfn !~m|/adm|) {
 8109: 	if ($thisfn =~ m|/ext/|) {
 8110: 	    $thisfn='/adm/wrapper'.$thisfn;
 8111: 	} else {
 8112: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8113: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8114: 	    if ($embstyle eq 'ssi'
 8115: 		|| ($embstyle eq 'hdn')
 8116: 		|| ($embstyle eq 'rat')
 8117: 		|| ($embstyle eq 'prv')
 8118: 		|| ($embstyle eq 'ign')) {
 8119: 		#do nothing with these
 8120: 	    } elsif (($embstyle eq 'img') 
 8121: 		|| ($embstyle eq 'emb')
 8122: 		|| ($embstyle eq 'wrp')) {
 8123: 		$thisfn='/adm/wrapper'.$thisfn;
 8124: 	    } elsif ($embstyle eq 'unk'
 8125: 		     && $thisfn!~/\.(sequence|page)$/) {
 8126: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8127: 	    } else {
 8128: #		&logthis("Got a blank emb style");
 8129: 	    }
 8130: 	}
 8131:     }
 8132:     return $thisfn;
 8133: }
 8134: 
 8135: sub clutter_with_no_wrapper {
 8136:     my $uri = &clutter(shift);
 8137:     if ($uri =~ m-^/adm/-) {
 8138: 	$uri =~ s-^/adm/wrapper/-/-;
 8139: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8140:     }
 8141:     return $uri;
 8142: }
 8143: 
 8144: sub freeze_escape {
 8145:     my ($value)=@_;
 8146:     if (ref($value)) {
 8147: 	$value=&nfreeze($value);
 8148: 	return '__FROZEN__'.&escape($value);
 8149:     }
 8150:     return &escape($value);
 8151: }
 8152: 
 8153: 
 8154: sub thaw_unescape {
 8155:     my ($value)=@_;
 8156:     if ($value =~ /^__FROZEN__/) {
 8157: 	substr($value,0,10,undef);
 8158: 	$value=&unescape($value);
 8159: 	return &thaw($value);
 8160:     }
 8161:     return &unescape($value);
 8162: }
 8163: 
 8164: sub correct_line_ends {
 8165:     my ($result)=@_;
 8166:     $$result =~s/\r\n/\n/mg;
 8167:     $$result =~s/\r/\n/mg;
 8168: }
 8169: # ================================================================ Main Program
 8170: 
 8171: sub goodbye {
 8172:    &logthis("Starting Shut down");
 8173: #not converted to using infrastruture and probably shouldn't be
 8174:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8175: #converted
 8176: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8177:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8178: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8179: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8180: #1.1 only
 8181: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8182: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8183: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8184: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8185:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8186:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8187:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8188:    &flushcourselogs();
 8189:    &logthis("Shutting down");
 8190: }
 8191: 
 8192: sub get_dns {
 8193:     my ($url,$func,$ignore_cache) = @_;
 8194:     if (!$ignore_cache) {
 8195: 	my ($content,$cached)=
 8196: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8197: 	if ($cached) {
 8198: 	    &$func($content);
 8199: 	    return;
 8200: 	}
 8201:     }
 8202: 
 8203:     my %alldns;
 8204:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8205:     foreach my $dns (<$config>) {
 8206: 	next if ($dns !~ /^\^(\S*)/x);
 8207: 	$alldns{$1} = 1;
 8208:     }
 8209:     while (%alldns) {
 8210: 	my ($dns) = keys(%alldns);
 8211: 	delete($alldns{$dns});
 8212: 	my $ua=new LWP::UserAgent;
 8213: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8214: 	my $response=$ua->request($request);
 8215: 	next if ($response->is_error());
 8216: 	my @content = split("\n",$response->content);
 8217: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8218: 	&$func(\@content);
 8219: 	return;
 8220:     }
 8221:     close($config);
 8222:     my $which = (split('/',$url))[3];
 8223:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8224:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8225:     my @content = <$config>;
 8226:     &$func(\@content);
 8227:     return;
 8228: }
 8229: # ------------------------------------------------------------ Read domain file
 8230: {
 8231:     my $loaded;
 8232:     my %domain;
 8233: 
 8234:     sub parse_domain_tab {
 8235: 	my ($lines) = @_;
 8236: 	foreach my $line (@$lines) {
 8237: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8238: 
 8239: 	    chomp($line);
 8240: 	    my ($name,@elements) = split(/:/,$line,9);
 8241: 	    my %this_domain;
 8242: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8243: 			       'lang_def', 'city', 'longi', 'lati',
 8244: 			       'primary') {
 8245: 		$this_domain{$field} = shift(@elements);
 8246: 	    }
 8247: 	    $domain{$name} = \%this_domain;
 8248: 	}
 8249:     }
 8250: 
 8251:     sub reset_domain_info {
 8252: 	undef($loaded);
 8253: 	undef(%domain);
 8254:     }
 8255: 
 8256:     sub load_domain_tab {
 8257: 	my ($ignore_cache) = @_;
 8258: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8259: 	my $fh;
 8260: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8261: 	    my @lines = <$fh>;
 8262: 	    &parse_domain_tab(\@lines);
 8263: 	}
 8264: 	close($fh);
 8265: 	$loaded = 1;
 8266:     }
 8267: 
 8268:     sub domain {
 8269: 	&load_domain_tab() if (!$loaded);
 8270: 
 8271: 	my ($name,$what) = @_;
 8272: 	return if ( !exists($domain{$name}) );
 8273: 
 8274: 	if (!$what) {
 8275: 	    return $domain{$name}{'description'};
 8276: 	}
 8277: 	return $domain{$name}{$what};
 8278:     }
 8279: }
 8280: 
 8281: 
 8282: # ------------------------------------------------------------- Read hosts file
 8283: {
 8284:     my %hostname;
 8285:     my %hostdom;
 8286:     my %libserv;
 8287:     my $loaded;
 8288:     my %name_to_host;
 8289: 
 8290:     sub parse_hosts_tab {
 8291: 	my ($file) = @_;
 8292: 	foreach my $configline (@$file) {
 8293: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8294: 	    next if ($configline =~ /^\^/);
 8295: 	    chomp($configline);
 8296: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8297: 	    $name=~s/\s//g;
 8298: 	    if ($id && $domain && $role && $name) {
 8299: 		$hostname{$id}=$name;
 8300: 		push(@{$name_to_host{$name}}, $id);
 8301: 		$hostdom{$id}=$domain;
 8302: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8303: 	    }
 8304: 	}
 8305:     }
 8306:     
 8307:     sub reset_hosts_info {
 8308: 	&purge_remembered();
 8309: 	&reset_domain_info();
 8310: 	&reset_hosts_ip_info();
 8311: 	undef(%name_to_host);
 8312: 	undef(%hostname);
 8313: 	undef(%hostdom);
 8314: 	undef(%libserv);
 8315: 	undef($loaded);
 8316:     }
 8317: 
 8318:     sub load_hosts_tab {
 8319: 	my ($ignore_cache) = @_;
 8320: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8321: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8322: 	my @config = <$config>;
 8323: 	&parse_hosts_tab(\@config);
 8324: 	close($config);
 8325: 	$loaded=1;
 8326:     }
 8327: 
 8328:     sub hostname {
 8329: 	&load_hosts_tab() if (!$loaded);
 8330: 
 8331: 	my ($lonid) = @_;
 8332: 	return $hostname{$lonid};
 8333:     }
 8334: 
 8335:     sub all_hostnames {
 8336: 	&load_hosts_tab() if (!$loaded);
 8337: 
 8338: 	return %hostname;
 8339:     }
 8340: 
 8341:     sub all_names {
 8342: 	&load_hosts_tab() if (!$loaded);
 8343: 
 8344: 	return %name_to_host;
 8345:     }
 8346: 
 8347:     sub is_library {
 8348: 	&load_hosts_tab() if (!$loaded);
 8349: 
 8350: 	return exists($libserv{$_[0]});
 8351:     }
 8352: 
 8353:     sub all_library {
 8354: 	&load_hosts_tab() if (!$loaded);
 8355: 
 8356: 	return %libserv;
 8357:     }
 8358: 
 8359:     sub get_servers {
 8360: 	&load_hosts_tab() if (!$loaded);
 8361: 
 8362: 	my ($domain,$type) = @_;
 8363: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8364: 	                                          : %hostname;
 8365: 	my %result;
 8366: 	if (ref($domain) eq 'ARRAY') {
 8367: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8368: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8369: 		    $result{$host} = $hostname;
 8370: 		}
 8371: 	    }
 8372: 	} else {
 8373: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8374: 		if ($hostdom{$host} eq $domain) {
 8375: 		    $result{$host} = $hostname;
 8376: 		}
 8377: 	    }
 8378: 	}
 8379: 	return %result;
 8380:     }
 8381: 
 8382:     sub host_domain {
 8383: 	&load_hosts_tab() if (!$loaded);
 8384: 
 8385: 	my ($lonid) = @_;
 8386: 	return $hostdom{$lonid};
 8387:     }
 8388: 
 8389:     sub all_domains {
 8390: 	&load_hosts_tab() if (!$loaded);
 8391: 
 8392: 	my %seen;
 8393: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8394: 	return @uniq;
 8395:     }
 8396: }
 8397: 
 8398: { 
 8399:     my %iphost;
 8400:     my %name_to_ip;
 8401:     my %lonid_to_ip;
 8402: 
 8403:     sub get_hosts_from_ip {
 8404: 	my ($ip) = @_;
 8405: 	my %iphosts = &get_iphost();
 8406: 	if (ref($iphosts{$ip})) {
 8407: 	    return @{$iphosts{$ip}};
 8408: 	}
 8409: 	return;
 8410:     }
 8411:     
 8412:     sub reset_hosts_ip_info {
 8413: 	undef(%iphost);
 8414: 	undef(%name_to_ip);
 8415: 	undef(%lonid_to_ip);
 8416:     }
 8417: 
 8418:     sub get_host_ip {
 8419: 	my ($lonid) = @_;
 8420: 	if (exists($lonid_to_ip{$lonid})) {
 8421: 	    return $lonid_to_ip{$lonid};
 8422: 	}
 8423: 	my $name=&hostname($lonid);
 8424:    	my $ip = gethostbyname($name);
 8425: 	return if (!$ip || length($ip) ne 4);
 8426: 	$ip=inet_ntoa($ip);
 8427: 	$name_to_ip{$name}   = $ip;
 8428: 	$lonid_to_ip{$lonid} = $ip;
 8429: 	return $ip;
 8430:     }
 8431:     
 8432:     sub get_iphost {
 8433: 	my ($ignore_cache) = @_;
 8434: 
 8435: 	if (!$ignore_cache) {
 8436: 	    if (%iphost) {
 8437: 		return %iphost;
 8438: 	    }
 8439: 	    my ($ip_info,$cached)=
 8440: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8441: 	    if ($cached) {
 8442: 		%iphost      = %{$ip_info->[0]};
 8443: 		%name_to_ip  = %{$ip_info->[1]};
 8444: 		%lonid_to_ip = %{$ip_info->[2]};
 8445: 		return %iphost;
 8446: 	    }
 8447: 	}
 8448: 
 8449: 	# get yesterday's info for fallback
 8450: 	my %old_name_to_ip;
 8451: 	my ($ip_info,$cached)=
 8452: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8453: 	if ($cached) {
 8454: 	    %old_name_to_ip = %{$ip_info->[1]};
 8455: 	}
 8456: 
 8457: 	my %name_to_host = &all_names();
 8458: 	foreach my $name (keys(%name_to_host)) {
 8459: 	    my $ip;
 8460: 	    if (!exists($name_to_ip{$name})) {
 8461: 		$ip = gethostbyname($name);
 8462: 		if (!$ip || length($ip) ne 4) {
 8463: 		    if (defined($old_name_to_ip{$name})) {
 8464: 			$ip = $old_name_to_ip{$name};
 8465: 			&logthis("Can't find $name defaulting to old $ip");
 8466: 		    } else {
 8467: 			&logthis("Name $name no IP found");
 8468: 			next;
 8469: 		    }
 8470: 		} else {
 8471: 		    $ip=inet_ntoa($ip);
 8472: 		}
 8473: 		$name_to_ip{$name} = $ip;
 8474: 	    } else {
 8475: 		$ip = $name_to_ip{$name};
 8476: 	    }
 8477: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8478: 		$lonid_to_ip{$id} = $ip;
 8479: 	    }
 8480: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8481: 	}
 8482: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8483: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8484: 				      48*60*60);
 8485: 
 8486: 	return %iphost;
 8487:     }
 8488: }
 8489: 
 8490: BEGIN {
 8491: 
 8492: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8493:     unless ($readit) {
 8494: {
 8495:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8496:     %perlvar = (%perlvar,%{$configvars});
 8497: }
 8498: 
 8499: 
 8500: # ------------------------------------------------------ Read spare server file
 8501: {
 8502:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8503: 
 8504:     while (my $configline=<$config>) {
 8505:        chomp($configline);
 8506:        if ($configline) {
 8507: 	   my ($host,$type) = split(':',$configline,2);
 8508: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8509: 	   push(@{ $spareid{$type} }, $host);
 8510:        }
 8511:     }
 8512:     close($config);
 8513: }
 8514: # ------------------------------------------------------------ Read permissions
 8515: {
 8516:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8517: 
 8518:     while (my $configline=<$config>) {
 8519: 	chomp($configline);
 8520: 	if ($configline) {
 8521: 	    my ($role,$perm)=split(/ /,$configline);
 8522: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8523: 	}
 8524:     }
 8525:     close($config);
 8526: }
 8527: 
 8528: # -------------------------------------------- Read plain texts for permissions
 8529: {
 8530:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8531: 
 8532:     while (my $configline=<$config>) {
 8533: 	chomp($configline);
 8534: 	if ($configline) {
 8535: 	    my ($short,@plain)=split(/:/,$configline);
 8536:             %{$prp{$short}} = ();
 8537: 	    if (@plain > 0) {
 8538:                 $prp{$short}{'std'} = $plain[0];
 8539:                 for (my $i=1; $i<@plain; $i++) {
 8540:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8541:                 }
 8542:             }
 8543: 	}
 8544:     }
 8545:     close($config);
 8546: }
 8547: 
 8548: # ---------------------------------------------------------- Read package table
 8549: {
 8550:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8551: 
 8552:     while (my $configline=<$config>) {
 8553: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8554: 	chomp($configline);
 8555: 	my ($short,$plain)=split(/:/,$configline);
 8556: 	my ($pack,$name)=split(/\&/,$short);
 8557: 	if ($plain ne '') {
 8558: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8559: 	    $packagetab{$short}=$plain; 
 8560: 	}
 8561:     }
 8562:     close($config);
 8563: }
 8564: 
 8565: # ------------- set up temporary directory
 8566: {
 8567:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8568: 
 8569: }
 8570: 
 8571: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8572: 				'compress_threshold'=> 20_000,
 8573:  			        });
 8574: 
 8575: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8576: $dumpcount=0;
 8577: 
 8578: &logtouch();
 8579: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8580: $readit=1;
 8581:     {
 8582: 	use integer;
 8583: 	my $test=(2**32)+1;
 8584: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8585: 	&logthis(" Detected 64bit platform ($_64bit)");
 8586:     }
 8587: }
 8588: }
 8589: 
 8590: 1;
 8591: __END__
 8592: 
 8593: =pod
 8594: 
 8595: =head1 NAME
 8596: 
 8597: Apache::lonnet - Subroutines to ask questions about things in the network.
 8598: 
 8599: =head1 SYNOPSIS
 8600: 
 8601: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8602: 
 8603:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8604: 
 8605: Common parameters:
 8606: 
 8607: =over 4
 8608: 
 8609: =item *
 8610: 
 8611: $uname : an internal username (if $cname expecting a course Id specifically)
 8612: 
 8613: =item *
 8614: 
 8615: $udom : a domain (if $cdom expecting a course's domain specifically)
 8616: 
 8617: =item *
 8618: 
 8619: $symb : a resource instance identifier
 8620: 
 8621: =item *
 8622: 
 8623: $namespace : the name of a .db file that contains the data needed or
 8624: being set.
 8625: 
 8626: =back
 8627: 
 8628: =head1 OVERVIEW
 8629: 
 8630: lonnet provides subroutines which interact with the
 8631: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8632: about classes, users, and resources.
 8633: 
 8634: For many of these objects you can also use this to store data about
 8635: them or modify them in various ways.
 8636: 
 8637: =head2 Symbs
 8638: 
 8639: To identify a specific instance of a resource, LON-CAPA uses symbols
 8640: or "symbs"X<symb>. These identifiers are built from the URL of the
 8641: map, the resource number of the resource in the map, and the URL of
 8642: the resource itself. The latter is somewhat redundant, but might help
 8643: if maps change.
 8644: 
 8645: An example is
 8646: 
 8647:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8648: 
 8649: The respective map entry is
 8650: 
 8651:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8652:   title="Problem 2">
 8653:  </resource>
 8654: 
 8655: Symbs are used by the random number generator, as well as to store and
 8656: restore data specific to a certain instance of for example a problem.
 8657: 
 8658: =head2 Storing And Retrieving Data
 8659: 
 8660: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8661: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8662: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8663: is is the non-critical message twin of cstore. These functions are for
 8664: handlers to store a perl hash to a user's permanent data space in an
 8665: easy manner, and to retrieve it again on another call. It is expected
 8666: that a handler would use this once at the beginning to retrieve data,
 8667: and then again once at the end to send only the new data back.
 8668: 
 8669: The data is stored in the user's data directory on the user's
 8670: homeserver under the ID of the course.
 8671: 
 8672: The hash that is returned by restore will have all of the previous
 8673: value for all of the elements of the hash.
 8674: 
 8675: Example:
 8676: 
 8677:  #creating a hash
 8678:  my %hash;
 8679:  $hash{'foo'}='bar';
 8680: 
 8681:  #storing it
 8682:  &Apache::lonnet::cstore(\%hash);
 8683: 
 8684:  #changing a value
 8685:  $hash{'foo'}='notbar';
 8686: 
 8687:  #adding a new value
 8688:  $hash{'bar'}='foo';
 8689:  &Apache::lonnet::cstore(\%hash);
 8690: 
 8691:  #retrieving the hash
 8692:  my %history=&Apache::lonnet::restore();
 8693: 
 8694:  #print the hash
 8695:  foreach my $key (sort(keys(%history))) {
 8696:    print("\%history{$key} = $history{$key}");
 8697:  }
 8698: 
 8699: Will print out:
 8700: 
 8701:  %history{1:foo} = bar
 8702:  %history{1:keys} = foo:timestamp
 8703:  %history{1:timestamp} = 990455579
 8704:  %history{2:bar} = foo
 8705:  %history{2:foo} = notbar
 8706:  %history{2:keys} = foo:bar:timestamp
 8707:  %history{2:timestamp} = 990455580
 8708:  %history{bar} = foo
 8709:  %history{foo} = notbar
 8710:  %history{timestamp} = 990455580
 8711:  %history{version} = 2
 8712: 
 8713: Note that the special hash entries C<keys>, C<version> and
 8714: C<timestamp> were added to the hash. C<version> will be equal to the
 8715: total number of versions of the data that have been stored. The
 8716: C<timestamp> attribute will be the UNIX time the hash was
 8717: stored. C<keys> is available in every historical section to list which
 8718: keys were added or changed at a specific historical revision of a
 8719: hash.
 8720: 
 8721: B<Warning>: do not store the hash that restore returns directly. This
 8722: will cause a mess since it will restore the historical keys as if the
 8723: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8724: 
 8725: Calling convention:
 8726: 
 8727:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8728:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8729: 
 8730: For more detailed information, see lonnet specific documentation.
 8731: 
 8732: =head1 RETURN MESSAGES
 8733: 
 8734: =over 4
 8735: 
 8736: =item * B<con_lost>: unable to contact remote host
 8737: 
 8738: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8739: when the connection is brought back up
 8740: 
 8741: =item * B<con_failed>: unable to contact remote host and unable to save message
 8742: for later delivery
 8743: 
 8744: =item * B<error:>: an error a occured, a description of the error follows the :
 8745: 
 8746: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8747: that was requested
 8748: 
 8749: =back
 8750: 
 8751: =head1 PUBLIC SUBROUTINES
 8752: 
 8753: =head2 Session Environment Functions
 8754: 
 8755: =over 4
 8756: 
 8757: =item * 
 8758: X<appenv()>
 8759: B<appenv(%hash)>: the value of %hash is written to
 8760: the user envirnoment file, and will be restored for each access this
 8761: user makes during this session, also modifies the %env for the current
 8762: process
 8763: 
 8764: =item *
 8765: X<delenv()>
 8766: B<delenv($regexp)>: removes all items from the session
 8767: environment file that matches the regular expression in $regexp. The
 8768: values are also delted from the current processes %env.
 8769: 
 8770: =item * get_env_multiple($name) 
 8771: 
 8772: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8773: values may be defined and end up as an array ref.
 8774: 
 8775: returns an array of values
 8776: 
 8777: =back
 8778: 
 8779: =head2 User Information
 8780: 
 8781: =over 4
 8782: 
 8783: =item *
 8784: X<queryauthenticate()>
 8785: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8786: authentication scheme
 8787: 
 8788: =item *
 8789: X<authenticate()>
 8790: B<authenticate($uname,$upass,$udom)>: try to
 8791: authenticate user from domain's lib servers (first use the current
 8792: one). C<$upass> should be the users password.
 8793: 
 8794: =item *
 8795: X<homeserver()>
 8796: B<homeserver($uname,$udom)>: find the server which has
 8797: the user's directory and files (there must be only one), this caches
 8798: the answer, and also caches if there is a borken connection.
 8799: 
 8800: =item *
 8801: X<idget()>
 8802: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8803: (IDs are a unique resource in a domain, there must be only 1 ID per
 8804: username, and only 1 username per ID in a specific domain) (returns
 8805: hash: id=>name,id=>name)
 8806: 
 8807: =item *
 8808: X<idrget()>
 8809: B<idrget($udom,@unames)>: find the IDs behind a list of
 8810: usernames (returns hash: name=>id,name=>id)
 8811: 
 8812: =item *
 8813: X<idput()>
 8814: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8815: 
 8816: =item *
 8817: X<rolesinit()>
 8818: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8819: 
 8820: =item *
 8821: X<getsection()>
 8822: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8823: course $cname, return section name/number or '' for "not in course"
 8824: and '-1' for "no section"
 8825: 
 8826: =item *
 8827: X<userenvironment()>
 8828: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8829: passed in @what from the requested user's environment, returns a hash
 8830: 
 8831: =item * 
 8832: X<userlog_query()>
 8833: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8834: activity.log file. %filters defines filters applied when parsing the
 8835: log file. These can be start or end timestamps, or the type of action
 8836: - log to look for Login or Logout events, check for Checkin or
 8837: Checkout, role for role selection. The response is in the form
 8838: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8839: escaped strings of the action recorded in the activity.log file.
 8840: 
 8841: =back
 8842: 
 8843: =head2 User Roles
 8844: 
 8845: =over 4
 8846: 
 8847: =item *
 8848: 
 8849: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8850:  F: full access
 8851:  U,I,K: authentication modes (cxx only)
 8852:  '': forbidden
 8853:  1: user needs to choose course
 8854:  2: browse allowed
 8855:  A: passphrase authentication needed
 8856: 
 8857: =item *
 8858: 
 8859: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8860: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8861: and course level
 8862: 
 8863: =item *
 8864: 
 8865: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8866: explanation of a user role term
 8867: 
 8868: =item *
 8869: 
 8870: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8871: All arguments are optional. Returns a hash of a roles, either for
 8872: co-author/assistant author roles for a user's Construction Space
 8873: (default), or if $context is 'userroles', roles for the user himself,
 8874: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8875: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8876: For each key, value is set to colon-separated start and end times for
 8877: the role.  If no username and domain are specified, will default to
 8878: current user/domain. Types, roles, and roledoms are references to arrays
 8879: of role statuses (active, future or previous), roles 
 8880: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8881: to restrict the list of roles reported. If no array ref is 
 8882: provided for types, will default to return only active roles.
 8883: 
 8884: =back
 8885: 
 8886: =head2 User Modification
 8887: 
 8888: =over 4
 8889: 
 8890: =item *
 8891: 
 8892: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8893: user for the level given by URL.  Optional start and end dates (leave empty
 8894: string or zero for "no date")
 8895: 
 8896: =item *
 8897: 
 8898: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8899: change a users, password, possible return values are: ok,
 8900: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8901: refused
 8902: 
 8903: =item *
 8904: 
 8905: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8906: 
 8907: =item *
 8908: 
 8909: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8910: modify user
 8911: 
 8912: =item *
 8913: 
 8914: modifystudent
 8915: 
 8916: modify a students enrollment and identification information.
 8917: The course id is resolved based on the current users environment.  
 8918: This means the envoking user must be a course coordinator or otherwise
 8919: associated with a course.
 8920: 
 8921: This call is essentially a wrapper for lonnet::modifyuser and
 8922: lonnet::modify_student_enrollment
 8923: 
 8924: Inputs: 
 8925: 
 8926: =over 4
 8927: 
 8928: =item B<$udom> Students loncapa domain
 8929: 
 8930: =item B<$uname> Students loncapa login name
 8931: 
 8932: =item B<$uid> Students id/student number
 8933: 
 8934: =item B<$umode> Students authentication mode
 8935: 
 8936: =item B<$upass> Students password
 8937: 
 8938: =item B<$first> Students first name
 8939: 
 8940: =item B<$middle> Students middle name
 8941: 
 8942: =item B<$last> Students last name
 8943: 
 8944: =item B<$gene> Students generation
 8945: 
 8946: =item B<$usec> Students section in course
 8947: 
 8948: =item B<$end> Unix time of the roles expiration
 8949: 
 8950: =item B<$start> Unix time of the roles start date
 8951: 
 8952: =item B<$forceid> If defined, allow $uid to be changed
 8953: 
 8954: =item B<$desiredhome> server to use as home server for student
 8955: 
 8956: =back
 8957: 
 8958: =item *
 8959: 
 8960: modify_student_enrollment
 8961: 
 8962: Change a students enrollment status in a class.  The environment variable
 8963: 'role.request.course' must be defined for this function to proceed.
 8964: 
 8965: Inputs:
 8966: 
 8967: =over 4
 8968: 
 8969: =item $udom, students domain
 8970: 
 8971: =item $uname, students name
 8972: 
 8973: =item $uid, students user id
 8974: 
 8975: =item $first, students first name
 8976: 
 8977: =item $middle
 8978: 
 8979: =item $last
 8980: 
 8981: =item $gene
 8982: 
 8983: =item $usec
 8984: 
 8985: =item $end
 8986: 
 8987: =item $start
 8988: 
 8989: =back
 8990: 
 8991: 
 8992: =item *
 8993: 
 8994: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8995: custom role; give a custom role to a user for the level given by URL.  Specify
 8996: name and domain of role author, and role name
 8997: 
 8998: =item *
 8999: 
 9000: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9001: 
 9002: =item *
 9003: 
 9004: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9005: 
 9006: =back
 9007: 
 9008: =head2 Course Infomation
 9009: 
 9010: =over 4
 9011: 
 9012: =item *
 9013: 
 9014: coursedescription($courseid) : returns a hash of information about the
 9015: specified course id, including all environment settings for the
 9016: course, the description of the course will be in the hash under the
 9017: key 'description'
 9018: 
 9019: =item *
 9020: 
 9021: resdata($name,$domain,$type,@which) : request for current parameter
 9022: setting for a specific $type, where $type is either 'course' or 'user',
 9023: @what should be a list of parameters to ask about. This routine caches
 9024: answers for 5 minutes.
 9025: 
 9026: =item *
 9027: 
 9028: get_courseresdata($courseid, $domain) : dump the entire course resource
 9029: data base, returning a hash that is keyed by the resource name and has
 9030: values that are the resource value.  I believe that the timestamps and
 9031: versions are also returned.
 9032: 
 9033: 
 9034: =back
 9035: 
 9036: =head2 Course Modification
 9037: 
 9038: =over 4
 9039: 
 9040: =item *
 9041: 
 9042: writecoursepref($courseid,%prefs) : write preferences (environment
 9043: database) for a course
 9044: 
 9045: =item *
 9046: 
 9047: createcourse($udom,$description,$url) : make/modify course
 9048: 
 9049: =back
 9050: 
 9051: =head2 Resource Subroutines
 9052: 
 9053: =over 4
 9054: 
 9055: =item *
 9056: 
 9057: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9058: 
 9059: =item *
 9060: 
 9061: repcopy($filename) : subscribes to the requested file, and attempts to
 9062: replicate from the owning library server, Might return
 9063: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9064: 'bad_request', also attempts to grab the metadata for the
 9065: resource. Expects the local filesystem pathname
 9066: (/home/httpd/html/res/....)
 9067: 
 9068: =back
 9069: 
 9070: =head2 Resource Information
 9071: 
 9072: =over 4
 9073: 
 9074: =item *
 9075: 
 9076: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9077: a vairety of different possible values, $varname should be a request
 9078: string, and the other parameters can be used to specify who and what
 9079: one is asking about.
 9080: 
 9081: Possible values for $varname are environment.lastname (or other item
 9082: from the envirnment hash), user.name (or someother aspect about the
 9083: user), resource.0.maxtries (or some other part and parameter of a
 9084: resource)
 9085: 
 9086: =item *
 9087: 
 9088: directcondval($number) : get current value of a condition; reads from a state
 9089: string
 9090: 
 9091: =item *
 9092: 
 9093: condval($condidx) : value of condition index based on state
 9094: 
 9095: =item *
 9096: 
 9097: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9098: resource's metadata, $what should be either a specific key, or either
 9099: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9100: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9101: 
 9102: this function automatically caches all requests
 9103: 
 9104: =item *
 9105: 
 9106: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9107: network of library servers; returns file handle of where SQL and regex results
 9108: will be stored for query
 9109: 
 9110: =item *
 9111: 
 9112: symbread($filename) : return symbolic list entry (filename argument optional);
 9113: returns the data handle
 9114: 
 9115: =item *
 9116: 
 9117: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9118: a possible symb for the URL in $thisfn, and if is an encryypted
 9119: resource that the user accessed using /enc/ returns a 1 on success, 0
 9120: on failure, user must be in a course, as it assumes the existance of
 9121: the course initial hash, and uses $env('request.course.id'}
 9122: 
 9123: 
 9124: =item *
 9125: 
 9126: symbclean($symb) : removes versions numbers from a symb, returns the
 9127: cleaned symb
 9128: 
 9129: =item *
 9130: 
 9131: is_on_map($uri) : checks if the $uri is somewhere on the current
 9132: course map, user must be in a course for it to work.
 9133: 
 9134: =item *
 9135: 
 9136: numval($salt) : return random seed value (addend for rndseed)
 9137: 
 9138: =item *
 9139: 
 9140: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9141: a random seed, all arguments are optional, if they aren't sent it uses the
 9142: environment to derive them. Note: if symb isn't sent and it can't get one
 9143: from &symbread it will use the current time as its return value
 9144: 
 9145: =item *
 9146: 
 9147: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9148: unfakeable, receipt
 9149: 
 9150: =item *
 9151: 
 9152: receipt() : API to ireceipt working off of env values; given out to users
 9153: 
 9154: =item *
 9155: 
 9156: countacc($url) : count the number of accesses to a given URL
 9157: 
 9158: =item *
 9159: 
 9160: 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
 9161: 
 9162: =item *
 9163: 
 9164: 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)
 9165: 
 9166: =item *
 9167: 
 9168: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9169: 
 9170: =item *
 9171: 
 9172: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9173: forcing spreadsheet to reevaluate the resource scores next time.
 9174: 
 9175: =back
 9176: 
 9177: =head2 Storing/Retreiving Data
 9178: 
 9179: =over 4
 9180: 
 9181: =item *
 9182: 
 9183: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9184: for this url; hashref needs to be given and should be a \%hashname; the
 9185: remaining args aren't required and if they aren't passed or are '' they will
 9186: be derived from the env
 9187: 
 9188: =item *
 9189: 
 9190: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9191: uses critical subroutine
 9192: 
 9193: =item *
 9194: 
 9195: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9196: all args are optional
 9197: 
 9198: =item *
 9199: 
 9200: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9201: dumps the complete (or key matching regexp) namespace into a hash
 9202: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9203: normally &store()ed into
 9204: 
 9205: $range should be either an integer '100' (give me the first 100
 9206:                                            matching records)
 9207:               or be  two integers sperated by a - with no spaces
 9208:                  '30-50' (give me the 30th through the 50th matching
 9209:                           records)
 9210: 
 9211: 
 9212: =item *
 9213: 
 9214: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9215: replaces a &store() version of data with a replacement set of data
 9216: for a particular resource in a namespace passed in the $storehash hash 
 9217: reference
 9218: 
 9219: =item *
 9220: 
 9221: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9222: works very similar to store/cstore, but all data is stored in a
 9223: temporary location and can be reset using tmpreset, $storehash should
 9224: be a hash reference, returns nothing on success
 9225: 
 9226: =item *
 9227: 
 9228: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9229: similar to restore, but all data is stored in a temporary location and
 9230: can be reset using tmpreset. Returns a hash of values on success,
 9231: error string otherwise.
 9232: 
 9233: =item *
 9234: 
 9235: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9236: deltes all keys for $symb form the temporary storage hash.
 9237: 
 9238: =item *
 9239: 
 9240: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9241: reference filled in from namesp ($udom and $uname are optional)
 9242: 
 9243: =item *
 9244: 
 9245: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9246: namesp ($udom and $uname are optional)
 9247: 
 9248: =item *
 9249: 
 9250: dump($namespace,$udom,$uname,$regexp,$range) : 
 9251: dumps the complete (or key matching regexp) namespace into a hash
 9252: ($udom, $uname, $regexp, $range are optional)
 9253: 
 9254: $range should be either an integer '100' (give me the first 100
 9255:                                            matching records)
 9256:               or be  two integers sperated by a - with no spaces
 9257:                  '30-50' (give me the 30th through the 50th matching
 9258:                           records)
 9259: =item *
 9260: 
 9261: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9262: $store can be a scalar, an array reference, or if the amount to be 
 9263: incremented is > 1, a hash reference.
 9264: 
 9265: ($udom and $uname are optional)
 9266: 
 9267: =item *
 9268: 
 9269: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9270: ($udom and $uname are optional)
 9271: 
 9272: =item *
 9273: 
 9274: cput($namespace,$storehash,$udom,$uname) : critical put
 9275: ($udom and $uname are optional)
 9276: 
 9277: =item *
 9278: 
 9279: newput($namespace,$storehash,$udom,$uname) :
 9280: 
 9281: Attempts to store the items in the $storehash, but only if they don't
 9282: currently exist, if this succeeds you can be certain that you have 
 9283: successfully created a new key value pair in the $namespace db.
 9284: 
 9285: 
 9286: Args:
 9287:  $namespace: name of database to store values to
 9288:  $storehash: hashref to store to the db
 9289:  $udom: (optional) domain of user containing the db
 9290:  $uname: (optional) name of user caontaining the db
 9291: 
 9292: Returns:
 9293:  'ok' -> succeeded in storing all keys of $storehash
 9294:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9295:                         least <key> already existed in the db (other
 9296:                         requested keys may also already exist)
 9297:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9298:  'con_lost' -> unable to contact request server
 9299:  'refused' -> action was not allowed by remote machine
 9300: 
 9301: 
 9302: =item *
 9303: 
 9304: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9305: reference filled in from namesp (encrypts the return communication)
 9306: ($udom and $uname are optional)
 9307: 
 9308: =item *
 9309: 
 9310: log($udom,$name,$home,$message) : write to permanent log for user; use
 9311: critical subroutine
 9312: 
 9313: =item *
 9314: 
 9315: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9316: array reference filled in from namespace found in domain level on either
 9317: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9318: 
 9319: =item *
 9320: 
 9321: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9322: domain level either on specified domain server ($uhome) or primary domain 
 9323: server ($udom and $uhome are optional)
 9324: 
 9325: =back
 9326: 
 9327: =head2 Network Status Functions
 9328: 
 9329: =over 4
 9330: 
 9331: =item *
 9332: 
 9333: dirlist($uri) : return directory list based on URI
 9334: 
 9335: =item *
 9336: 
 9337: spareserver() : find server with least workload from spare.tab
 9338: 
 9339: =back
 9340: 
 9341: =head2 Apache Request
 9342: 
 9343: =over 4
 9344: 
 9345: =item *
 9346: 
 9347: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9348: localhost, posts hash
 9349: 
 9350: =back
 9351: 
 9352: =head2 Data to String to Data
 9353: 
 9354: =over 4
 9355: 
 9356: =item *
 9357: 
 9358: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9359: and '&' separators, supports elements that are arrayrefs and hashrefs
 9360: 
 9361: =item *
 9362: 
 9363: hashref2str($hashref) : convert a hashref into a string complete with
 9364: escaping and '=' and '&' separators, supports elements that are
 9365: arrayrefs and hashrefs
 9366: 
 9367: =item *
 9368: 
 9369: arrayref2str($arrayref) : convert an arrayref into a string complete
 9370: with escaping and '&' separators, supports elements that are arrayrefs
 9371: and hashrefs
 9372: 
 9373: =item *
 9374: 
 9375: str2hash($string) : convert string to hash using unescaping and
 9376: splitting on '=' and '&', supports elements that are arrayrefs and
 9377: hashrefs
 9378: 
 9379: =item *
 9380: 
 9381: str2array($string) : convert string to hash using unescaping and
 9382: splitting on '&', supports elements that are arrayrefs and hashrefs
 9383: 
 9384: =back
 9385: 
 9386: =head2 Logging Routines
 9387: 
 9388: =over 4
 9389: 
 9390: These routines allow one to make log messages in the lonnet.log and
 9391: lonnet.perm logfiles.
 9392: 
 9393: =item *
 9394: 
 9395: logtouch() : make sure the logfile, lonnet.log, exists
 9396: 
 9397: =item *
 9398: 
 9399: logthis() : append message to the normal lonnet.log file, it gets
 9400: preiodically rolled over and deleted.
 9401: 
 9402: =item *
 9403: 
 9404: logperm() : append a permanent message to lonnet.perm.log, this log
 9405: file never gets deleted by any automated portion of the system, only
 9406: messages of critical importance should go in here.
 9407: 
 9408: =back
 9409: 
 9410: =head2 General File Helper Routines
 9411: 
 9412: =over 4
 9413: 
 9414: =item *
 9415: 
 9416: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9417: (a) files in /uploaded
 9418:   (i) If a local copy of the file exists - 
 9419:       compares modification date of local copy with last-modified date for 
 9420:       definitive version stored on home server for course. If local copy is 
 9421:       stale, requests a new version from the home server and stores it. 
 9422:       If the original has been removed from the home server, then local copy 
 9423:       is unlinked.
 9424:   (ii) If local copy does not exist -
 9425:       requests the file from the home server and stores it. 
 9426:   
 9427:   If $caller is 'uploadrep':  
 9428:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9429:     for request for files originally uploaded via DOCS. 
 9430:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9431:   
 9432:   Otherwise:
 9433:      This indicates a call from the content generation phase of the request.
 9434:      -  returns the entire contents of the file or -1.
 9435:      
 9436: (b) files in /res
 9437:    - returns the entire contents of a file or -1; 
 9438:    it properly subscribes to and replicates the file if neccessary.
 9439: 
 9440: 
 9441: =item *
 9442: 
 9443: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9444:                   reference
 9445: 
 9446: returns either a stat() list of data about the file or an empty list
 9447: if the file doesn't exist or couldn't find out about it (connection
 9448: problems or user unknown)
 9449: 
 9450: =item *
 9451: 
 9452: filelocation($dir,$file) : returns file system location of a file
 9453: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9454: directory that relative $file lookups are to looked in ($dir of /a/dir
 9455: and a file of ../bob will become /a/bob)
 9456: 
 9457: =item *
 9458: 
 9459: hreflocation($dir,$file) : returns file system location or a URL; same as
 9460: filelocation except for hrefs
 9461: 
 9462: =item *
 9463: 
 9464: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9465: 
 9466: =back
 9467: 
 9468: =head2 Usererfile file routines (/uploaded*)
 9469: 
 9470: =over 4
 9471: 
 9472: =item *
 9473: 
 9474: userfileupload(): main rotine for putting a file in a user or course's
 9475:                   filespace, arguments are,
 9476: 
 9477:  formname - required - this is the name of the element in $env where the
 9478:            filename, and the contents of the file to create/modifed exist
 9479:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9480:            contents of the file is located in $env{'form.'.$formname}
 9481:  coursedoc - if true, store the file in the course of the active role
 9482:              of the current user
 9483:  subdir - required - subdirectory to put the file in under ../userfiles/
 9484:          if undefined, it will be placed in "unknown"
 9485: 
 9486:  (This routine calls clean_filename() to remove any dangerous
 9487:  characters from the filename, and then calls finuserfileupload() to
 9488:  complete the transaction)
 9489: 
 9490:  returns either the url of the uploaded file (/uploaded/....) if successful
 9491:  and /adm/notfound.html if unsuccessful
 9492: 
 9493: =item *
 9494: 
 9495: clean_filename(): routine for cleaing a filename up for storage in
 9496:                  userfile space, argument is:
 9497: 
 9498:  filename - proposed filename
 9499: 
 9500: returns: the new clean filename
 9501: 
 9502: =item *
 9503: 
 9504: finishuserfileupload(): routine that creaes and sends the file to
 9505: userspace, probably shouldn't be called directly
 9506: 
 9507:   docuname: username or courseid of destination for the file
 9508:   docudom: domain of user/course of destination for the file
 9509:   formname: same as for userfileupload()
 9510:   fname: filename (inculding subdirectories) for the file
 9511: 
 9512:  returns either the url of the uploaded file (/uploaded/....) if successful
 9513:  and /adm/notfound.html if unsuccessful
 9514: 
 9515: =item *
 9516: 
 9517: renameuserfile(): renames an existing userfile to a new name
 9518: 
 9519:   Args:
 9520:    docuname: username or courseid of destination for the file
 9521:    docudom: domain of user/course of destination for the file
 9522:    old: current file name (including any subdirs under userfiles)
 9523:    new: desired file name (including any subdirs under userfiles)
 9524: 
 9525: =item *
 9526: 
 9527: mkdiruserfile(): creates a directory is a userfiles dir
 9528: 
 9529:   Args:
 9530:    docuname: username or courseid of destination for the file
 9531:    docudom: domain of user/course of destination for the file
 9532:    dir: dir to create (including any subdirs under userfiles)
 9533: 
 9534: =item *
 9535: 
 9536: removeuserfile(): removes a file that exists in userfiles
 9537: 
 9538:   Args:
 9539:    docuname: username or courseid of destination for the file
 9540:    docudom: domain of user/course of destination for the file
 9541:    fname: filname to delete (including any subdirs under userfiles)
 9542: 
 9543: =item *
 9544: 
 9545: removeuploadedurl(): convience function for removeuserfile()
 9546: 
 9547:   Args:
 9548:    url:  a full /uploaded/... url to delete
 9549: 
 9550: =item * 
 9551: 
 9552: get_portfile_permissions():
 9553:   Args:
 9554:     domain: domain of user or course contain the portfolio files
 9555:     user: name of user or num of course contain the portfolio files
 9556:   Returns:
 9557:     hashref of a dump of the proper file_permissions.db
 9558:    
 9559: 
 9560: =item * 
 9561: 
 9562: get_access_controls():
 9563: 
 9564: Args:
 9565:   current_permissions: the hash ref returned from get_portfile_permissions()
 9566:   group: (optional) the group you want the files associated with
 9567:   file: (optional) the file you want access info on
 9568: 
 9569: Returns:
 9570:     a hash (keys are file names) of hashes containing
 9571:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9572:         values are XML containing access control settings (see below) 
 9573: 
 9574: Internal notes:
 9575: 
 9576:  access controls are stored in file_permissions.db as key=value pairs.
 9577:     key -> path to file/file_name\0uniqueID:scope_end_start
 9578:         where scope -> public,guest,course,group,domains or users.
 9579:               end -> UNIX time for end of access (0 -> no end date)
 9580:               start -> UNIX time for start of access
 9581: 
 9582:     value -> XML description of access control
 9583:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9584:             <start></start>
 9585:             <end></end>
 9586: 
 9587:             <password></password>  for scope type = guest
 9588: 
 9589:             <domain></domain>     for scope type = course or group
 9590:             <number></number>
 9591:             <roles id="">
 9592:              <role></role>
 9593:              <access></access>
 9594:              <section></section>
 9595:              <group></group>
 9596:             </roles>
 9597: 
 9598:             <dom></dom>         for scope type = domains
 9599: 
 9600:             <users>             for scope type = users
 9601:              <user>
 9602:               <uname></uname>
 9603:               <udom></udom>
 9604:              </user>
 9605:             </users>
 9606:            </scope> 
 9607:               
 9608:  Access data is also aggregated for each file in an additional key=value pair:
 9609:  key -> path to file/file_name\0accesscontrol 
 9610:  value -> reference to hash
 9611:           hash contains key = value pairs
 9612:           where key = uniqueID:scope_end_start
 9613:                 value = UNIX time record was last updated
 9614: 
 9615:           Used to improve speed of look-ups of access controls for each file.  
 9616:  
 9617:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9618: 
 9619: modify_access_controls():
 9620: 
 9621: Modifies access controls for a portfolio file
 9622: Args
 9623: 1. file name
 9624: 2. reference to hash of required changes,
 9625: 3. domain
 9626: 4. username
 9627:   where domain,username are the domain of the portfolio owner 
 9628:   (either a user or a course) 
 9629: 
 9630: Returns:
 9631: 1. result of additions or updates ('ok' or 'error', with error message). 
 9632: 2. result of deletions ('ok' or 'error', with error message).
 9633: 3. reference to hash of any new or updated access controls.
 9634: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9635:    key = integer (inbound ID)
 9636:    value = uniqueID  
 9637: 
 9638: =back
 9639: 
 9640: =head2 HTTP Helper Routines
 9641: 
 9642: =over 4
 9643: 
 9644: =item *
 9645: 
 9646: escape() : unpack non-word characters into CGI-compatible hex codes
 9647: 
 9648: =item *
 9649: 
 9650: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9651: 
 9652: =back
 9653: 
 9654: =head1 PRIVATE SUBROUTINES
 9655: 
 9656: =head2 Underlying communication routines (Shouldn't call)
 9657: 
 9658: =over 4
 9659: 
 9660: =item *
 9661: 
 9662: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9663: 
 9664: =item *
 9665: 
 9666: reply() : uses subreply to send a message to remote machine, logs all failures
 9667: 
 9668: =item *
 9669: 
 9670: critical() : passes a critical message to another server; if cannot
 9671: get through then place message in connection buffer directory and
 9672: returns con_delayed, if incapable of saving message, returns
 9673: con_failed
 9674: 
 9675: =item *
 9676: 
 9677: reconlonc() : tries to reconnect lonc client processes.
 9678: 
 9679: =back
 9680: 
 9681: =head2 Resource Access Logging
 9682: 
 9683: =over 4
 9684: 
 9685: =item *
 9686: 
 9687: flushcourselogs() : flush (save) buffer logs and access logs
 9688: 
 9689: =item *
 9690: 
 9691: courselog($what) : save message for course in hash
 9692: 
 9693: =item *
 9694: 
 9695: courseacclog($what) : save message for course using &courselog().  Perform
 9696: special processing for specific resource types (problems, exams, quizzes, etc).
 9697: 
 9698: =item *
 9699: 
 9700: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9701: as a PerlChildExitHandler
 9702: 
 9703: =back
 9704: 
 9705: =head2 Other
 9706: 
 9707: =over 4
 9708: 
 9709: =item *
 9710: 
 9711: symblist($mapname,%newhash) : update symbolic storage links
 9712: 
 9713: =back
 9714: 
 9715: =cut
 9716: 

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