File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.840: download - view: text, annotated - select for diffs
Fri Mar 2 23:53:19 2007 UTC (17 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- code clarity, the var containst the lonid of the home server of the course

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.840 2007/03/02 23:53:19 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 %hostdom 
   39:    %libserv %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:     my $tryserver;
  644:     foreach $tryserver (keys %libserv) {
  645:         next if ($ignoreBadCache ne 'true' && 
  646: 		 exists($badServerCache{$tryserver}));
  647: 	if ($hostdom{$tryserver} eq $udom) {
  648:            my $answer=reply("home:$udom:$uname",$tryserver);
  649:            if ($answer eq 'found') {
  650:                delete($badServerCache{$tryserver}); 
  651: 	       return $homecache{$index}=$tryserver;
  652:            } elsif ($answer eq 'no_host') {
  653: 	       $badServerCache{$tryserver}=1;
  654:            }
  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 $tryserver;
  667:     foreach $tryserver (keys %libserv) {
  668:        if ($hostdom{$tryserver} eq $udom) {
  669: 	  my $idlist=join('&',@ids);
  670:           $idlist=~tr/A-Z/a-z/; 
  671: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  672:           my @answer=();
  673:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  674: 	      @answer=split(/\&/,$reply);
  675:           }                    ;
  676:           my $i;
  677:           for ($i=0;$i<=$#ids;$i++) {
  678:               if ($answer[$i]) {
  679: 		  $returnhash{$ids[$i]}=$answer[$i];
  680:               } 
  681:           }
  682:        }
  683:     }    
  684:     return %returnhash;
  685: }
  686: 
  687: # ------------------------------------- Find the IDs behind a list of usernames
  688: 
  689: sub idrget {
  690:     my ($udom,@unames)=@_;
  691:     my %returnhash=();
  692:     foreach my $uname (@unames) {
  693:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  694:     }
  695:     return %returnhash;
  696: }
  697: 
  698: # ------------------------------- Store away a list of names and associated IDs
  699: 
  700: sub idput {
  701:     my ($udom,%ids)=@_;
  702:     my %servers=();
  703:     foreach my $uname (keys(%ids)) {
  704: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  705:         my $uhom=&homeserver($uname,$udom);
  706:         if ($uhom ne 'no_host') {
  707:             my $id=&escape($ids{$uname});
  708:             $id=~tr/A-Z/a-z/;
  709:             my $esc_unam=&escape($uname);
  710: 	    if ($servers{$uhom}) {
  711: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  712:             } else {
  713:                 $servers{$uhom}=$id.'='.$esc_unam;
  714:             }
  715:         }
  716:     }
  717:     foreach my $server (keys(%servers)) {
  718:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  719:     }
  720: }
  721: 
  722: # ------------------------------------------- get items from domain db files   
  723: 
  724: sub get_dom {
  725:     my ($namespace,$storearr,$udom)=@_;
  726:     my $items='';
  727:     foreach my $item (@$storearr) {
  728:         $items.=&escape($item).'&';
  729:     }
  730:     $items=~s/\&$//;
  731:     if (!$udom) { $udom=$env{'user.domain'}; }
  732:     if (exists($domain_primary{$udom})) {
  733:         my $uhome=$domain_primary{$udom};
  734:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  735:         my @pairs=split(/\&/,$rep);
  736:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  737:             return @pairs;
  738:         }
  739:         my %returnhash=();
  740:         my $i=0;
  741:         foreach my $item (@$storearr) {
  742:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  743:             $i++;
  744:         }
  745:         return %returnhash;
  746:     } else {
  747:         &logthis("get_dom failed - no primary domain server for $udom");
  748:     }
  749: }
  750: 
  751: # -------------------------------------------- put items in domain db files 
  752: 
  753: sub put_dom {
  754:     my ($namespace,$storehash,$udom)=@_;
  755:     if (!$udom) { $udom=$env{'user.domain'}; }
  756:     if (exists($domain_primary{$udom})) {
  757:         my $uhome=$domain_primary{$udom};
  758:         my $items='';
  759:         foreach my $item (keys(%$storehash)) {
  760:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  761:         }
  762:         $items=~s/\&$//;
  763:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  764:     } else {
  765:         &logthis("put_dom failed - no primary domain server for $udom");
  766:     }
  767: }
  768: 
  769: sub retrieve_inst_usertypes {
  770:     my ($udom) = @_;
  771:     my (%returnhash,@order);
  772:     if (exists($domain_primary{$udom})) {
  773:         my $uhome=$domain_primary{$udom};
  774:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  775:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  776:         my @pairs=split(/\&/,$hashitems);
  777:         foreach my $item (@pairs) {
  778:             my ($key,$value)=split(/=/,$item,2);
  779:             $key = &unescape($key);
  780:             next if ($key =~ /^error: 2 /);
  781:             $returnhash{$key}=&thaw_unescape($value);
  782:         }
  783:         my @esc_order = split(/\&/,$orderitems);
  784:         foreach my $item (@esc_order) {
  785:             push(@order,&unescape($item));
  786:         }
  787:     } else {
  788:         &logthis("get_dom failed - no primary domain server for $udom");
  789:     }
  790:     return (\%returnhash,\@order);
  791: }
  792: 
  793: # --------------------------------------------------- Assign a key to a student
  794: 
  795: sub assign_access_key {
  796: #
  797: # a valid key looks like uname:udom#comments
  798: # comments are being appended
  799: #
  800:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  801:     $kdom=
  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  803:     $knum=
  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  805:     $cdom=
  806:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  807:     $cnum=
  808:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  809:     $udom=$env{'user.name'} unless (defined($udom));
  810:     $uname=$env{'user.domain'} unless (defined($uname));
  811:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  812:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  813:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  814:                                                   # assigned to this person
  815:                                                   # - this should not happen,
  816:                                                   # unless something went wrong
  817:                                                   # the first time around
  818: # ready to assign
  819:         $logentry=$1.'; '.$logentry;
  820:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  821:                                                  $kdom,$knum) eq 'ok') {
  822: # key now belongs to user
  823: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  824:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  825:                 &appenv('environment.'.$envkey => $ckey);
  826:                 return 'ok';
  827:             } else {
  828:                 return 
  829:   'error: Count not permanently assign key, will need to be re-entered later.';
  830: 	    }
  831:         } else {
  832:             return 'error: Could not assign key, try again later.';
  833:         }
  834:     } elsif (!$existing{$ckey}) {
  835: # the key does not exist
  836: 	return 'error: The key does not exist';
  837:     } else {
  838: # the key is somebody else's
  839: 	return 'error: The key is already in use';
  840:     }
  841: }
  842: 
  843: # ------------------------------------------ put an additional comment on a key
  844: 
  845: sub comment_access_key {
  846: #
  847: # a valid key looks like uname:udom#comments
  848: # comments are being appended
  849: #
  850:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  851:     $cdom=
  852:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  853:     $cnum=
  854:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  855:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  856:     if ($existing{$ckey}) {
  857:         $existing{$ckey}.='; '.$logentry;
  858: # ready to assign
  859:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  860:                                                  $cdom,$cnum) eq 'ok') {
  861: 	    return 'ok';
  862:         } else {
  863: 	    return 'error: Count not store comment.';
  864:         }
  865:     } else {
  866: # the key does not exist
  867: 	return 'error: The key does not exist';
  868:     }
  869: }
  870: 
  871: # ------------------------------------------------------ Generate a set of keys
  872: 
  873: sub generate_access_keys {
  874:     my ($number,$cdom,$cnum,$logentry)=@_;
  875:     $cdom=
  876:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  877:     $cnum=
  878:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  879:     unless (&allowed('mky',$cdom)) { return 0; }
  880:     unless (($cdom) && ($cnum)) { return 0; }
  881:     if ($number>10000) { return 0; }
  882:     sleep(2); # make sure don't get same seed twice
  883:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  884:     my $total=0;
  885:     for (my $i=1;$i<=$number;$i++) {
  886:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  887:                   sprintf("%lx",int(100000*rand)).'-'.
  888:                   sprintf("%lx",int(100000*rand));
  889:        $newkey=~s/1/g/g; # folks mix up 1 and l
  890:        $newkey=~s/0/h/g; # and also 0 and O
  891:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  892:        if ($existing{$newkey}) {
  893:            $i--;
  894:        } else {
  895: 	  if (&put('accesskeys',
  896:               { $newkey => '# generated '.localtime().
  897:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  898:                            '; '.$logentry },
  899: 		   $cdom,$cnum) eq 'ok') {
  900:               $total++;
  901: 	  }
  902:        }
  903:     }
  904:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  905:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  906:     return $total;
  907: }
  908: 
  909: # ------------------------------------------------------- Validate an accesskey
  910: 
  911: sub validate_access_key {
  912:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  913:     $cdom=
  914:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  915:     $cnum=
  916:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  917:     $udom=$env{'user.domain'} unless (defined($udom));
  918:     $uname=$env{'user.name'} unless (defined($uname));
  919:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  920:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  921: }
  922: 
  923: # ------------------------------------- Find the section of student in a course
  924: sub devalidate_getsection_cache {
  925:     my ($udom,$unam,$courseid)=@_;
  926:     my $hashid="$udom:$unam:$courseid";
  927:     &devalidate_cache_new('getsection',$hashid);
  928: }
  929: 
  930: sub courseid_to_courseurl {
  931:     my ($courseid) = @_;
  932:     #already url style courseid
  933:     return $courseid if ($courseid =~ m{^/});
  934: 
  935:     if (exists($env{'course.'.$courseid.'.num'})) {
  936: 	my $cnum = $env{'course.'.$courseid.'.num'};
  937: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  938: 	return "/$cdom/$cnum";
  939:     }
  940: 
  941:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  942:     if (exists($courseinfo{'num'})) {
  943: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  944:     }
  945: 
  946:     return undef;
  947: }
  948: 
  949: sub getsection {
  950:     my ($udom,$unam,$courseid)=@_;
  951:     my $cachetime=1800;
  952: 
  953:     my $hashid="$udom:$unam:$courseid";
  954:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  955:     if (defined($cached)) { return $result; }
  956: 
  957:     my %Pending; 
  958:     my %Expired;
  959:     #
  960:     # Each role can either have not started yet (pending), be active, 
  961:     #    or have expired.
  962:     #
  963:     # If there is an active role, we are done.
  964:     #
  965:     # If there is more than one role which has not started yet, 
  966:     #     choose the one which will start sooner
  967:     # If there is one role which has not started yet, return it.
  968:     #
  969:     # If there is more than one expired role, choose the one which ended last.
  970:     # If there is a role which has expired, return it.
  971:     #
  972:     $courseid = &courseid_to_courseurl($courseid);
  973:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
  974:     foreach my $key (keys(%roleshash)) {
  975:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  976:         my $section=$1;
  977:         if ($key eq $courseid.'_st') { $section=''; }
  978:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
  979:         my $now=time;
  980:         if (defined($end) && $end && ($now > $end)) {
  981:             $Expired{$end}=$section;
  982:             next;
  983:         }
  984:         if (defined($start) && $start && ($now < $start)) {
  985:             $Pending{$start}=$section;
  986:             next;
  987:         }
  988:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  989:     }
  990:     #
  991:     # Presumedly there will be few matching roles from the above
  992:     # loop and the sorting time will be negligible.
  993:     if (scalar(keys(%Pending))) {
  994:         my ($time) = sort {$a <=> $b} keys(%Pending);
  995:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  996:     } 
  997:     if (scalar(keys(%Expired))) {
  998:         my @sorted = sort {$a <=> $b} keys(%Expired);
  999:         my $time = pop(@sorted);
 1000:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1001:     }
 1002:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1003: }
 1004: 
 1005: sub save_cache {
 1006:     &purge_remembered();
 1007:     #&Apache::loncommon::validate_page();
 1008:     undef(%env);
 1009:     undef($env_loaded);
 1010: }
 1011: 
 1012: my $to_remember=-1;
 1013: my %remembered;
 1014: my %accessed;
 1015: my $kicks=0;
 1016: my $hits=0;
 1017: sub devalidate_cache_new {
 1018:     my ($name,$id,$debug) = @_;
 1019:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1020:     $id=&escape($name.':'.$id);
 1021:     $memcache->delete($id);
 1022:     delete($remembered{$id});
 1023:     delete($accessed{$id});
 1024: }
 1025: 
 1026: sub is_cached_new {
 1027:     my ($name,$id,$debug) = @_;
 1028:     $id=&escape($name.':'.$id);
 1029:     if (exists($remembered{$id})) {
 1030: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1031: 	$accessed{$id}=[&gettimeofday()];
 1032: 	$hits++;
 1033: 	return ($remembered{$id},1);
 1034:     }
 1035:     my $value = $memcache->get($id);
 1036:     if (!(defined($value))) {
 1037: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1038: 	return (undef,undef);
 1039:     }
 1040:     if ($value eq '__undef__') {
 1041: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1042: 	$value=undef;
 1043:     }
 1044:     &make_room($id,$value,$debug);
 1045:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1046:     return ($value,1);
 1047: }
 1048: 
 1049: sub do_cache_new {
 1050:     my ($name,$id,$value,$time,$debug) = @_;
 1051:     $id=&escape($name.':'.$id);
 1052:     my $setvalue=$value;
 1053:     if (!defined($setvalue)) {
 1054: 	$setvalue='__undef__';
 1055:     }
 1056:     if (!defined($time) ) {
 1057: 	$time=600;
 1058:     }
 1059:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1060:     $memcache->set($id,$setvalue,$time);
 1061:     # need to make a copy of $value
 1062:     #&make_room($id,$value,$debug);
 1063:     return $value;
 1064: }
 1065: 
 1066: sub make_room {
 1067:     my ($id,$value,$debug)=@_;
 1068:     $remembered{$id}=$value;
 1069:     if ($to_remember<0) { return; }
 1070:     $accessed{$id}=[&gettimeofday()];
 1071:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1072:     my $to_kick;
 1073:     my $max_time=0;
 1074:     foreach my $other (keys(%accessed)) {
 1075: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1076: 	    $to_kick=$other;
 1077: 	    $max_time=&tv_interval($accessed{$other});
 1078: 	}
 1079:     }
 1080:     delete($remembered{$to_kick});
 1081:     delete($accessed{$to_kick});
 1082:     $kicks++;
 1083:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1084:     return;
 1085: }
 1086: 
 1087: sub purge_remembered {
 1088:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1089:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1090:     undef(%remembered);
 1091:     undef(%accessed);
 1092: }
 1093: # ------------------------------------- Read an entry from a user's environment
 1094: 
 1095: sub userenvironment {
 1096:     my ($udom,$unam,@what)=@_;
 1097:     my %returnhash=();
 1098:     my @answer=split(/\&/,
 1099:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1100:                       &homeserver($unam,$udom)));
 1101:     my $i;
 1102:     for ($i=0;$i<=$#what;$i++) {
 1103: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1104:     }
 1105:     return %returnhash;
 1106: }
 1107: 
 1108: # ---------------------------------------------------------- Get a studentphoto
 1109: sub studentphoto {
 1110:     my ($udom,$unam,$ext) = @_;
 1111:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1112:     if (defined($env{'request.course.id'})) {
 1113:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1114:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1115:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1116:             } else {
 1117:                 my ($result,$perm_reqd)=
 1118: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1119:                 if ($result eq 'ok') {
 1120:                     if (!($perm_reqd eq 'yes')) {
 1121:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1122:                     }
 1123:                 }
 1124:             }
 1125:         }
 1126:     } else {
 1127:         my ($result,$perm_reqd) = 
 1128: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1129:         if ($result eq 'ok') {
 1130:             if (!($perm_reqd eq 'yes')) {
 1131:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1132:             }
 1133:         }
 1134:     }
 1135:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1136: }
 1137: 
 1138: sub retrievestudentphoto {
 1139:     my ($udom,$unam,$ext,$type) = @_;
 1140:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1141:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1142:     if ($ret eq 'ok') {
 1143:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1144:         if ($type eq 'thumbnail') {
 1145:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1146:         }
 1147:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1148:         return $tokenurl;
 1149:     } else {
 1150:         if ($type eq 'thumbnail') {
 1151:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1152:         } else { 
 1153:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1154:         }
 1155:     }
 1156: }
 1157: 
 1158: # -------------------------------------------------------------------- New chat
 1159: 
 1160: sub chatsend {
 1161:     my ($newentry,$anon,$group)=@_;
 1162:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1163:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1164:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1165:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1166: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1167: 		   &escape($newentry)).':'.$group,$chome);
 1168: }
 1169: 
 1170: # ------------------------------------------ Find current version of a resource
 1171: 
 1172: sub getversion {
 1173:     my $fname=&clutter(shift);
 1174:     unless ($fname=~/^\/res\//) { return -1; }
 1175:     return &currentversion(&filelocation('',$fname));
 1176: }
 1177: 
 1178: sub currentversion {
 1179:     my $fname=shift;
 1180:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1181:     if (defined($cached)) { return $result; }
 1182:     my $author=$fname;
 1183:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1184:     my ($udom,$uname)=split(/\//,$author);
 1185:     my $home=homeserver($uname,$udom);
 1186:     if ($home eq 'no_host') { 
 1187:         return -1; 
 1188:     }
 1189:     my $answer=reply("currentversion:$fname",$home);
 1190:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1191: 	return -1;
 1192:     }
 1193:     return &do_cache_new('resversion',$fname,$answer,600);
 1194: }
 1195: 
 1196: # ----------------------------- Subscribe to a resource, return URL if possible
 1197: 
 1198: sub subscribe {
 1199:     my $fname=shift;
 1200:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1201:     $fname=~s/[\n\r]//g;
 1202:     my $author=$fname;
 1203:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1204:     my ($udom,$uname)=split(/\//,$author);
 1205:     my $home=homeserver($uname,$udom);
 1206:     if ($home eq 'no_host') {
 1207:         return 'not_found';
 1208:     }
 1209:     my $answer=reply("sub:$fname",$home);
 1210:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1211: 	$answer.=' by '.$home;
 1212:     }
 1213:     return $answer;
 1214: }
 1215:     
 1216: # -------------------------------------------------------------- Replicate file
 1217: 
 1218: sub repcopy {
 1219:     my $filename=shift;
 1220:     $filename=~s/\/+/\//g;
 1221:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1222:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1223:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1224: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1225: 	return &repcopy_userfile($filename);
 1226:     }
 1227:     $filename=~s/[\n\r]//g;
 1228:     my $transname="$filename.in.transfer";
 1229: # FIXME: this should flock
 1230:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1231:     my $remoteurl=subscribe($filename);
 1232:     if ($remoteurl =~ /^con_lost by/) {
 1233: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1234:            return 'unavailable';
 1235:     } elsif ($remoteurl eq 'not_found') {
 1236: 	   #&logthis("Subscribe returned not_found: $filename");
 1237: 	   return 'not_found';
 1238:     } elsif ($remoteurl =~ /^rejected by/) {
 1239: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1240:            return 'forbidden';
 1241:     } elsif ($remoteurl eq 'directory') {
 1242:            return 'ok';
 1243:     } else {
 1244:         my $author=$filename;
 1245:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1246:         my ($udom,$uname)=split(/\//,$author);
 1247:         my $home=homeserver($uname,$udom);
 1248:         unless ($home eq $perlvar{'lonHostID'}) {
 1249:            my @parts=split(/\//,$filename);
 1250:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1251:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1252:                &logthis("Malconfiguration for replication: $filename");
 1253: 	       return 'bad_request';
 1254:            }
 1255:            my $count;
 1256:            for ($count=5;$count<$#parts;$count++) {
 1257:                $path.="/$parts[$count]";
 1258:                if ((-e $path)!=1) {
 1259: 		   mkdir($path,0777);
 1260:                }
 1261:            }
 1262:            my $ua=new LWP::UserAgent;
 1263:            my $request=new HTTP::Request('GET',"$remoteurl");
 1264:            my $response=$ua->request($request,$transname);
 1265:            if ($response->is_error()) {
 1266: 	       unlink($transname);
 1267:                my $message=$response->status_line;
 1268:                &logthis("<font color=\"blue\">WARNING:"
 1269:                        ." LWP get: $message: $filename</font>");
 1270:                return 'unavailable';
 1271:            } else {
 1272: 	       if ($remoteurl!~/\.meta$/) {
 1273:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1274:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1275:                   if ($mresponse->is_error()) {
 1276: 		      unlink($filename.'.meta');
 1277:                       &logthis(
 1278:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1279:                   }
 1280: 	       }
 1281:                rename($transname,$filename);
 1282:                return 'ok';
 1283:            }
 1284:        }
 1285:     }
 1286: }
 1287: 
 1288: # ------------------------------------------------ Get server side include body
 1289: sub ssi_body {
 1290:     my ($filelink,%form)=@_;
 1291:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1292:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1293:     }
 1294:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1295:                                      &ssi($filelink,%form));
 1296:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1297:     $output=~s/^.*?\<body[^\>]*\>//si;
 1298:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1299:     return $output;
 1300: }
 1301: 
 1302: # --------------------------------------------------------- Server Side Include
 1303: 
 1304: sub absolute_url {
 1305:     my ($host_name) = @_;
 1306:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1307:     if ($host_name eq '') {
 1308: 	$host_name = $ENV{'SERVER_NAME'};
 1309:     }
 1310:     return $protocol.$host_name;
 1311: }
 1312: 
 1313: sub ssi {
 1314: 
 1315:     my ($fn,%form)=@_;
 1316: 
 1317:     my $ua=new LWP::UserAgent;
 1318:     
 1319:     my $request;
 1320: 
 1321:     $form{'no_update_last_known'}=1;
 1322: 
 1323:     if (%form) {
 1324:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1325:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1326:     } else {
 1327:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1328:     }
 1329: 
 1330:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1331:     my $response=$ua->request($request);
 1332: 
 1333:     return $response->content;
 1334: }
 1335: 
 1336: sub externalssi {
 1337:     my ($url)=@_;
 1338:     my $ua=new LWP::UserAgent;
 1339:     my $request=new HTTP::Request('GET',$url);
 1340:     my $response=$ua->request($request);
 1341:     return $response->content;
 1342: }
 1343: 
 1344: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1345: 
 1346: sub allowuploaded {
 1347:     my ($srcurl,$url)=@_;
 1348:     $url=&clutter(&declutter($url));
 1349:     my $dir=$url;
 1350:     $dir=~s/\/[^\/]+$//;
 1351:     my %httpref=();
 1352:     my $httpurl=&hreflocation('',$url);
 1353:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1354:     &Apache::lonnet::appenv(%httpref);
 1355: }
 1356: 
 1357: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1358: # input: action, courseID, current domain, intended
 1359: #        path to file, source of file, instruction to parse file for objects,
 1360: #        ref to hash for embedded objects,
 1361: #        ref to hash for codebase of java objects.
 1362: #
 1363: # output: url to file (if action was uploaddoc), 
 1364: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1365: #
 1366: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1367: # course.
 1368: #
 1369: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1370: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1371: #          course's home server.
 1372: #
 1373: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1374: #          be copied from $source (current location) to 
 1375: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1376: #         and will then be copied to
 1377: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1378: #         course's home server.
 1379: #
 1380: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1381: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1382: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1383: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1384: #         in course's home server.
 1385: #
 1386: 
 1387: sub process_coursefile {
 1388:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1389:     my $fetchresult;
 1390:     my $home=&homeserver($docuname,$docudom);
 1391:     if ($action eq 'propagate') {
 1392:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1393: 			     $home);
 1394:     } else {
 1395:         my $fpath = '';
 1396:         my $fname = $file;
 1397:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1398:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1399:         my $filepath = &build_filepath($fpath);
 1400:         if ($action eq 'copy') {
 1401:             if ($source eq '') {
 1402:                 $fetchresult = 'no source file';
 1403:                 return $fetchresult;
 1404:             } else {
 1405:                 my $destination = $filepath.'/'.$fname;
 1406:                 rename($source,$destination);
 1407:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1408:                                  $home);
 1409:             }
 1410:         } elsif ($action eq 'uploaddoc') {
 1411:             open(my $fh,'>'.$filepath.'/'.$fname);
 1412:             print $fh $env{'form.'.$source};
 1413:             close($fh);
 1414:             if ($parser eq 'parse') {
 1415:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1416:                 unless ($parse_result eq 'ok') {
 1417:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1418:                 }
 1419:             }
 1420:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1421:                                  $home);
 1422:             if ($fetchresult eq 'ok') {
 1423:                 return '/uploaded/'.$fpath.'/'.$fname;
 1424:             } else {
 1425:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1426:                         ' to host '.$home.': '.$fetchresult);
 1427:                 return '/adm/notfound.html';
 1428:             }
 1429:         }
 1430:     }
 1431:     unless ( $fetchresult eq 'ok') {
 1432:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1433:              ' to host '.$home.': '.$fetchresult);
 1434:     }
 1435:     return $fetchresult;
 1436: }
 1437: 
 1438: sub build_filepath {
 1439:     my ($fpath) = @_;
 1440:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1441:     unless ($fpath eq '') {
 1442:         my @parts=split('/',$fpath);
 1443:         foreach my $part (@parts) {
 1444:             $filepath.= '/'.$part;
 1445:             if ((-e $filepath)!=1) {
 1446:                 mkdir($filepath,0777);
 1447:             }
 1448:         }
 1449:     }
 1450:     return $filepath;
 1451: }
 1452: 
 1453: sub store_edited_file {
 1454:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1455:     my $file = $primary_url;
 1456:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1457:     my $fpath = '';
 1458:     my $fname = $file;
 1459:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1460:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1461:     my $filepath = &build_filepath($fpath);
 1462:     open(my $fh,'>'.$filepath.'/'.$fname);
 1463:     print $fh $content;
 1464:     close($fh);
 1465:     my $home=&homeserver($docuname,$docudom);
 1466:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1467: 			  $home);
 1468:     if ($$fetchresult eq 'ok') {
 1469:         return '/uploaded/'.$fpath.'/'.$fname;
 1470:     } else {
 1471:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1472: 		 ' to host '.$home.': '.$$fetchresult);
 1473:         return '/adm/notfound.html';
 1474:     }
 1475: }
 1476: 
 1477: sub clean_filename {
 1478:     my ($fname,$args)=@_;
 1479: # Replace Windows backslashes by forward slashes
 1480:     $fname=~s/\\/\//g;
 1481:     if (!$args->{'keep_path'}) {
 1482:         # Get rid of everything but the actual filename
 1483: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1484:     }
 1485: # Replace spaces by underscores
 1486:     $fname=~s/\s+/\_/g;
 1487: # Replace all other weird characters by nothing
 1488:     $fname=~s{[^/\w\.\-]}{}g;
 1489: # Replace all .\d. sequences with _\d. so they no longer look like version
 1490: # numbers
 1491:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1492:     return $fname;
 1493: }
 1494: 
 1495: # --------------- Take an uploaded file and put it into the userfiles directory
 1496: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1497: #                    the desired filenam is in $env{"form.$formname.filename"}
 1498: #        $coursedoc - if true up to the current course
 1499: #                     if false
 1500: #        $subdir - directory in userfile to store the file into
 1501: #        $parser, $allfiles, $codebase - unknown
 1502: #
 1503: # output: url of file in userspace, or error: <message> 
 1504: #             or /adm/notfound.html if failure to upload occurse
 1505: 
 1506: 
 1507: sub userfileupload {
 1508:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1509:     if (!defined($subdir)) { $subdir='unknown'; }
 1510:     my $fname=$env{'form.'.$formname.'.filename'};
 1511:     $fname=&clean_filename($fname);
 1512: # See if there is anything left
 1513:     unless ($fname) { return 'error: no uploaded file'; }
 1514:     chop($env{'form.'.$formname});
 1515:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1516:         my $now = time;
 1517:         my $filepath = 'tmp/helprequests/'.$now;
 1518:         my @parts=split(/\//,$filepath);
 1519:         my $fullpath = $perlvar{'lonDaemons'};
 1520:         for (my $i=0;$i<@parts;$i++) {
 1521:             $fullpath .= '/'.$parts[$i];
 1522:             if ((-e $fullpath)!=1) {
 1523:                 mkdir($fullpath,0777);
 1524:             }
 1525:         }
 1526:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1527:         print $fh $env{'form.'.$formname};
 1528:         close($fh);
 1529:         return $fullpath.'/'.$fname;
 1530:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1531:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1532:                        '_'.$env{'user.domain'}.'/pending';
 1533:         my @parts=split(/\//,$filepath);
 1534:         my $fullpath = $perlvar{'lonDaemons'};
 1535:         for (my $i=0;$i<@parts;$i++) {
 1536:             $fullpath .= '/'.$parts[$i];
 1537:             if ((-e $fullpath)!=1) {
 1538:                 mkdir($fullpath,0777);
 1539:             }
 1540:         }
 1541:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1542:         print $fh $env{'form.'.$formname};
 1543:         close($fh);
 1544:         return $fullpath.'/'.$fname;
 1545:     }
 1546:     
 1547: # Create the directory if not present
 1548:     $fname="$subdir/$fname";
 1549:     if ($coursedoc) {
 1550: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1551: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1552:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1553:             return &finishuserfileupload($docuname,$docudom,
 1554: 					 $formname,$fname,$parser,$allfiles,
 1555: 					 $codebase);
 1556:         } else {
 1557:             $fname=$env{'form.folder'}.'/'.$fname;
 1558:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1559: 				       $fname,$formname,$parser,
 1560: 				       $allfiles,$codebase);
 1561:         }
 1562:     } elsif (defined($destuname)) {
 1563:         my $docuname=$destuname;
 1564:         my $docudom=$destudom;
 1565: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1566: 				     $fname,$parser,$allfiles,$codebase);
 1567:         
 1568:     } else {
 1569:         my $docuname=$env{'user.name'};
 1570:         my $docudom=$env{'user.domain'};
 1571:         if (exists($env{'form.group'})) {
 1572:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1573:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1574:         }
 1575: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1576: 				     $fname,$parser,$allfiles,$codebase);
 1577:     }
 1578: }
 1579: 
 1580: sub finishuserfileupload {
 1581:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1582:     my $path=$docudom.'/'.$docuname.'/';
 1583:     my $filepath=$perlvar{'lonDocRoot'};
 1584:     my ($fnamepath,$file);
 1585:     $file=$fname;
 1586:     if ($fname=~m|/|) {
 1587:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1588: 	$path.=$fnamepath.'/';
 1589:     }
 1590:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1591:     my $count;
 1592:     for ($count=4;$count<=$#parts;$count++) {
 1593:         $filepath.="/$parts[$count]";
 1594:         if ((-e $filepath)!=1) {
 1595: 	    mkdir($filepath,0777);
 1596:         }
 1597:     }
 1598: # Save the file
 1599:     {
 1600: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1601: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1602: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1603: 	    return '/adm/notfound.html';
 1604: 	}
 1605: 	if (!print FH ($env{'form.'.$formname})) {
 1606: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1607: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1608: 	    return '/adm/notfound.html';
 1609: 	}
 1610: 	close(FH);
 1611:     }
 1612:     if ($parser eq 'parse') {
 1613:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1614: 						   $codebase);
 1615:         unless ($parse_result eq 'ok') {
 1616:             &logthis('Failed to parse '.$filepath.$file.
 1617: 		     ' for embedded media: '.$parse_result); 
 1618:         }
 1619:     }
 1620: # Notify homeserver to grep it
 1621: #
 1622:     my $docuhome=&homeserver($docuname,$docudom);
 1623:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1624:     if ($fetchresult eq 'ok') {
 1625: #
 1626: # Return the URL to it
 1627:         return '/uploaded/'.$path.$file;
 1628:     } else {
 1629:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1630: 		 ': '.$fetchresult);
 1631:         return '/adm/notfound.html';
 1632:     }    
 1633: }
 1634: 
 1635: sub extract_embedded_items {
 1636:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1637:     my @state = ();
 1638:     my %javafiles = (
 1639:                       codebase => '',
 1640:                       code => '',
 1641:                       archive => ''
 1642:                     );
 1643:     my %mediafiles = (
 1644:                       src => '',
 1645:                       movie => '',
 1646:                      );
 1647:     my $p;
 1648:     if ($content) {
 1649:         $p = HTML::LCParser->new($content);
 1650:     } else {
 1651:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1652:     }
 1653:     while (my $t=$p->get_token()) {
 1654: 	if ($t->[0] eq 'S') {
 1655: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1656: 	    push (@state, $tagname);
 1657:             if (lc($tagname) eq 'allow') {
 1658:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1659:             }
 1660: 	    if (lc($tagname) eq 'img') {
 1661: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1662: 	    }
 1663:             if (lc($tagname) eq 'script') {
 1664:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1665:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1666:                 } else {
 1667:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1668:                 }
 1669:             }
 1670:             if (lc($tagname) eq 'link') {
 1671:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1672:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1673:                 }
 1674:             }
 1675: 	    if (lc($tagname) eq 'object' ||
 1676: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1677: 		foreach my $item (keys(%javafiles)) {
 1678: 		    $javafiles{$item} = '';
 1679: 		}
 1680: 	    }
 1681: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1682: 		my $name = lc($attr->{'name'});
 1683: 		foreach my $item (keys(%javafiles)) {
 1684: 		    if ($name eq $item) {
 1685: 			$javafiles{$item} = $attr->{'value'};
 1686: 			last;
 1687: 		    }
 1688: 		}
 1689: 		foreach my $item (keys(%mediafiles)) {
 1690: 		    if ($name eq $item) {
 1691: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1692: 			last;
 1693: 		    }
 1694: 		}
 1695: 	    }
 1696: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1697: 		foreach my $item (keys(%javafiles)) {
 1698: 		    if ($attr->{$item}) {
 1699: 			$javafiles{$item} = $attr->{$item};
 1700: 			last;
 1701: 		    }
 1702: 		}
 1703: 		foreach my $item (keys(%mediafiles)) {
 1704: 		    if ($attr->{$item}) {
 1705: 			&add_filetype($allfiles,$attr->{$item},$item);
 1706: 			last;
 1707: 		    }
 1708: 		}
 1709: 	    }
 1710: 	} elsif ($t->[0] eq 'E') {
 1711: 	    my ($tagname) = ($t->[1]);
 1712: 	    if ($javafiles{'codebase'} ne '') {
 1713: 		$javafiles{'codebase'} .= '/';
 1714: 	    }  
 1715: 	    if (lc($tagname) eq 'applet' ||
 1716: 		lc($tagname) eq 'object' ||
 1717: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1718: 		) {
 1719: 		foreach my $item (keys(%javafiles)) {
 1720: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1721: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1722: 			&add_filetype($allfiles,$file,$item);
 1723: 		    }
 1724: 		}
 1725: 	    } 
 1726: 	    pop @state;
 1727: 	}
 1728:     }
 1729:     return 'ok';
 1730: }
 1731: 
 1732: sub add_filetype {
 1733:     my ($allfiles,$file,$type)=@_;
 1734:     if (exists($allfiles->{$file})) {
 1735: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1736: 	    push(@{$allfiles->{$file}}, &escape($type));
 1737: 	}
 1738:     } else {
 1739: 	@{$allfiles->{$file}} = (&escape($type));
 1740:     }
 1741: }
 1742: 
 1743: sub removeuploadedurl {
 1744:     my ($url)=@_;
 1745:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1746:     return &removeuserfile($uname,$udom,$fname);
 1747: }
 1748: 
 1749: sub removeuserfile {
 1750:     my ($docuname,$docudom,$fname)=@_;
 1751:     my $home=&homeserver($docuname,$docudom);
 1752:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1753:     if ($result eq 'ok') {
 1754:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1755:             my $metafile = $fname.'.meta';
 1756:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1757: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1758:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1759:             my $sqlresult = 
 1760:                 &update_portfolio_table($docuname,$docudom,$file,
 1761:                                         'portfolio_metadata',$group,
 1762:                                         'delete');
 1763:         }
 1764:     }
 1765:     return $result;
 1766: }
 1767: 
 1768: sub mkdiruserfile {
 1769:     my ($docuname,$docudom,$dir)=@_;
 1770:     my $home=&homeserver($docuname,$docudom);
 1771:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1772: }
 1773: 
 1774: sub renameuserfile {
 1775:     my ($docuname,$docudom,$old,$new)=@_;
 1776:     my $home=&homeserver($docuname,$docudom);
 1777:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1778:                         &escape("$old").':'.&escape("$new"),$home);
 1779:     if ($result eq 'ok') {
 1780:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1781:             my $oldmeta = $old.'.meta';
 1782:             my $newmeta = $new.'.meta';
 1783:             my $metaresult = 
 1784:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1785: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1786:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1787:             my $sqlresult = 
 1788:                 &update_portfolio_table($docuname,$docudom,$file,
 1789:                                         'portfolio_metadata',$group,
 1790:                                         'delete');
 1791:         }
 1792:     }
 1793:     return $result;
 1794: }
 1795: 
 1796: # ------------------------------------------------------------------------- Log
 1797: 
 1798: sub log {
 1799:     my ($dom,$nam,$hom,$what)=@_;
 1800:     return critical("log:$dom:$nam:$what",$hom);
 1801: }
 1802: 
 1803: # ------------------------------------------------------------------ Course Log
 1804: #
 1805: # This routine flushes several buffers of non-mission-critical nature
 1806: #
 1807: 
 1808: sub flushcourselogs {
 1809:     &logthis('Flushing log buffers');
 1810: #
 1811: # course logs
 1812: # This is a log of all transactions in a course, which can be used
 1813: # for data mining purposes
 1814: #
 1815: # It also collects the courseid database, which lists last transaction
 1816: # times and course titles for all courseids
 1817: #
 1818:     my %courseidbuffer=();
 1819:     foreach my $crsid (keys %courselogs) {
 1820:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1821: 		          &escape($courselogs{$crsid}),
 1822: 		          $coursehombuf{$crsid}) eq 'ok') {
 1823: 	    delete $courselogs{$crsid};
 1824:         } else {
 1825:             &logthis('Failed to flush log buffer for '.$crsid);
 1826:             if (length($courselogs{$crsid})>40000) {
 1827:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1828:                         " exceeded maximum size, deleting.</font>");
 1829:                delete $courselogs{$crsid};
 1830:             }
 1831:         }
 1832:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1833:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1834: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1835:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1836:         } else {
 1837:            $courseidbuffer{$coursehombuf{$crsid}}=
 1838: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1839:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1840:         }
 1841:     }
 1842: #
 1843: # Write course id database (reverse lookup) to homeserver of courses 
 1844: # Is used in pickcourse
 1845: #
 1846:     foreach my $crs_home (keys(%courseidbuffer)) {
 1847:         &courseidput($hostdom{$crs_home},$courseidbuffer{$crs_home},
 1848: 		     $crs_home);
 1849:     }
 1850: #
 1851: # File accesses
 1852: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1853: #
 1854:     foreach my $entry (keys(%accesshash)) {
 1855:         if ($entry =~ /___count$/) {
 1856:             my ($dom,$name);
 1857:             ($dom,$name,undef)=
 1858: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1859:             if (! defined($dom) || $dom eq '' || 
 1860:                 ! defined($name) || $name eq '') {
 1861:                 my $cid = $env{'request.course.id'};
 1862:                 $dom  = $env{'request.'.$cid.'.domain'};
 1863:                 $name = $env{'request.'.$cid.'.num'};
 1864:             }
 1865:             my $value = $accesshash{$entry};
 1866:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1867:             my %temphash=($url => $value);
 1868:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1869:             if ($result eq 'ok') {
 1870:                 delete $accesshash{$entry};
 1871:             } elsif ($result eq 'unknown_cmd') {
 1872:                 # Target server has old code running on it.
 1873:                 my %temphash=($entry => $value);
 1874:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1875:                     delete $accesshash{$entry};
 1876:                 }
 1877:             }
 1878:         } else {
 1879:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1880:             my %temphash=($entry => $accesshash{$entry});
 1881:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1882:                 delete $accesshash{$entry};
 1883:             }
 1884:         }
 1885:     }
 1886: #
 1887: # Roles
 1888: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1889: #
 1890:     foreach my $entry (keys(%userrolehash)) {
 1891:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1892: 	    split(/\:/,$entry);
 1893:         if (&Apache::lonnet::put('nohist_userroles',
 1894:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1895:                 $rudom,$runame) eq 'ok') {
 1896: 	    delete $userrolehash{$entry};
 1897:         }
 1898:     }
 1899: #
 1900: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1901: #
 1902:     my %domrolebuffer = ();
 1903:     foreach my $entry (keys %domainrolehash) {
 1904:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1905:         if ($domrolebuffer{$rudom}) {
 1906:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1907:                       '='.&escape($domainrolehash{$entry});
 1908:         } else {
 1909:             $domrolebuffer{$rudom}.=&escape($entry).
 1910:                       '='.&escape($domainrolehash{$entry});
 1911:         }
 1912:         delete $domainrolehash{$entry};
 1913:     }
 1914:     foreach my $dom (keys(%domrolebuffer)) {
 1915:         foreach my $tryserver (keys %libserv) {
 1916:             if ($hostdom{$tryserver} eq $dom) {
 1917:                 unless (&reply('domroleput:'.$dom.':'.
 1918:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1919:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1920:                 }
 1921:             }
 1922:         }
 1923:     }
 1924:     $dumpcount++;
 1925: }
 1926: 
 1927: sub courselog {
 1928:     my $what=shift;
 1929:     $what=time.':'.$what;
 1930:     unless ($env{'request.course.id'}) { return ''; }
 1931:     $coursedombuf{$env{'request.course.id'}}=
 1932:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1933:     $coursenumbuf{$env{'request.course.id'}}=
 1934:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1935:     $coursehombuf{$env{'request.course.id'}}=
 1936:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1937:     $coursedescrbuf{$env{'request.course.id'}}=
 1938:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1939:     $courseinstcodebuf{$env{'request.course.id'}}=
 1940:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1941:     $courseownerbuf{$env{'request.course.id'}}=
 1942:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1943:     $coursetypebuf{$env{'request.course.id'}}=
 1944:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1945:     if (defined $courselogs{$env{'request.course.id'}}) {
 1946: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1947:     } else {
 1948: 	$courselogs{$env{'request.course.id'}}.=$what;
 1949:     }
 1950:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1951: 	&flushcourselogs();
 1952:     }
 1953: }
 1954: 
 1955: sub courseacclog {
 1956:     my $fnsymb=shift;
 1957:     unless ($env{'request.course.id'}) { return ''; }
 1958:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1959:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1960:         $what.=':POST';
 1961:         # FIXME: Probably ought to escape things....
 1962: 	foreach my $key (keys(%env)) {
 1963:             if ($key=~/^form\.(.*)/) {
 1964: 		$what.=':'.$1.'='.$env{$key};
 1965:             }
 1966:         }
 1967:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1968:         # FIXME: We should not be depending on a form parameter that someone
 1969:         # editing lonsearchcat.pm might change in the future.
 1970:         if ($env{'form.phase'} eq 'course_search') {
 1971:             $what.= ':POST';
 1972:             # FIXME: Probably ought to escape things....
 1973:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1974:                                  'crsdiscuss') {
 1975:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1976:             }
 1977:         }
 1978:     }
 1979:     &courselog($what);
 1980: }
 1981: 
 1982: sub countacc {
 1983:     my $url=&declutter(shift);
 1984:     return if (! defined($url) || $url eq '');
 1985:     unless ($env{'request.course.id'}) { return ''; }
 1986:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1987:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1988:     $accesshash{$key}++;
 1989: }
 1990: 
 1991: sub linklog {
 1992:     my ($from,$to)=@_;
 1993:     $from=&declutter($from);
 1994:     $to=&declutter($to);
 1995:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1996:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1997: }
 1998:   
 1999: sub userrolelog {
 2000:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2001:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2002:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2003:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2004:         ($trole=~/^ta/)) {
 2005:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2006:        $userrolehash
 2007:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2008:                     =$tend.':'.$tstart;
 2009:     }
 2010:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2011:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2012:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2013:         ($trole=~/^sc/)) {
 2014:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2015:        $domainrolehash
 2016:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2017:                     = $tend.':'.$tstart;
 2018:     }
 2019: }
 2020: 
 2021: sub get_course_adv_roles {
 2022:     my $cid=shift;
 2023:     $cid=$env{'request.course.id'} unless (defined($cid));
 2024:     my %coursehash=&coursedescription($cid);
 2025:     my %nothide=();
 2026:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2027: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2028:     }
 2029:     my %returnhash=();
 2030:     my %dumphash=
 2031:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2032:     my $now=time;
 2033:     foreach my $entry (keys %dumphash) {
 2034: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2035:         if (($tstart) && ($tstart<0)) { next; }
 2036:         if (($tend) && ($tend<$now)) { next; }
 2037:         if (($tstart) && ($now<$tstart)) { next; }
 2038:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2039: 	if ($username eq '' || $domain eq '') { next; }
 2040: 	if ((&privileged($username,$domain)) && 
 2041: 	    (!$nothide{$username.':'.$domain})) { next; }
 2042: 	if ($role eq 'cr') { next; }
 2043:         my $key=&plaintext($role);
 2044:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2045:         if ($returnhash{$key}) {
 2046: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2047:         } else {
 2048:             $returnhash{$key}=$username.':'.$domain;
 2049:         }
 2050:      }
 2051:     return %returnhash;
 2052: }
 2053: 
 2054: sub get_my_roles {
 2055:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
 2056:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2057:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2058:     my %dumphash=
 2059:             &dump('nohist_userroles',$udom,$uname);
 2060:     my %returnhash=();
 2061:     my $now=time;
 2062:     foreach my $entry (keys(%dumphash)) {
 2063: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2064:         if (($tstart) && ($tstart<0)) { next; }
 2065:         my $status = 'active';
 2066:         if (($tend) && ($tend<$now)) {
 2067:             $status = 'previous';
 2068:         } 
 2069:         if (($tstart) && ($now<$tstart)) {
 2070:             $status = 'future';
 2071:         }
 2072:         if (ref($types) eq 'ARRAY') {
 2073:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2074:                 next;
 2075:             } 
 2076:         } else {
 2077:             if ($status ne 'active') {
 2078:                 next;
 2079:             }
 2080:         }
 2081:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2082:         if (ref($roledoms) eq 'ARRAY') {
 2083:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2084:                 next;
 2085:             }
 2086:         }
 2087:         if (ref($roles) eq 'ARRAY') {
 2088:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2089:                 next;
 2090:             }
 2091:         } 
 2092: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2093:     }
 2094:     return %returnhash;
 2095: }
 2096: 
 2097: # ----------------------------------------------------- Frontpage Announcements
 2098: #
 2099: #
 2100: 
 2101: sub postannounce {
 2102:     my ($server,$text)=@_;
 2103:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 2104:     unless ($text=~/\w/) { $text=''; }
 2105:     return &reply('setannounce:'.&escape($text),$server);
 2106: }
 2107: 
 2108: sub getannounce {
 2109: 
 2110:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2111: 	my $announcement='';
 2112: 	while (my $line = <$fh>) { $announcement .= $line; }
 2113: 	close($fh);
 2114: 	if ($announcement=~/\w/) { 
 2115: 	    return 
 2116:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2117:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2118: 	} else {
 2119: 	    return '';
 2120: 	}
 2121:     } else {
 2122: 	return '';
 2123:     }
 2124: }
 2125: 
 2126: # ---------------------------------------------------------- Course ID routines
 2127: # Deal with domain's nohist_courseid.db files
 2128: #
 2129: 
 2130: sub courseidput {
 2131:     my ($domain,$what,$coursehome)=@_;
 2132:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2133: }
 2134: 
 2135: sub courseiddump {
 2136:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2137:     my %returnhash=();
 2138:     unless ($domfilter) { $domfilter=''; }
 2139:     foreach my $tryserver (keys %libserv) {
 2140:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 2141: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 2142: 	        foreach my $line (
 2143:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 2144: 			       $sincefilter.':'.&escape($descfilter).':'.
 2145:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2146:                                $tryserver))) {
 2147: 		    my ($key,$value)=split(/\=/,$line,2);
 2148:                     if (($key) && ($value)) {
 2149: 		        $returnhash{&unescape($key)}=$value;
 2150:                     }
 2151:                 }
 2152:             }
 2153:         }
 2154:     }
 2155:     return %returnhash;
 2156: }
 2157: 
 2158: # ---------------------------------------------------------- DC e-mail
 2159: 
 2160: sub dcmailput {
 2161:     my ($domain,$msgid,$message,$server)=@_;
 2162:     my $status = &Apache::lonnet::critical(
 2163:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2164:        &escape($message),$server);
 2165:     return $status;
 2166: }
 2167: 
 2168: sub dcmaildump {
 2169:     my ($dom,$startdate,$enddate,$senders) = @_;
 2170:     my %returnhash=();
 2171:     if (exists($domain_primary{$dom})) {
 2172:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2173:                                                          &escape($enddate).':';
 2174: 	my @esc_senders=map { &escape($_)} @$senders;
 2175: 	$cmd.=&escape(join('&',@esc_senders));
 2176: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2177:             my ($key,$value) = split(/\=/,$line,2);
 2178:             if (($key) && ($value)) {
 2179:                 $returnhash{&unescape($key)} = &unescape($value);
 2180:             }
 2181:         }
 2182:     }
 2183:     return %returnhash;
 2184: }
 2185: # ---------------------------------------------------------- Domain roles
 2186: 
 2187: sub get_domain_roles {
 2188:     my ($dom,$roles,$startdate,$enddate)=@_;
 2189:     if (undef($startdate) || $startdate eq '') {
 2190:         $startdate = '.';
 2191:     }
 2192:     if (undef($enddate) || $enddate eq '') {
 2193:         $enddate = '.';
 2194:     }
 2195:     my $rolelist = join(':',@{$roles});
 2196:     my %personnel = ();
 2197:     foreach my $tryserver (keys(%libserv)) {
 2198:         if ($hostdom{$tryserver} eq $dom) {
 2199:             %{$personnel{$tryserver}}=();
 2200:             foreach my $line (
 2201:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2202:                    &escape($startdate).':'.&escape($enddate).':'.
 2203:                    &escape($rolelist), $tryserver))) {
 2204:                 my ($key,$value) = split(/\=/,$line,2);
 2205:                 if (($key) && ($value)) {
 2206:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2207:                 }
 2208:             }
 2209:         }
 2210:     }
 2211:     return %personnel;
 2212: }
 2213: 
 2214: # ----------------------------------------------------------- Check out an item
 2215: 
 2216: sub get_first_access {
 2217:     my ($type,$argsymb)=@_;
 2218:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2219:     if ($argsymb) { $symb=$argsymb; }
 2220:     my ($map,$id,$res)=&decode_symb($symb);
 2221:     if ($type eq 'map') {
 2222: 	$res=&symbread($map);
 2223:     } else {
 2224: 	$res=$symb;
 2225:     }
 2226:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2227:     return $times{"$courseid\0$res"};
 2228: }
 2229: 
 2230: sub set_first_access {
 2231:     my ($type)=@_;
 2232:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2233:     my ($map,$id,$res)=&decode_symb($symb);
 2234:     if ($type eq 'map') {
 2235: 	$res=&symbread($map);
 2236:     } else {
 2237: 	$res=$symb;
 2238:     }
 2239:     my $firstaccess=&get_first_access($type,$symb);
 2240:     if (!$firstaccess) {
 2241: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2242:     }
 2243:     return 'already_set';
 2244: }
 2245: 
 2246: sub checkout {
 2247:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2248:     my $now=time;
 2249:     my $lonhost=$perlvar{'lonHostID'};
 2250:     my $infostr=&escape(
 2251:                  'CHECKOUTTOKEN&'.
 2252:                  $tuname.'&'.
 2253:                  $tudom.'&'.
 2254:                  $tcrsid.'&'.
 2255:                  $symb.'&'.
 2256: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2257:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2258:     if ($token=~/^error\:/) { 
 2259:         &logthis("<font color=\"blue\">WARNING: ".
 2260:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2261:                  "</font>");
 2262:         return ''; 
 2263:     }
 2264: 
 2265:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2266:     $token=~tr/a-z/A-Z/;
 2267: 
 2268:     my %infohash=('resource.0.outtoken' => $token,
 2269:                   'resource.0.checkouttime' => $now,
 2270:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2271: 
 2272:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2273:        return '';
 2274:     } else {
 2275:         &logthis("<font color=\"blue\">WARNING: ".
 2276:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2277:                  "</font>");
 2278:     }    
 2279: 
 2280:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2281:                          &escape('Checkout '.$infostr.' - '.
 2282:                                                  $token)) ne 'ok') {
 2283: 	return '';
 2284:     } else {
 2285:         &logthis("<font color=\"blue\">WARNING: ".
 2286:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2287:                  "</font>");
 2288:     }
 2289:     return $token;
 2290: }
 2291: 
 2292: # ------------------------------------------------------------ Check in an item
 2293: 
 2294: sub checkin {
 2295:     my $token=shift;
 2296:     my $now=time;
 2297:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2298:     $lonhost=~tr/A-Z/a-z/;
 2299:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2300:     $dtoken=~s/\W/\_/g;
 2301:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2302:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2303: 
 2304:     unless (($tuname) && ($tudom)) {
 2305:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2306:         return '';
 2307:     }
 2308:     
 2309:     unless (&allowed('mgr',$tcrsid)) {
 2310:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2311:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2312:         return '';
 2313:     }
 2314: 
 2315:     my %infohash=('resource.0.intoken' => $token,
 2316:                   'resource.0.checkintime' => $now,
 2317:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2318: 
 2319:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2320:        return '';
 2321:     }    
 2322: 
 2323:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2324:                          &escape('Checkin - '.$token)) ne 'ok') {
 2325: 	return '';
 2326:     }
 2327: 
 2328:     return ($symb,$tuname,$tudom,$tcrsid);    
 2329: }
 2330: 
 2331: # --------------------------------------------- Set Expire Date for Spreadsheet
 2332: 
 2333: sub expirespread {
 2334:     my ($uname,$udom,$stype,$usymb)=@_;
 2335:     my $cid=$env{'request.course.id'}; 
 2336:     if ($cid) {
 2337:        my $now=time;
 2338:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2339:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2340:                             $env{'course.'.$cid.'.num'}.
 2341: 	        	    ':nohist_expirationdates:'.
 2342:                             &escape($key).'='.$now,
 2343:                             $env{'course.'.$cid.'.home'})
 2344:     }
 2345:     return 'ok';
 2346: }
 2347: 
 2348: # ----------------------------------------------------- Devalidate Spreadsheets
 2349: 
 2350: sub devalidate {
 2351:     my ($symb,$uname,$udom)=@_;
 2352:     my $cid=$env{'request.course.id'}; 
 2353:     if ($cid) {
 2354:         # delete the stored spreadsheets for
 2355:         # - the student level sheet of this user in course's homespace
 2356:         # - the assessment level sheet for this resource 
 2357:         #   for this user in user's homespace
 2358: 	# - current conditional state info
 2359: 	my $key=$uname.':'.$udom.':';
 2360:         my $status=
 2361: 	    &del('nohist_calculatedsheets',
 2362: 		 [$key.'studentcalc:'],
 2363: 		 $env{'course.'.$cid.'.domain'},
 2364: 		 $env{'course.'.$cid.'.num'})
 2365: 		.' '.
 2366: 	    &del('nohist_calculatedsheets_'.$cid,
 2367: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2368:         unless ($status eq 'ok ok') {
 2369:            &logthis('Could not devalidate spreadsheet '.
 2370:                     $uname.' at '.$udom.' for '.
 2371: 		    $symb.': '.$status);
 2372:         }
 2373: 	&delenv('user.state.'.$cid);
 2374:     }
 2375: }
 2376: 
 2377: sub get_scalar {
 2378:     my ($string,$end) = @_;
 2379:     my $value;
 2380:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2381: 	$value = $1;
 2382:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2383: 	$value = $1;
 2384:     }
 2385:     return &unescape($value);
 2386: }
 2387: 
 2388: sub array2str {
 2389:   my (@array) = @_;
 2390:   my $result=&arrayref2str(\@array);
 2391:   $result=~s/^__ARRAY_REF__//;
 2392:   $result=~s/__END_ARRAY_REF__$//;
 2393:   return $result;
 2394: }
 2395: 
 2396: sub arrayref2str {
 2397:   my ($arrayref) = @_;
 2398:   my $result='__ARRAY_REF__';
 2399:   foreach my $elem (@$arrayref) {
 2400:     if(ref($elem) eq 'ARRAY') {
 2401:       $result.=&arrayref2str($elem).'&';
 2402:     } elsif(ref($elem) eq 'HASH') {
 2403:       $result.=&hashref2str($elem).'&';
 2404:     } elsif(ref($elem)) {
 2405:       #print("Got a ref of ".(ref($elem))." skipping.");
 2406:     } else {
 2407:       $result.=&escape($elem).'&';
 2408:     }
 2409:   }
 2410:   $result=~s/\&$//;
 2411:   $result .= '__END_ARRAY_REF__';
 2412:   return $result;
 2413: }
 2414: 
 2415: sub hash2str {
 2416:   my (%hash) = @_;
 2417:   my $result=&hashref2str(\%hash);
 2418:   $result=~s/^__HASH_REF__//;
 2419:   $result=~s/__END_HASH_REF__$//;
 2420:   return $result;
 2421: }
 2422: 
 2423: sub hashref2str {
 2424:   my ($hashref)=@_;
 2425:   my $result='__HASH_REF__';
 2426:   foreach my $key (sort(keys(%$hashref))) {
 2427:     if (ref($key) eq 'ARRAY') {
 2428:       $result.=&arrayref2str($key).'=';
 2429:     } elsif (ref($key) eq 'HASH') {
 2430:       $result.=&hashref2str($key).'=';
 2431:     } elsif (ref($key)) {
 2432:       $result.='=';
 2433:       #print("Got a ref of ".(ref($key))." skipping.");
 2434:     } else {
 2435: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2436:     }
 2437: 
 2438:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2439:       $result.=&arrayref2str($hashref->{$key}).'&';
 2440:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2441:       $result.=&hashref2str($hashref->{$key}).'&';
 2442:     } elsif(ref($hashref->{$key})) {
 2443:        $result.='&';
 2444:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2445:     } else {
 2446:       $result.=&escape($hashref->{$key}).'&';
 2447:     }
 2448:   }
 2449:   $result=~s/\&$//;
 2450:   $result .= '__END_HASH_REF__';
 2451:   return $result;
 2452: }
 2453: 
 2454: sub str2hash {
 2455:     my ($string)=@_;
 2456:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2457:     return %$hash;
 2458: }
 2459: 
 2460: sub str2hashref {
 2461:   my ($string) = @_;
 2462: 
 2463:   my %hash;
 2464: 
 2465:   if($string !~ /^__HASH_REF__/) {
 2466:       if (! ($string eq '' || !defined($string))) {
 2467: 	  $hash{'error'}='Not hash reference';
 2468:       }
 2469:       return (\%hash, $string);
 2470:   }
 2471: 
 2472:   $string =~ s/^__HASH_REF__//;
 2473: 
 2474:   while($string !~ /^__END_HASH_REF__/) {
 2475:       #key
 2476:       my $key='';
 2477:       if($string =~ /^__HASH_REF__/) {
 2478:           ($key, $string)=&str2hashref($string);
 2479:           if(defined($key->{'error'})) {
 2480:               $hash{'error'}='Bad data';
 2481:               return (\%hash, $string);
 2482:           }
 2483:       } elsif($string =~ /^__ARRAY_REF__/) {
 2484:           ($key, $string)=&str2arrayref($string);
 2485:           if($key->[0] eq 'Array reference error') {
 2486:               $hash{'error'}='Bad data';
 2487:               return (\%hash, $string);
 2488:           }
 2489:       } else {
 2490:           $string =~ s/^(.*?)=//;
 2491: 	  $key=&unescape($1);
 2492:       }
 2493:       $string =~ s/^=//;
 2494: 
 2495:       #value
 2496:       my $value='';
 2497:       if($string =~ /^__HASH_REF__/) {
 2498:           ($value, $string)=&str2hashref($string);
 2499:           if(defined($value->{'error'})) {
 2500:               $hash{'error'}='Bad data';
 2501:               return (\%hash, $string);
 2502:           }
 2503:       } elsif($string =~ /^__ARRAY_REF__/) {
 2504:           ($value, $string)=&str2arrayref($string);
 2505:           if($value->[0] eq 'Array reference error') {
 2506:               $hash{'error'}='Bad data';
 2507:               return (\%hash, $string);
 2508:           }
 2509:       } else {
 2510: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2511:       }
 2512:       $string =~ s/^&//;
 2513: 
 2514:       $hash{$key}=$value;
 2515:   }
 2516: 
 2517:   $string =~ s/^__END_HASH_REF__//;
 2518: 
 2519:   return (\%hash, $string);
 2520: }
 2521: 
 2522: sub str2array {
 2523:     my ($string)=@_;
 2524:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2525:     return @$array;
 2526: }
 2527: 
 2528: sub str2arrayref {
 2529:   my ($string) = @_;
 2530:   my @array;
 2531: 
 2532:   if($string !~ /^__ARRAY_REF__/) {
 2533:       if (! ($string eq '' || !defined($string))) {
 2534: 	  $array[0]='Array reference error';
 2535:       }
 2536:       return (\@array, $string);
 2537:   }
 2538: 
 2539:   $string =~ s/^__ARRAY_REF__//;
 2540: 
 2541:   while($string !~ /^__END_ARRAY_REF__/) {
 2542:       my $value='';
 2543:       if($string =~ /^__HASH_REF__/) {
 2544:           ($value, $string)=&str2hashref($string);
 2545:           if(defined($value->{'error'})) {
 2546:               $array[0] ='Array reference error';
 2547:               return (\@array, $string);
 2548:           }
 2549:       } elsif($string =~ /^__ARRAY_REF__/) {
 2550:           ($value, $string)=&str2arrayref($string);
 2551:           if($value->[0] eq 'Array reference error') {
 2552:               $array[0] ='Array reference error';
 2553:               return (\@array, $string);
 2554:           }
 2555:       } else {
 2556: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2557:       }
 2558:       $string =~ s/^&//;
 2559: 
 2560:       push(@array, $value);
 2561:   }
 2562: 
 2563:   $string =~ s/^__END_ARRAY_REF__//;
 2564: 
 2565:   return (\@array, $string);
 2566: }
 2567: 
 2568: # -------------------------------------------------------------------Temp Store
 2569: 
 2570: sub tmpreset {
 2571:   my ($symb,$namespace,$domain,$stuname) = @_;
 2572:   if (!$symb) {
 2573:     $symb=&symbread();
 2574:     if (!$symb) { $symb= $env{'request.url'}; }
 2575:   }
 2576:   $symb=escape($symb);
 2577: 
 2578:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2579:   $namespace=~s/\//\_/g;
 2580:   $namespace=~s/\W//g;
 2581: 
 2582:   if (!$domain) { $domain=$env{'user.domain'}; }
 2583:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2584:   if ($domain eq 'public' && $stuname eq 'public') {
 2585:       $stuname=$ENV{'REMOTE_ADDR'};
 2586:   }
 2587:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2588:   my %hash;
 2589:   if (tie(%hash,'GDBM_File',
 2590: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2591: 	  &GDBM_WRCREAT(),0640)) {
 2592:     foreach my $key (keys %hash) {
 2593:       if ($key=~ /:$symb/) {
 2594: 	delete($hash{$key});
 2595:       }
 2596:     }
 2597:   }
 2598: }
 2599: 
 2600: sub tmpstore {
 2601:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2602: 
 2603:   if (!$symb) {
 2604:     $symb=&symbread();
 2605:     if (!$symb) { $symb= $env{'request.url'}; }
 2606:   }
 2607:   $symb=escape($symb);
 2608: 
 2609:   if (!$namespace) {
 2610:     # I don't think we would ever want to store this for a course.
 2611:     # it seems this will only be used if we don't have a course.
 2612:     #$namespace=$env{'request.course.id'};
 2613:     #if (!$namespace) {
 2614:       $namespace=$env{'request.state'};
 2615:     #}
 2616:   }
 2617:   $namespace=~s/\//\_/g;
 2618:   $namespace=~s/\W//g;
 2619:   if (!$domain) { $domain=$env{'user.domain'}; }
 2620:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2621:   if ($domain eq 'public' && $stuname eq 'public') {
 2622:       $stuname=$ENV{'REMOTE_ADDR'};
 2623:   }
 2624:   my $now=time;
 2625:   my %hash;
 2626:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2627:   if (tie(%hash,'GDBM_File',
 2628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2629: 	  &GDBM_WRCREAT(),0640)) {
 2630:     $hash{"version:$symb"}++;
 2631:     my $version=$hash{"version:$symb"};
 2632:     my $allkeys=''; 
 2633:     foreach my $key (keys(%$storehash)) {
 2634:       $allkeys.=$key.':';
 2635:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2636:     }
 2637:     $hash{"$version:$symb:timestamp"}=$now;
 2638:     $allkeys.='timestamp';
 2639:     $hash{"$version:keys:$symb"}=$allkeys;
 2640:     if (untie(%hash)) {
 2641:       return 'ok';
 2642:     } else {
 2643:       return "error:$!";
 2644:     }
 2645:   } else {
 2646:     return "error:$!";
 2647:   }
 2648: }
 2649: 
 2650: # -----------------------------------------------------------------Temp Restore
 2651: 
 2652: sub tmprestore {
 2653:   my ($symb,$namespace,$domain,$stuname) = @_;
 2654: 
 2655:   if (!$symb) {
 2656:     $symb=&symbread();
 2657:     if (!$symb) { $symb= $env{'request.url'}; }
 2658:   }
 2659:   $symb=escape($symb);
 2660: 
 2661:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2662: 
 2663:   if (!$domain) { $domain=$env{'user.domain'}; }
 2664:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2665:   if ($domain eq 'public' && $stuname eq 'public') {
 2666:       $stuname=$ENV{'REMOTE_ADDR'};
 2667:   }
 2668:   my %returnhash;
 2669:   $namespace=~s/\//\_/g;
 2670:   $namespace=~s/\W//g;
 2671:   my %hash;
 2672:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2673:   if (tie(%hash,'GDBM_File',
 2674: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2675: 	  &GDBM_READER(),0640)) {
 2676:     my $version=$hash{"version:$symb"};
 2677:     $returnhash{'version'}=$version;
 2678:     my $scope;
 2679:     for ($scope=1;$scope<=$version;$scope++) {
 2680:       my $vkeys=$hash{"$scope:keys:$symb"};
 2681:       my @keys=split(/:/,$vkeys);
 2682:       my $key;
 2683:       $returnhash{"$scope:keys"}=$vkeys;
 2684:       foreach $key (@keys) {
 2685: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2686: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2687:       }
 2688:     }
 2689:     if (!(untie(%hash))) {
 2690:       return "error:$!";
 2691:     }
 2692:   } else {
 2693:     return "error:$!";
 2694:   }
 2695:   return %returnhash;
 2696: }
 2697: 
 2698: # ----------------------------------------------------------------------- Store
 2699: 
 2700: sub store {
 2701:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2702:     my $home='';
 2703: 
 2704:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2705: 
 2706:     $symb=&symbclean($symb);
 2707:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2708: 
 2709:     if (!$domain) { $domain=$env{'user.domain'}; }
 2710:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2711: 
 2712:     &devalidate($symb,$stuname,$domain);
 2713: 
 2714:     $symb=escape($symb);
 2715:     if (!$namespace) { 
 2716:        unless ($namespace=$env{'request.course.id'}) { 
 2717:           return ''; 
 2718:        } 
 2719:     }
 2720:     if (!$home) { $home=$env{'user.home'}; }
 2721: 
 2722:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2723:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2724: 
 2725:     my $namevalue='';
 2726:     foreach my $key (keys(%$storehash)) {
 2727:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2728:     }
 2729:     $namevalue=~s/\&$//;
 2730:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2731:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2732: }
 2733: 
 2734: # -------------------------------------------------------------- Critical Store
 2735: 
 2736: sub cstore {
 2737:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2738:     my $home='';
 2739: 
 2740:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2741: 
 2742:     $symb=&symbclean($symb);
 2743:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2744: 
 2745:     if (!$domain) { $domain=$env{'user.domain'}; }
 2746:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2747: 
 2748:     &devalidate($symb,$stuname,$domain);
 2749: 
 2750:     $symb=escape($symb);
 2751:     if (!$namespace) { 
 2752:        unless ($namespace=$env{'request.course.id'}) { 
 2753:           return ''; 
 2754:        } 
 2755:     }
 2756:     if (!$home) { $home=$env{'user.home'}; }
 2757: 
 2758:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2759:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2760: 
 2761:     my $namevalue='';
 2762:     foreach my $key (keys(%$storehash)) {
 2763:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2764:     }
 2765:     $namevalue=~s/\&$//;
 2766:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2767:     return critical
 2768:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2769: }
 2770: 
 2771: # --------------------------------------------------------------------- Restore
 2772: 
 2773: sub restore {
 2774:     my ($symb,$namespace,$domain,$stuname) = @_;
 2775:     my $home='';
 2776: 
 2777:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2778: 
 2779:     if (!$symb) {
 2780:       unless ($symb=escape(&symbread())) { return ''; }
 2781:     } else {
 2782:       $symb=&escape(&symbclean($symb));
 2783:     }
 2784:     if (!$namespace) { 
 2785:        unless ($namespace=$env{'request.course.id'}) { 
 2786:           return ''; 
 2787:        } 
 2788:     }
 2789:     if (!$domain) { $domain=$env{'user.domain'}; }
 2790:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2791:     if (!$home) { $home=$env{'user.home'}; }
 2792:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2793: 
 2794:     my %returnhash=();
 2795:     foreach my $line (split(/\&/,$answer)) {
 2796: 	my ($name,$value)=split(/\=/,$line);
 2797:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2798:     }
 2799:     my $version;
 2800:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2801:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2802:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2803:        }
 2804:     }
 2805:     return %returnhash;
 2806: }
 2807: 
 2808: # ---------------------------------------------------------- Course Description
 2809: 
 2810: sub coursedescription {
 2811:     my ($courseid,$args)=@_;
 2812:     $courseid=~s/^\///;
 2813:     $courseid=~s/\_/\//g;
 2814:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2815:     my $chome=&homeserver($cnum,$cdomain);
 2816:     my $normalid=$cdomain.'_'.$cnum;
 2817:     # need to always cache even if we get errors otherwise we keep 
 2818:     # trying and trying and trying to get the course description.
 2819:     my %envhash=();
 2820:     my %returnhash=();
 2821:     
 2822:     my $expiretime=600;
 2823:     if ($env{'request.course.id'} eq $normalid) {
 2824: 	$expiretime=120;
 2825:     }
 2826: 
 2827:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2828:     if (!$args->{'freshen_cache'}
 2829: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2830: 	foreach my $key (keys(%env)) {
 2831: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2832: 	    my ($setting) = $1;
 2833: 	    $returnhash{$setting} = $env{$key};
 2834: 	}
 2835: 	return %returnhash;
 2836:     }
 2837: 
 2838:     # get the data agin
 2839:     if (!$args->{'one_time'}) {
 2840: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2841:     }
 2842: 
 2843:     if ($chome ne 'no_host') {
 2844:        %returnhash=&dump('environment',$cdomain,$cnum);
 2845:        if (!exists($returnhash{'con_lost'})) {
 2846:            $returnhash{'home'}= $chome;
 2847: 	   $returnhash{'domain'} = $cdomain;
 2848: 	   $returnhash{'num'} = $cnum;
 2849:            if (!defined($returnhash{'type'})) {
 2850:                $returnhash{'type'} = 'Course';
 2851:            }
 2852:            while (my ($name,$value) = each %returnhash) {
 2853:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2854:            }
 2855:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2856:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2857: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2858:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2859:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2860:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2861:        }
 2862:     }
 2863:     if (!$args->{'one_time'}) {
 2864: 	&appenv(%envhash);
 2865:     }
 2866:     return %returnhash;
 2867: }
 2868: 
 2869: # -------------------------------------------------See if a user is privileged
 2870: 
 2871: sub privileged {
 2872:     my ($username,$domain)=@_;
 2873:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2874: 			&homeserver($username,$domain));
 2875:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2876:     my $now=time;
 2877:     if ($rolesdump ne '') {
 2878:         foreach my $entry (split(/&/,$rolesdump)) {
 2879: 	    if ($entry!~/^rolesdef_/) {
 2880: 		my ($area,$role)=split(/=/,$entry);
 2881: 		$area=~s/\_\w\w$//;
 2882: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2883: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2884: 		    my $active=1;
 2885: 		    if ($tend) {
 2886: 			if ($tend<$now) { $active=0; }
 2887: 		    }
 2888: 		    if ($tstart) {
 2889: 			if ($tstart>$now) { $active=0; }
 2890: 		    }
 2891: 		    if ($active) { return 1; }
 2892: 		}
 2893: 	    }
 2894: 	}
 2895:     }
 2896:     return 0;
 2897: }
 2898: 
 2899: # -------------------------------------------------------- Get user privileges
 2900: 
 2901: sub rolesinit {
 2902:     my ($domain,$username,$authhost)=@_;
 2903:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2904:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2905:     my %allroles=();
 2906:     my %allgroups=();   
 2907:     my $now=time;
 2908:     my %userroles = ('user.login.time' => $now);
 2909:     my $group_privs;
 2910: 
 2911:     if ($rolesdump ne '') {
 2912:         foreach my $entry (split(/&/,$rolesdump)) {
 2913: 	  if ($entry!~/^rolesdef_/) {
 2914:             my ($area,$role)=split(/=/,$entry);
 2915: 	    $area=~s/\_\w\w$//;
 2916:             my ($trole,$tend,$tstart,$group_privs);
 2917: 	    if ($role=~/^cr/) { 
 2918: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 2919: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 2920: 		    ($tend,$tstart)=split('_',$trest);
 2921: 		} else {
 2922: 		    $trole=$role;
 2923: 		}
 2924:             } elsif ($role =~ m|^gr/|) {
 2925:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2926:                 ($trole,$group_privs) = split(/\//,$trole);
 2927:                 $group_privs = &unescape($group_privs);
 2928: 	    } else {
 2929: 		($trole,$tend,$tstart)=split(/_/,$role);
 2930: 	    }
 2931: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2932: 					 $username);
 2933: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2934:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2935:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2936:             if (($area ne '') && ($trole ne '')) {
 2937: 		my $spec=$trole.'.'.$area;
 2938: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2939: 		if ($trole =~ /^cr\//) {
 2940:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2941:                 } elsif ($trole eq 'gr') {
 2942:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2943: 		} else {
 2944:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2945: 		}
 2946:             }
 2947:           }
 2948:         }
 2949:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2950:         $userroles{'user.adv'}    = $adv;
 2951: 	$userroles{'user.author'} = $author;
 2952:         $env{'user.adv'}=$adv;
 2953:     }
 2954:     return \%userroles;  
 2955: }
 2956: 
 2957: sub set_arearole {
 2958:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2959: # log the associated role with the area
 2960:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2961:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2962: }
 2963: 
 2964: sub custom_roleprivs {
 2965:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2966:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2967:     my $homsvr=homeserver($rauthor,$rdomain);
 2968:     if (&hostname($homsvr) ne '') {
 2969:         my ($rdummy,$roledef)=
 2970:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2971:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2972:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2973:             if (defined($syspriv)) {
 2974:                 $$allroles{'cm./'}.=':'.$syspriv;
 2975:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2976:             }
 2977:             if ($tdomain ne '') {
 2978:                 if (defined($dompriv)) {
 2979:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2980:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2981:                 }
 2982:                 if (($trest ne '') && (defined($coursepriv))) {
 2983:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2984:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2985:                 }
 2986:             }
 2987:         }
 2988:     }
 2989: }
 2990: 
 2991: sub group_roleprivs {
 2992:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2993:     my $access = 1;
 2994:     my $now = time;
 2995:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2996:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2997:     if ($access) {
 2998:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 2999:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3000:     }
 3001: }
 3002: 
 3003: sub standard_roleprivs {
 3004:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3005:     if (defined($pr{$trole.':s'})) {
 3006:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3007:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3008:     }
 3009:     if ($tdomain ne '') {
 3010:         if (defined($pr{$trole.':d'})) {
 3011:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3012:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3013:         }
 3014:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3015:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3016:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3017:         }
 3018:     }
 3019: }
 3020: 
 3021: sub set_userprivs {
 3022:     my ($userroles,$allroles,$allgroups) = @_; 
 3023:     my $author=0;
 3024:     my $adv=0;
 3025:     my %grouproles = ();
 3026:     if (keys(%{$allgroups}) > 0) {
 3027:         foreach my $role (keys %{$allroles}) {
 3028:             my ($trole,$area,$sec,$extendedarea);
 3029:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3030:                 $trole = $1;
 3031:                 $area = $2;
 3032:                 $sec = $3;
 3033:                 $extendedarea = $area.$sec;
 3034:                 if (exists($$allgroups{$area})) {
 3035:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3036:                         my $spec = $trole.'.'.$extendedarea;
 3037:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3038:                                                 $$allgroups{$area}{$group};
 3039:                     }
 3040:                 }
 3041:             }
 3042:         }
 3043:     }
 3044:     foreach my $group (keys(%grouproles)) {
 3045:         $$allroles{$group} = $grouproles{$group};
 3046:     }
 3047:     foreach my $role (keys(%{$allroles})) {
 3048:         my %thesepriv;
 3049:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3050:         foreach my $item (split(/:/,$$allroles{$role})) {
 3051:             if ($item ne '') {
 3052:                 my ($privilege,$restrictions)=split(/&/,$item);
 3053:                 if ($restrictions eq '') {
 3054:                     $thesepriv{$privilege}='F';
 3055:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3056:                     $thesepriv{$privilege}.=$restrictions;
 3057:                 }
 3058:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3059:             }
 3060:         }
 3061:         my $thesestr='';
 3062:         foreach my $priv (keys(%thesepriv)) {
 3063: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3064: 	}
 3065:         $userroles->{'user.priv.'.$role} = $thesestr;
 3066:     }
 3067:     return ($author,$adv);
 3068: }
 3069: 
 3070: # --------------------------------------------------------------- get interface
 3071: 
 3072: sub get {
 3073:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3074:    my $items='';
 3075:    foreach my $item (@$storearr) {
 3076:        $items.=&escape($item).'&';
 3077:    }
 3078:    $items=~s/\&$//;
 3079:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3080:    if (!$uname) { $uname=$env{'user.name'}; }
 3081:    my $uhome=&homeserver($uname,$udomain);
 3082: 
 3083:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3084:    my @pairs=split(/\&/,$rep);
 3085:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3086:      return @pairs;
 3087:    }
 3088:    my %returnhash=();
 3089:    my $i=0;
 3090:    foreach my $item (@$storearr) {
 3091:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3092:       $i++;
 3093:    }
 3094:    return %returnhash;
 3095: }
 3096: 
 3097: # --------------------------------------------------------------- del interface
 3098: 
 3099: sub del {
 3100:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3101:    my $items='';
 3102:    foreach my $item (@$storearr) {
 3103:        $items.=&escape($item).'&';
 3104:    }
 3105:    $items=~s/\&$//;
 3106:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3107:    if (!$uname) { $uname=$env{'user.name'}; }
 3108:    my $uhome=&homeserver($uname,$udomain);
 3109: 
 3110:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3111: }
 3112: 
 3113: # -------------------------------------------------------------- dump interface
 3114: 
 3115: sub dump {
 3116:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3117:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3118:     if (!$uname) { $uname=$env{'user.name'}; }
 3119:     my $uhome=&homeserver($uname,$udomain);
 3120:     if ($regexp) {
 3121: 	$regexp=&escape($regexp);
 3122:     } else {
 3123: 	$regexp='.';
 3124:     }
 3125:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3126:     my @pairs=split(/\&/,$rep);
 3127:     my %returnhash=();
 3128:     foreach my $item (@pairs) {
 3129: 	my ($key,$value)=split(/=/,$item,2);
 3130: 	$key = &unescape($key);
 3131: 	next if ($key =~ /^error: 2 /);
 3132: 	$returnhash{$key}=&thaw_unescape($value);
 3133:     }
 3134:     return %returnhash;
 3135: }
 3136: 
 3137: # --------------------------------------------------------- dumpstore interface
 3138: 
 3139: sub dumpstore {
 3140:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3141:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3142:    if (!$uname) { $uname=$env{'user.name'}; }
 3143:    my $uhome=&homeserver($uname,$udomain);
 3144:    if ($regexp) {
 3145:        $regexp=&escape($regexp);
 3146:    } else {
 3147:        $regexp='.';
 3148:    }
 3149:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3150:    my @pairs=split(/\&/,$rep);
 3151:    my %returnhash=();
 3152:    foreach my $item (@pairs) {
 3153:        my ($key,$value)=split(/=/,$item,2);
 3154:        next if ($key =~ /^error: 2 /);
 3155:        $returnhash{$key}=&thaw_unescape($value);
 3156:    }
 3157:    return %returnhash;
 3158: }
 3159: 
 3160: # -------------------------------------------------------------- keys interface
 3161: 
 3162: sub getkeys {
 3163:    my ($namespace,$udomain,$uname)=@_;
 3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3165:    if (!$uname) { $uname=$env{'user.name'}; }
 3166:    my $uhome=&homeserver($uname,$udomain);
 3167:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3168:    my @keyarray=();
 3169:    foreach my $key (split(/\&/,$rep)) {
 3170:       next if ($key =~ /^error: 2 /);
 3171:       push(@keyarray,&unescape($key));
 3172:    }
 3173:    return @keyarray;
 3174: }
 3175: 
 3176: # --------------------------------------------------------------- currentdump
 3177: sub currentdump {
 3178:    my ($courseid,$sdom,$sname)=@_;
 3179:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3180:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3181:    $sname    = $env{'user.name'}         if (! defined($sname));
 3182:    my $uhome = &homeserver($sname,$sdom);
 3183:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3184:    return if ($rep =~ /^(error:|no_such_host)/);
 3185:    #
 3186:    my %returnhash=();
 3187:    #
 3188:    if ($rep eq "unknown_cmd") { 
 3189:        # an old lond will not know currentdump
 3190:        # Do a dump and make it look like a currentdump
 3191:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3192:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3193:        my %hash = @tmp;
 3194:        @tmp=();
 3195:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3196:    } else {
 3197:        my @pairs=split(/\&/,$rep);
 3198:        foreach my $pair (@pairs) {
 3199:            my ($key,$value)=split(/=/,$pair,2);
 3200:            my ($symb,$param) = split(/:/,$key);
 3201:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3202:                                                         &thaw_unescape($value);
 3203:        }
 3204:    }
 3205:    return %returnhash;
 3206: }
 3207: 
 3208: sub convert_dump_to_currentdump{
 3209:     my %hash = %{shift()};
 3210:     my %returnhash;
 3211:     # Code ripped from lond, essentially.  The only difference
 3212:     # here is the unescaping done by lonnet::dump().  Conceivably
 3213:     # we might run in to problems with parameter names =~ /^v\./
 3214:     while (my ($key,$value) = each(%hash)) {
 3215:         my ($v,$symb,$param) = split(/:/,$key);
 3216: 	$symb  = &unescape($symb);
 3217: 	$param = &unescape($param);
 3218:         next if ($v eq 'version' || $symb eq 'keys');
 3219:         next if (exists($returnhash{$symb}) &&
 3220:                  exists($returnhash{$symb}->{$param}) &&
 3221:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3222:         $returnhash{$symb}->{$param}=$value;
 3223:         $returnhash{$symb}->{'v.'.$param}=$v;
 3224:     }
 3225:     #
 3226:     # Remove all of the keys in the hashes which keep track of
 3227:     # the version of the parameter.
 3228:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3229:         # use a foreach because we are going to delete from the hash.
 3230:         foreach my $key (keys(%$param_hash)) {
 3231:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3232:         }
 3233:     }
 3234:     return \%returnhash;
 3235: }
 3236: 
 3237: # ------------------------------------------------------ critical inc interface
 3238: 
 3239: sub cinc {
 3240:     return &inc(@_,'critical');
 3241: }
 3242: 
 3243: # --------------------------------------------------------------- inc interface
 3244: 
 3245: sub inc {
 3246:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3247:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3248:     if (!$uname) { $uname=$env{'user.name'}; }
 3249:     my $uhome=&homeserver($uname,$udomain);
 3250:     my $items='';
 3251:     if (! ref($store)) {
 3252:         # got a single value, so use that instead
 3253:         $items = &escape($store).'=&';
 3254:     } elsif (ref($store) eq 'SCALAR') {
 3255:         $items = &escape($$store).'=&';        
 3256:     } elsif (ref($store) eq 'ARRAY') {
 3257:         $items = join('=&',map {&escape($_);} @{$store});
 3258:     } elsif (ref($store) eq 'HASH') {
 3259:         while (my($key,$value) = each(%{$store})) {
 3260:             $items.= &escape($key).'='.&escape($value).'&';
 3261:         }
 3262:     }
 3263:     $items=~s/\&$//;
 3264:     if ($critical) {
 3265: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3266:     } else {
 3267: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3268:     }
 3269: }
 3270: 
 3271: # --------------------------------------------------------------- put interface
 3272: 
 3273: sub put {
 3274:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3275:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3276:    if (!$uname) { $uname=$env{'user.name'}; }
 3277:    my $uhome=&homeserver($uname,$udomain);
 3278:    my $items='';
 3279:    foreach my $item (keys(%$storehash)) {
 3280:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3281:    }
 3282:    $items=~s/\&$//;
 3283:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3284: }
 3285: 
 3286: # ------------------------------------------------------------ newput interface
 3287: 
 3288: sub newput {
 3289:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3290:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3291:    if (!$uname) { $uname=$env{'user.name'}; }
 3292:    my $uhome=&homeserver($uname,$udomain);
 3293:    my $items='';
 3294:    foreach my $key (keys(%$storehash)) {
 3295:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3296:    }
 3297:    $items=~s/\&$//;
 3298:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3299: }
 3300: 
 3301: # ---------------------------------------------------------  putstore interface
 3302: 
 3303: sub putstore {
 3304:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3305:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3306:    if (!$uname) { $uname=$env{'user.name'}; }
 3307:    my $uhome=&homeserver($uname,$udomain);
 3308:    my $items='';
 3309:    foreach my $key (keys(%$storehash)) {
 3310:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3311:    }
 3312:    $items=~s/\&$//;
 3313:    my $esc_symb=&escape($symb);
 3314:    my $esc_v=&escape($version);
 3315:    my $reply =
 3316:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3317: 	      $uhome);
 3318:    if ($reply eq 'unknown_cmd') {
 3319:        # gfall back to way things use to be done
 3320:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3321: 			    $uname);
 3322:    }
 3323:    return $reply;
 3324: }
 3325: 
 3326: sub old_putstore {
 3327:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3328:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3329:     if (!$uname) { $uname=$env{'user.name'}; }
 3330:     my $uhome=&homeserver($uname,$udomain);
 3331:     my %newstorehash;
 3332:     foreach my $item (keys(%$storehash)) {
 3333: 	my $key = $version.':'.&escape($symb).':'.$item;
 3334: 	$newstorehash{$key} = $storehash->{$item};
 3335:     }
 3336:     my $items='';
 3337:     my %allitems = ();
 3338:     foreach my $item (keys(%newstorehash)) {
 3339: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3340: 	    my $key = $1.':keys:'.$2;
 3341: 	    $allitems{$key} .= $3.':';
 3342: 	}
 3343: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3344:     }
 3345:     foreach my $item (keys(%allitems)) {
 3346: 	$allitems{$item} =~ s/\:$//;
 3347: 	$items.= $item.'='.$allitems{$item}.'&';
 3348:     }
 3349:     $items=~s/\&$//;
 3350:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3351: }
 3352: 
 3353: # ------------------------------------------------------ critical put interface
 3354: 
 3355: sub cput {
 3356:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3357:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3358:    if (!$uname) { $uname=$env{'user.name'}; }
 3359:    my $uhome=&homeserver($uname,$udomain);
 3360:    my $items='';
 3361:    foreach my $item (keys(%$storehash)) {
 3362:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3363:    }
 3364:    $items=~s/\&$//;
 3365:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3366: }
 3367: 
 3368: # -------------------------------------------------------------- eget interface
 3369: 
 3370: sub eget {
 3371:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3372:    my $items='';
 3373:    foreach my $item (@$storearr) {
 3374:        $items.=&escape($item).'&';
 3375:    }
 3376:    $items=~s/\&$//;
 3377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3378:    if (!$uname) { $uname=$env{'user.name'}; }
 3379:    my $uhome=&homeserver($uname,$udomain);
 3380:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3381:    my @pairs=split(/\&/,$rep);
 3382:    my %returnhash=();
 3383:    my $i=0;
 3384:    foreach my $item (@$storearr) {
 3385:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3386:       $i++;
 3387:    }
 3388:    return %returnhash;
 3389: }
 3390: 
 3391: # ------------------------------------------------------------ tmpput interface
 3392: sub tmpput {
 3393:     my ($storehash,$server,$context)=@_;
 3394:     my $items='';
 3395:     foreach my $item (keys(%$storehash)) {
 3396: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3397:     }
 3398:     $items=~s/\&$//;
 3399:     if (defined($context)) {
 3400:         $items .= ':'.&escape($context);
 3401:     }
 3402:     return &reply("tmpput:$items",$server);
 3403: }
 3404: 
 3405: # ------------------------------------------------------------ tmpget interface
 3406: sub tmpget {
 3407:     my ($token,$server)=@_;
 3408:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3409:     my $rep=&reply("tmpget:$token",$server);
 3410:     my %returnhash;
 3411:     foreach my $item (split(/\&/,$rep)) {
 3412: 	my ($key,$value)=split(/=/,$item);
 3413: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3414:     }
 3415:     return %returnhash;
 3416: }
 3417: 
 3418: # ------------------------------------------------------------ tmpget interface
 3419: sub tmpdel {
 3420:     my ($token,$server)=@_;
 3421:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3422:     return &reply("tmpdel:$token",$server);
 3423: }
 3424: 
 3425: # -------------------------------------------------- portfolio access checking
 3426: 
 3427: sub portfolio_access {
 3428:     my ($requrl) = @_;
 3429:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3430:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3431:     if ($result) {
 3432:         my %setters;
 3433:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3434:             my ($startblock,$endblock) =
 3435:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3436:             if ($startblock && $endblock) {
 3437:                 return 'B';
 3438:             }
 3439:         } else {
 3440:             my ($startblock,$endblock) =
 3441:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3442:             if ($startblock && $endblock) {
 3443:                 return 'B';
 3444:             }
 3445:         }
 3446:     }
 3447:     if ($result eq 'ok') {
 3448:        return 'F';
 3449:     } elsif ($result =~ /^[^:]+:guest_/) {
 3450:        return 'A';
 3451:     }
 3452:     return '';
 3453: }
 3454: 
 3455: sub get_portfolio_access {
 3456:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3457: 
 3458:     if (!ref($access_hash)) {
 3459: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3460: 	my %access_controls = &get_access_controls($current_perms,$group,
 3461: 						   $file_name);
 3462: 	$access_hash = $access_controls{$file_name};
 3463:     }
 3464: 
 3465:     my ($public,$guest,@domains,@users,@courses,@groups);
 3466:     my $now = time;
 3467:     if (ref($access_hash) eq 'HASH') {
 3468:         foreach my $key (keys(%{$access_hash})) {
 3469:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3470:             if ($start > $now) {
 3471:                 next;
 3472:             }
 3473:             if ($end && $end<$now) {
 3474:                 next;
 3475:             }
 3476:             if ($scope eq 'public') {
 3477:                 $public = $key;
 3478:                 last;
 3479:             } elsif ($scope eq 'guest') {
 3480:                 $guest = $key;
 3481:             } elsif ($scope eq 'domains') {
 3482:                 push(@domains,$key);
 3483:             } elsif ($scope eq 'users') {
 3484:                 push(@users,$key);
 3485:             } elsif ($scope eq 'course') {
 3486:                 push(@courses,$key);
 3487:             } elsif ($scope eq 'group') {
 3488:                 push(@groups,$key);
 3489:             }
 3490:         }
 3491:         if ($public) {
 3492:             return 'ok';
 3493:         }
 3494:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3495:             if ($guest) {
 3496:                 return $guest;
 3497:             }
 3498:         } else {
 3499:             if (@domains > 0) {
 3500:                 foreach my $domkey (@domains) {
 3501:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3502:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3503:                             return 'ok';
 3504:                         }
 3505:                     }
 3506:                 }
 3507:             }
 3508:             if (@users > 0) {
 3509:                 foreach my $userkey (@users) {
 3510:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3511:                         return 'ok';
 3512:                     }
 3513:                 }
 3514:             }
 3515:             my %roleshash;
 3516:             my @courses_and_groups = @courses;
 3517:             push(@courses_and_groups,@groups); 
 3518:             if (@courses_and_groups > 0) {
 3519:                 my (%allgroups,%allroles); 
 3520:                 my ($start,$end,$role,$sec,$group);
 3521:                 foreach my $envkey (%env) {
 3522:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3523:                         my $cid = $2.'_'.$3; 
 3524:                         if ($1 eq 'gr') {
 3525:                             $group = $4;
 3526:                             $allgroups{$cid}{$group} = $env{$envkey};
 3527:                         } else {
 3528:                             if ($4 eq '') {
 3529:                                 $sec = 'none';
 3530:                             } else {
 3531:                                 $sec = $4;
 3532:                             }
 3533:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3534:                         }
 3535:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3536:                         my $cid = $2.'_'.$3;
 3537:                         if ($4 eq '') {
 3538:                             $sec = 'none';
 3539:                         } else {
 3540:                             $sec = $4;
 3541:                         }
 3542:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3543:                     }
 3544:                 }
 3545:                 if (keys(%allroles) == 0) {
 3546:                     return;
 3547:                 }
 3548:                 foreach my $key (@courses_and_groups) {
 3549:                     my %content = %{$$access_hash{$key}};
 3550:                     my $cnum = $content{'number'};
 3551:                     my $cdom = $content{'domain'};
 3552:                     my $cid = $cdom.'_'.$cnum;
 3553:                     if (!exists($allroles{$cid})) {
 3554:                         next;
 3555:                     }    
 3556:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3557:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3558:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3559:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3560:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3561:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3562:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3563:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3564:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3565:                                         if (grep/^all$/,@sections) {
 3566:                                             return 'ok';
 3567:                                         } else {
 3568:                                             if (grep/^$sec$/,@sections) {
 3569:                                                 return 'ok';
 3570:                                             }
 3571:                                         }
 3572:                                     }
 3573:                                 }
 3574:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3575:                                     if (grep/^none$/,@groups) {
 3576:                                         return 'ok';
 3577:                                     }
 3578:                                 } else {
 3579:                                     if (grep/^all$/,@groups) {
 3580:                                         return 'ok';
 3581:                                     } 
 3582:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3583:                                         if (grep/^$group$/,@groups) {
 3584:                                             return 'ok';
 3585:                                         }
 3586:                                     }
 3587:                                 } 
 3588:                             }
 3589:                         }
 3590:                     }
 3591:                 }
 3592:             }
 3593:             if ($guest) {
 3594:                 return $guest;
 3595:             }
 3596:         }
 3597:     }
 3598:     return;
 3599: }
 3600: 
 3601: sub course_group_datechecker {
 3602:     my ($dates,$now,$status) = @_;
 3603:     my ($start,$end) = split(/\./,$dates);
 3604:     if (!$start && !$end) {
 3605:         return 'ok';
 3606:     }
 3607:     if (grep/^active$/,@{$status}) {
 3608:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3609:             return 'ok';
 3610:         }
 3611:     }
 3612:     if (grep/^previous$/,@{$status}) {
 3613:         if ($end > $now ) {
 3614:             return 'ok';
 3615:         }
 3616:     }
 3617:     if (grep/^future$/,@{$status}) {
 3618:         if ($start > $now) {
 3619:             return 'ok';
 3620:         }
 3621:     }
 3622:     return; 
 3623: }
 3624: 
 3625: sub parse_portfolio_url {
 3626:     my ($url) = @_;
 3627: 
 3628:     my ($type,$udom,$unum,$group,$file_name);
 3629:     
 3630:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3631: 	$type = 1;
 3632:         $udom = $1;
 3633:         $unum = $2;
 3634:         $file_name = $3;
 3635:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3636: 	$type = 2;
 3637:         $udom = $1;
 3638:         $unum = $2;
 3639:         $group = $3;
 3640:         $file_name = $3.'/'.$4;
 3641:     }
 3642:     if (wantarray) {
 3643: 	return ($type,$udom,$unum,$file_name,$group);
 3644:     }
 3645:     return $type;
 3646: }
 3647: 
 3648: sub is_portfolio_url {
 3649:     my ($url) = @_;
 3650:     return scalar(&parse_portfolio_url($url));
 3651: }
 3652: 
 3653: sub is_portfolio_file {
 3654:     my ($file) = @_;
 3655:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3656:         return 1;
 3657:     }
 3658:     return;
 3659: }
 3660: 
 3661: 
 3662: # ---------------------------------------------- Custom access rule evaluation
 3663: 
 3664: sub customaccess {
 3665:     my ($priv,$uri)=@_;
 3666:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3667:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3668:     $udom = &LONCAPA::clean_domain($udom);
 3669:     $ucrs = &LONCAPA::clean_username($ucrs);
 3670:     my $access=0;
 3671:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3672: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3673:         if ($role) {
 3674: 	   if ($role ne $urole) { next; }
 3675:         }
 3676:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3677:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3678:             if ($tdom) {
 3679: 		if ($tdom ne $udom) { next; }
 3680:             }
 3681:             if ($tcrs) {
 3682: 		if ($tcrs ne $ucrs) { next; }
 3683:             }
 3684:             if ($tsec) {
 3685: 		if ($tsec ne $usec) { next; }
 3686:             }
 3687:             $access=($effect eq 'allow');
 3688:             last;
 3689:         }
 3690: 	if ($realm eq '' && $role eq '') {
 3691:             $access=($effect eq 'allow');
 3692: 	}
 3693:     }
 3694:     return $access;
 3695: }
 3696: 
 3697: # ------------------------------------------------- Check for a user privilege
 3698: 
 3699: sub allowed {
 3700:     my ($priv,$uri,$symb,$role)=@_;
 3701:     my $ver_orguri=$uri;
 3702:     $uri=&deversion($uri);
 3703:     my $orguri=$uri;
 3704:     $uri=&declutter($uri);
 3705: 
 3706:     if ($priv eq 'evb') {
 3707: # Evade communication block restrictions for specified role in a course
 3708:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3709:             return $1;
 3710:         } else {
 3711:             return;
 3712:         }
 3713:     }
 3714: 
 3715:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3716: # Free bre access to adm and meta resources
 3717:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3718: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3719: 	&& ($priv eq 'bre')) {
 3720: 	return 'F';
 3721:     }
 3722: 
 3723: # Free bre access to user's own portfolio contents
 3724:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3725:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3726: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3727:         my %setters;
 3728:         my ($startblock,$endblock) = 
 3729:             &Apache::loncommon::blockcheck(\%setters,'port');
 3730:         if ($startblock && $endblock) {
 3731:             return 'B';
 3732:         } else {
 3733:             return 'F';
 3734:         }
 3735:     }
 3736: 
 3737: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3738:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3739:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3740:         if (exists($env{'request.course.id'})) {
 3741:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3742:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3743:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3744:                 my $courseprivid=$env{'request.course.id'};
 3745:                 $courseprivid=~s/\_/\//;
 3746:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3747:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3748:                     return $1; 
 3749:                 } else {
 3750:                     if ($env{'request.course.sec'}) {
 3751:                         $courseprivid.='/'.$env{'request.course.sec'};
 3752:                     }
 3753:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3754:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3755:                         return $2;
 3756:                     }
 3757:                 }
 3758:             }
 3759:         }
 3760:     }
 3761: 
 3762: # Free bre to public access
 3763: 
 3764:     if ($priv eq 'bre') {
 3765:         my $copyright=&metadata($uri,'copyright');
 3766: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3767:            return 'F'; 
 3768:         }
 3769:         if ($copyright eq 'priv') {
 3770:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3771: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3772: 		return '';
 3773:             }
 3774:         }
 3775:         if ($copyright eq 'domain') {
 3776:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3777: 	    unless (($env{'user.domain'} eq $1) ||
 3778:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3779: 		return '';
 3780:             }
 3781:         }
 3782:         if ($env{'request.role'}=~ /li\.\//) {
 3783:             # Library role, so allow browsing of resources in this domain.
 3784:             return 'F';
 3785:         }
 3786:         if ($copyright eq 'custom') {
 3787: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3788:         }
 3789:     }
 3790:     # Domain coordinator is trying to create a course
 3791:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3792:         # uri is the requested domain in this case.
 3793:         # comparison to 'request.role.domain' shows if the user has selected
 3794:         # a role of dc for the domain in question.
 3795:         return 'F' if ($uri eq $env{'request.role.domain'});
 3796:     }
 3797: 
 3798:     my $thisallowed='';
 3799:     my $statecond=0;
 3800:     my $courseprivid='';
 3801: 
 3802: # Course
 3803: 
 3804:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3805:        $thisallowed.=$1;
 3806:     }
 3807: 
 3808: # Domain
 3809: 
 3810:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3811:        =~/\Q$priv\E\&([^\:]*)/) {
 3812:        $thisallowed.=$1;
 3813:     }
 3814: 
 3815: # Course: uri itself is a course
 3816:     my $courseuri=$uri;
 3817:     $courseuri=~s/\_(\d)/\/$1/;
 3818:     $courseuri=~s/^([^\/])/\/$1/;
 3819: 
 3820:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3821:        =~/\Q$priv\E\&([^\:]*)/) {
 3822:        $thisallowed.=$1;
 3823:     }
 3824: 
 3825: # URI is an uploaded document for this course, default permissions don't matter
 3826: # not allowing 'edit' access (editupload) to uploaded course docs
 3827:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3828: 	$thisallowed='';
 3829:         my ($match)=&is_on_map($uri);
 3830:         if ($match) {
 3831:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3832:                   =~/\Q$priv\E\&([^\:]*)/) {
 3833:                 $thisallowed.=$1;
 3834:             }
 3835:         } else {
 3836:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3837:             if ($refuri) {
 3838:                 if ($refuri =~ m|^/adm/|) {
 3839:                     $thisallowed='F';
 3840:                 } else {
 3841:                     $refuri=&declutter($refuri);
 3842:                     my ($match) = &is_on_map($refuri);
 3843:                     if ($match) {
 3844:                         $thisallowed='F';
 3845:                     }
 3846:                 }
 3847:             }
 3848:         }
 3849:     }
 3850: 
 3851:     if ($priv eq 'bre'
 3852: 	&& $thisallowed ne 'F' 
 3853: 	&& $thisallowed ne '2'
 3854: 	&& &is_portfolio_url($uri)) {
 3855: 	$thisallowed = &portfolio_access($uri);
 3856:     }
 3857:     
 3858: # Full access at system, domain or course-wide level? Exit.
 3859: 
 3860:     if ($thisallowed=~/F/) {
 3861: 	return 'F';
 3862:     }
 3863: 
 3864: # If this is generating or modifying users, exit with special codes
 3865: 
 3866:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3867: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3868: 	    my ($audom,$auname)=split('/',$uri);
 3869: # no author name given, so this just checks on the general right to make a co-author in this domain
 3870: 	    unless ($auname) { return $thisallowed; }
 3871: # an author name is given, so we are about to actually make a co-author for a certain account
 3872: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3873: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3874: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3875: 	}
 3876: 	return $thisallowed;
 3877:     }
 3878: #
 3879: # Gathered so far: system, domain and course wide privileges
 3880: #
 3881: # Course: See if uri or referer is an individual resource that is part of 
 3882: # the course
 3883: 
 3884:     if ($env{'request.course.id'}) {
 3885: 
 3886:        $courseprivid=$env{'request.course.id'};
 3887:        if ($env{'request.course.sec'}) {
 3888:           $courseprivid.='/'.$env{'request.course.sec'};
 3889:        }
 3890:        $courseprivid=~s/\_/\//;
 3891:        my $checkreferer=1;
 3892:        my ($match,$cond)=&is_on_map($uri);
 3893:        if ($match) {
 3894:            $statecond=$cond;
 3895:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3896:                =~/\Q$priv\E\&([^\:]*)/) {
 3897:                $thisallowed.=$1;
 3898:                $checkreferer=0;
 3899:            }
 3900:        }
 3901:        
 3902:        if ($checkreferer) {
 3903: 	  my $refuri=$env{'httpref.'.$orguri};
 3904:             unless ($refuri) {
 3905:                 foreach my $key (keys(%env)) {
 3906: 		    if ($key=~/^httpref\..*\*/) {
 3907: 			my $pattern=$key;
 3908:                         $pattern=~s/^httpref\.\/res\///;
 3909:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3910:                         $pattern=~s/\//\\\//g;
 3911:                         if ($orguri=~/$pattern/) {
 3912: 			    $refuri=$env{$key};
 3913:                         }
 3914:                     }
 3915:                 }
 3916:             }
 3917: 
 3918:          if ($refuri) { 
 3919: 	  $refuri=&declutter($refuri);
 3920:           my ($match,$cond)=&is_on_map($refuri);
 3921:             if ($match) {
 3922:               my $refstatecond=$cond;
 3923:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3924:                   =~/\Q$priv\E\&([^\:]*)/) {
 3925:                   $thisallowed.=$1;
 3926:                   $uri=$refuri;
 3927:                   $statecond=$refstatecond;
 3928:               }
 3929:           }
 3930:         }
 3931:        }
 3932:    }
 3933: 
 3934: #
 3935: # Gathered now: all privileges that could apply, and condition number
 3936: # 
 3937: #
 3938: # Full or no access?
 3939: #
 3940: 
 3941:     if ($thisallowed=~/F/) {
 3942: 	return 'F';
 3943:     }
 3944: 
 3945:     unless ($thisallowed) {
 3946:         return '';
 3947:     }
 3948: 
 3949: # Restrictions exist, deal with them
 3950: #
 3951: #   C:according to course preferences
 3952: #   R:according to resource settings
 3953: #   L:unless locked
 3954: #   X:according to user session state
 3955: #
 3956: 
 3957: # Possibly locked functionality, check all courses
 3958: # Locks might take effect only after 10 minutes cache expiration for other
 3959: # courses, and 2 minutes for current course
 3960: 
 3961:     my $envkey;
 3962:     if ($thisallowed=~/L/) {
 3963:         foreach $envkey (keys %env) {
 3964:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3965:                my $courseid=$2;
 3966:                my $roleid=$1.'.'.$2;
 3967:                $courseid=~s/^\///;
 3968:                my $expiretime=600;
 3969:                if ($env{'request.role'} eq $roleid) {
 3970: 		  $expiretime=120;
 3971:                }
 3972: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3973:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3974:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3975: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3976:                }
 3977:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3978:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3979: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3980:                        &log($env{'user.domain'},$env{'user.name'},
 3981:                             $env{'user.home'},
 3982:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3983:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3984:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3985: 		       return '';
 3986:                    }
 3987:                }
 3988:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3989:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3990: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3991:                        &log($env{'user.domain'},$env{'user.name'},
 3992:                             $env{'user.home'},
 3993:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3994:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3995:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3996: 		       return '';
 3997:                    }
 3998:                }
 3999: 	   }
 4000:        }
 4001:     }
 4002:    
 4003: #
 4004: # Rest of the restrictions depend on selected course
 4005: #
 4006: 
 4007:     unless ($env{'request.course.id'}) {
 4008: 	if ($thisallowed eq 'A') {
 4009: 	    return 'A';
 4010:         } elsif ($thisallowed eq 'B') {
 4011:             return 'B';
 4012: 	} else {
 4013: 	    return '1';
 4014: 	}
 4015:     }
 4016: 
 4017: #
 4018: # Now user is definitely in a course
 4019: #
 4020: 
 4021: 
 4022: # Course preferences
 4023: 
 4024:    if ($thisallowed=~/C/) {
 4025:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4026:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4027:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4028: 	   =~/\Q$rolecode\E/) {
 4029: 	   if ($priv ne 'pch') { 
 4030: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4031: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4032: 			$env{'request.course.id'});
 4033: 	   }
 4034:            return '';
 4035:        }
 4036: 
 4037:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4038: 	   =~/\Q$unamedom\E/) {
 4039: 	   if ($priv ne 'pch') { 
 4040: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4041: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4042: 			$env{'request.course.id'});
 4043: 	   }
 4044:            return '';
 4045:        }
 4046:    }
 4047: 
 4048: # Resource preferences
 4049: 
 4050:    if ($thisallowed=~/R/) {
 4051:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4052:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4053: 	   if ($priv ne 'pch') { 
 4054: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4055: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4056: 	   }
 4057: 	   return '';
 4058:        }
 4059:    }
 4060: 
 4061: # Restricted by state or randomout?
 4062: 
 4063:    if ($thisallowed=~/X/) {
 4064:       if ($env{'acc.randomout'}) {
 4065: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4066:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4067:             return ''; 
 4068:          }
 4069:       }
 4070:       if (&condval($statecond)) {
 4071: 	 return '2';
 4072:       } else {
 4073:          return '';
 4074:       }
 4075:    }
 4076: 
 4077:     if ($thisallowed eq 'A') {
 4078: 	return 'A';
 4079:     } elsif ($thisallowed eq 'B') {
 4080:         return 'B';
 4081:     }
 4082:    return 'F';
 4083: }
 4084: 
 4085: sub split_uri_for_cond {
 4086:     my $uri=&deversion(&declutter(shift));
 4087:     my @uriparts=split(/\//,$uri);
 4088:     my $filename=pop(@uriparts);
 4089:     my $pathname=join('/',@uriparts);
 4090:     return ($pathname,$filename);
 4091: }
 4092: # --------------------------------------------------- Is a resource on the map?
 4093: 
 4094: sub is_on_map {
 4095:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4096:     #Trying to find the conditional for the file
 4097:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4098: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4099:     if ($match) {
 4100: 	return (1,$1);
 4101:     } else {
 4102: 	return (0,0);
 4103:     }
 4104: }
 4105: 
 4106: # --------------------------------------------------------- Get symb from alias
 4107: 
 4108: sub get_symb_from_alias {
 4109:     my $symb=shift;
 4110:     my ($map,$resid,$url)=&decode_symb($symb);
 4111: # Already is a symb
 4112:     if ($url) { return $symb; }
 4113: # Must be an alias
 4114:     my $aliassymb='';
 4115:     my %bighash;
 4116:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4117:                             &GDBM_READER(),0640)) {
 4118:         my $rid=$bighash{'mapalias_'.$symb};
 4119: 	if ($rid) {
 4120: 	    my ($mapid,$resid)=split(/\./,$rid);
 4121: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4122: 				    $resid,$bighash{'src_'.$rid});
 4123: 	}
 4124:         untie %bighash;
 4125:     }
 4126:     return $aliassymb;
 4127: }
 4128: 
 4129: # ----------------------------------------------------------------- Define Role
 4130: 
 4131: sub definerole {
 4132:   if (allowed('mcr','/')) {
 4133:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4134:     foreach my $role (split(':',$sysrole)) {
 4135: 	my ($crole,$cqual)=split(/\&/,$role);
 4136:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4137:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4138: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4139:                return "refused:s:$crole&$cqual"; 
 4140:             }
 4141:         }
 4142:     }
 4143:     foreach my $role (split(':',$domrole)) {
 4144: 	my ($crole,$cqual)=split(/\&/,$role);
 4145:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4146:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4147: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4148:                return "refused:d:$crole&$cqual"; 
 4149:             }
 4150:         }
 4151:     }
 4152:     foreach my $role (split(':',$courole)) {
 4153: 	my ($crole,$cqual)=split(/\&/,$role);
 4154:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4155:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4156: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4157:                return "refused:c:$crole&$cqual"; 
 4158:             }
 4159:         }
 4160:     }
 4161:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4162:                 "$env{'user.domain'}:$env{'user.name'}:".
 4163: 	        "rolesdef_$rolename=".
 4164:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4165:     return reply($command,$env{'user.home'});
 4166:   } else {
 4167:     return 'refused';
 4168:   }
 4169: }
 4170: 
 4171: # ---------------- Make a metadata query against the network of library servers
 4172: 
 4173: sub metadata_query {
 4174:     my ($query,$custom,$customshow,$server_array)=@_;
 4175:     my %rhash;
 4176:     my @server_list = (defined($server_array) ? @$server_array
 4177:                                               : keys(%libserv) );
 4178:     for my $server (@server_list) {
 4179: 	unless ($custom or $customshow) {
 4180: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4181: 	    $rhash{$server}=$reply;
 4182: 	}
 4183: 	else {
 4184: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4185: 			     &escape($custom).':'.&escape($customshow),
 4186: 			     $server);
 4187: 	    $rhash{$server}=$reply;
 4188: 	}
 4189:     }
 4190:     return \%rhash;
 4191: }
 4192: 
 4193: # ----------------------------------------- Send log queries and wait for reply
 4194: 
 4195: sub log_query {
 4196:     my ($uname,$udom,$query,%filters)=@_;
 4197:     my $uhome=&homeserver($uname,$udom);
 4198:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4199:     my $uhost=&hostname($uhome);
 4200:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4201:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4202:                        $uhome);
 4203:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4204:     return get_query_reply($queryid);
 4205: }
 4206: 
 4207: # -------------------------- Update MySQL table for portfolio file
 4208: 
 4209: sub update_portfolio_table {
 4210:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4211:     my $homeserver = &homeserver($uname,$udom);
 4212:     my $queryid=
 4213:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4214:                ':'.&escape($file_name).':'.$action,$homeserver);
 4215:     my $reply = &get_query_reply($queryid);
 4216:     return $reply;
 4217: }
 4218: 
 4219: # ------- Request retrieval of institutional classlists for course(s)
 4220: 
 4221: sub fetch_enrollment_query {
 4222:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4223:     my $homeserver;
 4224:     my $maxtries = 1;
 4225:     if ($context eq 'automated') {
 4226:         $homeserver = $perlvar{'lonHostID'};
 4227:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4228:     } else {
 4229:         $homeserver = &homeserver($cnum,$dom);
 4230:     }
 4231:     my $host=&hostname($homeserver);
 4232:     my $cmd = '';
 4233:     foreach my $affiliate (keys %{$affiliatesref}) {
 4234:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4235:     }
 4236:     $cmd =~ s/%%$//;
 4237:     $cmd = &escape($cmd);
 4238:     my $query = 'fetchenrollment';
 4239:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4240:     unless ($queryid=~/^\Q$host\E\_/) { 
 4241:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4242:         return 'error: '.$queryid;
 4243:     }
 4244:     my $reply = &get_query_reply($queryid);
 4245:     my $tries = 1;
 4246:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4247:         $reply = &get_query_reply($queryid);
 4248:         $tries ++;
 4249:     }
 4250:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4251:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4252:     } else {
 4253:         my @responses = split/:/,$reply;
 4254:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4255:             foreach my $line (@responses) {
 4256:                 my ($key,$value) = split(/=/,$line,2);
 4257:                 $$replyref{$key} = $value;
 4258:             }
 4259:         } else {
 4260:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4261:             foreach my $line (@responses) {
 4262:                 my ($key,$value) = split(/=/,$line);
 4263:                 $$replyref{$key} = $value;
 4264:                 if ($value > 0) {
 4265:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4266:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4267:                         my $destname = $pathname.'/'.$filename;
 4268:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4269:                         if ($xml_classlist =~ /^error/) {
 4270:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4271:                         } else {
 4272:                             if ( open(FILE,">$destname") ) {
 4273:                                 print FILE &unescape($xml_classlist);
 4274:                                 close(FILE);
 4275:                             } else {
 4276:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4277:                             }
 4278:                         }
 4279:                     }
 4280:                 }
 4281:             }
 4282:         }
 4283:         return 'ok';
 4284:     }
 4285:     return 'error';
 4286: }
 4287: 
 4288: sub get_query_reply {
 4289:     my $queryid=shift;
 4290:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4291:     my $reply='';
 4292:     for (1..100) {
 4293: 	sleep 2;
 4294:         if (-e $replyfile.'.end') {
 4295: 	    if (open(my $fh,$replyfile)) {
 4296:                $reply.=<$fh>;
 4297:                close($fh);
 4298: 	   } else { return 'error: reply_file_error'; }
 4299:            return &unescape($reply);
 4300: 	}
 4301:     }
 4302:     return 'timeout:'.$queryid;
 4303: }
 4304: 
 4305: sub courselog_query {
 4306: #
 4307: # possible filters:
 4308: # url: url or symb
 4309: # username
 4310: # domain
 4311: # action: view, submit, grade
 4312: # start: timestamp
 4313: # end: timestamp
 4314: #
 4315:     my (%filters)=@_;
 4316:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4317:     if ($filters{'url'}) {
 4318: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4319:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4320:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4321:     }
 4322:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4323:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4324:     return &log_query($cname,$cdom,'courselog',%filters);
 4325: }
 4326: 
 4327: sub userlog_query {
 4328:     my ($uname,$udom,%filters)=@_;
 4329:     return &log_query($uname,$udom,'userlog',%filters);
 4330: }
 4331: 
 4332: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4333: 
 4334: sub auto_run {
 4335:     my ($cnum,$cdom) = @_;
 4336:     my $homeserver = &homeserver($cnum,$cdom);
 4337:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4338:     return $response;
 4339: }
 4340: 
 4341: sub auto_get_sections {
 4342:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4343:     my $homeserver = &homeserver($cnum,$cdom);
 4344:     my @secs = ();
 4345:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4346:     unless ($response eq 'refused') {
 4347:         @secs = split/:/,$response;
 4348:     }
 4349:     return @secs;
 4350: }
 4351: 
 4352: sub auto_new_course {
 4353:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4354:     my $homeserver = &homeserver($cnum,$cdom);
 4355:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4356:     return $response;
 4357: }
 4358: 
 4359: sub auto_validate_courseID {
 4360:     my ($cnum,$cdom,$inst_course_id) = @_;
 4361:     my $homeserver = &homeserver($cnum,$cdom);
 4362:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4363:     return $response;
 4364: }
 4365: 
 4366: sub auto_create_password {
 4367:     my ($cnum,$cdom,$authparam) = @_;
 4368:     my $homeserver = &homeserver($cnum,$cdom); 
 4369:     my $create_passwd = 0;
 4370:     my $authchk = '';
 4371:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4372:     if ($response eq 'refused') {
 4373:         $authchk = 'refused';
 4374:     } else {
 4375:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4376:     }
 4377:     return ($authparam,$create_passwd,$authchk);
 4378: }
 4379: 
 4380: sub auto_photo_permission {
 4381:     my ($cnum,$cdom,$students) = @_;
 4382:     my $homeserver = &homeserver($cnum,$cdom);
 4383:     my ($outcome,$perm_reqd,$conditions) = 
 4384: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4385:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4386: 	return (undef,undef);
 4387:     }
 4388:     return ($outcome,$perm_reqd,$conditions);
 4389: }
 4390: 
 4391: sub auto_checkphotos {
 4392:     my ($uname,$udom,$pid) = @_;
 4393:     my $homeserver = &homeserver($uname,$udom);
 4394:     my ($result,$resulttype);
 4395:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4396: 				   &escape($uname).':'.&escape($pid),
 4397: 				   $homeserver));
 4398:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4399: 	return (undef,undef);
 4400:     }
 4401:     if ($outcome) {
 4402:         ($result,$resulttype) = split(/:/,$outcome);
 4403:     } 
 4404:     return ($result,$resulttype);
 4405: }
 4406: 
 4407: sub auto_photochoice {
 4408:     my ($cnum,$cdom) = @_;
 4409:     my $homeserver = &homeserver($cnum,$cdom);
 4410:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4411: 						       &escape($cdom),
 4412: 						       $homeserver)));
 4413:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4414: 	return (undef,undef);
 4415:     }
 4416:     return ($update,$comment);
 4417: }
 4418: 
 4419: sub auto_photoupdate {
 4420:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4421:     my $homeserver = &homeserver($cnum,$dom);
 4422:     my $host=&hostname($homeserver);
 4423:     my $cmd = '';
 4424:     my $maxtries = 1;
 4425:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4426:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4427:     }
 4428:     $cmd =~ s/%%$//;
 4429:     $cmd = &escape($cmd);
 4430:     my $query = 'institutionalphotos';
 4431:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4432:     unless ($queryid=~/^\Q$host\E\_/) {
 4433:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4434:         return 'error: '.$queryid;
 4435:     }
 4436:     my $reply = &get_query_reply($queryid);
 4437:     my $tries = 1;
 4438:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4439:         $reply = &get_query_reply($queryid);
 4440:         $tries ++;
 4441:     }
 4442:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4443:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4444:     } else {
 4445:         my @responses = split(/:/,$reply);
 4446:         my $outcome = shift(@responses); 
 4447:         foreach my $item (@responses) {
 4448:             my ($key,$value) = split(/=/,$item);
 4449:             $$photo{$key} = $value;
 4450:         }
 4451:         return $outcome;
 4452:     }
 4453:     return 'error';
 4454: }
 4455: 
 4456: sub auto_instcode_format {
 4457:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4458: 	$cat_order) = @_;
 4459:     my $courses = '';
 4460:     my @homeservers;
 4461:     if ($caller eq 'global') {
 4462:         foreach my $tryserver (keys(%libserv)) {
 4463:             if ($hostdom{$tryserver} eq $codedom) {
 4464:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4465:                     push(@homeservers,$tryserver);
 4466:                 }
 4467:             }
 4468:         }
 4469:     } else {
 4470:         push(@homeservers,&homeserver($caller,$codedom));
 4471:     }
 4472:     foreach my $code (keys(%{$instcodes})) {
 4473:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4474:     }
 4475:     chop($courses);
 4476:     my $ok_response = 0;
 4477:     my $response;
 4478:     while (@homeservers > 0 && $ok_response == 0) {
 4479:         my $server = shift(@homeservers); 
 4480:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4481:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4482:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4483: 		split/:/,$response;
 4484:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4485:             push(@{$codetitles},&str2array($codetitles_str));
 4486:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4487:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4488:             $ok_response = 1;
 4489:         }
 4490:     }
 4491:     if ($ok_response) {
 4492:         return 'ok';
 4493:     } else {
 4494:         return $response;
 4495:     }
 4496: }
 4497: 
 4498: sub auto_instcode_defaults {
 4499:     my ($domain,$returnhash,$code_order) = @_;
 4500:     my @homeservers;
 4501:     foreach my $tryserver (keys(%libserv)) {
 4502:         if ($hostdom{$tryserver} eq $domain) {
 4503:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4504:                 push(@homeservers,$tryserver);
 4505:             }
 4506:         }
 4507:     }
 4508:     my $ok_response = 0;
 4509:     my $response;
 4510:     while (@homeservers > 0 && $ok_response == 0) {
 4511:         my $server = shift(@homeservers);
 4512:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4513:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4514:             foreach my $pair (split(/\&/,$response)) {
 4515:                 my ($name,$value)=split(/\=/,$pair);
 4516:                 if ($name eq 'code_order') {
 4517:                     @{$code_order} = split(/\&/,&unescape($value));
 4518:                 } else {
 4519:                     $returnhash->{&unescape($name)}=&unescape($value);
 4520:                 }
 4521:             }
 4522:             $ok_response = 1;
 4523:         }
 4524:     }
 4525:     if ($ok_response) {
 4526:         return 'ok';
 4527:     } else {
 4528:         return $response;
 4529:     }
 4530: } 
 4531: 
 4532: sub auto_validate_class_sec {
 4533:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4534:     my $homeserver = &homeserver($cnum,$cdom);
 4535:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4536:                         &escape($owner).':'.$cdom,$homeserver);
 4537:     return $response;
 4538: }
 4539: 
 4540: # ------------------------------------------------------- Course Group routines
 4541: 
 4542: sub get_coursegroups {
 4543:     my ($cdom,$cnum,$group,$namespace) = @_;
 4544:     return(&dump($namespace,$cdom,$cnum,$group));
 4545: }
 4546: 
 4547: sub modify_coursegroup {
 4548:     my ($cdom,$cnum,$groupsettings) = @_;
 4549:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4550: }
 4551: 
 4552: sub toggle_coursegroup_status {
 4553:     my ($cdom,$cnum,$group,$action) = @_;
 4554:     my ($from_namespace,$to_namespace);
 4555:     if ($action eq 'delete') {
 4556:         $from_namespace = 'coursegroups';
 4557:         $to_namespace = 'deleted_groups';
 4558:     } else {
 4559:         $from_namespace = 'deleted_groups';
 4560:         $to_namespace = 'coursegroups';
 4561:     }
 4562:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4563:     if (my $tmp = &error(%curr_group)) {
 4564:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4565:         return ('read error',$tmp);
 4566:     } else {
 4567:         my %savedsettings = %curr_group; 
 4568:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4569:         my $deloutcome;
 4570:         if ($result eq 'ok') {
 4571:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4572:         } else {
 4573:             return ('write error',$result);
 4574:         }
 4575:         if ($deloutcome eq 'ok') {
 4576:             return 'ok';
 4577:         } else {
 4578:             return ('delete error',$deloutcome);
 4579:         }
 4580:     }
 4581: }
 4582: 
 4583: sub modify_group_roles {
 4584:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4585:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4586:     my $role = 'gr/'.&escape($userprivs);
 4587:     my ($uname,$udom) = split(/:/,$user);
 4588:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4589:     if ($result eq 'ok') {
 4590:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4591:     }
 4592:     return $result;
 4593: }
 4594: 
 4595: sub modify_coursegroup_membership {
 4596:     my ($cdom,$cnum,$membership) = @_;
 4597:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4598:     return $result;
 4599: }
 4600: 
 4601: sub get_active_groups {
 4602:     my ($udom,$uname,$cdom,$cnum) = @_;
 4603:     my $now = time;
 4604:     my %groups = ();
 4605:     foreach my $key (keys(%env)) {
 4606:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4607:             my ($start,$end) = split(/\./,$env{$key});
 4608:             if (($end!=0) && ($end<$now)) { next; }
 4609:             if (($start!=0) && ($start>$now)) { next; }
 4610:             if ($1 eq $cdom && $2 eq $cnum) {
 4611:                 $groups{$3} = $env{$key} ;
 4612:             }
 4613:         }
 4614:     }
 4615:     return %groups;
 4616: }
 4617: 
 4618: sub get_group_membership {
 4619:     my ($cdom,$cnum,$group) = @_;
 4620:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4621: }
 4622: 
 4623: sub get_users_groups {
 4624:     my ($udom,$uname,$courseid) = @_;
 4625:     my @usersgroups;
 4626:     my $cachetime=1800;
 4627: 
 4628:     my $hashid="$udom:$uname:$courseid";
 4629:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4630:     if (defined($cached)) {
 4631:         @usersgroups = split(/:/,$grouplist);
 4632:     } else {  
 4633:         $grouplist = '';
 4634:         my $courseurl = &courseid_to_courseurl($courseid);
 4635:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4636:         my $access_end = $env{'course.'.$courseid.
 4637:                               '.default_enrollment_end_date'};
 4638:         my $now = time;
 4639:         foreach my $key (keys(%roleshash)) {
 4640:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4641:                 my $group = $1;
 4642:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4643:                     my $start = $2;
 4644:                     my $end = $1;
 4645:                     if ($start == -1) { next; } # deleted from group
 4646:                     if (($start!=0) && ($start>$now)) { next; }
 4647:                     if (($end!=0) && ($end<$now)) {
 4648:                         if ($access_end && $access_end < $now) {
 4649:                             if ($access_end - $end < 86400) {
 4650:                                 push(@usersgroups,$group);
 4651:                             }
 4652:                         }
 4653:                         next;
 4654:                     }
 4655:                     push(@usersgroups,$group);
 4656:                 }
 4657:             }
 4658:         }
 4659:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4660:         $grouplist = join(':',@usersgroups);
 4661:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4662:     }
 4663:     return @usersgroups;
 4664: }
 4665: 
 4666: sub devalidate_getgroups_cache {
 4667:     my ($udom,$uname,$cdom,$cnum)=@_;
 4668:     my $courseid = $cdom.'_'.$cnum;
 4669: 
 4670:     my $hashid="$udom:$uname:$courseid";
 4671:     &devalidate_cache_new('getgroups',$hashid);
 4672: }
 4673: 
 4674: # ------------------------------------------------------------------ Plain Text
 4675: 
 4676: sub plaintext {
 4677:     my ($short,$type,$cid) = @_;
 4678:     if ($short =~ /^cr/) {
 4679: 	return (split('/',$short))[-1];
 4680:     }
 4681:     if (!defined($cid)) {
 4682:         $cid = $env{'request.course.id'};
 4683:     }
 4684:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4685:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4686:                                           '.plaintext'});
 4687:     }
 4688:     my %rolenames = (
 4689:                       Course => 'std',
 4690:                       Group => 'alt1',
 4691:                     );
 4692:     if (defined($type) && 
 4693:          defined($rolenames{$type}) && 
 4694:          defined($prp{$short}{$rolenames{$type}})) {
 4695:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4696:     } else {
 4697:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4698:     }
 4699: }
 4700: 
 4701: # ----------------------------------------------------------------- Assign Role
 4702: 
 4703: sub assignrole {
 4704:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4705:     my $mrole;
 4706:     if ($role =~ /^cr\//) {
 4707:         my $cwosec=$url;
 4708:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4709: 	unless (&allowed('ccr',$cwosec)) {
 4710:            &logthis('Refused custom assignrole: '.
 4711:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4712: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4713:            return 'refused'; 
 4714:         }
 4715:         $mrole='cr';
 4716:     } elsif ($role =~ /^gr\//) {
 4717:         my $cwogrp=$url;
 4718:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4719:         unless (&allowed('mdg',$cwogrp)) {
 4720:             &logthis('Refused group assignrole: '.
 4721:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4722:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4723:             return 'refused';
 4724:         }
 4725:         $mrole='gr';
 4726:     } else {
 4727:         my $cwosec=$url;
 4728:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4729:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4730:            &logthis('Refused assignrole: '.
 4731:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4732: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4733:            return 'refused'; 
 4734:         }
 4735:         $mrole=$role;
 4736:     }
 4737:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4738:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4739:     if ($end) { $command.='_'.$end; }
 4740:     if ($start) {
 4741: 	if ($end) { 
 4742:            $command.='_'.$start; 
 4743:         } else {
 4744:            $command.='_0_'.$start;
 4745:         }
 4746:     }
 4747:     my $origstart = $start;
 4748:     my $origend = $end;
 4749: # actually delete
 4750:     if ($deleteflag) {
 4751: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4752: # modify command to delete the role
 4753:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4754:                 "$udom:$uname:$url".'_'."$mrole";
 4755: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4756: # set start and finish to negative values for userrolelog
 4757:            $start=-1;
 4758:            $end=-1;
 4759:         }
 4760:     }
 4761: # send command
 4762:     my $answer=&reply($command,&homeserver($uname,$udom));
 4763: # log new user role if status is ok
 4764:     if ($answer eq 'ok') {
 4765: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4766: # for course roles, perform group memberships changes triggered by role change.
 4767:         unless ($role =~ /^gr/) {
 4768:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4769:                                              $origstart);
 4770:         }
 4771:     }
 4772:     return $answer;
 4773: }
 4774: 
 4775: # -------------------------------------------------- Modify user authentication
 4776: # Overrides without validation
 4777: 
 4778: sub modifyuserauth {
 4779:     my ($udom,$uname,$umode,$upass)=@_;
 4780:     my $uhome=&homeserver($uname,$udom);
 4781:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4782:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4783:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4784:              ' in domain '.$env{'request.role.domain'});  
 4785:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4786: 		     &escape($upass),$uhome);
 4787:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4788:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4789:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4790:     &log($udom,,$uname,$uhome,
 4791:         'Authentication changed by '.$env{'user.domain'}.', '.
 4792:                                      $env{'user.name'}.', '.$umode.
 4793:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4794:     unless ($reply eq 'ok') {
 4795:         &logthis('Authentication mode error: '.$reply);
 4796: 	return 'error: '.$reply;
 4797:     }   
 4798:     return 'ok';
 4799: }
 4800: 
 4801: # --------------------------------------------------------------- Modify a user
 4802: 
 4803: sub modifyuser {
 4804:     my ($udom,    $uname, $uid,
 4805:         $umode,   $upass, $first,
 4806:         $middle,  $last,  $gene,
 4807:         $forceid, $desiredhome, $email)=@_;
 4808:     $udom= &LONCAPA::clean_domain($udom);
 4809:     $uname=&LONCAPA::clean_username($uname);
 4810:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4811:              $umode.', '.$first.', '.$middle.', '.
 4812: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4813:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4814:                                      ' desiredhome not specified'). 
 4815:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4816:              ' in domain '.$env{'request.role.domain'});
 4817:     my $uhome=&homeserver($uname,$udom,'true');
 4818: # ----------------------------------------------------------------- Create User
 4819:     if (($uhome eq 'no_host') && 
 4820: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4821:         my $unhome='';
 4822:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4823:             $unhome = $desiredhome;
 4824: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4825: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4826:         } else { # load balancing routine for determining $unhome
 4827:             my $tryserver;
 4828:             my $loadm=10000000;
 4829:             foreach $tryserver (keys %libserv) {
 4830: 	       if ($hostdom{$tryserver} eq $udom) {
 4831:                   my $answer=reply('load',$tryserver);
 4832:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4833: 		      $loadm=$answer;
 4834:                       $unhome=$tryserver;
 4835:                   }
 4836: 	       }
 4837: 	    }
 4838:         }
 4839:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4840: 	    return 'error: unable to find a home server for '.$uname.
 4841:                    ' in domain '.$udom;
 4842:         }
 4843:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4844:                          &escape($upass),$unhome);
 4845: 	unless ($reply eq 'ok') {
 4846:             return 'error: '.$reply;
 4847:         }   
 4848:         $uhome=&homeserver($uname,$udom,'true');
 4849:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4850: 	    return 'error: unable verify users home machine.';
 4851:         }
 4852:     }   # End of creation of new user
 4853: # ---------------------------------------------------------------------- Add ID
 4854:     if ($uid) {
 4855:        $uid=~tr/A-Z/a-z/;
 4856:        my %uidhash=&idrget($udom,$uname);
 4857:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4858:          && (!$forceid)) {
 4859: 	  unless ($uid eq $uidhash{$uname}) {
 4860: 	      return 'error: user id "'.$uid.'" does not match '.
 4861:                   'current user id "'.$uidhash{$uname}.'".';
 4862:           }
 4863:        } else {
 4864: 	  &idput($udom,($uname => $uid));
 4865:        }
 4866:     }
 4867: # -------------------------------------------------------------- Add names, etc
 4868:     my @tmp=&get('environment',
 4869: 		   ['firstname','middlename','lastname','generation'],
 4870: 		   $udom,$uname);
 4871:     my %names;
 4872:     if ($tmp[0] =~ m/^error:.*/) { 
 4873:         %names=(); 
 4874:     } else {
 4875:         %names = @tmp;
 4876:     }
 4877: #
 4878: # Make sure to not trash student environment if instructor does not bother
 4879: # to supply name and email information
 4880: #
 4881:     if ($first)  { $names{'firstname'}  = $first; }
 4882:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4883:     if ($last)   { $names{'lastname'}   = $last; }
 4884:     if (defined($gene))   { $names{'generation'} = $gene; }
 4885:     if ($email) {
 4886:        $email=~s/[^\w\@\.\-\,]//gs;
 4887:        if ($email=~/\@/) { $names{'notification'} = $email;
 4888: 			   $names{'critnotification'} = $email;
 4889: 			   $names{'permanentemail'} = $email; }
 4890:     }
 4891:     my $reply = &put('environment', \%names, $udom,$uname);
 4892:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4893:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4894:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4895:              $umode.', '.$first.', '.$middle.', '.
 4896: 	     $last.', '.$gene.' by '.
 4897:              $env{'user.name'}.' at '.$env{'user.domain'});
 4898:     return 'ok';
 4899: }
 4900: 
 4901: # -------------------------------------------------------------- Modify student
 4902: 
 4903: sub modifystudent {
 4904:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4905:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4906:     if (!$cid) {
 4907: 	unless ($cid=$env{'request.course.id'}) {
 4908: 	    return 'not_in_class';
 4909: 	}
 4910:     }
 4911: # --------------------------------------------------------------- Make the user
 4912:     my $reply=&modifyuser
 4913: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4914:          $desiredhome,$email);
 4915:     unless ($reply eq 'ok') { return $reply; }
 4916:     # This will cause &modify_student_enrollment to get the uid from the
 4917:     # students environment
 4918:     $uid = undef if (!$forceid);
 4919:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4920: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4921:     return $reply;
 4922: }
 4923: 
 4924: sub modify_student_enrollment {
 4925:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4926:     my ($cdom,$cnum,$chome);
 4927:     if (!$cid) {
 4928: 	unless ($cid=$env{'request.course.id'}) {
 4929: 	    return 'not_in_class';
 4930: 	}
 4931: 	$cdom=$env{'course.'.$cid.'.domain'};
 4932: 	$cnum=$env{'course.'.$cid.'.num'};
 4933:     } else {
 4934: 	($cdom,$cnum)=split(/_/,$cid);
 4935:     }
 4936:     $chome=$env{'course.'.$cid.'.home'};
 4937:     if (!$chome) {
 4938: 	$chome=&homeserver($cnum,$cdom);
 4939:     }
 4940:     if (!$chome) { return 'unknown_course'; }
 4941:     # Make sure the user exists
 4942:     my $uhome=&homeserver($uname,$udom);
 4943:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4944: 	return 'error: no such user';
 4945:     }
 4946:     # Get student data if we were not given enough information
 4947:     if (!defined($first)  || $first  eq '' || 
 4948:         !defined($last)   || $last   eq '' || 
 4949:         !defined($uid)    || $uid    eq '' || 
 4950:         !defined($middle) || $middle eq '' || 
 4951:         !defined($gene)   || $gene   eq '') {
 4952:         # They did not supply us with enough data to enroll the student, so
 4953:         # we need to pick up more information.
 4954:         my %tmp = &get('environment',
 4955:                        ['firstname','middlename','lastname', 'generation','id']
 4956:                        ,$udom,$uname);
 4957: 
 4958:         #foreach my $key (keys(%tmp)) {
 4959:         #    &logthis("key $key = ".$tmp{$key});
 4960:         #}
 4961:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4962:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4963:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4964:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4965:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4966:     }
 4967:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4968:     my $reply=cput('classlist',
 4969: 		   {"$uname:$udom" => 
 4970: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4971: 		   $cdom,$cnum);
 4972:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4973: 	return 'error: '.$reply;
 4974:     } else {
 4975: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4976:     }
 4977:     # Add student role to user
 4978:     my $uurl='/'.$cid;
 4979:     $uurl=~s/\_/\//g;
 4980:     if ($usec) {
 4981: 	$uurl.='/'.$usec;
 4982:     }
 4983:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4984: }
 4985: 
 4986: sub format_name {
 4987:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4988:     my $name;
 4989:     if ($first ne 'lastname') {
 4990: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4991:     } else {
 4992: 	if ($lastname=~/\S/) {
 4993: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4994: 	    $name=~s/\s+,/,/;
 4995: 	} else {
 4996: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4997: 	}
 4998:     }
 4999:     $name=~s/^\s+//;
 5000:     $name=~s/\s+$//;
 5001:     $name=~s/\s+/ /g;
 5002:     return $name;
 5003: }
 5004: 
 5005: # ------------------------------------------------- Write to course preferences
 5006: 
 5007: sub writecoursepref {
 5008:     my ($courseid,%prefs)=@_;
 5009:     $courseid=~s/^\///;
 5010:     $courseid=~s/\_/\//g;
 5011:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5012:     my $chome=homeserver($cnum,$cdomain);
 5013:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5014: 	return 'error: no such course';
 5015:     }
 5016:     my $cstring='';
 5017:     foreach my $pref (keys(%prefs)) {
 5018: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5019:     }
 5020:     $cstring=~s/\&$//;
 5021:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5022: }
 5023: 
 5024: # ---------------------------------------------------------- Make/modify course
 5025: 
 5026: sub createcourse {
 5027:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5028:         $course_owner,$crstype)=@_;
 5029:     $url=&declutter($url);
 5030:     my $cid='';
 5031:     unless (&allowed('ccc',$udom)) {
 5032:         return 'refused';
 5033:     }
 5034: # ------------------------------------------------------------------- Create ID
 5035:    my $uname=int(1+rand(9)).
 5036:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5037:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5038:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5039: # ----------------------------------------------- Make sure that does not exist
 5040:    my $uhome=&homeserver($uname,$udom,'true');
 5041:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5042:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5043:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5044:        $uhome=&homeserver($uname,$udom,'true');       
 5045:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5046:            return 'error: unable to generate unique course-ID';
 5047:        } 
 5048:    }
 5049: # ------------------------------------------------ Check supplied server name
 5050:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5051:     if (! exists($libserv{$course_server})) {
 5052:         return 'error:bad server name '.$course_server;
 5053:     }
 5054: # ------------------------------------------------------------- Make the course
 5055:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5056:                       $course_server);
 5057:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5058:     $uhome=&homeserver($uname,$udom,'true');
 5059:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5060: 	return 'error: no such course';
 5061:     }
 5062: # ----------------------------------------------------------------- Course made
 5063: # log existence
 5064:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5065:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5066:                   &escape($crstype),$uhome);
 5067:     &flushcourselogs();
 5068: # set toplevel url
 5069:     my $topurl=$url;
 5070:     unless ($nonstandard) {
 5071: # ------------------------------------------ For standard courses, make top url
 5072:         my $mapurl=&clutter($url);
 5073:         if ($mapurl eq '/res/') { $mapurl=''; }
 5074:         $env{'form.initmap'}=(<<ENDINITMAP);
 5075: <map>
 5076: <resource id="1" type="start"></resource>
 5077: <resource id="2" src="$mapurl"></resource>
 5078: <resource id="3" type="finish"></resource>
 5079: <link index="1" from="1" to="2"></link>
 5080: <link index="2" from="2" to="3"></link>
 5081: </map>
 5082: ENDINITMAP
 5083:         $topurl=&declutter(
 5084:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5085:                           );
 5086:     }
 5087: # ----------------------------------------------------------- Write preferences
 5088:     &writecoursepref($udom.'_'.$uname,
 5089:                      ('description' => $description,
 5090:                       'url'         => $topurl));
 5091:     return '/'.$udom.'/'.$uname;
 5092: }
 5093: 
 5094: sub is_course {
 5095:     my ($cdom,$cnum) = @_;
 5096:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5097: 				undef,'.');
 5098:     if (exists($courses{$cdom.'_'.$cnum})) {
 5099:         return 1;
 5100:     }
 5101:     return 0;
 5102: }
 5103: 
 5104: # ---------------------------------------------------------- Assign Custom Role
 5105: 
 5106: sub assigncustomrole {
 5107:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5108:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5109:                        $end,$start,$deleteflag);
 5110: }
 5111: 
 5112: # ----------------------------------------------------------------- Revoke Role
 5113: 
 5114: sub revokerole {
 5115:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5116:     my $now=time;
 5117:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5118: }
 5119: 
 5120: # ---------------------------------------------------------- Revoke Custom Role
 5121: 
 5122: sub revokecustomrole {
 5123:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5124:     my $now=time;
 5125:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5126:            $deleteflag);
 5127: }
 5128: 
 5129: # ------------------------------------------------------------ Disk usage
 5130: sub diskusage {
 5131:     my ($udom,$uname,$directoryRoot)=@_;
 5132:     $directoryRoot =~ s/\/$//;
 5133:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5134:     return $listing;
 5135: }
 5136: 
 5137: sub is_locked {
 5138:     my ($file_name, $domain, $user) = @_;
 5139:     my @check;
 5140:     my $is_locked;
 5141:     push @check, $file_name;
 5142:     my %locked = &get('file_permissions',\@check,
 5143: 		      $env{'user.domain'},$env{'user.name'});
 5144:     my ($tmp)=keys(%locked);
 5145:     if ($tmp=~/^error:/) { undef(%locked); }
 5146:     
 5147:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5148:         $is_locked = 'false';
 5149:         foreach my $entry (@{$locked{$file_name}}) {
 5150:            if (ref($entry) eq 'ARRAY') { 
 5151:                $is_locked = 'true';
 5152:                last;
 5153:            }
 5154:        }
 5155:     } else {
 5156:         $is_locked = 'false';
 5157:     }
 5158: }
 5159: 
 5160: sub declutter_portfile {
 5161:     my ($file) = @_;
 5162:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5163:     return $file;
 5164: }
 5165: 
 5166: # ------------------------------------------------------------- Mark as Read Only
 5167: 
 5168: sub mark_as_readonly {
 5169:     my ($domain,$user,$files,$what) = @_;
 5170:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5171:     my ($tmp)=keys(%current_permissions);
 5172:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5173:     foreach my $file (@{$files}) {
 5174: 	$file = &declutter_portfile($file);
 5175:         push(@{$current_permissions{$file}},$what);
 5176:     }
 5177:     &put('file_permissions',\%current_permissions,$domain,$user);
 5178:     return;
 5179: }
 5180: 
 5181: # ------------------------------------------------------------Save Selected Files
 5182: 
 5183: sub save_selected_files {
 5184:     my ($user, $path, @files) = @_;
 5185:     my $filename = $user."savedfiles";
 5186:     my @other_files = &files_not_in_path($user, $path);
 5187:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5188:     foreach my $file (@files) {
 5189:         print (OUT $env{'form.currentpath'}.$file."\n");
 5190:     }
 5191:     foreach my $file (@other_files) {
 5192:         print (OUT $file."\n");
 5193:     }
 5194:     close (OUT);
 5195:     return 'ok';
 5196: }
 5197: 
 5198: sub clear_selected_files {
 5199:     my ($user) = @_;
 5200:     my $filename = $user."savedfiles";
 5201:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5202:     print (OUT undef);
 5203:     close (OUT);
 5204:     return ("ok");    
 5205: }
 5206: 
 5207: sub files_in_path {
 5208:     my ($user, $path) = @_;
 5209:     my $filename = $user."savedfiles";
 5210:     my %return_files;
 5211:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5212:     while (my $line_in = <IN>) {
 5213:         chomp ($line_in);
 5214:         my @paths_and_file = split (m!/!, $line_in);
 5215:         my $file_part = pop (@paths_and_file);
 5216:         my $path_part = join ('/', @paths_and_file);
 5217:         $path_part.='/';
 5218:         my $path_and_file = $path_part.$file_part;
 5219:         if ($path_part eq $path) {
 5220:             $return_files{$file_part}= 'selected';
 5221:         }
 5222:     }
 5223:     close (IN);
 5224:     return (\%return_files);
 5225: }
 5226: 
 5227: # called in portfolio select mode, to show files selected NOT in current directory
 5228: sub files_not_in_path {
 5229:     my ($user, $path) = @_;
 5230:     my $filename = $user."savedfiles";
 5231:     my @return_files;
 5232:     my $path_part;
 5233:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5234:     while (my $line = <IN>) {
 5235:         #ok, I know it's clunky, but I want it to work
 5236:         my @paths_and_file = split(m|/|, $line);
 5237:         my $file_part = pop(@paths_and_file);
 5238:         chomp($file_part);
 5239:         my $path_part = join('/', @paths_and_file);
 5240:         $path_part .= '/';
 5241:         my $path_and_file = $path_part.$file_part;
 5242:         if ($path_part ne $path) {
 5243:             push(@return_files, ($path_and_file));
 5244:         }
 5245:     }
 5246:     close(OUT);
 5247:     return (@return_files);
 5248: }
 5249: 
 5250: #----------------------------------------------Get portfolio file permissions
 5251: 
 5252: sub get_portfile_permissions {
 5253:     my ($domain,$user) = @_;
 5254:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5255:     my ($tmp)=keys(%current_permissions);
 5256:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5257:     return \%current_permissions;
 5258: }
 5259: 
 5260: #---------------------------------------------Get portfolio file access controls
 5261: 
 5262: sub get_access_controls {
 5263:     my ($current_permissions,$group,$file) = @_;
 5264:     my %access;
 5265:     my $real_file = $file;
 5266:     $file =~ s/\.meta$//;
 5267:     if (defined($file)) {
 5268:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5269:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5270:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5271:             }
 5272:         }
 5273:     } else {
 5274:         foreach my $key (keys(%{$current_permissions})) {
 5275:             if ($key =~ /\0accesscontrol$/) {
 5276:                 if (defined($group)) {
 5277:                     if ($key !~ m-^\Q$group\E/-) {
 5278:                         next;
 5279:                     }
 5280:                 }
 5281:                 my ($fullpath) = split(/\0/,$key);
 5282:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5283:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5284:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5285:                     }
 5286:                 }
 5287:             }
 5288:         }
 5289:     }
 5290:     return %access;
 5291: }
 5292: 
 5293: sub modify_access_controls {
 5294:     my ($file_name,$changes,$domain,$user)=@_;
 5295:     my ($outcome,$deloutcome);
 5296:     my %store_permissions;
 5297:     my %new_values;
 5298:     my %new_control;
 5299:     my %translation;
 5300:     my @deletions = ();
 5301:     my $now = time;
 5302:     if (exists($$changes{'activate'})) {
 5303:         if (ref($$changes{'activate'}) eq 'HASH') {
 5304:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5305:             my $numnew = scalar(@newitems);
 5306:             for (my $i=0; $i<$numnew; $i++) {
 5307:                 my $newkey = $newitems[$i];
 5308:                 my $newid = &Apache::loncommon::get_cgi_id();
 5309:                 if ($newkey =~ /^\d+:/) { 
 5310:                     $newkey =~ s/^(\d+)/$newid/;
 5311:                     $translation{$1} = $newid;
 5312:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5313:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5314:                     $translation{$1} = $newid;
 5315:                 }
 5316:                 $new_values{$file_name."\0".$newkey} = 
 5317:                                           $$changes{'activate'}{$newitems[$i]};
 5318:                 $new_control{$newkey} = $now;
 5319:             }
 5320:         }
 5321:     }
 5322:     my %todelete;
 5323:     my %changed_items;
 5324:     foreach my $action ('delete','update') {
 5325:         if (exists($$changes{$action})) {
 5326:             if (ref($$changes{$action}) eq 'HASH') {
 5327:                 foreach my $key (keys(%{$$changes{$action}})) {
 5328:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5329:                     if ($action eq 'delete') { 
 5330:                         $todelete{$itemnum} = 1;
 5331:                     } else {
 5332:                         $changed_items{$itemnum} = $key;
 5333:                     }
 5334:                 }
 5335:             }
 5336:         }
 5337:     }
 5338:     # get lock on access controls for file.
 5339:     my $lockhash = {
 5340:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5341:                                                        ':'.$env{'user.domain'},
 5342:                    }; 
 5343:     my $tries = 0;
 5344:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5345:    
 5346:     while (($gotlock ne 'ok') && $tries <3) {
 5347:         $tries ++;
 5348:         sleep 1;
 5349:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5350:     }
 5351:     if ($gotlock eq 'ok') {
 5352:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5353:         my ($tmp)=keys(%curr_permissions);
 5354:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5355:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5356:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5357:             if (ref($curr_controls) eq 'HASH') {
 5358:                 foreach my $control_item (keys(%{$curr_controls})) {
 5359:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5360:                     if (defined($todelete{$itemnum})) {
 5361:                         push(@deletions,$file_name."\0".$control_item);
 5362:                     } else {
 5363:                         if (defined($changed_items{$itemnum})) {
 5364:                             $new_control{$changed_items{$itemnum}} = $now;
 5365:                             push(@deletions,$file_name."\0".$control_item);
 5366:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5367:                         } else {
 5368:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5369:                         }
 5370:                     }
 5371:                 }
 5372:             }
 5373:         }
 5374:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5375:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5376:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5377:         #  remove lock
 5378:         my @del_lock = ($file_name."\0".'locked_access_records');
 5379:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5380:         my ($file,$group);
 5381:         if (&is_course($domain,$user)) {
 5382:             ($group,$file) = split(/\//,$file_name,2);
 5383:         } else {
 5384:             $file = $file_name;
 5385:         }
 5386:         my $sqlresult =
 5387:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5388:                                     $group);
 5389:     } else {
 5390:         $outcome = "error: could not obtain lockfile\n";  
 5391:     }
 5392:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5393: }
 5394: 
 5395: sub make_public_indefinitely {
 5396:     my ($requrl) = @_;
 5397:     my $now = time;
 5398:     my $action = 'activate';
 5399:     my $aclnum = 0;
 5400:     if (&is_portfolio_url($requrl)) {
 5401:         my (undef,$udom,$unum,$file_name,$group) =
 5402:             &parse_portfolio_url($requrl);
 5403:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5404:         my %access_controls = &get_access_controls($current_perms,
 5405:                                                    $group,$file_name);
 5406:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5407:             my ($num,$scope,$end,$start) = 
 5408:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5409:             if ($scope eq 'public') {
 5410:                 if ($start <= $now && $end == 0) {
 5411:                     $action = 'none';
 5412:                 } else {
 5413:                     $action = 'update';
 5414:                     $aclnum = $num;
 5415:                 }
 5416:                 last;
 5417:             }
 5418:         }
 5419:         if ($action eq 'none') {
 5420:              return 'ok';
 5421:         } else {
 5422:             my %changes;
 5423:             my $newend = 0;
 5424:             my $newstart = $now;
 5425:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5426:             $changes{$action}{$newkey} = {
 5427:                 type => 'public',
 5428:                 time => {
 5429:                     start => $newstart,
 5430:                     end   => $newend,
 5431:                 },
 5432:             };
 5433:             my ($outcome,$deloutcome,$new_values,$translation) =
 5434:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5435:             return $outcome;
 5436:         }
 5437:     } else {
 5438:         return 'invalid';
 5439:     }
 5440: }
 5441: 
 5442: #------------------------------------------------------Get Marked as Read Only
 5443: 
 5444: sub get_marked_as_readonly {
 5445:     my ($domain,$user,$what,$group) = @_;
 5446:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5447:     my @readonly_files;
 5448:     my $cmp1=$what;
 5449:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5450:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5451:         if (defined($group)) {
 5452:             if ($file_name !~ m-^\Q$group\E/-) {
 5453:                 next;
 5454:             }
 5455:         }
 5456:         if (ref($value) eq "ARRAY"){
 5457:             foreach my $stored_what (@{$value}) {
 5458:                 my $cmp2=$stored_what;
 5459:                 if (ref($stored_what) eq 'ARRAY') {
 5460:                     $cmp2=join('',@{$stored_what});
 5461:                 }
 5462:                 if ($cmp1 eq $cmp2) {
 5463:                     push(@readonly_files, $file_name);
 5464:                     last;
 5465:                 } elsif (!defined($what)) {
 5466:                     push(@readonly_files, $file_name);
 5467:                     last;
 5468:                 }
 5469:             }
 5470:         }
 5471:     }
 5472:     return @readonly_files;
 5473: }
 5474: #-----------------------------------------------------------Get Marked as Read Only Hash
 5475: 
 5476: sub get_marked_as_readonly_hash {
 5477:     my ($current_permissions,$group,$what) = @_;
 5478:     my %readonly_files;
 5479:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5480:         if (defined($group)) {
 5481:             if ($file_name !~ m-^\Q$group\E/-) {
 5482:                 next;
 5483:             }
 5484:         }
 5485:         if (ref($value) eq "ARRAY"){
 5486:             foreach my $stored_what (@{$value}) {
 5487:                 if (ref($stored_what) eq 'ARRAY') {
 5488:                     foreach my $lock_descriptor(@{$stored_what}) {
 5489:                         if ($lock_descriptor eq 'graded') {
 5490:                             $readonly_files{$file_name} = 'graded';
 5491:                         } elsif ($lock_descriptor eq 'handback') {
 5492:                             $readonly_files{$file_name} = 'handback';
 5493:                         } else {
 5494:                             if (!exists($readonly_files{$file_name})) {
 5495:                                 $readonly_files{$file_name} = 'locked';
 5496:                             }
 5497:                         }
 5498:                     }
 5499:                 } 
 5500:             }
 5501:         } 
 5502:     }
 5503:     return %readonly_files;
 5504: }
 5505: # ------------------------------------------------------------ Unmark as Read Only
 5506: 
 5507: sub unmark_as_readonly {
 5508:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5509:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5510:     my ($domain,$user,$what,$file_name,$group) = @_;
 5511:     $file_name = &declutter_portfile($file_name);
 5512:     my $symb_crs = $what;
 5513:     if (ref($what)) { $symb_crs=join('',@$what); }
 5514:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5515:     my ($tmp)=keys(%current_permissions);
 5516:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5517:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5518:     foreach my $file (@readonly_files) {
 5519: 	my $clean_file = &declutter_portfile($file);
 5520: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5521: 	my $current_locks = $current_permissions{$file};
 5522:         my @new_locks;
 5523:         my @del_keys;
 5524:         if (ref($current_locks) eq "ARRAY"){
 5525:             foreach my $locker (@{$current_locks}) {
 5526:                 my $compare=$locker;
 5527:                 if (ref($locker) eq 'ARRAY') {
 5528:                     $compare=join('',@{$locker});
 5529:                     if ($compare ne $symb_crs) {
 5530:                         push(@new_locks, $locker);
 5531:                     }
 5532:                 }
 5533:             }
 5534:             if (scalar(@new_locks) > 0) {
 5535:                 $current_permissions{$file} = \@new_locks;
 5536:             } else {
 5537:                 push(@del_keys, $file);
 5538:                 &del('file_permissions',\@del_keys, $domain, $user);
 5539:                 delete($current_permissions{$file});
 5540:             }
 5541:         }
 5542:     }
 5543:     &put('file_permissions',\%current_permissions,$domain,$user);
 5544:     return;
 5545: }
 5546: 
 5547: # ------------------------------------------------------------ Directory lister
 5548: 
 5549: sub dirlist {
 5550:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5551: 
 5552:     $uri=~s/^\///;
 5553:     $uri=~s/\/$//;
 5554:     my ($udom, $uname);
 5555:     (undef,$udom,$uname)=split(/\//,$uri);
 5556:     if(defined($userdomain)) {
 5557:         $udom = $userdomain;
 5558:     }
 5559:     if(defined($username)) {
 5560:         $uname = $username;
 5561:     }
 5562: 
 5563:     my $dirRoot = $perlvar{'lonDocRoot'};
 5564:     if(defined($alternateDirectoryRoot)) {
 5565:         $dirRoot = $alternateDirectoryRoot;
 5566:         $dirRoot =~ s/\/$//;
 5567:     }
 5568: 
 5569:     if($udom) {
 5570:         if($uname) {
 5571:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5572: 				 &homeserver($uname,$udom));
 5573:             my @listing_results;
 5574:             if ($listing eq 'unknown_cmd') {
 5575:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5576: 				  &homeserver($uname,$udom));
 5577:                 @listing_results = split(/:/,$listing);
 5578:             } else {
 5579:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5580:             }
 5581:             return @listing_results;
 5582:         } elsif(!defined($alternateDirectoryRoot)) {
 5583:             my %allusers;
 5584:             foreach my $tryserver (keys(%libserv)) {
 5585:                 if($hostdom{$tryserver} eq $udom) {
 5586:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5587: 					 $udom, $tryserver);
 5588:                     my @listing_results;
 5589:                     if ($listing eq 'unknown_cmd') {
 5590:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5591: 					  $udom, $tryserver);
 5592:                         @listing_results = split(/:/,$listing);
 5593:                     } else {
 5594:                         @listing_results =
 5595:                             map { &unescape($_); } split(/:/,$listing);
 5596:                     }
 5597:                     if ($listing_results[0] ne 'no_such_dir' && 
 5598:                         $listing_results[0] ne 'empty'       &&
 5599:                         $listing_results[0] ne 'con_lost') {
 5600:                         foreach my $line (@listing_results) {
 5601:                             my ($entry) = split(/&/,$line,2);
 5602:                             $allusers{$entry} = 1;
 5603:                         }
 5604:                     }
 5605:                 }
 5606:             }
 5607:             my $alluserstr='';
 5608:             foreach my $user (sort(keys(%allusers))) {
 5609:                 $alluserstr.=$user.'&user:';
 5610:             }
 5611:             $alluserstr=~s/:$//;
 5612:             return split(/:/,$alluserstr);
 5613:         } else {
 5614:             return ('missing user name');
 5615:         }
 5616:     } elsif(!defined($alternateDirectoryRoot)) {
 5617:         my $tryserver;
 5618:         my %alldom=();
 5619:         foreach $tryserver (keys(%libserv)) {
 5620:             $alldom{$hostdom{$tryserver}}=1;
 5621:         }
 5622:         my $alldomstr='';
 5623:         foreach my $domain (sort(keys(%alldom))) {
 5624:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
 5625:         }
 5626:         $alldomstr=~s/:$//;
 5627:         return split(/:/,$alldomstr);       
 5628:     } else {
 5629:         return ('missing domain');
 5630:     }
 5631: }
 5632: 
 5633: # --------------------------------------------- GetFileTimestamp
 5634: # This function utilizes dirlist and returns the date stamp for
 5635: # when it was last modified.  It will also return an error of -1
 5636: # if an error occurs
 5637: 
 5638: ##
 5639: ## FIXME: This subroutine assumes its caller knows something about the
 5640: ## directory structure of the home server for the student ($root).
 5641: ## Not a good assumption to make.  Since this is for looking up files
 5642: ## in user directories, the full path should be constructed by lond, not
 5643: ## whatever machine we request data from.
 5644: ##
 5645: sub GetFileTimestamp {
 5646:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5647:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5648:     $studentName   = &LONCAPA::clean_username($studentName);
 5649:     my $subdir=$studentName.'__';
 5650:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5651:     my $proname="$studentDomain/$subdir/$studentName";
 5652:     $proname .= '/'.$filename;
 5653:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5654:                                               $studentName, $root);
 5655:     my @stats = split('&', $fileStat);
 5656:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5657:         # @stats contains first the filename, then the stat output
 5658:         return $stats[10]; # so this is 10 instead of 9.
 5659:     } else {
 5660:         return -1;
 5661:     }
 5662: }
 5663: 
 5664: sub stat_file {
 5665:     my ($uri) = @_;
 5666:     $uri = &clutter_with_no_wrapper($uri);
 5667: 
 5668:     my ($udom,$uname,$file,$dir);
 5669:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5670: 	($udom,$uname,$file) =
 5671: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5672: 	$file = 'userfiles/'.$file;
 5673: 	$dir = &propath($udom,$uname);
 5674:     }
 5675:     if ($uri =~ m-^/res/-) {
 5676: 	($udom,$uname) = 
 5677: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5678: 	$file = $uri;
 5679:     }
 5680: 
 5681:     if (!$udom || !$uname || !$file) {
 5682: 	# unable to handle the uri
 5683: 	return ();
 5684:     }
 5685: 
 5686:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5687:     my @stats = split('&', $result);
 5688:     
 5689:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5690: 	shift(@stats); #filename is first
 5691: 	return @stats;
 5692:     }
 5693:     return ();
 5694: }
 5695: 
 5696: # -------------------------------------------------------- Value of a Condition
 5697: 
 5698: # gets the value of a specific preevaluated condition
 5699: #    stored in the string  $env{user.state.<cid>}
 5700: # or looks up a condition reference in the bighash and if if hasn't
 5701: # already been evaluated recurses into docondval to get the value of
 5702: # the condition, then memoizing it to 
 5703: #   $env{user.state.<cid>.<condition>}
 5704: sub directcondval {
 5705:     my $number=shift;
 5706:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5707: 	&Apache::lonuserstate::evalstate();
 5708:     }
 5709:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5710: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5711:     } elsif ($number =~ /^_/) {
 5712: 	my $sub_condition;
 5713: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5714: 		&GDBM_READER(),0640)) {
 5715: 	    $sub_condition=$bighash{'conditions'.$number};
 5716: 	    untie(%bighash);
 5717: 	}
 5718: 	my $value = &docondval($sub_condition);
 5719: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5720: 	return $value;
 5721:     }
 5722:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5723:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5724:     } else {
 5725:        return 2;
 5726:     }
 5727: }
 5728: 
 5729: # get the collection of conditions for this resource
 5730: sub condval {
 5731:     my $condidx=shift;
 5732:     my $allpathcond='';
 5733:     foreach my $cond (split(/\|/,$condidx)) {
 5734: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5735: 	    $allpathcond.=
 5736: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5737: 	}
 5738:     }
 5739:     $allpathcond=~s/\|$//;
 5740:     return &docondval($allpathcond);
 5741: }
 5742: 
 5743: #evaluates an expression of conditions
 5744: sub docondval {
 5745:     my ($allpathcond) = @_;
 5746:     my $result=0;
 5747:     if ($env{'request.course.id'}
 5748: 	&& defined($allpathcond)) {
 5749: 	my $operand='|';
 5750: 	my @stack;
 5751: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5752: 	    if ($chunk eq '(') {
 5753: 		push @stack,($operand,$result);
 5754: 	    } elsif ($chunk eq ')') {
 5755: 		my $before=pop @stack;
 5756: 		if (pop @stack eq '&') {
 5757: 		    $result=$result>$before?$before:$result;
 5758: 		} else {
 5759: 		    $result=$result>$before?$result:$before;
 5760: 		}
 5761: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5762: 		$operand=$chunk;
 5763: 	    } else {
 5764: 		my $new=directcondval($chunk);
 5765: 		if ($operand eq '&') {
 5766: 		    $result=$result>$new?$new:$result;
 5767: 		} else {
 5768: 		    $result=$result>$new?$result:$new;
 5769: 		}
 5770: 	    }
 5771: 	}
 5772:     }
 5773:     return $result;
 5774: }
 5775: 
 5776: # ---------------------------------------------------- Devalidate courseresdata
 5777: 
 5778: sub devalidatecourseresdata {
 5779:     my ($coursenum,$coursedomain)=@_;
 5780:     my $hashid=$coursenum.':'.$coursedomain;
 5781:     &devalidate_cache_new('courseres',$hashid);
 5782: }
 5783: 
 5784: 
 5785: # --------------------------------------------------- Course Resourcedata Query
 5786: 
 5787: sub get_courseresdata {
 5788:     my ($coursenum,$coursedomain)=@_;
 5789:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5790:     my $hashid=$coursenum.':'.$coursedomain;
 5791:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5792:     my %dumpreply;
 5793:     unless (defined($cached)) {
 5794: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5795: 	$result=\%dumpreply;
 5796: 	my ($tmp) = keys(%dumpreply);
 5797: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5798: 	    &do_cache_new('courseres',$hashid,$result,600);
 5799: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5800: 	    return $tmp;
 5801: 	} elsif ($tmp =~ /^(error)/) {
 5802: 	    $result=undef;
 5803: 	    &do_cache_new('courseres',$hashid,$result,600);
 5804: 	}
 5805:     }
 5806:     return $result;
 5807: }
 5808: 
 5809: sub devalidateuserresdata {
 5810:     my ($uname,$udom)=@_;
 5811:     my $hashid="$udom:$uname";
 5812:     &devalidate_cache_new('userres',$hashid);
 5813: }
 5814: 
 5815: sub get_userresdata {
 5816:     my ($uname,$udom)=@_;
 5817:     #most student don\'t have any data set, check if there is some data
 5818:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5819: 
 5820:     my $hashid="$udom:$uname";
 5821:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5822:     if (!defined($cached)) {
 5823: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5824: 	$result=\%resourcedata;
 5825: 	&do_cache_new('userres',$hashid,$result,600);
 5826:     }
 5827:     my ($tmp)=keys(%$result);
 5828:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5829: 	return $result;
 5830:     }
 5831:     #error 2 occurs when the .db doesn't exist
 5832:     if ($tmp!~/error: 2 /) {
 5833: 	&logthis("<font color=\"blue\">WARNING:".
 5834: 		 " Trying to get resource data for ".
 5835: 		 $uname." at ".$udom.": ".
 5836: 		 $tmp."</font>");
 5837:     } elsif ($tmp=~/error: 2 /) {
 5838: 	#&EXT_cache_set($udom,$uname);
 5839: 	&do_cache_new('userres',$hashid,undef,600);
 5840: 	undef($tmp); # not really an error so don't send it back
 5841:     }
 5842:     return $tmp;
 5843: }
 5844: 
 5845: sub resdata {
 5846:     my ($name,$domain,$type,@which)=@_;
 5847:     my $result;
 5848:     if ($type eq 'course') {
 5849: 	$result=&get_courseresdata($name,$domain);
 5850:     } elsif ($type eq 'user') {
 5851: 	$result=&get_userresdata($name,$domain);
 5852:     }
 5853:     if (!ref($result)) { return $result; }    
 5854:     foreach my $item (@which) {
 5855: 	if (defined($result->{$item})) {
 5856: 	    return $result->{$item};
 5857: 	}
 5858:     }
 5859:     return undef;
 5860: }
 5861: 
 5862: #
 5863: # EXT resource caching routines
 5864: #
 5865: 
 5866: sub clear_EXT_cache_status {
 5867:     &delenv('cache.EXT.');
 5868: }
 5869: 
 5870: sub EXT_cache_status {
 5871:     my ($target_domain,$target_user) = @_;
 5872:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5873:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5874:         # We know already the user has no data
 5875:         return 1;
 5876:     } else {
 5877:         return 0;
 5878:     }
 5879: }
 5880: 
 5881: sub EXT_cache_set {
 5882:     my ($target_domain,$target_user) = @_;
 5883:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5884:     #&appenv($cachename => time);
 5885: }
 5886: 
 5887: # --------------------------------------------------------- Value of a Variable
 5888: sub EXT {
 5889: 
 5890:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5891:     unless ($varname) { return ''; }
 5892:     #get real user name/domain, courseid and symb
 5893:     my $courseid;
 5894:     my $publicuser;
 5895:     if ($symbparm) {
 5896: 	$symbparm=&get_symb_from_alias($symbparm);
 5897:     }
 5898:     if (!($uname && $udom)) {
 5899:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5900:       if (!$symbparm) {	$symbparm=$cursymb; }
 5901:     } else {
 5902: 	$courseid=$env{'request.course.id'};
 5903:     }
 5904:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5905:     my $rest;
 5906:     if (defined($therest[0])) {
 5907:        $rest=join('.',@therest);
 5908:     } else {
 5909:        $rest='';
 5910:     }
 5911: 
 5912:     my $qualifierrest=$qualifier;
 5913:     if ($rest) { $qualifierrest.='.'.$rest; }
 5914:     my $spacequalifierrest=$space;
 5915:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5916:     if ($realm eq 'user') {
 5917: # --------------------------------------------------------------- user.resource
 5918: 	if ($space eq 'resource') {
 5919: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5920: 		  || defined($Apache::lonhomework::parsing_a_task))
 5921: 		 &&
 5922: 		 ($symbparm eq &symbread()) ) {	
 5923: 		# if we are in the middle of processing the resource the
 5924: 		# get the value we are planning on committing
 5925:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5926:                     return $Apache::lonhomework::results{$qualifierrest};
 5927:                 } else {
 5928:                     return $Apache::lonhomework::history{$qualifierrest};
 5929:                 }
 5930: 	    } else {
 5931: 		my %restored;
 5932: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5933: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5934: 		} else {
 5935: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5936: 		}
 5937: 		return $restored{$qualifierrest};
 5938: 	    }
 5939: # ----------------------------------------------------------------- user.access
 5940:         } elsif ($space eq 'access') {
 5941: 	    # FIXME - not supporting calls for a specific user
 5942:             return &allowed($qualifier,$rest);
 5943: # ------------------------------------------ user.preferences, user.environment
 5944:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5945: 	    if (($uname eq $env{'user.name'}) &&
 5946: 		($udom eq $env{'user.domain'})) {
 5947: 		return $env{join('.',('environment',$qualifierrest))};
 5948: 	    } else {
 5949: 		my %returnhash;
 5950: 		if (!$publicuser) {
 5951: 		    %returnhash=&userenvironment($udom,$uname,
 5952: 						 $qualifierrest);
 5953: 		}
 5954: 		return $returnhash{$qualifierrest};
 5955: 	    }
 5956: # ----------------------------------------------------------------- user.course
 5957:         } elsif ($space eq 'course') {
 5958: 	    # FIXME - not supporting calls for a specific user
 5959:             return $env{join('.',('request.course',$qualifier))};
 5960: # ------------------------------------------------------------------- user.role
 5961:         } elsif ($space eq 'role') {
 5962: 	    # FIXME - not supporting calls for a specific user
 5963:             my ($role,$where)=split(/\./,$env{'request.role'});
 5964:             if ($qualifier eq 'value') {
 5965: 		return $role;
 5966:             } elsif ($qualifier eq 'extent') {
 5967:                 return $where;
 5968:             }
 5969: # ----------------------------------------------------------------- user.domain
 5970:         } elsif ($space eq 'domain') {
 5971:             return $udom;
 5972: # ------------------------------------------------------------------- user.name
 5973:         } elsif ($space eq 'name') {
 5974:             return $uname;
 5975: # ---------------------------------------------------- Any other user namespace
 5976:         } else {
 5977: 	    my %reply;
 5978: 	    if (!$publicuser) {
 5979: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5980: 	    }
 5981: 	    return $reply{$qualifierrest};
 5982:         }
 5983:     } elsif ($realm eq 'query') {
 5984: # ---------------------------------------------- pull stuff out of query string
 5985:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5986: 						[$spacequalifierrest]);
 5987: 	return $env{'form.'.$spacequalifierrest}; 
 5988:    } elsif ($realm eq 'request') {
 5989: # ------------------------------------------------------------- request.browser
 5990:         if ($space eq 'browser') {
 5991: 	    if ($qualifier eq 'textremote') {
 5992: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5993: 		    return 1;
 5994: 		} else {
 5995: 		    return 0;
 5996: 		}
 5997: 	    } else {
 5998: 		return $env{'browser.'.$qualifier};
 5999: 	    }
 6000: # ------------------------------------------------------------ request.filename
 6001:         } else {
 6002:             return $env{'request.'.$spacequalifierrest};
 6003:         }
 6004:     } elsif ($realm eq 'course') {
 6005: # ---------------------------------------------------------- course.description
 6006:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6007:     } elsif ($realm eq 'resource') {
 6008: 
 6009: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6010: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6011: 	}
 6012: 
 6013: 	if ($space eq 'title') {
 6014: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6015: 	    return &gettitle($symbparm);
 6016: 	}
 6017: 	
 6018: 	if ($space eq 'map') {
 6019: 	    my ($map) = &decode_symb($symbparm);
 6020: 	    return &symbread($map);
 6021: 	}
 6022: 
 6023: 	my ($section, $group, @groups);
 6024: 	my ($courselevelm,$courselevel);
 6025: 	if ($symbparm && defined($courseid) && 
 6026: 	    $courseid eq $env{'request.course.id'}) {
 6027: 
 6028: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6029: 
 6030: # ----------------------------------------------------- Cascading lookup scheme
 6031: 	    my $symbp=$symbparm;
 6032: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6033: 
 6034: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6035: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6036: 
 6037: 	    if (($env{'user.name'} eq $uname) &&
 6038: 		($env{'user.domain'} eq $udom)) {
 6039: 		$section=$env{'request.course.sec'};
 6040:                 @groups = split(/:/,$env{'request.course.groups'});  
 6041:                 @groups=&sort_course_groups($courseid,@groups); 
 6042: 	    } else {
 6043: 		if (! defined($usection)) {
 6044: 		    $section=&getsection($udom,$uname,$courseid);
 6045: 		} else {
 6046: 		    $section = $usection;
 6047: 		}
 6048:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6049: 	    }
 6050: 
 6051: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6052: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6053: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6054: 
 6055: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6056: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6057: 	    $courselevelm=$courseid.'.'.$mapparm;
 6058: 
 6059: # ----------------------------------------------------------- first, check user
 6060: 
 6061: 	    my $userreply=&resdata($uname,$udom,'user',
 6062: 				       ($courselevelr,$courselevelm,
 6063: 					$courselevel));
 6064: 	    if (defined($userreply)) { return $userreply; }
 6065: 
 6066: # ------------------------------------------------ second, check some of course
 6067:             my $coursereply;
 6068:             if (@groups > 0) {
 6069:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6070:                                        $mapparm,$spacequalifierrest);
 6071:                 if (defined($coursereply)) { return $coursereply; }
 6072:             }
 6073: 
 6074: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6075: 				     $env{'course.'.$courseid.'.domain'},
 6076: 				     'course',
 6077: 				     ($seclevelr,$seclevelm,$seclevel,
 6078: 				      $courselevelr));
 6079: 	    if (defined($coursereply)) { return $coursereply; }
 6080: 
 6081: # ------------------------------------------------------ third, check map parms
 6082: 	    my %parmhash=();
 6083: 	    my $thisparm='';
 6084: 	    if (tie(%parmhash,'GDBM_File',
 6085: 		    $env{'request.course.fn'}.'_parms.db',
 6086: 		    &GDBM_READER(),0640)) {
 6087: 		$thisparm=$parmhash{$symbparm};
 6088: 		untie(%parmhash);
 6089: 	    }
 6090: 	    if ($thisparm) { return $thisparm; }
 6091: 	}
 6092: # ------------------------------------------ fourth, look in resource metadata
 6093: 
 6094: 	$spacequalifierrest=~s/\./\_/;
 6095: 	my $filename;
 6096: 	if (!$symbparm) { $symbparm=&symbread(); }
 6097: 	if ($symbparm) {
 6098: 	    $filename=(&decode_symb($symbparm))[2];
 6099: 	} else {
 6100: 	    $filename=$env{'request.filename'};
 6101: 	}
 6102: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6103: 	if (defined($metadata)) { return $metadata; }
 6104: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6105: 	if (defined($metadata)) { return $metadata; }
 6106: 
 6107: # ---------------------------------------------- fourth, look in rest pf course
 6108: 	if ($symbparm && defined($courseid) && 
 6109: 	    $courseid eq $env{'request.course.id'}) {
 6110: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6111: 				     $env{'course.'.$courseid.'.domain'},
 6112: 				     'course',
 6113: 				     ($courselevelm,$courselevel));
 6114: 	    if (defined($coursereply)) { return $coursereply; }
 6115: 	}
 6116: # ------------------------------------------------------------------ Cascade up
 6117: 	unless ($space eq '0') {
 6118: 	    my @parts=split(/_/,$space);
 6119: 	    my $id=pop(@parts);
 6120: 	    my $part=join('_',@parts);
 6121: 	    if ($part eq '') { $part='0'; }
 6122: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6123: 				 $symbparm,$udom,$uname,$section,1);
 6124: 	    if (defined($partgeneral)) { return $partgeneral; }
 6125: 	}
 6126: 	if ($recurse) { return undef; }
 6127: 	my $pack_def=&packages_tab_default($filename,$varname);
 6128: 	if (defined($pack_def)) { return $pack_def; }
 6129: 
 6130: # ---------------------------------------------------- Any other user namespace
 6131:     } elsif ($realm eq 'environment') {
 6132: # ----------------------------------------------------------------- environment
 6133: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6134: 	    return $env{'environment.'.$spacequalifierrest};
 6135: 	} else {
 6136: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6137: 		return '';
 6138: 	    }
 6139: 	    my %returnhash=&userenvironment($udom,$uname,
 6140: 					    $spacequalifierrest);
 6141: 	    return $returnhash{$spacequalifierrest};
 6142: 	}
 6143:     } elsif ($realm eq 'system') {
 6144: # ----------------------------------------------------------------- system.time
 6145: 	if ($space eq 'time') {
 6146: 	    return time;
 6147:         }
 6148:     } elsif ($realm eq 'server') {
 6149: # ----------------------------------------------------------------- system.time
 6150: 	if ($space eq 'name') {
 6151: 	    return $ENV{'SERVER_NAME'};
 6152:         }
 6153:     }
 6154:     return '';
 6155: }
 6156: 
 6157: sub check_group_parms {
 6158:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6159:     my @groupitems = ();
 6160:     my $resultitem;
 6161:     my @levels = ($symbparm,$mapparm,$what);
 6162:     foreach my $group (@{$groups}) {
 6163:         foreach my $level (@levels) {
 6164:              my $item = $courseid.'.['.$group.'].'.$level;
 6165:              push(@groupitems,$item);
 6166:         }
 6167:     }
 6168:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6169:                             $env{'course.'.$courseid.'.domain'},
 6170:                                      'course',@groupitems);
 6171:     return $coursereply;
 6172: }
 6173: 
 6174: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6175:     my ($courseid,@groups) = @_;
 6176:     @groups = sort(@groups);
 6177:     return @groups;
 6178: }
 6179: 
 6180: sub packages_tab_default {
 6181:     my ($uri,$varname)=@_;
 6182:     my (undef,$part,$name)=split(/\./,$varname);
 6183: 
 6184:     my (@extension,@specifics,$do_default);
 6185:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6186: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6187: 	if ($pack_type eq 'default') {
 6188: 	    $do_default=1;
 6189: 	} elsif ($pack_type eq 'extension') {
 6190: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6191: 	} else {
 6192: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6193: 	}
 6194:     }
 6195:     # first look for a package that matches the requested part id
 6196:     foreach my $package (@specifics) {
 6197: 	my (undef,$pack_type,$pack_part)=@{$package};
 6198: 	next if ($pack_part ne $part);
 6199: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6200: 	    return $packagetab{"$pack_type&$name&default"};
 6201: 	}
 6202:     }
 6203:     # look for any possible matching non extension_ package
 6204:     foreach my $package (@specifics) {
 6205: 	my (undef,$pack_type,$pack_part)=@{$package};
 6206: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6207: 	    return $packagetab{"$pack_type&$name&default"};
 6208: 	}
 6209: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6210: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6211: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6212: 	}
 6213:     }
 6214:     # look for any posible extension_ match
 6215:     foreach my $package (@extension) {
 6216: 	my ($package,$pack_type)=@{$package};
 6217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6218: 	    return $packagetab{"$pack_type&$name&default"};
 6219: 	}
 6220: 	if (defined($packagetab{$package."&$name&default"})) {
 6221: 	    return $packagetab{$package."&$name&default"};
 6222: 	}
 6223:     }
 6224:     # look for a global default setting
 6225:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6226: 	return $packagetab{"default&$name&default"};
 6227:     }
 6228:     return undef;
 6229: }
 6230: 
 6231: sub add_prefix_and_part {
 6232:     my ($prefix,$part)=@_;
 6233:     my $keyroot;
 6234:     if (defined($prefix) && $prefix !~ /^__/) {
 6235: 	# prefix that has a part already
 6236: 	$keyroot=$prefix;
 6237:     } elsif (defined($prefix)) {
 6238: 	# prefix that is missing a part
 6239: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6240:     } else {
 6241: 	# no prefix at all
 6242: 	if (defined($part)) { $keyroot='_'.$part; }
 6243:     }
 6244:     return $keyroot;
 6245: }
 6246: 
 6247: # ---------------------------------------------------------------- Get metadata
 6248: 
 6249: my %metaentry;
 6250: sub metadata {
 6251:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6252:     $uri=&declutter($uri);
 6253:     # if it is a non metadata possible uri return quickly
 6254:     if (($uri eq '') || 
 6255: 	(($uri =~ m|^/*adm/|) && 
 6256: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6257:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6258: 	($uri =~ m|home/$match_username/public_html/|)) {
 6259: 	return undef;
 6260:     }
 6261:     my $filename=$uri;
 6262:     $uri=~s/\.meta$//;
 6263: #
 6264: # Is the metadata already cached?
 6265: # Look at timestamp of caching
 6266: # Everything is cached by the main uri, libraries are never directly cached
 6267: #
 6268:     if (!defined($liburi)) {
 6269: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6270: 	if (defined($cached)) { return $result->{':'.$what}; }
 6271:     }
 6272:     {
 6273: #
 6274: # Is this a recursive call for a library?
 6275: #
 6276: #	if (! exists($metacache{$uri})) {
 6277: #	    $metacache{$uri}={};
 6278: #	}
 6279:         if ($liburi) {
 6280: 	    $liburi=&declutter($liburi);
 6281:             $filename=$liburi;
 6282:         } else {
 6283: 	    &devalidate_cache_new('meta',$uri);
 6284: 	    undef(%metaentry);
 6285: 	}
 6286:         my %metathesekeys=();
 6287:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6288: 	my $metastring;
 6289: 	if ($uri !~ m -^(editupload)/-) {
 6290: 	    my $file=&filelocation('',&clutter($filename));
 6291: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6292: 	    $metastring=&getfile($file);
 6293: 	}
 6294:         my $parser=HTML::LCParser->new(\$metastring);
 6295:         my $token;
 6296:         undef %metathesekeys;
 6297:         while ($token=$parser->get_token) {
 6298: 	    if ($token->[0] eq 'S') {
 6299: 		if (defined($token->[2]->{'package'})) {
 6300: #
 6301: # This is a package - get package info
 6302: #
 6303: 		    my $package=$token->[2]->{'package'};
 6304: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6305: 		    if (defined($token->[2]->{'id'})) { 
 6306: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6307: 		    }
 6308: 		    if ($metaentry{':packages'}) {
 6309: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6310: 		    } else {
 6311: 			$metaentry{':packages'}=$package.$keyroot;
 6312: 		    }
 6313: 		    foreach my $pack_entry (keys(%packagetab)) {
 6314: 			my $part=$keyroot;
 6315: 			$part=~s/^\_//;
 6316: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6317: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6318: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6319: 			    # ignore package.tab specified default values
 6320:                             # here &package_tab_default() will fetch those
 6321: 			    if ($subp eq 'default') { next; }
 6322: 			    my $value=$packagetab{$pack_entry};
 6323: 			    my $unikey;
 6324: 			    if ($pack =~ /_0$/) {
 6325: 				$unikey='parameter_0_'.$name;
 6326: 				$part=0;
 6327: 			    } else {
 6328: 				$unikey='parameter'.$keyroot.'_'.$name;
 6329: 			    }
 6330: 			    if ($subp eq 'display') {
 6331: 				$value.=' [Part: '.$part.']';
 6332: 			    }
 6333: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6334: 			    $metathesekeys{$unikey}=1;
 6335: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6336: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6337: 			    }
 6338: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6339: 				$metaentry{':'.$unikey}=
 6340: 				    $metaentry{':'.$unikey.'.default'};
 6341: 			    }
 6342: 			}
 6343: 		    }
 6344: 		} else {
 6345: #
 6346: # This is not a package - some other kind of start tag
 6347: #
 6348: 		    my $entry=$token->[1];
 6349: 		    my $unikey;
 6350: 		    if ($entry eq 'import') {
 6351: 			$unikey='';
 6352: 		    } else {
 6353: 			$unikey=$entry;
 6354: 		    }
 6355: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6356: 
 6357: 		    if (defined($token->[2]->{'id'})) { 
 6358: 			$unikey.='_'.$token->[2]->{'id'}; 
 6359: 		    }
 6360: 
 6361: 		    if ($entry eq 'import') {
 6362: #
 6363: # Importing a library here
 6364: #
 6365: 			if ($depthcount<20) {
 6366: 			    my $location=$parser->get_text('/import');
 6367: 			    my $dir=$filename;
 6368: 			    $dir=~s|[^/]*$||;
 6369: 			    $location=&filelocation($dir,$location);
 6370: 			    my $metadata = 
 6371: 				&metadata($uri,'keys', $location,$unikey,
 6372: 					  $depthcount+1);
 6373: 			    foreach my $meta (split(',',$metadata)) {
 6374: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6375: 				$metathesekeys{$meta}=1;
 6376: 			    }
 6377: 			}
 6378: 		    } else { 
 6379: 			
 6380: 			if (defined($token->[2]->{'name'})) { 
 6381: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6382: 			}
 6383: 			$metathesekeys{$unikey}=1;
 6384: 			foreach my $param (@{$token->[3]}) {
 6385: 			    $metaentry{':'.$unikey.'.'.$param} =
 6386: 				$token->[2]->{$param};
 6387: 			}
 6388: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6389: 			my $default=$metaentry{':'.$unikey.'.default'};
 6390: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6391: 		 # only ws inside the tag, and not in default, so use default
 6392: 		 # as value
 6393: 			    $metaentry{':'.$unikey}=$default;
 6394: 			} else {
 6395: 		  # either something interesting inside the tag or default
 6396:                   # uninteresting
 6397: 			    $metaentry{':'.$unikey}=$internaltext;
 6398: 			}
 6399: # end of not-a-package not-a-library import
 6400: 		    }
 6401: # end of not-a-package start tag
 6402: 		}
 6403: # the next is the end of "start tag"
 6404: 	    }
 6405: 	}
 6406: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6407: 	foreach my $key (keys(%packagetab)) {
 6408: 	    #no specific packages #how's our extension
 6409: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6410: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6411: 					 \%metathesekeys);
 6412: 	}
 6413: 	if (!exists($metaentry{':packages'})) {
 6414: 	    foreach my $key (keys(%packagetab)) {
 6415: 		#no specific packages well let's get default then
 6416: 		if ($key!~/^default&/) { next; }
 6417: 		&metadata_create_package_def($uri,$key,'default',
 6418: 					     \%metathesekeys);
 6419: 	    }
 6420: 	}
 6421: # are there custom rights to evaluate
 6422: 	if ($metaentry{':copyright'} eq 'custom') {
 6423: 
 6424:     #
 6425:     # Importing a rights file here
 6426:     #
 6427: 	    unless ($depthcount) {
 6428: 		my $location=$metaentry{':customdistributionfile'};
 6429: 		my $dir=$filename;
 6430: 		$dir=~s|[^/]*$||;
 6431: 		$location=&filelocation($dir,$location);
 6432: 		my $rights_metadata =
 6433: 		    &metadata($uri,'keys',$location,'_rights',
 6434: 			      $depthcount+1);
 6435: 		foreach my $rights (split(',',$rights_metadata)) {
 6436: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6437: 		    $metathesekeys{$rights}=1;
 6438: 		}
 6439: 	    }
 6440: 	}
 6441: 	# uniqifiy package listing
 6442: 	my %seen;
 6443: 	my @uniq_packages =
 6444: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6445: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6446: 
 6447: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6448: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6449: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6450: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6451: # this is the end of "was not already recently cached
 6452:     }
 6453:     return $metaentry{':'.$what};
 6454: }
 6455: 
 6456: sub metadata_create_package_def {
 6457:     my ($uri,$key,$package,$metathesekeys)=@_;
 6458:     my ($pack,$name,$subp)=split(/\&/,$key);
 6459:     if ($subp eq 'default') { next; }
 6460:     
 6461:     if (defined($metaentry{':packages'})) {
 6462: 	$metaentry{':packages'}.=','.$package;
 6463:     } else {
 6464: 	$metaentry{':packages'}=$package;
 6465:     }
 6466:     my $value=$packagetab{$key};
 6467:     my $unikey;
 6468:     $unikey='parameter_0_'.$name;
 6469:     $metaentry{':'.$unikey.'.part'}=0;
 6470:     $$metathesekeys{$unikey}=1;
 6471:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6472: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6473:     }
 6474:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6475: 	$metaentry{':'.$unikey}=
 6476: 	    $metaentry{':'.$unikey.'.default'};
 6477:     }
 6478: }
 6479: 
 6480: sub metadata_generate_part0 {
 6481:     my ($metadata,$metacache,$uri) = @_;
 6482:     my %allnames;
 6483:     foreach my $metakey (keys(%$metadata)) {
 6484: 	if ($metakey=~/^parameter\_(.*)/) {
 6485: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6486: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6487: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6488: 	    $allnames{$name}=$part;
 6489: 	  }
 6490: 	}
 6491:     }
 6492:     foreach my $name (keys(%allnames)) {
 6493:       $$metadata{"parameter_0_$name"}=1;
 6494:       my $key=":parameter_0_$name";
 6495:       $$metacache{"$key.part"}='0';
 6496:       $$metacache{"$key.name"}=$name;
 6497:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6498: 					   $allnames{$name}.'_'.$name.
 6499: 					   '.type'};
 6500:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6501: 			     '.display'};
 6502:       my $expr='[Part: '.$allnames{$name}.']';
 6503:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6504:       $$metacache{"$key.display"}=$olddis;
 6505:     }
 6506: }
 6507: 
 6508: # ------------------------------------------------------ Devalidate title cache
 6509: 
 6510: sub devalidate_title_cache {
 6511:     my ($url)=@_;
 6512:     if (!$env{'request.course.id'}) { return; }
 6513:     my $symb=&symbread($url);
 6514:     if (!$symb) { return; }
 6515:     my $key=$env{'request.course.id'}."\0".$symb;
 6516:     &devalidate_cache_new('title',$key);
 6517: }
 6518: 
 6519: # ------------------------------------------------- Get the title of a resource
 6520: 
 6521: sub gettitle {
 6522:     my $urlsymb=shift;
 6523:     my $symb=&symbread($urlsymb);
 6524:     if ($symb) {
 6525: 	my $key=$env{'request.course.id'}."\0".$symb;
 6526: 	my ($result,$cached)=&is_cached_new('title',$key);
 6527: 	if (defined($cached)) { 
 6528: 	    return $result;
 6529: 	}
 6530: 	my ($map,$resid,$url)=&decode_symb($symb);
 6531: 	my $title='';
 6532: 	my %bighash;
 6533: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6534: 		&GDBM_READER(),0640)) {
 6535: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6536: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6537: 	    untie %bighash;
 6538: 	}
 6539: 	$title=~s/\&colon\;/\:/gs;
 6540: 	if ($title) {
 6541: 	    return &do_cache_new('title',$key,$title,600);
 6542: 	}
 6543: 	$urlsymb=$url;
 6544:     }
 6545:     my $title=&metadata($urlsymb,'title');
 6546:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6547:     return $title;
 6548: }
 6549: 
 6550: sub get_slot {
 6551:     my ($which,$cnum,$cdom)=@_;
 6552:     if (!$cnum || !$cdom) {
 6553: 	(undef,my $courseid)=&whichuser();
 6554: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6555: 	$cnum=$env{'course.'.$courseid.'.num'};
 6556:     }
 6557:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6558:     my %slotinfo;
 6559:     if (exists($remembered{$key})) {
 6560: 	$slotinfo{$which} = $remembered{$key};
 6561:     } else {
 6562: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6563: 	&Apache::lonhomework::showhash(%slotinfo);
 6564: 	my ($tmp)=keys(%slotinfo);
 6565: 	if ($tmp=~/^error:/) { return (); }
 6566: 	$remembered{$key} = $slotinfo{$which};
 6567:     }
 6568:     if (ref($slotinfo{$which}) eq 'HASH') {
 6569: 	return %{$slotinfo{$which}};
 6570:     }
 6571:     return $slotinfo{$which};
 6572: }
 6573: # ------------------------------------------------- Update symbolic store links
 6574: 
 6575: sub symblist {
 6576:     my ($mapname,%newhash)=@_;
 6577:     $mapname=&deversion(&declutter($mapname));
 6578:     my %hash;
 6579:     if (($env{'request.course.fn'}) && (%newhash)) {
 6580:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6581:                       &GDBM_WRCREAT(),0640)) {
 6582: 	    foreach my $url (keys %newhash) {
 6583: 		next if ($url eq 'last_known'
 6584: 			 && $env{'form.no_update_last_known'});
 6585: 		$hash{declutter($url)}=&encode_symb($mapname,
 6586: 						    $newhash{$url}->[1],
 6587: 						    $newhash{$url}->[0]);
 6588:             }
 6589:             if (untie(%hash)) {
 6590: 		return 'ok';
 6591:             }
 6592:         }
 6593:     }
 6594:     return 'error';
 6595: }
 6596: 
 6597: # --------------------------------------------------------------- Verify a symb
 6598: 
 6599: sub symbverify {
 6600:     my ($symb,$thisurl)=@_;
 6601:     my $thisfn=$thisurl;
 6602:     $thisfn=&declutter($thisfn);
 6603: # direct jump to resource in page or to a sequence - will construct own symbs
 6604:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6605: # check URL part
 6606:     my ($map,$resid,$url)=&decode_symb($symb);
 6607: 
 6608:     unless ($url eq $thisfn) { return 0; }
 6609: 
 6610:     $symb=&symbclean($symb);
 6611:     $thisurl=&deversion($thisurl);
 6612:     $thisfn=&deversion($thisfn);
 6613: 
 6614:     my %bighash;
 6615:     my $okay=0;
 6616: 
 6617:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6618:                             &GDBM_READER(),0640)) {
 6619:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6620:         unless ($ids) { 
 6621:            $ids=$bighash{'ids_/'.$thisurl};
 6622:         }
 6623:         if ($ids) {
 6624: # ------------------------------------------------------------------- Has ID(s)
 6625: 	    foreach my $id (split(/\,/,$ids)) {
 6626: 	       my ($mapid,$resid)=split(/\./,$id);
 6627:                if (
 6628:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6629:    eq $symb) { 
 6630: 		   if (($env{'request.role.adv'}) ||
 6631: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6632: 		       $okay=1; 
 6633: 		   }
 6634: 	       }
 6635: 	   }
 6636:         }
 6637: 	untie(%bighash);
 6638:     }
 6639:     return $okay;
 6640: }
 6641: 
 6642: # --------------------------------------------------------------- Clean-up symb
 6643: 
 6644: sub symbclean {
 6645:     my $symb=shift;
 6646:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6647: # remove version from map
 6648:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6649: 
 6650: # remove version from URL
 6651:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6652: 
 6653: # remove wrapper
 6654: 
 6655:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6656:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6657:     return $symb;
 6658: }
 6659: 
 6660: # ---------------------------------------------- Split symb to find map and url
 6661: 
 6662: sub encode_symb {
 6663:     my ($map,$resid,$url)=@_;
 6664:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6665: }
 6666: 
 6667: sub decode_symb {
 6668:     my $symb=shift;
 6669:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6670:     my ($map,$resid,$url)=split(/___/,$symb);
 6671:     return (&fixversion($map),$resid,&fixversion($url));
 6672: }
 6673: 
 6674: sub fixversion {
 6675:     my $fn=shift;
 6676:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6677:     my %bighash;
 6678:     my $uri=&clutter($fn);
 6679:     my $key=$env{'request.course.id'}.'_'.$uri;
 6680: # is this cached?
 6681:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6682:     if (defined($cached)) { return $result; }
 6683: # unfortunately not cached, or expired
 6684:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6685: 	    &GDBM_READER(),0640)) {
 6686:  	if ($bighash{'version_'.$uri}) {
 6687:  	    my $version=$bighash{'version_'.$uri};
 6688:  	    unless (($version eq 'mostrecent') || 
 6689: 		    ($version==&getversion($uri))) {
 6690:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6691:  	    }
 6692:  	}
 6693:  	untie %bighash;
 6694:     }
 6695:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6696: }
 6697: 
 6698: sub deversion {
 6699:     my $url=shift;
 6700:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6701:     return $url;
 6702: }
 6703: 
 6704: # ------------------------------------------------------ Return symb list entry
 6705: 
 6706: sub symbread {
 6707:     my ($thisfn,$donotrecurse)=@_;
 6708:     my $cache_str='request.symbread.cached.'.$thisfn;
 6709:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6710: # no filename provided? try from environment
 6711:     unless ($thisfn) {
 6712:         if ($env{'request.symb'}) {
 6713: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6714: 	}
 6715: 	$thisfn=$env{'request.filename'};
 6716:     }
 6717:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6718: # is that filename actually a symb? Verify, clean, and return
 6719:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6720: 	if (&symbverify($thisfn,$1)) {
 6721: 	    return $env{$cache_str}=&symbclean($thisfn);
 6722: 	}
 6723:     }
 6724:     $thisfn=declutter($thisfn);
 6725:     my %hash;
 6726:     my %bighash;
 6727:     my $syval='';
 6728:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6729:         my $targetfn = $thisfn;
 6730:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6731:             $targetfn = 'adm/wrapper/'.$thisfn;
 6732:         }
 6733: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6734: 	    $targetfn=$1;
 6735: 	}
 6736:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6737:                       &GDBM_READER(),0640)) {
 6738: 	    $syval=$hash{$targetfn};
 6739:             untie(%hash);
 6740:         }
 6741: # ---------------------------------------------------------- There was an entry
 6742:         if ($syval) {
 6743: 	    #unless ($syval=~/\_\d+$/) {
 6744: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6745: 		    #&appenv('request.ambiguous' => $thisfn);
 6746: 		    #return $env{$cache_str}='';
 6747: 		#}    
 6748: 		#$syval.=$1;
 6749: 	    #}
 6750:         } else {
 6751: # ------------------------------------------------------- Was not in symb table
 6752:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6753:                             &GDBM_READER(),0640)) {
 6754: # ---------------------------------------------- Get ID(s) for current resource
 6755:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6756:               unless ($ids) { 
 6757:                  $ids=$bighash{'ids_/'.$thisfn};
 6758:               }
 6759:               unless ($ids) {
 6760: # alias?
 6761: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6762:               }
 6763:               if ($ids) {
 6764: # ------------------------------------------------------------------- Has ID(s)
 6765:                  my @possibilities=split(/\,/,$ids);
 6766:                  if ($#possibilities==0) {
 6767: # ----------------------------------------------- There is only one possibility
 6768: 		     my ($mapid,$resid)=split(/\./,$ids);
 6769: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6770: 						    $resid,$thisfn);
 6771:                  } elsif (!$donotrecurse) {
 6772: # ------------------------------------------ There is more than one possibility
 6773:                      my $realpossible=0;
 6774:                      foreach my $id (@possibilities) {
 6775: 			 my $file=$bighash{'src_'.$id};
 6776:                          if (&allowed('bre',$file)) {
 6777:          		    my ($mapid,$resid)=split(/\./,$id);
 6778:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6779: 				$realpossible++;
 6780:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6781: 						    $resid,$thisfn);
 6782:                             }
 6783: 			 }
 6784:                      }
 6785: 		     if ($realpossible!=1) { $syval=''; }
 6786:                  } else {
 6787:                      $syval='';
 6788:                  }
 6789: 	      }
 6790:               untie(%bighash)
 6791:            }
 6792:         }
 6793:         if ($syval) {
 6794: 	    return $env{$cache_str}=$syval;
 6795:         }
 6796:     }
 6797:     &appenv('request.ambiguous' => $thisfn);
 6798:     return $env{$cache_str}='';
 6799: }
 6800: 
 6801: # ---------------------------------------------------------- Return random seed
 6802: 
 6803: sub numval {
 6804:     my $txt=shift;
 6805:     $txt=~tr/A-J/0-9/;
 6806:     $txt=~tr/a-j/0-9/;
 6807:     $txt=~tr/K-T/0-9/;
 6808:     $txt=~tr/k-t/0-9/;
 6809:     $txt=~tr/U-Z/0-5/;
 6810:     $txt=~tr/u-z/0-5/;
 6811:     $txt=~s/\D//g;
 6812:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6813:     return int($txt);
 6814: }
 6815: 
 6816: sub numval2 {
 6817:     my $txt=shift;
 6818:     $txt=~tr/A-J/0-9/;
 6819:     $txt=~tr/a-j/0-9/;
 6820:     $txt=~tr/K-T/0-9/;
 6821:     $txt=~tr/k-t/0-9/;
 6822:     $txt=~tr/U-Z/0-5/;
 6823:     $txt=~tr/u-z/0-5/;
 6824:     $txt=~s/\D//g;
 6825:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6826:     my $total;
 6827:     foreach my $val (@txts) { $total+=$val; }
 6828:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6829:     return int($total);
 6830: }
 6831: 
 6832: sub numval3 {
 6833:     use integer;
 6834:     my $txt=shift;
 6835:     $txt=~tr/A-J/0-9/;
 6836:     $txt=~tr/a-j/0-9/;
 6837:     $txt=~tr/K-T/0-9/;
 6838:     $txt=~tr/k-t/0-9/;
 6839:     $txt=~tr/U-Z/0-5/;
 6840:     $txt=~tr/u-z/0-5/;
 6841:     $txt=~s/\D//g;
 6842:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6843:     my $total;
 6844:     foreach my $val (@txts) { $total+=$val; }
 6845:     if ($_64bit) { $total=(($total<<32)>>32); }
 6846:     return $total;
 6847: }
 6848: 
 6849: sub digest {
 6850:     my ($data)=@_;
 6851:     my $digest=&Digest::MD5::md5($data);
 6852:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6853:     my ($e,$f);
 6854:     {
 6855:         use integer;
 6856:         $e=($a+$b);
 6857:         $f=($c+$d);
 6858:         if ($_64bit) {
 6859:             $e=(($e<<32)>>32);
 6860:             $f=(($f<<32)>>32);
 6861:         }
 6862:     }
 6863:     if (wantarray) {
 6864: 	return ($e,$f);
 6865:     } else {
 6866: 	my $g;
 6867: 	{
 6868: 	    use integer;
 6869: 	    $g=($e+$f);
 6870: 	    if ($_64bit) {
 6871: 		$g=(($g<<32)>>32);
 6872: 	    }
 6873: 	}
 6874: 	return $g;
 6875:     }
 6876: }
 6877: 
 6878: sub latest_rnd_algorithm_id {
 6879:     return '64bit5';
 6880: }
 6881: 
 6882: sub get_rand_alg {
 6883:     my ($courseid)=@_;
 6884:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6885:     if ($courseid) {
 6886: 	return $env{"course.$courseid.rndseed"};
 6887:     }
 6888:     return &latest_rnd_algorithm_id();
 6889: }
 6890: 
 6891: sub validCODE {
 6892:     my ($CODE)=@_;
 6893:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6894:     return 0;
 6895: }
 6896: 
 6897: sub getCODE {
 6898:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6899:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6900: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6901: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6902: 	return $Apache::lonhomework::history{'resource.CODE'};
 6903:     }
 6904:     return undef;
 6905: }
 6906: 
 6907: sub rndseed {
 6908:     my ($symb,$courseid,$domain,$username)=@_;
 6909: 
 6910:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6911:     if (!$symb) {
 6912: 	unless ($symb=$wsymb) { return time; }
 6913:     }
 6914:     if (!$courseid) { $courseid=$wcourseid; }
 6915:     if (!$domain) { $domain=$wdomain; }
 6916:     if (!$username) { $username=$wusername }
 6917:     my $which=&get_rand_alg();
 6918: 
 6919:     if (defined(&getCODE())) {
 6920: 	if ($which eq '64bit5') {
 6921: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6922: 	} elsif ($which eq '64bit4') {
 6923: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6924: 	} else {
 6925: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6926: 	}
 6927:     } elsif ($which eq '64bit5') {
 6928: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6929:     } elsif ($which eq '64bit4') {
 6930: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6931:     } elsif ($which eq '64bit3') {
 6932: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6933:     } elsif ($which eq '64bit2') {
 6934: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6935:     } elsif ($which eq '64bit') {
 6936: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6937:     }
 6938:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6939: }
 6940: 
 6941: sub rndseed_32bit {
 6942:     my ($symb,$courseid,$domain,$username)=@_;
 6943:     {
 6944: 	use integer;
 6945: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6946: 	my $symbseed=numval($symb) << 22;
 6947: 	my $namechck=unpack("%32C*",$username) << 17;
 6948: 	my $nameseed=numval($username) << 12;
 6949: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6950: 	my $courseseed=unpack("%32C*",$courseid);
 6951: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6952: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6953: 	#&logthis("rndseed :$num:$symb");
 6954: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6955: 	return $num;
 6956:     }
 6957: }
 6958: 
 6959: sub rndseed_64bit {
 6960:     my ($symb,$courseid,$domain,$username)=@_;
 6961:     {
 6962: 	use integer;
 6963: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6964: 	my $symbseed=numval($symb) << 10;
 6965: 	my $namechck=unpack("%32S*",$username);
 6966: 	
 6967: 	my $nameseed=numval($username) << 21;
 6968: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6969: 	my $courseseed=unpack("%32S*",$courseid);
 6970: 	
 6971: 	my $num1=$symbchck+$symbseed+$namechck;
 6972: 	my $num2=$nameseed+$domainseed+$courseseed;
 6973: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6974: 	#&logthis("rndseed :$num:$symb");
 6975: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6976: 	return "$num1,$num2";
 6977:     }
 6978: }
 6979: 
 6980: sub rndseed_64bit2 {
 6981:     my ($symb,$courseid,$domain,$username)=@_;
 6982:     {
 6983: 	use integer;
 6984: 	# strings need to be an even # of cahracters long, it it is odd the
 6985:         # last characters gets thrown away
 6986: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6987: 	my $symbseed=numval($symb) << 10;
 6988: 	my $namechck=unpack("%32S*",$username.' ');
 6989: 	
 6990: 	my $nameseed=numval($username) << 21;
 6991: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6992: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6993: 	
 6994: 	my $num1=$symbchck+$symbseed+$namechck;
 6995: 	my $num2=$nameseed+$domainseed+$courseseed;
 6996: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6997: 	#&logthis("rndseed :$num:$symb");
 6998: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6999: 	return "$num1,$num2";
 7000:     }
 7001: }
 7002: 
 7003: sub rndseed_64bit3 {
 7004:     my ($symb,$courseid,$domain,$username)=@_;
 7005:     {
 7006: 	use integer;
 7007: 	# strings need to be an even # of cahracters long, it it is odd the
 7008:         # last characters gets thrown away
 7009: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7010: 	my $symbseed=numval2($symb) << 10;
 7011: 	my $namechck=unpack("%32S*",$username.' ');
 7012: 	
 7013: 	my $nameseed=numval2($username) << 21;
 7014: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7015: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7016: 	
 7017: 	my $num1=$symbchck+$symbseed+$namechck;
 7018: 	my $num2=$nameseed+$domainseed+$courseseed;
 7019: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7020: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7021: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7022: 	
 7023: 	return "$num1:$num2";
 7024:     }
 7025: }
 7026: 
 7027: sub rndseed_64bit4 {
 7028:     my ($symb,$courseid,$domain,$username)=@_;
 7029:     {
 7030: 	use integer;
 7031: 	# strings need to be an even # of cahracters long, it it is odd the
 7032:         # last characters gets thrown away
 7033: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7034: 	my $symbseed=numval3($symb) << 10;
 7035: 	my $namechck=unpack("%32S*",$username.' ');
 7036: 	
 7037: 	my $nameseed=numval3($username) << 21;
 7038: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7039: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7040: 	
 7041: 	my $num1=$symbchck+$symbseed+$namechck;
 7042: 	my $num2=$nameseed+$domainseed+$courseseed;
 7043: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7044: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7045: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7046: 	
 7047: 	return "$num1:$num2";
 7048:     }
 7049: }
 7050: 
 7051: sub rndseed_64bit5 {
 7052:     my ($symb,$courseid,$domain,$username)=@_;
 7053:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7054:     return "$num1:$num2";
 7055: }
 7056: 
 7057: sub rndseed_CODE_64bit {
 7058:     my ($symb,$courseid,$domain,$username)=@_;
 7059:     {
 7060: 	use integer;
 7061: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7062: 	my $symbseed=numval2($symb);
 7063: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7064: 	my $CODEseed=numval(&getCODE());
 7065: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7066: 	my $num1=$symbseed+$CODEchck;
 7067: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7068: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7069: 	#&logthis("rndseed :$num1:$num2:$symb");
 7070: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7071: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7072: 	return "$num1:$num2";
 7073:     }
 7074: }
 7075: 
 7076: sub rndseed_CODE_64bit4 {
 7077:     my ($symb,$courseid,$domain,$username)=@_;
 7078:     {
 7079: 	use integer;
 7080: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7081: 	my $symbseed=numval3($symb);
 7082: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7083: 	my $CODEseed=numval3(&getCODE());
 7084: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7085: 	my $num1=$symbseed+$CODEchck;
 7086: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7087: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7088: 	#&logthis("rndseed :$num1:$num2:$symb");
 7089: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7090: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7091: 	return "$num1:$num2";
 7092:     }
 7093: }
 7094: 
 7095: sub rndseed_CODE_64bit5 {
 7096:     my ($symb,$courseid,$domain,$username)=@_;
 7097:     my $code = &getCODE();
 7098:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7099:     return "$num1:$num2";
 7100: }
 7101: 
 7102: sub setup_random_from_rndseed {
 7103:     my ($rndseed)=@_;
 7104:     if ($rndseed =~/([,:])/) {
 7105: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7106: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7107:     } else {
 7108: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7109:     }
 7110: }
 7111: 
 7112: sub latest_receipt_algorithm_id {
 7113:     return 'receipt3';
 7114: }
 7115: 
 7116: sub recunique {
 7117:     my $fucourseid=shift;
 7118:     my $unique;
 7119:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7120: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7121: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7122:     } else {
 7123: 	$unique=$perlvar{'lonReceipt'};
 7124:     }
 7125:     return unpack("%32C*",$unique);
 7126: }
 7127: 
 7128: sub recprefix {
 7129:     my $fucourseid=shift;
 7130:     my $prefix;
 7131:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7132: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7133: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7134:     } else {
 7135: 	$prefix=$perlvar{'lonHostID'};
 7136:     }
 7137:     return unpack("%32C*",$prefix);
 7138: }
 7139: 
 7140: sub ireceipt {
 7141:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7142: 
 7143:     my $return =&recprefix($fucourseid).'-';
 7144: 
 7145:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7146: 	$env{'request.state'} eq 'construct') {
 7147: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7148: 	return $return;
 7149:     }
 7150: 
 7151:     my $cuname=unpack("%32C*",$funame);
 7152:     my $cudom=unpack("%32C*",$fudom);
 7153:     my $cucourseid=unpack("%32C*",$fucourseid);
 7154:     my $cusymb=unpack("%32C*",$fusymb);
 7155:     my $cunique=&recunique($fucourseid);
 7156:     my $cpart=unpack("%32S*",$part);
 7157:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7158: 
 7159: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7160: 			       
 7161: 	$return.= ($cunique%$cuname+
 7162: 		   $cunique%$cudom+
 7163: 		   $cusymb%$cuname+
 7164: 		   $cusymb%$cudom+
 7165: 		   $cucourseid%$cuname+
 7166: 		   $cucourseid%$cudom+
 7167: 		   $cpart%$cuname+
 7168: 		   $cpart%$cudom);
 7169:     } else {
 7170: 	$return.= ($cunique%$cuname+
 7171: 		   $cunique%$cudom+
 7172: 		   $cusymb%$cuname+
 7173: 		   $cusymb%$cudom+
 7174: 		   $cucourseid%$cuname+
 7175: 		   $cucourseid%$cudom);
 7176:     }
 7177:     return $return;
 7178: }
 7179: 
 7180: sub receipt {
 7181:     my ($part)=@_;
 7182:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7183:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7184: }
 7185: 
 7186: sub whichuser {
 7187:     my ($passedsymb)=@_;
 7188:     my ($symb,$courseid,$domain,$name,$publicuser);
 7189:     if (defined($env{'form.grade_symb'})) {
 7190: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7191: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7192: 	if (!$allowed &&
 7193: 	    exists($env{'request.course.sec'}) &&
 7194: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7195: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7196: 			      '/'.$env{'request.course.sec'});
 7197: 	}
 7198: 	if ($allowed) {
 7199: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7200: 	    $courseid=$tmp_courseid;
 7201: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7202: 	    ($name)=&get_env_multiple('form.grade_username');
 7203: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7204: 	}
 7205:     }
 7206:     if (!$passedsymb) {
 7207: 	$symb=&symbread();
 7208:     } else {
 7209: 	$symb=$passedsymb;
 7210:     }
 7211:     $courseid=$env{'request.course.id'};
 7212:     $domain=$env{'user.domain'};
 7213:     $name=$env{'user.name'};
 7214:     if ($name eq 'public' && $domain eq 'public') {
 7215: 	if (!defined($env{'form.username'})) {
 7216: 	    $env{'form.username'}.=time.rand(10000000);
 7217: 	}
 7218: 	$name.=$env{'form.username'};
 7219:     }
 7220:     return ($symb,$courseid,$domain,$name,$publicuser);
 7221: 
 7222: }
 7223: 
 7224: # ------------------------------------------------------------ Serves up a file
 7225: # returns either the contents of the file or 
 7226: # -1 if the file doesn't exist
 7227: #
 7228: # if the target is a file that was uploaded via DOCS, 
 7229: # a check will be made to see if a current copy exists on the local server,
 7230: # if it does this will be served, otherwise a copy will be retrieved from
 7231: # the home server for the course and stored in /home/httpd/html/userfiles on
 7232: # the local server.   
 7233: 
 7234: sub getfile {
 7235:     my ($file) = @_;
 7236:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7237:     &repcopy($file);
 7238:     return &readfile($file);
 7239: }
 7240: 
 7241: sub repcopy_userfile {
 7242:     my ($file)=@_;
 7243:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7244:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7245:     my ($cdom,$cnum,$filename) = 
 7246: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7247:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7248:     if (-e "$file") {
 7249: # we already have a local copy, check it out
 7250: 	my @fileinfo = stat($file);
 7251: 	my $rtncode;
 7252: 	my $info;
 7253: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7254: 	if ($lwpresp ne 'ok') {
 7255: # there is no such file anymore, even though we had a local copy
 7256: 	    if ($rtncode eq '404') {
 7257: 		unlink($file);
 7258: 	    }
 7259: 	    return -1;
 7260: 	}
 7261: 	if ($info < $fileinfo[9]) {
 7262: # nice, the file we have is up-to-date, just say okay
 7263: 	    return 'ok';
 7264: 	} else {
 7265: # the file is outdated, get rid of it
 7266: 	    unlink($file);
 7267: 	}
 7268:     }
 7269: # one way or the other, at this point, we don't have the file
 7270: # construct the correct path for the file
 7271:     my @parts = ($cdom,$cnum); 
 7272:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7273: 	push @parts, split(/\//,$1);
 7274:     }
 7275:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7276:     foreach my $part (@parts) {
 7277: 	$path .= '/'.$part;
 7278: 	if (!-e $path) {
 7279: 	    mkdir($path,0770);
 7280: 	}
 7281:     }
 7282: # now the path exists for sure
 7283: # get a user agent
 7284:     my $ua=new LWP::UserAgent;
 7285:     my $transferfile=$file.'.in.transfer';
 7286: # FIXME: this should flock
 7287:     if (-e $transferfile) { return 'ok'; }
 7288:     my $request;
 7289:     $uri=~s/^\///;
 7290:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7291:     my $response=$ua->request($request,$transferfile);
 7292: # did it work?
 7293:     if ($response->is_error()) {
 7294: 	unlink($transferfile);
 7295: 	&logthis("Userfile repcopy failed for $uri");
 7296: 	return -1;
 7297:     }
 7298: # worked, rename the transfer file
 7299:     rename($transferfile,$file);
 7300:     return 'ok';
 7301: }
 7302: 
 7303: sub tokenwrapper {
 7304:     my $uri=shift;
 7305:     $uri=~s|^http\://([^/]+)||;
 7306:     $uri=~s|^/||;
 7307:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7308:     my $token=$1;
 7309:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7310:     if ($udom && $uname && $file) {
 7311: 	$file=~s|(\?\.*)*$||;
 7312:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7313:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7314:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7315:                                '&tokenissued='.$perlvar{'lonHostID'};
 7316:     } else {
 7317:         return '/adm/notfound.html';
 7318:     }
 7319: }
 7320: 
 7321: # call with reqtype HEAD: get last modification time
 7322: # call with reqtype GET: get the file contents
 7323: # Do not call this with reqtype GET for large files! It loads everything into memory
 7324: #
 7325: sub getuploaded {
 7326:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7327:     $uri=~s/^\///;
 7328:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7329:     my $ua=new LWP::UserAgent;
 7330:     my $request=new HTTP::Request($reqtype,$uri);
 7331:     my $response=$ua->request($request);
 7332:     $$rtncode = $response->code;
 7333:     if (! $response->is_success()) {
 7334: 	return 'failed';
 7335:     }      
 7336:     if ($reqtype eq 'HEAD') {
 7337: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7338:     } elsif ($reqtype eq 'GET') {
 7339: 	$$info = $response->content;
 7340:     }
 7341:     return 'ok';
 7342: }
 7343: 
 7344: sub readfile {
 7345:     my $file = shift;
 7346:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7347:     my $fh;
 7348:     open($fh,"<$file");
 7349:     my $a='';
 7350:     while (my $line = <$fh>) { $a .= $line; }
 7351:     return $a;
 7352: }
 7353: 
 7354: sub filelocation {
 7355:     my ($dir,$file) = @_;
 7356:     my $location;
 7357:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7358: 
 7359:     if ($file =~ m-^/adm/-) {
 7360: 	$file=~s-^/adm/wrapper/-/-;
 7361: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7362:     }
 7363:     if ($file=~m:^/~:) { # is a contruction space reference
 7364:         $location = $file;
 7365:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7366:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7367: 	# is a correct contruction space reference
 7368:         $location = $file;
 7369:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7370:         my ($udom,$uname,$filename)=
 7371:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7372:         my $home=&homeserver($uname,$udom);
 7373:         my $is_me=0;
 7374:         my @ids=&current_machine_ids();
 7375:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7376:         if ($is_me) {
 7377:   	    $location=&propath($udom,$uname).
 7378:   	      '/userfiles/'.$filename;
 7379:         } else {
 7380:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7381:   	      $udom.'/'.$uname.'/'.$filename;
 7382:         }
 7383:     } else {
 7384:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7385:         $file=~s:^/res/:/:;
 7386:         if ( !( $file =~ m:^/:) ) {
 7387:             $location = $dir. '/'.$file;
 7388:         } else {
 7389:             $location = '/home/httpd/html/res'.$file;
 7390:         }
 7391:     }
 7392:     $location=~s://+:/:g; # remove duplicate /
 7393:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7394:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7395:     return $location;
 7396: }
 7397: 
 7398: sub hreflocation {
 7399:     my ($dir,$file)=@_;
 7400:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7401: 	$file=filelocation($dir,$file);
 7402:     } elsif ($file=~m-^/adm/-) {
 7403: 	$file=~s-^/adm/wrapper/-/-;
 7404: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7405:     }
 7406:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7407: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7408:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7409: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7410:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7411: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7412: 	    -/uploaded/$1/$2/-x;
 7413:     }
 7414:     return $file;
 7415: }
 7416: 
 7417: sub current_machine_domains {
 7418:     my $hostname=&hostname($perlvar{'lonHostID'});
 7419:     my @domains;
 7420:     my %hostname = &all_hostnames();
 7421:     while( my($id, $name) = each(%hostname)) {
 7422: #	&logthis("-$id-$name-$hostname-");
 7423: 	if ($hostname eq $name) {
 7424: 	    push(@domains,$hostdom{$id});
 7425: 	}
 7426:     }
 7427:     return @domains;
 7428: }
 7429: 
 7430: sub current_machine_ids {
 7431:     my $hostname=&hostname($perlvar{'lonHostID'});
 7432:     my @ids;
 7433:     my %hostname = &all_hostnames();
 7434:     while( my($id, $name) = each(%hostname)) {
 7435: #	&logthis("-$id-$name-$hostname-");
 7436: 	if ($hostname eq $name) {
 7437: 	    push(@ids,$id);
 7438: 	}
 7439:     }
 7440:     return @ids;
 7441: }
 7442: 
 7443: sub additional_machine_domains {
 7444:     my @domains;
 7445:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7446:     while( my $line = <$fh>) {
 7447:         $line =~ s/\s//g;
 7448:         push(@domains,$line);
 7449:     }
 7450:     return @domains;
 7451: }
 7452: 
 7453: sub default_login_domain {
 7454:     my $domain = $perlvar{'lonDefDomain'};
 7455:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7456:     foreach my $posdom (&current_machine_domains(),
 7457:                         &additional_machine_domains()) {
 7458:         if (lc($posdom) eq lc($testdomain)) {
 7459:             $domain=$posdom;
 7460:             last;
 7461:         }
 7462:     }
 7463:     return $domain;
 7464: }
 7465: 
 7466: # ------------------------------------------------------------- Declutters URLs
 7467: 
 7468: sub declutter {
 7469:     my $thisfn=shift;
 7470:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7471:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7472:     $thisfn=~s/^\///;
 7473:     $thisfn=~s|^adm/wrapper/||;
 7474:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7475:     $thisfn=~s/^res\///;
 7476:     $thisfn=~s/\?.+$//;
 7477:     return $thisfn;
 7478: }
 7479: 
 7480: # ------------------------------------------------------------- Clutter up URLs
 7481: 
 7482: sub clutter {
 7483:     my $thisfn='/'.&declutter(shift);
 7484:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7485:        $thisfn='/res'.$thisfn; 
 7486:     }
 7487:     if ($thisfn !~m|/adm|) {
 7488: 	if ($thisfn =~ m|/ext/|) {
 7489: 	    $thisfn='/adm/wrapper'.$thisfn;
 7490: 	} else {
 7491: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7492: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7493: 	    if ($embstyle eq 'ssi'
 7494: 		|| ($embstyle eq 'hdn')
 7495: 		|| ($embstyle eq 'rat')
 7496: 		|| ($embstyle eq 'prv')
 7497: 		|| ($embstyle eq 'ign')) {
 7498: 		#do nothing with these
 7499: 	    } elsif (($embstyle eq 'img') 
 7500: 		|| ($embstyle eq 'emb')
 7501: 		|| ($embstyle eq 'wrp')) {
 7502: 		$thisfn='/adm/wrapper'.$thisfn;
 7503: 	    } elsif ($embstyle eq 'unk'
 7504: 		     && $thisfn!~/\.(sequence|page)$/) {
 7505: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7506: 	    } else {
 7507: #		&logthis("Got a blank emb style");
 7508: 	    }
 7509: 	}
 7510:     }
 7511:     return $thisfn;
 7512: }
 7513: 
 7514: sub clutter_with_no_wrapper {
 7515:     my $uri = &clutter(shift);
 7516:     if ($uri =~ m-^/adm/-) {
 7517: 	$uri =~ s-^/adm/wrapper/-/-;
 7518: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7519:     }
 7520:     return $uri;
 7521: }
 7522: 
 7523: sub freeze_escape {
 7524:     my ($value)=@_;
 7525:     if (ref($value)) {
 7526: 	$value=&nfreeze($value);
 7527: 	return '__FROZEN__'.&escape($value);
 7528:     }
 7529:     return &escape($value);
 7530: }
 7531: 
 7532: 
 7533: sub thaw_unescape {
 7534:     my ($value)=@_;
 7535:     if ($value =~ /^__FROZEN__/) {
 7536: 	substr($value,0,10,undef);
 7537: 	$value=&unescape($value);
 7538: 	return &thaw($value);
 7539:     }
 7540:     return &unescape($value);
 7541: }
 7542: 
 7543: sub correct_line_ends {
 7544:     my ($result)=@_;
 7545:     $$result =~s/\r\n/\n/mg;
 7546:     $$result =~s/\r/\n/mg;
 7547: }
 7548: # ================================================================ Main Program
 7549: 
 7550: sub goodbye {
 7551:    &logthis("Starting Shut down");
 7552: #not converted to using infrastruture and probably shouldn't be
 7553:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7554: #converted
 7555: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7556:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7557: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7558: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7559: #1.1 only
 7560: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7561: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7562: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7563: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7564:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7565:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7566:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7567:    &flushcourselogs();
 7568:    &logthis("Shutting down");
 7569: }
 7570: 
 7571: BEGIN {
 7572: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7573:     unless ($readit) {
 7574: {
 7575:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7576:     %perlvar = (%perlvar,%{$configvars});
 7577: }
 7578: 
 7579: # ------------------------------------------------------------ Read domain file
 7580: {
 7581:     %domaindescription = ();
 7582:     %domain_auth_def = ();
 7583:     %domain_auth_arg_def = ();
 7584:     my $fh;
 7585:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7586: 	while (my $line = <$fh>) {
 7587:            next if ($line =~ /^(\#|\s*$)/);
 7588: #           next if /^\#/;
 7589:            chomp $line;
 7590:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7591: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
 7592: 	   $domain_auth_def{$domain}=$def_auth;
 7593:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7594: 	   $domaindescription{$domain}=$domain_description;
 7595: 	   $domain_lang_def{$domain}=$def_lang;
 7596: 	   $domain_city{$domain}=$city;
 7597: 	   $domain_longi{$domain}=$longi;
 7598: 	   $domain_lati{$domain}=$lati;
 7599:            $domain_primary{$domain}=$primary;
 7600: 
 7601:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7602: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7603: 	}
 7604:     }
 7605:     close ($fh);
 7606: }
 7607: 
 7608: 
 7609: # ------------------------------------------------------------- Read hosts file
 7610: {
 7611:     my %hostname;
 7612:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7613: 
 7614:     while (my $configline=<$config>) {
 7615:        next if ($configline =~ /^(\#|\s*$)/);
 7616:        chomp($configline);
 7617:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7618:        $name=~s/\s//g;
 7619:        if ($id && $domain && $role && $name) {
 7620: 	 $hostname{$id}=$name;
 7621: 	 $hostdom{$id}=$domain;
 7622: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7623:        }
 7624:     }
 7625:     close($config);
 7626:     # FIXME: dev server don't want this, production servers _do_ want this
 7627:     #&get_iphost();
 7628: 
 7629:     sub hostname {
 7630: 	my ($lonid) = @_;
 7631: 	return $hostname{$lonid};
 7632:     }
 7633:     sub all_hostnames {
 7634: 	return %hostname;
 7635:     }
 7636: }
 7637: 
 7638: sub get_hosts_from_ip {
 7639:     my ($ip) = @_;
 7640:     my %iphosts = &get_iphost();
 7641:     if (ref($iphosts{$ip})) {
 7642: 	return @{$iphosts{$ip}};
 7643:     }
 7644:     return;
 7645: }
 7646: 
 7647: sub get_iphost {
 7648:     if (%iphost) { return %iphost; }
 7649:     my %name_to_ip;
 7650:     my %hostname = &all_hostnames();
 7651:     foreach my $id (keys(%hostname)) {
 7652: 	my $name=$hostname{$id};
 7653: 	my $ip;
 7654: 	if (!exists($name_to_ip{$name})) {
 7655: 	    $ip = gethostbyname($name);
 7656: 	    if (!$ip || length($ip) ne 4) {
 7657: 		&logthis("Skipping host $id name $name no IP found");
 7658: 		next;
 7659: 	    }
 7660: 	    $ip=inet_ntoa($ip);
 7661: 	    $name_to_ip{$name} = $ip;
 7662: 	} else {
 7663: 	    $ip = $name_to_ip{$name};
 7664: 	}
 7665: 	push(@{$iphost{$ip}},$id);
 7666:     }
 7667:     return %iphost;
 7668: }
 7669: 
 7670: # ------------------------------------------------------ Read spare server file
 7671: {
 7672:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7673: 
 7674:     while (my $configline=<$config>) {
 7675:        chomp($configline);
 7676:        if ($configline) {
 7677: 	   my ($host,$type) = split(':',$configline,2);
 7678: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7679: 	   push(@{ $spareid{$type} }, $host);
 7680:        }
 7681:     }
 7682:     close($config);
 7683: }
 7684: # ------------------------------------------------------------ Read permissions
 7685: {
 7686:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7687: 
 7688:     while (my $configline=<$config>) {
 7689: 	chomp($configline);
 7690: 	if ($configline) {
 7691: 	    my ($role,$perm)=split(/ /,$configline);
 7692: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7693: 	}
 7694:     }
 7695:     close($config);
 7696: }
 7697: 
 7698: # -------------------------------------------- Read plain texts for permissions
 7699: {
 7700:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7701: 
 7702:     while (my $configline=<$config>) {
 7703: 	chomp($configline);
 7704: 	if ($configline) {
 7705: 	    my ($short,@plain)=split(/:/,$configline);
 7706:             %{$prp{$short}} = ();
 7707: 	    if (@plain > 0) {
 7708:                 $prp{$short}{'std'} = $plain[0];
 7709:                 for (my $i=1; $i<@plain; $i++) {
 7710:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7711:                 }
 7712:             }
 7713: 	}
 7714:     }
 7715:     close($config);
 7716: }
 7717: 
 7718: # ---------------------------------------------------------- Read package table
 7719: {
 7720:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7721: 
 7722:     while (my $configline=<$config>) {
 7723: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7724: 	chomp($configline);
 7725: 	my ($short,$plain)=split(/:/,$configline);
 7726: 	my ($pack,$name)=split(/\&/,$short);
 7727: 	if ($plain ne '') {
 7728: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7729: 	    $packagetab{$short}=$plain; 
 7730: 	}
 7731:     }
 7732:     close($config);
 7733: }
 7734: 
 7735: # ------------- set up temporary directory
 7736: {
 7737:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7738: 
 7739: }
 7740: 
 7741: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7742: 				'compress_threshold'=> 20_000,
 7743:  			        });
 7744: 
 7745: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7746: $dumpcount=0;
 7747: 
 7748: &logtouch();
 7749: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7750: $readit=1;
 7751:     {
 7752: 	use integer;
 7753: 	my $test=(2**32)+1;
 7754: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7755: 	&logthis(" Detected 64bit platform ($_64bit)");
 7756:     }
 7757: }
 7758: }
 7759: 
 7760: 1;
 7761: __END__
 7762: 
 7763: =pod
 7764: 
 7765: =head1 NAME
 7766: 
 7767: Apache::lonnet - Subroutines to ask questions about things in the network.
 7768: 
 7769: =head1 SYNOPSIS
 7770: 
 7771: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7772: 
 7773:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7774: 
 7775: Common parameters:
 7776: 
 7777: =over 4
 7778: 
 7779: =item *
 7780: 
 7781: $uname : an internal username (if $cname expecting a course Id specifically)
 7782: 
 7783: =item *
 7784: 
 7785: $udom : a domain (if $cdom expecting a course's domain specifically)
 7786: 
 7787: =item *
 7788: 
 7789: $symb : a resource instance identifier
 7790: 
 7791: =item *
 7792: 
 7793: $namespace : the name of a .db file that contains the data needed or
 7794: being set.
 7795: 
 7796: =back
 7797: 
 7798: =head1 OVERVIEW
 7799: 
 7800: lonnet provides subroutines which interact with the
 7801: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7802: about classes, users, and resources.
 7803: 
 7804: For many of these objects you can also use this to store data about
 7805: them or modify them in various ways.
 7806: 
 7807: =head2 Symbs
 7808: 
 7809: To identify a specific instance of a resource, LON-CAPA uses symbols
 7810: or "symbs"X<symb>. These identifiers are built from the URL of the
 7811: map, the resource number of the resource in the map, and the URL of
 7812: the resource itself. The latter is somewhat redundant, but might help
 7813: if maps change.
 7814: 
 7815: An example is
 7816: 
 7817:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7818: 
 7819: The respective map entry is
 7820: 
 7821:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7822:   title="Problem 2">
 7823:  </resource>
 7824: 
 7825: Symbs are used by the random number generator, as well as to store and
 7826: restore data specific to a certain instance of for example a problem.
 7827: 
 7828: =head2 Storing And Retrieving Data
 7829: 
 7830: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7831: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7832: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7833: is is the non-critical message twin of cstore. These functions are for
 7834: handlers to store a perl hash to a user's permanent data space in an
 7835: easy manner, and to retrieve it again on another call. It is expected
 7836: that a handler would use this once at the beginning to retrieve data,
 7837: and then again once at the end to send only the new data back.
 7838: 
 7839: The data is stored in the user's data directory on the user's
 7840: homeserver under the ID of the course.
 7841: 
 7842: The hash that is returned by restore will have all of the previous
 7843: value for all of the elements of the hash.
 7844: 
 7845: Example:
 7846: 
 7847:  #creating a hash
 7848:  my %hash;
 7849:  $hash{'foo'}='bar';
 7850: 
 7851:  #storing it
 7852:  &Apache::lonnet::cstore(\%hash);
 7853: 
 7854:  #changing a value
 7855:  $hash{'foo'}='notbar';
 7856: 
 7857:  #adding a new value
 7858:  $hash{'bar'}='foo';
 7859:  &Apache::lonnet::cstore(\%hash);
 7860: 
 7861:  #retrieving the hash
 7862:  my %history=&Apache::lonnet::restore();
 7863: 
 7864:  #print the hash
 7865:  foreach my $key (sort(keys(%history))) {
 7866:    print("\%history{$key} = $history{$key}");
 7867:  }
 7868: 
 7869: Will print out:
 7870: 
 7871:  %history{1:foo} = bar
 7872:  %history{1:keys} = foo:timestamp
 7873:  %history{1:timestamp} = 990455579
 7874:  %history{2:bar} = foo
 7875:  %history{2:foo} = notbar
 7876:  %history{2:keys} = foo:bar:timestamp
 7877:  %history{2:timestamp} = 990455580
 7878:  %history{bar} = foo
 7879:  %history{foo} = notbar
 7880:  %history{timestamp} = 990455580
 7881:  %history{version} = 2
 7882: 
 7883: Note that the special hash entries C<keys>, C<version> and
 7884: C<timestamp> were added to the hash. C<version> will be equal to the
 7885: total number of versions of the data that have been stored. The
 7886: C<timestamp> attribute will be the UNIX time the hash was
 7887: stored. C<keys> is available in every historical section to list which
 7888: keys were added or changed at a specific historical revision of a
 7889: hash.
 7890: 
 7891: B<Warning>: do not store the hash that restore returns directly. This
 7892: will cause a mess since it will restore the historical keys as if the
 7893: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7894: 
 7895: Calling convention:
 7896: 
 7897:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7898:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7899: 
 7900: For more detailed information, see lonnet specific documentation.
 7901: 
 7902: =head1 RETURN MESSAGES
 7903: 
 7904: =over 4
 7905: 
 7906: =item * B<con_lost>: unable to contact remote host
 7907: 
 7908: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7909: when the connection is brought back up
 7910: 
 7911: =item * B<con_failed>: unable to contact remote host and unable to save message
 7912: for later delivery
 7913: 
 7914: =item * B<error:>: an error a occured, a description of the error follows the :
 7915: 
 7916: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7917: that was requested
 7918: 
 7919: =back
 7920: 
 7921: =head1 PUBLIC SUBROUTINES
 7922: 
 7923: =head2 Session Environment Functions
 7924: 
 7925: =over 4
 7926: 
 7927: =item * 
 7928: X<appenv()>
 7929: B<appenv(%hash)>: the value of %hash is written to
 7930: the user envirnoment file, and will be restored for each access this
 7931: user makes during this session, also modifies the %env for the current
 7932: process
 7933: 
 7934: =item *
 7935: X<delenv()>
 7936: B<delenv($regexp)>: removes all items from the session
 7937: environment file that matches the regular expression in $regexp. The
 7938: values are also delted from the current processes %env.
 7939: 
 7940: =item * get_env_multiple($name) 
 7941: 
 7942: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7943: values may be defined and end up as an array ref.
 7944: 
 7945: returns an array of values
 7946: 
 7947: =back
 7948: 
 7949: =head2 User Information
 7950: 
 7951: =over 4
 7952: 
 7953: =item *
 7954: X<queryauthenticate()>
 7955: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7956: authentication scheme
 7957: 
 7958: =item *
 7959: X<authenticate()>
 7960: B<authenticate($uname,$upass,$udom)>: try to
 7961: authenticate user from domain's lib servers (first use the current
 7962: one). C<$upass> should be the users password.
 7963: 
 7964: =item *
 7965: X<homeserver()>
 7966: B<homeserver($uname,$udom)>: find the server which has
 7967: the user's directory and files (there must be only one), this caches
 7968: the answer, and also caches if there is a borken connection.
 7969: 
 7970: =item *
 7971: X<idget()>
 7972: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7973: (IDs are a unique resource in a domain, there must be only 1 ID per
 7974: username, and only 1 username per ID in a specific domain) (returns
 7975: hash: id=>name,id=>name)
 7976: 
 7977: =item *
 7978: X<idrget()>
 7979: B<idrget($udom,@unames)>: find the IDs behind a list of
 7980: usernames (returns hash: name=>id,name=>id)
 7981: 
 7982: =item *
 7983: X<idput()>
 7984: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7985: 
 7986: =item *
 7987: X<rolesinit()>
 7988: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7989: 
 7990: =item *
 7991: X<getsection()>
 7992: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7993: course $cname, return section name/number or '' for "not in course"
 7994: and '-1' for "no section"
 7995: 
 7996: =item *
 7997: X<userenvironment()>
 7998: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7999: passed in @what from the requested user's environment, returns a hash
 8000: 
 8001: =back
 8002: 
 8003: =head2 User Roles
 8004: 
 8005: =over 4
 8006: 
 8007: =item *
 8008: 
 8009: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8010:  F: full access
 8011:  U,I,K: authentication modes (cxx only)
 8012:  '': forbidden
 8013:  1: user needs to choose course
 8014:  2: browse allowed
 8015:  A: passphrase authentication needed
 8016: 
 8017: =item *
 8018: 
 8019: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8020: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8021: and course level
 8022: 
 8023: =item *
 8024: 
 8025: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8026: explanation of a user role term
 8027: 
 8028: =item *
 8029: 
 8030: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
 8031: optional.  Returns a hash of a user's roles, with keys set to
 8032: colon-sparated $uname,$udom,and $role, and value set to
 8033: colon-separated start and end times for the role. If no username and
 8034: domain are specified, will default to current user/domain. Types,
 8035: roles, and roledoms are references to arrays, of role statuses
 8036: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
 8037: of the roles which can be used to restrict the list if roles
 8038: reported. If no array ref is provided for types, will default to
 8039: return only active roles.
 8040: 
 8041: =back
 8042: 
 8043: =head2 User Modification
 8044: 
 8045: =over 4
 8046: 
 8047: =item *
 8048: 
 8049: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8050: user for the level given by URL.  Optional start and end dates (leave empty
 8051: string or zero for "no date")
 8052: 
 8053: =item *
 8054: 
 8055: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8056: change a users, password, possible return values are: ok,
 8057: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8058: refused
 8059: 
 8060: =item *
 8061: 
 8062: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8063: 
 8064: =item *
 8065: 
 8066: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8067: modify user
 8068: 
 8069: =item *
 8070: 
 8071: modifystudent
 8072: 
 8073: modify a students enrollment and identification information.
 8074: The course id is resolved based on the current users environment.  
 8075: This means the envoking user must be a course coordinator or otherwise
 8076: associated with a course.
 8077: 
 8078: This call is essentially a wrapper for lonnet::modifyuser and
 8079: lonnet::modify_student_enrollment
 8080: 
 8081: Inputs: 
 8082: 
 8083: =over 4
 8084: 
 8085: =item B<$udom> Students loncapa domain
 8086: 
 8087: =item B<$uname> Students loncapa login name
 8088: 
 8089: =item B<$uid> Students id/student number
 8090: 
 8091: =item B<$umode> Students authentication mode
 8092: 
 8093: =item B<$upass> Students password
 8094: 
 8095: =item B<$first> Students first name
 8096: 
 8097: =item B<$middle> Students middle name
 8098: 
 8099: =item B<$last> Students last name
 8100: 
 8101: =item B<$gene> Students generation
 8102: 
 8103: =item B<$usec> Students section in course
 8104: 
 8105: =item B<$end> Unix time of the roles expiration
 8106: 
 8107: =item B<$start> Unix time of the roles start date
 8108: 
 8109: =item B<$forceid> If defined, allow $uid to be changed
 8110: 
 8111: =item B<$desiredhome> server to use as home server for student
 8112: 
 8113: =back
 8114: 
 8115: =item *
 8116: 
 8117: modify_student_enrollment
 8118: 
 8119: Change a students enrollment status in a class.  The environment variable
 8120: 'role.request.course' must be defined for this function to proceed.
 8121: 
 8122: Inputs:
 8123: 
 8124: =over 4
 8125: 
 8126: =item $udom, students domain
 8127: 
 8128: =item $uname, students name
 8129: 
 8130: =item $uid, students user id
 8131: 
 8132: =item $first, students first name
 8133: 
 8134: =item $middle
 8135: 
 8136: =item $last
 8137: 
 8138: =item $gene
 8139: 
 8140: =item $usec
 8141: 
 8142: =item $end
 8143: 
 8144: =item $start
 8145: 
 8146: =back
 8147: 
 8148: 
 8149: =item *
 8150: 
 8151: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8152: custom role; give a custom role to a user for the level given by URL.  Specify
 8153: name and domain of role author, and role name
 8154: 
 8155: =item *
 8156: 
 8157: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8158: 
 8159: =item *
 8160: 
 8161: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8162: 
 8163: =back
 8164: 
 8165: =head2 Course Infomation
 8166: 
 8167: =over 4
 8168: 
 8169: =item *
 8170: 
 8171: coursedescription($courseid) : returns a hash of information about the
 8172: specified course id, including all environment settings for the
 8173: course, the description of the course will be in the hash under the
 8174: key 'description'
 8175: 
 8176: =item *
 8177: 
 8178: resdata($name,$domain,$type,@which) : request for current parameter
 8179: setting for a specific $type, where $type is either 'course' or 'user',
 8180: @what should be a list of parameters to ask about. This routine caches
 8181: answers for 5 minutes.
 8182: 
 8183: =back
 8184: 
 8185: =head2 Course Modification
 8186: 
 8187: =over 4
 8188: 
 8189: =item *
 8190: 
 8191: writecoursepref($courseid,%prefs) : write preferences (environment
 8192: database) for a course
 8193: 
 8194: =item *
 8195: 
 8196: createcourse($udom,$description,$url) : make/modify course
 8197: 
 8198: =back
 8199: 
 8200: =head2 Resource Subroutines
 8201: 
 8202: =over 4
 8203: 
 8204: =item *
 8205: 
 8206: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8207: 
 8208: =item *
 8209: 
 8210: repcopy($filename) : subscribes to the requested file, and attempts to
 8211: replicate from the owning library server, Might return
 8212: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8213: 'bad_request', also attempts to grab the metadata for the
 8214: resource. Expects the local filesystem pathname
 8215: (/home/httpd/html/res/....)
 8216: 
 8217: =back
 8218: 
 8219: =head2 Resource Information
 8220: 
 8221: =over 4
 8222: 
 8223: =item *
 8224: 
 8225: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8226: a vairety of different possible values, $varname should be a request
 8227: string, and the other parameters can be used to specify who and what
 8228: one is asking about.
 8229: 
 8230: Possible values for $varname are environment.lastname (or other item
 8231: from the envirnment hash), user.name (or someother aspect about the
 8232: user), resource.0.maxtries (or some other part and parameter of a
 8233: resource)
 8234: 
 8235: =item *
 8236: 
 8237: directcondval($number) : get current value of a condition; reads from a state
 8238: string
 8239: 
 8240: =item *
 8241: 
 8242: condval($condidx) : value of condition index based on state
 8243: 
 8244: =item *
 8245: 
 8246: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8247: resource's metadata, $what should be either a specific key, or either
 8248: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8249: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8250: 
 8251: this function automatically caches all requests
 8252: 
 8253: =item *
 8254: 
 8255: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8256: network of library servers; returns file handle of where SQL and regex results
 8257: will be stored for query
 8258: 
 8259: =item *
 8260: 
 8261: symbread($filename) : return symbolic list entry (filename argument optional);
 8262: returns the data handle
 8263: 
 8264: =item *
 8265: 
 8266: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8267: a possible symb for the URL in $thisfn, and if is an encryypted
 8268: resource that the user accessed using /enc/ returns a 1 on success, 0
 8269: on failure, user must be in a course, as it assumes the existance of
 8270: the course initial hash, and uses $env('request.course.id'}
 8271: 
 8272: 
 8273: =item *
 8274: 
 8275: symbclean($symb) : removes versions numbers from a symb, returns the
 8276: cleaned symb
 8277: 
 8278: =item *
 8279: 
 8280: is_on_map($uri) : checks if the $uri is somewhere on the current
 8281: course map, user must be in a course for it to work.
 8282: 
 8283: =item *
 8284: 
 8285: numval($salt) : return random seed value (addend for rndseed)
 8286: 
 8287: =item *
 8288: 
 8289: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8290: a random seed, all arguments are optional, if they aren't sent it uses the
 8291: environment to derive them. Note: if symb isn't sent and it can't get one
 8292: from &symbread it will use the current time as its return value
 8293: 
 8294: =item *
 8295: 
 8296: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8297: unfakeable, receipt
 8298: 
 8299: =item *
 8300: 
 8301: receipt() : API to ireceipt working off of env values; given out to users
 8302: 
 8303: =item *
 8304: 
 8305: countacc($url) : count the number of accesses to a given URL
 8306: 
 8307: =item *
 8308: 
 8309: 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
 8310: 
 8311: =item *
 8312: 
 8313: 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)
 8314: 
 8315: =item *
 8316: 
 8317: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8318: 
 8319: =item *
 8320: 
 8321: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8322: forcing spreadsheet to reevaluate the resource scores next time.
 8323: 
 8324: =back
 8325: 
 8326: =head2 Storing/Retreiving Data
 8327: 
 8328: =over 4
 8329: 
 8330: =item *
 8331: 
 8332: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8333: for this url; hashref needs to be given and should be a \%hashname; the
 8334: remaining args aren't required and if they aren't passed or are '' they will
 8335: be derived from the env
 8336: 
 8337: =item *
 8338: 
 8339: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8340: uses critical subroutine
 8341: 
 8342: =item *
 8343: 
 8344: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8345: all args are optional
 8346: 
 8347: =item *
 8348: 
 8349: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8350: dumps the complete (or key matching regexp) namespace into a hash
 8351: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8352: normally &store()ed into
 8353: 
 8354: $range should be either an integer '100' (give me the first 100
 8355:                                            matching records)
 8356:               or be  two integers sperated by a - with no spaces
 8357:                  '30-50' (give me the 30th through the 50th matching
 8358:                           records)
 8359: 
 8360: 
 8361: =item *
 8362: 
 8363: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8364: replaces a &store() version of data with a replacement set of data
 8365: for a particular resource in a namespace passed in the $storehash hash 
 8366: reference
 8367: 
 8368: =item *
 8369: 
 8370: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8371: works very similar to store/cstore, but all data is stored in a
 8372: temporary location and can be reset using tmpreset, $storehash should
 8373: be a hash reference, returns nothing on success
 8374: 
 8375: =item *
 8376: 
 8377: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8378: similar to restore, but all data is stored in a temporary location and
 8379: can be reset using tmpreset. Returns a hash of values on success,
 8380: error string otherwise.
 8381: 
 8382: =item *
 8383: 
 8384: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8385: deltes all keys for $symb form the temporary storage hash.
 8386: 
 8387: =item *
 8388: 
 8389: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8390: reference filled in from namesp ($udom and $uname are optional)
 8391: 
 8392: =item *
 8393: 
 8394: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8395: namesp ($udom and $uname are optional)
 8396: 
 8397: =item *
 8398: 
 8399: dump($namespace,$udom,$uname,$regexp,$range) : 
 8400: dumps the complete (or key matching regexp) namespace into a hash
 8401: ($udom, $uname, $regexp, $range are optional)
 8402: 
 8403: $range should be either an integer '100' (give me the first 100
 8404:                                            matching records)
 8405:               or be  two integers sperated by a - with no spaces
 8406:                  '30-50' (give me the 30th through the 50th matching
 8407:                           records)
 8408: =item *
 8409: 
 8410: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8411: $store can be a scalar, an array reference, or if the amount to be 
 8412: incremented is > 1, a hash reference.
 8413: 
 8414: ($udom and $uname are optional)
 8415: 
 8416: =item *
 8417: 
 8418: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8419: ($udom and $uname are optional)
 8420: 
 8421: =item *
 8422: 
 8423: cput($namespace,$storehash,$udom,$uname) : critical put
 8424: ($udom and $uname are optional)
 8425: 
 8426: =item *
 8427: 
 8428: newput($namespace,$storehash,$udom,$uname) :
 8429: 
 8430: Attempts to store the items in the $storehash, but only if they don't
 8431: currently exist, if this succeeds you can be certain that you have 
 8432: successfully created a new key value pair in the $namespace db.
 8433: 
 8434: 
 8435: Args:
 8436:  $namespace: name of database to store values to
 8437:  $storehash: hashref to store to the db
 8438:  $udom: (optional) domain of user containing the db
 8439:  $uname: (optional) name of user caontaining the db
 8440: 
 8441: Returns:
 8442:  'ok' -> succeeded in storing all keys of $storehash
 8443:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8444:                         least <key> already existed in the db (other
 8445:                         requested keys may also already exist)
 8446:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8447:  'con_lost' -> unable to contact request server
 8448:  'refused' -> action was not allowed by remote machine
 8449: 
 8450: 
 8451: =item *
 8452: 
 8453: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8454: reference filled in from namesp (encrypts the return communication)
 8455: ($udom and $uname are optional)
 8456: 
 8457: =item *
 8458: 
 8459: log($udom,$name,$home,$message) : write to permanent log for user; use
 8460: critical subroutine
 8461: 
 8462: =item *
 8463: 
 8464: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
 8465: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
 8466: 
 8467: =item *
 8468: 
 8469: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
 8470: 
 8471: =back
 8472: 
 8473: =head2 Network Status Functions
 8474: 
 8475: =over 4
 8476: 
 8477: =item *
 8478: 
 8479: dirlist($uri) : return directory list based on URI
 8480: 
 8481: =item *
 8482: 
 8483: spareserver() : find server with least workload from spare.tab
 8484: 
 8485: =back
 8486: 
 8487: =head2 Apache Request
 8488: 
 8489: =over 4
 8490: 
 8491: =item *
 8492: 
 8493: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8494: localhost, posts hash
 8495: 
 8496: =back
 8497: 
 8498: =head2 Data to String to Data
 8499: 
 8500: =over 4
 8501: 
 8502: =item *
 8503: 
 8504: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8505: and '&' separators, supports elements that are arrayrefs and hashrefs
 8506: 
 8507: =item *
 8508: 
 8509: hashref2str($hashref) : convert a hashref into a string complete with
 8510: escaping and '=' and '&' separators, supports elements that are
 8511: arrayrefs and hashrefs
 8512: 
 8513: =item *
 8514: 
 8515: arrayref2str($arrayref) : convert an arrayref into a string complete
 8516: with escaping and '&' separators, supports elements that are arrayrefs
 8517: and hashrefs
 8518: 
 8519: =item *
 8520: 
 8521: str2hash($string) : convert string to hash using unescaping and
 8522: splitting on '=' and '&', supports elements that are arrayrefs and
 8523: hashrefs
 8524: 
 8525: =item *
 8526: 
 8527: str2array($string) : convert string to hash using unescaping and
 8528: splitting on '&', supports elements that are arrayrefs and hashrefs
 8529: 
 8530: =back
 8531: 
 8532: =head2 Logging Routines
 8533: 
 8534: =over 4
 8535: 
 8536: These routines allow one to make log messages in the lonnet.log and
 8537: lonnet.perm logfiles.
 8538: 
 8539: =item *
 8540: 
 8541: logtouch() : make sure the logfile, lonnet.log, exists
 8542: 
 8543: =item *
 8544: 
 8545: logthis() : append message to the normal lonnet.log file, it gets
 8546: preiodically rolled over and deleted.
 8547: 
 8548: =item *
 8549: 
 8550: logperm() : append a permanent message to lonnet.perm.log, this log
 8551: file never gets deleted by any automated portion of the system, only
 8552: messages of critical importance should go in here.
 8553: 
 8554: =back
 8555: 
 8556: =head2 General File Helper Routines
 8557: 
 8558: =over 4
 8559: 
 8560: =item *
 8561: 
 8562: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8563: (a) files in /uploaded
 8564:   (i) If a local copy of the file exists - 
 8565:       compares modification date of local copy with last-modified date for 
 8566:       definitive version stored on home server for course. If local copy is 
 8567:       stale, requests a new version from the home server and stores it. 
 8568:       If the original has been removed from the home server, then local copy 
 8569:       is unlinked.
 8570:   (ii) If local copy does not exist -
 8571:       requests the file from the home server and stores it. 
 8572:   
 8573:   If $caller is 'uploadrep':  
 8574:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8575:     for request for files originally uploaded via DOCS. 
 8576:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8577:   
 8578:   Otherwise:
 8579:      This indicates a call from the content generation phase of the request.
 8580:      -  returns the entire contents of the file or -1.
 8581:      
 8582: (b) files in /res
 8583:    - returns the entire contents of a file or -1; 
 8584:    it properly subscribes to and replicates the file if neccessary.
 8585: 
 8586: 
 8587: =item *
 8588: 
 8589: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8590:                   reference
 8591: 
 8592: returns either a stat() list of data about the file or an empty list
 8593: if the file doesn't exist or couldn't find out about it (connection
 8594: problems or user unknown)
 8595: 
 8596: =item *
 8597: 
 8598: filelocation($dir,$file) : returns file system location of a file
 8599: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8600: directory that relative $file lookups are to looked in ($dir of /a/dir
 8601: and a file of ../bob will become /a/bob)
 8602: 
 8603: =item *
 8604: 
 8605: hreflocation($dir,$file) : returns file system location or a URL; same as
 8606: filelocation except for hrefs
 8607: 
 8608: =item *
 8609: 
 8610: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8611: 
 8612: =back
 8613: 
 8614: =head2 Usererfile file routines (/uploaded*)
 8615: 
 8616: =over 4
 8617: 
 8618: =item *
 8619: 
 8620: userfileupload(): main rotine for putting a file in a user or course's
 8621:                   filespace, arguments are,
 8622: 
 8623:  formname - required - this is the name of the element in $env where the
 8624:            filename, and the contents of the file to create/modifed exist
 8625:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8626:            contents of the file is located in $env{'form.'.$formname}
 8627:  coursedoc - if true, store the file in the course of the active role
 8628:              of the current user
 8629:  subdir - required - subdirectory to put the file in under ../userfiles/
 8630:          if undefined, it will be placed in "unknown"
 8631: 
 8632:  (This routine calls clean_filename() to remove any dangerous
 8633:  characters from the filename, and then calls finuserfileupload() to
 8634:  complete the transaction)
 8635: 
 8636:  returns either the url of the uploaded file (/uploaded/....) if successful
 8637:  and /adm/notfound.html if unsuccessful
 8638: 
 8639: =item *
 8640: 
 8641: clean_filename(): routine for cleaing a filename up for storage in
 8642:                  userfile space, argument is:
 8643: 
 8644:  filename - proposed filename
 8645: 
 8646: returns: the new clean filename
 8647: 
 8648: =item *
 8649: 
 8650: finishuserfileupload(): routine that creaes and sends the file to
 8651: userspace, probably shouldn't be called directly
 8652: 
 8653:   docuname: username or courseid of destination for the file
 8654:   docudom: domain of user/course of destination for the file
 8655:   formname: same as for userfileupload()
 8656:   fname: filename (inculding subdirectories) for the file
 8657: 
 8658:  returns either the url of the uploaded file (/uploaded/....) if successful
 8659:  and /adm/notfound.html if unsuccessful
 8660: 
 8661: =item *
 8662: 
 8663: renameuserfile(): renames an existing userfile to a new name
 8664: 
 8665:   Args:
 8666:    docuname: username or courseid of destination for the file
 8667:    docudom: domain of user/course of destination for the file
 8668:    old: current file name (including any subdirs under userfiles)
 8669:    new: desired file name (including any subdirs under userfiles)
 8670: 
 8671: =item *
 8672: 
 8673: mkdiruserfile(): creates a directory is a userfiles dir
 8674: 
 8675:   Args:
 8676:    docuname: username or courseid of destination for the file
 8677:    docudom: domain of user/course of destination for the file
 8678:    dir: dir to create (including any subdirs under userfiles)
 8679: 
 8680: =item *
 8681: 
 8682: removeuserfile(): removes a file that exists in userfiles
 8683: 
 8684:   Args:
 8685:    docuname: username or courseid of destination for the file
 8686:    docudom: domain of user/course of destination for the file
 8687:    fname: filname to delete (including any subdirs under userfiles)
 8688: 
 8689: =item *
 8690: 
 8691: removeuploadedurl(): convience function for removeuserfile()
 8692: 
 8693:   Args:
 8694:    url:  a full /uploaded/... url to delete
 8695: 
 8696: =item * 
 8697: 
 8698: get_portfile_permissions():
 8699:   Args:
 8700:     domain: domain of user or course contain the portfolio files
 8701:     user: name of user or num of course contain the portfolio files
 8702:   Returns:
 8703:     hashref of a dump of the proper file_permissions.db
 8704:    
 8705: 
 8706: =item * 
 8707: 
 8708: get_access_controls():
 8709: 
 8710: Args:
 8711:   current_permissions: the hash ref returned from get_portfile_permissions()
 8712:   group: (optional) the group you want the files associated with
 8713:   file: (optional) the file you want access info on
 8714: 
 8715: Returns:
 8716:     a hash (keys are file names) of hashes containing
 8717:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8718:         values are XML containing access control settings (see below) 
 8719: 
 8720: Internal notes:
 8721: 
 8722:  access controls are stored in file_permissions.db as key=value pairs.
 8723:     key -> path to file/file_name\0uniqueID:scope_end_start
 8724:         where scope -> public,guest,course,group,domains or users.
 8725:               end -> UNIX time for end of access (0 -> no end date)
 8726:               start -> UNIX time for start of access
 8727: 
 8728:     value -> XML description of access control
 8729:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8730:             <start></start>
 8731:             <end></end>
 8732: 
 8733:             <password></password>  for scope type = guest
 8734: 
 8735:             <domain></domain>     for scope type = course or group
 8736:             <number></number>
 8737:             <roles id="">
 8738:              <role></role>
 8739:              <access></access>
 8740:              <section></section>
 8741:              <group></group>
 8742:             </roles>
 8743: 
 8744:             <dom></dom>         for scope type = domains
 8745: 
 8746:             <users>             for scope type = users
 8747:              <user>
 8748:               <uname></uname>
 8749:               <udom></udom>
 8750:              </user>
 8751:             </users>
 8752:            </scope> 
 8753:               
 8754:  Access data is also aggregated for each file in an additional key=value pair:
 8755:  key -> path to file/file_name\0accesscontrol 
 8756:  value -> reference to hash
 8757:           hash contains key = value pairs
 8758:           where key = uniqueID:scope_end_start
 8759:                 value = UNIX time record was last updated
 8760: 
 8761:           Used to improve speed of look-ups of access controls for each file.  
 8762:  
 8763:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8764: 
 8765: modify_access_controls():
 8766: 
 8767: Modifies access controls for a portfolio file
 8768: Args
 8769: 1. file name
 8770: 2. reference to hash of required changes,
 8771: 3. domain
 8772: 4. username
 8773:   where domain,username are the domain of the portfolio owner 
 8774:   (either a user or a course) 
 8775: 
 8776: Returns:
 8777: 1. result of additions or updates ('ok' or 'error', with error message). 
 8778: 2. result of deletions ('ok' or 'error', with error message).
 8779: 3. reference to hash of any new or updated access controls.
 8780: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8781:    key = integer (inbound ID)
 8782:    value = uniqueID  
 8783: 
 8784: =back
 8785: 
 8786: =head2 HTTP Helper Routines
 8787: 
 8788: =over 4
 8789: 
 8790: =item *
 8791: 
 8792: escape() : unpack non-word characters into CGI-compatible hex codes
 8793: 
 8794: =item *
 8795: 
 8796: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8797: 
 8798: =back
 8799: 
 8800: =head1 PRIVATE SUBROUTINES
 8801: 
 8802: =head2 Underlying communication routines (Shouldn't call)
 8803: 
 8804: =over 4
 8805: 
 8806: =item *
 8807: 
 8808: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8809: 
 8810: =item *
 8811: 
 8812: reply() : uses subreply to send a message to remote machine, logs all failures
 8813: 
 8814: =item *
 8815: 
 8816: critical() : passes a critical message to another server; if cannot
 8817: get through then place message in connection buffer directory and
 8818: returns con_delayed, if incapable of saving message, returns
 8819: con_failed
 8820: 
 8821: =item *
 8822: 
 8823: reconlonc() : tries to reconnect lonc client processes.
 8824: 
 8825: =back
 8826: 
 8827: =head2 Resource Access Logging
 8828: 
 8829: =over 4
 8830: 
 8831: =item *
 8832: 
 8833: flushcourselogs() : flush (save) buffer logs and access logs
 8834: 
 8835: =item *
 8836: 
 8837: courselog($what) : save message for course in hash
 8838: 
 8839: =item *
 8840: 
 8841: courseacclog($what) : save message for course using &courselog().  Perform
 8842: special processing for specific resource types (problems, exams, quizzes, etc).
 8843: 
 8844: =item *
 8845: 
 8846: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8847: as a PerlChildExitHandler
 8848: 
 8849: =back
 8850: 
 8851: =head2 Other
 8852: 
 8853: =over 4
 8854: 
 8855: =item *
 8856: 
 8857: symblist($mapname,%newhash) : update symbolic storage links
 8858: 
 8859: =back
 8860: 
 8861: =cut

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