File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.926: download - view: text, annotated - select for diffs
Tue Nov 20 00:13:56 2007 UTC (16 years, 8 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- add supprot for a first access time for the course

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

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