File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.845: download - view: text, annotated - select for diffs
Thu Mar 8 01:54:50 2007 UTC (17 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- elmiinate global libserv

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.845 2007/03/08 01:54:50 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::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %badServerCache %iphost %spareid 
   39:    %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: use Math::Random;
   56: use LONCAPA qw(:DEFAULT :match);
   57: use LONCAPA::Configuration;
   58: 
   59: my $readit;
   60: my $max_connection_retries = 10;     # Or some such value.
   61: 
   62: require Exporter;
   63: 
   64: our @ISA = qw (Exporter);
   65: our @EXPORT = qw(%env);
   66: 
   67: =pod
   68: 
   69: =head1 Package Variables
   70: 
   71: These are largely undocumented, so if you decipher one please note it here.
   72: 
   73: =over 4
   74: 
   75: =item $processmarker
   76: 
   77: Contains the time this process was started and this servers host id.
   78: 
   79: =item $dumpcount
   80: 
   81: Counts the number of times a message log flush has been attempted (regardless
   82: of success) by this process.  Used as part of the filename when messages are
   83: delayed.
   84: 
   85: =back
   86: 
   87: =cut
   88: 
   89: 
   90: # --------------------------------------------------------------------- Logging
   91: {
   92:     my $logid;
   93:     sub instructor_log {
   94: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   95: 	$logid++;
   96: 	my $id=time().'00000'.$$.'00000'.$logid;
   97: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   98: 				    { $id => {
   99: 					'exe_uname' => $env{'user.name'},
  100: 					'exe_udom'  => $env{'user.domain'},
  101: 					'exe_time'  => time(),
  102: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  103: 					'delflag'   => $delflag,
  104: 					'logentry'  => $storehash,
  105: 					'uname'     => $uname,
  106: 					'udom'      => $udom,
  107: 				    }
  108: 				  },
  109: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  110: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  111: 				    );
  112:     }
  113: }
  114: 
  115: sub logtouch {
  116:     my $execdir=$perlvar{'lonDaemons'};
  117:     unless (-e "$execdir/logs/lonnet.log") {	
  118: 	open(my $fh,">>$execdir/logs/lonnet.log");
  119: 	close $fh;
  120:     }
  121:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  122:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  123: }
  124: 
  125: sub logthis {
  126:     my $message=shift;
  127:     my $execdir=$perlvar{'lonDaemons'};
  128:     my $now=time;
  129:     my $local=localtime($now);
  130:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  131: 	print $fh "$local ($$): $message\n";
  132: 	close($fh);
  133:     }
  134:     return 1;
  135: }
  136: 
  137: sub logperm {
  138:     my $message=shift;
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     my $now=time;
  141:     my $local=localtime($now);
  142:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  143: 	print $fh "$now:$message:$local\n";
  144: 	close($fh);
  145:     }
  146:     return 1;
  147: }
  148: 
  149: # -------------------------------------------------- Non-critical communication
  150: sub subreply {
  151:     my ($cmd,$server)=@_;
  152:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  153:     #
  154:     #  With loncnew process trimming, there's a timing hole between lonc server
  155:     #  process exit and the master server picking up the listen on the AF_UNIX
  156:     #  socket.  In that time interval, a lock file will exist:
  157: 
  158:     my $lockfile=$peerfile.".lock";
  159:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  160: 	sleep(1);
  161:     }
  162:     # At this point, either a loncnew parent is listening or an old lonc
  163:     # or loncnew child is listening so we can connect or everything's dead.
  164:     #
  165:     #   We'll give the connection a few tries before abandoning it.  If
  166:     #   connection is not possible, we'll con_lost back to the client.
  167:     #   
  168:     my $client;
  169:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  170: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  171: 				      Type    => SOCK_STREAM,
  172: 				      Timeout => 10);
  173: 	if($client) {
  174: 	    last;		# Connected!
  175: 	}
  176: 	sleep(1);		# Try again later if failed connection.
  177:     }
  178:     my $answer;
  179:     if ($client) {
  180: 	print $client "sethost:$server:$cmd\n";
  181: 	$answer=<$client>;
  182: 	if (!$answer) { $answer="con_lost"; }
  183: 	chomp($answer);
  184:     } else {
  185: 	$answer = 'con_lost';	# Failed connection.
  186:     }
  187:     return $answer;
  188: }
  189: 
  190: sub reply {
  191:     my ($cmd,$server)=@_;
  192:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  193:     my $answer=subreply($cmd,$server);
  194:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  195:        &logthis("<font color=\"blue\">WARNING:".
  196:                 " $cmd to $server returned $answer</font>");
  197:     }
  198:     return $answer;
  199: }
  200: 
  201: # ----------------------------------------------------------- Send USR1 to lonc
  202: 
  203: sub reconlonc {
  204:     &logthis("Trying to reconnect lonc");
  205:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  206:     if (open(my $fh,"<$loncfile")) {
  207: 	my $loncpid=<$fh>;
  208:         chomp($loncpid);
  209:         if (kill 0 => $loncpid) {
  210: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  211:             kill USR1 => $loncpid;
  212:             sleep 1;
  213:          } else {
  214: 	    &logthis(
  215:                "<font color=\"blue\">WARNING:".
  216:                " lonc at pid $loncpid not responding, giving up</font>");
  217:         }
  218:     } else {
  219: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  220:     }
  221: }
  222: 
  223: # ------------------------------------------------------ Critical communication
  224: 
  225: sub critical {
  226:     my ($cmd,$server)=@_;
  227:     unless (&hostname($server)) {
  228:         &logthis("<font color=\"blue\">WARNING:".
  229:                " Critical message to unknown server ($server)</font>");
  230:         return 'no_such_host';
  231:     }
  232:     my $answer=reply($cmd,$server);
  233:     if ($answer eq 'con_lost') {
  234: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  235: 	my $answer=reply($cmd,$server);
  236:         if ($answer eq 'con_lost') {
  237:             my $now=time;
  238:             my $middlename=$cmd;
  239:             $middlename=substr($middlename,0,16);
  240:             $middlename=~s/\W//g;
  241:             my $dfilename=
  242:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  243:             $dumpcount++;
  244:             {
  245: 		my $dfh;
  246: 		if (open($dfh,">$dfilename")) {
  247: 		    print $dfh "$cmd\n"; 
  248: 		    close($dfh);
  249: 		}
  250:             }
  251:             sleep 2;
  252:             my $wcmd='';
  253:             {
  254: 		my $dfh;
  255: 		if (open($dfh,"<$dfilename")) {
  256: 		    $wcmd=<$dfh>; 
  257: 		    close($dfh);
  258: 		}
  259:             }
  260:             chomp($wcmd);
  261:             if ($wcmd eq $cmd) {
  262: 		&logthis("<font color=\"blue\">WARNING: ".
  263:                          "Connection buffer $dfilename: $cmd</font>");
  264:                 &logperm("D:$server:$cmd");
  265: 	        return 'con_delayed';
  266:             } else {
  267:                 &logthis("<font color=\"red\">CRITICAL:"
  268:                         ." Critical connection failed: $server $cmd</font>");
  269:                 &logperm("F:$server:$cmd");
  270:                 return 'con_failed';
  271:             }
  272:         }
  273:     }
  274:     return $answer;
  275: }
  276: 
  277: # ------------------------------------------- check if return value is an error
  278: 
  279: sub error {
  280:     my ($result) = @_;
  281:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  282: 	if ($2 == 2) { return undef; }
  283: 	return $1;
  284:     }
  285:     return undef;
  286: }
  287: 
  288: sub convert_and_load_session_env {
  289:     my ($lonidsdir,$handle)=@_;
  290:     my @profile;
  291:     {
  292: 	open(my $idf,"$lonidsdir/$handle.id");
  293: 	flock($idf,LOCK_SH);
  294: 	@profile=<$idf>;
  295: 	close($idf);
  296:     }
  297:     my %temp_env;
  298:     foreach my $line (@profile) {
  299: 	if ($line !~ m/=/) {
  300: 	    return 0;
  301: 	}
  302: 	chomp($line);
  303: 	my ($envname,$envvalue)=split(/=/,$line,2);
  304: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  305:     }
  306:     unlink("$lonidsdir/$handle.id");
  307:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  308: 	    0640)) {
  309: 	%disk_env = %temp_env;
  310: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  311: 	untie(%disk_env);
  312:     }
  313:     return 1;
  314: }
  315: 
  316: # ------------------------------------------- Transfer profile into environment
  317: my $env_loaded;
  318: sub transfer_profile_to_env {
  319:     my ($lonidsdir,$handle,$force_transfer) = @_;
  320:     if (!$force_transfer && $env_loaded) { return; } 
  321: 
  322:     if (!defined($lonidsdir)) {
  323: 	$lonidsdir = $perlvar{'lonIDsDir'};
  324:     }
  325:     if (!defined($handle)) {
  326:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  327:     }
  328: 
  329:     my $convert;
  330:     {
  331:     	open(my $idf,"$lonidsdir/$handle.id");
  332: 	flock($idf,LOCK_SH);
  333: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  334: 		&GDBM_READER(),0640)) {
  335: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  336: 	    untie(%disk_env);
  337: 	} else {
  338: 	    $convert = 1;
  339: 	}
  340:     }
  341:     if ($convert) {
  342: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  343: 	    &logthis("Failed to load session, or convert session.");
  344: 	}
  345:     }
  346: 
  347:     my %remove;
  348:     while ( my $envname = each(%env) ) {
  349:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  350:             if ($time < time-300) {
  351:                 $remove{$key}++;
  352:             }
  353:         }
  354:     }
  355: 
  356:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  357:     $env_loaded=1;
  358:     foreach my $expired_key (keys(%remove)) {
  359:         &delenv($expired_key);
  360:     }
  361: }
  362: 
  363: sub timed_flock {
  364:     my ($file,$lock_type) = @_;
  365:     my $failed=0;
  366:     eval {
  367: 	local $SIG{__DIE__}='DEFAULT';
  368: 	local $SIG{ALRM}=sub {
  369: 	    $failed=1;
  370: 	    die("failed lock");
  371: 	};
  372: 	alarm(13);
  373: 	flock($file,$lock_type);
  374: 	alarm(0);
  375:     };
  376:     if ($failed) {
  377: 	return undef;
  378:     } else {
  379: 	return 1;
  380:     }
  381: }
  382: 
  383: # ---------------------------------------------------------- Append Environment
  384: 
  385: sub appenv {
  386:     my %newenv=@_;
  387:     foreach my $key (keys(%newenv)) {
  388: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  389:             &logthis("<font color=\"blue\">WARNING: ".
  390:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  391:                 .'</font>');
  392: 	    delete($newenv{$key});
  393:         } else {
  394:             $env{$key}=$newenv{$key};
  395:         }
  396:     }
  397:     open(my $env_file,$env{'user.environment'});
  398:     if (&timed_flock($env_file,LOCK_EX)
  399: 	&&
  400: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  401: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  402: 	while (my ($key,$value) = each(%newenv)) {
  403: 	    $disk_env{$key} = $value;
  404: 	}
  405: 	untie(%disk_env);
  406:     }
  407:     return 'ok';
  408: }
  409: # ----------------------------------------------------- Delete from Environment
  410: 
  411: sub delenv {
  412:     my $delthis=shift;
  413:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  414:         &logthis("<font color=\"blue\">WARNING: ".
  415:                 "Attempt to delete from environment ".$delthis);
  416:         return 'error';
  417:     }
  418:     open(my $env_file,$env{'user.environment'});
  419:     if (&timed_flock($env_file,LOCK_EX)
  420: 	&&
  421: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  422: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  423: 	foreach my $key (keys(%disk_env)) {
  424: 	    if ($key=~/^$delthis/) { 
  425:                 delete($env{$key});
  426:                 delete($disk_env{$key});
  427:             }
  428: 	}
  429: 	untie(%disk_env);
  430:     }
  431:     return 'ok';
  432: }
  433: 
  434: sub get_env_multiple {
  435:     my ($name) = @_;
  436:     my @values;
  437:     if (defined($env{$name})) {
  438:         # exists is it an array
  439:         if (ref($env{$name})) {
  440:             @values=@{ $env{$name} };
  441:         } else {
  442:             $values[0]=$env{$name};
  443:         }
  444:     }
  445:     return(@values);
  446: }
  447: 
  448: # ------------------------------------------ Find out current server userload
  449: # there is a copy in lond
  450: sub userload {
  451:     my $numusers=0;
  452:     {
  453: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  454: 	my $filename;
  455: 	my $curtime=time;
  456: 	while ($filename=readdir(LONIDS)) {
  457: 	    if ($filename eq '.' || $filename eq '..') {next;}
  458: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  459: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  460: 	}
  461: 	closedir(LONIDS);
  462:     }
  463:     my $userloadpercent=0;
  464:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  465:     if ($maxuserload) {
  466: 	$userloadpercent=100*$numusers/$maxuserload;
  467:     }
  468:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  469:     return $userloadpercent;
  470: }
  471: 
  472: # ------------------------------------------ Fight off request when overloaded
  473: 
  474: sub overloaderror {
  475:     my ($r,$checkserver)=@_;
  476:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  477:     my $loadavg;
  478:     if ($checkserver eq $perlvar{'lonHostID'}) {
  479:        open(my $loadfile,'/proc/loadavg');
  480:        $loadavg=<$loadfile>;
  481:        $loadavg =~ s/\s.*//g;
  482:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  483:        close($loadfile);
  484:     } else {
  485:        $loadavg=&reply('load',$checkserver);
  486:     }
  487:     my $overload=$loadavg-100;
  488:     if ($overload>0) {
  489: 	$r->err_headers_out->{'Retry-After'}=$overload;
  490:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  491:         return 413;
  492:     }    
  493:     return '';
  494: }
  495: 
  496: # ------------------------------ Find server with least workload from spare.tab
  497: 
  498: sub spareserver {
  499:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  500:     my $spare_server;
  501:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  502:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  503:                                                      :  $userloadpercent;
  504:     
  505:     foreach my $try_server (@{ $spareid{'primary'} }) {
  506: 	($spare_server, $lowest_load) =
  507: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  508:     }
  509: 
  510:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  511: 
  512:     if (!$found_server) {
  513: 	foreach my $try_server (@{ $spareid{'default'} }) {
  514: 	    ($spare_server, $lowest_load) =
  515: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  516: 	}
  517:     }
  518: 
  519:     if (!$want_server_name) {
  520: 	$spare_server="http://".&hostname($spare_server);
  521:     }
  522:     return $spare_server;
  523: }
  524: 
  525: sub compare_server_load {
  526:     my ($try_server, $spare_server, $lowest_load) = @_;
  527: 
  528:     my $loadans     = &reply('load',    $try_server);
  529:     my $userloadans = &reply('userload',$try_server);
  530: 
  531:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  532: 	next; #didn't get a number from the server
  533:     }
  534: 
  535:     my $load;
  536:     if ($loadans =~ /\d/) {
  537: 	if ($userloadans =~ /\d/) {
  538: 	    #both are numbers, pick the bigger one
  539: 	    $load = ($loadans > $userloadans) ? $loadans 
  540: 		                              : $userloadans;
  541: 	} else {
  542: 	    $load = $loadans;
  543: 	}
  544:     } else {
  545: 	$load = $userloadans;
  546:     }
  547: 
  548:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  549: 	$spare_server = $try_server;
  550: 	$lowest_load  = $load;
  551:     }
  552:     return ($spare_server,$lowest_load);
  553: }
  554: # --------------------------------------------- Try to change a user's password
  555: 
  556: sub changepass {
  557:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  558:     $currentpass = &escape($currentpass);
  559:     $newpass     = &escape($newpass);
  560:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  561: 		       $server);
  562:     if (! $answer) {
  563: 	&logthis("No reply on password change request to $server ".
  564: 		 "by $uname in domain $udom.");
  565:     } elsif ($answer =~ "^ok") {
  566:         &logthis("$uname in $udom successfully changed their password ".
  567: 		 "on $server.");
  568:     } elsif ($answer =~ "^pwchange_failure") {
  569: 	&logthis("$uname in $udom was unable to change their password ".
  570: 		 "on $server.  The action was blocked by either lcpasswd ".
  571: 		 "or pwchange");
  572:     } elsif ($answer =~ "^non_authorized") {
  573:         &logthis("$uname in $udom did not get their password correct when ".
  574: 		 "attempting to change it on $server.");
  575:     } elsif ($answer =~ "^auth_mode_error") {
  576:         &logthis("$uname in $udom attempted to change their password despite ".
  577: 		 "not being locally or internally authenticated on $server.");
  578:     } elsif ($answer =~ "^unknown_user") {
  579:         &logthis("$uname in $udom attempted to change their password ".
  580: 		 "on $server but were unable to because $server is not ".
  581: 		 "their home server.");
  582:     } elsif ($answer =~ "^refused") {
  583: 	&logthis("$server refused to change $uname in $udom password because ".
  584: 		 "it was sent an unencrypted request to change the password.");
  585:     }
  586:     return $answer;
  587: }
  588: 
  589: # ----------------------- Try to determine user's current authentication scheme
  590: 
  591: sub queryauthenticate {
  592:     my ($uname,$udom)=@_;
  593:     my $uhome=&homeserver($uname,$udom);
  594:     if (!$uhome) {
  595: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  596: 	return 'no_host';
  597:     }
  598:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  599:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  600: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  601:     }
  602:     return $answer;
  603: }
  604: 
  605: # --------- Try to authenticate user from domain's lib servers (first this one)
  606: 
  607: sub authenticate {
  608:     my ($uname,$upass,$udom)=@_;
  609:     $upass=&escape($upass);
  610:     $uname= &LONCAPA::clean_username($uname);
  611:     my $uhome=&homeserver($uname,$udom,1);
  612:     if ((!$uhome) || ($uhome eq 'no_host')) {
  613: # Maybe the machine was offline and only re-appeared again recently?
  614:         &reconlonc();
  615: # One more
  616: 	my $uhome=&homeserver($uname,$udom,1);
  617: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  618: 	    &logthis("User $uname at $udom is unknown in authenticate");
  619: 	}
  620: 	return 'no_host';
  621:     }
  622:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  623:     if ($answer eq 'authorized') {
  624: 	&logthis("User $uname at $udom authorized by $uhome"); 
  625: 	return $uhome; 
  626:     }
  627:     if ($answer eq 'non_authorized') {
  628: 	&logthis("User $uname at $udom rejected by $uhome");
  629: 	return 'no_host'; 
  630:     }
  631:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  632:     return 'no_host';
  633: }
  634: 
  635: # ---------------------- Find the homebase for a user from domain's lib servers
  636: 
  637: my %homecache;
  638: sub homeserver {
  639:     my ($uname,$udom,$ignoreBadCache)=@_;
  640:     my $index="$uname:$udom";
  641: 
  642:     if (exists($homecache{$index})) { return $homecache{$index}; }
  643: 
  644:     my %servers = &get_servers($udom,'library');
  645:     foreach my $tryserver (keys(%servers)) {
  646:         next if ($ignoreBadCache ne 'true' && 
  647: 		 exists($badServerCache{$tryserver}));
  648: 
  649: 	my $answer=reply("home:$udom:$uname",$tryserver);
  650: 	if ($answer eq 'found') {
  651: 	    delete($badServerCache{$tryserver}); 
  652: 	    return $homecache{$index}=$tryserver;
  653: 	} elsif ($answer eq 'no_host') {
  654: 	    $badServerCache{$tryserver}=1;
  655: 	}
  656:     }    
  657:     return 'no_host';
  658: }
  659: 
  660: # ------------------------------------- Find the usernames behind a list of IDs
  661: 
  662: sub idget {
  663:     my ($udom,@ids)=@_;
  664:     my %returnhash=();
  665:     
  666:     my %servers = &get_servers($udom,'library');
  667:     foreach my $tryserver (keys(%servers)) {
  668: 	my $idlist=join('&',@ids);
  669: 	$idlist=~tr/A-Z/a-z/; 
  670: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  671: 	my @answer=();
  672: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  673: 	    @answer=split(/\&/,$reply);
  674: 	}                    ;
  675: 	my $i;
  676: 	for ($i=0;$i<=$#ids;$i++) {
  677: 	    if ($answer[$i]) {
  678: 		$returnhash{$ids[$i]}=$answer[$i];
  679: 	    } 
  680: 	}
  681:     } 
  682:     return %returnhash;
  683: }
  684: 
  685: # ------------------------------------- Find the IDs behind a list of usernames
  686: 
  687: sub idrget {
  688:     my ($udom,@unames)=@_;
  689:     my %returnhash=();
  690:     foreach my $uname (@unames) {
  691:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  692:     }
  693:     return %returnhash;
  694: }
  695: 
  696: # ------------------------------- Store away a list of names and associated IDs
  697: 
  698: sub idput {
  699:     my ($udom,%ids)=@_;
  700:     my %servers=();
  701:     foreach my $uname (keys(%ids)) {
  702: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  703:         my $uhom=&homeserver($uname,$udom);
  704:         if ($uhom ne 'no_host') {
  705:             my $id=&escape($ids{$uname});
  706:             $id=~tr/A-Z/a-z/;
  707:             my $esc_unam=&escape($uname);
  708: 	    if ($servers{$uhom}) {
  709: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  710:             } else {
  711:                 $servers{$uhom}=$id.'='.$esc_unam;
  712:             }
  713:         }
  714:     }
  715:     foreach my $server (keys(%servers)) {
  716:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  717:     }
  718: }
  719: 
  720: # ------------------------------------------- get items from domain db files   
  721: 
  722: sub get_dom {
  723:     my ($namespace,$storearr,$udom)=@_;
  724:     my $items='';
  725:     foreach my $item (@$storearr) {
  726:         $items.=&escape($item).'&';
  727:     }
  728:     $items=~s/\&$//;
  729:     if (!$udom) { $udom=$env{'user.domain'}; }
  730:     if (exists($domain_primary{$udom})) {
  731:         my $uhome=$domain_primary{$udom};
  732:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  733:         my @pairs=split(/\&/,$rep);
  734:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  735:             return @pairs;
  736:         }
  737:         my %returnhash=();
  738:         my $i=0;
  739:         foreach my $item (@$storearr) {
  740:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  741:             $i++;
  742:         }
  743:         return %returnhash;
  744:     } else {
  745:         &logthis("get_dom failed - no primary domain server for $udom");
  746:     }
  747: }
  748: 
  749: # -------------------------------------------- put items in domain db files 
  750: 
  751: sub put_dom {
  752:     my ($namespace,$storehash,$udom)=@_;
  753:     if (!$udom) { $udom=$env{'user.domain'}; }
  754:     if (exists($domain_primary{$udom})) {
  755:         my $uhome=$domain_primary{$udom};
  756:         my $items='';
  757:         foreach my $item (keys(%$storehash)) {
  758:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  759:         }
  760:         $items=~s/\&$//;
  761:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  762:     } else {
  763:         &logthis("put_dom failed - no primary domain server for $udom");
  764:     }
  765: }
  766: 
  767: sub retrieve_inst_usertypes {
  768:     my ($udom) = @_;
  769:     my (%returnhash,@order);
  770:     if (exists($domain_primary{$udom})) {
  771:         my $uhome=$domain_primary{$udom};
  772:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  773:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  774:         my @pairs=split(/\&/,$hashitems);
  775:         foreach my $item (@pairs) {
  776:             my ($key,$value)=split(/=/,$item,2);
  777:             $key = &unescape($key);
  778:             next if ($key =~ /^error: 2 /);
  779:             $returnhash{$key}=&thaw_unescape($value);
  780:         }
  781:         my @esc_order = split(/\&/,$orderitems);
  782:         foreach my $item (@esc_order) {
  783:             push(@order,&unescape($item));
  784:         }
  785:     } else {
  786:         &logthis("get_dom failed - no primary domain server for $udom");
  787:     }
  788:     return (\%returnhash,\@order);
  789: }
  790: 
  791: # --------------------------------------------------- Assign a key to a student
  792: 
  793: sub assign_access_key {
  794: #
  795: # a valid key looks like uname:udom#comments
  796: # comments are being appended
  797: #
  798:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  799:     $kdom=
  800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  801:     $knum=
  802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  803:     $cdom=
  804:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  805:     $cnum=
  806:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  807:     $udom=$env{'user.name'} unless (defined($udom));
  808:     $uname=$env{'user.domain'} unless (defined($uname));
  809:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  810:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  811:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  812:                                                   # assigned to this person
  813:                                                   # - this should not happen,
  814:                                                   # unless something went wrong
  815:                                                   # the first time around
  816: # ready to assign
  817:         $logentry=$1.'; '.$logentry;
  818:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  819:                                                  $kdom,$knum) eq 'ok') {
  820: # key now belongs to user
  821: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  822:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  823:                 &appenv('environment.'.$envkey => $ckey);
  824:                 return 'ok';
  825:             } else {
  826:                 return 
  827:   'error: Count not permanently assign key, will need to be re-entered later.';
  828: 	    }
  829:         } else {
  830:             return 'error: Could not assign key, try again later.';
  831:         }
  832:     } elsif (!$existing{$ckey}) {
  833: # the key does not exist
  834: 	return 'error: The key does not exist';
  835:     } else {
  836: # the key is somebody else's
  837: 	return 'error: The key is already in use';
  838:     }
  839: }
  840: 
  841: # ------------------------------------------ put an additional comment on a key
  842: 
  843: sub comment_access_key {
  844: #
  845: # a valid key looks like uname:udom#comments
  846: # comments are being appended
  847: #
  848:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  849:     $cdom=
  850:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  851:     $cnum=
  852:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  853:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  854:     if ($existing{$ckey}) {
  855:         $existing{$ckey}.='; '.$logentry;
  856: # ready to assign
  857:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  858:                                                  $cdom,$cnum) eq 'ok') {
  859: 	    return 'ok';
  860:         } else {
  861: 	    return 'error: Count not store comment.';
  862:         }
  863:     } else {
  864: # the key does not exist
  865: 	return 'error: The key does not exist';
  866:     }
  867: }
  868: 
  869: # ------------------------------------------------------ Generate a set of keys
  870: 
  871: sub generate_access_keys {
  872:     my ($number,$cdom,$cnum,$logentry)=@_;
  873:     $cdom=
  874:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  875:     $cnum=
  876:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  877:     unless (&allowed('mky',$cdom)) { return 0; }
  878:     unless (($cdom) && ($cnum)) { return 0; }
  879:     if ($number>10000) { return 0; }
  880:     sleep(2); # make sure don't get same seed twice
  881:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  882:     my $total=0;
  883:     for (my $i=1;$i<=$number;$i++) {
  884:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  885:                   sprintf("%lx",int(100000*rand)).'-'.
  886:                   sprintf("%lx",int(100000*rand));
  887:        $newkey=~s/1/g/g; # folks mix up 1 and l
  888:        $newkey=~s/0/h/g; # and also 0 and O
  889:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  890:        if ($existing{$newkey}) {
  891:            $i--;
  892:        } else {
  893: 	  if (&put('accesskeys',
  894:               { $newkey => '# generated '.localtime().
  895:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  896:                            '; '.$logentry },
  897: 		   $cdom,$cnum) eq 'ok') {
  898:               $total++;
  899: 	  }
  900:        }
  901:     }
  902:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  903:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  904:     return $total;
  905: }
  906: 
  907: # ------------------------------------------------------- Validate an accesskey
  908: 
  909: sub validate_access_key {
  910:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  911:     $cdom=
  912:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  913:     $cnum=
  914:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  915:     $udom=$env{'user.domain'} unless (defined($udom));
  916:     $uname=$env{'user.name'} unless (defined($uname));
  917:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  918:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  919: }
  920: 
  921: # ------------------------------------- Find the section of student in a course
  922: sub devalidate_getsection_cache {
  923:     my ($udom,$unam,$courseid)=@_;
  924:     my $hashid="$udom:$unam:$courseid";
  925:     &devalidate_cache_new('getsection',$hashid);
  926: }
  927: 
  928: sub courseid_to_courseurl {
  929:     my ($courseid) = @_;
  930:     #already url style courseid
  931:     return $courseid if ($courseid =~ m{^/});
  932: 
  933:     if (exists($env{'course.'.$courseid.'.num'})) {
  934: 	my $cnum = $env{'course.'.$courseid.'.num'};
  935: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  936: 	return "/$cdom/$cnum";
  937:     }
  938: 
  939:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  940:     if (exists($courseinfo{'num'})) {
  941: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  942:     }
  943: 
  944:     return undef;
  945: }
  946: 
  947: sub getsection {
  948:     my ($udom,$unam,$courseid)=@_;
  949:     my $cachetime=1800;
  950: 
  951:     my $hashid="$udom:$unam:$courseid";
  952:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  953:     if (defined($cached)) { return $result; }
  954: 
  955:     my %Pending; 
  956:     my %Expired;
  957:     #
  958:     # Each role can either have not started yet (pending), be active, 
  959:     #    or have expired.
  960:     #
  961:     # If there is an active role, we are done.
  962:     #
  963:     # If there is more than one role which has not started yet, 
  964:     #     choose the one which will start sooner
  965:     # If there is one role which has not started yet, return it.
  966:     #
  967:     # If there is more than one expired role, choose the one which ended last.
  968:     # If there is a role which has expired, return it.
  969:     #
  970:     $courseid = &courseid_to_courseurl($courseid);
  971:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
  972:     foreach my $key (keys(%roleshash)) {
  973:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  974:         my $section=$1;
  975:         if ($key eq $courseid.'_st') { $section=''; }
  976:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
  977:         my $now=time;
  978:         if (defined($end) && $end && ($now > $end)) {
  979:             $Expired{$end}=$section;
  980:             next;
  981:         }
  982:         if (defined($start) && $start && ($now < $start)) {
  983:             $Pending{$start}=$section;
  984:             next;
  985:         }
  986:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  987:     }
  988:     #
  989:     # Presumedly there will be few matching roles from the above
  990:     # loop and the sorting time will be negligible.
  991:     if (scalar(keys(%Pending))) {
  992:         my ($time) = sort {$a <=> $b} keys(%Pending);
  993:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  994:     } 
  995:     if (scalar(keys(%Expired))) {
  996:         my @sorted = sort {$a <=> $b} keys(%Expired);
  997:         my $time = pop(@sorted);
  998:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  999:     }
 1000:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1001: }
 1002: 
 1003: sub save_cache {
 1004:     &purge_remembered();
 1005:     #&Apache::loncommon::validate_page();
 1006:     undef(%env);
 1007:     undef($env_loaded);
 1008: }
 1009: 
 1010: my $to_remember=-1;
 1011: my %remembered;
 1012: my %accessed;
 1013: my $kicks=0;
 1014: my $hits=0;
 1015: sub devalidate_cache_new {
 1016:     my ($name,$id,$debug) = @_;
 1017:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1018:     $id=&escape($name.':'.$id);
 1019:     $memcache->delete($id);
 1020:     delete($remembered{$id});
 1021:     delete($accessed{$id});
 1022: }
 1023: 
 1024: sub is_cached_new {
 1025:     my ($name,$id,$debug) = @_;
 1026:     $id=&escape($name.':'.$id);
 1027:     if (exists($remembered{$id})) {
 1028: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1029: 	$accessed{$id}=[&gettimeofday()];
 1030: 	$hits++;
 1031: 	return ($remembered{$id},1);
 1032:     }
 1033:     my $value = $memcache->get($id);
 1034:     if (!(defined($value))) {
 1035: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1036: 	return (undef,undef);
 1037:     }
 1038:     if ($value eq '__undef__') {
 1039: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1040: 	$value=undef;
 1041:     }
 1042:     &make_room($id,$value,$debug);
 1043:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1044:     return ($value,1);
 1045: }
 1046: 
 1047: sub do_cache_new {
 1048:     my ($name,$id,$value,$time,$debug) = @_;
 1049:     $id=&escape($name.':'.$id);
 1050:     my $setvalue=$value;
 1051:     if (!defined($setvalue)) {
 1052: 	$setvalue='__undef__';
 1053:     }
 1054:     if (!defined($time) ) {
 1055: 	$time=600;
 1056:     }
 1057:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1058:     $memcache->set($id,$setvalue,$time);
 1059:     # need to make a copy of $value
 1060:     #&make_room($id,$value,$debug);
 1061:     return $value;
 1062: }
 1063: 
 1064: sub make_room {
 1065:     my ($id,$value,$debug)=@_;
 1066:     $remembered{$id}=$value;
 1067:     if ($to_remember<0) { return; }
 1068:     $accessed{$id}=[&gettimeofday()];
 1069:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1070:     my $to_kick;
 1071:     my $max_time=0;
 1072:     foreach my $other (keys(%accessed)) {
 1073: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1074: 	    $to_kick=$other;
 1075: 	    $max_time=&tv_interval($accessed{$other});
 1076: 	}
 1077:     }
 1078:     delete($remembered{$to_kick});
 1079:     delete($accessed{$to_kick});
 1080:     $kicks++;
 1081:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1082:     return;
 1083: }
 1084: 
 1085: sub purge_remembered {
 1086:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1087:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1088:     undef(%remembered);
 1089:     undef(%accessed);
 1090: }
 1091: # ------------------------------------- Read an entry from a user's environment
 1092: 
 1093: sub userenvironment {
 1094:     my ($udom,$unam,@what)=@_;
 1095:     my %returnhash=();
 1096:     my @answer=split(/\&/,
 1097:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1098:                       &homeserver($unam,$udom)));
 1099:     my $i;
 1100:     for ($i=0;$i<=$#what;$i++) {
 1101: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1102:     }
 1103:     return %returnhash;
 1104: }
 1105: 
 1106: # ---------------------------------------------------------- Get a studentphoto
 1107: sub studentphoto {
 1108:     my ($udom,$unam,$ext) = @_;
 1109:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1110:     if (defined($env{'request.course.id'})) {
 1111:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1112:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1113:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1114:             } else {
 1115:                 my ($result,$perm_reqd)=
 1116: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1117:                 if ($result eq 'ok') {
 1118:                     if (!($perm_reqd eq 'yes')) {
 1119:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1120:                     }
 1121:                 }
 1122:             }
 1123:         }
 1124:     } else {
 1125:         my ($result,$perm_reqd) = 
 1126: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1127:         if ($result eq 'ok') {
 1128:             if (!($perm_reqd eq 'yes')) {
 1129:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1130:             }
 1131:         }
 1132:     }
 1133:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1134: }
 1135: 
 1136: sub retrievestudentphoto {
 1137:     my ($udom,$unam,$ext,$type) = @_;
 1138:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1139:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1140:     if ($ret eq 'ok') {
 1141:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1142:         if ($type eq 'thumbnail') {
 1143:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1144:         }
 1145:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1146:         return $tokenurl;
 1147:     } else {
 1148:         if ($type eq 'thumbnail') {
 1149:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1150:         } else { 
 1151:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1152:         }
 1153:     }
 1154: }
 1155: 
 1156: # -------------------------------------------------------------------- New chat
 1157: 
 1158: sub chatsend {
 1159:     my ($newentry,$anon,$group)=@_;
 1160:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1161:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1162:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1163:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1164: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1165: 		   &escape($newentry)).':'.$group,$chome);
 1166: }
 1167: 
 1168: # ------------------------------------------ Find current version of a resource
 1169: 
 1170: sub getversion {
 1171:     my $fname=&clutter(shift);
 1172:     unless ($fname=~/^\/res\//) { return -1; }
 1173:     return &currentversion(&filelocation('',$fname));
 1174: }
 1175: 
 1176: sub currentversion {
 1177:     my $fname=shift;
 1178:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1179:     if (defined($cached)) { return $result; }
 1180:     my $author=$fname;
 1181:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1182:     my ($udom,$uname)=split(/\//,$author);
 1183:     my $home=homeserver($uname,$udom);
 1184:     if ($home eq 'no_host') { 
 1185:         return -1; 
 1186:     }
 1187:     my $answer=reply("currentversion:$fname",$home);
 1188:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1189: 	return -1;
 1190:     }
 1191:     return &do_cache_new('resversion',$fname,$answer,600);
 1192: }
 1193: 
 1194: # ----------------------------- Subscribe to a resource, return URL if possible
 1195: 
 1196: sub subscribe {
 1197:     my $fname=shift;
 1198:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1199:     $fname=~s/[\n\r]//g;
 1200:     my $author=$fname;
 1201:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1202:     my ($udom,$uname)=split(/\//,$author);
 1203:     my $home=homeserver($uname,$udom);
 1204:     if ($home eq 'no_host') {
 1205:         return 'not_found';
 1206:     }
 1207:     my $answer=reply("sub:$fname",$home);
 1208:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1209: 	$answer.=' by '.$home;
 1210:     }
 1211:     return $answer;
 1212: }
 1213:     
 1214: # -------------------------------------------------------------- Replicate file
 1215: 
 1216: sub repcopy {
 1217:     my $filename=shift;
 1218:     $filename=~s/\/+/\//g;
 1219:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1220:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1221:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1222: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1223: 	return &repcopy_userfile($filename);
 1224:     }
 1225:     $filename=~s/[\n\r]//g;
 1226:     my $transname="$filename.in.transfer";
 1227: # FIXME: this should flock
 1228:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1229:     my $remoteurl=subscribe($filename);
 1230:     if ($remoteurl =~ /^con_lost by/) {
 1231: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1232:            return 'unavailable';
 1233:     } elsif ($remoteurl eq 'not_found') {
 1234: 	   #&logthis("Subscribe returned not_found: $filename");
 1235: 	   return 'not_found';
 1236:     } elsif ($remoteurl =~ /^rejected by/) {
 1237: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1238:            return 'forbidden';
 1239:     } elsif ($remoteurl eq 'directory') {
 1240:            return 'ok';
 1241:     } else {
 1242:         my $author=$filename;
 1243:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1244:         my ($udom,$uname)=split(/\//,$author);
 1245:         my $home=homeserver($uname,$udom);
 1246:         unless ($home eq $perlvar{'lonHostID'}) {
 1247:            my @parts=split(/\//,$filename);
 1248:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1249:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1250:                &logthis("Malconfiguration for replication: $filename");
 1251: 	       return 'bad_request';
 1252:            }
 1253:            my $count;
 1254:            for ($count=5;$count<$#parts;$count++) {
 1255:                $path.="/$parts[$count]";
 1256:                if ((-e $path)!=1) {
 1257: 		   mkdir($path,0777);
 1258:                }
 1259:            }
 1260:            my $ua=new LWP::UserAgent;
 1261:            my $request=new HTTP::Request('GET',"$remoteurl");
 1262:            my $response=$ua->request($request,$transname);
 1263:            if ($response->is_error()) {
 1264: 	       unlink($transname);
 1265:                my $message=$response->status_line;
 1266:                &logthis("<font color=\"blue\">WARNING:"
 1267:                        ." LWP get: $message: $filename</font>");
 1268:                return 'unavailable';
 1269:            } else {
 1270: 	       if ($remoteurl!~/\.meta$/) {
 1271:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1272:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1273:                   if ($mresponse->is_error()) {
 1274: 		      unlink($filename.'.meta');
 1275:                       &logthis(
 1276:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1277:                   }
 1278: 	       }
 1279:                rename($transname,$filename);
 1280:                return 'ok';
 1281:            }
 1282:        }
 1283:     }
 1284: }
 1285: 
 1286: # ------------------------------------------------ Get server side include body
 1287: sub ssi_body {
 1288:     my ($filelink,%form)=@_;
 1289:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1290:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1291:     }
 1292:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1293:                                      &ssi($filelink,%form));
 1294:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1295:     $output=~s/^.*?\<body[^\>]*\>//si;
 1296:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1297:     return $output;
 1298: }
 1299: 
 1300: # --------------------------------------------------------- Server Side Include
 1301: 
 1302: sub absolute_url {
 1303:     my ($host_name) = @_;
 1304:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1305:     if ($host_name eq '') {
 1306: 	$host_name = $ENV{'SERVER_NAME'};
 1307:     }
 1308:     return $protocol.$host_name;
 1309: }
 1310: 
 1311: sub ssi {
 1312: 
 1313:     my ($fn,%form)=@_;
 1314: 
 1315:     my $ua=new LWP::UserAgent;
 1316:     
 1317:     my $request;
 1318: 
 1319:     $form{'no_update_last_known'}=1;
 1320: 
 1321:     if (%form) {
 1322:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1323:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1324:     } else {
 1325:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1326:     }
 1327: 
 1328:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1329:     my $response=$ua->request($request);
 1330: 
 1331:     return $response->content;
 1332: }
 1333: 
 1334: sub externalssi {
 1335:     my ($url)=@_;
 1336:     my $ua=new LWP::UserAgent;
 1337:     my $request=new HTTP::Request('GET',$url);
 1338:     my $response=$ua->request($request);
 1339:     return $response->content;
 1340: }
 1341: 
 1342: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1343: 
 1344: sub allowuploaded {
 1345:     my ($srcurl,$url)=@_;
 1346:     $url=&clutter(&declutter($url));
 1347:     my $dir=$url;
 1348:     $dir=~s/\/[^\/]+$//;
 1349:     my %httpref=();
 1350:     my $httpurl=&hreflocation('',$url);
 1351:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1352:     &Apache::lonnet::appenv(%httpref);
 1353: }
 1354: 
 1355: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1356: # input: action, courseID, current domain, intended
 1357: #        path to file, source of file, instruction to parse file for objects,
 1358: #        ref to hash for embedded objects,
 1359: #        ref to hash for codebase of java objects.
 1360: #
 1361: # output: url to file (if action was uploaddoc), 
 1362: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1363: #
 1364: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1365: # course.
 1366: #
 1367: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1368: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1369: #          course's home server.
 1370: #
 1371: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1372: #          be copied from $source (current location) to 
 1373: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1374: #         and will then be copied to
 1375: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1376: #         course's home server.
 1377: #
 1378: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1379: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1380: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1381: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1382: #         in course's home server.
 1383: #
 1384: 
 1385: sub process_coursefile {
 1386:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1387:     my $fetchresult;
 1388:     my $home=&homeserver($docuname,$docudom);
 1389:     if ($action eq 'propagate') {
 1390:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1391: 			     $home);
 1392:     } else {
 1393:         my $fpath = '';
 1394:         my $fname = $file;
 1395:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1396:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1397:         my $filepath = &build_filepath($fpath);
 1398:         if ($action eq 'copy') {
 1399:             if ($source eq '') {
 1400:                 $fetchresult = 'no source file';
 1401:                 return $fetchresult;
 1402:             } else {
 1403:                 my $destination = $filepath.'/'.$fname;
 1404:                 rename($source,$destination);
 1405:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1406:                                  $home);
 1407:             }
 1408:         } elsif ($action eq 'uploaddoc') {
 1409:             open(my $fh,'>'.$filepath.'/'.$fname);
 1410:             print $fh $env{'form.'.$source};
 1411:             close($fh);
 1412:             if ($parser eq 'parse') {
 1413:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1414:                 unless ($parse_result eq 'ok') {
 1415:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1416:                 }
 1417:             }
 1418:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1419:                                  $home);
 1420:             if ($fetchresult eq 'ok') {
 1421:                 return '/uploaded/'.$fpath.'/'.$fname;
 1422:             } else {
 1423:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1424:                         ' to host '.$home.': '.$fetchresult);
 1425:                 return '/adm/notfound.html';
 1426:             }
 1427:         }
 1428:     }
 1429:     unless ( $fetchresult eq 'ok') {
 1430:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1431:              ' to host '.$home.': '.$fetchresult);
 1432:     }
 1433:     return $fetchresult;
 1434: }
 1435: 
 1436: sub build_filepath {
 1437:     my ($fpath) = @_;
 1438:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1439:     unless ($fpath eq '') {
 1440:         my @parts=split('/',$fpath);
 1441:         foreach my $part (@parts) {
 1442:             $filepath.= '/'.$part;
 1443:             if ((-e $filepath)!=1) {
 1444:                 mkdir($filepath,0777);
 1445:             }
 1446:         }
 1447:     }
 1448:     return $filepath;
 1449: }
 1450: 
 1451: sub store_edited_file {
 1452:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1453:     my $file = $primary_url;
 1454:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1455:     my $fpath = '';
 1456:     my $fname = $file;
 1457:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1458:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1459:     my $filepath = &build_filepath($fpath);
 1460:     open(my $fh,'>'.$filepath.'/'.$fname);
 1461:     print $fh $content;
 1462:     close($fh);
 1463:     my $home=&homeserver($docuname,$docudom);
 1464:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1465: 			  $home);
 1466:     if ($$fetchresult eq 'ok') {
 1467:         return '/uploaded/'.$fpath.'/'.$fname;
 1468:     } else {
 1469:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1470: 		 ' to host '.$home.': '.$$fetchresult);
 1471:         return '/adm/notfound.html';
 1472:     }
 1473: }
 1474: 
 1475: sub clean_filename {
 1476:     my ($fname,$args)=@_;
 1477: # Replace Windows backslashes by forward slashes
 1478:     $fname=~s/\\/\//g;
 1479:     if (!$args->{'keep_path'}) {
 1480:         # Get rid of everything but the actual filename
 1481: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1482:     }
 1483: # Replace spaces by underscores
 1484:     $fname=~s/\s+/\_/g;
 1485: # Replace all other weird characters by nothing
 1486:     $fname=~s{[^/\w\.\-]}{}g;
 1487: # Replace all .\d. sequences with _\d. so they no longer look like version
 1488: # numbers
 1489:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1490:     return $fname;
 1491: }
 1492: 
 1493: # --------------- Take an uploaded file and put it into the userfiles directory
 1494: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1495: #                    the desired filenam is in $env{"form.$formname.filename"}
 1496: #        $coursedoc - if true up to the current course
 1497: #                     if false
 1498: #        $subdir - directory in userfile to store the file into
 1499: #        $parser, $allfiles, $codebase - unknown
 1500: #
 1501: # output: url of file in userspace, or error: <message> 
 1502: #             or /adm/notfound.html if failure to upload occurse
 1503: 
 1504: 
 1505: sub userfileupload {
 1506:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1507:     if (!defined($subdir)) { $subdir='unknown'; }
 1508:     my $fname=$env{'form.'.$formname.'.filename'};
 1509:     $fname=&clean_filename($fname);
 1510: # See if there is anything left
 1511:     unless ($fname) { return 'error: no uploaded file'; }
 1512:     chop($env{'form.'.$formname});
 1513:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1514:         my $now = time;
 1515:         my $filepath = 'tmp/helprequests/'.$now;
 1516:         my @parts=split(/\//,$filepath);
 1517:         my $fullpath = $perlvar{'lonDaemons'};
 1518:         for (my $i=0;$i<@parts;$i++) {
 1519:             $fullpath .= '/'.$parts[$i];
 1520:             if ((-e $fullpath)!=1) {
 1521:                 mkdir($fullpath,0777);
 1522:             }
 1523:         }
 1524:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1525:         print $fh $env{'form.'.$formname};
 1526:         close($fh);
 1527:         return $fullpath.'/'.$fname;
 1528:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1529:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1530:                        '_'.$env{'user.domain'}.'/pending';
 1531:         my @parts=split(/\//,$filepath);
 1532:         my $fullpath = $perlvar{'lonDaemons'};
 1533:         for (my $i=0;$i<@parts;$i++) {
 1534:             $fullpath .= '/'.$parts[$i];
 1535:             if ((-e $fullpath)!=1) {
 1536:                 mkdir($fullpath,0777);
 1537:             }
 1538:         }
 1539:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1540:         print $fh $env{'form.'.$formname};
 1541:         close($fh);
 1542:         return $fullpath.'/'.$fname;
 1543:     }
 1544:     
 1545: # Create the directory if not present
 1546:     $fname="$subdir/$fname";
 1547:     if ($coursedoc) {
 1548: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1549: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1550:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1551:             return &finishuserfileupload($docuname,$docudom,
 1552: 					 $formname,$fname,$parser,$allfiles,
 1553: 					 $codebase);
 1554:         } else {
 1555:             $fname=$env{'form.folder'}.'/'.$fname;
 1556:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1557: 				       $fname,$formname,$parser,
 1558: 				       $allfiles,$codebase);
 1559:         }
 1560:     } elsif (defined($destuname)) {
 1561:         my $docuname=$destuname;
 1562:         my $docudom=$destudom;
 1563: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1564: 				     $fname,$parser,$allfiles,$codebase);
 1565:         
 1566:     } else {
 1567:         my $docuname=$env{'user.name'};
 1568:         my $docudom=$env{'user.domain'};
 1569:         if (exists($env{'form.group'})) {
 1570:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1571:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1572:         }
 1573: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1574: 				     $fname,$parser,$allfiles,$codebase);
 1575:     }
 1576: }
 1577: 
 1578: sub finishuserfileupload {
 1579:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1580:     my $path=$docudom.'/'.$docuname.'/';
 1581:     my $filepath=$perlvar{'lonDocRoot'};
 1582:     my ($fnamepath,$file);
 1583:     $file=$fname;
 1584:     if ($fname=~m|/|) {
 1585:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1586: 	$path.=$fnamepath.'/';
 1587:     }
 1588:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1589:     my $count;
 1590:     for ($count=4;$count<=$#parts;$count++) {
 1591:         $filepath.="/$parts[$count]";
 1592:         if ((-e $filepath)!=1) {
 1593: 	    mkdir($filepath,0777);
 1594:         }
 1595:     }
 1596: # Save the file
 1597:     {
 1598: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1599: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1600: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1601: 	    return '/adm/notfound.html';
 1602: 	}
 1603: 	if (!print FH ($env{'form.'.$formname})) {
 1604: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1605: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1606: 	    return '/adm/notfound.html';
 1607: 	}
 1608: 	close(FH);
 1609:     }
 1610:     if ($parser eq 'parse') {
 1611:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1612: 						   $codebase);
 1613:         unless ($parse_result eq 'ok') {
 1614:             &logthis('Failed to parse '.$filepath.$file.
 1615: 		     ' for embedded media: '.$parse_result); 
 1616:         }
 1617:     }
 1618: # Notify homeserver to grep it
 1619: #
 1620:     my $docuhome=&homeserver($docuname,$docudom);
 1621:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1622:     if ($fetchresult eq 'ok') {
 1623: #
 1624: # Return the URL to it
 1625:         return '/uploaded/'.$path.$file;
 1626:     } else {
 1627:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1628: 		 ': '.$fetchresult);
 1629:         return '/adm/notfound.html';
 1630:     }    
 1631: }
 1632: 
 1633: sub extract_embedded_items {
 1634:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1635:     my @state = ();
 1636:     my %javafiles = (
 1637:                       codebase => '',
 1638:                       code => '',
 1639:                       archive => ''
 1640:                     );
 1641:     my %mediafiles = (
 1642:                       src => '',
 1643:                       movie => '',
 1644:                      );
 1645:     my $p;
 1646:     if ($content) {
 1647:         $p = HTML::LCParser->new($content);
 1648:     } else {
 1649:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1650:     }
 1651:     while (my $t=$p->get_token()) {
 1652: 	if ($t->[0] eq 'S') {
 1653: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1654: 	    push (@state, $tagname);
 1655:             if (lc($tagname) eq 'allow') {
 1656:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1657:             }
 1658: 	    if (lc($tagname) eq 'img') {
 1659: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1660: 	    }
 1661:             if (lc($tagname) eq 'script') {
 1662:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1663:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1664:                 } else {
 1665:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1666:                 }
 1667:             }
 1668:             if (lc($tagname) eq 'link') {
 1669:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1670:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1671:                 }
 1672:             }
 1673: 	    if (lc($tagname) eq 'object' ||
 1674: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1675: 		foreach my $item (keys(%javafiles)) {
 1676: 		    $javafiles{$item} = '';
 1677: 		}
 1678: 	    }
 1679: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1680: 		my $name = lc($attr->{'name'});
 1681: 		foreach my $item (keys(%javafiles)) {
 1682: 		    if ($name eq $item) {
 1683: 			$javafiles{$item} = $attr->{'value'};
 1684: 			last;
 1685: 		    }
 1686: 		}
 1687: 		foreach my $item (keys(%mediafiles)) {
 1688: 		    if ($name eq $item) {
 1689: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1690: 			last;
 1691: 		    }
 1692: 		}
 1693: 	    }
 1694: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1695: 		foreach my $item (keys(%javafiles)) {
 1696: 		    if ($attr->{$item}) {
 1697: 			$javafiles{$item} = $attr->{$item};
 1698: 			last;
 1699: 		    }
 1700: 		}
 1701: 		foreach my $item (keys(%mediafiles)) {
 1702: 		    if ($attr->{$item}) {
 1703: 			&add_filetype($allfiles,$attr->{$item},$item);
 1704: 			last;
 1705: 		    }
 1706: 		}
 1707: 	    }
 1708: 	} elsif ($t->[0] eq 'E') {
 1709: 	    my ($tagname) = ($t->[1]);
 1710: 	    if ($javafiles{'codebase'} ne '') {
 1711: 		$javafiles{'codebase'} .= '/';
 1712: 	    }  
 1713: 	    if (lc($tagname) eq 'applet' ||
 1714: 		lc($tagname) eq 'object' ||
 1715: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1716: 		) {
 1717: 		foreach my $item (keys(%javafiles)) {
 1718: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1719: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1720: 			&add_filetype($allfiles,$file,$item);
 1721: 		    }
 1722: 		}
 1723: 	    } 
 1724: 	    pop @state;
 1725: 	}
 1726:     }
 1727:     return 'ok';
 1728: }
 1729: 
 1730: sub add_filetype {
 1731:     my ($allfiles,$file,$type)=@_;
 1732:     if (exists($allfiles->{$file})) {
 1733: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1734: 	    push(@{$allfiles->{$file}}, &escape($type));
 1735: 	}
 1736:     } else {
 1737: 	@{$allfiles->{$file}} = (&escape($type));
 1738:     }
 1739: }
 1740: 
 1741: sub removeuploadedurl {
 1742:     my ($url)=@_;
 1743:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1744:     return &removeuserfile($uname,$udom,$fname);
 1745: }
 1746: 
 1747: sub removeuserfile {
 1748:     my ($docuname,$docudom,$fname)=@_;
 1749:     my $home=&homeserver($docuname,$docudom);
 1750:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1751:     if ($result eq 'ok') {
 1752:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1753:             my $metafile = $fname.'.meta';
 1754:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1755: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1756:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1757:             my $sqlresult = 
 1758:                 &update_portfolio_table($docuname,$docudom,$file,
 1759:                                         'portfolio_metadata',$group,
 1760:                                         'delete');
 1761:         }
 1762:     }
 1763:     return $result;
 1764: }
 1765: 
 1766: sub mkdiruserfile {
 1767:     my ($docuname,$docudom,$dir)=@_;
 1768:     my $home=&homeserver($docuname,$docudom);
 1769:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1770: }
 1771: 
 1772: sub renameuserfile {
 1773:     my ($docuname,$docudom,$old,$new)=@_;
 1774:     my $home=&homeserver($docuname,$docudom);
 1775:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1776:                         &escape("$old").':'.&escape("$new"),$home);
 1777:     if ($result eq 'ok') {
 1778:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1779:             my $oldmeta = $old.'.meta';
 1780:             my $newmeta = $new.'.meta';
 1781:             my $metaresult = 
 1782:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1783: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1784:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1785:             my $sqlresult = 
 1786:                 &update_portfolio_table($docuname,$docudom,$file,
 1787:                                         'portfolio_metadata',$group,
 1788:                                         'delete');
 1789:         }
 1790:     }
 1791:     return $result;
 1792: }
 1793: 
 1794: # ------------------------------------------------------------------------- Log
 1795: 
 1796: sub log {
 1797:     my ($dom,$nam,$hom,$what)=@_;
 1798:     return critical("log:$dom:$nam:$what",$hom);
 1799: }
 1800: 
 1801: # ------------------------------------------------------------------ Course Log
 1802: #
 1803: # This routine flushes several buffers of non-mission-critical nature
 1804: #
 1805: 
 1806: sub flushcourselogs {
 1807:     &logthis('Flushing log buffers');
 1808: #
 1809: # course logs
 1810: # This is a log of all transactions in a course, which can be used
 1811: # for data mining purposes
 1812: #
 1813: # It also collects the courseid database, which lists last transaction
 1814: # times and course titles for all courseids
 1815: #
 1816:     my %courseidbuffer=();
 1817:     foreach my $crsid (keys %courselogs) {
 1818:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1819: 		          &escape($courselogs{$crsid}),
 1820: 		          $coursehombuf{$crsid}) eq 'ok') {
 1821: 	    delete $courselogs{$crsid};
 1822:         } else {
 1823:             &logthis('Failed to flush log buffer for '.$crsid);
 1824:             if (length($courselogs{$crsid})>40000) {
 1825:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1826:                         " exceeded maximum size, deleting.</font>");
 1827:                delete $courselogs{$crsid};
 1828:             }
 1829:         }
 1830:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1831:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1832: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1833:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1834:         } else {
 1835:            $courseidbuffer{$coursehombuf{$crsid}}=
 1836: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1837:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1838:         }
 1839:     }
 1840: #
 1841: # Write course id database (reverse lookup) to homeserver of courses 
 1842: # Is used in pickcourse
 1843: #
 1844:     foreach my $crs_home (keys(%courseidbuffer)) {
 1845:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1846: 		     $crs_home);
 1847:     }
 1848: #
 1849: # File accesses
 1850: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1851: #
 1852:     foreach my $entry (keys(%accesshash)) {
 1853:         if ($entry =~ /___count$/) {
 1854:             my ($dom,$name);
 1855:             ($dom,$name,undef)=
 1856: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1857:             if (! defined($dom) || $dom eq '' || 
 1858:                 ! defined($name) || $name eq '') {
 1859:                 my $cid = $env{'request.course.id'};
 1860:                 $dom  = $env{'request.'.$cid.'.domain'};
 1861:                 $name = $env{'request.'.$cid.'.num'};
 1862:             }
 1863:             my $value = $accesshash{$entry};
 1864:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1865:             my %temphash=($url => $value);
 1866:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1867:             if ($result eq 'ok') {
 1868:                 delete $accesshash{$entry};
 1869:             } elsif ($result eq 'unknown_cmd') {
 1870:                 # Target server has old code running on it.
 1871:                 my %temphash=($entry => $value);
 1872:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1873:                     delete $accesshash{$entry};
 1874:                 }
 1875:             }
 1876:         } else {
 1877:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1878:             my %temphash=($entry => $accesshash{$entry});
 1879:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1880:                 delete $accesshash{$entry};
 1881:             }
 1882:         }
 1883:     }
 1884: #
 1885: # Roles
 1886: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1887: #
 1888:     foreach my $entry (keys(%userrolehash)) {
 1889:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1890: 	    split(/\:/,$entry);
 1891:         if (&Apache::lonnet::put('nohist_userroles',
 1892:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1893:                 $rudom,$runame) eq 'ok') {
 1894: 	    delete $userrolehash{$entry};
 1895:         }
 1896:     }
 1897: #
 1898: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1899: #
 1900:     my %domrolebuffer = ();
 1901:     foreach my $entry (keys %domainrolehash) {
 1902:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1903:         if ($domrolebuffer{$rudom}) {
 1904:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1905:                       '='.&escape($domainrolehash{$entry});
 1906:         } else {
 1907:             $domrolebuffer{$rudom}.=&escape($entry).
 1908:                       '='.&escape($domainrolehash{$entry});
 1909:         }
 1910:         delete $domainrolehash{$entry};
 1911:     }
 1912:     foreach my $dom (keys(%domrolebuffer)) {
 1913: 	my %servers = &get_servers($dom,'library');
 1914: 	foreach my $tryserver (keys(%servers)) {
 1915: 	    unless (&reply('domroleput:'.$dom.':'.
 1916: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1917: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1918: 	    }
 1919:         }
 1920:     }
 1921:     $dumpcount++;
 1922: }
 1923: 
 1924: sub courselog {
 1925:     my $what=shift;
 1926:     $what=time.':'.$what;
 1927:     unless ($env{'request.course.id'}) { return ''; }
 1928:     $coursedombuf{$env{'request.course.id'}}=
 1929:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1930:     $coursenumbuf{$env{'request.course.id'}}=
 1931:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1932:     $coursehombuf{$env{'request.course.id'}}=
 1933:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1934:     $coursedescrbuf{$env{'request.course.id'}}=
 1935:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1936:     $courseinstcodebuf{$env{'request.course.id'}}=
 1937:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1938:     $courseownerbuf{$env{'request.course.id'}}=
 1939:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1940:     $coursetypebuf{$env{'request.course.id'}}=
 1941:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1942:     if (defined $courselogs{$env{'request.course.id'}}) {
 1943: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1944:     } else {
 1945: 	$courselogs{$env{'request.course.id'}}.=$what;
 1946:     }
 1947:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1948: 	&flushcourselogs();
 1949:     }
 1950: }
 1951: 
 1952: sub courseacclog {
 1953:     my $fnsymb=shift;
 1954:     unless ($env{'request.course.id'}) { return ''; }
 1955:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1956:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1957:         $what.=':POST';
 1958:         # FIXME: Probably ought to escape things....
 1959: 	foreach my $key (keys(%env)) {
 1960:             if ($key=~/^form\.(.*)/) {
 1961: 		$what.=':'.$1.'='.$env{$key};
 1962:             }
 1963:         }
 1964:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1965:         # FIXME: We should not be depending on a form parameter that someone
 1966:         # editing lonsearchcat.pm might change in the future.
 1967:         if ($env{'form.phase'} eq 'course_search') {
 1968:             $what.= ':POST';
 1969:             # FIXME: Probably ought to escape things....
 1970:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1971:                                  'crsdiscuss') {
 1972:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1973:             }
 1974:         }
 1975:     }
 1976:     &courselog($what);
 1977: }
 1978: 
 1979: sub countacc {
 1980:     my $url=&declutter(shift);
 1981:     return if (! defined($url) || $url eq '');
 1982:     unless ($env{'request.course.id'}) { return ''; }
 1983:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1984:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1985:     $accesshash{$key}++;
 1986: }
 1987: 
 1988: sub linklog {
 1989:     my ($from,$to)=@_;
 1990:     $from=&declutter($from);
 1991:     $to=&declutter($to);
 1992:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1993:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1994: }
 1995:   
 1996: sub userrolelog {
 1997:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1998:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1999:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2000:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2001:         ($trole=~/^ta/)) {
 2002:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2003:        $userrolehash
 2004:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2005:                     =$tend.':'.$tstart;
 2006:     }
 2007:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2008:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2009:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2010:         ($trole=~/^sc/)) {
 2011:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2012:        $domainrolehash
 2013:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2014:                     = $tend.':'.$tstart;
 2015:     }
 2016: }
 2017: 
 2018: sub get_course_adv_roles {
 2019:     my $cid=shift;
 2020:     $cid=$env{'request.course.id'} unless (defined($cid));
 2021:     my %coursehash=&coursedescription($cid);
 2022:     my %nothide=();
 2023:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2024: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2025:     }
 2026:     my %returnhash=();
 2027:     my %dumphash=
 2028:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2029:     my $now=time;
 2030:     foreach my $entry (keys %dumphash) {
 2031: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2032:         if (($tstart) && ($tstart<0)) { next; }
 2033:         if (($tend) && ($tend<$now)) { next; }
 2034:         if (($tstart) && ($now<$tstart)) { next; }
 2035:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2036: 	if ($username eq '' || $domain eq '') { next; }
 2037: 	if ((&privileged($username,$domain)) && 
 2038: 	    (!$nothide{$username.':'.$domain})) { next; }
 2039: 	if ($role eq 'cr') { next; }
 2040:         my $key=&plaintext($role);
 2041:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2042:         if ($returnhash{$key}) {
 2043: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2044:         } else {
 2045:             $returnhash{$key}=$username.':'.$domain;
 2046:         }
 2047:      }
 2048:     return %returnhash;
 2049: }
 2050: 
 2051: sub get_my_roles {
 2052:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
 2053:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2054:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2055:     my %dumphash=
 2056:             &dump('nohist_userroles',$udom,$uname);
 2057:     my %returnhash=();
 2058:     my $now=time;
 2059:     foreach my $entry (keys(%dumphash)) {
 2060: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2061:         if (($tstart) && ($tstart<0)) { next; }
 2062:         my $status = 'active';
 2063:         if (($tend) && ($tend<$now)) {
 2064:             $status = 'previous';
 2065:         } 
 2066:         if (($tstart) && ($now<$tstart)) {
 2067:             $status = 'future';
 2068:         }
 2069:         if (ref($types) eq 'ARRAY') {
 2070:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2071:                 next;
 2072:             } 
 2073:         } else {
 2074:             if ($status ne 'active') {
 2075:                 next;
 2076:             }
 2077:         }
 2078:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2079:         if (ref($roledoms) eq 'ARRAY') {
 2080:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2081:                 next;
 2082:             }
 2083:         }
 2084:         if (ref($roles) eq 'ARRAY') {
 2085:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2086:                 next;
 2087:             }
 2088:         } 
 2089: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2090:     }
 2091:     return %returnhash;
 2092: }
 2093: 
 2094: # ----------------------------------------------------- Frontpage Announcements
 2095: #
 2096: #
 2097: 
 2098: sub postannounce {
 2099:     my ($server,$text)=@_;
 2100:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2101:     unless ($text=~/\w/) { $text=''; }
 2102:     return &reply('setannounce:'.&escape($text),$server);
 2103: }
 2104: 
 2105: sub getannounce {
 2106: 
 2107:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2108: 	my $announcement='';
 2109: 	while (my $line = <$fh>) { $announcement .= $line; }
 2110: 	close($fh);
 2111: 	if ($announcement=~/\w/) { 
 2112: 	    return 
 2113:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2114:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2115: 	} else {
 2116: 	    return '';
 2117: 	}
 2118:     } else {
 2119: 	return '';
 2120:     }
 2121: }
 2122: 
 2123: # ---------------------------------------------------------- Course ID routines
 2124: # Deal with domain's nohist_courseid.db files
 2125: #
 2126: 
 2127: sub courseidput {
 2128:     my ($domain,$what,$coursehome)=@_;
 2129:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2130: }
 2131: 
 2132: sub courseiddump {
 2133:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2134:     my %returnhash=();
 2135:     unless ($domfilter) { $domfilter=''; }
 2136:     my %libserv = &all_library();
 2137:     foreach my $tryserver (keys(%libserv)) {
 2138:         if ( (  $hostidflag == 1 
 2139: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2140: 	     || (!defined($hostidflag)) ) {
 2141: 
 2142: 	    if ($domfilter eq ''
 2143: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2144: 	        foreach my $line (
 2145:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2146: 			       $sincefilter.':'.&escape($descfilter).':'.
 2147:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2148:                                $tryserver))) {
 2149: 		    my ($key,$value)=split(/\=/,$line,2);
 2150:                     if (($key) && ($value)) {
 2151: 		        $returnhash{&unescape($key)}=$value;
 2152:                     }
 2153:                 }
 2154:             }
 2155:         }
 2156:     }
 2157:     return %returnhash;
 2158: }
 2159: 
 2160: # ---------------------------------------------------------- DC e-mail
 2161: 
 2162: sub dcmailput {
 2163:     my ($domain,$msgid,$message,$server)=@_;
 2164:     my $status = &Apache::lonnet::critical(
 2165:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2166:        &escape($message),$server);
 2167:     return $status;
 2168: }
 2169: 
 2170: sub dcmaildump {
 2171:     my ($dom,$startdate,$enddate,$senders) = @_;
 2172:     my %returnhash=();
 2173:     if (exists($domain_primary{$dom})) {
 2174:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2175:                                                          &escape($enddate).':';
 2176: 	my @esc_senders=map { &escape($_)} @$senders;
 2177: 	$cmd.=&escape(join('&',@esc_senders));
 2178: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2179:             my ($key,$value) = split(/\=/,$line,2);
 2180:             if (($key) && ($value)) {
 2181:                 $returnhash{&unescape($key)} = &unescape($value);
 2182:             }
 2183:         }
 2184:     }
 2185:     return %returnhash;
 2186: }
 2187: # ---------------------------------------------------------- Domain roles
 2188: 
 2189: sub get_domain_roles {
 2190:     my ($dom,$roles,$startdate,$enddate)=@_;
 2191:     if (undef($startdate) || $startdate eq '') {
 2192:         $startdate = '.';
 2193:     }
 2194:     if (undef($enddate) || $enddate eq '') {
 2195:         $enddate = '.';
 2196:     }
 2197:     my $rolelist = join(':',@{$roles});
 2198:     my %personnel = ();
 2199: 
 2200:     my %servers = &get_servers($dom,'library');
 2201:     foreach my $tryserver (keys(%servers)) {
 2202: 	%{$personnel{$tryserver}}=();
 2203: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2204: 					    &escape($startdate).':'.
 2205: 					    &escape($enddate).':'.
 2206: 					    &escape($rolelist), $tryserver))) {
 2207: 	    my ($key,$value) = split(/\=/,$line,2);
 2208: 	    if (($key) && ($value)) {
 2209: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2210: 	    }
 2211: 	}
 2212:     }
 2213:     return %personnel;
 2214: }
 2215: 
 2216: # ----------------------------------------------------------- Check out an item
 2217: 
 2218: sub get_first_access {
 2219:     my ($type,$argsymb)=@_;
 2220:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2221:     if ($argsymb) { $symb=$argsymb; }
 2222:     my ($map,$id,$res)=&decode_symb($symb);
 2223:     if ($type eq 'map') {
 2224: 	$res=&symbread($map);
 2225:     } else {
 2226: 	$res=$symb;
 2227:     }
 2228:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2229:     return $times{"$courseid\0$res"};
 2230: }
 2231: 
 2232: sub set_first_access {
 2233:     my ($type)=@_;
 2234:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2235:     my ($map,$id,$res)=&decode_symb($symb);
 2236:     if ($type eq 'map') {
 2237: 	$res=&symbread($map);
 2238:     } else {
 2239: 	$res=$symb;
 2240:     }
 2241:     my $firstaccess=&get_first_access($type,$symb);
 2242:     if (!$firstaccess) {
 2243: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2244:     }
 2245:     return 'already_set';
 2246: }
 2247: 
 2248: sub checkout {
 2249:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2250:     my $now=time;
 2251:     my $lonhost=$perlvar{'lonHostID'};
 2252:     my $infostr=&escape(
 2253:                  'CHECKOUTTOKEN&'.
 2254:                  $tuname.'&'.
 2255:                  $tudom.'&'.
 2256:                  $tcrsid.'&'.
 2257:                  $symb.'&'.
 2258: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2259:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2260:     if ($token=~/^error\:/) { 
 2261:         &logthis("<font color=\"blue\">WARNING: ".
 2262:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2263:                  "</font>");
 2264:         return ''; 
 2265:     }
 2266: 
 2267:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2268:     $token=~tr/a-z/A-Z/;
 2269: 
 2270:     my %infohash=('resource.0.outtoken' => $token,
 2271:                   'resource.0.checkouttime' => $now,
 2272:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2273: 
 2274:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2275:        return '';
 2276:     } else {
 2277:         &logthis("<font color=\"blue\">WARNING: ".
 2278:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2279:                  "</font>");
 2280:     }    
 2281: 
 2282:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2283:                          &escape('Checkout '.$infostr.' - '.
 2284:                                                  $token)) ne 'ok') {
 2285: 	return '';
 2286:     } else {
 2287:         &logthis("<font color=\"blue\">WARNING: ".
 2288:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2289:                  "</font>");
 2290:     }
 2291:     return $token;
 2292: }
 2293: 
 2294: # ------------------------------------------------------------ Check in an item
 2295: 
 2296: sub checkin {
 2297:     my $token=shift;
 2298:     my $now=time;
 2299:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2300:     $lonhost=~tr/A-Z/a-z/;
 2301:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2302:     $dtoken=~s/\W/\_/g;
 2303:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2304:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2305: 
 2306:     unless (($tuname) && ($tudom)) {
 2307:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2308:         return '';
 2309:     }
 2310:     
 2311:     unless (&allowed('mgr',$tcrsid)) {
 2312:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2313:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2314:         return '';
 2315:     }
 2316: 
 2317:     my %infohash=('resource.0.intoken' => $token,
 2318:                   'resource.0.checkintime' => $now,
 2319:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2320: 
 2321:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2322:        return '';
 2323:     }    
 2324: 
 2325:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2326:                          &escape('Checkin - '.$token)) ne 'ok') {
 2327: 	return '';
 2328:     }
 2329: 
 2330:     return ($symb,$tuname,$tudom,$tcrsid);    
 2331: }
 2332: 
 2333: # --------------------------------------------- Set Expire Date for Spreadsheet
 2334: 
 2335: sub expirespread {
 2336:     my ($uname,$udom,$stype,$usymb)=@_;
 2337:     my $cid=$env{'request.course.id'}; 
 2338:     if ($cid) {
 2339:        my $now=time;
 2340:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2341:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2342:                             $env{'course.'.$cid.'.num'}.
 2343: 	        	    ':nohist_expirationdates:'.
 2344:                             &escape($key).'='.$now,
 2345:                             $env{'course.'.$cid.'.home'})
 2346:     }
 2347:     return 'ok';
 2348: }
 2349: 
 2350: # ----------------------------------------------------- Devalidate Spreadsheets
 2351: 
 2352: sub devalidate {
 2353:     my ($symb,$uname,$udom)=@_;
 2354:     my $cid=$env{'request.course.id'}; 
 2355:     if ($cid) {
 2356:         # delete the stored spreadsheets for
 2357:         # - the student level sheet of this user in course's homespace
 2358:         # - the assessment level sheet for this resource 
 2359:         #   for this user in user's homespace
 2360: 	# - current conditional state info
 2361: 	my $key=$uname.':'.$udom.':';
 2362:         my $status=
 2363: 	    &del('nohist_calculatedsheets',
 2364: 		 [$key.'studentcalc:'],
 2365: 		 $env{'course.'.$cid.'.domain'},
 2366: 		 $env{'course.'.$cid.'.num'})
 2367: 		.' '.
 2368: 	    &del('nohist_calculatedsheets_'.$cid,
 2369: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2370:         unless ($status eq 'ok ok') {
 2371:            &logthis('Could not devalidate spreadsheet '.
 2372:                     $uname.' at '.$udom.' for '.
 2373: 		    $symb.': '.$status);
 2374:         }
 2375: 	&delenv('user.state.'.$cid);
 2376:     }
 2377: }
 2378: 
 2379: sub get_scalar {
 2380:     my ($string,$end) = @_;
 2381:     my $value;
 2382:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2383: 	$value = $1;
 2384:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2385: 	$value = $1;
 2386:     }
 2387:     return &unescape($value);
 2388: }
 2389: 
 2390: sub array2str {
 2391:   my (@array) = @_;
 2392:   my $result=&arrayref2str(\@array);
 2393:   $result=~s/^__ARRAY_REF__//;
 2394:   $result=~s/__END_ARRAY_REF__$//;
 2395:   return $result;
 2396: }
 2397: 
 2398: sub arrayref2str {
 2399:   my ($arrayref) = @_;
 2400:   my $result='__ARRAY_REF__';
 2401:   foreach my $elem (@$arrayref) {
 2402:     if(ref($elem) eq 'ARRAY') {
 2403:       $result.=&arrayref2str($elem).'&';
 2404:     } elsif(ref($elem) eq 'HASH') {
 2405:       $result.=&hashref2str($elem).'&';
 2406:     } elsif(ref($elem)) {
 2407:       #print("Got a ref of ".(ref($elem))." skipping.");
 2408:     } else {
 2409:       $result.=&escape($elem).'&';
 2410:     }
 2411:   }
 2412:   $result=~s/\&$//;
 2413:   $result .= '__END_ARRAY_REF__';
 2414:   return $result;
 2415: }
 2416: 
 2417: sub hash2str {
 2418:   my (%hash) = @_;
 2419:   my $result=&hashref2str(\%hash);
 2420:   $result=~s/^__HASH_REF__//;
 2421:   $result=~s/__END_HASH_REF__$//;
 2422:   return $result;
 2423: }
 2424: 
 2425: sub hashref2str {
 2426:   my ($hashref)=@_;
 2427:   my $result='__HASH_REF__';
 2428:   foreach my $key (sort(keys(%$hashref))) {
 2429:     if (ref($key) eq 'ARRAY') {
 2430:       $result.=&arrayref2str($key).'=';
 2431:     } elsif (ref($key) eq 'HASH') {
 2432:       $result.=&hashref2str($key).'=';
 2433:     } elsif (ref($key)) {
 2434:       $result.='=';
 2435:       #print("Got a ref of ".(ref($key))." skipping.");
 2436:     } else {
 2437: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2438:     }
 2439: 
 2440:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2441:       $result.=&arrayref2str($hashref->{$key}).'&';
 2442:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2443:       $result.=&hashref2str($hashref->{$key}).'&';
 2444:     } elsif(ref($hashref->{$key})) {
 2445:        $result.='&';
 2446:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2447:     } else {
 2448:       $result.=&escape($hashref->{$key}).'&';
 2449:     }
 2450:   }
 2451:   $result=~s/\&$//;
 2452:   $result .= '__END_HASH_REF__';
 2453:   return $result;
 2454: }
 2455: 
 2456: sub str2hash {
 2457:     my ($string)=@_;
 2458:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2459:     return %$hash;
 2460: }
 2461: 
 2462: sub str2hashref {
 2463:   my ($string) = @_;
 2464: 
 2465:   my %hash;
 2466: 
 2467:   if($string !~ /^__HASH_REF__/) {
 2468:       if (! ($string eq '' || !defined($string))) {
 2469: 	  $hash{'error'}='Not hash reference';
 2470:       }
 2471:       return (\%hash, $string);
 2472:   }
 2473: 
 2474:   $string =~ s/^__HASH_REF__//;
 2475: 
 2476:   while($string !~ /^__END_HASH_REF__/) {
 2477:       #key
 2478:       my $key='';
 2479:       if($string =~ /^__HASH_REF__/) {
 2480:           ($key, $string)=&str2hashref($string);
 2481:           if(defined($key->{'error'})) {
 2482:               $hash{'error'}='Bad data';
 2483:               return (\%hash, $string);
 2484:           }
 2485:       } elsif($string =~ /^__ARRAY_REF__/) {
 2486:           ($key, $string)=&str2arrayref($string);
 2487:           if($key->[0] eq 'Array reference error') {
 2488:               $hash{'error'}='Bad data';
 2489:               return (\%hash, $string);
 2490:           }
 2491:       } else {
 2492:           $string =~ s/^(.*?)=//;
 2493: 	  $key=&unescape($1);
 2494:       }
 2495:       $string =~ s/^=//;
 2496: 
 2497:       #value
 2498:       my $value='';
 2499:       if($string =~ /^__HASH_REF__/) {
 2500:           ($value, $string)=&str2hashref($string);
 2501:           if(defined($value->{'error'})) {
 2502:               $hash{'error'}='Bad data';
 2503:               return (\%hash, $string);
 2504:           }
 2505:       } elsif($string =~ /^__ARRAY_REF__/) {
 2506:           ($value, $string)=&str2arrayref($string);
 2507:           if($value->[0] eq 'Array reference error') {
 2508:               $hash{'error'}='Bad data';
 2509:               return (\%hash, $string);
 2510:           }
 2511:       } else {
 2512: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2513:       }
 2514:       $string =~ s/^&//;
 2515: 
 2516:       $hash{$key}=$value;
 2517:   }
 2518: 
 2519:   $string =~ s/^__END_HASH_REF__//;
 2520: 
 2521:   return (\%hash, $string);
 2522: }
 2523: 
 2524: sub str2array {
 2525:     my ($string)=@_;
 2526:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2527:     return @$array;
 2528: }
 2529: 
 2530: sub str2arrayref {
 2531:   my ($string) = @_;
 2532:   my @array;
 2533: 
 2534:   if($string !~ /^__ARRAY_REF__/) {
 2535:       if (! ($string eq '' || !defined($string))) {
 2536: 	  $array[0]='Array reference error';
 2537:       }
 2538:       return (\@array, $string);
 2539:   }
 2540: 
 2541:   $string =~ s/^__ARRAY_REF__//;
 2542: 
 2543:   while($string !~ /^__END_ARRAY_REF__/) {
 2544:       my $value='';
 2545:       if($string =~ /^__HASH_REF__/) {
 2546:           ($value, $string)=&str2hashref($string);
 2547:           if(defined($value->{'error'})) {
 2548:               $array[0] ='Array reference error';
 2549:               return (\@array, $string);
 2550:           }
 2551:       } elsif($string =~ /^__ARRAY_REF__/) {
 2552:           ($value, $string)=&str2arrayref($string);
 2553:           if($value->[0] eq 'Array reference error') {
 2554:               $array[0] ='Array reference error';
 2555:               return (\@array, $string);
 2556:           }
 2557:       } else {
 2558: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2559:       }
 2560:       $string =~ s/^&//;
 2561: 
 2562:       push(@array, $value);
 2563:   }
 2564: 
 2565:   $string =~ s/^__END_ARRAY_REF__//;
 2566: 
 2567:   return (\@array, $string);
 2568: }
 2569: 
 2570: # -------------------------------------------------------------------Temp Store
 2571: 
 2572: sub tmpreset {
 2573:   my ($symb,$namespace,$domain,$stuname) = @_;
 2574:   if (!$symb) {
 2575:     $symb=&symbread();
 2576:     if (!$symb) { $symb= $env{'request.url'}; }
 2577:   }
 2578:   $symb=escape($symb);
 2579: 
 2580:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2581:   $namespace=~s/\//\_/g;
 2582:   $namespace=~s/\W//g;
 2583: 
 2584:   if (!$domain) { $domain=$env{'user.domain'}; }
 2585:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2586:   if ($domain eq 'public' && $stuname eq 'public') {
 2587:       $stuname=$ENV{'REMOTE_ADDR'};
 2588:   }
 2589:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2590:   my %hash;
 2591:   if (tie(%hash,'GDBM_File',
 2592: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2593: 	  &GDBM_WRCREAT(),0640)) {
 2594:     foreach my $key (keys %hash) {
 2595:       if ($key=~ /:$symb/) {
 2596: 	delete($hash{$key});
 2597:       }
 2598:     }
 2599:   }
 2600: }
 2601: 
 2602: sub tmpstore {
 2603:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2604: 
 2605:   if (!$symb) {
 2606:     $symb=&symbread();
 2607:     if (!$symb) { $symb= $env{'request.url'}; }
 2608:   }
 2609:   $symb=escape($symb);
 2610: 
 2611:   if (!$namespace) {
 2612:     # I don't think we would ever want to store this for a course.
 2613:     # it seems this will only be used if we don't have a course.
 2614:     #$namespace=$env{'request.course.id'};
 2615:     #if (!$namespace) {
 2616:       $namespace=$env{'request.state'};
 2617:     #}
 2618:   }
 2619:   $namespace=~s/\//\_/g;
 2620:   $namespace=~s/\W//g;
 2621:   if (!$domain) { $domain=$env{'user.domain'}; }
 2622:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2623:   if ($domain eq 'public' && $stuname eq 'public') {
 2624:       $stuname=$ENV{'REMOTE_ADDR'};
 2625:   }
 2626:   my $now=time;
 2627:   my %hash;
 2628:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2629:   if (tie(%hash,'GDBM_File',
 2630: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2631: 	  &GDBM_WRCREAT(),0640)) {
 2632:     $hash{"version:$symb"}++;
 2633:     my $version=$hash{"version:$symb"};
 2634:     my $allkeys=''; 
 2635:     foreach my $key (keys(%$storehash)) {
 2636:       $allkeys.=$key.':';
 2637:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2638:     }
 2639:     $hash{"$version:$symb:timestamp"}=$now;
 2640:     $allkeys.='timestamp';
 2641:     $hash{"$version:keys:$symb"}=$allkeys;
 2642:     if (untie(%hash)) {
 2643:       return 'ok';
 2644:     } else {
 2645:       return "error:$!";
 2646:     }
 2647:   } else {
 2648:     return "error:$!";
 2649:   }
 2650: }
 2651: 
 2652: # -----------------------------------------------------------------Temp Restore
 2653: 
 2654: sub tmprestore {
 2655:   my ($symb,$namespace,$domain,$stuname) = @_;
 2656: 
 2657:   if (!$symb) {
 2658:     $symb=&symbread();
 2659:     if (!$symb) { $symb= $env{'request.url'}; }
 2660:   }
 2661:   $symb=escape($symb);
 2662: 
 2663:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2664: 
 2665:   if (!$domain) { $domain=$env{'user.domain'}; }
 2666:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2667:   if ($domain eq 'public' && $stuname eq 'public') {
 2668:       $stuname=$ENV{'REMOTE_ADDR'};
 2669:   }
 2670:   my %returnhash;
 2671:   $namespace=~s/\//\_/g;
 2672:   $namespace=~s/\W//g;
 2673:   my %hash;
 2674:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2675:   if (tie(%hash,'GDBM_File',
 2676: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2677: 	  &GDBM_READER(),0640)) {
 2678:     my $version=$hash{"version:$symb"};
 2679:     $returnhash{'version'}=$version;
 2680:     my $scope;
 2681:     for ($scope=1;$scope<=$version;$scope++) {
 2682:       my $vkeys=$hash{"$scope:keys:$symb"};
 2683:       my @keys=split(/:/,$vkeys);
 2684:       my $key;
 2685:       $returnhash{"$scope:keys"}=$vkeys;
 2686:       foreach $key (@keys) {
 2687: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2688: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2689:       }
 2690:     }
 2691:     if (!(untie(%hash))) {
 2692:       return "error:$!";
 2693:     }
 2694:   } else {
 2695:     return "error:$!";
 2696:   }
 2697:   return %returnhash;
 2698: }
 2699: 
 2700: # ----------------------------------------------------------------------- Store
 2701: 
 2702: sub store {
 2703:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2704:     my $home='';
 2705: 
 2706:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2707: 
 2708:     $symb=&symbclean($symb);
 2709:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2710: 
 2711:     if (!$domain) { $domain=$env{'user.domain'}; }
 2712:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2713: 
 2714:     &devalidate($symb,$stuname,$domain);
 2715: 
 2716:     $symb=escape($symb);
 2717:     if (!$namespace) { 
 2718:        unless ($namespace=$env{'request.course.id'}) { 
 2719:           return ''; 
 2720:        } 
 2721:     }
 2722:     if (!$home) { $home=$env{'user.home'}; }
 2723: 
 2724:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2725:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2726: 
 2727:     my $namevalue='';
 2728:     foreach my $key (keys(%$storehash)) {
 2729:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2730:     }
 2731:     $namevalue=~s/\&$//;
 2732:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2733:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2734: }
 2735: 
 2736: # -------------------------------------------------------------- Critical Store
 2737: 
 2738: sub cstore {
 2739:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2740:     my $home='';
 2741: 
 2742:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2743: 
 2744:     $symb=&symbclean($symb);
 2745:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2746: 
 2747:     if (!$domain) { $domain=$env{'user.domain'}; }
 2748:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2749: 
 2750:     &devalidate($symb,$stuname,$domain);
 2751: 
 2752:     $symb=escape($symb);
 2753:     if (!$namespace) { 
 2754:        unless ($namespace=$env{'request.course.id'}) { 
 2755:           return ''; 
 2756:        } 
 2757:     }
 2758:     if (!$home) { $home=$env{'user.home'}; }
 2759: 
 2760:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2761:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2762: 
 2763:     my $namevalue='';
 2764:     foreach my $key (keys(%$storehash)) {
 2765:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2766:     }
 2767:     $namevalue=~s/\&$//;
 2768:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2769:     return critical
 2770:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2771: }
 2772: 
 2773: # --------------------------------------------------------------------- Restore
 2774: 
 2775: sub restore {
 2776:     my ($symb,$namespace,$domain,$stuname) = @_;
 2777:     my $home='';
 2778: 
 2779:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2780: 
 2781:     if (!$symb) {
 2782:       unless ($symb=escape(&symbread())) { return ''; }
 2783:     } else {
 2784:       $symb=&escape(&symbclean($symb));
 2785:     }
 2786:     if (!$namespace) { 
 2787:        unless ($namespace=$env{'request.course.id'}) { 
 2788:           return ''; 
 2789:        } 
 2790:     }
 2791:     if (!$domain) { $domain=$env{'user.domain'}; }
 2792:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2793:     if (!$home) { $home=$env{'user.home'}; }
 2794:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2795: 
 2796:     my %returnhash=();
 2797:     foreach my $line (split(/\&/,$answer)) {
 2798: 	my ($name,$value)=split(/\=/,$line);
 2799:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2800:     }
 2801:     my $version;
 2802:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2803:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2804:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2805:        }
 2806:     }
 2807:     return %returnhash;
 2808: }
 2809: 
 2810: # ---------------------------------------------------------- Course Description
 2811: 
 2812: sub coursedescription {
 2813:     my ($courseid,$args)=@_;
 2814:     $courseid=~s/^\///;
 2815:     $courseid=~s/\_/\//g;
 2816:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2817:     my $chome=&homeserver($cnum,$cdomain);
 2818:     my $normalid=$cdomain.'_'.$cnum;
 2819:     # need to always cache even if we get errors otherwise we keep 
 2820:     # trying and trying and trying to get the course description.
 2821:     my %envhash=();
 2822:     my %returnhash=();
 2823:     
 2824:     my $expiretime=600;
 2825:     if ($env{'request.course.id'} eq $normalid) {
 2826: 	$expiretime=120;
 2827:     }
 2828: 
 2829:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2830:     if (!$args->{'freshen_cache'}
 2831: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2832: 	foreach my $key (keys(%env)) {
 2833: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2834: 	    my ($setting) = $1;
 2835: 	    $returnhash{$setting} = $env{$key};
 2836: 	}
 2837: 	return %returnhash;
 2838:     }
 2839: 
 2840:     # get the data agin
 2841:     if (!$args->{'one_time'}) {
 2842: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2843:     }
 2844: 
 2845:     if ($chome ne 'no_host') {
 2846:        %returnhash=&dump('environment',$cdomain,$cnum);
 2847:        if (!exists($returnhash{'con_lost'})) {
 2848:            $returnhash{'home'}= $chome;
 2849: 	   $returnhash{'domain'} = $cdomain;
 2850: 	   $returnhash{'num'} = $cnum;
 2851:            if (!defined($returnhash{'type'})) {
 2852:                $returnhash{'type'} = 'Course';
 2853:            }
 2854:            while (my ($name,$value) = each %returnhash) {
 2855:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2856:            }
 2857:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2858:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2859: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2860:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2861:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2862:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2863:        }
 2864:     }
 2865:     if (!$args->{'one_time'}) {
 2866: 	&appenv(%envhash);
 2867:     }
 2868:     return %returnhash;
 2869: }
 2870: 
 2871: # -------------------------------------------------See if a user is privileged
 2872: 
 2873: sub privileged {
 2874:     my ($username,$domain)=@_;
 2875:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2876: 			&homeserver($username,$domain));
 2877:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2878:     my $now=time;
 2879:     if ($rolesdump ne '') {
 2880:         foreach my $entry (split(/&/,$rolesdump)) {
 2881: 	    if ($entry!~/^rolesdef_/) {
 2882: 		my ($area,$role)=split(/=/,$entry);
 2883: 		$area=~s/\_\w\w$//;
 2884: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2885: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2886: 		    my $active=1;
 2887: 		    if ($tend) {
 2888: 			if ($tend<$now) { $active=0; }
 2889: 		    }
 2890: 		    if ($tstart) {
 2891: 			if ($tstart>$now) { $active=0; }
 2892: 		    }
 2893: 		    if ($active) { return 1; }
 2894: 		}
 2895: 	    }
 2896: 	}
 2897:     }
 2898:     return 0;
 2899: }
 2900: 
 2901: # -------------------------------------------------------- Get user privileges
 2902: 
 2903: sub rolesinit {
 2904:     my ($domain,$username,$authhost)=@_;
 2905:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2906:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2907:     my %allroles=();
 2908:     my %allgroups=();   
 2909:     my $now=time;
 2910:     my %userroles = ('user.login.time' => $now);
 2911:     my $group_privs;
 2912: 
 2913:     if ($rolesdump ne '') {
 2914:         foreach my $entry (split(/&/,$rolesdump)) {
 2915: 	  if ($entry!~/^rolesdef_/) {
 2916:             my ($area,$role)=split(/=/,$entry);
 2917: 	    $area=~s/\_\w\w$//;
 2918:             my ($trole,$tend,$tstart,$group_privs);
 2919: 	    if ($role=~/^cr/) { 
 2920: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 2921: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 2922: 		    ($tend,$tstart)=split('_',$trest);
 2923: 		} else {
 2924: 		    $trole=$role;
 2925: 		}
 2926:             } elsif ($role =~ m|^gr/|) {
 2927:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2928:                 ($trole,$group_privs) = split(/\//,$trole);
 2929:                 $group_privs = &unescape($group_privs);
 2930: 	    } else {
 2931: 		($trole,$tend,$tstart)=split(/_/,$role);
 2932: 	    }
 2933: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2934: 					 $username);
 2935: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2936:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2937:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2938:             if (($area ne '') && ($trole ne '')) {
 2939: 		my $spec=$trole.'.'.$area;
 2940: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2941: 		if ($trole =~ /^cr\//) {
 2942:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2943:                 } elsif ($trole eq 'gr') {
 2944:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2945: 		} else {
 2946:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2947: 		}
 2948:             }
 2949:           }
 2950:         }
 2951:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2952:         $userroles{'user.adv'}    = $adv;
 2953: 	$userroles{'user.author'} = $author;
 2954:         $env{'user.adv'}=$adv;
 2955:     }
 2956:     return \%userroles;  
 2957: }
 2958: 
 2959: sub set_arearole {
 2960:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2961: # log the associated role with the area
 2962:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2963:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2964: }
 2965: 
 2966: sub custom_roleprivs {
 2967:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2968:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2969:     my $homsvr=homeserver($rauthor,$rdomain);
 2970:     if (&hostname($homsvr) ne '') {
 2971:         my ($rdummy,$roledef)=
 2972:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2973:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2974:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2975:             if (defined($syspriv)) {
 2976:                 $$allroles{'cm./'}.=':'.$syspriv;
 2977:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2978:             }
 2979:             if ($tdomain ne '') {
 2980:                 if (defined($dompriv)) {
 2981:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2982:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2983:                 }
 2984:                 if (($trest ne '') && (defined($coursepriv))) {
 2985:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2986:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2987:                 }
 2988:             }
 2989:         }
 2990:     }
 2991: }
 2992: 
 2993: sub group_roleprivs {
 2994:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2995:     my $access = 1;
 2996:     my $now = time;
 2997:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2998:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2999:     if ($access) {
 3000:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3001:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3002:     }
 3003: }
 3004: 
 3005: sub standard_roleprivs {
 3006:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3007:     if (defined($pr{$trole.':s'})) {
 3008:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3009:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3010:     }
 3011:     if ($tdomain ne '') {
 3012:         if (defined($pr{$trole.':d'})) {
 3013:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3014:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3015:         }
 3016:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3017:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3018:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3019:         }
 3020:     }
 3021: }
 3022: 
 3023: sub set_userprivs {
 3024:     my ($userroles,$allroles,$allgroups) = @_; 
 3025:     my $author=0;
 3026:     my $adv=0;
 3027:     my %grouproles = ();
 3028:     if (keys(%{$allgroups}) > 0) {
 3029:         foreach my $role (keys %{$allroles}) {
 3030:             my ($trole,$area,$sec,$extendedarea);
 3031:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3032:                 $trole = $1;
 3033:                 $area = $2;
 3034:                 $sec = $3;
 3035:                 $extendedarea = $area.$sec;
 3036:                 if (exists($$allgroups{$area})) {
 3037:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3038:                         my $spec = $trole.'.'.$extendedarea;
 3039:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3040:                                                 $$allgroups{$area}{$group};
 3041:                     }
 3042:                 }
 3043:             }
 3044:         }
 3045:     }
 3046:     foreach my $group (keys(%grouproles)) {
 3047:         $$allroles{$group} = $grouproles{$group};
 3048:     }
 3049:     foreach my $role (keys(%{$allroles})) {
 3050:         my %thesepriv;
 3051:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3052:         foreach my $item (split(/:/,$$allroles{$role})) {
 3053:             if ($item ne '') {
 3054:                 my ($privilege,$restrictions)=split(/&/,$item);
 3055:                 if ($restrictions eq '') {
 3056:                     $thesepriv{$privilege}='F';
 3057:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3058:                     $thesepriv{$privilege}.=$restrictions;
 3059:                 }
 3060:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3061:             }
 3062:         }
 3063:         my $thesestr='';
 3064:         foreach my $priv (keys(%thesepriv)) {
 3065: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3066: 	}
 3067:         $userroles->{'user.priv.'.$role} = $thesestr;
 3068:     }
 3069:     return ($author,$adv);
 3070: }
 3071: 
 3072: # --------------------------------------------------------------- get interface
 3073: 
 3074: sub get {
 3075:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3076:    my $items='';
 3077:    foreach my $item (@$storearr) {
 3078:        $items.=&escape($item).'&';
 3079:    }
 3080:    $items=~s/\&$//;
 3081:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3082:    if (!$uname) { $uname=$env{'user.name'}; }
 3083:    my $uhome=&homeserver($uname,$udomain);
 3084: 
 3085:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3086:    my @pairs=split(/\&/,$rep);
 3087:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3088:      return @pairs;
 3089:    }
 3090:    my %returnhash=();
 3091:    my $i=0;
 3092:    foreach my $item (@$storearr) {
 3093:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3094:       $i++;
 3095:    }
 3096:    return %returnhash;
 3097: }
 3098: 
 3099: # --------------------------------------------------------------- del interface
 3100: 
 3101: sub del {
 3102:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3103:    my $items='';
 3104:    foreach my $item (@$storearr) {
 3105:        $items.=&escape($item).'&';
 3106:    }
 3107:    $items=~s/\&$//;
 3108:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3109:    if (!$uname) { $uname=$env{'user.name'}; }
 3110:    my $uhome=&homeserver($uname,$udomain);
 3111: 
 3112:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3113: }
 3114: 
 3115: # -------------------------------------------------------------- dump interface
 3116: 
 3117: sub dump {
 3118:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3119:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3120:     if (!$uname) { $uname=$env{'user.name'}; }
 3121:     my $uhome=&homeserver($uname,$udomain);
 3122:     if ($regexp) {
 3123: 	$regexp=&escape($regexp);
 3124:     } else {
 3125: 	$regexp='.';
 3126:     }
 3127:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3128:     my @pairs=split(/\&/,$rep);
 3129:     my %returnhash=();
 3130:     foreach my $item (@pairs) {
 3131: 	my ($key,$value)=split(/=/,$item,2);
 3132: 	$key = &unescape($key);
 3133: 	next if ($key =~ /^error: 2 /);
 3134: 	$returnhash{$key}=&thaw_unescape($value);
 3135:     }
 3136:     return %returnhash;
 3137: }
 3138: 
 3139: # --------------------------------------------------------- dumpstore interface
 3140: 
 3141: sub dumpstore {
 3142:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3143:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3144:    if (!$uname) { $uname=$env{'user.name'}; }
 3145:    my $uhome=&homeserver($uname,$udomain);
 3146:    if ($regexp) {
 3147:        $regexp=&escape($regexp);
 3148:    } else {
 3149:        $regexp='.';
 3150:    }
 3151:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3152:    my @pairs=split(/\&/,$rep);
 3153:    my %returnhash=();
 3154:    foreach my $item (@pairs) {
 3155:        my ($key,$value)=split(/=/,$item,2);
 3156:        next if ($key =~ /^error: 2 /);
 3157:        $returnhash{$key}=&thaw_unescape($value);
 3158:    }
 3159:    return %returnhash;
 3160: }
 3161: 
 3162: # -------------------------------------------------------------- keys interface
 3163: 
 3164: sub getkeys {
 3165:    my ($namespace,$udomain,$uname)=@_;
 3166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3167:    if (!$uname) { $uname=$env{'user.name'}; }
 3168:    my $uhome=&homeserver($uname,$udomain);
 3169:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3170:    my @keyarray=();
 3171:    foreach my $key (split(/\&/,$rep)) {
 3172:       next if ($key =~ /^error: 2 /);
 3173:       push(@keyarray,&unescape($key));
 3174:    }
 3175:    return @keyarray;
 3176: }
 3177: 
 3178: # --------------------------------------------------------------- currentdump
 3179: sub currentdump {
 3180:    my ($courseid,$sdom,$sname)=@_;
 3181:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3182:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3183:    $sname    = $env{'user.name'}         if (! defined($sname));
 3184:    my $uhome = &homeserver($sname,$sdom);
 3185:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3186:    return if ($rep =~ /^(error:|no_such_host)/);
 3187:    #
 3188:    my %returnhash=();
 3189:    #
 3190:    if ($rep eq "unknown_cmd") { 
 3191:        # an old lond will not know currentdump
 3192:        # Do a dump and make it look like a currentdump
 3193:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3194:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3195:        my %hash = @tmp;
 3196:        @tmp=();
 3197:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3198:    } else {
 3199:        my @pairs=split(/\&/,$rep);
 3200:        foreach my $pair (@pairs) {
 3201:            my ($key,$value)=split(/=/,$pair,2);
 3202:            my ($symb,$param) = split(/:/,$key);
 3203:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3204:                                                         &thaw_unescape($value);
 3205:        }
 3206:    }
 3207:    return %returnhash;
 3208: }
 3209: 
 3210: sub convert_dump_to_currentdump{
 3211:     my %hash = %{shift()};
 3212:     my %returnhash;
 3213:     # Code ripped from lond, essentially.  The only difference
 3214:     # here is the unescaping done by lonnet::dump().  Conceivably
 3215:     # we might run in to problems with parameter names =~ /^v\./
 3216:     while (my ($key,$value) = each(%hash)) {
 3217:         my ($v,$symb,$param) = split(/:/,$key);
 3218: 	$symb  = &unescape($symb);
 3219: 	$param = &unescape($param);
 3220:         next if ($v eq 'version' || $symb eq 'keys');
 3221:         next if (exists($returnhash{$symb}) &&
 3222:                  exists($returnhash{$symb}->{$param}) &&
 3223:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3224:         $returnhash{$symb}->{$param}=$value;
 3225:         $returnhash{$symb}->{'v.'.$param}=$v;
 3226:     }
 3227:     #
 3228:     # Remove all of the keys in the hashes which keep track of
 3229:     # the version of the parameter.
 3230:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3231:         # use a foreach because we are going to delete from the hash.
 3232:         foreach my $key (keys(%$param_hash)) {
 3233:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3234:         }
 3235:     }
 3236:     return \%returnhash;
 3237: }
 3238: 
 3239: # ------------------------------------------------------ critical inc interface
 3240: 
 3241: sub cinc {
 3242:     return &inc(@_,'critical');
 3243: }
 3244: 
 3245: # --------------------------------------------------------------- inc interface
 3246: 
 3247: sub inc {
 3248:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3249:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3250:     if (!$uname) { $uname=$env{'user.name'}; }
 3251:     my $uhome=&homeserver($uname,$udomain);
 3252:     my $items='';
 3253:     if (! ref($store)) {
 3254:         # got a single value, so use that instead
 3255:         $items = &escape($store).'=&';
 3256:     } elsif (ref($store) eq 'SCALAR') {
 3257:         $items = &escape($$store).'=&';        
 3258:     } elsif (ref($store) eq 'ARRAY') {
 3259:         $items = join('=&',map {&escape($_);} @{$store});
 3260:     } elsif (ref($store) eq 'HASH') {
 3261:         while (my($key,$value) = each(%{$store})) {
 3262:             $items.= &escape($key).'='.&escape($value).'&';
 3263:         }
 3264:     }
 3265:     $items=~s/\&$//;
 3266:     if ($critical) {
 3267: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3268:     } else {
 3269: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3270:     }
 3271: }
 3272: 
 3273: # --------------------------------------------------------------- put interface
 3274: 
 3275: sub put {
 3276:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3277:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3278:    if (!$uname) { $uname=$env{'user.name'}; }
 3279:    my $uhome=&homeserver($uname,$udomain);
 3280:    my $items='';
 3281:    foreach my $item (keys(%$storehash)) {
 3282:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3283:    }
 3284:    $items=~s/\&$//;
 3285:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3286: }
 3287: 
 3288: # ------------------------------------------------------------ newput interface
 3289: 
 3290: sub newput {
 3291:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3292:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3293:    if (!$uname) { $uname=$env{'user.name'}; }
 3294:    my $uhome=&homeserver($uname,$udomain);
 3295:    my $items='';
 3296:    foreach my $key (keys(%$storehash)) {
 3297:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3298:    }
 3299:    $items=~s/\&$//;
 3300:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3301: }
 3302: 
 3303: # ---------------------------------------------------------  putstore interface
 3304: 
 3305: sub putstore {
 3306:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3307:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3308:    if (!$uname) { $uname=$env{'user.name'}; }
 3309:    my $uhome=&homeserver($uname,$udomain);
 3310:    my $items='';
 3311:    foreach my $key (keys(%$storehash)) {
 3312:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3313:    }
 3314:    $items=~s/\&$//;
 3315:    my $esc_symb=&escape($symb);
 3316:    my $esc_v=&escape($version);
 3317:    my $reply =
 3318:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3319: 	      $uhome);
 3320:    if ($reply eq 'unknown_cmd') {
 3321:        # gfall back to way things use to be done
 3322:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3323: 			    $uname);
 3324:    }
 3325:    return $reply;
 3326: }
 3327: 
 3328: sub old_putstore {
 3329:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3330:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3331:     if (!$uname) { $uname=$env{'user.name'}; }
 3332:     my $uhome=&homeserver($uname,$udomain);
 3333:     my %newstorehash;
 3334:     foreach my $item (keys(%$storehash)) {
 3335: 	my $key = $version.':'.&escape($symb).':'.$item;
 3336: 	$newstorehash{$key} = $storehash->{$item};
 3337:     }
 3338:     my $items='';
 3339:     my %allitems = ();
 3340:     foreach my $item (keys(%newstorehash)) {
 3341: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3342: 	    my $key = $1.':keys:'.$2;
 3343: 	    $allitems{$key} .= $3.':';
 3344: 	}
 3345: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3346:     }
 3347:     foreach my $item (keys(%allitems)) {
 3348: 	$allitems{$item} =~ s/\:$//;
 3349: 	$items.= $item.'='.$allitems{$item}.'&';
 3350:     }
 3351:     $items=~s/\&$//;
 3352:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3353: }
 3354: 
 3355: # ------------------------------------------------------ critical put interface
 3356: 
 3357: sub cput {
 3358:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3359:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3360:    if (!$uname) { $uname=$env{'user.name'}; }
 3361:    my $uhome=&homeserver($uname,$udomain);
 3362:    my $items='';
 3363:    foreach my $item (keys(%$storehash)) {
 3364:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3365:    }
 3366:    $items=~s/\&$//;
 3367:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3368: }
 3369: 
 3370: # -------------------------------------------------------------- eget interface
 3371: 
 3372: sub eget {
 3373:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3374:    my $items='';
 3375:    foreach my $item (@$storearr) {
 3376:        $items.=&escape($item).'&';
 3377:    }
 3378:    $items=~s/\&$//;
 3379:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3380:    if (!$uname) { $uname=$env{'user.name'}; }
 3381:    my $uhome=&homeserver($uname,$udomain);
 3382:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3383:    my @pairs=split(/\&/,$rep);
 3384:    my %returnhash=();
 3385:    my $i=0;
 3386:    foreach my $item (@$storearr) {
 3387:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3388:       $i++;
 3389:    }
 3390:    return %returnhash;
 3391: }
 3392: 
 3393: # ------------------------------------------------------------ tmpput interface
 3394: sub tmpput {
 3395:     my ($storehash,$server,$context)=@_;
 3396:     my $items='';
 3397:     foreach my $item (keys(%$storehash)) {
 3398: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3399:     }
 3400:     $items=~s/\&$//;
 3401:     if (defined($context)) {
 3402:         $items .= ':'.&escape($context);
 3403:     }
 3404:     return &reply("tmpput:$items",$server);
 3405: }
 3406: 
 3407: # ------------------------------------------------------------ tmpget interface
 3408: sub tmpget {
 3409:     my ($token,$server)=@_;
 3410:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3411:     my $rep=&reply("tmpget:$token",$server);
 3412:     my %returnhash;
 3413:     foreach my $item (split(/\&/,$rep)) {
 3414: 	my ($key,$value)=split(/=/,$item);
 3415: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3416:     }
 3417:     return %returnhash;
 3418: }
 3419: 
 3420: # ------------------------------------------------------------ tmpget interface
 3421: sub tmpdel {
 3422:     my ($token,$server)=@_;
 3423:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3424:     return &reply("tmpdel:$token",$server);
 3425: }
 3426: 
 3427: # -------------------------------------------------- portfolio access checking
 3428: 
 3429: sub portfolio_access {
 3430:     my ($requrl) = @_;
 3431:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3432:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3433:     if ($result) {
 3434:         my %setters;
 3435:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3436:             my ($startblock,$endblock) =
 3437:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3438:             if ($startblock && $endblock) {
 3439:                 return 'B';
 3440:             }
 3441:         } else {
 3442:             my ($startblock,$endblock) =
 3443:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3444:             if ($startblock && $endblock) {
 3445:                 return 'B';
 3446:             }
 3447:         }
 3448:     }
 3449:     if ($result eq 'ok') {
 3450:        return 'F';
 3451:     } elsif ($result =~ /^[^:]+:guest_/) {
 3452:        return 'A';
 3453:     }
 3454:     return '';
 3455: }
 3456: 
 3457: sub get_portfolio_access {
 3458:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3459: 
 3460:     if (!ref($access_hash)) {
 3461: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3462: 	my %access_controls = &get_access_controls($current_perms,$group,
 3463: 						   $file_name);
 3464: 	$access_hash = $access_controls{$file_name};
 3465:     }
 3466: 
 3467:     my ($public,$guest,@domains,@users,@courses,@groups);
 3468:     my $now = time;
 3469:     if (ref($access_hash) eq 'HASH') {
 3470:         foreach my $key (keys(%{$access_hash})) {
 3471:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3472:             if ($start > $now) {
 3473:                 next;
 3474:             }
 3475:             if ($end && $end<$now) {
 3476:                 next;
 3477:             }
 3478:             if ($scope eq 'public') {
 3479:                 $public = $key;
 3480:                 last;
 3481:             } elsif ($scope eq 'guest') {
 3482:                 $guest = $key;
 3483:             } elsif ($scope eq 'domains') {
 3484:                 push(@domains,$key);
 3485:             } elsif ($scope eq 'users') {
 3486:                 push(@users,$key);
 3487:             } elsif ($scope eq 'course') {
 3488:                 push(@courses,$key);
 3489:             } elsif ($scope eq 'group') {
 3490:                 push(@groups,$key);
 3491:             }
 3492:         }
 3493:         if ($public) {
 3494:             return 'ok';
 3495:         }
 3496:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3497:             if ($guest) {
 3498:                 return $guest;
 3499:             }
 3500:         } else {
 3501:             if (@domains > 0) {
 3502:                 foreach my $domkey (@domains) {
 3503:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3504:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3505:                             return 'ok';
 3506:                         }
 3507:                     }
 3508:                 }
 3509:             }
 3510:             if (@users > 0) {
 3511:                 foreach my $userkey (@users) {
 3512:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3513:                         return 'ok';
 3514:                     }
 3515:                 }
 3516:             }
 3517:             my %roleshash;
 3518:             my @courses_and_groups = @courses;
 3519:             push(@courses_and_groups,@groups); 
 3520:             if (@courses_and_groups > 0) {
 3521:                 my (%allgroups,%allroles); 
 3522:                 my ($start,$end,$role,$sec,$group);
 3523:                 foreach my $envkey (%env) {
 3524:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3525:                         my $cid = $2.'_'.$3; 
 3526:                         if ($1 eq 'gr') {
 3527:                             $group = $4;
 3528:                             $allgroups{$cid}{$group} = $env{$envkey};
 3529:                         } else {
 3530:                             if ($4 eq '') {
 3531:                                 $sec = 'none';
 3532:                             } else {
 3533:                                 $sec = $4;
 3534:                             }
 3535:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3536:                         }
 3537:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3538:                         my $cid = $2.'_'.$3;
 3539:                         if ($4 eq '') {
 3540:                             $sec = 'none';
 3541:                         } else {
 3542:                             $sec = $4;
 3543:                         }
 3544:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3545:                     }
 3546:                 }
 3547:                 if (keys(%allroles) == 0) {
 3548:                     return;
 3549:                 }
 3550:                 foreach my $key (@courses_and_groups) {
 3551:                     my %content = %{$$access_hash{$key}};
 3552:                     my $cnum = $content{'number'};
 3553:                     my $cdom = $content{'domain'};
 3554:                     my $cid = $cdom.'_'.$cnum;
 3555:                     if (!exists($allroles{$cid})) {
 3556:                         next;
 3557:                     }    
 3558:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3559:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3560:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3561:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3562:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3563:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3564:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3565:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3566:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3567:                                         if (grep/^all$/,@sections) {
 3568:                                             return 'ok';
 3569:                                         } else {
 3570:                                             if (grep/^$sec$/,@sections) {
 3571:                                                 return 'ok';
 3572:                                             }
 3573:                                         }
 3574:                                     }
 3575:                                 }
 3576:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3577:                                     if (grep/^none$/,@groups) {
 3578:                                         return 'ok';
 3579:                                     }
 3580:                                 } else {
 3581:                                     if (grep/^all$/,@groups) {
 3582:                                         return 'ok';
 3583:                                     } 
 3584:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3585:                                         if (grep/^$group$/,@groups) {
 3586:                                             return 'ok';
 3587:                                         }
 3588:                                     }
 3589:                                 } 
 3590:                             }
 3591:                         }
 3592:                     }
 3593:                 }
 3594:             }
 3595:             if ($guest) {
 3596:                 return $guest;
 3597:             }
 3598:         }
 3599:     }
 3600:     return;
 3601: }
 3602: 
 3603: sub course_group_datechecker {
 3604:     my ($dates,$now,$status) = @_;
 3605:     my ($start,$end) = split(/\./,$dates);
 3606:     if (!$start && !$end) {
 3607:         return 'ok';
 3608:     }
 3609:     if (grep/^active$/,@{$status}) {
 3610:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3611:             return 'ok';
 3612:         }
 3613:     }
 3614:     if (grep/^previous$/,@{$status}) {
 3615:         if ($end > $now ) {
 3616:             return 'ok';
 3617:         }
 3618:     }
 3619:     if (grep/^future$/,@{$status}) {
 3620:         if ($start > $now) {
 3621:             return 'ok';
 3622:         }
 3623:     }
 3624:     return; 
 3625: }
 3626: 
 3627: sub parse_portfolio_url {
 3628:     my ($url) = @_;
 3629: 
 3630:     my ($type,$udom,$unum,$group,$file_name);
 3631:     
 3632:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3633: 	$type = 1;
 3634:         $udom = $1;
 3635:         $unum = $2;
 3636:         $file_name = $3;
 3637:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3638: 	$type = 2;
 3639:         $udom = $1;
 3640:         $unum = $2;
 3641:         $group = $3;
 3642:         $file_name = $3.'/'.$4;
 3643:     }
 3644:     if (wantarray) {
 3645: 	return ($type,$udom,$unum,$file_name,$group);
 3646:     }
 3647:     return $type;
 3648: }
 3649: 
 3650: sub is_portfolio_url {
 3651:     my ($url) = @_;
 3652:     return scalar(&parse_portfolio_url($url));
 3653: }
 3654: 
 3655: sub is_portfolio_file {
 3656:     my ($file) = @_;
 3657:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3658:         return 1;
 3659:     }
 3660:     return;
 3661: }
 3662: 
 3663: 
 3664: # ---------------------------------------------- Custom access rule evaluation
 3665: 
 3666: sub customaccess {
 3667:     my ($priv,$uri)=@_;
 3668:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3669:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3670:     $udom = &LONCAPA::clean_domain($udom);
 3671:     $ucrs = &LONCAPA::clean_username($ucrs);
 3672:     my $access=0;
 3673:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3674: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3675:         if ($role) {
 3676: 	   if ($role ne $urole) { next; }
 3677:         }
 3678:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3679:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3680:             if ($tdom) {
 3681: 		if ($tdom ne $udom) { next; }
 3682:             }
 3683:             if ($tcrs) {
 3684: 		if ($tcrs ne $ucrs) { next; }
 3685:             }
 3686:             if ($tsec) {
 3687: 		if ($tsec ne $usec) { next; }
 3688:             }
 3689:             $access=($effect eq 'allow');
 3690:             last;
 3691:         }
 3692: 	if ($realm eq '' && $role eq '') {
 3693:             $access=($effect eq 'allow');
 3694: 	}
 3695:     }
 3696:     return $access;
 3697: }
 3698: 
 3699: # ------------------------------------------------- Check for a user privilege
 3700: 
 3701: sub allowed {
 3702:     my ($priv,$uri,$symb,$role)=@_;
 3703:     my $ver_orguri=$uri;
 3704:     $uri=&deversion($uri);
 3705:     my $orguri=$uri;
 3706:     $uri=&declutter($uri);
 3707: 
 3708:     if ($priv eq 'evb') {
 3709: # Evade communication block restrictions for specified role in a course
 3710:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3711:             return $1;
 3712:         } else {
 3713:             return;
 3714:         }
 3715:     }
 3716: 
 3717:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3718: # Free bre access to adm and meta resources
 3719:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3720: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3721: 	&& ($priv eq 'bre')) {
 3722: 	return 'F';
 3723:     }
 3724: 
 3725: # Free bre access to user's own portfolio contents
 3726:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3727:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3728: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3729:         my %setters;
 3730:         my ($startblock,$endblock) = 
 3731:             &Apache::loncommon::blockcheck(\%setters,'port');
 3732:         if ($startblock && $endblock) {
 3733:             return 'B';
 3734:         } else {
 3735:             return 'F';
 3736:         }
 3737:     }
 3738: 
 3739: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3740:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3741:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3742:         if (exists($env{'request.course.id'})) {
 3743:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3744:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3745:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3746:                 my $courseprivid=$env{'request.course.id'};
 3747:                 $courseprivid=~s/\_/\//;
 3748:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3749:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3750:                     return $1; 
 3751:                 } else {
 3752:                     if ($env{'request.course.sec'}) {
 3753:                         $courseprivid.='/'.$env{'request.course.sec'};
 3754:                     }
 3755:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3756:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3757:                         return $2;
 3758:                     }
 3759:                 }
 3760:             }
 3761:         }
 3762:     }
 3763: 
 3764: # Free bre to public access
 3765: 
 3766:     if ($priv eq 'bre') {
 3767:         my $copyright=&metadata($uri,'copyright');
 3768: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3769:            return 'F'; 
 3770:         }
 3771:         if ($copyright eq 'priv') {
 3772:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3773: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3774: 		return '';
 3775:             }
 3776:         }
 3777:         if ($copyright eq 'domain') {
 3778:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3779: 	    unless (($env{'user.domain'} eq $1) ||
 3780:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3781: 		return '';
 3782:             }
 3783:         }
 3784:         if ($env{'request.role'}=~ /li\.\//) {
 3785:             # Library role, so allow browsing of resources in this domain.
 3786:             return 'F';
 3787:         }
 3788:         if ($copyright eq 'custom') {
 3789: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3790:         }
 3791:     }
 3792:     # Domain coordinator is trying to create a course
 3793:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3794:         # uri is the requested domain in this case.
 3795:         # comparison to 'request.role.domain' shows if the user has selected
 3796:         # a role of dc for the domain in question.
 3797:         return 'F' if ($uri eq $env{'request.role.domain'});
 3798:     }
 3799: 
 3800:     my $thisallowed='';
 3801:     my $statecond=0;
 3802:     my $courseprivid='';
 3803: 
 3804: # Course
 3805: 
 3806:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3807:        $thisallowed.=$1;
 3808:     }
 3809: 
 3810: # Domain
 3811: 
 3812:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3813:        =~/\Q$priv\E\&([^\:]*)/) {
 3814:        $thisallowed.=$1;
 3815:     }
 3816: 
 3817: # Course: uri itself is a course
 3818:     my $courseuri=$uri;
 3819:     $courseuri=~s/\_(\d)/\/$1/;
 3820:     $courseuri=~s/^([^\/])/\/$1/;
 3821: 
 3822:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3823:        =~/\Q$priv\E\&([^\:]*)/) {
 3824:        $thisallowed.=$1;
 3825:     }
 3826: 
 3827: # URI is an uploaded document for this course, default permissions don't matter
 3828: # not allowing 'edit' access (editupload) to uploaded course docs
 3829:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3830: 	$thisallowed='';
 3831:         my ($match)=&is_on_map($uri);
 3832:         if ($match) {
 3833:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3834:                   =~/\Q$priv\E\&([^\:]*)/) {
 3835:                 $thisallowed.=$1;
 3836:             }
 3837:         } else {
 3838:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3839:             if ($refuri) {
 3840:                 if ($refuri =~ m|^/adm/|) {
 3841:                     $thisallowed='F';
 3842:                 } else {
 3843:                     $refuri=&declutter($refuri);
 3844:                     my ($match) = &is_on_map($refuri);
 3845:                     if ($match) {
 3846:                         $thisallowed='F';
 3847:                     }
 3848:                 }
 3849:             }
 3850:         }
 3851:     }
 3852: 
 3853:     if ($priv eq 'bre'
 3854: 	&& $thisallowed ne 'F' 
 3855: 	&& $thisallowed ne '2'
 3856: 	&& &is_portfolio_url($uri)) {
 3857: 	$thisallowed = &portfolio_access($uri);
 3858:     }
 3859:     
 3860: # Full access at system, domain or course-wide level? Exit.
 3861: 
 3862:     if ($thisallowed=~/F/) {
 3863: 	return 'F';
 3864:     }
 3865: 
 3866: # If this is generating or modifying users, exit with special codes
 3867: 
 3868:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3869: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3870: 	    my ($audom,$auname)=split('/',$uri);
 3871: # no author name given, so this just checks on the general right to make a co-author in this domain
 3872: 	    unless ($auname) { return $thisallowed; }
 3873: # an author name is given, so we are about to actually make a co-author for a certain account
 3874: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3875: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3876: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3877: 	}
 3878: 	return $thisallowed;
 3879:     }
 3880: #
 3881: # Gathered so far: system, domain and course wide privileges
 3882: #
 3883: # Course: See if uri or referer is an individual resource that is part of 
 3884: # the course
 3885: 
 3886:     if ($env{'request.course.id'}) {
 3887: 
 3888:        $courseprivid=$env{'request.course.id'};
 3889:        if ($env{'request.course.sec'}) {
 3890:           $courseprivid.='/'.$env{'request.course.sec'};
 3891:        }
 3892:        $courseprivid=~s/\_/\//;
 3893:        my $checkreferer=1;
 3894:        my ($match,$cond)=&is_on_map($uri);
 3895:        if ($match) {
 3896:            $statecond=$cond;
 3897:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3898:                =~/\Q$priv\E\&([^\:]*)/) {
 3899:                $thisallowed.=$1;
 3900:                $checkreferer=0;
 3901:            }
 3902:        }
 3903:        
 3904:        if ($checkreferer) {
 3905: 	  my $refuri=$env{'httpref.'.$orguri};
 3906:             unless ($refuri) {
 3907:                 foreach my $key (keys(%env)) {
 3908: 		    if ($key=~/^httpref\..*\*/) {
 3909: 			my $pattern=$key;
 3910:                         $pattern=~s/^httpref\.\/res\///;
 3911:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3912:                         $pattern=~s/\//\\\//g;
 3913:                         if ($orguri=~/$pattern/) {
 3914: 			    $refuri=$env{$key};
 3915:                         }
 3916:                     }
 3917:                 }
 3918:             }
 3919: 
 3920:          if ($refuri) { 
 3921: 	  $refuri=&declutter($refuri);
 3922:           my ($match,$cond)=&is_on_map($refuri);
 3923:             if ($match) {
 3924:               my $refstatecond=$cond;
 3925:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3926:                   =~/\Q$priv\E\&([^\:]*)/) {
 3927:                   $thisallowed.=$1;
 3928:                   $uri=$refuri;
 3929:                   $statecond=$refstatecond;
 3930:               }
 3931:           }
 3932:         }
 3933:        }
 3934:    }
 3935: 
 3936: #
 3937: # Gathered now: all privileges that could apply, and condition number
 3938: # 
 3939: #
 3940: # Full or no access?
 3941: #
 3942: 
 3943:     if ($thisallowed=~/F/) {
 3944: 	return 'F';
 3945:     }
 3946: 
 3947:     unless ($thisallowed) {
 3948:         return '';
 3949:     }
 3950: 
 3951: # Restrictions exist, deal with them
 3952: #
 3953: #   C:according to course preferences
 3954: #   R:according to resource settings
 3955: #   L:unless locked
 3956: #   X:according to user session state
 3957: #
 3958: 
 3959: # Possibly locked functionality, check all courses
 3960: # Locks might take effect only after 10 minutes cache expiration for other
 3961: # courses, and 2 minutes for current course
 3962: 
 3963:     my $envkey;
 3964:     if ($thisallowed=~/L/) {
 3965:         foreach $envkey (keys %env) {
 3966:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3967:                my $courseid=$2;
 3968:                my $roleid=$1.'.'.$2;
 3969:                $courseid=~s/^\///;
 3970:                my $expiretime=600;
 3971:                if ($env{'request.role'} eq $roleid) {
 3972: 		  $expiretime=120;
 3973:                }
 3974: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3975:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3976:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3977: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3978:                }
 3979:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3980:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3981: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3982:                        &log($env{'user.domain'},$env{'user.name'},
 3983:                             $env{'user.home'},
 3984:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3985:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3986:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3987: 		       return '';
 3988:                    }
 3989:                }
 3990:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3991:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3992: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3993:                        &log($env{'user.domain'},$env{'user.name'},
 3994:                             $env{'user.home'},
 3995:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3996:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3997:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3998: 		       return '';
 3999:                    }
 4000:                }
 4001: 	   }
 4002:        }
 4003:     }
 4004:    
 4005: #
 4006: # Rest of the restrictions depend on selected course
 4007: #
 4008: 
 4009:     unless ($env{'request.course.id'}) {
 4010: 	if ($thisallowed eq 'A') {
 4011: 	    return 'A';
 4012:         } elsif ($thisallowed eq 'B') {
 4013:             return 'B';
 4014: 	} else {
 4015: 	    return '1';
 4016: 	}
 4017:     }
 4018: 
 4019: #
 4020: # Now user is definitely in a course
 4021: #
 4022: 
 4023: 
 4024: # Course preferences
 4025: 
 4026:    if ($thisallowed=~/C/) {
 4027:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4028:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4029:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4030: 	   =~/\Q$rolecode\E/) {
 4031: 	   if ($priv ne 'pch') { 
 4032: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4033: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4034: 			$env{'request.course.id'});
 4035: 	   }
 4036:            return '';
 4037:        }
 4038: 
 4039:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4040: 	   =~/\Q$unamedom\E/) {
 4041: 	   if ($priv ne 'pch') { 
 4042: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4043: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4044: 			$env{'request.course.id'});
 4045: 	   }
 4046:            return '';
 4047:        }
 4048:    }
 4049: 
 4050: # Resource preferences
 4051: 
 4052:    if ($thisallowed=~/R/) {
 4053:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4054:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4055: 	   if ($priv ne 'pch') { 
 4056: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4057: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4058: 	   }
 4059: 	   return '';
 4060:        }
 4061:    }
 4062: 
 4063: # Restricted by state or randomout?
 4064: 
 4065:    if ($thisallowed=~/X/) {
 4066:       if ($env{'acc.randomout'}) {
 4067: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4068:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4069:             return ''; 
 4070:          }
 4071:       }
 4072:       if (&condval($statecond)) {
 4073: 	 return '2';
 4074:       } else {
 4075:          return '';
 4076:       }
 4077:    }
 4078: 
 4079:     if ($thisallowed eq 'A') {
 4080: 	return 'A';
 4081:     } elsif ($thisallowed eq 'B') {
 4082:         return 'B';
 4083:     }
 4084:    return 'F';
 4085: }
 4086: 
 4087: sub split_uri_for_cond {
 4088:     my $uri=&deversion(&declutter(shift));
 4089:     my @uriparts=split(/\//,$uri);
 4090:     my $filename=pop(@uriparts);
 4091:     my $pathname=join('/',@uriparts);
 4092:     return ($pathname,$filename);
 4093: }
 4094: # --------------------------------------------------- Is a resource on the map?
 4095: 
 4096: sub is_on_map {
 4097:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4098:     #Trying to find the conditional for the file
 4099:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4100: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4101:     if ($match) {
 4102: 	return (1,$1);
 4103:     } else {
 4104: 	return (0,0);
 4105:     }
 4106: }
 4107: 
 4108: # --------------------------------------------------------- Get symb from alias
 4109: 
 4110: sub get_symb_from_alias {
 4111:     my $symb=shift;
 4112:     my ($map,$resid,$url)=&decode_symb($symb);
 4113: # Already is a symb
 4114:     if ($url) { return $symb; }
 4115: # Must be an alias
 4116:     my $aliassymb='';
 4117:     my %bighash;
 4118:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4119:                             &GDBM_READER(),0640)) {
 4120:         my $rid=$bighash{'mapalias_'.$symb};
 4121: 	if ($rid) {
 4122: 	    my ($mapid,$resid)=split(/\./,$rid);
 4123: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4124: 				    $resid,$bighash{'src_'.$rid});
 4125: 	}
 4126:         untie %bighash;
 4127:     }
 4128:     return $aliassymb;
 4129: }
 4130: 
 4131: # ----------------------------------------------------------------- Define Role
 4132: 
 4133: sub definerole {
 4134:   if (allowed('mcr','/')) {
 4135:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4136:     foreach my $role (split(':',$sysrole)) {
 4137: 	my ($crole,$cqual)=split(/\&/,$role);
 4138:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4139:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4140: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4141:                return "refused:s:$crole&$cqual"; 
 4142:             }
 4143:         }
 4144:     }
 4145:     foreach my $role (split(':',$domrole)) {
 4146: 	my ($crole,$cqual)=split(/\&/,$role);
 4147:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4148:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4149: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4150:                return "refused:d:$crole&$cqual"; 
 4151:             }
 4152:         }
 4153:     }
 4154:     foreach my $role (split(':',$courole)) {
 4155: 	my ($crole,$cqual)=split(/\&/,$role);
 4156:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4157:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4158: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4159:                return "refused:c:$crole&$cqual"; 
 4160:             }
 4161:         }
 4162:     }
 4163:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4164:                 "$env{'user.domain'}:$env{'user.name'}:".
 4165: 	        "rolesdef_$rolename=".
 4166:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4167:     return reply($command,$env{'user.home'});
 4168:   } else {
 4169:     return 'refused';
 4170:   }
 4171: }
 4172: 
 4173: # ---------------- Make a metadata query against the network of library servers
 4174: 
 4175: sub metadata_query {
 4176:     my ($query,$custom,$customshow,$server_array)=@_;
 4177:     my %rhash;
 4178:     my %libserv = &all_library();
 4179:     my @server_list = (defined($server_array) ? @$server_array
 4180:                                               : keys(%libserv) );
 4181:     for my $server (@server_list) {
 4182: 	unless ($custom or $customshow) {
 4183: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4184: 	    $rhash{$server}=$reply;
 4185: 	}
 4186: 	else {
 4187: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4188: 			     &escape($custom).':'.&escape($customshow),
 4189: 			     $server);
 4190: 	    $rhash{$server}=$reply;
 4191: 	}
 4192:     }
 4193:     return \%rhash;
 4194: }
 4195: 
 4196: # ----------------------------------------- Send log queries and wait for reply
 4197: 
 4198: sub log_query {
 4199:     my ($uname,$udom,$query,%filters)=@_;
 4200:     my $uhome=&homeserver($uname,$udom);
 4201:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4202:     my $uhost=&hostname($uhome);
 4203:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4204:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4205:                        $uhome);
 4206:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4207:     return get_query_reply($queryid);
 4208: }
 4209: 
 4210: # -------------------------- Update MySQL table for portfolio file
 4211: 
 4212: sub update_portfolio_table {
 4213:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4214:     my $homeserver = &homeserver($uname,$udom);
 4215:     my $queryid=
 4216:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4217:                ':'.&escape($file_name).':'.$action,$homeserver);
 4218:     my $reply = &get_query_reply($queryid);
 4219:     return $reply;
 4220: }
 4221: 
 4222: # ------- Request retrieval of institutional classlists for course(s)
 4223: 
 4224: sub fetch_enrollment_query {
 4225:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4226:     my $homeserver;
 4227:     my $maxtries = 1;
 4228:     if ($context eq 'automated') {
 4229:         $homeserver = $perlvar{'lonHostID'};
 4230:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4231:     } else {
 4232:         $homeserver = &homeserver($cnum,$dom);
 4233:     }
 4234:     my $host=&hostname($homeserver);
 4235:     my $cmd = '';
 4236:     foreach my $affiliate (keys %{$affiliatesref}) {
 4237:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4238:     }
 4239:     $cmd =~ s/%%$//;
 4240:     $cmd = &escape($cmd);
 4241:     my $query = 'fetchenrollment';
 4242:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4243:     unless ($queryid=~/^\Q$host\E\_/) { 
 4244:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4245:         return 'error: '.$queryid;
 4246:     }
 4247:     my $reply = &get_query_reply($queryid);
 4248:     my $tries = 1;
 4249:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4250:         $reply = &get_query_reply($queryid);
 4251:         $tries ++;
 4252:     }
 4253:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4254:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4255:     } else {
 4256:         my @responses = split/:/,$reply;
 4257:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4258:             foreach my $line (@responses) {
 4259:                 my ($key,$value) = split(/=/,$line,2);
 4260:                 $$replyref{$key} = $value;
 4261:             }
 4262:         } else {
 4263:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4264:             foreach my $line (@responses) {
 4265:                 my ($key,$value) = split(/=/,$line);
 4266:                 $$replyref{$key} = $value;
 4267:                 if ($value > 0) {
 4268:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4269:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4270:                         my $destname = $pathname.'/'.$filename;
 4271:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4272:                         if ($xml_classlist =~ /^error/) {
 4273:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4274:                         } else {
 4275:                             if ( open(FILE,">$destname") ) {
 4276:                                 print FILE &unescape($xml_classlist);
 4277:                                 close(FILE);
 4278:                             } else {
 4279:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4280:                             }
 4281:                         }
 4282:                     }
 4283:                 }
 4284:             }
 4285:         }
 4286:         return 'ok';
 4287:     }
 4288:     return 'error';
 4289: }
 4290: 
 4291: sub get_query_reply {
 4292:     my $queryid=shift;
 4293:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4294:     my $reply='';
 4295:     for (1..100) {
 4296: 	sleep 2;
 4297:         if (-e $replyfile.'.end') {
 4298: 	    if (open(my $fh,$replyfile)) {
 4299:                $reply.=<$fh>;
 4300:                close($fh);
 4301: 	   } else { return 'error: reply_file_error'; }
 4302:            return &unescape($reply);
 4303: 	}
 4304:     }
 4305:     return 'timeout:'.$queryid;
 4306: }
 4307: 
 4308: sub courselog_query {
 4309: #
 4310: # possible filters:
 4311: # url: url or symb
 4312: # username
 4313: # domain
 4314: # action: view, submit, grade
 4315: # start: timestamp
 4316: # end: timestamp
 4317: #
 4318:     my (%filters)=@_;
 4319:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4320:     if ($filters{'url'}) {
 4321: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4322:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4323:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4324:     }
 4325:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4326:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4327:     return &log_query($cname,$cdom,'courselog',%filters);
 4328: }
 4329: 
 4330: sub userlog_query {
 4331:     my ($uname,$udom,%filters)=@_;
 4332:     return &log_query($uname,$udom,'userlog',%filters);
 4333: }
 4334: 
 4335: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4336: 
 4337: sub auto_run {
 4338:     my ($cnum,$cdom) = @_;
 4339:     my $homeserver = &homeserver($cnum,$cdom);
 4340:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4341:     return $response;
 4342: }
 4343: 
 4344: sub auto_get_sections {
 4345:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4346:     my $homeserver = &homeserver($cnum,$cdom);
 4347:     my @secs = ();
 4348:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4349:     unless ($response eq 'refused') {
 4350:         @secs = split/:/,$response;
 4351:     }
 4352:     return @secs;
 4353: }
 4354: 
 4355: sub auto_new_course {
 4356:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4357:     my $homeserver = &homeserver($cnum,$cdom);
 4358:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4359:     return $response;
 4360: }
 4361: 
 4362: sub auto_validate_courseID {
 4363:     my ($cnum,$cdom,$inst_course_id) = @_;
 4364:     my $homeserver = &homeserver($cnum,$cdom);
 4365:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4366:     return $response;
 4367: }
 4368: 
 4369: sub auto_create_password {
 4370:     my ($cnum,$cdom,$authparam) = @_;
 4371:     my $homeserver = &homeserver($cnum,$cdom); 
 4372:     my $create_passwd = 0;
 4373:     my $authchk = '';
 4374:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4375:     if ($response eq 'refused') {
 4376:         $authchk = 'refused';
 4377:     } else {
 4378:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4379:     }
 4380:     return ($authparam,$create_passwd,$authchk);
 4381: }
 4382: 
 4383: sub auto_photo_permission {
 4384:     my ($cnum,$cdom,$students) = @_;
 4385:     my $homeserver = &homeserver($cnum,$cdom);
 4386:     my ($outcome,$perm_reqd,$conditions) = 
 4387: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4388:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4389: 	return (undef,undef);
 4390:     }
 4391:     return ($outcome,$perm_reqd,$conditions);
 4392: }
 4393: 
 4394: sub auto_checkphotos {
 4395:     my ($uname,$udom,$pid) = @_;
 4396:     my $homeserver = &homeserver($uname,$udom);
 4397:     my ($result,$resulttype);
 4398:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4399: 				   &escape($uname).':'.&escape($pid),
 4400: 				   $homeserver));
 4401:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4402: 	return (undef,undef);
 4403:     }
 4404:     if ($outcome) {
 4405:         ($result,$resulttype) = split(/:/,$outcome);
 4406:     } 
 4407:     return ($result,$resulttype);
 4408: }
 4409: 
 4410: sub auto_photochoice {
 4411:     my ($cnum,$cdom) = @_;
 4412:     my $homeserver = &homeserver($cnum,$cdom);
 4413:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4414: 						       &escape($cdom),
 4415: 						       $homeserver)));
 4416:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4417: 	return (undef,undef);
 4418:     }
 4419:     return ($update,$comment);
 4420: }
 4421: 
 4422: sub auto_photoupdate {
 4423:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4424:     my $homeserver = &homeserver($cnum,$dom);
 4425:     my $host=&hostname($homeserver);
 4426:     my $cmd = '';
 4427:     my $maxtries = 1;
 4428:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4429:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4430:     }
 4431:     $cmd =~ s/%%$//;
 4432:     $cmd = &escape($cmd);
 4433:     my $query = 'institutionalphotos';
 4434:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4435:     unless ($queryid=~/^\Q$host\E\_/) {
 4436:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4437:         return 'error: '.$queryid;
 4438:     }
 4439:     my $reply = &get_query_reply($queryid);
 4440:     my $tries = 1;
 4441:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4442:         $reply = &get_query_reply($queryid);
 4443:         $tries ++;
 4444:     }
 4445:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4446:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4447:     } else {
 4448:         my @responses = split(/:/,$reply);
 4449:         my $outcome = shift(@responses); 
 4450:         foreach my $item (@responses) {
 4451:             my ($key,$value) = split(/=/,$item);
 4452:             $$photo{$key} = $value;
 4453:         }
 4454:         return $outcome;
 4455:     }
 4456:     return 'error';
 4457: }
 4458: 
 4459: sub auto_instcode_format {
 4460:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4461: 	$cat_order) = @_;
 4462:     my $courses = '';
 4463:     my @homeservers;
 4464:     if ($caller eq 'global') {
 4465: 	my %servers = &get_servers($codedom,'library');
 4466: 	foreach my $tryserver (keys(%servers)) {
 4467: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4468: 		push(@homeservers,$tryserver);
 4469: 	    }
 4470:         }
 4471:     } else {
 4472:         push(@homeservers,&homeserver($caller,$codedom));
 4473:     }
 4474:     foreach my $code (keys(%{$instcodes})) {
 4475:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4476:     }
 4477:     chop($courses);
 4478:     my $ok_response = 0;
 4479:     my $response;
 4480:     while (@homeservers > 0 && $ok_response == 0) {
 4481:         my $server = shift(@homeservers); 
 4482:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4483:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4484:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4485: 		split/:/,$response;
 4486:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4487:             push(@{$codetitles},&str2array($codetitles_str));
 4488:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4489:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4490:             $ok_response = 1;
 4491:         }
 4492:     }
 4493:     if ($ok_response) {
 4494:         return 'ok';
 4495:     } else {
 4496:         return $response;
 4497:     }
 4498: }
 4499: 
 4500: sub auto_instcode_defaults {
 4501:     my ($domain,$returnhash,$code_order) = @_;
 4502:     my @homeservers;
 4503: 
 4504:     my %servers = &get_servers($domain,'library');
 4505:     foreach my $tryserver (keys(%servers)) {
 4506: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4507: 	    push(@homeservers,$tryserver);
 4508: 	}
 4509:     }
 4510: 
 4511:     my $response;
 4512:     foreach my $server (@homeservers) {
 4513:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4514:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4515: 	
 4516: 	foreach my $pair (split(/\&/,$response)) {
 4517: 	    my ($name,$value)=split(/\=/,$pair);
 4518: 	    if ($name eq 'code_order') {
 4519: 		@{$code_order} = split(/\&/,&unescape($value));
 4520: 	    } else {
 4521: 		$returnhash->{&unescape($name)}=&unescape($value);
 4522: 	    }
 4523: 	}
 4524: 	return 'ok';
 4525:     }
 4526: 
 4527:     return $response;
 4528: } 
 4529: 
 4530: sub auto_validate_class_sec {
 4531:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4532:     my $homeserver = &homeserver($cnum,$cdom);
 4533:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4534:                         &escape($owner).':'.$cdom,$homeserver);
 4535:     return $response;
 4536: }
 4537: 
 4538: # ------------------------------------------------------- Course Group routines
 4539: 
 4540: sub get_coursegroups {
 4541:     my ($cdom,$cnum,$group,$namespace) = @_;
 4542:     return(&dump($namespace,$cdom,$cnum,$group));
 4543: }
 4544: 
 4545: sub modify_coursegroup {
 4546:     my ($cdom,$cnum,$groupsettings) = @_;
 4547:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4548: }
 4549: 
 4550: sub toggle_coursegroup_status {
 4551:     my ($cdom,$cnum,$group,$action) = @_;
 4552:     my ($from_namespace,$to_namespace);
 4553:     if ($action eq 'delete') {
 4554:         $from_namespace = 'coursegroups';
 4555:         $to_namespace = 'deleted_groups';
 4556:     } else {
 4557:         $from_namespace = 'deleted_groups';
 4558:         $to_namespace = 'coursegroups';
 4559:     }
 4560:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4561:     if (my $tmp = &error(%curr_group)) {
 4562:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4563:         return ('read error',$tmp);
 4564:     } else {
 4565:         my %savedsettings = %curr_group; 
 4566:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4567:         my $deloutcome;
 4568:         if ($result eq 'ok') {
 4569:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4570:         } else {
 4571:             return ('write error',$result);
 4572:         }
 4573:         if ($deloutcome eq 'ok') {
 4574:             return 'ok';
 4575:         } else {
 4576:             return ('delete error',$deloutcome);
 4577:         }
 4578:     }
 4579: }
 4580: 
 4581: sub modify_group_roles {
 4582:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4583:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4584:     my $role = 'gr/'.&escape($userprivs);
 4585:     my ($uname,$udom) = split(/:/,$user);
 4586:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4587:     if ($result eq 'ok') {
 4588:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4589:     }
 4590:     return $result;
 4591: }
 4592: 
 4593: sub modify_coursegroup_membership {
 4594:     my ($cdom,$cnum,$membership) = @_;
 4595:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4596:     return $result;
 4597: }
 4598: 
 4599: sub get_active_groups {
 4600:     my ($udom,$uname,$cdom,$cnum) = @_;
 4601:     my $now = time;
 4602:     my %groups = ();
 4603:     foreach my $key (keys(%env)) {
 4604:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4605:             my ($start,$end) = split(/\./,$env{$key});
 4606:             if (($end!=0) && ($end<$now)) { next; }
 4607:             if (($start!=0) && ($start>$now)) { next; }
 4608:             if ($1 eq $cdom && $2 eq $cnum) {
 4609:                 $groups{$3} = $env{$key} ;
 4610:             }
 4611:         }
 4612:     }
 4613:     return %groups;
 4614: }
 4615: 
 4616: sub get_group_membership {
 4617:     my ($cdom,$cnum,$group) = @_;
 4618:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4619: }
 4620: 
 4621: sub get_users_groups {
 4622:     my ($udom,$uname,$courseid) = @_;
 4623:     my @usersgroups;
 4624:     my $cachetime=1800;
 4625: 
 4626:     my $hashid="$udom:$uname:$courseid";
 4627:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4628:     if (defined($cached)) {
 4629:         @usersgroups = split(/:/,$grouplist);
 4630:     } else {  
 4631:         $grouplist = '';
 4632:         my $courseurl = &courseid_to_courseurl($courseid);
 4633:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4634:         my $access_end = $env{'course.'.$courseid.
 4635:                               '.default_enrollment_end_date'};
 4636:         my $now = time;
 4637:         foreach my $key (keys(%roleshash)) {
 4638:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4639:                 my $group = $1;
 4640:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4641:                     my $start = $2;
 4642:                     my $end = $1;
 4643:                     if ($start == -1) { next; } # deleted from group
 4644:                     if (($start!=0) && ($start>$now)) { next; }
 4645:                     if (($end!=0) && ($end<$now)) {
 4646:                         if ($access_end && $access_end < $now) {
 4647:                             if ($access_end - $end < 86400) {
 4648:                                 push(@usersgroups,$group);
 4649:                             }
 4650:                         }
 4651:                         next;
 4652:                     }
 4653:                     push(@usersgroups,$group);
 4654:                 }
 4655:             }
 4656:         }
 4657:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4658:         $grouplist = join(':',@usersgroups);
 4659:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4660:     }
 4661:     return @usersgroups;
 4662: }
 4663: 
 4664: sub devalidate_getgroups_cache {
 4665:     my ($udom,$uname,$cdom,$cnum)=@_;
 4666:     my $courseid = $cdom.'_'.$cnum;
 4667: 
 4668:     my $hashid="$udom:$uname:$courseid";
 4669:     &devalidate_cache_new('getgroups',$hashid);
 4670: }
 4671: 
 4672: # ------------------------------------------------------------------ Plain Text
 4673: 
 4674: sub plaintext {
 4675:     my ($short,$type,$cid) = @_;
 4676:     if ($short =~ /^cr/) {
 4677: 	return (split('/',$short))[-1];
 4678:     }
 4679:     if (!defined($cid)) {
 4680:         $cid = $env{'request.course.id'};
 4681:     }
 4682:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4683:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4684:                                           '.plaintext'});
 4685:     }
 4686:     my %rolenames = (
 4687:                       Course => 'std',
 4688:                       Group => 'alt1',
 4689:                     );
 4690:     if (defined($type) && 
 4691:          defined($rolenames{$type}) && 
 4692:          defined($prp{$short}{$rolenames{$type}})) {
 4693:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4694:     } else {
 4695:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4696:     }
 4697: }
 4698: 
 4699: # ----------------------------------------------------------------- Assign Role
 4700: 
 4701: sub assignrole {
 4702:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4703:     my $mrole;
 4704:     if ($role =~ /^cr\//) {
 4705:         my $cwosec=$url;
 4706:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4707: 	unless (&allowed('ccr',$cwosec)) {
 4708:            &logthis('Refused custom assignrole: '.
 4709:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4710: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4711:            return 'refused'; 
 4712:         }
 4713:         $mrole='cr';
 4714:     } elsif ($role =~ /^gr\//) {
 4715:         my $cwogrp=$url;
 4716:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4717:         unless (&allowed('mdg',$cwogrp)) {
 4718:             &logthis('Refused group assignrole: '.
 4719:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4720:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4721:             return 'refused';
 4722:         }
 4723:         $mrole='gr';
 4724:     } else {
 4725:         my $cwosec=$url;
 4726:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4727:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4728:            &logthis('Refused assignrole: '.
 4729:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4730: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4731:            return 'refused'; 
 4732:         }
 4733:         $mrole=$role;
 4734:     }
 4735:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4736:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4737:     if ($end) { $command.='_'.$end; }
 4738:     if ($start) {
 4739: 	if ($end) { 
 4740:            $command.='_'.$start; 
 4741:         } else {
 4742:            $command.='_0_'.$start;
 4743:         }
 4744:     }
 4745:     my $origstart = $start;
 4746:     my $origend = $end;
 4747: # actually delete
 4748:     if ($deleteflag) {
 4749: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4750: # modify command to delete the role
 4751:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4752:                 "$udom:$uname:$url".'_'."$mrole";
 4753: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4754: # set start and finish to negative values for userrolelog
 4755:            $start=-1;
 4756:            $end=-1;
 4757:         }
 4758:     }
 4759: # send command
 4760:     my $answer=&reply($command,&homeserver($uname,$udom));
 4761: # log new user role if status is ok
 4762:     if ($answer eq 'ok') {
 4763: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4764: # for course roles, perform group memberships changes triggered by role change.
 4765:         unless ($role =~ /^gr/) {
 4766:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4767:                                              $origstart);
 4768:         }
 4769:     }
 4770:     return $answer;
 4771: }
 4772: 
 4773: # -------------------------------------------------- Modify user authentication
 4774: # Overrides without validation
 4775: 
 4776: sub modifyuserauth {
 4777:     my ($udom,$uname,$umode,$upass)=@_;
 4778:     my $uhome=&homeserver($uname,$udom);
 4779:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4780:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4781:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4782:              ' in domain '.$env{'request.role.domain'});  
 4783:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4784: 		     &escape($upass),$uhome);
 4785:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4786:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4787:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4788:     &log($udom,,$uname,$uhome,
 4789:         'Authentication changed by '.$env{'user.domain'}.', '.
 4790:                                      $env{'user.name'}.', '.$umode.
 4791:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4792:     unless ($reply eq 'ok') {
 4793:         &logthis('Authentication mode error: '.$reply);
 4794: 	return 'error: '.$reply;
 4795:     }   
 4796:     return 'ok';
 4797: }
 4798: 
 4799: # --------------------------------------------------------------- Modify a user
 4800: 
 4801: sub modifyuser {
 4802:     my ($udom,    $uname, $uid,
 4803:         $umode,   $upass, $first,
 4804:         $middle,  $last,  $gene,
 4805:         $forceid, $desiredhome, $email)=@_;
 4806:     $udom= &LONCAPA::clean_domain($udom);
 4807:     $uname=&LONCAPA::clean_username($uname);
 4808:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4809:              $umode.', '.$first.', '.$middle.', '.
 4810: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4811:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4812:                                      ' desiredhome not specified'). 
 4813:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4814:              ' in domain '.$env{'request.role.domain'});
 4815:     my $uhome=&homeserver($uname,$udom,'true');
 4816: # ----------------------------------------------------------------- Create User
 4817:     if (($uhome eq 'no_host') && 
 4818: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4819:         my $unhome='';
 4820:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4821:             $unhome = $desiredhome;
 4822: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4823: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4824:         } else { # load balancing routine for determining $unhome
 4825:             my $loadm=10000000;
 4826: 	    my %servers = &get_servers($udom,'library');
 4827: 	    foreach my $tryserver (keys(%servers)) {
 4828: 		my $answer=reply('load',$tryserver);
 4829: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4830: 		    $loadm=$answer;
 4831: 		    $unhome=$tryserver;
 4832: 		}
 4833: 	    }
 4834:         }
 4835:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4836: 	    return 'error: unable to find a home server for '.$uname.
 4837:                    ' in domain '.$udom;
 4838:         }
 4839:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4840:                          &escape($upass),$unhome);
 4841: 	unless ($reply eq 'ok') {
 4842:             return 'error: '.$reply;
 4843:         }   
 4844:         $uhome=&homeserver($uname,$udom,'true');
 4845:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4846: 	    return 'error: unable verify users home machine.';
 4847:         }
 4848:     }   # End of creation of new user
 4849: # ---------------------------------------------------------------------- Add ID
 4850:     if ($uid) {
 4851:        $uid=~tr/A-Z/a-z/;
 4852:        my %uidhash=&idrget($udom,$uname);
 4853:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4854:          && (!$forceid)) {
 4855: 	  unless ($uid eq $uidhash{$uname}) {
 4856: 	      return 'error: user id "'.$uid.'" does not match '.
 4857:                   'current user id "'.$uidhash{$uname}.'".';
 4858:           }
 4859:        } else {
 4860: 	  &idput($udom,($uname => $uid));
 4861:        }
 4862:     }
 4863: # -------------------------------------------------------------- Add names, etc
 4864:     my @tmp=&get('environment',
 4865: 		   ['firstname','middlename','lastname','generation'],
 4866: 		   $udom,$uname);
 4867:     my %names;
 4868:     if ($tmp[0] =~ m/^error:.*/) { 
 4869:         %names=(); 
 4870:     } else {
 4871:         %names = @tmp;
 4872:     }
 4873: #
 4874: # Make sure to not trash student environment if instructor does not bother
 4875: # to supply name and email information
 4876: #
 4877:     if ($first)  { $names{'firstname'}  = $first; }
 4878:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4879:     if ($last)   { $names{'lastname'}   = $last; }
 4880:     if (defined($gene))   { $names{'generation'} = $gene; }
 4881:     if ($email) {
 4882:        $email=~s/[^\w\@\.\-\,]//gs;
 4883:        if ($email=~/\@/) { $names{'notification'} = $email;
 4884: 			   $names{'critnotification'} = $email;
 4885: 			   $names{'permanentemail'} = $email; }
 4886:     }
 4887:     my $reply = &put('environment', \%names, $udom,$uname);
 4888:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4889:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4890:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4891:              $umode.', '.$first.', '.$middle.', '.
 4892: 	     $last.', '.$gene.' by '.
 4893:              $env{'user.name'}.' at '.$env{'user.domain'});
 4894:     return 'ok';
 4895: }
 4896: 
 4897: # -------------------------------------------------------------- Modify student
 4898: 
 4899: sub modifystudent {
 4900:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4901:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4902:     if (!$cid) {
 4903: 	unless ($cid=$env{'request.course.id'}) {
 4904: 	    return 'not_in_class';
 4905: 	}
 4906:     }
 4907: # --------------------------------------------------------------- Make the user
 4908:     my $reply=&modifyuser
 4909: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4910:          $desiredhome,$email);
 4911:     unless ($reply eq 'ok') { return $reply; }
 4912:     # This will cause &modify_student_enrollment to get the uid from the
 4913:     # students environment
 4914:     $uid = undef if (!$forceid);
 4915:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4916: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4917:     return $reply;
 4918: }
 4919: 
 4920: sub modify_student_enrollment {
 4921:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4922:     my ($cdom,$cnum,$chome);
 4923:     if (!$cid) {
 4924: 	unless ($cid=$env{'request.course.id'}) {
 4925: 	    return 'not_in_class';
 4926: 	}
 4927: 	$cdom=$env{'course.'.$cid.'.domain'};
 4928: 	$cnum=$env{'course.'.$cid.'.num'};
 4929:     } else {
 4930: 	($cdom,$cnum)=split(/_/,$cid);
 4931:     }
 4932:     $chome=$env{'course.'.$cid.'.home'};
 4933:     if (!$chome) {
 4934: 	$chome=&homeserver($cnum,$cdom);
 4935:     }
 4936:     if (!$chome) { return 'unknown_course'; }
 4937:     # Make sure the user exists
 4938:     my $uhome=&homeserver($uname,$udom);
 4939:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4940: 	return 'error: no such user';
 4941:     }
 4942:     # Get student data if we were not given enough information
 4943:     if (!defined($first)  || $first  eq '' || 
 4944:         !defined($last)   || $last   eq '' || 
 4945:         !defined($uid)    || $uid    eq '' || 
 4946:         !defined($middle) || $middle eq '' || 
 4947:         !defined($gene)   || $gene   eq '') {
 4948:         # They did not supply us with enough data to enroll the student, so
 4949:         # we need to pick up more information.
 4950:         my %tmp = &get('environment',
 4951:                        ['firstname','middlename','lastname', 'generation','id']
 4952:                        ,$udom,$uname);
 4953: 
 4954:         #foreach my $key (keys(%tmp)) {
 4955:         #    &logthis("key $key = ".$tmp{$key});
 4956:         #}
 4957:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4958:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4959:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4960:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4961:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4962:     }
 4963:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4964:     my $reply=cput('classlist',
 4965: 		   {"$uname:$udom" => 
 4966: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4967: 		   $cdom,$cnum);
 4968:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4969: 	return 'error: '.$reply;
 4970:     } else {
 4971: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4972:     }
 4973:     # Add student role to user
 4974:     my $uurl='/'.$cid;
 4975:     $uurl=~s/\_/\//g;
 4976:     if ($usec) {
 4977: 	$uurl.='/'.$usec;
 4978:     }
 4979:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4980: }
 4981: 
 4982: sub format_name {
 4983:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4984:     my $name;
 4985:     if ($first ne 'lastname') {
 4986: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4987:     } else {
 4988: 	if ($lastname=~/\S/) {
 4989: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4990: 	    $name=~s/\s+,/,/;
 4991: 	} else {
 4992: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4993: 	}
 4994:     }
 4995:     $name=~s/^\s+//;
 4996:     $name=~s/\s+$//;
 4997:     $name=~s/\s+/ /g;
 4998:     return $name;
 4999: }
 5000: 
 5001: # ------------------------------------------------- Write to course preferences
 5002: 
 5003: sub writecoursepref {
 5004:     my ($courseid,%prefs)=@_;
 5005:     $courseid=~s/^\///;
 5006:     $courseid=~s/\_/\//g;
 5007:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5008:     my $chome=homeserver($cnum,$cdomain);
 5009:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5010: 	return 'error: no such course';
 5011:     }
 5012:     my $cstring='';
 5013:     foreach my $pref (keys(%prefs)) {
 5014: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5015:     }
 5016:     $cstring=~s/\&$//;
 5017:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5018: }
 5019: 
 5020: # ---------------------------------------------------------- Make/modify course
 5021: 
 5022: sub createcourse {
 5023:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5024:         $course_owner,$crstype)=@_;
 5025:     $url=&declutter($url);
 5026:     my $cid='';
 5027:     unless (&allowed('ccc',$udom)) {
 5028:         return 'refused';
 5029:     }
 5030: # ------------------------------------------------------------------- Create ID
 5031:    my $uname=int(1+rand(9)).
 5032:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5033:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5034:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5035: # ----------------------------------------------- Make sure that does not exist
 5036:    my $uhome=&homeserver($uname,$udom,'true');
 5037:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5038:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5039:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5040:        $uhome=&homeserver($uname,$udom,'true');       
 5041:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5042:            return 'error: unable to generate unique course-ID';
 5043:        } 
 5044:    }
 5045: # ------------------------------------------------ Check supplied server name
 5046:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5047:     if (! &is_library($course_server)) {
 5048:         return 'error:bad server name '.$course_server;
 5049:     }
 5050: # ------------------------------------------------------------- Make the course
 5051:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5052:                       $course_server);
 5053:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5054:     $uhome=&homeserver($uname,$udom,'true');
 5055:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5056: 	return 'error: no such course';
 5057:     }
 5058: # ----------------------------------------------------------------- Course made
 5059: # log existence
 5060:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5061:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5062:                   &escape($crstype),$uhome);
 5063:     &flushcourselogs();
 5064: # set toplevel url
 5065:     my $topurl=$url;
 5066:     unless ($nonstandard) {
 5067: # ------------------------------------------ For standard courses, make top url
 5068:         my $mapurl=&clutter($url);
 5069:         if ($mapurl eq '/res/') { $mapurl=''; }
 5070:         $env{'form.initmap'}=(<<ENDINITMAP);
 5071: <map>
 5072: <resource id="1" type="start"></resource>
 5073: <resource id="2" src="$mapurl"></resource>
 5074: <resource id="3" type="finish"></resource>
 5075: <link index="1" from="1" to="2"></link>
 5076: <link index="2" from="2" to="3"></link>
 5077: </map>
 5078: ENDINITMAP
 5079:         $topurl=&declutter(
 5080:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5081:                           );
 5082:     }
 5083: # ----------------------------------------------------------- Write preferences
 5084:     &writecoursepref($udom.'_'.$uname,
 5085:                      ('description' => $description,
 5086:                       'url'         => $topurl));
 5087:     return '/'.$udom.'/'.$uname;
 5088: }
 5089: 
 5090: sub is_course {
 5091:     my ($cdom,$cnum) = @_;
 5092:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5093: 				undef,'.');
 5094:     if (exists($courses{$cdom.'_'.$cnum})) {
 5095:         return 1;
 5096:     }
 5097:     return 0;
 5098: }
 5099: 
 5100: # ---------------------------------------------------------- Assign Custom Role
 5101: 
 5102: sub assigncustomrole {
 5103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5104:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5105:                        $end,$start,$deleteflag);
 5106: }
 5107: 
 5108: # ----------------------------------------------------------------- Revoke Role
 5109: 
 5110: sub revokerole {
 5111:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5112:     my $now=time;
 5113:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5114: }
 5115: 
 5116: # ---------------------------------------------------------- Revoke Custom Role
 5117: 
 5118: sub revokecustomrole {
 5119:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5120:     my $now=time;
 5121:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5122:            $deleteflag);
 5123: }
 5124: 
 5125: # ------------------------------------------------------------ Disk usage
 5126: sub diskusage {
 5127:     my ($udom,$uname,$directoryRoot)=@_;
 5128:     $directoryRoot =~ s/\/$//;
 5129:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5130:     return $listing;
 5131: }
 5132: 
 5133: sub is_locked {
 5134:     my ($file_name, $domain, $user) = @_;
 5135:     my @check;
 5136:     my $is_locked;
 5137:     push @check, $file_name;
 5138:     my %locked = &get('file_permissions',\@check,
 5139: 		      $env{'user.domain'},$env{'user.name'});
 5140:     my ($tmp)=keys(%locked);
 5141:     if ($tmp=~/^error:/) { undef(%locked); }
 5142:     
 5143:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5144:         $is_locked = 'false';
 5145:         foreach my $entry (@{$locked{$file_name}}) {
 5146:            if (ref($entry) eq 'ARRAY') { 
 5147:                $is_locked = 'true';
 5148:                last;
 5149:            }
 5150:        }
 5151:     } else {
 5152:         $is_locked = 'false';
 5153:     }
 5154: }
 5155: 
 5156: sub declutter_portfile {
 5157:     my ($file) = @_;
 5158:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5159:     return $file;
 5160: }
 5161: 
 5162: # ------------------------------------------------------------- Mark as Read Only
 5163: 
 5164: sub mark_as_readonly {
 5165:     my ($domain,$user,$files,$what) = @_;
 5166:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5167:     my ($tmp)=keys(%current_permissions);
 5168:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5169:     foreach my $file (@{$files}) {
 5170: 	$file = &declutter_portfile($file);
 5171:         push(@{$current_permissions{$file}},$what);
 5172:     }
 5173:     &put('file_permissions',\%current_permissions,$domain,$user);
 5174:     return;
 5175: }
 5176: 
 5177: # ------------------------------------------------------------Save Selected Files
 5178: 
 5179: sub save_selected_files {
 5180:     my ($user, $path, @files) = @_;
 5181:     my $filename = $user."savedfiles";
 5182:     my @other_files = &files_not_in_path($user, $path);
 5183:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5184:     foreach my $file (@files) {
 5185:         print (OUT $env{'form.currentpath'}.$file."\n");
 5186:     }
 5187:     foreach my $file (@other_files) {
 5188:         print (OUT $file."\n");
 5189:     }
 5190:     close (OUT);
 5191:     return 'ok';
 5192: }
 5193: 
 5194: sub clear_selected_files {
 5195:     my ($user) = @_;
 5196:     my $filename = $user."savedfiles";
 5197:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5198:     print (OUT undef);
 5199:     close (OUT);
 5200:     return ("ok");    
 5201: }
 5202: 
 5203: sub files_in_path {
 5204:     my ($user, $path) = @_;
 5205:     my $filename = $user."savedfiles";
 5206:     my %return_files;
 5207:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5208:     while (my $line_in = <IN>) {
 5209:         chomp ($line_in);
 5210:         my @paths_and_file = split (m!/!, $line_in);
 5211:         my $file_part = pop (@paths_and_file);
 5212:         my $path_part = join ('/', @paths_and_file);
 5213:         $path_part.='/';
 5214:         my $path_and_file = $path_part.$file_part;
 5215:         if ($path_part eq $path) {
 5216:             $return_files{$file_part}= 'selected';
 5217:         }
 5218:     }
 5219:     close (IN);
 5220:     return (\%return_files);
 5221: }
 5222: 
 5223: # called in portfolio select mode, to show files selected NOT in current directory
 5224: sub files_not_in_path {
 5225:     my ($user, $path) = @_;
 5226:     my $filename = $user."savedfiles";
 5227:     my @return_files;
 5228:     my $path_part;
 5229:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5230:     while (my $line = <IN>) {
 5231:         #ok, I know it's clunky, but I want it to work
 5232:         my @paths_and_file = split(m|/|, $line);
 5233:         my $file_part = pop(@paths_and_file);
 5234:         chomp($file_part);
 5235:         my $path_part = join('/', @paths_and_file);
 5236:         $path_part .= '/';
 5237:         my $path_and_file = $path_part.$file_part;
 5238:         if ($path_part ne $path) {
 5239:             push(@return_files, ($path_and_file));
 5240:         }
 5241:     }
 5242:     close(OUT);
 5243:     return (@return_files);
 5244: }
 5245: 
 5246: #----------------------------------------------Get portfolio file permissions
 5247: 
 5248: sub get_portfile_permissions {
 5249:     my ($domain,$user) = @_;
 5250:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5251:     my ($tmp)=keys(%current_permissions);
 5252:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5253:     return \%current_permissions;
 5254: }
 5255: 
 5256: #---------------------------------------------Get portfolio file access controls
 5257: 
 5258: sub get_access_controls {
 5259:     my ($current_permissions,$group,$file) = @_;
 5260:     my %access;
 5261:     my $real_file = $file;
 5262:     $file =~ s/\.meta$//;
 5263:     if (defined($file)) {
 5264:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5265:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5266:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5267:             }
 5268:         }
 5269:     } else {
 5270:         foreach my $key (keys(%{$current_permissions})) {
 5271:             if ($key =~ /\0accesscontrol$/) {
 5272:                 if (defined($group)) {
 5273:                     if ($key !~ m-^\Q$group\E/-) {
 5274:                         next;
 5275:                     }
 5276:                 }
 5277:                 my ($fullpath) = split(/\0/,$key);
 5278:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5279:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5280:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5281:                     }
 5282:                 }
 5283:             }
 5284:         }
 5285:     }
 5286:     return %access;
 5287: }
 5288: 
 5289: sub modify_access_controls {
 5290:     my ($file_name,$changes,$domain,$user)=@_;
 5291:     my ($outcome,$deloutcome);
 5292:     my %store_permissions;
 5293:     my %new_values;
 5294:     my %new_control;
 5295:     my %translation;
 5296:     my @deletions = ();
 5297:     my $now = time;
 5298:     if (exists($$changes{'activate'})) {
 5299:         if (ref($$changes{'activate'}) eq 'HASH') {
 5300:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5301:             my $numnew = scalar(@newitems);
 5302:             for (my $i=0; $i<$numnew; $i++) {
 5303:                 my $newkey = $newitems[$i];
 5304:                 my $newid = &Apache::loncommon::get_cgi_id();
 5305:                 if ($newkey =~ /^\d+:/) { 
 5306:                     $newkey =~ s/^(\d+)/$newid/;
 5307:                     $translation{$1} = $newid;
 5308:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5309:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5310:                     $translation{$1} = $newid;
 5311:                 }
 5312:                 $new_values{$file_name."\0".$newkey} = 
 5313:                                           $$changes{'activate'}{$newitems[$i]};
 5314:                 $new_control{$newkey} = $now;
 5315:             }
 5316:         }
 5317:     }
 5318:     my %todelete;
 5319:     my %changed_items;
 5320:     foreach my $action ('delete','update') {
 5321:         if (exists($$changes{$action})) {
 5322:             if (ref($$changes{$action}) eq 'HASH') {
 5323:                 foreach my $key (keys(%{$$changes{$action}})) {
 5324:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5325:                     if ($action eq 'delete') { 
 5326:                         $todelete{$itemnum} = 1;
 5327:                     } else {
 5328:                         $changed_items{$itemnum} = $key;
 5329:                     }
 5330:                 }
 5331:             }
 5332:         }
 5333:     }
 5334:     # get lock on access controls for file.
 5335:     my $lockhash = {
 5336:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5337:                                                        ':'.$env{'user.domain'},
 5338:                    }; 
 5339:     my $tries = 0;
 5340:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5341:    
 5342:     while (($gotlock ne 'ok') && $tries <3) {
 5343:         $tries ++;
 5344:         sleep 1;
 5345:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5346:     }
 5347:     if ($gotlock eq 'ok') {
 5348:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5349:         my ($tmp)=keys(%curr_permissions);
 5350:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5351:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5352:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5353:             if (ref($curr_controls) eq 'HASH') {
 5354:                 foreach my $control_item (keys(%{$curr_controls})) {
 5355:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5356:                     if (defined($todelete{$itemnum})) {
 5357:                         push(@deletions,$file_name."\0".$control_item);
 5358:                     } else {
 5359:                         if (defined($changed_items{$itemnum})) {
 5360:                             $new_control{$changed_items{$itemnum}} = $now;
 5361:                             push(@deletions,$file_name."\0".$control_item);
 5362:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5363:                         } else {
 5364:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5365:                         }
 5366:                     }
 5367:                 }
 5368:             }
 5369:         }
 5370:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5371:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5372:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5373:         #  remove lock
 5374:         my @del_lock = ($file_name."\0".'locked_access_records');
 5375:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5376:         my ($file,$group);
 5377:         if (&is_course($domain,$user)) {
 5378:             ($group,$file) = split(/\//,$file_name,2);
 5379:         } else {
 5380:             $file = $file_name;
 5381:         }
 5382:         my $sqlresult =
 5383:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5384:                                     $group);
 5385:     } else {
 5386:         $outcome = "error: could not obtain lockfile\n";  
 5387:     }
 5388:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5389: }
 5390: 
 5391: sub make_public_indefinitely {
 5392:     my ($requrl) = @_;
 5393:     my $now = time;
 5394:     my $action = 'activate';
 5395:     my $aclnum = 0;
 5396:     if (&is_portfolio_url($requrl)) {
 5397:         my (undef,$udom,$unum,$file_name,$group) =
 5398:             &parse_portfolio_url($requrl);
 5399:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5400:         my %access_controls = &get_access_controls($current_perms,
 5401:                                                    $group,$file_name);
 5402:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5403:             my ($num,$scope,$end,$start) = 
 5404:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5405:             if ($scope eq 'public') {
 5406:                 if ($start <= $now && $end == 0) {
 5407:                     $action = 'none';
 5408:                 } else {
 5409:                     $action = 'update';
 5410:                     $aclnum = $num;
 5411:                 }
 5412:                 last;
 5413:             }
 5414:         }
 5415:         if ($action eq 'none') {
 5416:              return 'ok';
 5417:         } else {
 5418:             my %changes;
 5419:             my $newend = 0;
 5420:             my $newstart = $now;
 5421:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5422:             $changes{$action}{$newkey} = {
 5423:                 type => 'public',
 5424:                 time => {
 5425:                     start => $newstart,
 5426:                     end   => $newend,
 5427:                 },
 5428:             };
 5429:             my ($outcome,$deloutcome,$new_values,$translation) =
 5430:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5431:             return $outcome;
 5432:         }
 5433:     } else {
 5434:         return 'invalid';
 5435:     }
 5436: }
 5437: 
 5438: #------------------------------------------------------Get Marked as Read Only
 5439: 
 5440: sub get_marked_as_readonly {
 5441:     my ($domain,$user,$what,$group) = @_;
 5442:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5443:     my @readonly_files;
 5444:     my $cmp1=$what;
 5445:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5446:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5447:         if (defined($group)) {
 5448:             if ($file_name !~ m-^\Q$group\E/-) {
 5449:                 next;
 5450:             }
 5451:         }
 5452:         if (ref($value) eq "ARRAY"){
 5453:             foreach my $stored_what (@{$value}) {
 5454:                 my $cmp2=$stored_what;
 5455:                 if (ref($stored_what) eq 'ARRAY') {
 5456:                     $cmp2=join('',@{$stored_what});
 5457:                 }
 5458:                 if ($cmp1 eq $cmp2) {
 5459:                     push(@readonly_files, $file_name);
 5460:                     last;
 5461:                 } elsif (!defined($what)) {
 5462:                     push(@readonly_files, $file_name);
 5463:                     last;
 5464:                 }
 5465:             }
 5466:         }
 5467:     }
 5468:     return @readonly_files;
 5469: }
 5470: #-----------------------------------------------------------Get Marked as Read Only Hash
 5471: 
 5472: sub get_marked_as_readonly_hash {
 5473:     my ($current_permissions,$group,$what) = @_;
 5474:     my %readonly_files;
 5475:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5476:         if (defined($group)) {
 5477:             if ($file_name !~ m-^\Q$group\E/-) {
 5478:                 next;
 5479:             }
 5480:         }
 5481:         if (ref($value) eq "ARRAY"){
 5482:             foreach my $stored_what (@{$value}) {
 5483:                 if (ref($stored_what) eq 'ARRAY') {
 5484:                     foreach my $lock_descriptor(@{$stored_what}) {
 5485:                         if ($lock_descriptor eq 'graded') {
 5486:                             $readonly_files{$file_name} = 'graded';
 5487:                         } elsif ($lock_descriptor eq 'handback') {
 5488:                             $readonly_files{$file_name} = 'handback';
 5489:                         } else {
 5490:                             if (!exists($readonly_files{$file_name})) {
 5491:                                 $readonly_files{$file_name} = 'locked';
 5492:                             }
 5493:                         }
 5494:                     }
 5495:                 } 
 5496:             }
 5497:         } 
 5498:     }
 5499:     return %readonly_files;
 5500: }
 5501: # ------------------------------------------------------------ Unmark as Read Only
 5502: 
 5503: sub unmark_as_readonly {
 5504:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5505:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5506:     my ($domain,$user,$what,$file_name,$group) = @_;
 5507:     $file_name = &declutter_portfile($file_name);
 5508:     my $symb_crs = $what;
 5509:     if (ref($what)) { $symb_crs=join('',@$what); }
 5510:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5511:     my ($tmp)=keys(%current_permissions);
 5512:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5513:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5514:     foreach my $file (@readonly_files) {
 5515: 	my $clean_file = &declutter_portfile($file);
 5516: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5517: 	my $current_locks = $current_permissions{$file};
 5518:         my @new_locks;
 5519:         my @del_keys;
 5520:         if (ref($current_locks) eq "ARRAY"){
 5521:             foreach my $locker (@{$current_locks}) {
 5522:                 my $compare=$locker;
 5523:                 if (ref($locker) eq 'ARRAY') {
 5524:                     $compare=join('',@{$locker});
 5525:                     if ($compare ne $symb_crs) {
 5526:                         push(@new_locks, $locker);
 5527:                     }
 5528:                 }
 5529:             }
 5530:             if (scalar(@new_locks) > 0) {
 5531:                 $current_permissions{$file} = \@new_locks;
 5532:             } else {
 5533:                 push(@del_keys, $file);
 5534:                 &del('file_permissions',\@del_keys, $domain, $user);
 5535:                 delete($current_permissions{$file});
 5536:             }
 5537:         }
 5538:     }
 5539:     &put('file_permissions',\%current_permissions,$domain,$user);
 5540:     return;
 5541: }
 5542: 
 5543: # ------------------------------------------------------------ Directory lister
 5544: 
 5545: sub dirlist {
 5546:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5547: 
 5548:     $uri=~s/^\///;
 5549:     $uri=~s/\/$//;
 5550:     my ($udom, $uname);
 5551:     (undef,$udom,$uname)=split(/\//,$uri);
 5552:     if(defined($userdomain)) {
 5553:         $udom = $userdomain;
 5554:     }
 5555:     if(defined($username)) {
 5556:         $uname = $username;
 5557:     }
 5558: 
 5559:     my $dirRoot = $perlvar{'lonDocRoot'};
 5560:     if(defined($alternateDirectoryRoot)) {
 5561:         $dirRoot = $alternateDirectoryRoot;
 5562:         $dirRoot =~ s/\/$//;
 5563:     }
 5564: 
 5565:     if($udom) {
 5566:         if($uname) {
 5567:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5568: 				 &homeserver($uname,$udom));
 5569:             my @listing_results;
 5570:             if ($listing eq 'unknown_cmd') {
 5571:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5572: 				  &homeserver($uname,$udom));
 5573:                 @listing_results = split(/:/,$listing);
 5574:             } else {
 5575:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5576:             }
 5577:             return @listing_results;
 5578:         } elsif(!defined($alternateDirectoryRoot)) {
 5579:             my %allusers;
 5580: 	    my %servers = &get_servers($udom,'library');
 5581: 	    foreach my $tryserver (keys(%servers)) {
 5582: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5583: 				     $udom, $tryserver);
 5584: 		my @listing_results;
 5585: 		if ($listing eq 'unknown_cmd') {
 5586: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5587: 				      $udom, $tryserver);
 5588: 		    @listing_results = split(/:/,$listing);
 5589: 		} else {
 5590: 		    @listing_results =
 5591: 			map { &unescape($_); } split(/:/,$listing);
 5592: 		}
 5593: 		if ($listing_results[0] ne 'no_such_dir' && 
 5594: 		    $listing_results[0] ne 'empty'       &&
 5595: 		    $listing_results[0] ne 'con_lost') {
 5596: 		    foreach my $line (@listing_results) {
 5597: 			my ($entry) = split(/&/,$line,2);
 5598: 			$allusers{$entry} = 1;
 5599: 		    }
 5600: 		}
 5601:             }
 5602:             my $alluserstr='';
 5603:             foreach my $user (sort(keys(%allusers))) {
 5604:                 $alluserstr.=$user.'&user:';
 5605:             }
 5606:             $alluserstr=~s/:$//;
 5607:             return split(/:/,$alluserstr);
 5608:         } else {
 5609:             return ('missing user name');
 5610:         }
 5611:     } elsif(!defined($alternateDirectoryRoot)) {
 5612:         my @all_domains = sort(&all_domains());
 5613:          foreach my $domain (@all_domains) {
 5614:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5615:          }
 5616:          return @all_domains;
 5617:      } else {
 5618:         return ('missing domain');
 5619:     }
 5620: }
 5621: 
 5622: # --------------------------------------------- GetFileTimestamp
 5623: # This function utilizes dirlist and returns the date stamp for
 5624: # when it was last modified.  It will also return an error of -1
 5625: # if an error occurs
 5626: 
 5627: ##
 5628: ## FIXME: This subroutine assumes its caller knows something about the
 5629: ## directory structure of the home server for the student ($root).
 5630: ## Not a good assumption to make.  Since this is for looking up files
 5631: ## in user directories, the full path should be constructed by lond, not
 5632: ## whatever machine we request data from.
 5633: ##
 5634: sub GetFileTimestamp {
 5635:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5636:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5637:     $studentName   = &LONCAPA::clean_username($studentName);
 5638:     my $subdir=$studentName.'__';
 5639:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5640:     my $proname="$studentDomain/$subdir/$studentName";
 5641:     $proname .= '/'.$filename;
 5642:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5643:                                               $studentName, $root);
 5644:     my @stats = split('&', $fileStat);
 5645:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5646:         # @stats contains first the filename, then the stat output
 5647:         return $stats[10]; # so this is 10 instead of 9.
 5648:     } else {
 5649:         return -1;
 5650:     }
 5651: }
 5652: 
 5653: sub stat_file {
 5654:     my ($uri) = @_;
 5655:     $uri = &clutter_with_no_wrapper($uri);
 5656: 
 5657:     my ($udom,$uname,$file,$dir);
 5658:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5659: 	($udom,$uname,$file) =
 5660: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5661: 	$file = 'userfiles/'.$file;
 5662: 	$dir = &propath($udom,$uname);
 5663:     }
 5664:     if ($uri =~ m-^/res/-) {
 5665: 	($udom,$uname) = 
 5666: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5667: 	$file = $uri;
 5668:     }
 5669: 
 5670:     if (!$udom || !$uname || !$file) {
 5671: 	# unable to handle the uri
 5672: 	return ();
 5673:     }
 5674: 
 5675:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5676:     my @stats = split('&', $result);
 5677:     
 5678:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5679: 	shift(@stats); #filename is first
 5680: 	return @stats;
 5681:     }
 5682:     return ();
 5683: }
 5684: 
 5685: # -------------------------------------------------------- Value of a Condition
 5686: 
 5687: # gets the value of a specific preevaluated condition
 5688: #    stored in the string  $env{user.state.<cid>}
 5689: # or looks up a condition reference in the bighash and if if hasn't
 5690: # already been evaluated recurses into docondval to get the value of
 5691: # the condition, then memoizing it to 
 5692: #   $env{user.state.<cid>.<condition>}
 5693: sub directcondval {
 5694:     my $number=shift;
 5695:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5696: 	&Apache::lonuserstate::evalstate();
 5697:     }
 5698:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5699: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5700:     } elsif ($number =~ /^_/) {
 5701: 	my $sub_condition;
 5702: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5703: 		&GDBM_READER(),0640)) {
 5704: 	    $sub_condition=$bighash{'conditions'.$number};
 5705: 	    untie(%bighash);
 5706: 	}
 5707: 	my $value = &docondval($sub_condition);
 5708: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5709: 	return $value;
 5710:     }
 5711:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5712:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5713:     } else {
 5714:        return 2;
 5715:     }
 5716: }
 5717: 
 5718: # get the collection of conditions for this resource
 5719: sub condval {
 5720:     my $condidx=shift;
 5721:     my $allpathcond='';
 5722:     foreach my $cond (split(/\|/,$condidx)) {
 5723: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5724: 	    $allpathcond.=
 5725: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5726: 	}
 5727:     }
 5728:     $allpathcond=~s/\|$//;
 5729:     return &docondval($allpathcond);
 5730: }
 5731: 
 5732: #evaluates an expression of conditions
 5733: sub docondval {
 5734:     my ($allpathcond) = @_;
 5735:     my $result=0;
 5736:     if ($env{'request.course.id'}
 5737: 	&& defined($allpathcond)) {
 5738: 	my $operand='|';
 5739: 	my @stack;
 5740: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5741: 	    if ($chunk eq '(') {
 5742: 		push @stack,($operand,$result);
 5743: 	    } elsif ($chunk eq ')') {
 5744: 		my $before=pop @stack;
 5745: 		if (pop @stack eq '&') {
 5746: 		    $result=$result>$before?$before:$result;
 5747: 		} else {
 5748: 		    $result=$result>$before?$result:$before;
 5749: 		}
 5750: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5751: 		$operand=$chunk;
 5752: 	    } else {
 5753: 		my $new=directcondval($chunk);
 5754: 		if ($operand eq '&') {
 5755: 		    $result=$result>$new?$new:$result;
 5756: 		} else {
 5757: 		    $result=$result>$new?$result:$new;
 5758: 		}
 5759: 	    }
 5760: 	}
 5761:     }
 5762:     return $result;
 5763: }
 5764: 
 5765: # ---------------------------------------------------- Devalidate courseresdata
 5766: 
 5767: sub devalidatecourseresdata {
 5768:     my ($coursenum,$coursedomain)=@_;
 5769:     my $hashid=$coursenum.':'.$coursedomain;
 5770:     &devalidate_cache_new('courseres',$hashid);
 5771: }
 5772: 
 5773: 
 5774: # --------------------------------------------------- Course Resourcedata Query
 5775: 
 5776: sub get_courseresdata {
 5777:     my ($coursenum,$coursedomain)=@_;
 5778:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5779:     my $hashid=$coursenum.':'.$coursedomain;
 5780:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5781:     my %dumpreply;
 5782:     unless (defined($cached)) {
 5783: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5784: 	$result=\%dumpreply;
 5785: 	my ($tmp) = keys(%dumpreply);
 5786: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5787: 	    &do_cache_new('courseres',$hashid,$result,600);
 5788: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5789: 	    return $tmp;
 5790: 	} elsif ($tmp =~ /^(error)/) {
 5791: 	    $result=undef;
 5792: 	    &do_cache_new('courseres',$hashid,$result,600);
 5793: 	}
 5794:     }
 5795:     return $result;
 5796: }
 5797: 
 5798: sub devalidateuserresdata {
 5799:     my ($uname,$udom)=@_;
 5800:     my $hashid="$udom:$uname";
 5801:     &devalidate_cache_new('userres',$hashid);
 5802: }
 5803: 
 5804: sub get_userresdata {
 5805:     my ($uname,$udom)=@_;
 5806:     #most student don\'t have any data set, check if there is some data
 5807:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5808: 
 5809:     my $hashid="$udom:$uname";
 5810:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5811:     if (!defined($cached)) {
 5812: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5813: 	$result=\%resourcedata;
 5814: 	&do_cache_new('userres',$hashid,$result,600);
 5815:     }
 5816:     my ($tmp)=keys(%$result);
 5817:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5818: 	return $result;
 5819:     }
 5820:     #error 2 occurs when the .db doesn't exist
 5821:     if ($tmp!~/error: 2 /) {
 5822: 	&logthis("<font color=\"blue\">WARNING:".
 5823: 		 " Trying to get resource data for ".
 5824: 		 $uname." at ".$udom.": ".
 5825: 		 $tmp."</font>");
 5826:     } elsif ($tmp=~/error: 2 /) {
 5827: 	#&EXT_cache_set($udom,$uname);
 5828: 	&do_cache_new('userres',$hashid,undef,600);
 5829: 	undef($tmp); # not really an error so don't send it back
 5830:     }
 5831:     return $tmp;
 5832: }
 5833: 
 5834: sub resdata {
 5835:     my ($name,$domain,$type,@which)=@_;
 5836:     my $result;
 5837:     if ($type eq 'course') {
 5838: 	$result=&get_courseresdata($name,$domain);
 5839:     } elsif ($type eq 'user') {
 5840: 	$result=&get_userresdata($name,$domain);
 5841:     }
 5842:     if (!ref($result)) { return $result; }    
 5843:     foreach my $item (@which) {
 5844: 	if (defined($result->{$item})) {
 5845: 	    return $result->{$item};
 5846: 	}
 5847:     }
 5848:     return undef;
 5849: }
 5850: 
 5851: #
 5852: # EXT resource caching routines
 5853: #
 5854: 
 5855: sub clear_EXT_cache_status {
 5856:     &delenv('cache.EXT.');
 5857: }
 5858: 
 5859: sub EXT_cache_status {
 5860:     my ($target_domain,$target_user) = @_;
 5861:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5862:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5863:         # We know already the user has no data
 5864:         return 1;
 5865:     } else {
 5866:         return 0;
 5867:     }
 5868: }
 5869: 
 5870: sub EXT_cache_set {
 5871:     my ($target_domain,$target_user) = @_;
 5872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5873:     #&appenv($cachename => time);
 5874: }
 5875: 
 5876: # --------------------------------------------------------- Value of a Variable
 5877: sub EXT {
 5878: 
 5879:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5880:     unless ($varname) { return ''; }
 5881:     #get real user name/domain, courseid and symb
 5882:     my $courseid;
 5883:     my $publicuser;
 5884:     if ($symbparm) {
 5885: 	$symbparm=&get_symb_from_alias($symbparm);
 5886:     }
 5887:     if (!($uname && $udom)) {
 5888:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5889:       if (!$symbparm) {	$symbparm=$cursymb; }
 5890:     } else {
 5891: 	$courseid=$env{'request.course.id'};
 5892:     }
 5893:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5894:     my $rest;
 5895:     if (defined($therest[0])) {
 5896:        $rest=join('.',@therest);
 5897:     } else {
 5898:        $rest='';
 5899:     }
 5900: 
 5901:     my $qualifierrest=$qualifier;
 5902:     if ($rest) { $qualifierrest.='.'.$rest; }
 5903:     my $spacequalifierrest=$space;
 5904:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5905:     if ($realm eq 'user') {
 5906: # --------------------------------------------------------------- user.resource
 5907: 	if ($space eq 'resource') {
 5908: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5909: 		  || defined($Apache::lonhomework::parsing_a_task))
 5910: 		 &&
 5911: 		 ($symbparm eq &symbread()) ) {	
 5912: 		# if we are in the middle of processing the resource the
 5913: 		# get the value we are planning on committing
 5914:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5915:                     return $Apache::lonhomework::results{$qualifierrest};
 5916:                 } else {
 5917:                     return $Apache::lonhomework::history{$qualifierrest};
 5918:                 }
 5919: 	    } else {
 5920: 		my %restored;
 5921: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5922: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5923: 		} else {
 5924: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5925: 		}
 5926: 		return $restored{$qualifierrest};
 5927: 	    }
 5928: # ----------------------------------------------------------------- user.access
 5929:         } elsif ($space eq 'access') {
 5930: 	    # FIXME - not supporting calls for a specific user
 5931:             return &allowed($qualifier,$rest);
 5932: # ------------------------------------------ user.preferences, user.environment
 5933:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5934: 	    if (($uname eq $env{'user.name'}) &&
 5935: 		($udom eq $env{'user.domain'})) {
 5936: 		return $env{join('.',('environment',$qualifierrest))};
 5937: 	    } else {
 5938: 		my %returnhash;
 5939: 		if (!$publicuser) {
 5940: 		    %returnhash=&userenvironment($udom,$uname,
 5941: 						 $qualifierrest);
 5942: 		}
 5943: 		return $returnhash{$qualifierrest};
 5944: 	    }
 5945: # ----------------------------------------------------------------- user.course
 5946:         } elsif ($space eq 'course') {
 5947: 	    # FIXME - not supporting calls for a specific user
 5948:             return $env{join('.',('request.course',$qualifier))};
 5949: # ------------------------------------------------------------------- user.role
 5950:         } elsif ($space eq 'role') {
 5951: 	    # FIXME - not supporting calls for a specific user
 5952:             my ($role,$where)=split(/\./,$env{'request.role'});
 5953:             if ($qualifier eq 'value') {
 5954: 		return $role;
 5955:             } elsif ($qualifier eq 'extent') {
 5956:                 return $where;
 5957:             }
 5958: # ----------------------------------------------------------------- user.domain
 5959:         } elsif ($space eq 'domain') {
 5960:             return $udom;
 5961: # ------------------------------------------------------------------- user.name
 5962:         } elsif ($space eq 'name') {
 5963:             return $uname;
 5964: # ---------------------------------------------------- Any other user namespace
 5965:         } else {
 5966: 	    my %reply;
 5967: 	    if (!$publicuser) {
 5968: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5969: 	    }
 5970: 	    return $reply{$qualifierrest};
 5971:         }
 5972:     } elsif ($realm eq 'query') {
 5973: # ---------------------------------------------- pull stuff out of query string
 5974:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5975: 						[$spacequalifierrest]);
 5976: 	return $env{'form.'.$spacequalifierrest}; 
 5977:    } elsif ($realm eq 'request') {
 5978: # ------------------------------------------------------------- request.browser
 5979:         if ($space eq 'browser') {
 5980: 	    if ($qualifier eq 'textremote') {
 5981: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5982: 		    return 1;
 5983: 		} else {
 5984: 		    return 0;
 5985: 		}
 5986: 	    } else {
 5987: 		return $env{'browser.'.$qualifier};
 5988: 	    }
 5989: # ------------------------------------------------------------ request.filename
 5990:         } else {
 5991:             return $env{'request.'.$spacequalifierrest};
 5992:         }
 5993:     } elsif ($realm eq 'course') {
 5994: # ---------------------------------------------------------- course.description
 5995:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5996:     } elsif ($realm eq 'resource') {
 5997: 
 5998: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5999: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6000: 	}
 6001: 
 6002: 	if ($space eq 'title') {
 6003: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6004: 	    return &gettitle($symbparm);
 6005: 	}
 6006: 	
 6007: 	if ($space eq 'map') {
 6008: 	    my ($map) = &decode_symb($symbparm);
 6009: 	    return &symbread($map);
 6010: 	}
 6011: 
 6012: 	my ($section, $group, @groups);
 6013: 	my ($courselevelm,$courselevel);
 6014: 	if ($symbparm && defined($courseid) && 
 6015: 	    $courseid eq $env{'request.course.id'}) {
 6016: 
 6017: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6018: 
 6019: # ----------------------------------------------------- Cascading lookup scheme
 6020: 	    my $symbp=$symbparm;
 6021: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6022: 
 6023: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6024: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6025: 
 6026: 	    if (($env{'user.name'} eq $uname) &&
 6027: 		($env{'user.domain'} eq $udom)) {
 6028: 		$section=$env{'request.course.sec'};
 6029:                 @groups = split(/:/,$env{'request.course.groups'});  
 6030:                 @groups=&sort_course_groups($courseid,@groups); 
 6031: 	    } else {
 6032: 		if (! defined($usection)) {
 6033: 		    $section=&getsection($udom,$uname,$courseid);
 6034: 		} else {
 6035: 		    $section = $usection;
 6036: 		}
 6037:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6038: 	    }
 6039: 
 6040: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6041: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6042: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6043: 
 6044: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6045: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6046: 	    $courselevelm=$courseid.'.'.$mapparm;
 6047: 
 6048: # ----------------------------------------------------------- first, check user
 6049: 
 6050: 	    my $userreply=&resdata($uname,$udom,'user',
 6051: 				       ($courselevelr,$courselevelm,
 6052: 					$courselevel));
 6053: 	    if (defined($userreply)) { return $userreply; }
 6054: 
 6055: # ------------------------------------------------ second, check some of course
 6056:             my $coursereply;
 6057:             if (@groups > 0) {
 6058:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6059:                                        $mapparm,$spacequalifierrest);
 6060:                 if (defined($coursereply)) { return $coursereply; }
 6061:             }
 6062: 
 6063: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6064: 				     $env{'course.'.$courseid.'.domain'},
 6065: 				     'course',
 6066: 				     ($seclevelr,$seclevelm,$seclevel,
 6067: 				      $courselevelr));
 6068: 	    if (defined($coursereply)) { return $coursereply; }
 6069: 
 6070: # ------------------------------------------------------ third, check map parms
 6071: 	    my %parmhash=();
 6072: 	    my $thisparm='';
 6073: 	    if (tie(%parmhash,'GDBM_File',
 6074: 		    $env{'request.course.fn'}.'_parms.db',
 6075: 		    &GDBM_READER(),0640)) {
 6076: 		$thisparm=$parmhash{$symbparm};
 6077: 		untie(%parmhash);
 6078: 	    }
 6079: 	    if ($thisparm) { return $thisparm; }
 6080: 	}
 6081: # ------------------------------------------ fourth, look in resource metadata
 6082: 
 6083: 	$spacequalifierrest=~s/\./\_/;
 6084: 	my $filename;
 6085: 	if (!$symbparm) { $symbparm=&symbread(); }
 6086: 	if ($symbparm) {
 6087: 	    $filename=(&decode_symb($symbparm))[2];
 6088: 	} else {
 6089: 	    $filename=$env{'request.filename'};
 6090: 	}
 6091: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6092: 	if (defined($metadata)) { return $metadata; }
 6093: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6094: 	if (defined($metadata)) { return $metadata; }
 6095: 
 6096: # ---------------------------------------------- fourth, look in rest pf course
 6097: 	if ($symbparm && defined($courseid) && 
 6098: 	    $courseid eq $env{'request.course.id'}) {
 6099: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6100: 				     $env{'course.'.$courseid.'.domain'},
 6101: 				     'course',
 6102: 				     ($courselevelm,$courselevel));
 6103: 	    if (defined($coursereply)) { return $coursereply; }
 6104: 	}
 6105: # ------------------------------------------------------------------ Cascade up
 6106: 	unless ($space eq '0') {
 6107: 	    my @parts=split(/_/,$space);
 6108: 	    my $id=pop(@parts);
 6109: 	    my $part=join('_',@parts);
 6110: 	    if ($part eq '') { $part='0'; }
 6111: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6112: 				 $symbparm,$udom,$uname,$section,1);
 6113: 	    if (defined($partgeneral)) { return $partgeneral; }
 6114: 	}
 6115: 	if ($recurse) { return undef; }
 6116: 	my $pack_def=&packages_tab_default($filename,$varname);
 6117: 	if (defined($pack_def)) { return $pack_def; }
 6118: 
 6119: # ---------------------------------------------------- Any other user namespace
 6120:     } elsif ($realm eq 'environment') {
 6121: # ----------------------------------------------------------------- environment
 6122: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6123: 	    return $env{'environment.'.$spacequalifierrest};
 6124: 	} else {
 6125: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6126: 		return '';
 6127: 	    }
 6128: 	    my %returnhash=&userenvironment($udom,$uname,
 6129: 					    $spacequalifierrest);
 6130: 	    return $returnhash{$spacequalifierrest};
 6131: 	}
 6132:     } elsif ($realm eq 'system') {
 6133: # ----------------------------------------------------------------- system.time
 6134: 	if ($space eq 'time') {
 6135: 	    return time;
 6136:         }
 6137:     } elsif ($realm eq 'server') {
 6138: # ----------------------------------------------------------------- system.time
 6139: 	if ($space eq 'name') {
 6140: 	    return $ENV{'SERVER_NAME'};
 6141:         }
 6142:     }
 6143:     return '';
 6144: }
 6145: 
 6146: sub check_group_parms {
 6147:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6148:     my @groupitems = ();
 6149:     my $resultitem;
 6150:     my @levels = ($symbparm,$mapparm,$what);
 6151:     foreach my $group (@{$groups}) {
 6152:         foreach my $level (@levels) {
 6153:              my $item = $courseid.'.['.$group.'].'.$level;
 6154:              push(@groupitems,$item);
 6155:         }
 6156:     }
 6157:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6158:                             $env{'course.'.$courseid.'.domain'},
 6159:                                      'course',@groupitems);
 6160:     return $coursereply;
 6161: }
 6162: 
 6163: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6164:     my ($courseid,@groups) = @_;
 6165:     @groups = sort(@groups);
 6166:     return @groups;
 6167: }
 6168: 
 6169: sub packages_tab_default {
 6170:     my ($uri,$varname)=@_;
 6171:     my (undef,$part,$name)=split(/\./,$varname);
 6172: 
 6173:     my (@extension,@specifics,$do_default);
 6174:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6175: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6176: 	if ($pack_type eq 'default') {
 6177: 	    $do_default=1;
 6178: 	} elsif ($pack_type eq 'extension') {
 6179: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6180: 	} else {
 6181: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6182: 	}
 6183:     }
 6184:     # first look for a package that matches the requested part id
 6185:     foreach my $package (@specifics) {
 6186: 	my (undef,$pack_type,$pack_part)=@{$package};
 6187: 	next if ($pack_part ne $part);
 6188: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6189: 	    return $packagetab{"$pack_type&$name&default"};
 6190: 	}
 6191:     }
 6192:     # look for any possible matching non extension_ package
 6193:     foreach my $package (@specifics) {
 6194: 	my (undef,$pack_type,$pack_part)=@{$package};
 6195: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6196: 	    return $packagetab{"$pack_type&$name&default"};
 6197: 	}
 6198: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6199: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6200: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6201: 	}
 6202:     }
 6203:     # look for any posible extension_ match
 6204:     foreach my $package (@extension) {
 6205: 	my ($package,$pack_type)=@{$package};
 6206: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6207: 	    return $packagetab{"$pack_type&$name&default"};
 6208: 	}
 6209: 	if (defined($packagetab{$package."&$name&default"})) {
 6210: 	    return $packagetab{$package."&$name&default"};
 6211: 	}
 6212:     }
 6213:     # look for a global default setting
 6214:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6215: 	return $packagetab{"default&$name&default"};
 6216:     }
 6217:     return undef;
 6218: }
 6219: 
 6220: sub add_prefix_and_part {
 6221:     my ($prefix,$part)=@_;
 6222:     my $keyroot;
 6223:     if (defined($prefix) && $prefix !~ /^__/) {
 6224: 	# prefix that has a part already
 6225: 	$keyroot=$prefix;
 6226:     } elsif (defined($prefix)) {
 6227: 	# prefix that is missing a part
 6228: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6229:     } else {
 6230: 	# no prefix at all
 6231: 	if (defined($part)) { $keyroot='_'.$part; }
 6232:     }
 6233:     return $keyroot;
 6234: }
 6235: 
 6236: # ---------------------------------------------------------------- Get metadata
 6237: 
 6238: my %metaentry;
 6239: sub metadata {
 6240:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6241:     $uri=&declutter($uri);
 6242:     # if it is a non metadata possible uri return quickly
 6243:     if (($uri eq '') || 
 6244: 	(($uri =~ m|^/*adm/|) && 
 6245: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6246:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6247: 	($uri =~ m|home/$match_username/public_html/|)) {
 6248: 	return undef;
 6249:     }
 6250:     my $filename=$uri;
 6251:     $uri=~s/\.meta$//;
 6252: #
 6253: # Is the metadata already cached?
 6254: # Look at timestamp of caching
 6255: # Everything is cached by the main uri, libraries are never directly cached
 6256: #
 6257:     if (!defined($liburi)) {
 6258: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6259: 	if (defined($cached)) { return $result->{':'.$what}; }
 6260:     }
 6261:     {
 6262: #
 6263: # Is this a recursive call for a library?
 6264: #
 6265: #	if (! exists($metacache{$uri})) {
 6266: #	    $metacache{$uri}={};
 6267: #	}
 6268:         if ($liburi) {
 6269: 	    $liburi=&declutter($liburi);
 6270:             $filename=$liburi;
 6271:         } else {
 6272: 	    &devalidate_cache_new('meta',$uri);
 6273: 	    undef(%metaentry);
 6274: 	}
 6275:         my %metathesekeys=();
 6276:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6277: 	my $metastring;
 6278: 	if ($uri !~ m -^(editupload)/-) {
 6279: 	    my $file=&filelocation('',&clutter($filename));
 6280: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6281: 	    $metastring=&getfile($file);
 6282: 	}
 6283:         my $parser=HTML::LCParser->new(\$metastring);
 6284:         my $token;
 6285:         undef %metathesekeys;
 6286:         while ($token=$parser->get_token) {
 6287: 	    if ($token->[0] eq 'S') {
 6288: 		if (defined($token->[2]->{'package'})) {
 6289: #
 6290: # This is a package - get package info
 6291: #
 6292: 		    my $package=$token->[2]->{'package'};
 6293: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6294: 		    if (defined($token->[2]->{'id'})) { 
 6295: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6296: 		    }
 6297: 		    if ($metaentry{':packages'}) {
 6298: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6299: 		    } else {
 6300: 			$metaentry{':packages'}=$package.$keyroot;
 6301: 		    }
 6302: 		    foreach my $pack_entry (keys(%packagetab)) {
 6303: 			my $part=$keyroot;
 6304: 			$part=~s/^\_//;
 6305: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6306: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6307: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6308: 			    # ignore package.tab specified default values
 6309:                             # here &package_tab_default() will fetch those
 6310: 			    if ($subp eq 'default') { next; }
 6311: 			    my $value=$packagetab{$pack_entry};
 6312: 			    my $unikey;
 6313: 			    if ($pack =~ /_0$/) {
 6314: 				$unikey='parameter_0_'.$name;
 6315: 				$part=0;
 6316: 			    } else {
 6317: 				$unikey='parameter'.$keyroot.'_'.$name;
 6318: 			    }
 6319: 			    if ($subp eq 'display') {
 6320: 				$value.=' [Part: '.$part.']';
 6321: 			    }
 6322: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6323: 			    $metathesekeys{$unikey}=1;
 6324: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6325: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6326: 			    }
 6327: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6328: 				$metaentry{':'.$unikey}=
 6329: 				    $metaentry{':'.$unikey.'.default'};
 6330: 			    }
 6331: 			}
 6332: 		    }
 6333: 		} else {
 6334: #
 6335: # This is not a package - some other kind of start tag
 6336: #
 6337: 		    my $entry=$token->[1];
 6338: 		    my $unikey;
 6339: 		    if ($entry eq 'import') {
 6340: 			$unikey='';
 6341: 		    } else {
 6342: 			$unikey=$entry;
 6343: 		    }
 6344: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6345: 
 6346: 		    if (defined($token->[2]->{'id'})) { 
 6347: 			$unikey.='_'.$token->[2]->{'id'}; 
 6348: 		    }
 6349: 
 6350: 		    if ($entry eq 'import') {
 6351: #
 6352: # Importing a library here
 6353: #
 6354: 			if ($depthcount<20) {
 6355: 			    my $location=$parser->get_text('/import');
 6356: 			    my $dir=$filename;
 6357: 			    $dir=~s|[^/]*$||;
 6358: 			    $location=&filelocation($dir,$location);
 6359: 			    my $metadata = 
 6360: 				&metadata($uri,'keys', $location,$unikey,
 6361: 					  $depthcount+1);
 6362: 			    foreach my $meta (split(',',$metadata)) {
 6363: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6364: 				$metathesekeys{$meta}=1;
 6365: 			    }
 6366: 			}
 6367: 		    } else { 
 6368: 			
 6369: 			if (defined($token->[2]->{'name'})) { 
 6370: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6371: 			}
 6372: 			$metathesekeys{$unikey}=1;
 6373: 			foreach my $param (@{$token->[3]}) {
 6374: 			    $metaentry{':'.$unikey.'.'.$param} =
 6375: 				$token->[2]->{$param};
 6376: 			}
 6377: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6378: 			my $default=$metaentry{':'.$unikey.'.default'};
 6379: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6380: 		 # only ws inside the tag, and not in default, so use default
 6381: 		 # as value
 6382: 			    $metaentry{':'.$unikey}=$default;
 6383: 			} else {
 6384: 		  # either something interesting inside the tag or default
 6385:                   # uninteresting
 6386: 			    $metaentry{':'.$unikey}=$internaltext;
 6387: 			}
 6388: # end of not-a-package not-a-library import
 6389: 		    }
 6390: # end of not-a-package start tag
 6391: 		}
 6392: # the next is the end of "start tag"
 6393: 	    }
 6394: 	}
 6395: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6396: 	foreach my $key (keys(%packagetab)) {
 6397: 	    #no specific packages #how's our extension
 6398: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6399: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6400: 					 \%metathesekeys);
 6401: 	}
 6402: 	if (!exists($metaentry{':packages'})) {
 6403: 	    foreach my $key (keys(%packagetab)) {
 6404: 		#no specific packages well let's get default then
 6405: 		if ($key!~/^default&/) { next; }
 6406: 		&metadata_create_package_def($uri,$key,'default',
 6407: 					     \%metathesekeys);
 6408: 	    }
 6409: 	}
 6410: # are there custom rights to evaluate
 6411: 	if ($metaentry{':copyright'} eq 'custom') {
 6412: 
 6413:     #
 6414:     # Importing a rights file here
 6415:     #
 6416: 	    unless ($depthcount) {
 6417: 		my $location=$metaentry{':customdistributionfile'};
 6418: 		my $dir=$filename;
 6419: 		$dir=~s|[^/]*$||;
 6420: 		$location=&filelocation($dir,$location);
 6421: 		my $rights_metadata =
 6422: 		    &metadata($uri,'keys',$location,'_rights',
 6423: 			      $depthcount+1);
 6424: 		foreach my $rights (split(',',$rights_metadata)) {
 6425: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6426: 		    $metathesekeys{$rights}=1;
 6427: 		}
 6428: 	    }
 6429: 	}
 6430: 	# uniqifiy package listing
 6431: 	my %seen;
 6432: 	my @uniq_packages =
 6433: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6434: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6435: 
 6436: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6437: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6438: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6439: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6440: # this is the end of "was not already recently cached
 6441:     }
 6442:     return $metaentry{':'.$what};
 6443: }
 6444: 
 6445: sub metadata_create_package_def {
 6446:     my ($uri,$key,$package,$metathesekeys)=@_;
 6447:     my ($pack,$name,$subp)=split(/\&/,$key);
 6448:     if ($subp eq 'default') { next; }
 6449:     
 6450:     if (defined($metaentry{':packages'})) {
 6451: 	$metaentry{':packages'}.=','.$package;
 6452:     } else {
 6453: 	$metaentry{':packages'}=$package;
 6454:     }
 6455:     my $value=$packagetab{$key};
 6456:     my $unikey;
 6457:     $unikey='parameter_0_'.$name;
 6458:     $metaentry{':'.$unikey.'.part'}=0;
 6459:     $$metathesekeys{$unikey}=1;
 6460:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6461: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6462:     }
 6463:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6464: 	$metaentry{':'.$unikey}=
 6465: 	    $metaentry{':'.$unikey.'.default'};
 6466:     }
 6467: }
 6468: 
 6469: sub metadata_generate_part0 {
 6470:     my ($metadata,$metacache,$uri) = @_;
 6471:     my %allnames;
 6472:     foreach my $metakey (keys(%$metadata)) {
 6473: 	if ($metakey=~/^parameter\_(.*)/) {
 6474: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6475: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6476: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6477: 	    $allnames{$name}=$part;
 6478: 	  }
 6479: 	}
 6480:     }
 6481:     foreach my $name (keys(%allnames)) {
 6482:       $$metadata{"parameter_0_$name"}=1;
 6483:       my $key=":parameter_0_$name";
 6484:       $$metacache{"$key.part"}='0';
 6485:       $$metacache{"$key.name"}=$name;
 6486:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6487: 					   $allnames{$name}.'_'.$name.
 6488: 					   '.type'};
 6489:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6490: 			     '.display'};
 6491:       my $expr='[Part: '.$allnames{$name}.']';
 6492:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6493:       $$metacache{"$key.display"}=$olddis;
 6494:     }
 6495: }
 6496: 
 6497: # ------------------------------------------------------ Devalidate title cache
 6498: 
 6499: sub devalidate_title_cache {
 6500:     my ($url)=@_;
 6501:     if (!$env{'request.course.id'}) { return; }
 6502:     my $symb=&symbread($url);
 6503:     if (!$symb) { return; }
 6504:     my $key=$env{'request.course.id'}."\0".$symb;
 6505:     &devalidate_cache_new('title',$key);
 6506: }
 6507: 
 6508: # ------------------------------------------------- Get the title of a resource
 6509: 
 6510: sub gettitle {
 6511:     my $urlsymb=shift;
 6512:     my $symb=&symbread($urlsymb);
 6513:     if ($symb) {
 6514: 	my $key=$env{'request.course.id'}."\0".$symb;
 6515: 	my ($result,$cached)=&is_cached_new('title',$key);
 6516: 	if (defined($cached)) { 
 6517: 	    return $result;
 6518: 	}
 6519: 	my ($map,$resid,$url)=&decode_symb($symb);
 6520: 	my $title='';
 6521: 	my %bighash;
 6522: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6523: 		&GDBM_READER(),0640)) {
 6524: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6525: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6526: 	    untie %bighash;
 6527: 	}
 6528: 	$title=~s/\&colon\;/\:/gs;
 6529: 	if ($title) {
 6530: 	    return &do_cache_new('title',$key,$title,600);
 6531: 	}
 6532: 	$urlsymb=$url;
 6533:     }
 6534:     my $title=&metadata($urlsymb,'title');
 6535:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6536:     return $title;
 6537: }
 6538: 
 6539: sub get_slot {
 6540:     my ($which,$cnum,$cdom)=@_;
 6541:     if (!$cnum || !$cdom) {
 6542: 	(undef,my $courseid)=&whichuser();
 6543: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6544: 	$cnum=$env{'course.'.$courseid.'.num'};
 6545:     }
 6546:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6547:     my %slotinfo;
 6548:     if (exists($remembered{$key})) {
 6549: 	$slotinfo{$which} = $remembered{$key};
 6550:     } else {
 6551: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6552: 	&Apache::lonhomework::showhash(%slotinfo);
 6553: 	my ($tmp)=keys(%slotinfo);
 6554: 	if ($tmp=~/^error:/) { return (); }
 6555: 	$remembered{$key} = $slotinfo{$which};
 6556:     }
 6557:     if (ref($slotinfo{$which}) eq 'HASH') {
 6558: 	return %{$slotinfo{$which}};
 6559:     }
 6560:     return $slotinfo{$which};
 6561: }
 6562: # ------------------------------------------------- Update symbolic store links
 6563: 
 6564: sub symblist {
 6565:     my ($mapname,%newhash)=@_;
 6566:     $mapname=&deversion(&declutter($mapname));
 6567:     my %hash;
 6568:     if (($env{'request.course.fn'}) && (%newhash)) {
 6569:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6570:                       &GDBM_WRCREAT(),0640)) {
 6571: 	    foreach my $url (keys %newhash) {
 6572: 		next if ($url eq 'last_known'
 6573: 			 && $env{'form.no_update_last_known'});
 6574: 		$hash{declutter($url)}=&encode_symb($mapname,
 6575: 						    $newhash{$url}->[1],
 6576: 						    $newhash{$url}->[0]);
 6577:             }
 6578:             if (untie(%hash)) {
 6579: 		return 'ok';
 6580:             }
 6581:         }
 6582:     }
 6583:     return 'error';
 6584: }
 6585: 
 6586: # --------------------------------------------------------------- Verify a symb
 6587: 
 6588: sub symbverify {
 6589:     my ($symb,$thisurl)=@_;
 6590:     my $thisfn=$thisurl;
 6591:     $thisfn=&declutter($thisfn);
 6592: # direct jump to resource in page or to a sequence - will construct own symbs
 6593:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6594: # check URL part
 6595:     my ($map,$resid,$url)=&decode_symb($symb);
 6596: 
 6597:     unless ($url eq $thisfn) { return 0; }
 6598: 
 6599:     $symb=&symbclean($symb);
 6600:     $thisurl=&deversion($thisurl);
 6601:     $thisfn=&deversion($thisfn);
 6602: 
 6603:     my %bighash;
 6604:     my $okay=0;
 6605: 
 6606:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6607:                             &GDBM_READER(),0640)) {
 6608:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6609:         unless ($ids) { 
 6610:            $ids=$bighash{'ids_/'.$thisurl};
 6611:         }
 6612:         if ($ids) {
 6613: # ------------------------------------------------------------------- Has ID(s)
 6614: 	    foreach my $id (split(/\,/,$ids)) {
 6615: 	       my ($mapid,$resid)=split(/\./,$id);
 6616:                if (
 6617:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6618:    eq $symb) { 
 6619: 		   if (($env{'request.role.adv'}) ||
 6620: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6621: 		       $okay=1; 
 6622: 		   }
 6623: 	       }
 6624: 	   }
 6625:         }
 6626: 	untie(%bighash);
 6627:     }
 6628:     return $okay;
 6629: }
 6630: 
 6631: # --------------------------------------------------------------- Clean-up symb
 6632: 
 6633: sub symbclean {
 6634:     my $symb=shift;
 6635:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6636: # remove version from map
 6637:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6638: 
 6639: # remove version from URL
 6640:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6641: 
 6642: # remove wrapper
 6643: 
 6644:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6645:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6646:     return $symb;
 6647: }
 6648: 
 6649: # ---------------------------------------------- Split symb to find map and url
 6650: 
 6651: sub encode_symb {
 6652:     my ($map,$resid,$url)=@_;
 6653:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6654: }
 6655: 
 6656: sub decode_symb {
 6657:     my $symb=shift;
 6658:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6659:     my ($map,$resid,$url)=split(/___/,$symb);
 6660:     return (&fixversion($map),$resid,&fixversion($url));
 6661: }
 6662: 
 6663: sub fixversion {
 6664:     my $fn=shift;
 6665:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6666:     my %bighash;
 6667:     my $uri=&clutter($fn);
 6668:     my $key=$env{'request.course.id'}.'_'.$uri;
 6669: # is this cached?
 6670:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6671:     if (defined($cached)) { return $result; }
 6672: # unfortunately not cached, or expired
 6673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6674: 	    &GDBM_READER(),0640)) {
 6675:  	if ($bighash{'version_'.$uri}) {
 6676:  	    my $version=$bighash{'version_'.$uri};
 6677:  	    unless (($version eq 'mostrecent') || 
 6678: 		    ($version==&getversion($uri))) {
 6679:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6680:  	    }
 6681:  	}
 6682:  	untie %bighash;
 6683:     }
 6684:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6685: }
 6686: 
 6687: sub deversion {
 6688:     my $url=shift;
 6689:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6690:     return $url;
 6691: }
 6692: 
 6693: # ------------------------------------------------------ Return symb list entry
 6694: 
 6695: sub symbread {
 6696:     my ($thisfn,$donotrecurse)=@_;
 6697:     my $cache_str='request.symbread.cached.'.$thisfn;
 6698:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6699: # no filename provided? try from environment
 6700:     unless ($thisfn) {
 6701:         if ($env{'request.symb'}) {
 6702: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6703: 	}
 6704: 	$thisfn=$env{'request.filename'};
 6705:     }
 6706:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6707: # is that filename actually a symb? Verify, clean, and return
 6708:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6709: 	if (&symbverify($thisfn,$1)) {
 6710: 	    return $env{$cache_str}=&symbclean($thisfn);
 6711: 	}
 6712:     }
 6713:     $thisfn=declutter($thisfn);
 6714:     my %hash;
 6715:     my %bighash;
 6716:     my $syval='';
 6717:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6718:         my $targetfn = $thisfn;
 6719:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6720:             $targetfn = 'adm/wrapper/'.$thisfn;
 6721:         }
 6722: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6723: 	    $targetfn=$1;
 6724: 	}
 6725:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6726:                       &GDBM_READER(),0640)) {
 6727: 	    $syval=$hash{$targetfn};
 6728:             untie(%hash);
 6729:         }
 6730: # ---------------------------------------------------------- There was an entry
 6731:         if ($syval) {
 6732: 	    #unless ($syval=~/\_\d+$/) {
 6733: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6734: 		    #&appenv('request.ambiguous' => $thisfn);
 6735: 		    #return $env{$cache_str}='';
 6736: 		#}    
 6737: 		#$syval.=$1;
 6738: 	    #}
 6739:         } else {
 6740: # ------------------------------------------------------- Was not in symb table
 6741:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6742:                             &GDBM_READER(),0640)) {
 6743: # ---------------------------------------------- Get ID(s) for current resource
 6744:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6745:               unless ($ids) { 
 6746:                  $ids=$bighash{'ids_/'.$thisfn};
 6747:               }
 6748:               unless ($ids) {
 6749: # alias?
 6750: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6751:               }
 6752:               if ($ids) {
 6753: # ------------------------------------------------------------------- Has ID(s)
 6754:                  my @possibilities=split(/\,/,$ids);
 6755:                  if ($#possibilities==0) {
 6756: # ----------------------------------------------- There is only one possibility
 6757: 		     my ($mapid,$resid)=split(/\./,$ids);
 6758: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6759: 						    $resid,$thisfn);
 6760:                  } elsif (!$donotrecurse) {
 6761: # ------------------------------------------ There is more than one possibility
 6762:                      my $realpossible=0;
 6763:                      foreach my $id (@possibilities) {
 6764: 			 my $file=$bighash{'src_'.$id};
 6765:                          if (&allowed('bre',$file)) {
 6766:          		    my ($mapid,$resid)=split(/\./,$id);
 6767:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6768: 				$realpossible++;
 6769:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6770: 						    $resid,$thisfn);
 6771:                             }
 6772: 			 }
 6773:                      }
 6774: 		     if ($realpossible!=1) { $syval=''; }
 6775:                  } else {
 6776:                      $syval='';
 6777:                  }
 6778: 	      }
 6779:               untie(%bighash)
 6780:            }
 6781:         }
 6782:         if ($syval) {
 6783: 	    return $env{$cache_str}=$syval;
 6784:         }
 6785:     }
 6786:     &appenv('request.ambiguous' => $thisfn);
 6787:     return $env{$cache_str}='';
 6788: }
 6789: 
 6790: # ---------------------------------------------------------- Return random seed
 6791: 
 6792: sub numval {
 6793:     my $txt=shift;
 6794:     $txt=~tr/A-J/0-9/;
 6795:     $txt=~tr/a-j/0-9/;
 6796:     $txt=~tr/K-T/0-9/;
 6797:     $txt=~tr/k-t/0-9/;
 6798:     $txt=~tr/U-Z/0-5/;
 6799:     $txt=~tr/u-z/0-5/;
 6800:     $txt=~s/\D//g;
 6801:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6802:     return int($txt);
 6803: }
 6804: 
 6805: sub numval2 {
 6806:     my $txt=shift;
 6807:     $txt=~tr/A-J/0-9/;
 6808:     $txt=~tr/a-j/0-9/;
 6809:     $txt=~tr/K-T/0-9/;
 6810:     $txt=~tr/k-t/0-9/;
 6811:     $txt=~tr/U-Z/0-5/;
 6812:     $txt=~tr/u-z/0-5/;
 6813:     $txt=~s/\D//g;
 6814:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6815:     my $total;
 6816:     foreach my $val (@txts) { $total+=$val; }
 6817:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6818:     return int($total);
 6819: }
 6820: 
 6821: sub numval3 {
 6822:     use integer;
 6823:     my $txt=shift;
 6824:     $txt=~tr/A-J/0-9/;
 6825:     $txt=~tr/a-j/0-9/;
 6826:     $txt=~tr/K-T/0-9/;
 6827:     $txt=~tr/k-t/0-9/;
 6828:     $txt=~tr/U-Z/0-5/;
 6829:     $txt=~tr/u-z/0-5/;
 6830:     $txt=~s/\D//g;
 6831:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6832:     my $total;
 6833:     foreach my $val (@txts) { $total+=$val; }
 6834:     if ($_64bit) { $total=(($total<<32)>>32); }
 6835:     return $total;
 6836: }
 6837: 
 6838: sub digest {
 6839:     my ($data)=@_;
 6840:     my $digest=&Digest::MD5::md5($data);
 6841:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6842:     my ($e,$f);
 6843:     {
 6844:         use integer;
 6845:         $e=($a+$b);
 6846:         $f=($c+$d);
 6847:         if ($_64bit) {
 6848:             $e=(($e<<32)>>32);
 6849:             $f=(($f<<32)>>32);
 6850:         }
 6851:     }
 6852:     if (wantarray) {
 6853: 	return ($e,$f);
 6854:     } else {
 6855: 	my $g;
 6856: 	{
 6857: 	    use integer;
 6858: 	    $g=($e+$f);
 6859: 	    if ($_64bit) {
 6860: 		$g=(($g<<32)>>32);
 6861: 	    }
 6862: 	}
 6863: 	return $g;
 6864:     }
 6865: }
 6866: 
 6867: sub latest_rnd_algorithm_id {
 6868:     return '64bit5';
 6869: }
 6870: 
 6871: sub get_rand_alg {
 6872:     my ($courseid)=@_;
 6873:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6874:     if ($courseid) {
 6875: 	return $env{"course.$courseid.rndseed"};
 6876:     }
 6877:     return &latest_rnd_algorithm_id();
 6878: }
 6879: 
 6880: sub validCODE {
 6881:     my ($CODE)=@_;
 6882:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6883:     return 0;
 6884: }
 6885: 
 6886: sub getCODE {
 6887:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6888:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6889: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6890: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6891: 	return $Apache::lonhomework::history{'resource.CODE'};
 6892:     }
 6893:     return undef;
 6894: }
 6895: 
 6896: sub rndseed {
 6897:     my ($symb,$courseid,$domain,$username)=@_;
 6898: 
 6899:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6900:     if (!$symb) {
 6901: 	unless ($symb=$wsymb) { return time; }
 6902:     }
 6903:     if (!$courseid) { $courseid=$wcourseid; }
 6904:     if (!$domain) { $domain=$wdomain; }
 6905:     if (!$username) { $username=$wusername }
 6906:     my $which=&get_rand_alg();
 6907: 
 6908:     if (defined(&getCODE())) {
 6909: 	if ($which eq '64bit5') {
 6910: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6911: 	} elsif ($which eq '64bit4') {
 6912: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6913: 	} else {
 6914: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6915: 	}
 6916:     } elsif ($which eq '64bit5') {
 6917: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6918:     } elsif ($which eq '64bit4') {
 6919: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6920:     } elsif ($which eq '64bit3') {
 6921: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6922:     } elsif ($which eq '64bit2') {
 6923: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6924:     } elsif ($which eq '64bit') {
 6925: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6926:     }
 6927:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6928: }
 6929: 
 6930: sub rndseed_32bit {
 6931:     my ($symb,$courseid,$domain,$username)=@_;
 6932:     {
 6933: 	use integer;
 6934: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6935: 	my $symbseed=numval($symb) << 22;
 6936: 	my $namechck=unpack("%32C*",$username) << 17;
 6937: 	my $nameseed=numval($username) << 12;
 6938: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6939: 	my $courseseed=unpack("%32C*",$courseid);
 6940: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6941: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6942: 	#&logthis("rndseed :$num:$symb");
 6943: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6944: 	return $num;
 6945:     }
 6946: }
 6947: 
 6948: sub rndseed_64bit {
 6949:     my ($symb,$courseid,$domain,$username)=@_;
 6950:     {
 6951: 	use integer;
 6952: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6953: 	my $symbseed=numval($symb) << 10;
 6954: 	my $namechck=unpack("%32S*",$username);
 6955: 	
 6956: 	my $nameseed=numval($username) << 21;
 6957: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6958: 	my $courseseed=unpack("%32S*",$courseid);
 6959: 	
 6960: 	my $num1=$symbchck+$symbseed+$namechck;
 6961: 	my $num2=$nameseed+$domainseed+$courseseed;
 6962: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6963: 	#&logthis("rndseed :$num:$symb");
 6964: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6965: 	return "$num1,$num2";
 6966:     }
 6967: }
 6968: 
 6969: sub rndseed_64bit2 {
 6970:     my ($symb,$courseid,$domain,$username)=@_;
 6971:     {
 6972: 	use integer;
 6973: 	# strings need to be an even # of cahracters long, it it is odd the
 6974:         # last characters gets thrown away
 6975: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6976: 	my $symbseed=numval($symb) << 10;
 6977: 	my $namechck=unpack("%32S*",$username.' ');
 6978: 	
 6979: 	my $nameseed=numval($username) << 21;
 6980: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6981: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6982: 	
 6983: 	my $num1=$symbchck+$symbseed+$namechck;
 6984: 	my $num2=$nameseed+$domainseed+$courseseed;
 6985: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6986: 	#&logthis("rndseed :$num:$symb");
 6987: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6988: 	return "$num1,$num2";
 6989:     }
 6990: }
 6991: 
 6992: sub rndseed_64bit3 {
 6993:     my ($symb,$courseid,$domain,$username)=@_;
 6994:     {
 6995: 	use integer;
 6996: 	# strings need to be an even # of cahracters long, it it is odd the
 6997:         # last characters gets thrown away
 6998: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6999: 	my $symbseed=numval2($symb) << 10;
 7000: 	my $namechck=unpack("%32S*",$username.' ');
 7001: 	
 7002: 	my $nameseed=numval2($username) << 21;
 7003: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7004: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7005: 	
 7006: 	my $num1=$symbchck+$symbseed+$namechck;
 7007: 	my $num2=$nameseed+$domainseed+$courseseed;
 7008: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7009: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7010: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7011: 	
 7012: 	return "$num1:$num2";
 7013:     }
 7014: }
 7015: 
 7016: sub rndseed_64bit4 {
 7017:     my ($symb,$courseid,$domain,$username)=@_;
 7018:     {
 7019: 	use integer;
 7020: 	# strings need to be an even # of cahracters long, it it is odd the
 7021:         # last characters gets thrown away
 7022: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7023: 	my $symbseed=numval3($symb) << 10;
 7024: 	my $namechck=unpack("%32S*",$username.' ');
 7025: 	
 7026: 	my $nameseed=numval3($username) << 21;
 7027: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7028: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7029: 	
 7030: 	my $num1=$symbchck+$symbseed+$namechck;
 7031: 	my $num2=$nameseed+$domainseed+$courseseed;
 7032: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7033: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7034: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7035: 	
 7036: 	return "$num1:$num2";
 7037:     }
 7038: }
 7039: 
 7040: sub rndseed_64bit5 {
 7041:     my ($symb,$courseid,$domain,$username)=@_;
 7042:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7043:     return "$num1:$num2";
 7044: }
 7045: 
 7046: sub rndseed_CODE_64bit {
 7047:     my ($symb,$courseid,$domain,$username)=@_;
 7048:     {
 7049: 	use integer;
 7050: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7051: 	my $symbseed=numval2($symb);
 7052: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7053: 	my $CODEseed=numval(&getCODE());
 7054: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7055: 	my $num1=$symbseed+$CODEchck;
 7056: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7057: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7058: 	#&logthis("rndseed :$num1:$num2:$symb");
 7059: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7060: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7061: 	return "$num1:$num2";
 7062:     }
 7063: }
 7064: 
 7065: sub rndseed_CODE_64bit4 {
 7066:     my ($symb,$courseid,$domain,$username)=@_;
 7067:     {
 7068: 	use integer;
 7069: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7070: 	my $symbseed=numval3($symb);
 7071: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7072: 	my $CODEseed=numval3(&getCODE());
 7073: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7074: 	my $num1=$symbseed+$CODEchck;
 7075: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7076: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7077: 	#&logthis("rndseed :$num1:$num2:$symb");
 7078: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7079: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7080: 	return "$num1:$num2";
 7081:     }
 7082: }
 7083: 
 7084: sub rndseed_CODE_64bit5 {
 7085:     my ($symb,$courseid,$domain,$username)=@_;
 7086:     my $code = &getCODE();
 7087:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7088:     return "$num1:$num2";
 7089: }
 7090: 
 7091: sub setup_random_from_rndseed {
 7092:     my ($rndseed)=@_;
 7093:     if ($rndseed =~/([,:])/) {
 7094: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7095: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7096:     } else {
 7097: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7098:     }
 7099: }
 7100: 
 7101: sub latest_receipt_algorithm_id {
 7102:     return 'receipt3';
 7103: }
 7104: 
 7105: sub recunique {
 7106:     my $fucourseid=shift;
 7107:     my $unique;
 7108:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7109: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7110: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7111:     } else {
 7112: 	$unique=$perlvar{'lonReceipt'};
 7113:     }
 7114:     return unpack("%32C*",$unique);
 7115: }
 7116: 
 7117: sub recprefix {
 7118:     my $fucourseid=shift;
 7119:     my $prefix;
 7120:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7121: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7122: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7123:     } else {
 7124: 	$prefix=$perlvar{'lonHostID'};
 7125:     }
 7126:     return unpack("%32C*",$prefix);
 7127: }
 7128: 
 7129: sub ireceipt {
 7130:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7131: 
 7132:     my $return =&recprefix($fucourseid).'-';
 7133: 
 7134:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7135: 	$env{'request.state'} eq 'construct') {
 7136: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7137: 	return $return;
 7138:     }
 7139: 
 7140:     my $cuname=unpack("%32C*",$funame);
 7141:     my $cudom=unpack("%32C*",$fudom);
 7142:     my $cucourseid=unpack("%32C*",$fucourseid);
 7143:     my $cusymb=unpack("%32C*",$fusymb);
 7144:     my $cunique=&recunique($fucourseid);
 7145:     my $cpart=unpack("%32S*",$part);
 7146:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7147: 
 7148: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7149: 			       
 7150: 	$return.= ($cunique%$cuname+
 7151: 		   $cunique%$cudom+
 7152: 		   $cusymb%$cuname+
 7153: 		   $cusymb%$cudom+
 7154: 		   $cucourseid%$cuname+
 7155: 		   $cucourseid%$cudom+
 7156: 		   $cpart%$cuname+
 7157: 		   $cpart%$cudom);
 7158:     } else {
 7159: 	$return.= ($cunique%$cuname+
 7160: 		   $cunique%$cudom+
 7161: 		   $cusymb%$cuname+
 7162: 		   $cusymb%$cudom+
 7163: 		   $cucourseid%$cuname+
 7164: 		   $cucourseid%$cudom);
 7165:     }
 7166:     return $return;
 7167: }
 7168: 
 7169: sub receipt {
 7170:     my ($part)=@_;
 7171:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7172:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7173: }
 7174: 
 7175: sub whichuser {
 7176:     my ($passedsymb)=@_;
 7177:     my ($symb,$courseid,$domain,$name,$publicuser);
 7178:     if (defined($env{'form.grade_symb'})) {
 7179: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7180: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7181: 	if (!$allowed &&
 7182: 	    exists($env{'request.course.sec'}) &&
 7183: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7184: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7185: 			      '/'.$env{'request.course.sec'});
 7186: 	}
 7187: 	if ($allowed) {
 7188: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7189: 	    $courseid=$tmp_courseid;
 7190: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7191: 	    ($name)=&get_env_multiple('form.grade_username');
 7192: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7193: 	}
 7194:     }
 7195:     if (!$passedsymb) {
 7196: 	$symb=&symbread();
 7197:     } else {
 7198: 	$symb=$passedsymb;
 7199:     }
 7200:     $courseid=$env{'request.course.id'};
 7201:     $domain=$env{'user.domain'};
 7202:     $name=$env{'user.name'};
 7203:     if ($name eq 'public' && $domain eq 'public') {
 7204: 	if (!defined($env{'form.username'})) {
 7205: 	    $env{'form.username'}.=time.rand(10000000);
 7206: 	}
 7207: 	$name.=$env{'form.username'};
 7208:     }
 7209:     return ($symb,$courseid,$domain,$name,$publicuser);
 7210: 
 7211: }
 7212: 
 7213: # ------------------------------------------------------------ Serves up a file
 7214: # returns either the contents of the file or 
 7215: # -1 if the file doesn't exist
 7216: #
 7217: # if the target is a file that was uploaded via DOCS, 
 7218: # a check will be made to see if a current copy exists on the local server,
 7219: # if it does this will be served, otherwise a copy will be retrieved from
 7220: # the home server for the course and stored in /home/httpd/html/userfiles on
 7221: # the local server.   
 7222: 
 7223: sub getfile {
 7224:     my ($file) = @_;
 7225:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7226:     &repcopy($file);
 7227:     return &readfile($file);
 7228: }
 7229: 
 7230: sub repcopy_userfile {
 7231:     my ($file)=@_;
 7232:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7233:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7234:     my ($cdom,$cnum,$filename) = 
 7235: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7236:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7237:     if (-e "$file") {
 7238: # we already have a local copy, check it out
 7239: 	my @fileinfo = stat($file);
 7240: 	my $rtncode;
 7241: 	my $info;
 7242: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7243: 	if ($lwpresp ne 'ok') {
 7244: # there is no such file anymore, even though we had a local copy
 7245: 	    if ($rtncode eq '404') {
 7246: 		unlink($file);
 7247: 	    }
 7248: 	    return -1;
 7249: 	}
 7250: 	if ($info < $fileinfo[9]) {
 7251: # nice, the file we have is up-to-date, just say okay
 7252: 	    return 'ok';
 7253: 	} else {
 7254: # the file is outdated, get rid of it
 7255: 	    unlink($file);
 7256: 	}
 7257:     }
 7258: # one way or the other, at this point, we don't have the file
 7259: # construct the correct path for the file
 7260:     my @parts = ($cdom,$cnum); 
 7261:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7262: 	push @parts, split(/\//,$1);
 7263:     }
 7264:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7265:     foreach my $part (@parts) {
 7266: 	$path .= '/'.$part;
 7267: 	if (!-e $path) {
 7268: 	    mkdir($path,0770);
 7269: 	}
 7270:     }
 7271: # now the path exists for sure
 7272: # get a user agent
 7273:     my $ua=new LWP::UserAgent;
 7274:     my $transferfile=$file.'.in.transfer';
 7275: # FIXME: this should flock
 7276:     if (-e $transferfile) { return 'ok'; }
 7277:     my $request;
 7278:     $uri=~s/^\///;
 7279:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7280:     my $response=$ua->request($request,$transferfile);
 7281: # did it work?
 7282:     if ($response->is_error()) {
 7283: 	unlink($transferfile);
 7284: 	&logthis("Userfile repcopy failed for $uri");
 7285: 	return -1;
 7286:     }
 7287: # worked, rename the transfer file
 7288:     rename($transferfile,$file);
 7289:     return 'ok';
 7290: }
 7291: 
 7292: sub tokenwrapper {
 7293:     my $uri=shift;
 7294:     $uri=~s|^http\://([^/]+)||;
 7295:     $uri=~s|^/||;
 7296:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7297:     my $token=$1;
 7298:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7299:     if ($udom && $uname && $file) {
 7300: 	$file=~s|(\?\.*)*$||;
 7301:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7302:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7303:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7304:                                '&tokenissued='.$perlvar{'lonHostID'};
 7305:     } else {
 7306:         return '/adm/notfound.html';
 7307:     }
 7308: }
 7309: 
 7310: # call with reqtype HEAD: get last modification time
 7311: # call with reqtype GET: get the file contents
 7312: # Do not call this with reqtype GET for large files! It loads everything into memory
 7313: #
 7314: sub getuploaded {
 7315:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7316:     $uri=~s/^\///;
 7317:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7318:     my $ua=new LWP::UserAgent;
 7319:     my $request=new HTTP::Request($reqtype,$uri);
 7320:     my $response=$ua->request($request);
 7321:     $$rtncode = $response->code;
 7322:     if (! $response->is_success()) {
 7323: 	return 'failed';
 7324:     }      
 7325:     if ($reqtype eq 'HEAD') {
 7326: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7327:     } elsif ($reqtype eq 'GET') {
 7328: 	$$info = $response->content;
 7329:     }
 7330:     return 'ok';
 7331: }
 7332: 
 7333: sub readfile {
 7334:     my $file = shift;
 7335:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7336:     my $fh;
 7337:     open($fh,"<$file");
 7338:     my $a='';
 7339:     while (my $line = <$fh>) { $a .= $line; }
 7340:     return $a;
 7341: }
 7342: 
 7343: sub filelocation {
 7344:     my ($dir,$file) = @_;
 7345:     my $location;
 7346:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7347: 
 7348:     if ($file =~ m-^/adm/-) {
 7349: 	$file=~s-^/adm/wrapper/-/-;
 7350: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7351:     }
 7352:     if ($file=~m:^/~:) { # is a contruction space reference
 7353:         $location = $file;
 7354:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7355:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7356: 	# is a correct contruction space reference
 7357:         $location = $file;
 7358:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7359:         my ($udom,$uname,$filename)=
 7360:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7361:         my $home=&homeserver($uname,$udom);
 7362:         my $is_me=0;
 7363:         my @ids=&current_machine_ids();
 7364:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7365:         if ($is_me) {
 7366:   	    $location=&propath($udom,$uname).
 7367:   	      '/userfiles/'.$filename;
 7368:         } else {
 7369:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7370:   	      $udom.'/'.$uname.'/'.$filename;
 7371:         }
 7372:     } else {
 7373:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7374:         $file=~s:^/res/:/:;
 7375:         if ( !( $file =~ m:^/:) ) {
 7376:             $location = $dir. '/'.$file;
 7377:         } else {
 7378:             $location = '/home/httpd/html/res'.$file;
 7379:         }
 7380:     }
 7381:     $location=~s://+:/:g; # remove duplicate /
 7382:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7383:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7384:     return $location;
 7385: }
 7386: 
 7387: sub hreflocation {
 7388:     my ($dir,$file)=@_;
 7389:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7390: 	$file=filelocation($dir,$file);
 7391:     } elsif ($file=~m-^/adm/-) {
 7392: 	$file=~s-^/adm/wrapper/-/-;
 7393: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7394:     }
 7395:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7396: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7397:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7398: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7399:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7400: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7401: 	    -/uploaded/$1/$2/-x;
 7402:     }
 7403:     return $file;
 7404: }
 7405: 
 7406: sub current_machine_domains {
 7407:     my $hostname=&hostname($perlvar{'lonHostID'});
 7408:     my @domains;
 7409:     my %hostname = &all_hostnames();
 7410:     while( my($id, $name) = each(%hostname)) {
 7411: #	&logthis("-$id-$name-$hostname-");
 7412: 	if ($hostname eq $name) {
 7413: 	    push(@domains,&host_domain($id));
 7414: 	}
 7415:     }
 7416:     return @domains;
 7417: }
 7418: 
 7419: sub current_machine_ids {
 7420:     my $hostname=&hostname($perlvar{'lonHostID'});
 7421:     my @ids;
 7422:     my %hostname = &all_hostnames();
 7423:     while( my($id, $name) = each(%hostname)) {
 7424: #	&logthis("-$id-$name-$hostname-");
 7425: 	if ($hostname eq $name) {
 7426: 	    push(@ids,$id);
 7427: 	}
 7428:     }
 7429:     return @ids;
 7430: }
 7431: 
 7432: sub additional_machine_domains {
 7433:     my @domains;
 7434:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7435:     while( my $line = <$fh>) {
 7436:         $line =~ s/\s//g;
 7437:         push(@domains,$line);
 7438:     }
 7439:     return @domains;
 7440: }
 7441: 
 7442: sub default_login_domain {
 7443:     my $domain = $perlvar{'lonDefDomain'};
 7444:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7445:     foreach my $posdom (&current_machine_domains(),
 7446:                         &additional_machine_domains()) {
 7447:         if (lc($posdom) eq lc($testdomain)) {
 7448:             $domain=$posdom;
 7449:             last;
 7450:         }
 7451:     }
 7452:     return $domain;
 7453: }
 7454: 
 7455: # ------------------------------------------------------------- Declutters URLs
 7456: 
 7457: sub declutter {
 7458:     my $thisfn=shift;
 7459:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7460:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7461:     $thisfn=~s/^\///;
 7462:     $thisfn=~s|^adm/wrapper/||;
 7463:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7464:     $thisfn=~s/^res\///;
 7465:     $thisfn=~s/\?.+$//;
 7466:     return $thisfn;
 7467: }
 7468: 
 7469: # ------------------------------------------------------------- Clutter up URLs
 7470: 
 7471: sub clutter {
 7472:     my $thisfn='/'.&declutter(shift);
 7473:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7474:        $thisfn='/res'.$thisfn; 
 7475:     }
 7476:     if ($thisfn !~m|/adm|) {
 7477: 	if ($thisfn =~ m|/ext/|) {
 7478: 	    $thisfn='/adm/wrapper'.$thisfn;
 7479: 	} else {
 7480: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7481: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7482: 	    if ($embstyle eq 'ssi'
 7483: 		|| ($embstyle eq 'hdn')
 7484: 		|| ($embstyle eq 'rat')
 7485: 		|| ($embstyle eq 'prv')
 7486: 		|| ($embstyle eq 'ign')) {
 7487: 		#do nothing with these
 7488: 	    } elsif (($embstyle eq 'img') 
 7489: 		|| ($embstyle eq 'emb')
 7490: 		|| ($embstyle eq 'wrp')) {
 7491: 		$thisfn='/adm/wrapper'.$thisfn;
 7492: 	    } elsif ($embstyle eq 'unk'
 7493: 		     && $thisfn!~/\.(sequence|page)$/) {
 7494: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7495: 	    } else {
 7496: #		&logthis("Got a blank emb style");
 7497: 	    }
 7498: 	}
 7499:     }
 7500:     return $thisfn;
 7501: }
 7502: 
 7503: sub clutter_with_no_wrapper {
 7504:     my $uri = &clutter(shift);
 7505:     if ($uri =~ m-^/adm/-) {
 7506: 	$uri =~ s-^/adm/wrapper/-/-;
 7507: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7508:     }
 7509:     return $uri;
 7510: }
 7511: 
 7512: sub freeze_escape {
 7513:     my ($value)=@_;
 7514:     if (ref($value)) {
 7515: 	$value=&nfreeze($value);
 7516: 	return '__FROZEN__'.&escape($value);
 7517:     }
 7518:     return &escape($value);
 7519: }
 7520: 
 7521: 
 7522: sub thaw_unescape {
 7523:     my ($value)=@_;
 7524:     if ($value =~ /^__FROZEN__/) {
 7525: 	substr($value,0,10,undef);
 7526: 	$value=&unescape($value);
 7527: 	return &thaw($value);
 7528:     }
 7529:     return &unescape($value);
 7530: }
 7531: 
 7532: sub correct_line_ends {
 7533:     my ($result)=@_;
 7534:     $$result =~s/\r\n/\n/mg;
 7535:     $$result =~s/\r/\n/mg;
 7536: }
 7537: # ================================================================ Main Program
 7538: 
 7539: sub goodbye {
 7540:    &logthis("Starting Shut down");
 7541: #not converted to using infrastruture and probably shouldn't be
 7542:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7543: #converted
 7544: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7545:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7546: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7547: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7548: #1.1 only
 7549: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7550: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7551: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7552: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7553:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7554:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7555:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7556:    &flushcourselogs();
 7557:    &logthis("Shutting down");
 7558: }
 7559: 
 7560: BEGIN {
 7561: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7562:     unless ($readit) {
 7563: {
 7564:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7565:     %perlvar = (%perlvar,%{$configvars});
 7566: }
 7567: 
 7568: # ------------------------------------------------------------ Read domain file
 7569: {
 7570:     %domaindescription = ();
 7571:     %domain_auth_def = ();
 7572:     %domain_auth_arg_def = ();
 7573:     my $fh;
 7574:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7575: 	while (my $line = <$fh>) {
 7576:            next if ($line =~ /^(\#|\s*$)/);
 7577: #           next if /^\#/;
 7578:            chomp $line;
 7579:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7580: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
 7581: 	   $domain_auth_def{$domain}=$def_auth;
 7582:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7583: 	   $domaindescription{$domain}=$domain_description;
 7584: 	   $domain_lang_def{$domain}=$def_lang;
 7585: 	   $domain_city{$domain}=$city;
 7586: 	   $domain_longi{$domain}=$longi;
 7587: 	   $domain_lati{$domain}=$lati;
 7588:            $domain_primary{$domain}=$primary;
 7589: 
 7590:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7591: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7592: 	}
 7593:     }
 7594:     close ($fh);
 7595: }
 7596: 
 7597: 
 7598: # ------------------------------------------------------------- Read hosts file
 7599: {
 7600:     my %hostname;
 7601:     my %hostdom;
 7602:     my %libserv;
 7603:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7604: 
 7605:     while (my $configline=<$config>) {
 7606:        next if ($configline =~ /^(\#|\s*$)/);
 7607:        chomp($configline);
 7608:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7609:        $name=~s/\s//g;
 7610:        if ($id && $domain && $role && $name) {
 7611: 	 $hostname{$id}=$name;
 7612: 	 $hostdom{$id}=$domain;
 7613: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7614:        }
 7615:     }
 7616:     close($config);
 7617:     # FIXME: dev server don't want this, production servers _do_ want this
 7618:     #&get_iphost();
 7619: 
 7620:     sub hostname {
 7621: 	my ($lonid) = @_;
 7622: 	return $hostname{$lonid};
 7623:     }
 7624: 
 7625:     sub all_hostnames {
 7626: 	return %hostname;
 7627:     }
 7628: 
 7629:     sub is_library {
 7630: 	return exists($libserv{$_[0]});
 7631:     }
 7632: 
 7633:     sub all_library {
 7634: 	return %libserv;
 7635:     }
 7636: 
 7637:     sub get_servers {
 7638: 	my ($domain,$type) = @_;
 7639: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7640: 	                                          : %hostname;
 7641: 	my %result;
 7642: 	if (ref($domain) eq 'ARRAY') {
 7643: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7644: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7645: 		    $result{$host} = $hostname;
 7646: 		}
 7647: 	    }
 7648: 	} else {
 7649: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7650: 		if ($hostdom{$host} eq $domain) {
 7651: 		    $result{$host} = $hostname;
 7652: 		}
 7653: 	    }
 7654: 	}
 7655: 	return %result;
 7656:     }
 7657: 
 7658:     sub host_domain {
 7659: 	my ($lonid) = @_;
 7660: 	return $hostdom{$lonid};
 7661:     }
 7662: 
 7663:     sub all_domains {
 7664: 	my %seen;
 7665: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7666: 	return @uniq;
 7667:     }
 7668: }
 7669: 
 7670: sub get_hosts_from_ip {
 7671:     my ($ip) = @_;
 7672:     my %iphosts = &get_iphost();
 7673:     if (ref($iphosts{$ip})) {
 7674: 	return @{$iphosts{$ip}};
 7675:     }
 7676:     return;
 7677: }
 7678: 
 7679: sub get_iphost {
 7680:     if (%iphost) { return %iphost; }
 7681:     my %name_to_ip;
 7682:     my %hostname = &all_hostnames();
 7683:     foreach my $id (keys(%hostname)) {
 7684: 	my $name=$hostname{$id};
 7685: 	my $ip;
 7686: 	if (!exists($name_to_ip{$name})) {
 7687: 	    $ip = gethostbyname($name);
 7688: 	    if (!$ip || length($ip) ne 4) {
 7689: 		&logthis("Skipping host $id name $name no IP found");
 7690: 		next;
 7691: 	    }
 7692: 	    $ip=inet_ntoa($ip);
 7693: 	    $name_to_ip{$name} = $ip;
 7694: 	} else {
 7695: 	    $ip = $name_to_ip{$name};
 7696: 	}
 7697: 	push(@{$iphost{$ip}},$id);
 7698:     }
 7699:     return %iphost;
 7700: }
 7701: 
 7702: # ------------------------------------------------------ Read spare server file
 7703: {
 7704:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7705: 
 7706:     while (my $configline=<$config>) {
 7707:        chomp($configline);
 7708:        if ($configline) {
 7709: 	   my ($host,$type) = split(':',$configline,2);
 7710: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7711: 	   push(@{ $spareid{$type} }, $host);
 7712:        }
 7713:     }
 7714:     close($config);
 7715: }
 7716: # ------------------------------------------------------------ Read permissions
 7717: {
 7718:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7719: 
 7720:     while (my $configline=<$config>) {
 7721: 	chomp($configline);
 7722: 	if ($configline) {
 7723: 	    my ($role,$perm)=split(/ /,$configline);
 7724: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7725: 	}
 7726:     }
 7727:     close($config);
 7728: }
 7729: 
 7730: # -------------------------------------------- Read plain texts for permissions
 7731: {
 7732:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7733: 
 7734:     while (my $configline=<$config>) {
 7735: 	chomp($configline);
 7736: 	if ($configline) {
 7737: 	    my ($short,@plain)=split(/:/,$configline);
 7738:             %{$prp{$short}} = ();
 7739: 	    if (@plain > 0) {
 7740:                 $prp{$short}{'std'} = $plain[0];
 7741:                 for (my $i=1; $i<@plain; $i++) {
 7742:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7743:                 }
 7744:             }
 7745: 	}
 7746:     }
 7747:     close($config);
 7748: }
 7749: 
 7750: # ---------------------------------------------------------- Read package table
 7751: {
 7752:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7753: 
 7754:     while (my $configline=<$config>) {
 7755: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7756: 	chomp($configline);
 7757: 	my ($short,$plain)=split(/:/,$configline);
 7758: 	my ($pack,$name)=split(/\&/,$short);
 7759: 	if ($plain ne '') {
 7760: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7761: 	    $packagetab{$short}=$plain; 
 7762: 	}
 7763:     }
 7764:     close($config);
 7765: }
 7766: 
 7767: # ------------- set up temporary directory
 7768: {
 7769:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7770: 
 7771: }
 7772: 
 7773: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7774: 				'compress_threshold'=> 20_000,
 7775:  			        });
 7776: 
 7777: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7778: $dumpcount=0;
 7779: 
 7780: &logtouch();
 7781: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7782: $readit=1;
 7783:     {
 7784: 	use integer;
 7785: 	my $test=(2**32)+1;
 7786: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7787: 	&logthis(" Detected 64bit platform ($_64bit)");
 7788:     }
 7789: }
 7790: }
 7791: 
 7792: 1;
 7793: __END__
 7794: 
 7795: =pod
 7796: 
 7797: =head1 NAME
 7798: 
 7799: Apache::lonnet - Subroutines to ask questions about things in the network.
 7800: 
 7801: =head1 SYNOPSIS
 7802: 
 7803: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7804: 
 7805:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7806: 
 7807: Common parameters:
 7808: 
 7809: =over 4
 7810: 
 7811: =item *
 7812: 
 7813: $uname : an internal username (if $cname expecting a course Id specifically)
 7814: 
 7815: =item *
 7816: 
 7817: $udom : a domain (if $cdom expecting a course's domain specifically)
 7818: 
 7819: =item *
 7820: 
 7821: $symb : a resource instance identifier
 7822: 
 7823: =item *
 7824: 
 7825: $namespace : the name of a .db file that contains the data needed or
 7826: being set.
 7827: 
 7828: =back
 7829: 
 7830: =head1 OVERVIEW
 7831: 
 7832: lonnet provides subroutines which interact with the
 7833: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7834: about classes, users, and resources.
 7835: 
 7836: For many of these objects you can also use this to store data about
 7837: them or modify them in various ways.
 7838: 
 7839: =head2 Symbs
 7840: 
 7841: To identify a specific instance of a resource, LON-CAPA uses symbols
 7842: or "symbs"X<symb>. These identifiers are built from the URL of the
 7843: map, the resource number of the resource in the map, and the URL of
 7844: the resource itself. The latter is somewhat redundant, but might help
 7845: if maps change.
 7846: 
 7847: An example is
 7848: 
 7849:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7850: 
 7851: The respective map entry is
 7852: 
 7853:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7854:   title="Problem 2">
 7855:  </resource>
 7856: 
 7857: Symbs are used by the random number generator, as well as to store and
 7858: restore data specific to a certain instance of for example a problem.
 7859: 
 7860: =head2 Storing And Retrieving Data
 7861: 
 7862: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7863: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7864: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7865: is is the non-critical message twin of cstore. These functions are for
 7866: handlers to store a perl hash to a user's permanent data space in an
 7867: easy manner, and to retrieve it again on another call. It is expected
 7868: that a handler would use this once at the beginning to retrieve data,
 7869: and then again once at the end to send only the new data back.
 7870: 
 7871: The data is stored in the user's data directory on the user's
 7872: homeserver under the ID of the course.
 7873: 
 7874: The hash that is returned by restore will have all of the previous
 7875: value for all of the elements of the hash.
 7876: 
 7877: Example:
 7878: 
 7879:  #creating a hash
 7880:  my %hash;
 7881:  $hash{'foo'}='bar';
 7882: 
 7883:  #storing it
 7884:  &Apache::lonnet::cstore(\%hash);
 7885: 
 7886:  #changing a value
 7887:  $hash{'foo'}='notbar';
 7888: 
 7889:  #adding a new value
 7890:  $hash{'bar'}='foo';
 7891:  &Apache::lonnet::cstore(\%hash);
 7892: 
 7893:  #retrieving the hash
 7894:  my %history=&Apache::lonnet::restore();
 7895: 
 7896:  #print the hash
 7897:  foreach my $key (sort(keys(%history))) {
 7898:    print("\%history{$key} = $history{$key}");
 7899:  }
 7900: 
 7901: Will print out:
 7902: 
 7903:  %history{1:foo} = bar
 7904:  %history{1:keys} = foo:timestamp
 7905:  %history{1:timestamp} = 990455579
 7906:  %history{2:bar} = foo
 7907:  %history{2:foo} = notbar
 7908:  %history{2:keys} = foo:bar:timestamp
 7909:  %history{2:timestamp} = 990455580
 7910:  %history{bar} = foo
 7911:  %history{foo} = notbar
 7912:  %history{timestamp} = 990455580
 7913:  %history{version} = 2
 7914: 
 7915: Note that the special hash entries C<keys>, C<version> and
 7916: C<timestamp> were added to the hash. C<version> will be equal to the
 7917: total number of versions of the data that have been stored. The
 7918: C<timestamp> attribute will be the UNIX time the hash was
 7919: stored. C<keys> is available in every historical section to list which
 7920: keys were added or changed at a specific historical revision of a
 7921: hash.
 7922: 
 7923: B<Warning>: do not store the hash that restore returns directly. This
 7924: will cause a mess since it will restore the historical keys as if the
 7925: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7926: 
 7927: Calling convention:
 7928: 
 7929:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7930:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7931: 
 7932: For more detailed information, see lonnet specific documentation.
 7933: 
 7934: =head1 RETURN MESSAGES
 7935: 
 7936: =over 4
 7937: 
 7938: =item * B<con_lost>: unable to contact remote host
 7939: 
 7940: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7941: when the connection is brought back up
 7942: 
 7943: =item * B<con_failed>: unable to contact remote host and unable to save message
 7944: for later delivery
 7945: 
 7946: =item * B<error:>: an error a occured, a description of the error follows the :
 7947: 
 7948: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7949: that was requested
 7950: 
 7951: =back
 7952: 
 7953: =head1 PUBLIC SUBROUTINES
 7954: 
 7955: =head2 Session Environment Functions
 7956: 
 7957: =over 4
 7958: 
 7959: =item * 
 7960: X<appenv()>
 7961: B<appenv(%hash)>: the value of %hash is written to
 7962: the user envirnoment file, and will be restored for each access this
 7963: user makes during this session, also modifies the %env for the current
 7964: process
 7965: 
 7966: =item *
 7967: X<delenv()>
 7968: B<delenv($regexp)>: removes all items from the session
 7969: environment file that matches the regular expression in $regexp. The
 7970: values are also delted from the current processes %env.
 7971: 
 7972: =item * get_env_multiple($name) 
 7973: 
 7974: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7975: values may be defined and end up as an array ref.
 7976: 
 7977: returns an array of values
 7978: 
 7979: =back
 7980: 
 7981: =head2 User Information
 7982: 
 7983: =over 4
 7984: 
 7985: =item *
 7986: X<queryauthenticate()>
 7987: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7988: authentication scheme
 7989: 
 7990: =item *
 7991: X<authenticate()>
 7992: B<authenticate($uname,$upass,$udom)>: try to
 7993: authenticate user from domain's lib servers (first use the current
 7994: one). C<$upass> should be the users password.
 7995: 
 7996: =item *
 7997: X<homeserver()>
 7998: B<homeserver($uname,$udom)>: find the server which has
 7999: the user's directory and files (there must be only one), this caches
 8000: the answer, and also caches if there is a borken connection.
 8001: 
 8002: =item *
 8003: X<idget()>
 8004: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8005: (IDs are a unique resource in a domain, there must be only 1 ID per
 8006: username, and only 1 username per ID in a specific domain) (returns
 8007: hash: id=>name,id=>name)
 8008: 
 8009: =item *
 8010: X<idrget()>
 8011: B<idrget($udom,@unames)>: find the IDs behind a list of
 8012: usernames (returns hash: name=>id,name=>id)
 8013: 
 8014: =item *
 8015: X<idput()>
 8016: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8017: 
 8018: =item *
 8019: X<rolesinit()>
 8020: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8021: 
 8022: =item *
 8023: X<getsection()>
 8024: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8025: course $cname, return section name/number or '' for "not in course"
 8026: and '-1' for "no section"
 8027: 
 8028: =item *
 8029: X<userenvironment()>
 8030: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8031: passed in @what from the requested user's environment, returns a hash
 8032: 
 8033: =back
 8034: 
 8035: =head2 User Roles
 8036: 
 8037: =over 4
 8038: 
 8039: =item *
 8040: 
 8041: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8042:  F: full access
 8043:  U,I,K: authentication modes (cxx only)
 8044:  '': forbidden
 8045:  1: user needs to choose course
 8046:  2: browse allowed
 8047:  A: passphrase authentication needed
 8048: 
 8049: =item *
 8050: 
 8051: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8052: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8053: and course level
 8054: 
 8055: =item *
 8056: 
 8057: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8058: explanation of a user role term
 8059: 
 8060: =item *
 8061: 
 8062: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
 8063: optional.  Returns a hash of a user's roles, with keys set to
 8064: colon-sparated $uname,$udom,and $role, and value set to
 8065: colon-separated start and end times for the role. If no username and
 8066: domain are specified, will default to current user/domain. Types,
 8067: roles, and roledoms are references to arrays, of role statuses
 8068: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
 8069: of the roles which can be used to restrict the list if roles
 8070: reported. If no array ref is provided for types, will default to
 8071: return only active roles.
 8072: 
 8073: =back
 8074: 
 8075: =head2 User Modification
 8076: 
 8077: =over 4
 8078: 
 8079: =item *
 8080: 
 8081: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8082: user for the level given by URL.  Optional start and end dates (leave empty
 8083: string or zero for "no date")
 8084: 
 8085: =item *
 8086: 
 8087: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8088: change a users, password, possible return values are: ok,
 8089: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8090: refused
 8091: 
 8092: =item *
 8093: 
 8094: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8095: 
 8096: =item *
 8097: 
 8098: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8099: modify user
 8100: 
 8101: =item *
 8102: 
 8103: modifystudent
 8104: 
 8105: modify a students enrollment and identification information.
 8106: The course id is resolved based on the current users environment.  
 8107: This means the envoking user must be a course coordinator or otherwise
 8108: associated with a course.
 8109: 
 8110: This call is essentially a wrapper for lonnet::modifyuser and
 8111: lonnet::modify_student_enrollment
 8112: 
 8113: Inputs: 
 8114: 
 8115: =over 4
 8116: 
 8117: =item B<$udom> Students loncapa domain
 8118: 
 8119: =item B<$uname> Students loncapa login name
 8120: 
 8121: =item B<$uid> Students id/student number
 8122: 
 8123: =item B<$umode> Students authentication mode
 8124: 
 8125: =item B<$upass> Students password
 8126: 
 8127: =item B<$first> Students first name
 8128: 
 8129: =item B<$middle> Students middle name
 8130: 
 8131: =item B<$last> Students last name
 8132: 
 8133: =item B<$gene> Students generation
 8134: 
 8135: =item B<$usec> Students section in course
 8136: 
 8137: =item B<$end> Unix time of the roles expiration
 8138: 
 8139: =item B<$start> Unix time of the roles start date
 8140: 
 8141: =item B<$forceid> If defined, allow $uid to be changed
 8142: 
 8143: =item B<$desiredhome> server to use as home server for student
 8144: 
 8145: =back
 8146: 
 8147: =item *
 8148: 
 8149: modify_student_enrollment
 8150: 
 8151: Change a students enrollment status in a class.  The environment variable
 8152: 'role.request.course' must be defined for this function to proceed.
 8153: 
 8154: Inputs:
 8155: 
 8156: =over 4
 8157: 
 8158: =item $udom, students domain
 8159: 
 8160: =item $uname, students name
 8161: 
 8162: =item $uid, students user id
 8163: 
 8164: =item $first, students first name
 8165: 
 8166: =item $middle
 8167: 
 8168: =item $last
 8169: 
 8170: =item $gene
 8171: 
 8172: =item $usec
 8173: 
 8174: =item $end
 8175: 
 8176: =item $start
 8177: 
 8178: =back
 8179: 
 8180: 
 8181: =item *
 8182: 
 8183: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8184: custom role; give a custom role to a user for the level given by URL.  Specify
 8185: name and domain of role author, and role name
 8186: 
 8187: =item *
 8188: 
 8189: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8190: 
 8191: =item *
 8192: 
 8193: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8194: 
 8195: =back
 8196: 
 8197: =head2 Course Infomation
 8198: 
 8199: =over 4
 8200: 
 8201: =item *
 8202: 
 8203: coursedescription($courseid) : returns a hash of information about the
 8204: specified course id, including all environment settings for the
 8205: course, the description of the course will be in the hash under the
 8206: key 'description'
 8207: 
 8208: =item *
 8209: 
 8210: resdata($name,$domain,$type,@which) : request for current parameter
 8211: setting for a specific $type, where $type is either 'course' or 'user',
 8212: @what should be a list of parameters to ask about. This routine caches
 8213: answers for 5 minutes.
 8214: 
 8215: =back
 8216: 
 8217: =head2 Course Modification
 8218: 
 8219: =over 4
 8220: 
 8221: =item *
 8222: 
 8223: writecoursepref($courseid,%prefs) : write preferences (environment
 8224: database) for a course
 8225: 
 8226: =item *
 8227: 
 8228: createcourse($udom,$description,$url) : make/modify course
 8229: 
 8230: =back
 8231: 
 8232: =head2 Resource Subroutines
 8233: 
 8234: =over 4
 8235: 
 8236: =item *
 8237: 
 8238: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8239: 
 8240: =item *
 8241: 
 8242: repcopy($filename) : subscribes to the requested file, and attempts to
 8243: replicate from the owning library server, Might return
 8244: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8245: 'bad_request', also attempts to grab the metadata for the
 8246: resource. Expects the local filesystem pathname
 8247: (/home/httpd/html/res/....)
 8248: 
 8249: =back
 8250: 
 8251: =head2 Resource Information
 8252: 
 8253: =over 4
 8254: 
 8255: =item *
 8256: 
 8257: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8258: a vairety of different possible values, $varname should be a request
 8259: string, and the other parameters can be used to specify who and what
 8260: one is asking about.
 8261: 
 8262: Possible values for $varname are environment.lastname (or other item
 8263: from the envirnment hash), user.name (or someother aspect about the
 8264: user), resource.0.maxtries (or some other part and parameter of a
 8265: resource)
 8266: 
 8267: =item *
 8268: 
 8269: directcondval($number) : get current value of a condition; reads from a state
 8270: string
 8271: 
 8272: =item *
 8273: 
 8274: condval($condidx) : value of condition index based on state
 8275: 
 8276: =item *
 8277: 
 8278: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8279: resource's metadata, $what should be either a specific key, or either
 8280: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8281: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8282: 
 8283: this function automatically caches all requests
 8284: 
 8285: =item *
 8286: 
 8287: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8288: network of library servers; returns file handle of where SQL and regex results
 8289: will be stored for query
 8290: 
 8291: =item *
 8292: 
 8293: symbread($filename) : return symbolic list entry (filename argument optional);
 8294: returns the data handle
 8295: 
 8296: =item *
 8297: 
 8298: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8299: a possible symb for the URL in $thisfn, and if is an encryypted
 8300: resource that the user accessed using /enc/ returns a 1 on success, 0
 8301: on failure, user must be in a course, as it assumes the existance of
 8302: the course initial hash, and uses $env('request.course.id'}
 8303: 
 8304: 
 8305: =item *
 8306: 
 8307: symbclean($symb) : removes versions numbers from a symb, returns the
 8308: cleaned symb
 8309: 
 8310: =item *
 8311: 
 8312: is_on_map($uri) : checks if the $uri is somewhere on the current
 8313: course map, user must be in a course for it to work.
 8314: 
 8315: =item *
 8316: 
 8317: numval($salt) : return random seed value (addend for rndseed)
 8318: 
 8319: =item *
 8320: 
 8321: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8322: a random seed, all arguments are optional, if they aren't sent it uses the
 8323: environment to derive them. Note: if symb isn't sent and it can't get one
 8324: from &symbread it will use the current time as its return value
 8325: 
 8326: =item *
 8327: 
 8328: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8329: unfakeable, receipt
 8330: 
 8331: =item *
 8332: 
 8333: receipt() : API to ireceipt working off of env values; given out to users
 8334: 
 8335: =item *
 8336: 
 8337: countacc($url) : count the number of accesses to a given URL
 8338: 
 8339: =item *
 8340: 
 8341: 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
 8342: 
 8343: =item *
 8344: 
 8345: 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)
 8346: 
 8347: =item *
 8348: 
 8349: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8350: 
 8351: =item *
 8352: 
 8353: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8354: forcing spreadsheet to reevaluate the resource scores next time.
 8355: 
 8356: =back
 8357: 
 8358: =head2 Storing/Retreiving Data
 8359: 
 8360: =over 4
 8361: 
 8362: =item *
 8363: 
 8364: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8365: for this url; hashref needs to be given and should be a \%hashname; the
 8366: remaining args aren't required and if they aren't passed or are '' they will
 8367: be derived from the env
 8368: 
 8369: =item *
 8370: 
 8371: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8372: uses critical subroutine
 8373: 
 8374: =item *
 8375: 
 8376: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8377: all args are optional
 8378: 
 8379: =item *
 8380: 
 8381: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8382: dumps the complete (or key matching regexp) namespace into a hash
 8383: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8384: normally &store()ed into
 8385: 
 8386: $range should be either an integer '100' (give me the first 100
 8387:                                            matching records)
 8388:               or be  two integers sperated by a - with no spaces
 8389:                  '30-50' (give me the 30th through the 50th matching
 8390:                           records)
 8391: 
 8392: 
 8393: =item *
 8394: 
 8395: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8396: replaces a &store() version of data with a replacement set of data
 8397: for a particular resource in a namespace passed in the $storehash hash 
 8398: reference
 8399: 
 8400: =item *
 8401: 
 8402: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8403: works very similar to store/cstore, but all data is stored in a
 8404: temporary location and can be reset using tmpreset, $storehash should
 8405: be a hash reference, returns nothing on success
 8406: 
 8407: =item *
 8408: 
 8409: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8410: similar to restore, but all data is stored in a temporary location and
 8411: can be reset using tmpreset. Returns a hash of values on success,
 8412: error string otherwise.
 8413: 
 8414: =item *
 8415: 
 8416: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8417: deltes all keys for $symb form the temporary storage hash.
 8418: 
 8419: =item *
 8420: 
 8421: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8422: reference filled in from namesp ($udom and $uname are optional)
 8423: 
 8424: =item *
 8425: 
 8426: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8427: namesp ($udom and $uname are optional)
 8428: 
 8429: =item *
 8430: 
 8431: dump($namespace,$udom,$uname,$regexp,$range) : 
 8432: dumps the complete (or key matching regexp) namespace into a hash
 8433: ($udom, $uname, $regexp, $range are optional)
 8434: 
 8435: $range should be either an integer '100' (give me the first 100
 8436:                                            matching records)
 8437:               or be  two integers sperated by a - with no spaces
 8438:                  '30-50' (give me the 30th through the 50th matching
 8439:                           records)
 8440: =item *
 8441: 
 8442: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8443: $store can be a scalar, an array reference, or if the amount to be 
 8444: incremented is > 1, a hash reference.
 8445: 
 8446: ($udom and $uname are optional)
 8447: 
 8448: =item *
 8449: 
 8450: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8451: ($udom and $uname are optional)
 8452: 
 8453: =item *
 8454: 
 8455: cput($namespace,$storehash,$udom,$uname) : critical put
 8456: ($udom and $uname are optional)
 8457: 
 8458: =item *
 8459: 
 8460: newput($namespace,$storehash,$udom,$uname) :
 8461: 
 8462: Attempts to store the items in the $storehash, but only if they don't
 8463: currently exist, if this succeeds you can be certain that you have 
 8464: successfully created a new key value pair in the $namespace db.
 8465: 
 8466: 
 8467: Args:
 8468:  $namespace: name of database to store values to
 8469:  $storehash: hashref to store to the db
 8470:  $udom: (optional) domain of user containing the db
 8471:  $uname: (optional) name of user caontaining the db
 8472: 
 8473: Returns:
 8474:  'ok' -> succeeded in storing all keys of $storehash
 8475:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8476:                         least <key> already existed in the db (other
 8477:                         requested keys may also already exist)
 8478:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8479:  'con_lost' -> unable to contact request server
 8480:  'refused' -> action was not allowed by remote machine
 8481: 
 8482: 
 8483: =item *
 8484: 
 8485: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8486: reference filled in from namesp (encrypts the return communication)
 8487: ($udom and $uname are optional)
 8488: 
 8489: =item *
 8490: 
 8491: log($udom,$name,$home,$message) : write to permanent log for user; use
 8492: critical subroutine
 8493: 
 8494: =item *
 8495: 
 8496: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
 8497: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
 8498: 
 8499: =item *
 8500: 
 8501: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
 8502: 
 8503: =back
 8504: 
 8505: =head2 Network Status Functions
 8506: 
 8507: =over 4
 8508: 
 8509: =item *
 8510: 
 8511: dirlist($uri) : return directory list based on URI
 8512: 
 8513: =item *
 8514: 
 8515: spareserver() : find server with least workload from spare.tab
 8516: 
 8517: =back
 8518: 
 8519: =head2 Apache Request
 8520: 
 8521: =over 4
 8522: 
 8523: =item *
 8524: 
 8525: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8526: localhost, posts hash
 8527: 
 8528: =back
 8529: 
 8530: =head2 Data to String to Data
 8531: 
 8532: =over 4
 8533: 
 8534: =item *
 8535: 
 8536: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8537: and '&' separators, supports elements that are arrayrefs and hashrefs
 8538: 
 8539: =item *
 8540: 
 8541: hashref2str($hashref) : convert a hashref into a string complete with
 8542: escaping and '=' and '&' separators, supports elements that are
 8543: arrayrefs and hashrefs
 8544: 
 8545: =item *
 8546: 
 8547: arrayref2str($arrayref) : convert an arrayref into a string complete
 8548: with escaping and '&' separators, supports elements that are arrayrefs
 8549: and hashrefs
 8550: 
 8551: =item *
 8552: 
 8553: str2hash($string) : convert string to hash using unescaping and
 8554: splitting on '=' and '&', supports elements that are arrayrefs and
 8555: hashrefs
 8556: 
 8557: =item *
 8558: 
 8559: str2array($string) : convert string to hash using unescaping and
 8560: splitting on '&', supports elements that are arrayrefs and hashrefs
 8561: 
 8562: =back
 8563: 
 8564: =head2 Logging Routines
 8565: 
 8566: =over 4
 8567: 
 8568: These routines allow one to make log messages in the lonnet.log and
 8569: lonnet.perm logfiles.
 8570: 
 8571: =item *
 8572: 
 8573: logtouch() : make sure the logfile, lonnet.log, exists
 8574: 
 8575: =item *
 8576: 
 8577: logthis() : append message to the normal lonnet.log file, it gets
 8578: preiodically rolled over and deleted.
 8579: 
 8580: =item *
 8581: 
 8582: logperm() : append a permanent message to lonnet.perm.log, this log
 8583: file never gets deleted by any automated portion of the system, only
 8584: messages of critical importance should go in here.
 8585: 
 8586: =back
 8587: 
 8588: =head2 General File Helper Routines
 8589: 
 8590: =over 4
 8591: 
 8592: =item *
 8593: 
 8594: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8595: (a) files in /uploaded
 8596:   (i) If a local copy of the file exists - 
 8597:       compares modification date of local copy with last-modified date for 
 8598:       definitive version stored on home server for course. If local copy is 
 8599:       stale, requests a new version from the home server and stores it. 
 8600:       If the original has been removed from the home server, then local copy 
 8601:       is unlinked.
 8602:   (ii) If local copy does not exist -
 8603:       requests the file from the home server and stores it. 
 8604:   
 8605:   If $caller is 'uploadrep':  
 8606:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8607:     for request for files originally uploaded via DOCS. 
 8608:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8609:   
 8610:   Otherwise:
 8611:      This indicates a call from the content generation phase of the request.
 8612:      -  returns the entire contents of the file or -1.
 8613:      
 8614: (b) files in /res
 8615:    - returns the entire contents of a file or -1; 
 8616:    it properly subscribes to and replicates the file if neccessary.
 8617: 
 8618: 
 8619: =item *
 8620: 
 8621: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8622:                   reference
 8623: 
 8624: returns either a stat() list of data about the file or an empty list
 8625: if the file doesn't exist or couldn't find out about it (connection
 8626: problems or user unknown)
 8627: 
 8628: =item *
 8629: 
 8630: filelocation($dir,$file) : returns file system location of a file
 8631: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8632: directory that relative $file lookups are to looked in ($dir of /a/dir
 8633: and a file of ../bob will become /a/bob)
 8634: 
 8635: =item *
 8636: 
 8637: hreflocation($dir,$file) : returns file system location or a URL; same as
 8638: filelocation except for hrefs
 8639: 
 8640: =item *
 8641: 
 8642: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8643: 
 8644: =back
 8645: 
 8646: =head2 Usererfile file routines (/uploaded*)
 8647: 
 8648: =over 4
 8649: 
 8650: =item *
 8651: 
 8652: userfileupload(): main rotine for putting a file in a user or course's
 8653:                   filespace, arguments are,
 8654: 
 8655:  formname - required - this is the name of the element in $env where the
 8656:            filename, and the contents of the file to create/modifed exist
 8657:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8658:            contents of the file is located in $env{'form.'.$formname}
 8659:  coursedoc - if true, store the file in the course of the active role
 8660:              of the current user
 8661:  subdir - required - subdirectory to put the file in under ../userfiles/
 8662:          if undefined, it will be placed in "unknown"
 8663: 
 8664:  (This routine calls clean_filename() to remove any dangerous
 8665:  characters from the filename, and then calls finuserfileupload() to
 8666:  complete the transaction)
 8667: 
 8668:  returns either the url of the uploaded file (/uploaded/....) if successful
 8669:  and /adm/notfound.html if unsuccessful
 8670: 
 8671: =item *
 8672: 
 8673: clean_filename(): routine for cleaing a filename up for storage in
 8674:                  userfile space, argument is:
 8675: 
 8676:  filename - proposed filename
 8677: 
 8678: returns: the new clean filename
 8679: 
 8680: =item *
 8681: 
 8682: finishuserfileupload(): routine that creaes and sends the file to
 8683: userspace, probably shouldn't be called directly
 8684: 
 8685:   docuname: username or courseid of destination for the file
 8686:   docudom: domain of user/course of destination for the file
 8687:   formname: same as for userfileupload()
 8688:   fname: filename (inculding subdirectories) for the file
 8689: 
 8690:  returns either the url of the uploaded file (/uploaded/....) if successful
 8691:  and /adm/notfound.html if unsuccessful
 8692: 
 8693: =item *
 8694: 
 8695: renameuserfile(): renames an existing userfile to a new name
 8696: 
 8697:   Args:
 8698:    docuname: username or courseid of destination for the file
 8699:    docudom: domain of user/course of destination for the file
 8700:    old: current file name (including any subdirs under userfiles)
 8701:    new: desired file name (including any subdirs under userfiles)
 8702: 
 8703: =item *
 8704: 
 8705: mkdiruserfile(): creates a directory is a userfiles dir
 8706: 
 8707:   Args:
 8708:    docuname: username or courseid of destination for the file
 8709:    docudom: domain of user/course of destination for the file
 8710:    dir: dir to create (including any subdirs under userfiles)
 8711: 
 8712: =item *
 8713: 
 8714: removeuserfile(): removes a file that exists in userfiles
 8715: 
 8716:   Args:
 8717:    docuname: username or courseid of destination for the file
 8718:    docudom: domain of user/course of destination for the file
 8719:    fname: filname to delete (including any subdirs under userfiles)
 8720: 
 8721: =item *
 8722: 
 8723: removeuploadedurl(): convience function for removeuserfile()
 8724: 
 8725:   Args:
 8726:    url:  a full /uploaded/... url to delete
 8727: 
 8728: =item * 
 8729: 
 8730: get_portfile_permissions():
 8731:   Args:
 8732:     domain: domain of user or course contain the portfolio files
 8733:     user: name of user or num of course contain the portfolio files
 8734:   Returns:
 8735:     hashref of a dump of the proper file_permissions.db
 8736:    
 8737: 
 8738: =item * 
 8739: 
 8740: get_access_controls():
 8741: 
 8742: Args:
 8743:   current_permissions: the hash ref returned from get_portfile_permissions()
 8744:   group: (optional) the group you want the files associated with
 8745:   file: (optional) the file you want access info on
 8746: 
 8747: Returns:
 8748:     a hash (keys are file names) of hashes containing
 8749:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8750:         values are XML containing access control settings (see below) 
 8751: 
 8752: Internal notes:
 8753: 
 8754:  access controls are stored in file_permissions.db as key=value pairs.
 8755:     key -> path to file/file_name\0uniqueID:scope_end_start
 8756:         where scope -> public,guest,course,group,domains or users.
 8757:               end -> UNIX time for end of access (0 -> no end date)
 8758:               start -> UNIX time for start of access
 8759: 
 8760:     value -> XML description of access control
 8761:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8762:             <start></start>
 8763:             <end></end>
 8764: 
 8765:             <password></password>  for scope type = guest
 8766: 
 8767:             <domain></domain>     for scope type = course or group
 8768:             <number></number>
 8769:             <roles id="">
 8770:              <role></role>
 8771:              <access></access>
 8772:              <section></section>
 8773:              <group></group>
 8774:             </roles>
 8775: 
 8776:             <dom></dom>         for scope type = domains
 8777: 
 8778:             <users>             for scope type = users
 8779:              <user>
 8780:               <uname></uname>
 8781:               <udom></udom>
 8782:              </user>
 8783:             </users>
 8784:            </scope> 
 8785:               
 8786:  Access data is also aggregated for each file in an additional key=value pair:
 8787:  key -> path to file/file_name\0accesscontrol 
 8788:  value -> reference to hash
 8789:           hash contains key = value pairs
 8790:           where key = uniqueID:scope_end_start
 8791:                 value = UNIX time record was last updated
 8792: 
 8793:           Used to improve speed of look-ups of access controls for each file.  
 8794:  
 8795:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8796: 
 8797: modify_access_controls():
 8798: 
 8799: Modifies access controls for a portfolio file
 8800: Args
 8801: 1. file name
 8802: 2. reference to hash of required changes,
 8803: 3. domain
 8804: 4. username
 8805:   where domain,username are the domain of the portfolio owner 
 8806:   (either a user or a course) 
 8807: 
 8808: Returns:
 8809: 1. result of additions or updates ('ok' or 'error', with error message). 
 8810: 2. result of deletions ('ok' or 'error', with error message).
 8811: 3. reference to hash of any new or updated access controls.
 8812: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8813:    key = integer (inbound ID)
 8814:    value = uniqueID  
 8815: 
 8816: =back
 8817: 
 8818: =head2 HTTP Helper Routines
 8819: 
 8820: =over 4
 8821: 
 8822: =item *
 8823: 
 8824: escape() : unpack non-word characters into CGI-compatible hex codes
 8825: 
 8826: =item *
 8827: 
 8828: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8829: 
 8830: =back
 8831: 
 8832: =head1 PRIVATE SUBROUTINES
 8833: 
 8834: =head2 Underlying communication routines (Shouldn't call)
 8835: 
 8836: =over 4
 8837: 
 8838: =item *
 8839: 
 8840: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8841: 
 8842: =item *
 8843: 
 8844: reply() : uses subreply to send a message to remote machine, logs all failures
 8845: 
 8846: =item *
 8847: 
 8848: critical() : passes a critical message to another server; if cannot
 8849: get through then place message in connection buffer directory and
 8850: returns con_delayed, if incapable of saving message, returns
 8851: con_failed
 8852: 
 8853: =item *
 8854: 
 8855: reconlonc() : tries to reconnect lonc client processes.
 8856: 
 8857: =back
 8858: 
 8859: =head2 Resource Access Logging
 8860: 
 8861: =over 4
 8862: 
 8863: =item *
 8864: 
 8865: flushcourselogs() : flush (save) buffer logs and access logs
 8866: 
 8867: =item *
 8868: 
 8869: courselog($what) : save message for course in hash
 8870: 
 8871: =item *
 8872: 
 8873: courseacclog($what) : save message for course using &courselog().  Perform
 8874: special processing for specific resource types (problems, exams, quizzes, etc).
 8875: 
 8876: =item *
 8877: 
 8878: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8879: as a PerlChildExitHandler
 8880: 
 8881: =back
 8882: 
 8883: =head2 Other
 8884: 
 8885: =over 4
 8886: 
 8887: =item *
 8888: 
 8889: symblist($mapname,%newhash) : update symbolic storage links
 8890: 
 8891: =back
 8892: 
 8893: =cut

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