File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.867: download - view: text, annotated - select for diffs
Tue Apr 10 20:29:53 2007 UTC (17 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Correction to get_my_roles() - role data stored differently in nohist_userroles.db (for roles for a course) and roles.db for roles for a user.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.867 2007/04/10 20:29:53 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %badServerCache %spareid 
   39:    %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    $tmpdir $_64bit %env);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use HTML::Parser;
   48: use Fcntl qw(:flock);
   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   50: use Time::HiRes qw( gettimeofday tv_interval );
   51: use Cache::Memcached;
   52: use Digest::MD5;
   53: use Math::Random;
   54: use LONCAPA qw(:DEFAULT :match);
   55: use LONCAPA::Configuration;
   56: 
   57: my $readit;
   58: my $max_connection_retries = 10;     # Or some such value.
   59: 
   60: require Exporter;
   61: 
   62: our @ISA = qw (Exporter);
   63: our @EXPORT = qw(%env);
   64: 
   65: =pod
   66: 
   67: =head1 Package Variables
   68: 
   69: These are largely undocumented, so if you decipher one please note it here.
   70: 
   71: =over 4
   72: 
   73: =item $processmarker
   74: 
   75: Contains the time this process was started and this servers host id.
   76: 
   77: =item $dumpcount
   78: 
   79: Counts the number of times a message log flush has been attempted (regardless
   80: of success) by this process.  Used as part of the filename when messages are
   81: delayed.
   82: 
   83: =back
   84: 
   85: =cut
   86: 
   87: 
   88: # --------------------------------------------------------------------- Logging
   89: {
   90:     my $logid;
   91:     sub instructor_log {
   92: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   93: 	$logid++;
   94: 	my $id=time().'00000'.$$.'00000'.$logid;
   95: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   96: 				    { $id => {
   97: 					'exe_uname' => $env{'user.name'},
   98: 					'exe_udom'  => $env{'user.domain'},
   99: 					'exe_time'  => time(),
  100: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  101: 					'delflag'   => $delflag,
  102: 					'logentry'  => $storehash,
  103: 					'uname'     => $uname,
  104: 					'udom'      => $udom,
  105: 				    }
  106: 				  },
  107: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  108: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  109: 				    );
  110:     }
  111: }
  112: 
  113: sub logtouch {
  114:     my $execdir=$perlvar{'lonDaemons'};
  115:     unless (-e "$execdir/logs/lonnet.log") {	
  116: 	open(my $fh,">>$execdir/logs/lonnet.log");
  117: 	close $fh;
  118:     }
  119:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  120:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  121: }
  122: 
  123: sub logthis {
  124:     my $message=shift;
  125:     my $execdir=$perlvar{'lonDaemons'};
  126:     my $now=time;
  127:     my $local=localtime($now);
  128:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  129: 	print $fh "$local ($$): $message\n";
  130: 	close($fh);
  131:     }
  132:     return 1;
  133: }
  134: 
  135: sub logperm {
  136:     my $message=shift;
  137:     my $execdir=$perlvar{'lonDaemons'};
  138:     my $now=time;
  139:     my $local=localtime($now);
  140:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  141: 	print $fh "$now:$message:$local\n";
  142: 	close($fh);
  143:     }
  144:     return 1;
  145: }
  146: 
  147: sub create_connection {
  148:     my ($hostname,$lonid) = @_;
  149:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  150: 				     Type    => SOCK_STREAM,
  151: 				     Timeout => 10);
  152:     return 0 if (!$client);
  153:     print $client (join(':',$hostname,$lonid,&machine_ids($lonid))."\n");
  154:     my $result = <$client>;
  155:     chomp($result);
  156:     return 1 if ($result eq 'done');
  157:     return 0;
  158: }
  159: 
  160: 
  161: # -------------------------------------------------- Non-critical communication
  162: sub subreply {
  163:     my ($cmd,$server)=@_;
  164:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  165:     #
  166:     #  With loncnew process trimming, there's a timing hole between lonc server
  167:     #  process exit and the master server picking up the listen on the AF_UNIX
  168:     #  socket.  In that time interval, a lock file will exist:
  169: 
  170:     my $lockfile=$peerfile.".lock";
  171:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  172: 	sleep(1);
  173:     }
  174:     # At this point, either a loncnew parent is listening or an old lonc
  175:     # or loncnew child is listening so we can connect or everything's dead.
  176:     #
  177:     #   We'll give the connection a few tries before abandoning it.  If
  178:     #   connection is not possible, we'll con_lost back to the client.
  179:     #   
  180:     my $client;
  181:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  182: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  183: 				      Type    => SOCK_STREAM,
  184: 				      Timeout => 10);
  185: 	if($client) {
  186: 	    last;		# Connected!
  187: 	} else {
  188: 	    &create_connection(&hostname($server),$server);
  189: 	}
  190:         sleep(1);		# Try again later if failed connection.
  191:     }
  192:     my $answer;
  193:     if ($client) {
  194: 	print $client "sethost:$server:$cmd\n";
  195: 	$answer=<$client>;
  196: 	if (!$answer) { $answer="con_lost"; }
  197: 	chomp($answer);
  198:     } else {
  199: 	$answer = 'con_lost';	# Failed connection.
  200:     }
  201:     return $answer;
  202: }
  203: 
  204: sub reply {
  205:     my ($cmd,$server)=@_;
  206:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  207:     my $answer=subreply($cmd,$server);
  208:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  209:        &logthis("<font color=\"blue\">WARNING:".
  210:                 " $cmd to $server returned $answer</font>");
  211:     }
  212:     return $answer;
  213: }
  214: 
  215: # ----------------------------------------------------------- Send USR1 to lonc
  216: 
  217: sub reconlonc {
  218:     &logthis("Trying to reconnect lonc");
  219:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  220:     if (open(my $fh,"<$loncfile")) {
  221: 	my $loncpid=<$fh>;
  222:         chomp($loncpid);
  223:         if (kill 0 => $loncpid) {
  224: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  225:             kill USR1 => $loncpid;
  226:             sleep 1;
  227:          } else {
  228: 	    &logthis(
  229:                "<font color=\"blue\">WARNING:".
  230:                " lonc at pid $loncpid not responding, giving up</font>");
  231:         }
  232:     } else {
  233: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  234:     }
  235: }
  236: 
  237: # ------------------------------------------------------ Critical communication
  238: 
  239: sub critical {
  240:     my ($cmd,$server)=@_;
  241:     unless (&hostname($server)) {
  242:         &logthis("<font color=\"blue\">WARNING:".
  243:                " Critical message to unknown server ($server)</font>");
  244:         return 'no_such_host';
  245:     }
  246:     my $answer=reply($cmd,$server);
  247:     if ($answer eq 'con_lost') {
  248: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  249: 	my $answer=reply($cmd,$server);
  250:         if ($answer eq 'con_lost') {
  251:             my $now=time;
  252:             my $middlename=$cmd;
  253:             $middlename=substr($middlename,0,16);
  254:             $middlename=~s/\W//g;
  255:             my $dfilename=
  256:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  257:             $dumpcount++;
  258:             {
  259: 		my $dfh;
  260: 		if (open($dfh,">$dfilename")) {
  261: 		    print $dfh "$cmd\n"; 
  262: 		    close($dfh);
  263: 		}
  264:             }
  265:             sleep 2;
  266:             my $wcmd='';
  267:             {
  268: 		my $dfh;
  269: 		if (open($dfh,"<$dfilename")) {
  270: 		    $wcmd=<$dfh>; 
  271: 		    close($dfh);
  272: 		}
  273:             }
  274:             chomp($wcmd);
  275:             if ($wcmd eq $cmd) {
  276: 		&logthis("<font color=\"blue\">WARNING: ".
  277:                          "Connection buffer $dfilename: $cmd</font>");
  278:                 &logperm("D:$server:$cmd");
  279: 	        return 'con_delayed';
  280:             } else {
  281:                 &logthis("<font color=\"red\">CRITICAL:"
  282:                         ." Critical connection failed: $server $cmd</font>");
  283:                 &logperm("F:$server:$cmd");
  284:                 return 'con_failed';
  285:             }
  286:         }
  287:     }
  288:     return $answer;
  289: }
  290: 
  291: # ------------------------------------------- check if return value is an error
  292: 
  293: sub error {
  294:     my ($result) = @_;
  295:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  296: 	if ($2 == 2) { return undef; }
  297: 	return $1;
  298:     }
  299:     return undef;
  300: }
  301: 
  302: sub convert_and_load_session_env {
  303:     my ($lonidsdir,$handle)=@_;
  304:     my @profile;
  305:     {
  306: 	open(my $idf,"$lonidsdir/$handle.id");
  307: 	flock($idf,LOCK_SH);
  308: 	@profile=<$idf>;
  309: 	close($idf);
  310:     }
  311:     my %temp_env;
  312:     foreach my $line (@profile) {
  313: 	if ($line !~ m/=/) {
  314: 	    return 0;
  315: 	}
  316: 	chomp($line);
  317: 	my ($envname,$envvalue)=split(/=/,$line,2);
  318: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  319:     }
  320:     unlink("$lonidsdir/$handle.id");
  321:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  322: 	    0640)) {
  323: 	%disk_env = %temp_env;
  324: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  325: 	untie(%disk_env);
  326:     }
  327:     return 1;
  328: }
  329: 
  330: # ------------------------------------------- Transfer profile into environment
  331: my $env_loaded;
  332: sub transfer_profile_to_env {
  333:     my ($lonidsdir,$handle,$force_transfer) = @_;
  334:     if (!$force_transfer && $env_loaded) { return; } 
  335: 
  336:     if (!defined($lonidsdir)) {
  337: 	$lonidsdir = $perlvar{'lonIDsDir'};
  338:     }
  339:     if (!defined($handle)) {
  340:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  341:     }
  342: 
  343:     my $convert;
  344:     {
  345:     	open(my $idf,"$lonidsdir/$handle.id");
  346: 	flock($idf,LOCK_SH);
  347: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  348: 		&GDBM_READER(),0640)) {
  349: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  350: 	    untie(%disk_env);
  351: 	} else {
  352: 	    $convert = 1;
  353: 	}
  354:     }
  355:     if ($convert) {
  356: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  357: 	    &logthis("Failed to load session, or convert session.");
  358: 	}
  359:     }
  360: 
  361:     my %remove;
  362:     while ( my $envname = each(%env) ) {
  363:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  364:             if ($time < time-300) {
  365:                 $remove{$key}++;
  366:             }
  367:         }
  368:     }
  369: 
  370:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  371:     $env_loaded=1;
  372:     foreach my $expired_key (keys(%remove)) {
  373:         &delenv($expired_key);
  374:     }
  375: }
  376: 
  377: sub timed_flock {
  378:     my ($file,$lock_type) = @_;
  379:     my $failed=0;
  380:     eval {
  381: 	local $SIG{__DIE__}='DEFAULT';
  382: 	local $SIG{ALRM}=sub {
  383: 	    $failed=1;
  384: 	    die("failed lock");
  385: 	};
  386: 	alarm(13);
  387: 	flock($file,$lock_type);
  388: 	alarm(0);
  389:     };
  390:     if ($failed) {
  391: 	return undef;
  392:     } else {
  393: 	return 1;
  394:     }
  395: }
  396: 
  397: # ---------------------------------------------------------- Append Environment
  398: 
  399: sub appenv {
  400:     my %newenv=@_;
  401:     foreach my $key (keys(%newenv)) {
  402: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  403:             &logthis("<font color=\"blue\">WARNING: ".
  404:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  405:                 .'</font>');
  406: 	    delete($newenv{$key});
  407:         } else {
  408:             $env{$key}=$newenv{$key};
  409:         }
  410:     }
  411:     open(my $env_file,$env{'user.environment'});
  412:     if (&timed_flock($env_file,LOCK_EX)
  413: 	&&
  414: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  415: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  416: 	while (my ($key,$value) = each(%newenv)) {
  417: 	    $disk_env{$key} = $value;
  418: 	}
  419: 	untie(%disk_env);
  420:     }
  421:     return 'ok';
  422: }
  423: # ----------------------------------------------------- Delete from Environment
  424: 
  425: sub delenv {
  426:     my $delthis=shift;
  427:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  428:         &logthis("<font color=\"blue\">WARNING: ".
  429:                 "Attempt to delete from environment ".$delthis);
  430:         return 'error';
  431:     }
  432:     open(my $env_file,$env{'user.environment'});
  433:     if (&timed_flock($env_file,LOCK_EX)
  434: 	&&
  435: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  436: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  437: 	foreach my $key (keys(%disk_env)) {
  438: 	    if ($key=~/^$delthis/) { 
  439:                 delete($env{$key});
  440:                 delete($disk_env{$key});
  441:             }
  442: 	}
  443: 	untie(%disk_env);
  444:     }
  445:     return 'ok';
  446: }
  447: 
  448: sub get_env_multiple {
  449:     my ($name) = @_;
  450:     my @values;
  451:     if (defined($env{$name})) {
  452:         # exists is it an array
  453:         if (ref($env{$name})) {
  454:             @values=@{ $env{$name} };
  455:         } else {
  456:             $values[0]=$env{$name};
  457:         }
  458:     }
  459:     return(@values);
  460: }
  461: 
  462: # ------------------------------------------ Find out current server userload
  463: # there is a copy in lond
  464: sub userload {
  465:     my $numusers=0;
  466:     {
  467: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  468: 	my $filename;
  469: 	my $curtime=time;
  470: 	while ($filename=readdir(LONIDS)) {
  471: 	    if ($filename eq '.' || $filename eq '..') {next;}
  472: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  473: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  474: 	}
  475: 	closedir(LONIDS);
  476:     }
  477:     my $userloadpercent=0;
  478:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  479:     if ($maxuserload) {
  480: 	$userloadpercent=100*$numusers/$maxuserload;
  481:     }
  482:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  483:     return $userloadpercent;
  484: }
  485: 
  486: # ------------------------------------------ Fight off request when overloaded
  487: 
  488: sub overloaderror {
  489:     my ($r,$checkserver)=@_;
  490:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  491:     my $loadavg;
  492:     if ($checkserver eq $perlvar{'lonHostID'}) {
  493:        open(my $loadfile,'/proc/loadavg');
  494:        $loadavg=<$loadfile>;
  495:        $loadavg =~ s/\s.*//g;
  496:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  497:        close($loadfile);
  498:     } else {
  499:        $loadavg=&reply('load',$checkserver);
  500:     }
  501:     my $overload=$loadavg-100;
  502:     if ($overload>0) {
  503: 	$r->err_headers_out->{'Retry-After'}=$overload;
  504:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  505:         return 413;
  506:     }    
  507:     return '';
  508: }
  509: 
  510: # ------------------------------ Find server with least workload from spare.tab
  511: 
  512: sub spareserver {
  513:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  514:     my $spare_server;
  515:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  516:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  517:                                                      :  $userloadpercent;
  518:     
  519:     foreach my $try_server (@{ $spareid{'primary'} }) {
  520: 	($spare_server, $lowest_load) =
  521: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  522:     }
  523: 
  524:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  525: 
  526:     if (!$found_server) {
  527: 	foreach my $try_server (@{ $spareid{'default'} }) {
  528: 	    ($spare_server, $lowest_load) =
  529: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  530: 	}
  531:     }
  532: 
  533:     if (!$want_server_name) {
  534: 	$spare_server="http://".&hostname($spare_server);
  535:     }
  536:     return $spare_server;
  537: }
  538: 
  539: sub compare_server_load {
  540:     my ($try_server, $spare_server, $lowest_load) = @_;
  541: 
  542:     my $loadans     = &reply('load',    $try_server);
  543:     my $userloadans = &reply('userload',$try_server);
  544: 
  545:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  546: 	next; #didn't get a number from the server
  547:     }
  548: 
  549:     my $load;
  550:     if ($loadans =~ /\d/) {
  551: 	if ($userloadans =~ /\d/) {
  552: 	    #both are numbers, pick the bigger one
  553: 	    $load = ($loadans > $userloadans) ? $loadans 
  554: 		                              : $userloadans;
  555: 	} else {
  556: 	    $load = $loadans;
  557: 	}
  558:     } else {
  559: 	$load = $userloadans;
  560:     }
  561: 
  562:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  563: 	$spare_server = $try_server;
  564: 	$lowest_load  = $load;
  565:     }
  566:     return ($spare_server,$lowest_load);
  567: }
  568: # --------------------------------------------- Try to change a user's password
  569: 
  570: sub changepass {
  571:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  572:     $currentpass = &escape($currentpass);
  573:     $newpass     = &escape($newpass);
  574:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  575: 		       $server);
  576:     if (! $answer) {
  577: 	&logthis("No reply on password change request to $server ".
  578: 		 "by $uname in domain $udom.");
  579:     } elsif ($answer =~ "^ok") {
  580:         &logthis("$uname in $udom successfully changed their password ".
  581: 		 "on $server.");
  582:     } elsif ($answer =~ "^pwchange_failure") {
  583: 	&logthis("$uname in $udom was unable to change their password ".
  584: 		 "on $server.  The action was blocked by either lcpasswd ".
  585: 		 "or pwchange");
  586:     } elsif ($answer =~ "^non_authorized") {
  587:         &logthis("$uname in $udom did not get their password correct when ".
  588: 		 "attempting to change it on $server.");
  589:     } elsif ($answer =~ "^auth_mode_error") {
  590:         &logthis("$uname in $udom attempted to change their password despite ".
  591: 		 "not being locally or internally authenticated on $server.");
  592:     } elsif ($answer =~ "^unknown_user") {
  593:         &logthis("$uname in $udom attempted to change their password ".
  594: 		 "on $server but were unable to because $server is not ".
  595: 		 "their home server.");
  596:     } elsif ($answer =~ "^refused") {
  597: 	&logthis("$server refused to change $uname in $udom password because ".
  598: 		 "it was sent an unencrypted request to change the password.");
  599:     }
  600:     return $answer;
  601: }
  602: 
  603: # ----------------------- Try to determine user's current authentication scheme
  604: 
  605: sub queryauthenticate {
  606:     my ($uname,$udom)=@_;
  607:     my $uhome=&homeserver($uname,$udom);
  608:     if (!$uhome) {
  609: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  610: 	return 'no_host';
  611:     }
  612:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  613:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  614: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  615:     }
  616:     return $answer;
  617: }
  618: 
  619: # --------- Try to authenticate user from domain's lib servers (first this one)
  620: 
  621: sub authenticate {
  622:     my ($uname,$upass,$udom)=@_;
  623:     $upass=&escape($upass);
  624:     $uname= &LONCAPA::clean_username($uname);
  625:     my $uhome=&homeserver($uname,$udom,1);
  626:     if ((!$uhome) || ($uhome eq 'no_host')) {
  627: # Maybe the machine was offline and only re-appeared again recently?
  628:         &reconlonc();
  629: # One more
  630: 	my $uhome=&homeserver($uname,$udom,1);
  631: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  632: 	    &logthis("User $uname at $udom is unknown in authenticate");
  633: 	}
  634: 	return 'no_host';
  635:     }
  636:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  637:     if ($answer eq 'authorized') {
  638: 	&logthis("User $uname at $udom authorized by $uhome"); 
  639: 	return $uhome; 
  640:     }
  641:     if ($answer eq 'non_authorized') {
  642: 	&logthis("User $uname at $udom rejected by $uhome");
  643: 	return 'no_host'; 
  644:     }
  645:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  646:     return 'no_host';
  647: }
  648: 
  649: # ---------------------- Find the homebase for a user from domain's lib servers
  650: 
  651: my %homecache;
  652: sub homeserver {
  653:     my ($uname,$udom,$ignoreBadCache)=@_;
  654:     my $index="$uname:$udom";
  655: 
  656:     if (exists($homecache{$index})) { return $homecache{$index}; }
  657: 
  658:     my %servers = &get_servers($udom,'library');
  659:     foreach my $tryserver (keys(%servers)) {
  660:         next if ($ignoreBadCache ne 'true' && 
  661: 		 exists($badServerCache{$tryserver}));
  662: 
  663: 	my $answer=reply("home:$udom:$uname",$tryserver);
  664: 	if ($answer eq 'found') {
  665: 	    delete($badServerCache{$tryserver}); 
  666: 	    return $homecache{$index}=$tryserver;
  667: 	} elsif ($answer eq 'no_host') {
  668: 	    $badServerCache{$tryserver}=1;
  669: 	}
  670:     }    
  671:     return 'no_host';
  672: }
  673: 
  674: # ------------------------------------- Find the usernames behind a list of IDs
  675: 
  676: sub idget {
  677:     my ($udom,@ids)=@_;
  678:     my %returnhash=();
  679:     
  680:     my %servers = &get_servers($udom,'library');
  681:     foreach my $tryserver (keys(%servers)) {
  682: 	my $idlist=join('&',@ids);
  683: 	$idlist=~tr/A-Z/a-z/; 
  684: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  685: 	my @answer=();
  686: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  687: 	    @answer=split(/\&/,$reply);
  688: 	}                    ;
  689: 	my $i;
  690: 	for ($i=0;$i<=$#ids;$i++) {
  691: 	    if ($answer[$i]) {
  692: 		$returnhash{$ids[$i]}=$answer[$i];
  693: 	    } 
  694: 	}
  695:     } 
  696:     return %returnhash;
  697: }
  698: 
  699: # ------------------------------------- Find the IDs behind a list of usernames
  700: 
  701: sub idrget {
  702:     my ($udom,@unames)=@_;
  703:     my %returnhash=();
  704:     foreach my $uname (@unames) {
  705:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  706:     }
  707:     return %returnhash;
  708: }
  709: 
  710: # ------------------------------- Store away a list of names and associated IDs
  711: 
  712: sub idput {
  713:     my ($udom,%ids)=@_;
  714:     my %servers=();
  715:     foreach my $uname (keys(%ids)) {
  716: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  717:         my $uhom=&homeserver($uname,$udom);
  718:         if ($uhom ne 'no_host') {
  719:             my $id=&escape($ids{$uname});
  720:             $id=~tr/A-Z/a-z/;
  721:             my $esc_unam=&escape($uname);
  722: 	    if ($servers{$uhom}) {
  723: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  724:             } else {
  725:                 $servers{$uhom}=$id.'='.$esc_unam;
  726:             }
  727:         }
  728:     }
  729:     foreach my $server (keys(%servers)) {
  730:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  731:     }
  732: }
  733: 
  734: # ------------------------------------------- get items from domain db files   
  735: 
  736: sub get_dom {
  737:     my ($namespace,$storearr,$udom,$uhome)=@_;
  738:     my $items='';
  739:     foreach my $item (@$storearr) {
  740:         $items.=&escape($item).'&';
  741:     }
  742:     $items=~s/\&$//;
  743:     if (!$udom) {
  744:         $udom=$env{'user.domain'};
  745:         if (defined(&domain($udom,'primary'))) {
  746:             $uhome=&domain($udom,'primary');
  747:         } else {
  748:             $uhome eq '';
  749:         }
  750:     } else {
  751:         if (!$uhome) {
  752:             if (defined(&domain($udom,'primary'))) {
  753:                 $uhome=&domain($udom,'primary');
  754:             }
  755:         }
  756:     }
  757:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  758:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  759:         my %returnhash;
  760:         if ($rep =~ /^error: 2 /) {
  761:             return %returnhash;
  762:         }
  763:         my @pairs=split(/\&/,$rep);
  764:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  765:             return @pairs;
  766:         }
  767:         my %returnhash=();
  768:         my $i=0;
  769:         foreach my $item (@$storearr) {
  770:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  771:             $i++;
  772:         }
  773:         return %returnhash;
  774:     } else {
  775:         &logthis("get_dom failed - no homeserver and/or domain");
  776:     }
  777: }
  778: 
  779: # -------------------------------------------- put items in domain db files 
  780: 
  781: sub put_dom {
  782:     my ($namespace,$storehash,$udom,$uhome)=@_;
  783:     if (!$udom) {
  784:         $udom=$env{'user.domain'};
  785:         if (defined(&domain($udom,'primary'))) {
  786:             $uhome=&domain($udom,'primary');
  787:         } else {
  788:             $uhome eq '';
  789:         }
  790:     } else {
  791:         if (!$uhome) {
  792:             if (defined(&domain($udom,'primary'))) {
  793:                 $uhome=&domain($udom,'primary');
  794:             }
  795:         }
  796:     } 
  797:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  798:         my $items='';
  799:         foreach my $item (keys(%$storehash)) {
  800:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  801:         }
  802:         $items=~s/\&$//;
  803:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  804:     } else {
  805:         &logthis("put_dom failed - no homeserver and/or domain");
  806:     }
  807: }
  808: 
  809: sub retrieve_inst_usertypes {
  810:     my ($udom) = @_;
  811:     my (%returnhash,@order);
  812:     if (defined(&domain($udom,'primary'))) {
  813:         my $uhome=&domain($udom,'primary');
  814:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  815:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  816:         my @pairs=split(/\&/,$hashitems);
  817:         foreach my $item (@pairs) {
  818:             my ($key,$value)=split(/=/,$item,2);
  819:             $key = &unescape($key);
  820:             next if ($key =~ /^error: 2 /);
  821:             $returnhash{$key}=&thaw_unescape($value);
  822:         }
  823:         my @esc_order = split(/\&/,$orderitems);
  824:         foreach my $item (@esc_order) {
  825:             push(@order,&unescape($item));
  826:         }
  827:     } else {
  828:         &logthis("get_dom failed - no primary domain server for $udom");
  829:     }
  830:     return (\%returnhash,\@order);
  831: }
  832: 
  833: # --------------------------------------------------- Assign a key to a student
  834: 
  835: sub assign_access_key {
  836: #
  837: # a valid key looks like uname:udom#comments
  838: # comments are being appended
  839: #
  840:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  841:     $kdom=
  842:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  843:     $knum=
  844:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  845:     $cdom=
  846:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  847:     $cnum=
  848:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  849:     $udom=$env{'user.name'} unless (defined($udom));
  850:     $uname=$env{'user.domain'} unless (defined($uname));
  851:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  852:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  853:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  854:                                                   # assigned to this person
  855:                                                   # - this should not happen,
  856:                                                   # unless something went wrong
  857:                                                   # the first time around
  858: # ready to assign
  859:         $logentry=$1.'; '.$logentry;
  860:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  861:                                                  $kdom,$knum) eq 'ok') {
  862: # key now belongs to user
  863: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  864:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  865:                 &appenv('environment.'.$envkey => $ckey);
  866:                 return 'ok';
  867:             } else {
  868:                 return 
  869:   'error: Count not permanently assign key, will need to be re-entered later.';
  870: 	    }
  871:         } else {
  872:             return 'error: Could not assign key, try again later.';
  873:         }
  874:     } elsif (!$existing{$ckey}) {
  875: # the key does not exist
  876: 	return 'error: The key does not exist';
  877:     } else {
  878: # the key is somebody else's
  879: 	return 'error: The key is already in use';
  880:     }
  881: }
  882: 
  883: # ------------------------------------------ put an additional comment on a key
  884: 
  885: sub comment_access_key {
  886: #
  887: # a valid key looks like uname:udom#comments
  888: # comments are being appended
  889: #
  890:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  891:     $cdom=
  892:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  893:     $cnum=
  894:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  895:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  896:     if ($existing{$ckey}) {
  897:         $existing{$ckey}.='; '.$logentry;
  898: # ready to assign
  899:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  900:                                                  $cdom,$cnum) eq 'ok') {
  901: 	    return 'ok';
  902:         } else {
  903: 	    return 'error: Count not store comment.';
  904:         }
  905:     } else {
  906: # the key does not exist
  907: 	return 'error: The key does not exist';
  908:     }
  909: }
  910: 
  911: # ------------------------------------------------------ Generate a set of keys
  912: 
  913: sub generate_access_keys {
  914:     my ($number,$cdom,$cnum,$logentry)=@_;
  915:     $cdom=
  916:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  917:     $cnum=
  918:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  919:     unless (&allowed('mky',$cdom)) { return 0; }
  920:     unless (($cdom) && ($cnum)) { return 0; }
  921:     if ($number>10000) { return 0; }
  922:     sleep(2); # make sure don't get same seed twice
  923:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  924:     my $total=0;
  925:     for (my $i=1;$i<=$number;$i++) {
  926:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  927:                   sprintf("%lx",int(100000*rand)).'-'.
  928:                   sprintf("%lx",int(100000*rand));
  929:        $newkey=~s/1/g/g; # folks mix up 1 and l
  930:        $newkey=~s/0/h/g; # and also 0 and O
  931:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  932:        if ($existing{$newkey}) {
  933:            $i--;
  934:        } else {
  935: 	  if (&put('accesskeys',
  936:               { $newkey => '# generated '.localtime().
  937:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  938:                            '; '.$logentry },
  939: 		   $cdom,$cnum) eq 'ok') {
  940:               $total++;
  941: 	  }
  942:        }
  943:     }
  944:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  945:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  946:     return $total;
  947: }
  948: 
  949: # ------------------------------------------------------- Validate an accesskey
  950: 
  951: sub validate_access_key {
  952:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  953:     $cdom=
  954:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  955:     $cnum=
  956:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  957:     $udom=$env{'user.domain'} unless (defined($udom));
  958:     $uname=$env{'user.name'} unless (defined($uname));
  959:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  960:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  961: }
  962: 
  963: # ------------------------------------- Find the section of student in a course
  964: sub devalidate_getsection_cache {
  965:     my ($udom,$unam,$courseid)=@_;
  966:     my $hashid="$udom:$unam:$courseid";
  967:     &devalidate_cache_new('getsection',$hashid);
  968: }
  969: 
  970: sub courseid_to_courseurl {
  971:     my ($courseid) = @_;
  972:     #already url style courseid
  973:     return $courseid if ($courseid =~ m{^/});
  974: 
  975:     if (exists($env{'course.'.$courseid.'.num'})) {
  976: 	my $cnum = $env{'course.'.$courseid.'.num'};
  977: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  978: 	return "/$cdom/$cnum";
  979:     }
  980: 
  981:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  982:     if (exists($courseinfo{'num'})) {
  983: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  984:     }
  985: 
  986:     return undef;
  987: }
  988: 
  989: sub getsection {
  990:     my ($udom,$unam,$courseid)=@_;
  991:     my $cachetime=1800;
  992: 
  993:     my $hashid="$udom:$unam:$courseid";
  994:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  995:     if (defined($cached)) { return $result; }
  996: 
  997:     my %Pending; 
  998:     my %Expired;
  999:     #
 1000:     # Each role can either have not started yet (pending), be active, 
 1001:     #    or have expired.
 1002:     #
 1003:     # If there is an active role, we are done.
 1004:     #
 1005:     # If there is more than one role which has not started yet, 
 1006:     #     choose the one which will start sooner
 1007:     # If there is one role which has not started yet, return it.
 1008:     #
 1009:     # If there is more than one expired role, choose the one which ended last.
 1010:     # If there is a role which has expired, return it.
 1011:     #
 1012:     $courseid = &courseid_to_courseurl($courseid);
 1013:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1014:     foreach my $key (keys(%roleshash)) {
 1015:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1016:         my $section=$1;
 1017:         if ($key eq $courseid.'_st') { $section=''; }
 1018:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1019:         my $now=time;
 1020:         if (defined($end) && $end && ($now > $end)) {
 1021:             $Expired{$end}=$section;
 1022:             next;
 1023:         }
 1024:         if (defined($start) && $start && ($now < $start)) {
 1025:             $Pending{$start}=$section;
 1026:             next;
 1027:         }
 1028:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1029:     }
 1030:     #
 1031:     # Presumedly there will be few matching roles from the above
 1032:     # loop and the sorting time will be negligible.
 1033:     if (scalar(keys(%Pending))) {
 1034:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1035:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1036:     } 
 1037:     if (scalar(keys(%Expired))) {
 1038:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1039:         my $time = pop(@sorted);
 1040:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1041:     }
 1042:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1043: }
 1044: 
 1045: sub save_cache {
 1046:     &purge_remembered();
 1047:     #&Apache::loncommon::validate_page();
 1048:     undef(%env);
 1049:     undef($env_loaded);
 1050: }
 1051: 
 1052: my $to_remember=-1;
 1053: my %remembered;
 1054: my %accessed;
 1055: my $kicks=0;
 1056: my $hits=0;
 1057: sub make_key {
 1058:     my ($name,$id) = @_;
 1059:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
 1060:     return &escape($name.':'.$id);
 1061: }
 1062: 
 1063: sub devalidate_cache_new {
 1064:     my ($name,$id,$debug) = @_;
 1065:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1066:     $id=&make_key($name,$id);
 1067:     $memcache->delete($id);
 1068:     delete($remembered{$id});
 1069:     delete($accessed{$id});
 1070: }
 1071: 
 1072: sub is_cached_new {
 1073:     my ($name,$id,$debug) = @_;
 1074:     $id=&make_key($name,$id);
 1075:     if (exists($remembered{$id})) {
 1076: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1077: 	$accessed{$id}=[&gettimeofday()];
 1078: 	$hits++;
 1079: 	return ($remembered{$id},1);
 1080:     }
 1081:     my $value = $memcache->get($id);
 1082:     if (!(defined($value))) {
 1083: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1084: 	return (undef,undef);
 1085:     }
 1086:     if ($value eq '__undef__') {
 1087: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1088: 	$value=undef;
 1089:     }
 1090:     &make_room($id,$value,$debug);
 1091:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1092:     return ($value,1);
 1093: }
 1094: 
 1095: sub do_cache_new {
 1096:     my ($name,$id,$value,$time,$debug) = @_;
 1097:     $id=&make_key($name,$id);
 1098:     my $setvalue=$value;
 1099:     if (!defined($setvalue)) {
 1100: 	$setvalue='__undef__';
 1101:     }
 1102:     if (!defined($time) ) {
 1103: 	$time=600;
 1104:     }
 1105:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1106:     $memcache->set($id,$setvalue,$time);
 1107:     # need to make a copy of $value
 1108:     #&make_room($id,$value,$debug);
 1109:     return $value;
 1110: }
 1111: 
 1112: sub make_room {
 1113:     my ($id,$value,$debug)=@_;
 1114:     $remembered{$id}=$value;
 1115:     if ($to_remember<0) { return; }
 1116:     $accessed{$id}=[&gettimeofday()];
 1117:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1118:     my $to_kick;
 1119:     my $max_time=0;
 1120:     foreach my $other (keys(%accessed)) {
 1121: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1122: 	    $to_kick=$other;
 1123: 	    $max_time=&tv_interval($accessed{$other});
 1124: 	}
 1125:     }
 1126:     delete($remembered{$to_kick});
 1127:     delete($accessed{$to_kick});
 1128:     $kicks++;
 1129:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1130:     return;
 1131: }
 1132: 
 1133: sub purge_remembered {
 1134:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1135:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1136:     undef(%remembered);
 1137:     undef(%accessed);
 1138: }
 1139: # ------------------------------------- Read an entry from a user's environment
 1140: 
 1141: sub userenvironment {
 1142:     my ($udom,$unam,@what)=@_;
 1143:     my %returnhash=();
 1144:     my @answer=split(/\&/,
 1145:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1146:                       &homeserver($unam,$udom)));
 1147:     my $i;
 1148:     for ($i=0;$i<=$#what;$i++) {
 1149: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1150:     }
 1151:     return %returnhash;
 1152: }
 1153: 
 1154: # ---------------------------------------------------------- Get a studentphoto
 1155: sub studentphoto {
 1156:     my ($udom,$unam,$ext) = @_;
 1157:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1158:     if (defined($env{'request.course.id'})) {
 1159:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1160:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1161:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1162:             } else {
 1163:                 my ($result,$perm_reqd)=
 1164: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1165:                 if ($result eq 'ok') {
 1166:                     if (!($perm_reqd eq 'yes')) {
 1167:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1168:                     }
 1169:                 }
 1170:             }
 1171:         }
 1172:     } else {
 1173:         my ($result,$perm_reqd) = 
 1174: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1175:         if ($result eq 'ok') {
 1176:             if (!($perm_reqd eq 'yes')) {
 1177:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1178:             }
 1179:         }
 1180:     }
 1181:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1182: }
 1183: 
 1184: sub retrievestudentphoto {
 1185:     my ($udom,$unam,$ext,$type) = @_;
 1186:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1187:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1188:     if ($ret eq 'ok') {
 1189:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1190:         if ($type eq 'thumbnail') {
 1191:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1192:         }
 1193:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1194:         return $tokenurl;
 1195:     } else {
 1196:         if ($type eq 'thumbnail') {
 1197:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1198:         } else { 
 1199:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1200:         }
 1201:     }
 1202: }
 1203: 
 1204: # -------------------------------------------------------------------- New chat
 1205: 
 1206: sub chatsend {
 1207:     my ($newentry,$anon,$group)=@_;
 1208:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1209:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1210:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1211:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1212: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1213: 		   &escape($newentry)).':'.$group,$chome);
 1214: }
 1215: 
 1216: # ------------------------------------------ Find current version of a resource
 1217: 
 1218: sub getversion {
 1219:     my $fname=&clutter(shift);
 1220:     unless ($fname=~/^\/res\//) { return -1; }
 1221:     return &currentversion(&filelocation('',$fname));
 1222: }
 1223: 
 1224: sub currentversion {
 1225:     my $fname=shift;
 1226:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1227:     if (defined($cached)) { return $result; }
 1228:     my $author=$fname;
 1229:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1230:     my ($udom,$uname)=split(/\//,$author);
 1231:     my $home=homeserver($uname,$udom);
 1232:     if ($home eq 'no_host') { 
 1233:         return -1; 
 1234:     }
 1235:     my $answer=reply("currentversion:$fname",$home);
 1236:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1237: 	return -1;
 1238:     }
 1239:     return &do_cache_new('resversion',$fname,$answer,600);
 1240: }
 1241: 
 1242: # ----------------------------- Subscribe to a resource, return URL if possible
 1243: 
 1244: sub subscribe {
 1245:     my $fname=shift;
 1246:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1247:     $fname=~s/[\n\r]//g;
 1248:     my $author=$fname;
 1249:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1250:     my ($udom,$uname)=split(/\//,$author);
 1251:     my $home=homeserver($uname,$udom);
 1252:     if ($home eq 'no_host') {
 1253:         return 'not_found';
 1254:     }
 1255:     my $answer=reply("sub:$fname",$home);
 1256:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1257: 	$answer.=' by '.$home;
 1258:     }
 1259:     return $answer;
 1260: }
 1261:     
 1262: # -------------------------------------------------------------- Replicate file
 1263: 
 1264: sub repcopy {
 1265:     my $filename=shift;
 1266:     $filename=~s/\/+/\//g;
 1267:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1268:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1269:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1270: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1271: 	return &repcopy_userfile($filename);
 1272:     }
 1273:     $filename=~s/[\n\r]//g;
 1274:     my $transname="$filename.in.transfer";
 1275: # FIXME: this should flock
 1276:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1277:     my $remoteurl=subscribe($filename);
 1278:     if ($remoteurl =~ /^con_lost by/) {
 1279: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1280:            return 'unavailable';
 1281:     } elsif ($remoteurl eq 'not_found') {
 1282: 	   #&logthis("Subscribe returned not_found: $filename");
 1283: 	   return 'not_found';
 1284:     } elsif ($remoteurl =~ /^rejected by/) {
 1285: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1286:            return 'forbidden';
 1287:     } elsif ($remoteurl eq 'directory') {
 1288:            return 'ok';
 1289:     } else {
 1290:         my $author=$filename;
 1291:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1292:         my ($udom,$uname)=split(/\//,$author);
 1293:         my $home=homeserver($uname,$udom);
 1294:         unless ($home eq $perlvar{'lonHostID'}) {
 1295:            my @parts=split(/\//,$filename);
 1296:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1297:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1298:                &logthis("Malconfiguration for replication: $filename");
 1299: 	       return 'bad_request';
 1300:            }
 1301:            my $count;
 1302:            for ($count=5;$count<$#parts;$count++) {
 1303:                $path.="/$parts[$count]";
 1304:                if ((-e $path)!=1) {
 1305: 		   mkdir($path,0777);
 1306:                }
 1307:            }
 1308:            my $ua=new LWP::UserAgent;
 1309:            my $request=new HTTP::Request('GET',"$remoteurl");
 1310:            my $response=$ua->request($request,$transname);
 1311:            if ($response->is_error()) {
 1312: 	       unlink($transname);
 1313:                my $message=$response->status_line;
 1314:                &logthis("<font color=\"blue\">WARNING:"
 1315:                        ." LWP get: $message: $filename</font>");
 1316:                return 'unavailable';
 1317:            } else {
 1318: 	       if ($remoteurl!~/\.meta$/) {
 1319:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1320:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1321:                   if ($mresponse->is_error()) {
 1322: 		      unlink($filename.'.meta');
 1323:                       &logthis(
 1324:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1325:                   }
 1326: 	       }
 1327:                rename($transname,$filename);
 1328:                return 'ok';
 1329:            }
 1330:        }
 1331:     }
 1332: }
 1333: 
 1334: # ------------------------------------------------ Get server side include body
 1335: sub ssi_body {
 1336:     my ($filelink,%form)=@_;
 1337:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1338:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1339:     }
 1340:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1341:                                      &ssi($filelink,%form));
 1342:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1343:     $output=~s/^.*?\<body[^\>]*\>//si;
 1344:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1345:     return $output;
 1346: }
 1347: 
 1348: # --------------------------------------------------------- Server Side Include
 1349: 
 1350: sub absolute_url {
 1351:     my ($host_name) = @_;
 1352:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1353:     if ($host_name eq '') {
 1354: 	$host_name = $ENV{'SERVER_NAME'};
 1355:     }
 1356:     return $protocol.$host_name;
 1357: }
 1358: 
 1359: sub ssi {
 1360: 
 1361:     my ($fn,%form)=@_;
 1362: 
 1363:     my $ua=new LWP::UserAgent;
 1364:     
 1365:     my $request;
 1366: 
 1367:     $form{'no_update_last_known'}=1;
 1368: 
 1369:     if (%form) {
 1370:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1371:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1372:     } else {
 1373:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1374:     }
 1375: 
 1376:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1377:     my $response=$ua->request($request);
 1378: 
 1379:     return $response->content;
 1380: }
 1381: 
 1382: sub externalssi {
 1383:     my ($url)=@_;
 1384:     my $ua=new LWP::UserAgent;
 1385:     my $request=new HTTP::Request('GET',$url);
 1386:     my $response=$ua->request($request);
 1387:     return $response->content;
 1388: }
 1389: 
 1390: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1391: 
 1392: sub allowuploaded {
 1393:     my ($srcurl,$url)=@_;
 1394:     $url=&clutter(&declutter($url));
 1395:     my $dir=$url;
 1396:     $dir=~s/\/[^\/]+$//;
 1397:     my %httpref=();
 1398:     my $httpurl=&hreflocation('',$url);
 1399:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1400:     &Apache::lonnet::appenv(%httpref);
 1401: }
 1402: 
 1403: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1404: # input: action, courseID, current domain, intended
 1405: #        path to file, source of file, instruction to parse file for objects,
 1406: #        ref to hash for embedded objects,
 1407: #        ref to hash for codebase of java objects.
 1408: #
 1409: # output: url to file (if action was uploaddoc), 
 1410: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1411: #
 1412: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1413: # course.
 1414: #
 1415: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1416: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1417: #          course's home server.
 1418: #
 1419: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1420: #          be copied from $source (current location) to 
 1421: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1422: #         and will then be copied to
 1423: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1424: #         course's home server.
 1425: #
 1426: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1427: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1428: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1429: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1430: #         in course's home server.
 1431: #
 1432: 
 1433: sub process_coursefile {
 1434:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1435:     my $fetchresult;
 1436:     my $home=&homeserver($docuname,$docudom);
 1437:     if ($action eq 'propagate') {
 1438:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1439: 			     $home);
 1440:     } else {
 1441:         my $fpath = '';
 1442:         my $fname = $file;
 1443:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1444:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1445:         my $filepath = &build_filepath($fpath);
 1446:         if ($action eq 'copy') {
 1447:             if ($source eq '') {
 1448:                 $fetchresult = 'no source file';
 1449:                 return $fetchresult;
 1450:             } else {
 1451:                 my $destination = $filepath.'/'.$fname;
 1452:                 rename($source,$destination);
 1453:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1454:                                  $home);
 1455:             }
 1456:         } elsif ($action eq 'uploaddoc') {
 1457:             open(my $fh,'>'.$filepath.'/'.$fname);
 1458:             print $fh $env{'form.'.$source};
 1459:             close($fh);
 1460:             if ($parser eq 'parse') {
 1461:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1462:                 unless ($parse_result eq 'ok') {
 1463:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1464:                 }
 1465:             }
 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:     unless ( $fetchresult eq 'ok') {
 1478:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1479:              ' to host '.$home.': '.$fetchresult);
 1480:     }
 1481:     return $fetchresult;
 1482: }
 1483: 
 1484: sub build_filepath {
 1485:     my ($fpath) = @_;
 1486:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1487:     unless ($fpath eq '') {
 1488:         my @parts=split('/',$fpath);
 1489:         foreach my $part (@parts) {
 1490:             $filepath.= '/'.$part;
 1491:             if ((-e $filepath)!=1) {
 1492:                 mkdir($filepath,0777);
 1493:             }
 1494:         }
 1495:     }
 1496:     return $filepath;
 1497: }
 1498: 
 1499: sub store_edited_file {
 1500:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1501:     my $file = $primary_url;
 1502:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1503:     my $fpath = '';
 1504:     my $fname = $file;
 1505:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1506:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1507:     my $filepath = &build_filepath($fpath);
 1508:     open(my $fh,'>'.$filepath.'/'.$fname);
 1509:     print $fh $content;
 1510:     close($fh);
 1511:     my $home=&homeserver($docuname,$docudom);
 1512:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1513: 			  $home);
 1514:     if ($$fetchresult eq 'ok') {
 1515:         return '/uploaded/'.$fpath.'/'.$fname;
 1516:     } else {
 1517:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1518: 		 ' to host '.$home.': '.$$fetchresult);
 1519:         return '/adm/notfound.html';
 1520:     }
 1521: }
 1522: 
 1523: sub clean_filename {
 1524:     my ($fname,$args)=@_;
 1525: # Replace Windows backslashes by forward slashes
 1526:     $fname=~s/\\/\//g;
 1527:     if (!$args->{'keep_path'}) {
 1528:         # Get rid of everything but the actual filename
 1529: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1530:     }
 1531: # Replace spaces by underscores
 1532:     $fname=~s/\s+/\_/g;
 1533: # Replace all other weird characters by nothing
 1534:     $fname=~s{[^/\w\.\-]}{}g;
 1535: # Replace all .\d. sequences with _\d. so they no longer look like version
 1536: # numbers
 1537:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1538:     return $fname;
 1539: }
 1540: 
 1541: # --------------- Take an uploaded file and put it into the userfiles directory
 1542: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1543: #                    the desired filenam is in $env{"form.$formname.filename"}
 1544: #        $coursedoc - if true up to the current course
 1545: #                     if false
 1546: #        $subdir - directory in userfile to store the file into
 1547: #        $parser - instruction to parse file for objects ($parser = parse)    
 1548: #        $allfiles - reference to hash for embedded objects
 1549: #        $codebase - reference to hash for codebase of java objects
 1550: #        $desuname - username for permanent storage of uploaded file
 1551: #        $dsetudom - domain for permanaent storage of uploaded file
 1552: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1553: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1554: # 
 1555: # output: url of file in userspace, or error: <message> 
 1556: #             or /adm/notfound.html if failure to upload occurse
 1557: 
 1558: 
 1559: sub userfileupload {
 1560:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1561:         $destudom,$thumbwidth,$thumbheight)=@_;
 1562:     if (!defined($subdir)) { $subdir='unknown'; }
 1563:     my $fname=$env{'form.'.$formname.'.filename'};
 1564:     $fname=&clean_filename($fname);
 1565: # See if there is anything left
 1566:     unless ($fname) { return 'error: no uploaded file'; }
 1567:     chop($env{'form.'.$formname});
 1568:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1569:         my $now = time;
 1570:         my $filepath = 'tmp/helprequests/'.$now;
 1571:         my @parts=split(/\//,$filepath);
 1572:         my $fullpath = $perlvar{'lonDaemons'};
 1573:         for (my $i=0;$i<@parts;$i++) {
 1574:             $fullpath .= '/'.$parts[$i];
 1575:             if ((-e $fullpath)!=1) {
 1576:                 mkdir($fullpath,0777);
 1577:             }
 1578:         }
 1579:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1580:         print $fh $env{'form.'.$formname};
 1581:         close($fh);
 1582:         return $fullpath.'/'.$fname;
 1583:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1584:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1585:                        '_'.$env{'user.domain'}.'/pending';
 1586:         my @parts=split(/\//,$filepath);
 1587:         my $fullpath = $perlvar{'lonDaemons'};
 1588:         for (my $i=0;$i<@parts;$i++) {
 1589:             $fullpath .= '/'.$parts[$i];
 1590:             if ((-e $fullpath)!=1) {
 1591:                 mkdir($fullpath,0777);
 1592:             }
 1593:         }
 1594:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1595:         print $fh $env{'form.'.$formname};
 1596:         close($fh);
 1597:         return $fullpath.'/'.$fname;
 1598:     }
 1599:     
 1600: # Create the directory if not present
 1601:     $fname="$subdir/$fname";
 1602:     if ($coursedoc) {
 1603: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1604: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1605:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1606:             return &finishuserfileupload($docuname,$docudom,
 1607: 					 $formname,$fname,$parser,$allfiles,
 1608: 					 $codebase,$thumbwidth,$thumbheight);
 1609:         } else {
 1610:             $fname=$env{'form.folder'}.'/'.$fname;
 1611:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1612: 				       $fname,$formname,$parser,
 1613: 				       $allfiles,$codebase);
 1614:         }
 1615:     } elsif (defined($destuname)) {
 1616:         my $docuname=$destuname;
 1617:         my $docudom=$destudom;
 1618: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1619: 				     $parser,$allfiles,$codebase,
 1620:                                      $thumbwidth,$thumbheight);
 1621:         
 1622:     } else {
 1623:         my $docuname=$env{'user.name'};
 1624:         my $docudom=$env{'user.domain'};
 1625:         if (exists($env{'form.group'})) {
 1626:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1627:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1628:         }
 1629: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1630: 				     $parser,$allfiles,$codebase,
 1631:                                      $thumbwidth,$thumbheight);
 1632:     }
 1633: }
 1634: 
 1635: sub finishuserfileupload {
 1636:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1637:         $thumbwidth,$thumbheight) = @_;
 1638:     my $path=$docudom.'/'.$docuname.'/';
 1639:     my $filepath=$perlvar{'lonDocRoot'};
 1640:     my ($fnamepath,$file,$fetchthumb);
 1641:     $file=$fname;
 1642:     if ($fname=~m|/|) {
 1643:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1644: 	$path.=$fnamepath.'/';
 1645:     }
 1646:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1647:     my $count;
 1648:     for ($count=4;$count<=$#parts;$count++) {
 1649:         $filepath.="/$parts[$count]";
 1650:         if ((-e $filepath)!=1) {
 1651: 	    mkdir($filepath,0777);
 1652:         }
 1653:     }
 1654: # Save the file
 1655:     {
 1656: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1657: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1658: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1659: 	    return '/adm/notfound.html';
 1660: 	}
 1661: 	if (!print FH ($env{'form.'.$formname})) {
 1662: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1663: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1664: 	    return '/adm/notfound.html';
 1665: 	}
 1666: 	close(FH);
 1667:     }
 1668:     if ($parser eq 'parse') {
 1669:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1670: 						   $codebase);
 1671:         unless ($parse_result eq 'ok') {
 1672:             &logthis('Failed to parse '.$filepath.$file.
 1673: 		     ' for embedded media: '.$parse_result); 
 1674:         }
 1675:     }
 1676:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1677:         my $input = $filepath.'/'.$file;
 1678:         my $output = $filepath.'/'.'tn-'.$file;
 1679:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1680:         system("convert -sample $thumbsize $input $output");
 1681:         if (-e $filepath.'/'.'tn-'.$file) {
 1682:             $fetchthumb  = 1; 
 1683:         }
 1684:     }
 1685:  
 1686: # Notify homeserver to grep it
 1687: #
 1688:     my $docuhome=&homeserver($docuname,$docudom);
 1689:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1690:     if ($fetchresult eq 'ok') {
 1691:         if ($fetchthumb) {
 1692:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1693:             if ($thumbresult ne 'ok') {
 1694:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1695:                          $docuhome.': '.$thumbresult);
 1696:             }
 1697:         }
 1698: #
 1699: # Return the URL to it
 1700:         return '/uploaded/'.$path.$file;
 1701:     } else {
 1702:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1703: 		 ': '.$fetchresult);
 1704:         return '/adm/notfound.html';
 1705:     }
 1706: }
 1707: 
 1708: sub extract_embedded_items {
 1709:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1710:     my @state = ();
 1711:     my %javafiles = (
 1712:                       codebase => '',
 1713:                       code => '',
 1714:                       archive => ''
 1715:                     );
 1716:     my %mediafiles = (
 1717:                       src => '',
 1718:                       movie => '',
 1719:                      );
 1720:     my $p;
 1721:     if ($content) {
 1722:         $p = HTML::LCParser->new($content);
 1723:     } else {
 1724:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1725:     }
 1726:     while (my $t=$p->get_token()) {
 1727: 	if ($t->[0] eq 'S') {
 1728: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1729: 	    push (@state, $tagname);
 1730:             if (lc($tagname) eq 'allow') {
 1731:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1732:             }
 1733: 	    if (lc($tagname) eq 'img') {
 1734: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1735: 	    }
 1736:             if (lc($tagname) eq 'script') {
 1737:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1738:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1739:                 } else {
 1740:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1741:                 }
 1742:             }
 1743:             if (lc($tagname) eq 'link') {
 1744:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1745:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1746:                 }
 1747:             }
 1748: 	    if (lc($tagname) eq 'object' ||
 1749: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1750: 		foreach my $item (keys(%javafiles)) {
 1751: 		    $javafiles{$item} = '';
 1752: 		}
 1753: 	    }
 1754: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1755: 		my $name = lc($attr->{'name'});
 1756: 		foreach my $item (keys(%javafiles)) {
 1757: 		    if ($name eq $item) {
 1758: 			$javafiles{$item} = $attr->{'value'};
 1759: 			last;
 1760: 		    }
 1761: 		}
 1762: 		foreach my $item (keys(%mediafiles)) {
 1763: 		    if ($name eq $item) {
 1764: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1765: 			last;
 1766: 		    }
 1767: 		}
 1768: 	    }
 1769: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1770: 		foreach my $item (keys(%javafiles)) {
 1771: 		    if ($attr->{$item}) {
 1772: 			$javafiles{$item} = $attr->{$item};
 1773: 			last;
 1774: 		    }
 1775: 		}
 1776: 		foreach my $item (keys(%mediafiles)) {
 1777: 		    if ($attr->{$item}) {
 1778: 			&add_filetype($allfiles,$attr->{$item},$item);
 1779: 			last;
 1780: 		    }
 1781: 		}
 1782: 	    }
 1783: 	} elsif ($t->[0] eq 'E') {
 1784: 	    my ($tagname) = ($t->[1]);
 1785: 	    if ($javafiles{'codebase'} ne '') {
 1786: 		$javafiles{'codebase'} .= '/';
 1787: 	    }  
 1788: 	    if (lc($tagname) eq 'applet' ||
 1789: 		lc($tagname) eq 'object' ||
 1790: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1791: 		) {
 1792: 		foreach my $item (keys(%javafiles)) {
 1793: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1794: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1795: 			&add_filetype($allfiles,$file,$item);
 1796: 		    }
 1797: 		}
 1798: 	    } 
 1799: 	    pop @state;
 1800: 	}
 1801:     }
 1802:     return 'ok';
 1803: }
 1804: 
 1805: sub add_filetype {
 1806:     my ($allfiles,$file,$type)=@_;
 1807:     if (exists($allfiles->{$file})) {
 1808: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1809: 	    push(@{$allfiles->{$file}}, &escape($type));
 1810: 	}
 1811:     } else {
 1812: 	@{$allfiles->{$file}} = (&escape($type));
 1813:     }
 1814: }
 1815: 
 1816: sub removeuploadedurl {
 1817:     my ($url)=@_;
 1818:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1819:     return &removeuserfile($uname,$udom,$fname);
 1820: }
 1821: 
 1822: sub removeuserfile {
 1823:     my ($docuname,$docudom,$fname)=@_;
 1824:     my $home=&homeserver($docuname,$docudom);
 1825:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1826:     if ($result eq 'ok') {
 1827:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1828:             my $metafile = $fname.'.meta';
 1829:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1830: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1831:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1832:             my $sqlresult = 
 1833:                 &update_portfolio_table($docuname,$docudom,$file,
 1834:                                         'portfolio_metadata',$group,
 1835:                                         'delete');
 1836:         }
 1837:     }
 1838:     return $result;
 1839: }
 1840: 
 1841: sub mkdiruserfile {
 1842:     my ($docuname,$docudom,$dir)=@_;
 1843:     my $home=&homeserver($docuname,$docudom);
 1844:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1845: }
 1846: 
 1847: sub renameuserfile {
 1848:     my ($docuname,$docudom,$old,$new)=@_;
 1849:     my $home=&homeserver($docuname,$docudom);
 1850:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1851:                         &escape("$old").':'.&escape("$new"),$home);
 1852:     if ($result eq 'ok') {
 1853:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1854:             my $oldmeta = $old.'.meta';
 1855:             my $newmeta = $new.'.meta';
 1856:             my $metaresult = 
 1857:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1858: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1859:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1860:             my $sqlresult = 
 1861:                 &update_portfolio_table($docuname,$docudom,$file,
 1862:                                         'portfolio_metadata',$group,
 1863:                                         'delete');
 1864:         }
 1865:     }
 1866:     return $result;
 1867: }
 1868: 
 1869: # ------------------------------------------------------------------------- Log
 1870: 
 1871: sub log {
 1872:     my ($dom,$nam,$hom,$what)=@_;
 1873:     return critical("log:$dom:$nam:$what",$hom);
 1874: }
 1875: 
 1876: # ------------------------------------------------------------------ Course Log
 1877: #
 1878: # This routine flushes several buffers of non-mission-critical nature
 1879: #
 1880: 
 1881: sub flushcourselogs {
 1882:     &logthis('Flushing log buffers');
 1883: #
 1884: # course logs
 1885: # This is a log of all transactions in a course, which can be used
 1886: # for data mining purposes
 1887: #
 1888: # It also collects the courseid database, which lists last transaction
 1889: # times and course titles for all courseids
 1890: #
 1891:     my %courseidbuffer=();
 1892:     foreach my $crsid (keys %courselogs) {
 1893:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1894: 		          &escape($courselogs{$crsid}),
 1895: 		          $coursehombuf{$crsid}) eq 'ok') {
 1896: 	    delete $courselogs{$crsid};
 1897:         } else {
 1898:             &logthis('Failed to flush log buffer for '.$crsid);
 1899:             if (length($courselogs{$crsid})>40000) {
 1900:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1901:                         " exceeded maximum size, deleting.</font>");
 1902:                delete $courselogs{$crsid};
 1903:             }
 1904:         }
 1905:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1906:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1907: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1908:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1909:         } else {
 1910:            $courseidbuffer{$coursehombuf{$crsid}}=
 1911: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1912:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1913:         }
 1914:     }
 1915: #
 1916: # Write course id database (reverse lookup) to homeserver of courses 
 1917: # Is used in pickcourse
 1918: #
 1919:     foreach my $crs_home (keys(%courseidbuffer)) {
 1920:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1921: 		     $crs_home);
 1922:     }
 1923: #
 1924: # File accesses
 1925: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1926: #
 1927:     foreach my $entry (keys(%accesshash)) {
 1928:         if ($entry =~ /___count$/) {
 1929:             my ($dom,$name);
 1930:             ($dom,$name,undef)=
 1931: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1932:             if (! defined($dom) || $dom eq '' || 
 1933:                 ! defined($name) || $name eq '') {
 1934:                 my $cid = $env{'request.course.id'};
 1935:                 $dom  = $env{'request.'.$cid.'.domain'};
 1936:                 $name = $env{'request.'.$cid.'.num'};
 1937:             }
 1938:             my $value = $accesshash{$entry};
 1939:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1940:             my %temphash=($url => $value);
 1941:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1942:             if ($result eq 'ok') {
 1943:                 delete $accesshash{$entry};
 1944:             } elsif ($result eq 'unknown_cmd') {
 1945:                 # Target server has old code running on it.
 1946:                 my %temphash=($entry => $value);
 1947:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1948:                     delete $accesshash{$entry};
 1949:                 }
 1950:             }
 1951:         } else {
 1952:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1953:             my %temphash=($entry => $accesshash{$entry});
 1954:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1955:                 delete $accesshash{$entry};
 1956:             }
 1957:         }
 1958:     }
 1959: #
 1960: # Roles
 1961: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1962: #
 1963:     foreach my $entry (keys(%userrolehash)) {
 1964:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1965: 	    split(/\:/,$entry);
 1966:         if (&Apache::lonnet::put('nohist_userroles',
 1967:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1968:                 $rudom,$runame) eq 'ok') {
 1969: 	    delete $userrolehash{$entry};
 1970:         }
 1971:     }
 1972: #
 1973: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1974: #
 1975:     my %domrolebuffer = ();
 1976:     foreach my $entry (keys %domainrolehash) {
 1977:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1978:         if ($domrolebuffer{$rudom}) {
 1979:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1980:                       '='.&escape($domainrolehash{$entry});
 1981:         } else {
 1982:             $domrolebuffer{$rudom}.=&escape($entry).
 1983:                       '='.&escape($domainrolehash{$entry});
 1984:         }
 1985:         delete $domainrolehash{$entry};
 1986:     }
 1987:     foreach my $dom (keys(%domrolebuffer)) {
 1988: 	my %servers = &get_servers($dom,'library');
 1989: 	foreach my $tryserver (keys(%servers)) {
 1990: 	    unless (&reply('domroleput:'.$dom.':'.
 1991: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1992: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1993: 	    }
 1994:         }
 1995:     }
 1996:     $dumpcount++;
 1997: }
 1998: 
 1999: sub courselog {
 2000:     my $what=shift;
 2001:     $what=time.':'.$what;
 2002:     unless ($env{'request.course.id'}) { return ''; }
 2003:     $coursedombuf{$env{'request.course.id'}}=
 2004:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2005:     $coursenumbuf{$env{'request.course.id'}}=
 2006:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2007:     $coursehombuf{$env{'request.course.id'}}=
 2008:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2009:     $coursedescrbuf{$env{'request.course.id'}}=
 2010:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2011:     $courseinstcodebuf{$env{'request.course.id'}}=
 2012:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2013:     $courseownerbuf{$env{'request.course.id'}}=
 2014:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2015:     $coursetypebuf{$env{'request.course.id'}}=
 2016:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2017:     if (defined $courselogs{$env{'request.course.id'}}) {
 2018: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2019:     } else {
 2020: 	$courselogs{$env{'request.course.id'}}.=$what;
 2021:     }
 2022:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2023: 	&flushcourselogs();
 2024:     }
 2025: }
 2026: 
 2027: sub courseacclog {
 2028:     my $fnsymb=shift;
 2029:     unless ($env{'request.course.id'}) { return ''; }
 2030:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2031:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2032:         $what.=':POST';
 2033:         # FIXME: Probably ought to escape things....
 2034: 	foreach my $key (keys(%env)) {
 2035:             if ($key=~/^form\.(.*)/) {
 2036: 		$what.=':'.$1.'='.$env{$key};
 2037:             }
 2038:         }
 2039:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2040:         # FIXME: We should not be depending on a form parameter that someone
 2041:         # editing lonsearchcat.pm might change in the future.
 2042:         if ($env{'form.phase'} eq 'course_search') {
 2043:             $what.= ':POST';
 2044:             # FIXME: Probably ought to escape things....
 2045:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2046:                                  'crsdiscuss') {
 2047:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2048:             }
 2049:         }
 2050:     }
 2051:     &courselog($what);
 2052: }
 2053: 
 2054: sub countacc {
 2055:     my $url=&declutter(shift);
 2056:     return if (! defined($url) || $url eq '');
 2057:     unless ($env{'request.course.id'}) { return ''; }
 2058:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2059:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2060:     $accesshash{$key}++;
 2061: }
 2062: 
 2063: sub linklog {
 2064:     my ($from,$to)=@_;
 2065:     $from=&declutter($from);
 2066:     $to=&declutter($to);
 2067:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2068:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2069: }
 2070:   
 2071: sub userrolelog {
 2072:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2073:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2074:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2075:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2076:         ($trole=~/^ta/)) {
 2077:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2078:        $userrolehash
 2079:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2080:                     =$tend.':'.$tstart;
 2081:     }
 2082:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2083:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2084:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2085:         ($trole=~/^sc/)) {
 2086:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2087:        $domainrolehash
 2088:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2089:                     = $tend.':'.$tstart;
 2090:     }
 2091: }
 2092: 
 2093: sub get_course_adv_roles {
 2094:     my $cid=shift;
 2095:     $cid=$env{'request.course.id'} unless (defined($cid));
 2096:     my %coursehash=&coursedescription($cid);
 2097:     my %nothide=();
 2098:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2099: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2100:     }
 2101:     my %returnhash=();
 2102:     my %dumphash=
 2103:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2104:     my $now=time;
 2105:     foreach my $entry (keys %dumphash) {
 2106: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2107:         if (($tstart) && ($tstart<0)) { next; }
 2108:         if (($tend) && ($tend<$now)) { next; }
 2109:         if (($tstart) && ($now<$tstart)) { next; }
 2110:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2111: 	if ($username eq '' || $domain eq '') { next; }
 2112: 	if ((&privileged($username,$domain)) && 
 2113: 	    (!$nothide{$username.':'.$domain})) { next; }
 2114: 	if ($role eq 'cr') { next; }
 2115:         my $key=&plaintext($role);
 2116:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2117:         if ($returnhash{$key}) {
 2118: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2119:         } else {
 2120:             $returnhash{$key}=$username.':'.$domain;
 2121:         }
 2122:      }
 2123:     return %returnhash;
 2124: }
 2125: 
 2126: sub get_my_roles {
 2127:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2128:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2129:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2130:     my %dumphash;
 2131:     if ($context eq 'userroles') { 
 2132:         %dumphash = &dump('roles',$udom,$uname);
 2133:     } else {
 2134:         %dumphash=
 2135:             &dump('nohist_userroles',$udom,$uname);
 2136:     }
 2137:     my %returnhash=();
 2138:     my $now=time;
 2139:     foreach my $entry (keys(%dumphash)) {
 2140:         my ($role,$tend,$tstart);
 2141:         if ($context eq 'userroles') {
 2142: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2143:         } else {
 2144:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2145:         }
 2146:         if (($tstart) && ($tstart<0)) { next; }
 2147:         my $status = 'active';
 2148:         if (($tend) && ($tend<$now)) {
 2149:             $status = 'previous';
 2150:         } 
 2151:         if (($tstart) && ($now<$tstart)) {
 2152:             $status = 'future';
 2153:         }
 2154:         if (ref($types) eq 'ARRAY') {
 2155:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2156:                 next;
 2157:             } 
 2158:         } else {
 2159:             if ($status ne 'active') {
 2160:                 next;
 2161:             }
 2162:         }
 2163:         my ($rolecode,$username,$domain,$section,$area);
 2164:         if ($context eq 'userroles') {
 2165:             ($area,$rolecode) = split(/_/,$entry);
 2166:             (undef,$domain,$username,$section) = split(/\//,$area);
 2167:         } else {
 2168:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2169:         }
 2170:         if (ref($roledoms) eq 'ARRAY') {
 2171:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2172:                 next;
 2173:             }
 2174:         }
 2175:         if (ref($roles) eq 'ARRAY') {
 2176:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2177:                 next;
 2178:             }
 2179:         }
 2180: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2181:     }
 2182:     return %returnhash;
 2183: }
 2184: 
 2185: # ----------------------------------------------------- Frontpage Announcements
 2186: #
 2187: #
 2188: 
 2189: sub postannounce {
 2190:     my ($server,$text)=@_;
 2191:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2192:     unless ($text=~/\w/) { $text=''; }
 2193:     return &reply('setannounce:'.&escape($text),$server);
 2194: }
 2195: 
 2196: sub getannounce {
 2197: 
 2198:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2199: 	my $announcement='';
 2200: 	while (my $line = <$fh>) { $announcement .= $line; }
 2201: 	close($fh);
 2202: 	if ($announcement=~/\w/) { 
 2203: 	    return 
 2204:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2205:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2206: 	} else {
 2207: 	    return '';
 2208: 	}
 2209:     } else {
 2210: 	return '';
 2211:     }
 2212: }
 2213: 
 2214: # ---------------------------------------------------------- Course ID routines
 2215: # Deal with domain's nohist_courseid.db files
 2216: #
 2217: 
 2218: sub courseidput {
 2219:     my ($domain,$what,$coursehome)=@_;
 2220:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2221: }
 2222: 
 2223: sub courseiddump {
 2224:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2225:     my %returnhash=();
 2226:     unless ($domfilter) { $domfilter=''; }
 2227:     my %libserv = &all_library();
 2228:     foreach my $tryserver (keys(%libserv)) {
 2229:         if ( (  $hostidflag == 1 
 2230: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2231: 	     || (!defined($hostidflag)) ) {
 2232: 
 2233: 	    if ($domfilter eq ''
 2234: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2235: 	        foreach my $line (
 2236:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2237: 			       $sincefilter.':'.&escape($descfilter).':'.
 2238:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2239:                                $tryserver))) {
 2240: 		    my ($key,$value)=split(/\=/,$line,2);
 2241:                     if (($key) && ($value)) {
 2242: 		        $returnhash{&unescape($key)}=$value;
 2243:                     }
 2244:                 }
 2245:             }
 2246:         }
 2247:     }
 2248:     return %returnhash;
 2249: }
 2250: 
 2251: # ---------------------------------------------------------- DC e-mail
 2252: 
 2253: sub dcmailput {
 2254:     my ($domain,$msgid,$message,$server)=@_;
 2255:     my $status = &Apache::lonnet::critical(
 2256:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2257:        &escape($message),$server);
 2258:     return $status;
 2259: }
 2260: 
 2261: sub dcmaildump {
 2262:     my ($dom,$startdate,$enddate,$senders) = @_;
 2263:     my %returnhash=();
 2264: 
 2265:     if (defined(&domain($dom,'primary'))) {
 2266:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2267:                                                          &escape($enddate).':';
 2268: 	my @esc_senders=map { &escape($_)} @$senders;
 2269: 	$cmd.=&escape(join('&',@esc_senders));
 2270: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2271:             my ($key,$value) = split(/\=/,$line,2);
 2272:             if (($key) && ($value)) {
 2273:                 $returnhash{&unescape($key)} = &unescape($value);
 2274:             }
 2275:         }
 2276:     }
 2277:     return %returnhash;
 2278: }
 2279: # ---------------------------------------------------------- Domain roles
 2280: 
 2281: sub get_domain_roles {
 2282:     my ($dom,$roles,$startdate,$enddate)=@_;
 2283:     if (undef($startdate) || $startdate eq '') {
 2284:         $startdate = '.';
 2285:     }
 2286:     if (undef($enddate) || $enddate eq '') {
 2287:         $enddate = '.';
 2288:     }
 2289:     my $rolelist = join(':',@{$roles});
 2290:     my %personnel = ();
 2291: 
 2292:     my %servers = &get_servers($dom,'library');
 2293:     foreach my $tryserver (keys(%servers)) {
 2294: 	%{$personnel{$tryserver}}=();
 2295: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2296: 					    &escape($startdate).':'.
 2297: 					    &escape($enddate).':'.
 2298: 					    &escape($rolelist), $tryserver))) {
 2299: 	    my ($key,$value) = split(/\=/,$line,2);
 2300: 	    if (($key) && ($value)) {
 2301: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2302: 	    }
 2303: 	}
 2304:     }
 2305:     return %personnel;
 2306: }
 2307: 
 2308: # ----------------------------------------------------------- Check out an item
 2309: 
 2310: sub get_first_access {
 2311:     my ($type,$argsymb)=@_;
 2312:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2313:     if ($argsymb) { $symb=$argsymb; }
 2314:     my ($map,$id,$res)=&decode_symb($symb);
 2315:     if ($type eq 'map') {
 2316: 	$res=&symbread($map);
 2317:     } else {
 2318: 	$res=$symb;
 2319:     }
 2320:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2321:     return $times{"$courseid\0$res"};
 2322: }
 2323: 
 2324: sub set_first_access {
 2325:     my ($type)=@_;
 2326:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2327:     my ($map,$id,$res)=&decode_symb($symb);
 2328:     if ($type eq 'map') {
 2329: 	$res=&symbread($map);
 2330:     } else {
 2331: 	$res=$symb;
 2332:     }
 2333:     my $firstaccess=&get_first_access($type,$symb);
 2334:     if (!$firstaccess) {
 2335: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2336:     }
 2337:     return 'already_set';
 2338: }
 2339: 
 2340: sub checkout {
 2341:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2342:     my $now=time;
 2343:     my $lonhost=$perlvar{'lonHostID'};
 2344:     my $infostr=&escape(
 2345:                  'CHECKOUTTOKEN&'.
 2346:                  $tuname.'&'.
 2347:                  $tudom.'&'.
 2348:                  $tcrsid.'&'.
 2349:                  $symb.'&'.
 2350: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2351:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2352:     if ($token=~/^error\:/) { 
 2353:         &logthis("<font color=\"blue\">WARNING: ".
 2354:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2355:                  "</font>");
 2356:         return ''; 
 2357:     }
 2358: 
 2359:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2360:     $token=~tr/a-z/A-Z/;
 2361: 
 2362:     my %infohash=('resource.0.outtoken' => $token,
 2363:                   'resource.0.checkouttime' => $now,
 2364:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2365: 
 2366:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2367:        return '';
 2368:     } else {
 2369:         &logthis("<font color=\"blue\">WARNING: ".
 2370:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2371:                  "</font>");
 2372:     }    
 2373: 
 2374:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2375:                          &escape('Checkout '.$infostr.' - '.
 2376:                                                  $token)) ne 'ok') {
 2377: 	return '';
 2378:     } else {
 2379:         &logthis("<font color=\"blue\">WARNING: ".
 2380:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2381:                  "</font>");
 2382:     }
 2383:     return $token;
 2384: }
 2385: 
 2386: # ------------------------------------------------------------ Check in an item
 2387: 
 2388: sub checkin {
 2389:     my $token=shift;
 2390:     my $now=time;
 2391:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2392:     $lonhost=~tr/A-Z/a-z/;
 2393:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2394:     $dtoken=~s/\W/\_/g;
 2395:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2396:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2397: 
 2398:     unless (($tuname) && ($tudom)) {
 2399:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2400:         return '';
 2401:     }
 2402:     
 2403:     unless (&allowed('mgr',$tcrsid)) {
 2404:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2405:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2406:         return '';
 2407:     }
 2408: 
 2409:     my %infohash=('resource.0.intoken' => $token,
 2410:                   'resource.0.checkintime' => $now,
 2411:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2412: 
 2413:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2414:        return '';
 2415:     }    
 2416: 
 2417:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2418:                          &escape('Checkin - '.$token)) ne 'ok') {
 2419: 	return '';
 2420:     }
 2421: 
 2422:     return ($symb,$tuname,$tudom,$tcrsid);    
 2423: }
 2424: 
 2425: # --------------------------------------------- Set Expire Date for Spreadsheet
 2426: 
 2427: sub expirespread {
 2428:     my ($uname,$udom,$stype,$usymb)=@_;
 2429:     my $cid=$env{'request.course.id'}; 
 2430:     if ($cid) {
 2431:        my $now=time;
 2432:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2433:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2434:                             $env{'course.'.$cid.'.num'}.
 2435: 	        	    ':nohist_expirationdates:'.
 2436:                             &escape($key).'='.$now,
 2437:                             $env{'course.'.$cid.'.home'})
 2438:     }
 2439:     return 'ok';
 2440: }
 2441: 
 2442: # ----------------------------------------------------- Devalidate Spreadsheets
 2443: 
 2444: sub devalidate {
 2445:     my ($symb,$uname,$udom)=@_;
 2446:     my $cid=$env{'request.course.id'}; 
 2447:     if ($cid) {
 2448:         # delete the stored spreadsheets for
 2449:         # - the student level sheet of this user in course's homespace
 2450:         # - the assessment level sheet for this resource 
 2451:         #   for this user in user's homespace
 2452: 	# - current conditional state info
 2453: 	my $key=$uname.':'.$udom.':';
 2454:         my $status=
 2455: 	    &del('nohist_calculatedsheets',
 2456: 		 [$key.'studentcalc:'],
 2457: 		 $env{'course.'.$cid.'.domain'},
 2458: 		 $env{'course.'.$cid.'.num'})
 2459: 		.' '.
 2460: 	    &del('nohist_calculatedsheets_'.$cid,
 2461: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2462:         unless ($status eq 'ok ok') {
 2463:            &logthis('Could not devalidate spreadsheet '.
 2464:                     $uname.' at '.$udom.' for '.
 2465: 		    $symb.': '.$status);
 2466:         }
 2467: 	&delenv('user.state.'.$cid);
 2468:     }
 2469: }
 2470: 
 2471: sub get_scalar {
 2472:     my ($string,$end) = @_;
 2473:     my $value;
 2474:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2475: 	$value = $1;
 2476:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2477: 	$value = $1;
 2478:     }
 2479:     return &unescape($value);
 2480: }
 2481: 
 2482: sub array2str {
 2483:   my (@array) = @_;
 2484:   my $result=&arrayref2str(\@array);
 2485:   $result=~s/^__ARRAY_REF__//;
 2486:   $result=~s/__END_ARRAY_REF__$//;
 2487:   return $result;
 2488: }
 2489: 
 2490: sub arrayref2str {
 2491:   my ($arrayref) = @_;
 2492:   my $result='__ARRAY_REF__';
 2493:   foreach my $elem (@$arrayref) {
 2494:     if(ref($elem) eq 'ARRAY') {
 2495:       $result.=&arrayref2str($elem).'&';
 2496:     } elsif(ref($elem) eq 'HASH') {
 2497:       $result.=&hashref2str($elem).'&';
 2498:     } elsif(ref($elem)) {
 2499:       #print("Got a ref of ".(ref($elem))." skipping.");
 2500:     } else {
 2501:       $result.=&escape($elem).'&';
 2502:     }
 2503:   }
 2504:   $result=~s/\&$//;
 2505:   $result .= '__END_ARRAY_REF__';
 2506:   return $result;
 2507: }
 2508: 
 2509: sub hash2str {
 2510:   my (%hash) = @_;
 2511:   my $result=&hashref2str(\%hash);
 2512:   $result=~s/^__HASH_REF__//;
 2513:   $result=~s/__END_HASH_REF__$//;
 2514:   return $result;
 2515: }
 2516: 
 2517: sub hashref2str {
 2518:   my ($hashref)=@_;
 2519:   my $result='__HASH_REF__';
 2520:   foreach my $key (sort(keys(%$hashref))) {
 2521:     if (ref($key) eq 'ARRAY') {
 2522:       $result.=&arrayref2str($key).'=';
 2523:     } elsif (ref($key) eq 'HASH') {
 2524:       $result.=&hashref2str($key).'=';
 2525:     } elsif (ref($key)) {
 2526:       $result.='=';
 2527:       #print("Got a ref of ".(ref($key))." skipping.");
 2528:     } else {
 2529: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2530:     }
 2531: 
 2532:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2533:       $result.=&arrayref2str($hashref->{$key}).'&';
 2534:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2535:       $result.=&hashref2str($hashref->{$key}).'&';
 2536:     } elsif(ref($hashref->{$key})) {
 2537:        $result.='&';
 2538:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2539:     } else {
 2540:       $result.=&escape($hashref->{$key}).'&';
 2541:     }
 2542:   }
 2543:   $result=~s/\&$//;
 2544:   $result .= '__END_HASH_REF__';
 2545:   return $result;
 2546: }
 2547: 
 2548: sub str2hash {
 2549:     my ($string)=@_;
 2550:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2551:     return %$hash;
 2552: }
 2553: 
 2554: sub str2hashref {
 2555:   my ($string) = @_;
 2556: 
 2557:   my %hash;
 2558: 
 2559:   if($string !~ /^__HASH_REF__/) {
 2560:       if (! ($string eq '' || !defined($string))) {
 2561: 	  $hash{'error'}='Not hash reference';
 2562:       }
 2563:       return (\%hash, $string);
 2564:   }
 2565: 
 2566:   $string =~ s/^__HASH_REF__//;
 2567: 
 2568:   while($string !~ /^__END_HASH_REF__/) {
 2569:       #key
 2570:       my $key='';
 2571:       if($string =~ /^__HASH_REF__/) {
 2572:           ($key, $string)=&str2hashref($string);
 2573:           if(defined($key->{'error'})) {
 2574:               $hash{'error'}='Bad data';
 2575:               return (\%hash, $string);
 2576:           }
 2577:       } elsif($string =~ /^__ARRAY_REF__/) {
 2578:           ($key, $string)=&str2arrayref($string);
 2579:           if($key->[0] eq 'Array reference error') {
 2580:               $hash{'error'}='Bad data';
 2581:               return (\%hash, $string);
 2582:           }
 2583:       } else {
 2584:           $string =~ s/^(.*?)=//;
 2585: 	  $key=&unescape($1);
 2586:       }
 2587:       $string =~ s/^=//;
 2588: 
 2589:       #value
 2590:       my $value='';
 2591:       if($string =~ /^__HASH_REF__/) {
 2592:           ($value, $string)=&str2hashref($string);
 2593:           if(defined($value->{'error'})) {
 2594:               $hash{'error'}='Bad data';
 2595:               return (\%hash, $string);
 2596:           }
 2597:       } elsif($string =~ /^__ARRAY_REF__/) {
 2598:           ($value, $string)=&str2arrayref($string);
 2599:           if($value->[0] eq 'Array reference error') {
 2600:               $hash{'error'}='Bad data';
 2601:               return (\%hash, $string);
 2602:           }
 2603:       } else {
 2604: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2605:       }
 2606:       $string =~ s/^&//;
 2607: 
 2608:       $hash{$key}=$value;
 2609:   }
 2610: 
 2611:   $string =~ s/^__END_HASH_REF__//;
 2612: 
 2613:   return (\%hash, $string);
 2614: }
 2615: 
 2616: sub str2array {
 2617:     my ($string)=@_;
 2618:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2619:     return @$array;
 2620: }
 2621: 
 2622: sub str2arrayref {
 2623:   my ($string) = @_;
 2624:   my @array;
 2625: 
 2626:   if($string !~ /^__ARRAY_REF__/) {
 2627:       if (! ($string eq '' || !defined($string))) {
 2628: 	  $array[0]='Array reference error';
 2629:       }
 2630:       return (\@array, $string);
 2631:   }
 2632: 
 2633:   $string =~ s/^__ARRAY_REF__//;
 2634: 
 2635:   while($string !~ /^__END_ARRAY_REF__/) {
 2636:       my $value='';
 2637:       if($string =~ /^__HASH_REF__/) {
 2638:           ($value, $string)=&str2hashref($string);
 2639:           if(defined($value->{'error'})) {
 2640:               $array[0] ='Array reference error';
 2641:               return (\@array, $string);
 2642:           }
 2643:       } elsif($string =~ /^__ARRAY_REF__/) {
 2644:           ($value, $string)=&str2arrayref($string);
 2645:           if($value->[0] eq 'Array reference error') {
 2646:               $array[0] ='Array reference error';
 2647:               return (\@array, $string);
 2648:           }
 2649:       } else {
 2650: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2651:       }
 2652:       $string =~ s/^&//;
 2653: 
 2654:       push(@array, $value);
 2655:   }
 2656: 
 2657:   $string =~ s/^__END_ARRAY_REF__//;
 2658: 
 2659:   return (\@array, $string);
 2660: }
 2661: 
 2662: # -------------------------------------------------------------------Temp Store
 2663: 
 2664: sub tmpreset {
 2665:   my ($symb,$namespace,$domain,$stuname) = @_;
 2666:   if (!$symb) {
 2667:     $symb=&symbread();
 2668:     if (!$symb) { $symb= $env{'request.url'}; }
 2669:   }
 2670:   $symb=escape($symb);
 2671: 
 2672:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2673:   $namespace=~s/\//\_/g;
 2674:   $namespace=~s/\W//g;
 2675: 
 2676:   if (!$domain) { $domain=$env{'user.domain'}; }
 2677:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2678:   if ($domain eq 'public' && $stuname eq 'public') {
 2679:       $stuname=$ENV{'REMOTE_ADDR'};
 2680:   }
 2681:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2682:   my %hash;
 2683:   if (tie(%hash,'GDBM_File',
 2684: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2685: 	  &GDBM_WRCREAT(),0640)) {
 2686:     foreach my $key (keys %hash) {
 2687:       if ($key=~ /:$symb/) {
 2688: 	delete($hash{$key});
 2689:       }
 2690:     }
 2691:   }
 2692: }
 2693: 
 2694: sub tmpstore {
 2695:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2696: 
 2697:   if (!$symb) {
 2698:     $symb=&symbread();
 2699:     if (!$symb) { $symb= $env{'request.url'}; }
 2700:   }
 2701:   $symb=escape($symb);
 2702: 
 2703:   if (!$namespace) {
 2704:     # I don't think we would ever want to store this for a course.
 2705:     # it seems this will only be used if we don't have a course.
 2706:     #$namespace=$env{'request.course.id'};
 2707:     #if (!$namespace) {
 2708:       $namespace=$env{'request.state'};
 2709:     #}
 2710:   }
 2711:   $namespace=~s/\//\_/g;
 2712:   $namespace=~s/\W//g;
 2713:   if (!$domain) { $domain=$env{'user.domain'}; }
 2714:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2715:   if ($domain eq 'public' && $stuname eq 'public') {
 2716:       $stuname=$ENV{'REMOTE_ADDR'};
 2717:   }
 2718:   my $now=time;
 2719:   my %hash;
 2720:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2721:   if (tie(%hash,'GDBM_File',
 2722: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2723: 	  &GDBM_WRCREAT(),0640)) {
 2724:     $hash{"version:$symb"}++;
 2725:     my $version=$hash{"version:$symb"};
 2726:     my $allkeys=''; 
 2727:     foreach my $key (keys(%$storehash)) {
 2728:       $allkeys.=$key.':';
 2729:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2730:     }
 2731:     $hash{"$version:$symb:timestamp"}=$now;
 2732:     $allkeys.='timestamp';
 2733:     $hash{"$version:keys:$symb"}=$allkeys;
 2734:     if (untie(%hash)) {
 2735:       return 'ok';
 2736:     } else {
 2737:       return "error:$!";
 2738:     }
 2739:   } else {
 2740:     return "error:$!";
 2741:   }
 2742: }
 2743: 
 2744: # -----------------------------------------------------------------Temp Restore
 2745: 
 2746: sub tmprestore {
 2747:   my ($symb,$namespace,$domain,$stuname) = @_;
 2748: 
 2749:   if (!$symb) {
 2750:     $symb=&symbread();
 2751:     if (!$symb) { $symb= $env{'request.url'}; }
 2752:   }
 2753:   $symb=escape($symb);
 2754: 
 2755:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2756: 
 2757:   if (!$domain) { $domain=$env{'user.domain'}; }
 2758:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2759:   if ($domain eq 'public' && $stuname eq 'public') {
 2760:       $stuname=$ENV{'REMOTE_ADDR'};
 2761:   }
 2762:   my %returnhash;
 2763:   $namespace=~s/\//\_/g;
 2764:   $namespace=~s/\W//g;
 2765:   my %hash;
 2766:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2767:   if (tie(%hash,'GDBM_File',
 2768: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2769: 	  &GDBM_READER(),0640)) {
 2770:     my $version=$hash{"version:$symb"};
 2771:     $returnhash{'version'}=$version;
 2772:     my $scope;
 2773:     for ($scope=1;$scope<=$version;$scope++) {
 2774:       my $vkeys=$hash{"$scope:keys:$symb"};
 2775:       my @keys=split(/:/,$vkeys);
 2776:       my $key;
 2777:       $returnhash{"$scope:keys"}=$vkeys;
 2778:       foreach $key (@keys) {
 2779: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2780: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2781:       }
 2782:     }
 2783:     if (!(untie(%hash))) {
 2784:       return "error:$!";
 2785:     }
 2786:   } else {
 2787:     return "error:$!";
 2788:   }
 2789:   return %returnhash;
 2790: }
 2791: 
 2792: # ----------------------------------------------------------------------- Store
 2793: 
 2794: sub store {
 2795:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2796:     my $home='';
 2797: 
 2798:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2799: 
 2800:     $symb=&symbclean($symb);
 2801:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2802: 
 2803:     if (!$domain) { $domain=$env{'user.domain'}; }
 2804:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2805: 
 2806:     &devalidate($symb,$stuname,$domain);
 2807: 
 2808:     $symb=escape($symb);
 2809:     if (!$namespace) { 
 2810:        unless ($namespace=$env{'request.course.id'}) { 
 2811:           return ''; 
 2812:        } 
 2813:     }
 2814:     if (!$home) { $home=$env{'user.home'}; }
 2815: 
 2816:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2817:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2818: 
 2819:     my $namevalue='';
 2820:     foreach my $key (keys(%$storehash)) {
 2821:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2822:     }
 2823:     $namevalue=~s/\&$//;
 2824:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2825:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2826: }
 2827: 
 2828: # -------------------------------------------------------------- Critical Store
 2829: 
 2830: sub cstore {
 2831:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2832:     my $home='';
 2833: 
 2834:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2835: 
 2836:     $symb=&symbclean($symb);
 2837:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2838: 
 2839:     if (!$domain) { $domain=$env{'user.domain'}; }
 2840:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2841: 
 2842:     &devalidate($symb,$stuname,$domain);
 2843: 
 2844:     $symb=escape($symb);
 2845:     if (!$namespace) { 
 2846:        unless ($namespace=$env{'request.course.id'}) { 
 2847:           return ''; 
 2848:        } 
 2849:     }
 2850:     if (!$home) { $home=$env{'user.home'}; }
 2851: 
 2852:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2853:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2854: 
 2855:     my $namevalue='';
 2856:     foreach my $key (keys(%$storehash)) {
 2857:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2858:     }
 2859:     $namevalue=~s/\&$//;
 2860:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2861:     return critical
 2862:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2863: }
 2864: 
 2865: # --------------------------------------------------------------------- Restore
 2866: 
 2867: sub restore {
 2868:     my ($symb,$namespace,$domain,$stuname) = @_;
 2869:     my $home='';
 2870: 
 2871:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2872: 
 2873:     if (!$symb) {
 2874:       unless ($symb=escape(&symbread())) { return ''; }
 2875:     } else {
 2876:       $symb=&escape(&symbclean($symb));
 2877:     }
 2878:     if (!$namespace) { 
 2879:        unless ($namespace=$env{'request.course.id'}) { 
 2880:           return ''; 
 2881:        } 
 2882:     }
 2883:     if (!$domain) { $domain=$env{'user.domain'}; }
 2884:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2885:     if (!$home) { $home=$env{'user.home'}; }
 2886:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2887: 
 2888:     my %returnhash=();
 2889:     foreach my $line (split(/\&/,$answer)) {
 2890: 	my ($name,$value)=split(/\=/,$line);
 2891:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2892:     }
 2893:     my $version;
 2894:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2895:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2896:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2897:        }
 2898:     }
 2899:     return %returnhash;
 2900: }
 2901: 
 2902: # ---------------------------------------------------------- Course Description
 2903: 
 2904: sub coursedescription {
 2905:     my ($courseid,$args)=@_;
 2906:     $courseid=~s/^\///;
 2907:     $courseid=~s/\_/\//g;
 2908:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2909:     my $chome=&homeserver($cnum,$cdomain);
 2910:     my $normalid=$cdomain.'_'.$cnum;
 2911:     # need to always cache even if we get errors otherwise we keep 
 2912:     # trying and trying and trying to get the course description.
 2913:     my %envhash=();
 2914:     my %returnhash=();
 2915:     
 2916:     my $expiretime=600;
 2917:     if ($env{'request.course.id'} eq $normalid) {
 2918: 	$expiretime=120;
 2919:     }
 2920: 
 2921:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2922:     if (!$args->{'freshen_cache'}
 2923: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2924: 	foreach my $key (keys(%env)) {
 2925: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2926: 	    my ($setting) = $1;
 2927: 	    $returnhash{$setting} = $env{$key};
 2928: 	}
 2929: 	return %returnhash;
 2930:     }
 2931: 
 2932:     # get the data agin
 2933:     if (!$args->{'one_time'}) {
 2934: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2935:     }
 2936: 
 2937:     if ($chome ne 'no_host') {
 2938:        %returnhash=&dump('environment',$cdomain,$cnum);
 2939:        if (!exists($returnhash{'con_lost'})) {
 2940:            $returnhash{'home'}= $chome;
 2941: 	   $returnhash{'domain'} = $cdomain;
 2942: 	   $returnhash{'num'} = $cnum;
 2943:            if (!defined($returnhash{'type'})) {
 2944:                $returnhash{'type'} = 'Course';
 2945:            }
 2946:            while (my ($name,$value) = each %returnhash) {
 2947:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2948:            }
 2949:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2950:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2951: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2952:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2953:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2954:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2955:        }
 2956:     }
 2957:     if (!$args->{'one_time'}) {
 2958: 	&appenv(%envhash);
 2959:     }
 2960:     return %returnhash;
 2961: }
 2962: 
 2963: # -------------------------------------------------See if a user is privileged
 2964: 
 2965: sub privileged {
 2966:     my ($username,$domain)=@_;
 2967:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2968: 			&homeserver($username,$domain));
 2969:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2970:     my $now=time;
 2971:     if ($rolesdump ne '') {
 2972:         foreach my $entry (split(/&/,$rolesdump)) {
 2973: 	    if ($entry!~/^rolesdef_/) {
 2974: 		my ($area,$role)=split(/=/,$entry);
 2975: 		$area=~s/\_\w\w$//;
 2976: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2977: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2978: 		    my $active=1;
 2979: 		    if ($tend) {
 2980: 			if ($tend<$now) { $active=0; }
 2981: 		    }
 2982: 		    if ($tstart) {
 2983: 			if ($tstart>$now) { $active=0; }
 2984: 		    }
 2985: 		    if ($active) { return 1; }
 2986: 		}
 2987: 	    }
 2988: 	}
 2989:     }
 2990:     return 0;
 2991: }
 2992: 
 2993: # -------------------------------------------------------- Get user privileges
 2994: 
 2995: sub rolesinit {
 2996:     my ($domain,$username,$authhost)=@_;
 2997:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2998:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2999:     my %allroles=();
 3000:     my %allgroups=();   
 3001:     my $now=time;
 3002:     my %userroles = ('user.login.time' => $now);
 3003:     my $group_privs;
 3004: 
 3005:     if ($rolesdump ne '') {
 3006:         foreach my $entry (split(/&/,$rolesdump)) {
 3007: 	  if ($entry!~/^rolesdef_/) {
 3008:             my ($area,$role)=split(/=/,$entry);
 3009: 	    $area=~s/\_\w\w$//;
 3010:             my ($trole,$tend,$tstart,$group_privs);
 3011: 	    if ($role=~/^cr/) { 
 3012: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3013: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3014: 		    ($tend,$tstart)=split('_',$trest);
 3015: 		} else {
 3016: 		    $trole=$role;
 3017: 		}
 3018:             } elsif ($role =~ m|^gr/|) {
 3019:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3020:                 ($trole,$group_privs) = split(/\//,$trole);
 3021:                 $group_privs = &unescape($group_privs);
 3022: 	    } else {
 3023: 		($trole,$tend,$tstart)=split(/_/,$role);
 3024: 	    }
 3025: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3026: 					 $username);
 3027: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3028:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3029:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3030:             if (($area ne '') && ($trole ne '')) {
 3031: 		my $spec=$trole.'.'.$area;
 3032: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3033: 		if ($trole =~ /^cr\//) {
 3034:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3035:                 } elsif ($trole eq 'gr') {
 3036:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3037: 		} else {
 3038:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3039: 		}
 3040:             }
 3041:           }
 3042:         }
 3043:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3044:         $userroles{'user.adv'}    = $adv;
 3045: 	$userroles{'user.author'} = $author;
 3046:         $env{'user.adv'}=$adv;
 3047:     }
 3048:     return \%userroles;  
 3049: }
 3050: 
 3051: sub set_arearole {
 3052:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3053: # log the associated role with the area
 3054:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3055:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3056: }
 3057: 
 3058: sub custom_roleprivs {
 3059:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3060:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3061:     my $homsvr=homeserver($rauthor,$rdomain);
 3062:     if (&hostname($homsvr) ne '') {
 3063:         my ($rdummy,$roledef)=
 3064:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3065:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3066:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3067:             if (defined($syspriv)) {
 3068:                 $$allroles{'cm./'}.=':'.$syspriv;
 3069:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3070:             }
 3071:             if ($tdomain ne '') {
 3072:                 if (defined($dompriv)) {
 3073:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3074:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3075:                 }
 3076:                 if (($trest ne '') && (defined($coursepriv))) {
 3077:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3078:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3079:                 }
 3080:             }
 3081:         }
 3082:     }
 3083: }
 3084: 
 3085: sub group_roleprivs {
 3086:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3087:     my $access = 1;
 3088:     my $now = time;
 3089:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3090:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3091:     if ($access) {
 3092:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3093:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3094:     }
 3095: }
 3096: 
 3097: sub standard_roleprivs {
 3098:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3099:     if (defined($pr{$trole.':s'})) {
 3100:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3101:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3102:     }
 3103:     if ($tdomain ne '') {
 3104:         if (defined($pr{$trole.':d'})) {
 3105:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3106:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3107:         }
 3108:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3109:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3110:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3111:         }
 3112:     }
 3113: }
 3114: 
 3115: sub set_userprivs {
 3116:     my ($userroles,$allroles,$allgroups) = @_; 
 3117:     my $author=0;
 3118:     my $adv=0;
 3119:     my %grouproles = ();
 3120:     if (keys(%{$allgroups}) > 0) {
 3121:         foreach my $role (keys %{$allroles}) {
 3122:             my ($trole,$area,$sec,$extendedarea);
 3123:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3124:                 $trole = $1;
 3125:                 $area = $2;
 3126:                 $sec = $3;
 3127:                 $extendedarea = $area.$sec;
 3128:                 if (exists($$allgroups{$area})) {
 3129:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3130:                         my $spec = $trole.'.'.$extendedarea;
 3131:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3132:                                                 $$allgroups{$area}{$group};
 3133:                     }
 3134:                 }
 3135:             }
 3136:         }
 3137:     }
 3138:     foreach my $group (keys(%grouproles)) {
 3139:         $$allroles{$group} = $grouproles{$group};
 3140:     }
 3141:     foreach my $role (keys(%{$allroles})) {
 3142:         my %thesepriv;
 3143:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3144:         foreach my $item (split(/:/,$$allroles{$role})) {
 3145:             if ($item ne '') {
 3146:                 my ($privilege,$restrictions)=split(/&/,$item);
 3147:                 if ($restrictions eq '') {
 3148:                     $thesepriv{$privilege}='F';
 3149:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3150:                     $thesepriv{$privilege}.=$restrictions;
 3151:                 }
 3152:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3153:             }
 3154:         }
 3155:         my $thesestr='';
 3156:         foreach my $priv (keys(%thesepriv)) {
 3157: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3158: 	}
 3159:         $userroles->{'user.priv.'.$role} = $thesestr;
 3160:     }
 3161:     return ($author,$adv);
 3162: }
 3163: 
 3164: # --------------------------------------------------------------- get interface
 3165: 
 3166: sub get {
 3167:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3168:    my $items='';
 3169:    foreach my $item (@$storearr) {
 3170:        $items.=&escape($item).'&';
 3171:    }
 3172:    $items=~s/\&$//;
 3173:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3174:    if (!$uname) { $uname=$env{'user.name'}; }
 3175:    my $uhome=&homeserver($uname,$udomain);
 3176: 
 3177:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3178:    my @pairs=split(/\&/,$rep);
 3179:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3180:      return @pairs;
 3181:    }
 3182:    my %returnhash=();
 3183:    my $i=0;
 3184:    foreach my $item (@$storearr) {
 3185:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3186:       $i++;
 3187:    }
 3188:    return %returnhash;
 3189: }
 3190: 
 3191: # --------------------------------------------------------------- del interface
 3192: 
 3193: sub del {
 3194:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3195:    my $items='';
 3196:    foreach my $item (@$storearr) {
 3197:        $items.=&escape($item).'&';
 3198:    }
 3199:    $items=~s/\&$//;
 3200:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3201:    if (!$uname) { $uname=$env{'user.name'}; }
 3202:    my $uhome=&homeserver($uname,$udomain);
 3203: 
 3204:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3205: }
 3206: 
 3207: # -------------------------------------------------------------- dump interface
 3208: 
 3209: sub dump {
 3210:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3211:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3212:     if (!$uname) { $uname=$env{'user.name'}; }
 3213:     my $uhome=&homeserver($uname,$udomain);
 3214:     if ($regexp) {
 3215: 	$regexp=&escape($regexp);
 3216:     } else {
 3217: 	$regexp='.';
 3218:     }
 3219:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3220:     my @pairs=split(/\&/,$rep);
 3221:     my %returnhash=();
 3222:     foreach my $item (@pairs) {
 3223: 	my ($key,$value)=split(/=/,$item,2);
 3224: 	$key = &unescape($key);
 3225: 	next if ($key =~ /^error: 2 /);
 3226: 	$returnhash{$key}=&thaw_unescape($value);
 3227:     }
 3228:     return %returnhash;
 3229: }
 3230: 
 3231: # --------------------------------------------------------- dumpstore interface
 3232: 
 3233: sub dumpstore {
 3234:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3235:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3236:    if (!$uname) { $uname=$env{'user.name'}; }
 3237:    my $uhome=&homeserver($uname,$udomain);
 3238:    if ($regexp) {
 3239:        $regexp=&escape($regexp);
 3240:    } else {
 3241:        $regexp='.';
 3242:    }
 3243:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3244:    my @pairs=split(/\&/,$rep);
 3245:    my %returnhash=();
 3246:    foreach my $item (@pairs) {
 3247:        my ($key,$value)=split(/=/,$item,2);
 3248:        next if ($key =~ /^error: 2 /);
 3249:        $returnhash{$key}=&thaw_unescape($value);
 3250:    }
 3251:    return %returnhash;
 3252: }
 3253: 
 3254: # -------------------------------------------------------------- keys interface
 3255: 
 3256: sub getkeys {
 3257:    my ($namespace,$udomain,$uname)=@_;
 3258:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3259:    if (!$uname) { $uname=$env{'user.name'}; }
 3260:    my $uhome=&homeserver($uname,$udomain);
 3261:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3262:    my @keyarray=();
 3263:    foreach my $key (split(/\&/,$rep)) {
 3264:       next if ($key =~ /^error: 2 /);
 3265:       push(@keyarray,&unescape($key));
 3266:    }
 3267:    return @keyarray;
 3268: }
 3269: 
 3270: # --------------------------------------------------------------- currentdump
 3271: sub currentdump {
 3272:    my ($courseid,$sdom,$sname)=@_;
 3273:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3274:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3275:    $sname    = $env{'user.name'}         if (! defined($sname));
 3276:    my $uhome = &homeserver($sname,$sdom);
 3277:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3278:    return if ($rep =~ /^(error:|no_such_host)/);
 3279:    #
 3280:    my %returnhash=();
 3281:    #
 3282:    if ($rep eq "unknown_cmd") { 
 3283:        # an old lond will not know currentdump
 3284:        # Do a dump and make it look like a currentdump
 3285:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3286:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3287:        my %hash = @tmp;
 3288:        @tmp=();
 3289:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3290:    } else {
 3291:        my @pairs=split(/\&/,$rep);
 3292:        foreach my $pair (@pairs) {
 3293:            my ($key,$value)=split(/=/,$pair,2);
 3294:            my ($symb,$param) = split(/:/,$key);
 3295:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3296:                                                         &thaw_unescape($value);
 3297:        }
 3298:    }
 3299:    return %returnhash;
 3300: }
 3301: 
 3302: sub convert_dump_to_currentdump{
 3303:     my %hash = %{shift()};
 3304:     my %returnhash;
 3305:     # Code ripped from lond, essentially.  The only difference
 3306:     # here is the unescaping done by lonnet::dump().  Conceivably
 3307:     # we might run in to problems with parameter names =~ /^v\./
 3308:     while (my ($key,$value) = each(%hash)) {
 3309:         my ($v,$symb,$param) = split(/:/,$key);
 3310: 	$symb  = &unescape($symb);
 3311: 	$param = &unescape($param);
 3312:         next if ($v eq 'version' || $symb eq 'keys');
 3313:         next if (exists($returnhash{$symb}) &&
 3314:                  exists($returnhash{$symb}->{$param}) &&
 3315:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3316:         $returnhash{$symb}->{$param}=$value;
 3317:         $returnhash{$symb}->{'v.'.$param}=$v;
 3318:     }
 3319:     #
 3320:     # Remove all of the keys in the hashes which keep track of
 3321:     # the version of the parameter.
 3322:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3323:         # use a foreach because we are going to delete from the hash.
 3324:         foreach my $key (keys(%$param_hash)) {
 3325:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3326:         }
 3327:     }
 3328:     return \%returnhash;
 3329: }
 3330: 
 3331: # ------------------------------------------------------ critical inc interface
 3332: 
 3333: sub cinc {
 3334:     return &inc(@_,'critical');
 3335: }
 3336: 
 3337: # --------------------------------------------------------------- inc interface
 3338: 
 3339: sub inc {
 3340:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3341:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3342:     if (!$uname) { $uname=$env{'user.name'}; }
 3343:     my $uhome=&homeserver($uname,$udomain);
 3344:     my $items='';
 3345:     if (! ref($store)) {
 3346:         # got a single value, so use that instead
 3347:         $items = &escape($store).'=&';
 3348:     } elsif (ref($store) eq 'SCALAR') {
 3349:         $items = &escape($$store).'=&';        
 3350:     } elsif (ref($store) eq 'ARRAY') {
 3351:         $items = join('=&',map {&escape($_);} @{$store});
 3352:     } elsif (ref($store) eq 'HASH') {
 3353:         while (my($key,$value) = each(%{$store})) {
 3354:             $items.= &escape($key).'='.&escape($value).'&';
 3355:         }
 3356:     }
 3357:     $items=~s/\&$//;
 3358:     if ($critical) {
 3359: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3360:     } else {
 3361: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3362:     }
 3363: }
 3364: 
 3365: # --------------------------------------------------------------- put interface
 3366: 
 3367: sub put {
 3368:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3369:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3370:    if (!$uname) { $uname=$env{'user.name'}; }
 3371:    my $uhome=&homeserver($uname,$udomain);
 3372:    my $items='';
 3373:    foreach my $item (keys(%$storehash)) {
 3374:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3375:    }
 3376:    $items=~s/\&$//;
 3377:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3378: }
 3379: 
 3380: # ------------------------------------------------------------ newput interface
 3381: 
 3382: sub newput {
 3383:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3384:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3385:    if (!$uname) { $uname=$env{'user.name'}; }
 3386:    my $uhome=&homeserver($uname,$udomain);
 3387:    my $items='';
 3388:    foreach my $key (keys(%$storehash)) {
 3389:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3390:    }
 3391:    $items=~s/\&$//;
 3392:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3393: }
 3394: 
 3395: # ---------------------------------------------------------  putstore interface
 3396: 
 3397: sub putstore {
 3398:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3399:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3400:    if (!$uname) { $uname=$env{'user.name'}; }
 3401:    my $uhome=&homeserver($uname,$udomain);
 3402:    my $items='';
 3403:    foreach my $key (keys(%$storehash)) {
 3404:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3405:    }
 3406:    $items=~s/\&$//;
 3407:    my $esc_symb=&escape($symb);
 3408:    my $esc_v=&escape($version);
 3409:    my $reply =
 3410:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3411: 	      $uhome);
 3412:    if ($reply eq 'unknown_cmd') {
 3413:        # gfall back to way things use to be done
 3414:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3415: 			    $uname);
 3416:    }
 3417:    return $reply;
 3418: }
 3419: 
 3420: sub old_putstore {
 3421:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3422:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3423:     if (!$uname) { $uname=$env{'user.name'}; }
 3424:     my $uhome=&homeserver($uname,$udomain);
 3425:     my %newstorehash;
 3426:     foreach my $item (keys(%$storehash)) {
 3427: 	my $key = $version.':'.&escape($symb).':'.$item;
 3428: 	$newstorehash{$key} = $storehash->{$item};
 3429:     }
 3430:     my $items='';
 3431:     my %allitems = ();
 3432:     foreach my $item (keys(%newstorehash)) {
 3433: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3434: 	    my $key = $1.':keys:'.$2;
 3435: 	    $allitems{$key} .= $3.':';
 3436: 	}
 3437: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3438:     }
 3439:     foreach my $item (keys(%allitems)) {
 3440: 	$allitems{$item} =~ s/\:$//;
 3441: 	$items.= $item.'='.$allitems{$item}.'&';
 3442:     }
 3443:     $items=~s/\&$//;
 3444:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3445: }
 3446: 
 3447: # ------------------------------------------------------ critical put interface
 3448: 
 3449: sub cput {
 3450:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3451:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3452:    if (!$uname) { $uname=$env{'user.name'}; }
 3453:    my $uhome=&homeserver($uname,$udomain);
 3454:    my $items='';
 3455:    foreach my $item (keys(%$storehash)) {
 3456:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3457:    }
 3458:    $items=~s/\&$//;
 3459:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3460: }
 3461: 
 3462: # -------------------------------------------------------------- eget interface
 3463: 
 3464: sub eget {
 3465:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3466:    my $items='';
 3467:    foreach my $item (@$storearr) {
 3468:        $items.=&escape($item).'&';
 3469:    }
 3470:    $items=~s/\&$//;
 3471:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3472:    if (!$uname) { $uname=$env{'user.name'}; }
 3473:    my $uhome=&homeserver($uname,$udomain);
 3474:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3475:    my @pairs=split(/\&/,$rep);
 3476:    my %returnhash=();
 3477:    my $i=0;
 3478:    foreach my $item (@$storearr) {
 3479:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3480:       $i++;
 3481:    }
 3482:    return %returnhash;
 3483: }
 3484: 
 3485: # ------------------------------------------------------------ tmpput interface
 3486: sub tmpput {
 3487:     my ($storehash,$server,$context)=@_;
 3488:     my $items='';
 3489:     foreach my $item (keys(%$storehash)) {
 3490: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3491:     }
 3492:     $items=~s/\&$//;
 3493:     if (defined($context)) {
 3494:         $items .= ':'.&escape($context);
 3495:     }
 3496:     return &reply("tmpput:$items",$server);
 3497: }
 3498: 
 3499: # ------------------------------------------------------------ tmpget interface
 3500: sub tmpget {
 3501:     my ($token,$server)=@_;
 3502:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3503:     my $rep=&reply("tmpget:$token",$server);
 3504:     my %returnhash;
 3505:     foreach my $item (split(/\&/,$rep)) {
 3506: 	my ($key,$value)=split(/=/,$item);
 3507: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3508:     }
 3509:     return %returnhash;
 3510: }
 3511: 
 3512: # ------------------------------------------------------------ tmpget interface
 3513: sub tmpdel {
 3514:     my ($token,$server)=@_;
 3515:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3516:     return &reply("tmpdel:$token",$server);
 3517: }
 3518: 
 3519: # -------------------------------------------------- portfolio access checking
 3520: 
 3521: sub portfolio_access {
 3522:     my ($requrl) = @_;
 3523:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3524:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3525:     if ($result) {
 3526:         my %setters;
 3527:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3528:             my ($startblock,$endblock) =
 3529:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3530:             if ($startblock && $endblock) {
 3531:                 return 'B';
 3532:             }
 3533:         } else {
 3534:             my ($startblock,$endblock) =
 3535:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3536:             if ($startblock && $endblock) {
 3537:                 return 'B';
 3538:             }
 3539:         }
 3540:     }
 3541:     if ($result eq 'ok') {
 3542:        return 'F';
 3543:     } elsif ($result =~ /^[^:]+:guest_/) {
 3544:        return 'A';
 3545:     }
 3546:     return '';
 3547: }
 3548: 
 3549: sub get_portfolio_access {
 3550:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3551: 
 3552:     if (!ref($access_hash)) {
 3553: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3554: 	my %access_controls = &get_access_controls($current_perms,$group,
 3555: 						   $file_name);
 3556: 	$access_hash = $access_controls{$file_name};
 3557:     }
 3558: 
 3559:     my ($public,$guest,@domains,@users,@courses,@groups);
 3560:     my $now = time;
 3561:     if (ref($access_hash) eq 'HASH') {
 3562:         foreach my $key (keys(%{$access_hash})) {
 3563:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3564:             if ($start > $now) {
 3565:                 next;
 3566:             }
 3567:             if ($end && $end<$now) {
 3568:                 next;
 3569:             }
 3570:             if ($scope eq 'public') {
 3571:                 $public = $key;
 3572:                 last;
 3573:             } elsif ($scope eq 'guest') {
 3574:                 $guest = $key;
 3575:             } elsif ($scope eq 'domains') {
 3576:                 push(@domains,$key);
 3577:             } elsif ($scope eq 'users') {
 3578:                 push(@users,$key);
 3579:             } elsif ($scope eq 'course') {
 3580:                 push(@courses,$key);
 3581:             } elsif ($scope eq 'group') {
 3582:                 push(@groups,$key);
 3583:             }
 3584:         }
 3585:         if ($public) {
 3586:             return 'ok';
 3587:         }
 3588:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3589:             if ($guest) {
 3590:                 return $guest;
 3591:             }
 3592:         } else {
 3593:             if (@domains > 0) {
 3594:                 foreach my $domkey (@domains) {
 3595:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3596:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3597:                             return 'ok';
 3598:                         }
 3599:                     }
 3600:                 }
 3601:             }
 3602:             if (@users > 0) {
 3603:                 foreach my $userkey (@users) {
 3604:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3605:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3606:                             if (ref($item) eq 'HASH') {
 3607:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3608:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3609:                                     return 'ok';
 3610:                                 }
 3611:                             }
 3612:                         }
 3613:                     } 
 3614:                 }
 3615:             }
 3616:             my %roleshash;
 3617:             my @courses_and_groups = @courses;
 3618:             push(@courses_and_groups,@groups); 
 3619:             if (@courses_and_groups > 0) {
 3620:                 my (%allgroups,%allroles); 
 3621:                 my ($start,$end,$role,$sec,$group);
 3622:                 foreach my $envkey (%env) {
 3623:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3624:                         my $cid = $2.'_'.$3; 
 3625:                         if ($1 eq 'gr') {
 3626:                             $group = $4;
 3627:                             $allgroups{$cid}{$group} = $env{$envkey};
 3628:                         } else {
 3629:                             if ($4 eq '') {
 3630:                                 $sec = 'none';
 3631:                             } else {
 3632:                                 $sec = $4;
 3633:                             }
 3634:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3635:                         }
 3636:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3637:                         my $cid = $2.'_'.$3;
 3638:                         if ($4 eq '') {
 3639:                             $sec = 'none';
 3640:                         } else {
 3641:                             $sec = $4;
 3642:                         }
 3643:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3644:                     }
 3645:                 }
 3646:                 if (keys(%allroles) == 0) {
 3647:                     return;
 3648:                 }
 3649:                 foreach my $key (@courses_and_groups) {
 3650:                     my %content = %{$$access_hash{$key}};
 3651:                     my $cnum = $content{'number'};
 3652:                     my $cdom = $content{'domain'};
 3653:                     my $cid = $cdom.'_'.$cnum;
 3654:                     if (!exists($allroles{$cid})) {
 3655:                         next;
 3656:                     }    
 3657:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3658:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3659:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3660:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3661:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3662:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3663:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3664:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3665:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3666:                                         if (grep/^all$/,@sections) {
 3667:                                             return 'ok';
 3668:                                         } else {
 3669:                                             if (grep/^$sec$/,@sections) {
 3670:                                                 return 'ok';
 3671:                                             }
 3672:                                         }
 3673:                                     }
 3674:                                 }
 3675:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3676:                                     if (grep/^none$/,@groups) {
 3677:                                         return 'ok';
 3678:                                     }
 3679:                                 } else {
 3680:                                     if (grep/^all$/,@groups) {
 3681:                                         return 'ok';
 3682:                                     } 
 3683:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3684:                                         if (grep/^$group$/,@groups) {
 3685:                                             return 'ok';
 3686:                                         }
 3687:                                     }
 3688:                                 } 
 3689:                             }
 3690:                         }
 3691:                     }
 3692:                 }
 3693:             }
 3694:             if ($guest) {
 3695:                 return $guest;
 3696:             }
 3697:         }
 3698:     }
 3699:     return;
 3700: }
 3701: 
 3702: sub course_group_datechecker {
 3703:     my ($dates,$now,$status) = @_;
 3704:     my ($start,$end) = split(/\./,$dates);
 3705:     if (!$start && !$end) {
 3706:         return 'ok';
 3707:     }
 3708:     if (grep/^active$/,@{$status}) {
 3709:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3710:             return 'ok';
 3711:         }
 3712:     }
 3713:     if (grep/^previous$/,@{$status}) {
 3714:         if ($end > $now ) {
 3715:             return 'ok';
 3716:         }
 3717:     }
 3718:     if (grep/^future$/,@{$status}) {
 3719:         if ($start > $now) {
 3720:             return 'ok';
 3721:         }
 3722:     }
 3723:     return; 
 3724: }
 3725: 
 3726: sub parse_portfolio_url {
 3727:     my ($url) = @_;
 3728: 
 3729:     my ($type,$udom,$unum,$group,$file_name);
 3730:     
 3731:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3732: 	$type = 1;
 3733:         $udom = $1;
 3734:         $unum = $2;
 3735:         $file_name = $3;
 3736:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3737: 	$type = 2;
 3738:         $udom = $1;
 3739:         $unum = $2;
 3740:         $group = $3;
 3741:         $file_name = $3.'/'.$4;
 3742:     }
 3743:     if (wantarray) {
 3744: 	return ($type,$udom,$unum,$file_name,$group);
 3745:     }
 3746:     return $type;
 3747: }
 3748: 
 3749: sub is_portfolio_url {
 3750:     my ($url) = @_;
 3751:     return scalar(&parse_portfolio_url($url));
 3752: }
 3753: 
 3754: sub is_portfolio_file {
 3755:     my ($file) = @_;
 3756:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3757:         return 1;
 3758:     }
 3759:     return;
 3760: }
 3761: 
 3762: 
 3763: # ---------------------------------------------- Custom access rule evaluation
 3764: 
 3765: sub customaccess {
 3766:     my ($priv,$uri)=@_;
 3767:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3768:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3769:     $udom = &LONCAPA::clean_domain($udom);
 3770:     $ucrs = &LONCAPA::clean_username($ucrs);
 3771:     my $access=0;
 3772:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3773: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3774:         if ($role) {
 3775: 	   if ($role ne $urole) { next; }
 3776:         }
 3777:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3778:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3779:             if ($tdom) {
 3780: 		if ($tdom ne $udom) { next; }
 3781:             }
 3782:             if ($tcrs) {
 3783: 		if ($tcrs ne $ucrs) { next; }
 3784:             }
 3785:             if ($tsec) {
 3786: 		if ($tsec ne $usec) { next; }
 3787:             }
 3788:             $access=($effect eq 'allow');
 3789:             last;
 3790:         }
 3791: 	if ($realm eq '' && $role eq '') {
 3792:             $access=($effect eq 'allow');
 3793: 	}
 3794:     }
 3795:     return $access;
 3796: }
 3797: 
 3798: # ------------------------------------------------- Check for a user privilege
 3799: 
 3800: sub allowed {
 3801:     my ($priv,$uri,$symb,$role)=@_;
 3802:     my $ver_orguri=$uri;
 3803:     $uri=&deversion($uri);
 3804:     my $orguri=$uri;
 3805:     $uri=&declutter($uri);
 3806: 
 3807:     if ($priv eq 'evb') {
 3808: # Evade communication block restrictions for specified role in a course
 3809:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3810:             return $1;
 3811:         } else {
 3812:             return;
 3813:         }
 3814:     }
 3815: 
 3816:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3817: # Free bre access to adm and meta resources
 3818:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3819: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3820: 	&& ($priv eq 'bre')) {
 3821: 	return 'F';
 3822:     }
 3823: 
 3824: # Free bre access to user's own portfolio contents
 3825:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3826:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3827: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3828:         my %setters;
 3829:         my ($startblock,$endblock) = 
 3830:             &Apache::loncommon::blockcheck(\%setters,'port');
 3831:         if ($startblock && $endblock) {
 3832:             return 'B';
 3833:         } else {
 3834:             return 'F';
 3835:         }
 3836:     }
 3837: 
 3838: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3839:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3840:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3841:         if (exists($env{'request.course.id'})) {
 3842:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3843:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3844:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3845:                 my $courseprivid=$env{'request.course.id'};
 3846:                 $courseprivid=~s/\_/\//;
 3847:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3848:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3849:                     return $1; 
 3850:                 } else {
 3851:                     if ($env{'request.course.sec'}) {
 3852:                         $courseprivid.='/'.$env{'request.course.sec'};
 3853:                     }
 3854:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3855:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3856:                         return $2;
 3857:                     }
 3858:                 }
 3859:             }
 3860:         }
 3861:     }
 3862: 
 3863: # Free bre to public access
 3864: 
 3865:     if ($priv eq 'bre') {
 3866:         my $copyright=&metadata($uri,'copyright');
 3867: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3868:            return 'F'; 
 3869:         }
 3870:         if ($copyright eq 'priv') {
 3871:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3872: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3873: 		return '';
 3874:             }
 3875:         }
 3876:         if ($copyright eq 'domain') {
 3877:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3878: 	    unless (($env{'user.domain'} eq $1) ||
 3879:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3880: 		return '';
 3881:             }
 3882:         }
 3883:         if ($env{'request.role'}=~ /li\.\//) {
 3884:             # Library role, so allow browsing of resources in this domain.
 3885:             return 'F';
 3886:         }
 3887:         if ($copyright eq 'custom') {
 3888: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3889:         }
 3890:     }
 3891:     # Domain coordinator is trying to create a course
 3892:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3893:         # uri is the requested domain in this case.
 3894:         # comparison to 'request.role.domain' shows if the user has selected
 3895:         # a role of dc for the domain in question.
 3896:         return 'F' if ($uri eq $env{'request.role.domain'});
 3897:     }
 3898: 
 3899:     my $thisallowed='';
 3900:     my $statecond=0;
 3901:     my $courseprivid='';
 3902: 
 3903: # Course
 3904: 
 3905:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3906:        $thisallowed.=$1;
 3907:     }
 3908: 
 3909: # Domain
 3910: 
 3911:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3912:        =~/\Q$priv\E\&([^\:]*)/) {
 3913:        $thisallowed.=$1;
 3914:     }
 3915: 
 3916: # Course: uri itself is a course
 3917:     my $courseuri=$uri;
 3918:     $courseuri=~s/\_(\d)/\/$1/;
 3919:     $courseuri=~s/^([^\/])/\/$1/;
 3920: 
 3921:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3922:        =~/\Q$priv\E\&([^\:]*)/) {
 3923:        $thisallowed.=$1;
 3924:     }
 3925: 
 3926: # URI is an uploaded document for this course, default permissions don't matter
 3927: # not allowing 'edit' access (editupload) to uploaded course docs
 3928:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3929: 	$thisallowed='';
 3930:         my ($match)=&is_on_map($uri);
 3931:         if ($match) {
 3932:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3933:                   =~/\Q$priv\E\&([^\:]*)/) {
 3934:                 $thisallowed.=$1;
 3935:             }
 3936:         } else {
 3937:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3938:             if ($refuri) {
 3939:                 if ($refuri =~ m|^/adm/|) {
 3940:                     $thisallowed='F';
 3941:                 } else {
 3942:                     $refuri=&declutter($refuri);
 3943:                     my ($match) = &is_on_map($refuri);
 3944:                     if ($match) {
 3945:                         $thisallowed='F';
 3946:                     }
 3947:                 }
 3948:             }
 3949:         }
 3950:     }
 3951: 
 3952:     if ($priv eq 'bre'
 3953: 	&& $thisallowed ne 'F' 
 3954: 	&& $thisallowed ne '2'
 3955: 	&& &is_portfolio_url($uri)) {
 3956: 	$thisallowed = &portfolio_access($uri);
 3957:     }
 3958:     
 3959: # Full access at system, domain or course-wide level? Exit.
 3960: 
 3961:     if ($thisallowed=~/F/) {
 3962: 	return 'F';
 3963:     }
 3964: 
 3965: # If this is generating or modifying users, exit with special codes
 3966: 
 3967:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3968: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3969: 	    my ($audom,$auname)=split('/',$uri);
 3970: # no author name given, so this just checks on the general right to make a co-author in this domain
 3971: 	    unless ($auname) { return $thisallowed; }
 3972: # an author name is given, so we are about to actually make a co-author for a certain account
 3973: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3974: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3975: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3976: 	}
 3977: 	return $thisallowed;
 3978:     }
 3979: #
 3980: # Gathered so far: system, domain and course wide privileges
 3981: #
 3982: # Course: See if uri or referer is an individual resource that is part of 
 3983: # the course
 3984: 
 3985:     if ($env{'request.course.id'}) {
 3986: 
 3987:        $courseprivid=$env{'request.course.id'};
 3988:        if ($env{'request.course.sec'}) {
 3989:           $courseprivid.='/'.$env{'request.course.sec'};
 3990:        }
 3991:        $courseprivid=~s/\_/\//;
 3992:        my $checkreferer=1;
 3993:        my ($match,$cond)=&is_on_map($uri);
 3994:        if ($match) {
 3995:            $statecond=$cond;
 3996:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3997:                =~/\Q$priv\E\&([^\:]*)/) {
 3998:                $thisallowed.=$1;
 3999:                $checkreferer=0;
 4000:            }
 4001:        }
 4002:        
 4003:        if ($checkreferer) {
 4004: 	  my $refuri=$env{'httpref.'.$orguri};
 4005:             unless ($refuri) {
 4006:                 foreach my $key (keys(%env)) {
 4007: 		    if ($key=~/^httpref\..*\*/) {
 4008: 			my $pattern=$key;
 4009:                         $pattern=~s/^httpref\.\/res\///;
 4010:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4011:                         $pattern=~s/\//\\\//g;
 4012:                         if ($orguri=~/$pattern/) {
 4013: 			    $refuri=$env{$key};
 4014:                         }
 4015:                     }
 4016:                 }
 4017:             }
 4018: 
 4019:          if ($refuri) { 
 4020: 	  $refuri=&declutter($refuri);
 4021:           my ($match,$cond)=&is_on_map($refuri);
 4022:             if ($match) {
 4023:               my $refstatecond=$cond;
 4024:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4025:                   =~/\Q$priv\E\&([^\:]*)/) {
 4026:                   $thisallowed.=$1;
 4027:                   $uri=$refuri;
 4028:                   $statecond=$refstatecond;
 4029:               }
 4030:           }
 4031:         }
 4032:        }
 4033:    }
 4034: 
 4035: #
 4036: # Gathered now: all privileges that could apply, and condition number
 4037: # 
 4038: #
 4039: # Full or no access?
 4040: #
 4041: 
 4042:     if ($thisallowed=~/F/) {
 4043: 	return 'F';
 4044:     }
 4045: 
 4046:     unless ($thisallowed) {
 4047:         return '';
 4048:     }
 4049: 
 4050: # Restrictions exist, deal with them
 4051: #
 4052: #   C:according to course preferences
 4053: #   R:according to resource settings
 4054: #   L:unless locked
 4055: #   X:according to user session state
 4056: #
 4057: 
 4058: # Possibly locked functionality, check all courses
 4059: # Locks might take effect only after 10 minutes cache expiration for other
 4060: # courses, and 2 minutes for current course
 4061: 
 4062:     my $envkey;
 4063:     if ($thisallowed=~/L/) {
 4064:         foreach $envkey (keys %env) {
 4065:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4066:                my $courseid=$2;
 4067:                my $roleid=$1.'.'.$2;
 4068:                $courseid=~s/^\///;
 4069:                my $expiretime=600;
 4070:                if ($env{'request.role'} eq $roleid) {
 4071: 		  $expiretime=120;
 4072:                }
 4073: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4074:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4075:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4076: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4077:                }
 4078:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4079:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4080: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4081:                        &log($env{'user.domain'},$env{'user.name'},
 4082:                             $env{'user.home'},
 4083:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4084:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4085:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4086: 		       return '';
 4087:                    }
 4088:                }
 4089:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4090:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4091: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4092:                        &log($env{'user.domain'},$env{'user.name'},
 4093:                             $env{'user.home'},
 4094:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4095:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4096:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4097: 		       return '';
 4098:                    }
 4099:                }
 4100: 	   }
 4101:        }
 4102:     }
 4103:    
 4104: #
 4105: # Rest of the restrictions depend on selected course
 4106: #
 4107: 
 4108:     unless ($env{'request.course.id'}) {
 4109: 	if ($thisallowed eq 'A') {
 4110: 	    return 'A';
 4111:         } elsif ($thisallowed eq 'B') {
 4112:             return 'B';
 4113: 	} else {
 4114: 	    return '1';
 4115: 	}
 4116:     }
 4117: 
 4118: #
 4119: # Now user is definitely in a course
 4120: #
 4121: 
 4122: 
 4123: # Course preferences
 4124: 
 4125:    if ($thisallowed=~/C/) {
 4126:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4127:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4128:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4129: 	   =~/\Q$rolecode\E/) {
 4130: 	   if ($priv ne 'pch') { 
 4131: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4132: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4133: 			$env{'request.course.id'});
 4134: 	   }
 4135:            return '';
 4136:        }
 4137: 
 4138:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4139: 	   =~/\Q$unamedom\E/) {
 4140: 	   if ($priv ne 'pch') { 
 4141: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4142: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4143: 			$env{'request.course.id'});
 4144: 	   }
 4145:            return '';
 4146:        }
 4147:    }
 4148: 
 4149: # Resource preferences
 4150: 
 4151:    if ($thisallowed=~/R/) {
 4152:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4153:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4154: 	   if ($priv ne 'pch') { 
 4155: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4156: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4157: 	   }
 4158: 	   return '';
 4159:        }
 4160:    }
 4161: 
 4162: # Restricted by state or randomout?
 4163: 
 4164:    if ($thisallowed=~/X/) {
 4165:       if ($env{'acc.randomout'}) {
 4166: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4167:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4168:             return ''; 
 4169:          }
 4170:       }
 4171:       if (&condval($statecond)) {
 4172: 	 return '2';
 4173:       } else {
 4174:          return '';
 4175:       }
 4176:    }
 4177: 
 4178:     if ($thisallowed eq 'A') {
 4179: 	return 'A';
 4180:     } elsif ($thisallowed eq 'B') {
 4181:         return 'B';
 4182:     }
 4183:    return 'F';
 4184: }
 4185: 
 4186: sub split_uri_for_cond {
 4187:     my $uri=&deversion(&declutter(shift));
 4188:     my @uriparts=split(/\//,$uri);
 4189:     my $filename=pop(@uriparts);
 4190:     my $pathname=join('/',@uriparts);
 4191:     return ($pathname,$filename);
 4192: }
 4193: # --------------------------------------------------- Is a resource on the map?
 4194: 
 4195: sub is_on_map {
 4196:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4197:     #Trying to find the conditional for the file
 4198:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4199: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4200:     if ($match) {
 4201: 	return (1,$1);
 4202:     } else {
 4203: 	return (0,0);
 4204:     }
 4205: }
 4206: 
 4207: # --------------------------------------------------------- Get symb from alias
 4208: 
 4209: sub get_symb_from_alias {
 4210:     my $symb=shift;
 4211:     my ($map,$resid,$url)=&decode_symb($symb);
 4212: # Already is a symb
 4213:     if ($url) { return $symb; }
 4214: # Must be an alias
 4215:     my $aliassymb='';
 4216:     my %bighash;
 4217:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4218:                             &GDBM_READER(),0640)) {
 4219:         my $rid=$bighash{'mapalias_'.$symb};
 4220: 	if ($rid) {
 4221: 	    my ($mapid,$resid)=split(/\./,$rid);
 4222: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4223: 				    $resid,$bighash{'src_'.$rid});
 4224: 	}
 4225:         untie %bighash;
 4226:     }
 4227:     return $aliassymb;
 4228: }
 4229: 
 4230: # ----------------------------------------------------------------- Define Role
 4231: 
 4232: sub definerole {
 4233:   if (allowed('mcr','/')) {
 4234:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4235:     foreach my $role (split(':',$sysrole)) {
 4236: 	my ($crole,$cqual)=split(/\&/,$role);
 4237:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4238:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4239: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4240:                return "refused:s:$crole&$cqual"; 
 4241:             }
 4242:         }
 4243:     }
 4244:     foreach my $role (split(':',$domrole)) {
 4245: 	my ($crole,$cqual)=split(/\&/,$role);
 4246:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4247:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4248: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4249:                return "refused:d:$crole&$cqual"; 
 4250:             }
 4251:         }
 4252:     }
 4253:     foreach my $role (split(':',$courole)) {
 4254: 	my ($crole,$cqual)=split(/\&/,$role);
 4255:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4256:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4257: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4258:                return "refused:c:$crole&$cqual"; 
 4259:             }
 4260:         }
 4261:     }
 4262:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4263:                 "$env{'user.domain'}:$env{'user.name'}:".
 4264: 	        "rolesdef_$rolename=".
 4265:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4266:     return reply($command,$env{'user.home'});
 4267:   } else {
 4268:     return 'refused';
 4269:   }
 4270: }
 4271: 
 4272: # ---------------- Make a metadata query against the network of library servers
 4273: 
 4274: sub metadata_query {
 4275:     my ($query,$custom,$customshow,$server_array)=@_;
 4276:     my %rhash;
 4277:     my %libserv = &all_library();
 4278:     my @server_list = (defined($server_array) ? @$server_array
 4279:                                               : keys(%libserv) );
 4280:     for my $server (@server_list) {
 4281: 	unless ($custom or $customshow) {
 4282: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4283: 	    $rhash{$server}=$reply;
 4284: 	}
 4285: 	else {
 4286: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4287: 			     &escape($custom).':'.&escape($customshow),
 4288: 			     $server);
 4289: 	    $rhash{$server}=$reply;
 4290: 	}
 4291:     }
 4292:     return \%rhash;
 4293: }
 4294: 
 4295: # ----------------------------------------- Send log queries and wait for reply
 4296: 
 4297: sub log_query {
 4298:     my ($uname,$udom,$query,%filters)=@_;
 4299:     my $uhome=&homeserver($uname,$udom);
 4300:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4301:     my $uhost=&hostname($uhome);
 4302:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4303:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4304:                        $uhome);
 4305:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4306:     return get_query_reply($queryid);
 4307: }
 4308: 
 4309: # -------------------------- Update MySQL table for portfolio file
 4310: 
 4311: sub update_portfolio_table {
 4312:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4313:     my $homeserver = &homeserver($uname,$udom);
 4314:     my $queryid=
 4315:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4316:                ':'.&escape($file_name).':'.$action,$homeserver);
 4317:     my $reply = &get_query_reply($queryid);
 4318:     return $reply;
 4319: }
 4320: 
 4321: # ------- Request retrieval of institutional classlists for course(s)
 4322: 
 4323: sub fetch_enrollment_query {
 4324:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4325:     my $homeserver;
 4326:     my $maxtries = 1;
 4327:     if ($context eq 'automated') {
 4328:         $homeserver = $perlvar{'lonHostID'};
 4329:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4330:     } else {
 4331:         $homeserver = &homeserver($cnum,$dom);
 4332:     }
 4333:     my $host=&hostname($homeserver);
 4334:     my $cmd = '';
 4335:     foreach my $affiliate (keys %{$affiliatesref}) {
 4336:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4337:     }
 4338:     $cmd =~ s/%%$//;
 4339:     $cmd = &escape($cmd);
 4340:     my $query = 'fetchenrollment';
 4341:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4342:     unless ($queryid=~/^\Q$host\E\_/) { 
 4343:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4344:         return 'error: '.$queryid;
 4345:     }
 4346:     my $reply = &get_query_reply($queryid);
 4347:     my $tries = 1;
 4348:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4349:         $reply = &get_query_reply($queryid);
 4350:         $tries ++;
 4351:     }
 4352:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4353:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4354:     } else {
 4355:         my @responses = split/:/,$reply;
 4356:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4357:             foreach my $line (@responses) {
 4358:                 my ($key,$value) = split(/=/,$line,2);
 4359:                 $$replyref{$key} = $value;
 4360:             }
 4361:         } else {
 4362:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4363:             foreach my $line (@responses) {
 4364:                 my ($key,$value) = split(/=/,$line);
 4365:                 $$replyref{$key} = $value;
 4366:                 if ($value > 0) {
 4367:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4368:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4369:                         my $destname = $pathname.'/'.$filename;
 4370:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4371:                         if ($xml_classlist =~ /^error/) {
 4372:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4373:                         } else {
 4374:                             if ( open(FILE,">$destname") ) {
 4375:                                 print FILE &unescape($xml_classlist);
 4376:                                 close(FILE);
 4377:                             } else {
 4378:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4379:                             }
 4380:                         }
 4381:                     }
 4382:                 }
 4383:             }
 4384:         }
 4385:         return 'ok';
 4386:     }
 4387:     return 'error';
 4388: }
 4389: 
 4390: sub get_query_reply {
 4391:     my $queryid=shift;
 4392:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4393:     my $reply='';
 4394:     for (1..100) {
 4395: 	sleep 2;
 4396:         if (-e $replyfile.'.end') {
 4397: 	    if (open(my $fh,$replyfile)) {
 4398:                $reply.=<$fh>;
 4399:                close($fh);
 4400: 	   } else { return 'error: reply_file_error'; }
 4401:            return &unescape($reply);
 4402: 	}
 4403:     }
 4404:     return 'timeout:'.$queryid;
 4405: }
 4406: 
 4407: sub courselog_query {
 4408: #
 4409: # possible filters:
 4410: # url: url or symb
 4411: # username
 4412: # domain
 4413: # action: view, submit, grade
 4414: # start: timestamp
 4415: # end: timestamp
 4416: #
 4417:     my (%filters)=@_;
 4418:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4419:     if ($filters{'url'}) {
 4420: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4421:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4422:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4423:     }
 4424:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4425:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4426:     return &log_query($cname,$cdom,'courselog',%filters);
 4427: }
 4428: 
 4429: sub userlog_query {
 4430: #
 4431: # possible filters:
 4432: # action: log check role
 4433: # start: timestamp
 4434: # end: timestamp
 4435: #
 4436:     my ($uname,$udom,%filters)=@_;
 4437:     return &log_query($uname,$udom,'userlog',%filters);
 4438: }
 4439: 
 4440: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4441: 
 4442: sub auto_run {
 4443:     my ($cnum,$cdom) = @_;
 4444:     my $homeserver = &homeserver($cnum,$cdom);
 4445:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4446:     return $response;
 4447: }
 4448: 
 4449: sub auto_get_sections {
 4450:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4451:     my $homeserver = &homeserver($cnum,$cdom);
 4452:     my @secs = ();
 4453:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4454:     unless ($response eq 'refused') {
 4455:         @secs = split/:/,$response;
 4456:     }
 4457:     return @secs;
 4458: }
 4459: 
 4460: sub auto_new_course {
 4461:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4462:     my $homeserver = &homeserver($cnum,$cdom);
 4463:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4464:     return $response;
 4465: }
 4466: 
 4467: sub auto_validate_courseID {
 4468:     my ($cnum,$cdom,$inst_course_id) = @_;
 4469:     my $homeserver = &homeserver($cnum,$cdom);
 4470:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4471:     return $response;
 4472: }
 4473: 
 4474: sub auto_create_password {
 4475:     my ($cnum,$cdom,$authparam) = @_;
 4476:     my $homeserver = &homeserver($cnum,$cdom); 
 4477:     my $create_passwd = 0;
 4478:     my $authchk = '';
 4479:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4480:     if ($response eq 'refused') {
 4481:         $authchk = 'refused';
 4482:     } else {
 4483:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4484:     }
 4485:     return ($authparam,$create_passwd,$authchk);
 4486: }
 4487: 
 4488: sub auto_photo_permission {
 4489:     my ($cnum,$cdom,$students) = @_;
 4490:     my $homeserver = &homeserver($cnum,$cdom);
 4491:     my ($outcome,$perm_reqd,$conditions) = 
 4492: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4493:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4494: 	return (undef,undef);
 4495:     }
 4496:     return ($outcome,$perm_reqd,$conditions);
 4497: }
 4498: 
 4499: sub auto_checkphotos {
 4500:     my ($uname,$udom,$pid) = @_;
 4501:     my $homeserver = &homeserver($uname,$udom);
 4502:     my ($result,$resulttype);
 4503:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4504: 				   &escape($uname).':'.&escape($pid),
 4505: 				   $homeserver));
 4506:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4507: 	return (undef,undef);
 4508:     }
 4509:     if ($outcome) {
 4510:         ($result,$resulttype) = split(/:/,$outcome);
 4511:     } 
 4512:     return ($result,$resulttype);
 4513: }
 4514: 
 4515: sub auto_photochoice {
 4516:     my ($cnum,$cdom) = @_;
 4517:     my $homeserver = &homeserver($cnum,$cdom);
 4518:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4519: 						       &escape($cdom),
 4520: 						       $homeserver)));
 4521:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4522: 	return (undef,undef);
 4523:     }
 4524:     return ($update,$comment);
 4525: }
 4526: 
 4527: sub auto_photoupdate {
 4528:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4529:     my $homeserver = &homeserver($cnum,$dom);
 4530:     my $host=&hostname($homeserver);
 4531:     my $cmd = '';
 4532:     my $maxtries = 1;
 4533:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4534:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4535:     }
 4536:     $cmd =~ s/%%$//;
 4537:     $cmd = &escape($cmd);
 4538:     my $query = 'institutionalphotos';
 4539:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4540:     unless ($queryid=~/^\Q$host\E\_/) {
 4541:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4542:         return 'error: '.$queryid;
 4543:     }
 4544:     my $reply = &get_query_reply($queryid);
 4545:     my $tries = 1;
 4546:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4547:         $reply = &get_query_reply($queryid);
 4548:         $tries ++;
 4549:     }
 4550:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4551:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4552:     } else {
 4553:         my @responses = split(/:/,$reply);
 4554:         my $outcome = shift(@responses); 
 4555:         foreach my $item (@responses) {
 4556:             my ($key,$value) = split(/=/,$item);
 4557:             $$photo{$key} = $value;
 4558:         }
 4559:         return $outcome;
 4560:     }
 4561:     return 'error';
 4562: }
 4563: 
 4564: sub auto_instcode_format {
 4565:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4566: 	$cat_order) = @_;
 4567:     my $courses = '';
 4568:     my @homeservers;
 4569:     if ($caller eq 'global') {
 4570: 	my %servers = &get_servers($codedom,'library');
 4571: 	foreach my $tryserver (keys(%servers)) {
 4572: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4573: 		push(@homeservers,$tryserver);
 4574: 	    }
 4575:         }
 4576:     } else {
 4577:         push(@homeservers,&homeserver($caller,$codedom));
 4578:     }
 4579:     foreach my $code (keys(%{$instcodes})) {
 4580:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4581:     }
 4582:     chop($courses);
 4583:     my $ok_response = 0;
 4584:     my $response;
 4585:     while (@homeservers > 0 && $ok_response == 0) {
 4586:         my $server = shift(@homeservers); 
 4587:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4588:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4589:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4590: 		split/:/,$response;
 4591:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4592:             push(@{$codetitles},&str2array($codetitles_str));
 4593:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4594:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4595:             $ok_response = 1;
 4596:         }
 4597:     }
 4598:     if ($ok_response) {
 4599:         return 'ok';
 4600:     } else {
 4601:         return $response;
 4602:     }
 4603: }
 4604: 
 4605: sub auto_instcode_defaults {
 4606:     my ($domain,$returnhash,$code_order) = @_;
 4607:     my @homeservers;
 4608: 
 4609:     my %servers = &get_servers($domain,'library');
 4610:     foreach my $tryserver (keys(%servers)) {
 4611: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4612: 	    push(@homeservers,$tryserver);
 4613: 	}
 4614:     }
 4615: 
 4616:     my $response;
 4617:     foreach my $server (@homeservers) {
 4618:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4619:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4620: 	
 4621: 	foreach my $pair (split(/\&/,$response)) {
 4622: 	    my ($name,$value)=split(/\=/,$pair);
 4623: 	    if ($name eq 'code_order') {
 4624: 		@{$code_order} = split(/\&/,&unescape($value));
 4625: 	    } else {
 4626: 		$returnhash->{&unescape($name)}=&unescape($value);
 4627: 	    }
 4628: 	}
 4629: 	return 'ok';
 4630:     }
 4631: 
 4632:     return $response;
 4633: } 
 4634: 
 4635: sub auto_validate_class_sec {
 4636:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4637:     my $homeserver = &homeserver($cnum,$cdom);
 4638:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4639:                         &escape($owner).':'.$cdom,$homeserver);
 4640:     return $response;
 4641: }
 4642: 
 4643: # ------------------------------------------------------- Course Group routines
 4644: 
 4645: sub get_coursegroups {
 4646:     my ($cdom,$cnum,$group,$namespace) = @_;
 4647:     return(&dump($namespace,$cdom,$cnum,$group));
 4648: }
 4649: 
 4650: sub modify_coursegroup {
 4651:     my ($cdom,$cnum,$groupsettings) = @_;
 4652:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4653: }
 4654: 
 4655: sub toggle_coursegroup_status {
 4656:     my ($cdom,$cnum,$group,$action) = @_;
 4657:     my ($from_namespace,$to_namespace);
 4658:     if ($action eq 'delete') {
 4659:         $from_namespace = 'coursegroups';
 4660:         $to_namespace = 'deleted_groups';
 4661:     } else {
 4662:         $from_namespace = 'deleted_groups';
 4663:         $to_namespace = 'coursegroups';
 4664:     }
 4665:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4666:     if (my $tmp = &error(%curr_group)) {
 4667:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4668:         return ('read error',$tmp);
 4669:     } else {
 4670:         my %savedsettings = %curr_group; 
 4671:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4672:         my $deloutcome;
 4673:         if ($result eq 'ok') {
 4674:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4675:         } else {
 4676:             return ('write error',$result);
 4677:         }
 4678:         if ($deloutcome eq 'ok') {
 4679:             return 'ok';
 4680:         } else {
 4681:             return ('delete error',$deloutcome);
 4682:         }
 4683:     }
 4684: }
 4685: 
 4686: sub modify_group_roles {
 4687:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4688:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4689:     my $role = 'gr/'.&escape($userprivs);
 4690:     my ($uname,$udom) = split(/:/,$user);
 4691:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4692:     if ($result eq 'ok') {
 4693:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4694:     }
 4695:     return $result;
 4696: }
 4697: 
 4698: sub modify_coursegroup_membership {
 4699:     my ($cdom,$cnum,$membership) = @_;
 4700:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4701:     return $result;
 4702: }
 4703: 
 4704: sub get_active_groups {
 4705:     my ($udom,$uname,$cdom,$cnum) = @_;
 4706:     my $now = time;
 4707:     my %groups = ();
 4708:     foreach my $key (keys(%env)) {
 4709:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4710:             my ($start,$end) = split(/\./,$env{$key});
 4711:             if (($end!=0) && ($end<$now)) { next; }
 4712:             if (($start!=0) && ($start>$now)) { next; }
 4713:             if ($1 eq $cdom && $2 eq $cnum) {
 4714:                 $groups{$3} = $env{$key} ;
 4715:             }
 4716:         }
 4717:     }
 4718:     return %groups;
 4719: }
 4720: 
 4721: sub get_group_membership {
 4722:     my ($cdom,$cnum,$group) = @_;
 4723:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4724: }
 4725: 
 4726: sub get_users_groups {
 4727:     my ($udom,$uname,$courseid) = @_;
 4728:     my @usersgroups;
 4729:     my $cachetime=1800;
 4730: 
 4731:     my $hashid="$udom:$uname:$courseid";
 4732:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4733:     if (defined($cached)) {
 4734:         @usersgroups = split(/:/,$grouplist);
 4735:     } else {  
 4736:         $grouplist = '';
 4737:         my $courseurl = &courseid_to_courseurl($courseid);
 4738:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4739:         my $access_end = $env{'course.'.$courseid.
 4740:                               '.default_enrollment_end_date'};
 4741:         my $now = time;
 4742:         foreach my $key (keys(%roleshash)) {
 4743:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4744:                 my $group = $1;
 4745:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4746:                     my $start = $2;
 4747:                     my $end = $1;
 4748:                     if ($start == -1) { next; } # deleted from group
 4749:                     if (($start!=0) && ($start>$now)) { next; }
 4750:                     if (($end!=0) && ($end<$now)) {
 4751:                         if ($access_end && $access_end < $now) {
 4752:                             if ($access_end - $end < 86400) {
 4753:                                 push(@usersgroups,$group);
 4754:                             }
 4755:                         }
 4756:                         next;
 4757:                     }
 4758:                     push(@usersgroups,$group);
 4759:                 }
 4760:             }
 4761:         }
 4762:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4763:         $grouplist = join(':',@usersgroups);
 4764:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4765:     }
 4766:     return @usersgroups;
 4767: }
 4768: 
 4769: sub devalidate_getgroups_cache {
 4770:     my ($udom,$uname,$cdom,$cnum)=@_;
 4771:     my $courseid = $cdom.'_'.$cnum;
 4772: 
 4773:     my $hashid="$udom:$uname:$courseid";
 4774:     &devalidate_cache_new('getgroups',$hashid);
 4775: }
 4776: 
 4777: # ------------------------------------------------------------------ Plain Text
 4778: 
 4779: sub plaintext {
 4780:     my ($short,$type,$cid) = @_;
 4781:     if ($short =~ /^cr/) {
 4782: 	return (split('/',$short))[-1];
 4783:     }
 4784:     if (!defined($cid)) {
 4785:         $cid = $env{'request.course.id'};
 4786:     }
 4787:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4788:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4789:                                           '.plaintext'});
 4790:     }
 4791:     my %rolenames = (
 4792:                       Course => 'std',
 4793:                       Group => 'alt1',
 4794:                     );
 4795:     if (defined($type) && 
 4796:          defined($rolenames{$type}) && 
 4797:          defined($prp{$short}{$rolenames{$type}})) {
 4798:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4799:     } else {
 4800:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4801:     }
 4802: }
 4803: 
 4804: # ----------------------------------------------------------------- Assign Role
 4805: 
 4806: sub assignrole {
 4807:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4808:     my $mrole;
 4809:     if ($role =~ /^cr\//) {
 4810:         my $cwosec=$url;
 4811:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4812: 	unless (&allowed('ccr',$cwosec)) {
 4813:            &logthis('Refused custom assignrole: '.
 4814:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4815: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4816:            return 'refused'; 
 4817:         }
 4818:         $mrole='cr';
 4819:     } elsif ($role =~ /^gr\//) {
 4820:         my $cwogrp=$url;
 4821:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4822:         unless (&allowed('mdg',$cwogrp)) {
 4823:             &logthis('Refused group assignrole: '.
 4824:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4825:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4826:             return 'refused';
 4827:         }
 4828:         $mrole='gr';
 4829:     } else {
 4830:         my $cwosec=$url;
 4831:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4832:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4833:            &logthis('Refused assignrole: '.
 4834:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4835: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4836:            return 'refused'; 
 4837:         }
 4838:         $mrole=$role;
 4839:     }
 4840:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4841:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4842:     if ($end) { $command.='_'.$end; }
 4843:     if ($start) {
 4844: 	if ($end) { 
 4845:            $command.='_'.$start; 
 4846:         } else {
 4847:            $command.='_0_'.$start;
 4848:         }
 4849:     }
 4850:     my $origstart = $start;
 4851:     my $origend = $end;
 4852: # actually delete
 4853:     if ($deleteflag) {
 4854: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4855: # modify command to delete the role
 4856:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4857:                 "$udom:$uname:$url".'_'."$mrole";
 4858: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4859: # set start and finish to negative values for userrolelog
 4860:            $start=-1;
 4861:            $end=-1;
 4862:         }
 4863:     }
 4864: # send command
 4865:     my $answer=&reply($command,&homeserver($uname,$udom));
 4866: # log new user role if status is ok
 4867:     if ($answer eq 'ok') {
 4868: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4869: # for course roles, perform group memberships changes triggered by role change.
 4870:         unless ($role =~ /^gr/) {
 4871:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4872:                                              $origstart);
 4873:         }
 4874:     }
 4875:     return $answer;
 4876: }
 4877: 
 4878: # -------------------------------------------------- Modify user authentication
 4879: # Overrides without validation
 4880: 
 4881: sub modifyuserauth {
 4882:     my ($udom,$uname,$umode,$upass)=@_;
 4883:     my $uhome=&homeserver($uname,$udom);
 4884:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4885:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4886:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4887:              ' in domain '.$env{'request.role.domain'});  
 4888:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4889: 		     &escape($upass),$uhome);
 4890:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4891:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4892:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4893:     &log($udom,,$uname,$uhome,
 4894:         'Authentication changed by '.$env{'user.domain'}.', '.
 4895:                                      $env{'user.name'}.', '.$umode.
 4896:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4897:     unless ($reply eq 'ok') {
 4898:         &logthis('Authentication mode error: '.$reply);
 4899: 	return 'error: '.$reply;
 4900:     }   
 4901:     return 'ok';
 4902: }
 4903: 
 4904: # --------------------------------------------------------------- Modify a user
 4905: 
 4906: sub modifyuser {
 4907:     my ($udom,    $uname, $uid,
 4908:         $umode,   $upass, $first,
 4909:         $middle,  $last,  $gene,
 4910:         $forceid, $desiredhome, $email)=@_;
 4911:     $udom= &LONCAPA::clean_domain($udom);
 4912:     $uname=&LONCAPA::clean_username($uname);
 4913:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4914:              $umode.', '.$first.', '.$middle.', '.
 4915: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4916:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4917:                                      ' desiredhome not specified'). 
 4918:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4919:              ' in domain '.$env{'request.role.domain'});
 4920:     my $uhome=&homeserver($uname,$udom,'true');
 4921: # ----------------------------------------------------------------- Create User
 4922:     if (($uhome eq 'no_host') && 
 4923: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4924:         my $unhome='';
 4925:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4926:             $unhome = $desiredhome;
 4927: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4928: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4929:         } else { # load balancing routine for determining $unhome
 4930:             my $loadm=10000000;
 4931: 	    my %servers = &get_servers($udom,'library');
 4932: 	    foreach my $tryserver (keys(%servers)) {
 4933: 		my $answer=reply('load',$tryserver);
 4934: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4935: 		    $loadm=$answer;
 4936: 		    $unhome=$tryserver;
 4937: 		}
 4938: 	    }
 4939:         }
 4940:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4941: 	    return 'error: unable to find a home server for '.$uname.
 4942:                    ' in domain '.$udom;
 4943:         }
 4944:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4945:                          &escape($upass),$unhome);
 4946: 	unless ($reply eq 'ok') {
 4947:             return 'error: '.$reply;
 4948:         }   
 4949:         $uhome=&homeserver($uname,$udom,'true');
 4950:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4951: 	    return 'error: unable verify users home machine.';
 4952:         }
 4953:     }   # End of creation of new user
 4954: # ---------------------------------------------------------------------- Add ID
 4955:     if ($uid) {
 4956:        $uid=~tr/A-Z/a-z/;
 4957:        my %uidhash=&idrget($udom,$uname);
 4958:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4959:          && (!$forceid)) {
 4960: 	  unless ($uid eq $uidhash{$uname}) {
 4961: 	      return 'error: user id "'.$uid.'" does not match '.
 4962:                   'current user id "'.$uidhash{$uname}.'".';
 4963:           }
 4964:        } else {
 4965: 	  &idput($udom,($uname => $uid));
 4966:        }
 4967:     }
 4968: # -------------------------------------------------------------- Add names, etc
 4969:     my @tmp=&get('environment',
 4970: 		   ['firstname','middlename','lastname','generation'],
 4971: 		   $udom,$uname);
 4972:     my %names;
 4973:     if ($tmp[0] =~ m/^error:.*/) { 
 4974:         %names=(); 
 4975:     } else {
 4976:         %names = @tmp;
 4977:     }
 4978: #
 4979: # Make sure to not trash student environment if instructor does not bother
 4980: # to supply name and email information
 4981: #
 4982:     if ($first)  { $names{'firstname'}  = $first; }
 4983:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4984:     if ($last)   { $names{'lastname'}   = $last; }
 4985:     if (defined($gene))   { $names{'generation'} = $gene; }
 4986:     if ($email) {
 4987:        $email=~s/[^\w\@\.\-\,]//gs;
 4988:        if ($email=~/\@/) { $names{'notification'} = $email;
 4989: 			   $names{'critnotification'} = $email;
 4990: 			   $names{'permanentemail'} = $email; }
 4991:     }
 4992:     my $reply = &put('environment', \%names, $udom,$uname);
 4993:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4994:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4995:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4996:              $umode.', '.$first.', '.$middle.', '.
 4997: 	     $last.', '.$gene.' by '.
 4998:              $env{'user.name'}.' at '.$env{'user.domain'});
 4999:     return 'ok';
 5000: }
 5001: 
 5002: # -------------------------------------------------------------- Modify student
 5003: 
 5004: sub modifystudent {
 5005:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5006:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5007:     if (!$cid) {
 5008: 	unless ($cid=$env{'request.course.id'}) {
 5009: 	    return 'not_in_class';
 5010: 	}
 5011:     }
 5012: # --------------------------------------------------------------- Make the user
 5013:     my $reply=&modifyuser
 5014: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5015:          $desiredhome,$email);
 5016:     unless ($reply eq 'ok') { return $reply; }
 5017:     # This will cause &modify_student_enrollment to get the uid from the
 5018:     # students environment
 5019:     $uid = undef if (!$forceid);
 5020:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5021: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5022:     return $reply;
 5023: }
 5024: 
 5025: sub modify_student_enrollment {
 5026:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5027:     my ($cdom,$cnum,$chome);
 5028:     if (!$cid) {
 5029: 	unless ($cid=$env{'request.course.id'}) {
 5030: 	    return 'not_in_class';
 5031: 	}
 5032: 	$cdom=$env{'course.'.$cid.'.domain'};
 5033: 	$cnum=$env{'course.'.$cid.'.num'};
 5034:     } else {
 5035: 	($cdom,$cnum)=split(/_/,$cid);
 5036:     }
 5037:     $chome=$env{'course.'.$cid.'.home'};
 5038:     if (!$chome) {
 5039: 	$chome=&homeserver($cnum,$cdom);
 5040:     }
 5041:     if (!$chome) { return 'unknown_course'; }
 5042:     # Make sure the user exists
 5043:     my $uhome=&homeserver($uname,$udom);
 5044:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5045: 	return 'error: no such user';
 5046:     }
 5047:     # Get student data if we were not given enough information
 5048:     if (!defined($first)  || $first  eq '' || 
 5049:         !defined($last)   || $last   eq '' || 
 5050:         !defined($uid)    || $uid    eq '' || 
 5051:         !defined($middle) || $middle eq '' || 
 5052:         !defined($gene)   || $gene   eq '') {
 5053:         # They did not supply us with enough data to enroll the student, so
 5054:         # we need to pick up more information.
 5055:         my %tmp = &get('environment',
 5056:                        ['firstname','middlename','lastname', 'generation','id']
 5057:                        ,$udom,$uname);
 5058: 
 5059:         #foreach my $key (keys(%tmp)) {
 5060:         #    &logthis("key $key = ".$tmp{$key});
 5061:         #}
 5062:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5063:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5064:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5065:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5066:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5067:     }
 5068:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5069:     my $reply=cput('classlist',
 5070: 		   {"$uname:$udom" => 
 5071: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5072: 		   $cdom,$cnum);
 5073:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5074: 	return 'error: '.$reply;
 5075:     } else {
 5076: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5077:     }
 5078:     # Add student role to user
 5079:     my $uurl='/'.$cid;
 5080:     $uurl=~s/\_/\//g;
 5081:     if ($usec) {
 5082: 	$uurl.='/'.$usec;
 5083:     }
 5084:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5085: }
 5086: 
 5087: sub format_name {
 5088:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5089:     my $name;
 5090:     if ($first ne 'lastname') {
 5091: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5092:     } else {
 5093: 	if ($lastname=~/\S/) {
 5094: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5095: 	    $name=~s/\s+,/,/;
 5096: 	} else {
 5097: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5098: 	}
 5099:     }
 5100:     $name=~s/^\s+//;
 5101:     $name=~s/\s+$//;
 5102:     $name=~s/\s+/ /g;
 5103:     return $name;
 5104: }
 5105: 
 5106: # ------------------------------------------------- Write to course preferences
 5107: 
 5108: sub writecoursepref {
 5109:     my ($courseid,%prefs)=@_;
 5110:     $courseid=~s/^\///;
 5111:     $courseid=~s/\_/\//g;
 5112:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5113:     my $chome=homeserver($cnum,$cdomain);
 5114:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5115: 	return 'error: no such course';
 5116:     }
 5117:     my $cstring='';
 5118:     foreach my $pref (keys(%prefs)) {
 5119: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5120:     }
 5121:     $cstring=~s/\&$//;
 5122:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5123: }
 5124: 
 5125: # ---------------------------------------------------------- Make/modify course
 5126: 
 5127: sub createcourse {
 5128:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5129:         $course_owner,$crstype)=@_;
 5130:     $url=&declutter($url);
 5131:     my $cid='';
 5132:     unless (&allowed('ccc',$udom)) {
 5133:         return 'refused';
 5134:     }
 5135: # ------------------------------------------------------------------- Create ID
 5136:    my $uname=int(1+rand(9)).
 5137:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5138:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5139:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5140: # ----------------------------------------------- Make sure that does not exist
 5141:    my $uhome=&homeserver($uname,$udom,'true');
 5142:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5143:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5144:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5145:        $uhome=&homeserver($uname,$udom,'true');       
 5146:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5147:            return 'error: unable to generate unique course-ID';
 5148:        } 
 5149:    }
 5150: # ------------------------------------------------ Check supplied server name
 5151:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5152:     if (! &is_library($course_server)) {
 5153:         return 'error:bad server name '.$course_server;
 5154:     }
 5155: # ------------------------------------------------------------- Make the course
 5156:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5157:                       $course_server);
 5158:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5159:     $uhome=&homeserver($uname,$udom,'true');
 5160:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5161: 	return 'error: no such course';
 5162:     }
 5163: # ----------------------------------------------------------------- Course made
 5164: # log existence
 5165:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5166:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5167:                   &escape($crstype),$uhome);
 5168:     &flushcourselogs();
 5169: # set toplevel url
 5170:     my $topurl=$url;
 5171:     unless ($nonstandard) {
 5172: # ------------------------------------------ For standard courses, make top url
 5173:         my $mapurl=&clutter($url);
 5174:         if ($mapurl eq '/res/') { $mapurl=''; }
 5175:         $env{'form.initmap'}=(<<ENDINITMAP);
 5176: <map>
 5177: <resource id="1" type="start"></resource>
 5178: <resource id="2" src="$mapurl"></resource>
 5179: <resource id="3" type="finish"></resource>
 5180: <link index="1" from="1" to="2"></link>
 5181: <link index="2" from="2" to="3"></link>
 5182: </map>
 5183: ENDINITMAP
 5184:         $topurl=&declutter(
 5185:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5186:                           );
 5187:     }
 5188: # ----------------------------------------------------------- Write preferences
 5189:     &writecoursepref($udom.'_'.$uname,
 5190:                      ('description' => $description,
 5191:                       'url'         => $topurl));
 5192:     return '/'.$udom.'/'.$uname;
 5193: }
 5194: 
 5195: sub is_course {
 5196:     my ($cdom,$cnum) = @_;
 5197:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5198: 				undef,'.');
 5199:     if (exists($courses{$cdom.'_'.$cnum})) {
 5200:         return 1;
 5201:     }
 5202:     return 0;
 5203: }
 5204: 
 5205: # ---------------------------------------------------------- Assign Custom Role
 5206: 
 5207: sub assigncustomrole {
 5208:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5209:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5210:                        $end,$start,$deleteflag);
 5211: }
 5212: 
 5213: # ----------------------------------------------------------------- Revoke Role
 5214: 
 5215: sub revokerole {
 5216:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5217:     my $now=time;
 5218:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5219: }
 5220: 
 5221: # ---------------------------------------------------------- Revoke Custom Role
 5222: 
 5223: sub revokecustomrole {
 5224:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5225:     my $now=time;
 5226:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5227:            $deleteflag);
 5228: }
 5229: 
 5230: # ------------------------------------------------------------ Disk usage
 5231: sub diskusage {
 5232:     my ($udom,$uname,$directoryRoot)=@_;
 5233:     $directoryRoot =~ s/\/$//;
 5234:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5235:     return $listing;
 5236: }
 5237: 
 5238: sub is_locked {
 5239:     my ($file_name, $domain, $user) = @_;
 5240:     my @check;
 5241:     my $is_locked;
 5242:     push @check, $file_name;
 5243:     my %locked = &get('file_permissions',\@check,
 5244: 		      $env{'user.domain'},$env{'user.name'});
 5245:     my ($tmp)=keys(%locked);
 5246:     if ($tmp=~/^error:/) { undef(%locked); }
 5247:     
 5248:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5249:         $is_locked = 'false';
 5250:         foreach my $entry (@{$locked{$file_name}}) {
 5251:            if (ref($entry) eq 'ARRAY') { 
 5252:                $is_locked = 'true';
 5253:                last;
 5254:            }
 5255:        }
 5256:     } else {
 5257:         $is_locked = 'false';
 5258:     }
 5259: }
 5260: 
 5261: sub declutter_portfile {
 5262:     my ($file) = @_;
 5263:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5264:     return $file;
 5265: }
 5266: 
 5267: # ------------------------------------------------------------- Mark as Read Only
 5268: 
 5269: sub mark_as_readonly {
 5270:     my ($domain,$user,$files,$what) = @_;
 5271:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5272:     my ($tmp)=keys(%current_permissions);
 5273:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5274:     foreach my $file (@{$files}) {
 5275: 	$file = &declutter_portfile($file);
 5276:         push(@{$current_permissions{$file}},$what);
 5277:     }
 5278:     &put('file_permissions',\%current_permissions,$domain,$user);
 5279:     return;
 5280: }
 5281: 
 5282: # ------------------------------------------------------------Save Selected Files
 5283: 
 5284: sub save_selected_files {
 5285:     my ($user, $path, @files) = @_;
 5286:     my $filename = $user."savedfiles";
 5287:     my @other_files = &files_not_in_path($user, $path);
 5288:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5289:     foreach my $file (@files) {
 5290:         print (OUT $env{'form.currentpath'}.$file."\n");
 5291:     }
 5292:     foreach my $file (@other_files) {
 5293:         print (OUT $file."\n");
 5294:     }
 5295:     close (OUT);
 5296:     return 'ok';
 5297: }
 5298: 
 5299: sub clear_selected_files {
 5300:     my ($user) = @_;
 5301:     my $filename = $user."savedfiles";
 5302:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5303:     print (OUT undef);
 5304:     close (OUT);
 5305:     return ("ok");    
 5306: }
 5307: 
 5308: sub files_in_path {
 5309:     my ($user, $path) = @_;
 5310:     my $filename = $user."savedfiles";
 5311:     my %return_files;
 5312:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5313:     while (my $line_in = <IN>) {
 5314:         chomp ($line_in);
 5315:         my @paths_and_file = split (m!/!, $line_in);
 5316:         my $file_part = pop (@paths_and_file);
 5317:         my $path_part = join ('/', @paths_and_file);
 5318:         $path_part.='/';
 5319:         my $path_and_file = $path_part.$file_part;
 5320:         if ($path_part eq $path) {
 5321:             $return_files{$file_part}= 'selected';
 5322:         }
 5323:     }
 5324:     close (IN);
 5325:     return (\%return_files);
 5326: }
 5327: 
 5328: # called in portfolio select mode, to show files selected NOT in current directory
 5329: sub files_not_in_path {
 5330:     my ($user, $path) = @_;
 5331:     my $filename = $user."savedfiles";
 5332:     my @return_files;
 5333:     my $path_part;
 5334:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5335:     while (my $line = <IN>) {
 5336:         #ok, I know it's clunky, but I want it to work
 5337:         my @paths_and_file = split(m|/|, $line);
 5338:         my $file_part = pop(@paths_and_file);
 5339:         chomp($file_part);
 5340:         my $path_part = join('/', @paths_and_file);
 5341:         $path_part .= '/';
 5342:         my $path_and_file = $path_part.$file_part;
 5343:         if ($path_part ne $path) {
 5344:             push(@return_files, ($path_and_file));
 5345:         }
 5346:     }
 5347:     close(OUT);
 5348:     return (@return_files);
 5349: }
 5350: 
 5351: #----------------------------------------------Get portfolio file permissions
 5352: 
 5353: sub get_portfile_permissions {
 5354:     my ($domain,$user) = @_;
 5355:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5356:     my ($tmp)=keys(%current_permissions);
 5357:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5358:     return \%current_permissions;
 5359: }
 5360: 
 5361: #---------------------------------------------Get portfolio file access controls
 5362: 
 5363: sub get_access_controls {
 5364:     my ($current_permissions,$group,$file) = @_;
 5365:     my %access;
 5366:     my $real_file = $file;
 5367:     $file =~ s/\.meta$//;
 5368:     if (defined($file)) {
 5369:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5370:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5371:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5372:             }
 5373:         }
 5374:     } else {
 5375:         foreach my $key (keys(%{$current_permissions})) {
 5376:             if ($key =~ /\0accesscontrol$/) {
 5377:                 if (defined($group)) {
 5378:                     if ($key !~ m-^\Q$group\E/-) {
 5379:                         next;
 5380:                     }
 5381:                 }
 5382:                 my ($fullpath) = split(/\0/,$key);
 5383:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5384:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5385:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5386:                     }
 5387:                 }
 5388:             }
 5389:         }
 5390:     }
 5391:     return %access;
 5392: }
 5393: 
 5394: sub modify_access_controls {
 5395:     my ($file_name,$changes,$domain,$user)=@_;
 5396:     my ($outcome,$deloutcome);
 5397:     my %store_permissions;
 5398:     my %new_values;
 5399:     my %new_control;
 5400:     my %translation;
 5401:     my @deletions = ();
 5402:     my $now = time;
 5403:     if (exists($$changes{'activate'})) {
 5404:         if (ref($$changes{'activate'}) eq 'HASH') {
 5405:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5406:             my $numnew = scalar(@newitems);
 5407:             for (my $i=0; $i<$numnew; $i++) {
 5408:                 my $newkey = $newitems[$i];
 5409:                 my $newid = &Apache::loncommon::get_cgi_id();
 5410:                 if ($newkey =~ /^\d+:/) { 
 5411:                     $newkey =~ s/^(\d+)/$newid/;
 5412:                     $translation{$1} = $newid;
 5413:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5414:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5415:                     $translation{$1} = $newid;
 5416:                 }
 5417:                 $new_values{$file_name."\0".$newkey} = 
 5418:                                           $$changes{'activate'}{$newitems[$i]};
 5419:                 $new_control{$newkey} = $now;
 5420:             }
 5421:         }
 5422:     }
 5423:     my %todelete;
 5424:     my %changed_items;
 5425:     foreach my $action ('delete','update') {
 5426:         if (exists($$changes{$action})) {
 5427:             if (ref($$changes{$action}) eq 'HASH') {
 5428:                 foreach my $key (keys(%{$$changes{$action}})) {
 5429:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5430:                     if ($action eq 'delete') { 
 5431:                         $todelete{$itemnum} = 1;
 5432:                     } else {
 5433:                         $changed_items{$itemnum} = $key;
 5434:                     }
 5435:                 }
 5436:             }
 5437:         }
 5438:     }
 5439:     # get lock on access controls for file.
 5440:     my $lockhash = {
 5441:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5442:                                                        ':'.$env{'user.domain'},
 5443:                    }; 
 5444:     my $tries = 0;
 5445:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5446:    
 5447:     while (($gotlock ne 'ok') && $tries <3) {
 5448:         $tries ++;
 5449:         sleep 1;
 5450:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5451:     }
 5452:     if ($gotlock eq 'ok') {
 5453:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5454:         my ($tmp)=keys(%curr_permissions);
 5455:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5456:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5457:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5458:             if (ref($curr_controls) eq 'HASH') {
 5459:                 foreach my $control_item (keys(%{$curr_controls})) {
 5460:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5461:                     if (defined($todelete{$itemnum})) {
 5462:                         push(@deletions,$file_name."\0".$control_item);
 5463:                     } else {
 5464:                         if (defined($changed_items{$itemnum})) {
 5465:                             $new_control{$changed_items{$itemnum}} = $now;
 5466:                             push(@deletions,$file_name."\0".$control_item);
 5467:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5468:                         } else {
 5469:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5470:                         }
 5471:                     }
 5472:                 }
 5473:             }
 5474:         }
 5475:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5476:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5477:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5478:         #  remove lock
 5479:         my @del_lock = ($file_name."\0".'locked_access_records');
 5480:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5481:         my ($file,$group);
 5482:         if (&is_course($domain,$user)) {
 5483:             ($group,$file) = split(/\//,$file_name,2);
 5484:         } else {
 5485:             $file = $file_name;
 5486:         }
 5487:         my $sqlresult =
 5488:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5489:                                     $group);
 5490:     } else {
 5491:         $outcome = "error: could not obtain lockfile\n";  
 5492:     }
 5493:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5494: }
 5495: 
 5496: sub make_public_indefinitely {
 5497:     my ($requrl) = @_;
 5498:     my $now = time;
 5499:     my $action = 'activate';
 5500:     my $aclnum = 0;
 5501:     if (&is_portfolio_url($requrl)) {
 5502:         my (undef,$udom,$unum,$file_name,$group) =
 5503:             &parse_portfolio_url($requrl);
 5504:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5505:         my %access_controls = &get_access_controls($current_perms,
 5506:                                                    $group,$file_name);
 5507:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5508:             my ($num,$scope,$end,$start) = 
 5509:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5510:             if ($scope eq 'public') {
 5511:                 if ($start <= $now && $end == 0) {
 5512:                     $action = 'none';
 5513:                 } else {
 5514:                     $action = 'update';
 5515:                     $aclnum = $num;
 5516:                 }
 5517:                 last;
 5518:             }
 5519:         }
 5520:         if ($action eq 'none') {
 5521:              return 'ok';
 5522:         } else {
 5523:             my %changes;
 5524:             my $newend = 0;
 5525:             my $newstart = $now;
 5526:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5527:             $changes{$action}{$newkey} = {
 5528:                 type => 'public',
 5529:                 time => {
 5530:                     start => $newstart,
 5531:                     end   => $newend,
 5532:                 },
 5533:             };
 5534:             my ($outcome,$deloutcome,$new_values,$translation) =
 5535:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5536:             return $outcome;
 5537:         }
 5538:     } else {
 5539:         return 'invalid';
 5540:     }
 5541: }
 5542: 
 5543: #------------------------------------------------------Get Marked as Read Only
 5544: 
 5545: sub get_marked_as_readonly {
 5546:     my ($domain,$user,$what,$group) = @_;
 5547:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5548:     my @readonly_files;
 5549:     my $cmp1=$what;
 5550:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5551:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5552:         if (defined($group)) {
 5553:             if ($file_name !~ m-^\Q$group\E/-) {
 5554:                 next;
 5555:             }
 5556:         }
 5557:         if (ref($value) eq "ARRAY"){
 5558:             foreach my $stored_what (@{$value}) {
 5559:                 my $cmp2=$stored_what;
 5560:                 if (ref($stored_what) eq 'ARRAY') {
 5561:                     $cmp2=join('',@{$stored_what});
 5562:                 }
 5563:                 if ($cmp1 eq $cmp2) {
 5564:                     push(@readonly_files, $file_name);
 5565:                     last;
 5566:                 } elsif (!defined($what)) {
 5567:                     push(@readonly_files, $file_name);
 5568:                     last;
 5569:                 }
 5570:             }
 5571:         }
 5572:     }
 5573:     return @readonly_files;
 5574: }
 5575: #-----------------------------------------------------------Get Marked as Read Only Hash
 5576: 
 5577: sub get_marked_as_readonly_hash {
 5578:     my ($current_permissions,$group,$what) = @_;
 5579:     my %readonly_files;
 5580:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5581:         if (defined($group)) {
 5582:             if ($file_name !~ m-^\Q$group\E/-) {
 5583:                 next;
 5584:             }
 5585:         }
 5586:         if (ref($value) eq "ARRAY"){
 5587:             foreach my $stored_what (@{$value}) {
 5588:                 if (ref($stored_what) eq 'ARRAY') {
 5589:                     foreach my $lock_descriptor(@{$stored_what}) {
 5590:                         if ($lock_descriptor eq 'graded') {
 5591:                             $readonly_files{$file_name} = 'graded';
 5592:                         } elsif ($lock_descriptor eq 'handback') {
 5593:                             $readonly_files{$file_name} = 'handback';
 5594:                         } else {
 5595:                             if (!exists($readonly_files{$file_name})) {
 5596:                                 $readonly_files{$file_name} = 'locked';
 5597:                             }
 5598:                         }
 5599:                     }
 5600:                 } 
 5601:             }
 5602:         } 
 5603:     }
 5604:     return %readonly_files;
 5605: }
 5606: # ------------------------------------------------------------ Unmark as Read Only
 5607: 
 5608: sub unmark_as_readonly {
 5609:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5610:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5611:     my ($domain,$user,$what,$file_name,$group) = @_;
 5612:     $file_name = &declutter_portfile($file_name);
 5613:     my $symb_crs = $what;
 5614:     if (ref($what)) { $symb_crs=join('',@$what); }
 5615:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5616:     my ($tmp)=keys(%current_permissions);
 5617:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5618:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5619:     foreach my $file (@readonly_files) {
 5620: 	my $clean_file = &declutter_portfile($file);
 5621: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5622: 	my $current_locks = $current_permissions{$file};
 5623:         my @new_locks;
 5624:         my @del_keys;
 5625:         if (ref($current_locks) eq "ARRAY"){
 5626:             foreach my $locker (@{$current_locks}) {
 5627:                 my $compare=$locker;
 5628:                 if (ref($locker) eq 'ARRAY') {
 5629:                     $compare=join('',@{$locker});
 5630:                     if ($compare ne $symb_crs) {
 5631:                         push(@new_locks, $locker);
 5632:                     }
 5633:                 }
 5634:             }
 5635:             if (scalar(@new_locks) > 0) {
 5636:                 $current_permissions{$file} = \@new_locks;
 5637:             } else {
 5638:                 push(@del_keys, $file);
 5639:                 &del('file_permissions',\@del_keys, $domain, $user);
 5640:                 delete($current_permissions{$file});
 5641:             }
 5642:         }
 5643:     }
 5644:     &put('file_permissions',\%current_permissions,$domain,$user);
 5645:     return;
 5646: }
 5647: 
 5648: # ------------------------------------------------------------ Directory lister
 5649: 
 5650: sub dirlist {
 5651:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5652: 
 5653:     $uri=~s/^\///;
 5654:     $uri=~s/\/$//;
 5655:     my ($udom, $uname);
 5656:     (undef,$udom,$uname)=split(/\//,$uri);
 5657:     if(defined($userdomain)) {
 5658:         $udom = $userdomain;
 5659:     }
 5660:     if(defined($username)) {
 5661:         $uname = $username;
 5662:     }
 5663: 
 5664:     my $dirRoot = $perlvar{'lonDocRoot'};
 5665:     if(defined($alternateDirectoryRoot)) {
 5666:         $dirRoot = $alternateDirectoryRoot;
 5667:         $dirRoot =~ s/\/$//;
 5668:     }
 5669: 
 5670:     if($udom) {
 5671:         if($uname) {
 5672:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5673: 				 &homeserver($uname,$udom));
 5674:             my @listing_results;
 5675:             if ($listing eq 'unknown_cmd') {
 5676:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5677: 				  &homeserver($uname,$udom));
 5678:                 @listing_results = split(/:/,$listing);
 5679:             } else {
 5680:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5681:             }
 5682:             return @listing_results;
 5683:         } elsif(!defined($alternateDirectoryRoot)) {
 5684:             my %allusers;
 5685: 	    my %servers = &get_servers($udom,'library');
 5686: 	    foreach my $tryserver (keys(%servers)) {
 5687: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5688: 				     $udom, $tryserver);
 5689: 		my @listing_results;
 5690: 		if ($listing eq 'unknown_cmd') {
 5691: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5692: 				      $udom, $tryserver);
 5693: 		    @listing_results = split(/:/,$listing);
 5694: 		} else {
 5695: 		    @listing_results =
 5696: 			map { &unescape($_); } split(/:/,$listing);
 5697: 		}
 5698: 		if ($listing_results[0] ne 'no_such_dir' && 
 5699: 		    $listing_results[0] ne 'empty'       &&
 5700: 		    $listing_results[0] ne 'con_lost') {
 5701: 		    foreach my $line (@listing_results) {
 5702: 			my ($entry) = split(/&/,$line,2);
 5703: 			$allusers{$entry} = 1;
 5704: 		    }
 5705: 		}
 5706:             }
 5707:             my $alluserstr='';
 5708:             foreach my $user (sort(keys(%allusers))) {
 5709:                 $alluserstr.=$user.'&user:';
 5710:             }
 5711:             $alluserstr=~s/:$//;
 5712:             return split(/:/,$alluserstr);
 5713:         } else {
 5714:             return ('missing user name');
 5715:         }
 5716:     } elsif(!defined($alternateDirectoryRoot)) {
 5717:         my @all_domains = sort(&all_domains());
 5718:          foreach my $domain (@all_domains) {
 5719:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5720:          }
 5721:          return @all_domains;
 5722:      } else {
 5723:         return ('missing domain');
 5724:     }
 5725: }
 5726: 
 5727: # --------------------------------------------- GetFileTimestamp
 5728: # This function utilizes dirlist and returns the date stamp for
 5729: # when it was last modified.  It will also return an error of -1
 5730: # if an error occurs
 5731: 
 5732: ##
 5733: ## FIXME: This subroutine assumes its caller knows something about the
 5734: ## directory structure of the home server for the student ($root).
 5735: ## Not a good assumption to make.  Since this is for looking up files
 5736: ## in user directories, the full path should be constructed by lond, not
 5737: ## whatever machine we request data from.
 5738: ##
 5739: sub GetFileTimestamp {
 5740:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5741:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5742:     $studentName   = &LONCAPA::clean_username($studentName);
 5743:     my $subdir=$studentName.'__';
 5744:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5745:     my $proname="$studentDomain/$subdir/$studentName";
 5746:     $proname .= '/'.$filename;
 5747:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5748:                                               $studentName, $root);
 5749:     my @stats = split('&', $fileStat);
 5750:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5751:         # @stats contains first the filename, then the stat output
 5752:         return $stats[10]; # so this is 10 instead of 9.
 5753:     } else {
 5754:         return -1;
 5755:     }
 5756: }
 5757: 
 5758: sub stat_file {
 5759:     my ($uri) = @_;
 5760:     $uri = &clutter_with_no_wrapper($uri);
 5761: 
 5762:     my ($udom,$uname,$file,$dir);
 5763:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5764: 	($udom,$uname,$file) =
 5765: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5766: 	$file = 'userfiles/'.$file;
 5767: 	$dir = &propath($udom,$uname);
 5768:     }
 5769:     if ($uri =~ m-^/res/-) {
 5770: 	($udom,$uname) = 
 5771: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5772: 	$file = $uri;
 5773:     }
 5774: 
 5775:     if (!$udom || !$uname || !$file) {
 5776: 	# unable to handle the uri
 5777: 	return ();
 5778:     }
 5779: 
 5780:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5781:     my @stats = split('&', $result);
 5782:     
 5783:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5784: 	shift(@stats); #filename is first
 5785: 	return @stats;
 5786:     }
 5787:     return ();
 5788: }
 5789: 
 5790: # -------------------------------------------------------- Value of a Condition
 5791: 
 5792: # gets the value of a specific preevaluated condition
 5793: #    stored in the string  $env{user.state.<cid>}
 5794: # or looks up a condition reference in the bighash and if if hasn't
 5795: # already been evaluated recurses into docondval to get the value of
 5796: # the condition, then memoizing it to 
 5797: #   $env{user.state.<cid>.<condition>}
 5798: sub directcondval {
 5799:     my $number=shift;
 5800:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5801: 	&Apache::lonuserstate::evalstate();
 5802:     }
 5803:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5804: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5805:     } elsif ($number =~ /^_/) {
 5806: 	my $sub_condition;
 5807: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5808: 		&GDBM_READER(),0640)) {
 5809: 	    $sub_condition=$bighash{'conditions'.$number};
 5810: 	    untie(%bighash);
 5811: 	}
 5812: 	my $value = &docondval($sub_condition);
 5813: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5814: 	return $value;
 5815:     }
 5816:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5817:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5818:     } else {
 5819:        return 2;
 5820:     }
 5821: }
 5822: 
 5823: # get the collection of conditions for this resource
 5824: sub condval {
 5825:     my $condidx=shift;
 5826:     my $allpathcond='';
 5827:     foreach my $cond (split(/\|/,$condidx)) {
 5828: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5829: 	    $allpathcond.=
 5830: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5831: 	}
 5832:     }
 5833:     $allpathcond=~s/\|$//;
 5834:     return &docondval($allpathcond);
 5835: }
 5836: 
 5837: #evaluates an expression of conditions
 5838: sub docondval {
 5839:     my ($allpathcond) = @_;
 5840:     my $result=0;
 5841:     if ($env{'request.course.id'}
 5842: 	&& defined($allpathcond)) {
 5843: 	my $operand='|';
 5844: 	my @stack;
 5845: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5846: 	    if ($chunk eq '(') {
 5847: 		push @stack,($operand,$result);
 5848: 	    } elsif ($chunk eq ')') {
 5849: 		my $before=pop @stack;
 5850: 		if (pop @stack eq '&') {
 5851: 		    $result=$result>$before?$before:$result;
 5852: 		} else {
 5853: 		    $result=$result>$before?$result:$before;
 5854: 		}
 5855: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5856: 		$operand=$chunk;
 5857: 	    } else {
 5858: 		my $new=directcondval($chunk);
 5859: 		if ($operand eq '&') {
 5860: 		    $result=$result>$new?$new:$result;
 5861: 		} else {
 5862: 		    $result=$result>$new?$result:$new;
 5863: 		}
 5864: 	    }
 5865: 	}
 5866:     }
 5867:     return $result;
 5868: }
 5869: 
 5870: # ---------------------------------------------------- Devalidate courseresdata
 5871: 
 5872: sub devalidatecourseresdata {
 5873:     my ($coursenum,$coursedomain)=@_;
 5874:     my $hashid=$coursenum.':'.$coursedomain;
 5875:     &devalidate_cache_new('courseres',$hashid);
 5876: }
 5877: 
 5878: 
 5879: # --------------------------------------------------- Course Resourcedata Query
 5880: 
 5881: sub get_courseresdata {
 5882:     my ($coursenum,$coursedomain)=@_;
 5883:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5884:     my $hashid=$coursenum.':'.$coursedomain;
 5885:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5886:     my %dumpreply;
 5887:     unless (defined($cached)) {
 5888: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5889: 	$result=\%dumpreply;
 5890: 	my ($tmp) = keys(%dumpreply);
 5891: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5892: 	    &do_cache_new('courseres',$hashid,$result,600);
 5893: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5894: 	    return $tmp;
 5895: 	} elsif ($tmp =~ /^(error)/) {
 5896: 	    $result=undef;
 5897: 	    &do_cache_new('courseres',$hashid,$result,600);
 5898: 	}
 5899:     }
 5900:     return $result;
 5901: }
 5902: 
 5903: sub devalidateuserresdata {
 5904:     my ($uname,$udom)=@_;
 5905:     my $hashid="$udom:$uname";
 5906:     &devalidate_cache_new('userres',$hashid);
 5907: }
 5908: 
 5909: sub get_userresdata {
 5910:     my ($uname,$udom)=@_;
 5911:     #most student don\'t have any data set, check if there is some data
 5912:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5913: 
 5914:     my $hashid="$udom:$uname";
 5915:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5916:     if (!defined($cached)) {
 5917: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5918: 	$result=\%resourcedata;
 5919: 	&do_cache_new('userres',$hashid,$result,600);
 5920:     }
 5921:     my ($tmp)=keys(%$result);
 5922:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5923: 	return $result;
 5924:     }
 5925:     #error 2 occurs when the .db doesn't exist
 5926:     if ($tmp!~/error: 2 /) {
 5927: 	&logthis("<font color=\"blue\">WARNING:".
 5928: 		 " Trying to get resource data for ".
 5929: 		 $uname." at ".$udom.": ".
 5930: 		 $tmp."</font>");
 5931:     } elsif ($tmp=~/error: 2 /) {
 5932: 	#&EXT_cache_set($udom,$uname);
 5933: 	&do_cache_new('userres',$hashid,undef,600);
 5934: 	undef($tmp); # not really an error so don't send it back
 5935:     }
 5936:     return $tmp;
 5937: }
 5938: 
 5939: sub resdata {
 5940:     my ($name,$domain,$type,@which)=@_;
 5941:     my $result;
 5942:     if ($type eq 'course') {
 5943: 	$result=&get_courseresdata($name,$domain);
 5944:     } elsif ($type eq 'user') {
 5945: 	$result=&get_userresdata($name,$domain);
 5946:     }
 5947:     if (!ref($result)) { return $result; }    
 5948:     foreach my $item (@which) {
 5949: 	if (defined($result->{$item})) {
 5950: 	    return $result->{$item};
 5951: 	}
 5952:     }
 5953:     return undef;
 5954: }
 5955: 
 5956: #
 5957: # EXT resource caching routines
 5958: #
 5959: 
 5960: sub clear_EXT_cache_status {
 5961:     &delenv('cache.EXT.');
 5962: }
 5963: 
 5964: sub EXT_cache_status {
 5965:     my ($target_domain,$target_user) = @_;
 5966:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5967:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5968:         # We know already the user has no data
 5969:         return 1;
 5970:     } else {
 5971:         return 0;
 5972:     }
 5973: }
 5974: 
 5975: sub EXT_cache_set {
 5976:     my ($target_domain,$target_user) = @_;
 5977:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5978:     #&appenv($cachename => time);
 5979: }
 5980: 
 5981: # --------------------------------------------------------- Value of a Variable
 5982: sub EXT {
 5983: 
 5984:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5985:     unless ($varname) { return ''; }
 5986:     #get real user name/domain, courseid and symb
 5987:     my $courseid;
 5988:     my $publicuser;
 5989:     if ($symbparm) {
 5990: 	$symbparm=&get_symb_from_alias($symbparm);
 5991:     }
 5992:     if (!($uname && $udom)) {
 5993:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5994:       if (!$symbparm) {	$symbparm=$cursymb; }
 5995:     } else {
 5996: 	$courseid=$env{'request.course.id'};
 5997:     }
 5998:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5999:     my $rest;
 6000:     if (defined($therest[0])) {
 6001:        $rest=join('.',@therest);
 6002:     } else {
 6003:        $rest='';
 6004:     }
 6005: 
 6006:     my $qualifierrest=$qualifier;
 6007:     if ($rest) { $qualifierrest.='.'.$rest; }
 6008:     my $spacequalifierrest=$space;
 6009:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6010:     if ($realm eq 'user') {
 6011: # --------------------------------------------------------------- user.resource
 6012: 	if ($space eq 'resource') {
 6013: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6014: 		  || defined($Apache::lonhomework::parsing_a_task))
 6015: 		 &&
 6016: 		 ($symbparm eq &symbread()) ) {	
 6017: 		# if we are in the middle of processing the resource the
 6018: 		# get the value we are planning on committing
 6019:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6020:                     return $Apache::lonhomework::results{$qualifierrest};
 6021:                 } else {
 6022:                     return $Apache::lonhomework::history{$qualifierrest};
 6023:                 }
 6024: 	    } else {
 6025: 		my %restored;
 6026: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6027: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6028: 		} else {
 6029: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6030: 		}
 6031: 		return $restored{$qualifierrest};
 6032: 	    }
 6033: # ----------------------------------------------------------------- user.access
 6034:         } elsif ($space eq 'access') {
 6035: 	    # FIXME - not supporting calls for a specific user
 6036:             return &allowed($qualifier,$rest);
 6037: # ------------------------------------------ user.preferences, user.environment
 6038:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6039: 	    if (($uname eq $env{'user.name'}) &&
 6040: 		($udom eq $env{'user.domain'})) {
 6041: 		return $env{join('.',('environment',$qualifierrest))};
 6042: 	    } else {
 6043: 		my %returnhash;
 6044: 		if (!$publicuser) {
 6045: 		    %returnhash=&userenvironment($udom,$uname,
 6046: 						 $qualifierrest);
 6047: 		}
 6048: 		return $returnhash{$qualifierrest};
 6049: 	    }
 6050: # ----------------------------------------------------------------- user.course
 6051:         } elsif ($space eq 'course') {
 6052: 	    # FIXME - not supporting calls for a specific user
 6053:             return $env{join('.',('request.course',$qualifier))};
 6054: # ------------------------------------------------------------------- user.role
 6055:         } elsif ($space eq 'role') {
 6056: 	    # FIXME - not supporting calls for a specific user
 6057:             my ($role,$where)=split(/\./,$env{'request.role'});
 6058:             if ($qualifier eq 'value') {
 6059: 		return $role;
 6060:             } elsif ($qualifier eq 'extent') {
 6061:                 return $where;
 6062:             }
 6063: # ----------------------------------------------------------------- user.domain
 6064:         } elsif ($space eq 'domain') {
 6065:             return $udom;
 6066: # ------------------------------------------------------------------- user.name
 6067:         } elsif ($space eq 'name') {
 6068:             return $uname;
 6069: # ---------------------------------------------------- Any other user namespace
 6070:         } else {
 6071: 	    my %reply;
 6072: 	    if (!$publicuser) {
 6073: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6074: 	    }
 6075: 	    return $reply{$qualifierrest};
 6076:         }
 6077:     } elsif ($realm eq 'query') {
 6078: # ---------------------------------------------- pull stuff out of query string
 6079:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6080: 						[$spacequalifierrest]);
 6081: 	return $env{'form.'.$spacequalifierrest}; 
 6082:    } elsif ($realm eq 'request') {
 6083: # ------------------------------------------------------------- request.browser
 6084:         if ($space eq 'browser') {
 6085: 	    if ($qualifier eq 'textremote') {
 6086: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6087: 		    return 1;
 6088: 		} else {
 6089: 		    return 0;
 6090: 		}
 6091: 	    } else {
 6092: 		return $env{'browser.'.$qualifier};
 6093: 	    }
 6094: # ------------------------------------------------------------ request.filename
 6095:         } else {
 6096:             return $env{'request.'.$spacequalifierrest};
 6097:         }
 6098:     } elsif ($realm eq 'course') {
 6099: # ---------------------------------------------------------- course.description
 6100:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6101:     } elsif ($realm eq 'resource') {
 6102: 
 6103: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6104: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6105: 	}
 6106: 
 6107: 	if ($space eq 'title') {
 6108: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6109: 	    return &gettitle($symbparm);
 6110: 	}
 6111: 	
 6112: 	if ($space eq 'map') {
 6113: 	    my ($map) = &decode_symb($symbparm);
 6114: 	    return &symbread($map);
 6115: 	}
 6116: 
 6117: 	my ($section, $group, @groups);
 6118: 	my ($courselevelm,$courselevel);
 6119: 	if ($symbparm && defined($courseid) && 
 6120: 	    $courseid eq $env{'request.course.id'}) {
 6121: 
 6122: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6123: 
 6124: # ----------------------------------------------------- Cascading lookup scheme
 6125: 	    my $symbp=$symbparm;
 6126: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6127: 
 6128: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6129: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6130: 
 6131: 	    if (($env{'user.name'} eq $uname) &&
 6132: 		($env{'user.domain'} eq $udom)) {
 6133: 		$section=$env{'request.course.sec'};
 6134:                 @groups = split(/:/,$env{'request.course.groups'});  
 6135:                 @groups=&sort_course_groups($courseid,@groups); 
 6136: 	    } else {
 6137: 		if (! defined($usection)) {
 6138: 		    $section=&getsection($udom,$uname,$courseid);
 6139: 		} else {
 6140: 		    $section = $usection;
 6141: 		}
 6142:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6143: 	    }
 6144: 
 6145: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6146: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6147: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6148: 
 6149: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6150: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6151: 	    $courselevelm=$courseid.'.'.$mapparm;
 6152: 
 6153: # ----------------------------------------------------------- first, check user
 6154: 
 6155: 	    my $userreply=&resdata($uname,$udom,'user',
 6156: 				       ($courselevelr,$courselevelm,
 6157: 					$courselevel));
 6158: 	    if (defined($userreply)) { return $userreply; }
 6159: 
 6160: # ------------------------------------------------ second, check some of course
 6161:             my $coursereply;
 6162:             if (@groups > 0) {
 6163:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6164:                                        $mapparm,$spacequalifierrest);
 6165:                 if (defined($coursereply)) { return $coursereply; }
 6166:             }
 6167: 
 6168: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6169: 				     $env{'course.'.$courseid.'.domain'},
 6170: 				     'course',
 6171: 				     ($seclevelr,$seclevelm,$seclevel,
 6172: 				      $courselevelr));
 6173: 	    if (defined($coursereply)) { return $coursereply; }
 6174: 
 6175: # ------------------------------------------------------ third, check map parms
 6176: 	    my %parmhash=();
 6177: 	    my $thisparm='';
 6178: 	    if (tie(%parmhash,'GDBM_File',
 6179: 		    $env{'request.course.fn'}.'_parms.db',
 6180: 		    &GDBM_READER(),0640)) {
 6181: 		$thisparm=$parmhash{$symbparm};
 6182: 		untie(%parmhash);
 6183: 	    }
 6184: 	    if ($thisparm) { return $thisparm; }
 6185: 	}
 6186: # ------------------------------------------ fourth, look in resource metadata
 6187: 
 6188: 	$spacequalifierrest=~s/\./\_/;
 6189: 	my $filename;
 6190: 	if (!$symbparm) { $symbparm=&symbread(); }
 6191: 	if ($symbparm) {
 6192: 	    $filename=(&decode_symb($symbparm))[2];
 6193: 	} else {
 6194: 	    $filename=$env{'request.filename'};
 6195: 	}
 6196: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6197: 	if (defined($metadata)) { return $metadata; }
 6198: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6199: 	if (defined($metadata)) { return $metadata; }
 6200: 
 6201: # ---------------------------------------------- fourth, look in rest pf course
 6202: 	if ($symbparm && defined($courseid) && 
 6203: 	    $courseid eq $env{'request.course.id'}) {
 6204: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6205: 				     $env{'course.'.$courseid.'.domain'},
 6206: 				     'course',
 6207: 				     ($courselevelm,$courselevel));
 6208: 	    if (defined($coursereply)) { return $coursereply; }
 6209: 	}
 6210: # ------------------------------------------------------------------ Cascade up
 6211: 	unless ($space eq '0') {
 6212: 	    my @parts=split(/_/,$space);
 6213: 	    my $id=pop(@parts);
 6214: 	    my $part=join('_',@parts);
 6215: 	    if ($part eq '') { $part='0'; }
 6216: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6217: 				 $symbparm,$udom,$uname,$section,1);
 6218: 	    if (defined($partgeneral)) { return $partgeneral; }
 6219: 	}
 6220: 	if ($recurse) { return undef; }
 6221: 	my $pack_def=&packages_tab_default($filename,$varname);
 6222: 	if (defined($pack_def)) { return $pack_def; }
 6223: 
 6224: # ---------------------------------------------------- Any other user namespace
 6225:     } elsif ($realm eq 'environment') {
 6226: # ----------------------------------------------------------------- environment
 6227: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6228: 	    return $env{'environment.'.$spacequalifierrest};
 6229: 	} else {
 6230: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6231: 		return '';
 6232: 	    }
 6233: 	    my %returnhash=&userenvironment($udom,$uname,
 6234: 					    $spacequalifierrest);
 6235: 	    return $returnhash{$spacequalifierrest};
 6236: 	}
 6237:     } elsif ($realm eq 'system') {
 6238: # ----------------------------------------------------------------- system.time
 6239: 	if ($space eq 'time') {
 6240: 	    return time;
 6241:         }
 6242:     } elsif ($realm eq 'server') {
 6243: # ----------------------------------------------------------------- system.time
 6244: 	if ($space eq 'name') {
 6245: 	    return $ENV{'SERVER_NAME'};
 6246:         }
 6247:     }
 6248:     return '';
 6249: }
 6250: 
 6251: sub check_group_parms {
 6252:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6253:     my @groupitems = ();
 6254:     my $resultitem;
 6255:     my @levels = ($symbparm,$mapparm,$what);
 6256:     foreach my $group (@{$groups}) {
 6257:         foreach my $level (@levels) {
 6258:              my $item = $courseid.'.['.$group.'].'.$level;
 6259:              push(@groupitems,$item);
 6260:         }
 6261:     }
 6262:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6263:                             $env{'course.'.$courseid.'.domain'},
 6264:                                      'course',@groupitems);
 6265:     return $coursereply;
 6266: }
 6267: 
 6268: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6269:     my ($courseid,@groups) = @_;
 6270:     @groups = sort(@groups);
 6271:     return @groups;
 6272: }
 6273: 
 6274: sub packages_tab_default {
 6275:     my ($uri,$varname)=@_;
 6276:     my (undef,$part,$name)=split(/\./,$varname);
 6277: 
 6278:     my (@extension,@specifics,$do_default);
 6279:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6280: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6281: 	if ($pack_type eq 'default') {
 6282: 	    $do_default=1;
 6283: 	} elsif ($pack_type eq 'extension') {
 6284: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6285: 	} elsif ($pack_part eq $part) {
 6286: 	    # only look at packages defaults for packages that this id is
 6287: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6288: 	}
 6289:     }
 6290:     # first look for a package that matches the requested part id
 6291:     foreach my $package (@specifics) {
 6292: 	my (undef,$pack_type,$pack_part)=@{$package};
 6293: 	next if ($pack_part ne $part);
 6294: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6295: 	    return $packagetab{"$pack_type&$name&default"};
 6296: 	}
 6297:     }
 6298:     # look for any possible matching non extension_ package
 6299:     foreach my $package (@specifics) {
 6300: 	my (undef,$pack_type,$pack_part)=@{$package};
 6301: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6302: 	    return $packagetab{"$pack_type&$name&default"};
 6303: 	}
 6304: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6305: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6306: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6307: 	}
 6308:     }
 6309:     # look for any posible extension_ match
 6310:     foreach my $package (@extension) {
 6311: 	my ($package,$pack_type)=@{$package};
 6312: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6313: 	    return $packagetab{"$pack_type&$name&default"};
 6314: 	}
 6315: 	if (defined($packagetab{$package."&$name&default"})) {
 6316: 	    return $packagetab{$package."&$name&default"};
 6317: 	}
 6318:     }
 6319:     # look for a global default setting
 6320:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6321: 	return $packagetab{"default&$name&default"};
 6322:     }
 6323:     return undef;
 6324: }
 6325: 
 6326: sub add_prefix_and_part {
 6327:     my ($prefix,$part)=@_;
 6328:     my $keyroot;
 6329:     if (defined($prefix) && $prefix !~ /^__/) {
 6330: 	# prefix that has a part already
 6331: 	$keyroot=$prefix;
 6332:     } elsif (defined($prefix)) {
 6333: 	# prefix that is missing a part
 6334: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6335:     } else {
 6336: 	# no prefix at all
 6337: 	if (defined($part)) { $keyroot='_'.$part; }
 6338:     }
 6339:     return $keyroot;
 6340: }
 6341: 
 6342: # ---------------------------------------------------------------- Get metadata
 6343: 
 6344: my %metaentry;
 6345: sub metadata {
 6346:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6347:     $uri=&declutter($uri);
 6348:     # if it is a non metadata possible uri return quickly
 6349:     if (($uri eq '') || 
 6350: 	(($uri =~ m|^/*adm/|) && 
 6351: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6352:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6353: 	($uri =~ m|home/$match_username/public_html/|)) {
 6354: 	return undef;
 6355:     }
 6356:     my $filename=$uri;
 6357:     $uri=~s/\.meta$//;
 6358: #
 6359: # Is the metadata already cached?
 6360: # Look at timestamp of caching
 6361: # Everything is cached by the main uri, libraries are never directly cached
 6362: #
 6363:     if (!defined($liburi)) {
 6364: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6365: 	if (defined($cached)) { return $result->{':'.$what}; }
 6366:     }
 6367:     {
 6368: #
 6369: # Is this a recursive call for a library?
 6370: #
 6371: #	if (! exists($metacache{$uri})) {
 6372: #	    $metacache{$uri}={};
 6373: #	}
 6374:         if ($liburi) {
 6375: 	    $liburi=&declutter($liburi);
 6376:             $filename=$liburi;
 6377:         } else {
 6378: 	    &devalidate_cache_new('meta',$uri);
 6379: 	    undef(%metaentry);
 6380: 	}
 6381:         my %metathesekeys=();
 6382:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6383: 	my $metastring;
 6384: 	if ($uri !~ m -^(editupload)/-) {
 6385: 	    my $file=&filelocation('',&clutter($filename));
 6386: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6387: 	    $metastring=&getfile($file);
 6388: 	}
 6389:         my $parser=HTML::LCParser->new(\$metastring);
 6390:         my $token;
 6391:         undef %metathesekeys;
 6392:         while ($token=$parser->get_token) {
 6393: 	    if ($token->[0] eq 'S') {
 6394: 		if (defined($token->[2]->{'package'})) {
 6395: #
 6396: # This is a package - get package info
 6397: #
 6398: 		    my $package=$token->[2]->{'package'};
 6399: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6400: 		    if (defined($token->[2]->{'id'})) { 
 6401: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6402: 		    }
 6403: 		    if ($metaentry{':packages'}) {
 6404: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6405: 		    } else {
 6406: 			$metaentry{':packages'}=$package.$keyroot;
 6407: 		    }
 6408: 		    foreach my $pack_entry (keys(%packagetab)) {
 6409: 			my $part=$keyroot;
 6410: 			$part=~s/^\_//;
 6411: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6412: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6413: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6414: 			    # ignore package.tab specified default values
 6415:                             # here &package_tab_default() will fetch those
 6416: 			    if ($subp eq 'default') { next; }
 6417: 			    my $value=$packagetab{$pack_entry};
 6418: 			    my $unikey;
 6419: 			    if ($pack =~ /_0$/) {
 6420: 				$unikey='parameter_0_'.$name;
 6421: 				$part=0;
 6422: 			    } else {
 6423: 				$unikey='parameter'.$keyroot.'_'.$name;
 6424: 			    }
 6425: 			    if ($subp eq 'display') {
 6426: 				$value.=' [Part: '.$part.']';
 6427: 			    }
 6428: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6429: 			    $metathesekeys{$unikey}=1;
 6430: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6431: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6432: 			    }
 6433: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6434: 				$metaentry{':'.$unikey}=
 6435: 				    $metaentry{':'.$unikey.'.default'};
 6436: 			    }
 6437: 			}
 6438: 		    }
 6439: 		} else {
 6440: #
 6441: # This is not a package - some other kind of start tag
 6442: #
 6443: 		    my $entry=$token->[1];
 6444: 		    my $unikey;
 6445: 		    if ($entry eq 'import') {
 6446: 			$unikey='';
 6447: 		    } else {
 6448: 			$unikey=$entry;
 6449: 		    }
 6450: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6451: 
 6452: 		    if (defined($token->[2]->{'id'})) { 
 6453: 			$unikey.='_'.$token->[2]->{'id'}; 
 6454: 		    }
 6455: 
 6456: 		    if ($entry eq 'import') {
 6457: #
 6458: # Importing a library here
 6459: #
 6460: 			if ($depthcount<20) {
 6461: 			    my $location=$parser->get_text('/import');
 6462: 			    my $dir=$filename;
 6463: 			    $dir=~s|[^/]*$||;
 6464: 			    $location=&filelocation($dir,$location);
 6465: 			    my $metadata = 
 6466: 				&metadata($uri,'keys', $location,$unikey,
 6467: 					  $depthcount+1);
 6468: 			    foreach my $meta (split(',',$metadata)) {
 6469: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6470: 				$metathesekeys{$meta}=1;
 6471: 			    }
 6472: 			}
 6473: 		    } else { 
 6474: 			
 6475: 			if (defined($token->[2]->{'name'})) { 
 6476: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6477: 			}
 6478: 			$metathesekeys{$unikey}=1;
 6479: 			foreach my $param (@{$token->[3]}) {
 6480: 			    $metaentry{':'.$unikey.'.'.$param} =
 6481: 				$token->[2]->{$param};
 6482: 			}
 6483: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6484: 			my $default=$metaentry{':'.$unikey.'.default'};
 6485: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6486: 		 # only ws inside the tag, and not in default, so use default
 6487: 		 # as value
 6488: 			    $metaentry{':'.$unikey}=$default;
 6489: 			} else {
 6490: 		  # either something interesting inside the tag or default
 6491:                   # uninteresting
 6492: 			    $metaentry{':'.$unikey}=$internaltext;
 6493: 			}
 6494: # end of not-a-package not-a-library import
 6495: 		    }
 6496: # end of not-a-package start tag
 6497: 		}
 6498: # the next is the end of "start tag"
 6499: 	    }
 6500: 	}
 6501: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6502: 	foreach my $key (keys(%packagetab)) {
 6503: 	    #no specific packages #how's our extension
 6504: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6505: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6506: 					 \%metathesekeys);
 6507: 	}
 6508: 	if (!exists($metaentry{':packages'})) {
 6509: 	    foreach my $key (keys(%packagetab)) {
 6510: 		#no specific packages well let's get default then
 6511: 		if ($key!~/^default&/) { next; }
 6512: 		&metadata_create_package_def($uri,$key,'default',
 6513: 					     \%metathesekeys);
 6514: 	    }
 6515: 	}
 6516: # are there custom rights to evaluate
 6517: 	if ($metaentry{':copyright'} eq 'custom') {
 6518: 
 6519:     #
 6520:     # Importing a rights file here
 6521:     #
 6522: 	    unless ($depthcount) {
 6523: 		my $location=$metaentry{':customdistributionfile'};
 6524: 		my $dir=$filename;
 6525: 		$dir=~s|[^/]*$||;
 6526: 		$location=&filelocation($dir,$location);
 6527: 		my $rights_metadata =
 6528: 		    &metadata($uri,'keys',$location,'_rights',
 6529: 			      $depthcount+1);
 6530: 		foreach my $rights (split(',',$rights_metadata)) {
 6531: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6532: 		    $metathesekeys{$rights}=1;
 6533: 		}
 6534: 	    }
 6535: 	}
 6536: 	# uniqifiy package listing
 6537: 	my %seen;
 6538: 	my @uniq_packages =
 6539: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6540: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6541: 
 6542: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6543: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6544: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6545: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6546: # this is the end of "was not already recently cached
 6547:     }
 6548:     return $metaentry{':'.$what};
 6549: }
 6550: 
 6551: sub metadata_create_package_def {
 6552:     my ($uri,$key,$package,$metathesekeys)=@_;
 6553:     my ($pack,$name,$subp)=split(/\&/,$key);
 6554:     if ($subp eq 'default') { next; }
 6555:     
 6556:     if (defined($metaentry{':packages'})) {
 6557: 	$metaentry{':packages'}.=','.$package;
 6558:     } else {
 6559: 	$metaentry{':packages'}=$package;
 6560:     }
 6561:     my $value=$packagetab{$key};
 6562:     my $unikey;
 6563:     $unikey='parameter_0_'.$name;
 6564:     $metaentry{':'.$unikey.'.part'}=0;
 6565:     $$metathesekeys{$unikey}=1;
 6566:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6567: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6568:     }
 6569:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6570: 	$metaentry{':'.$unikey}=
 6571: 	    $metaentry{':'.$unikey.'.default'};
 6572:     }
 6573: }
 6574: 
 6575: sub metadata_generate_part0 {
 6576:     my ($metadata,$metacache,$uri) = @_;
 6577:     my %allnames;
 6578:     foreach my $metakey (keys(%$metadata)) {
 6579: 	if ($metakey=~/^parameter\_(.*)/) {
 6580: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6581: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6582: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6583: 	    $allnames{$name}=$part;
 6584: 	  }
 6585: 	}
 6586:     }
 6587:     foreach my $name (keys(%allnames)) {
 6588:       $$metadata{"parameter_0_$name"}=1;
 6589:       my $key=":parameter_0_$name";
 6590:       $$metacache{"$key.part"}='0';
 6591:       $$metacache{"$key.name"}=$name;
 6592:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6593: 					   $allnames{$name}.'_'.$name.
 6594: 					   '.type'};
 6595:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6596: 			     '.display'};
 6597:       my $expr='[Part: '.$allnames{$name}.']';
 6598:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6599:       $$metacache{"$key.display"}=$olddis;
 6600:     }
 6601: }
 6602: 
 6603: # ------------------------------------------------------ Devalidate title cache
 6604: 
 6605: sub devalidate_title_cache {
 6606:     my ($url)=@_;
 6607:     if (!$env{'request.course.id'}) { return; }
 6608:     my $symb=&symbread($url);
 6609:     if (!$symb) { return; }
 6610:     my $key=$env{'request.course.id'}."\0".$symb;
 6611:     &devalidate_cache_new('title',$key);
 6612: }
 6613: 
 6614: # ------------------------------------------------- Get the title of a resource
 6615: 
 6616: sub gettitle {
 6617:     my $urlsymb=shift;
 6618:     my $symb=&symbread($urlsymb);
 6619:     if ($symb) {
 6620: 	my $key=$env{'request.course.id'}."\0".$symb;
 6621: 	my ($result,$cached)=&is_cached_new('title',$key);
 6622: 	if (defined($cached)) { 
 6623: 	    return $result;
 6624: 	}
 6625: 	my ($map,$resid,$url)=&decode_symb($symb);
 6626: 	my $title='';
 6627: 	my %bighash;
 6628: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6629: 		&GDBM_READER(),0640)) {
 6630: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6631: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6632: 	    untie %bighash;
 6633: 	}
 6634: 	$title=~s/\&colon\;/\:/gs;
 6635: 	if ($title) {
 6636: 	    return &do_cache_new('title',$key,$title,600);
 6637: 	}
 6638: 	$urlsymb=$url;
 6639:     }
 6640:     my $title=&metadata($urlsymb,'title');
 6641:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6642:     return $title;
 6643: }
 6644: 
 6645: sub get_slot {
 6646:     my ($which,$cnum,$cdom)=@_;
 6647:     if (!$cnum || !$cdom) {
 6648: 	(undef,my $courseid)=&whichuser();
 6649: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6650: 	$cnum=$env{'course.'.$courseid.'.num'};
 6651:     }
 6652:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6653:     my %slotinfo;
 6654:     if (exists($remembered{$key})) {
 6655: 	$slotinfo{$which} = $remembered{$key};
 6656:     } else {
 6657: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6658: 	&Apache::lonhomework::showhash(%slotinfo);
 6659: 	my ($tmp)=keys(%slotinfo);
 6660: 	if ($tmp=~/^error:/) { return (); }
 6661: 	$remembered{$key} = $slotinfo{$which};
 6662:     }
 6663:     if (ref($slotinfo{$which}) eq 'HASH') {
 6664: 	return %{$slotinfo{$which}};
 6665:     }
 6666:     return $slotinfo{$which};
 6667: }
 6668: # ------------------------------------------------- Update symbolic store links
 6669: 
 6670: sub symblist {
 6671:     my ($mapname,%newhash)=@_;
 6672:     $mapname=&deversion(&declutter($mapname));
 6673:     my %hash;
 6674:     if (($env{'request.course.fn'}) && (%newhash)) {
 6675:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6676:                       &GDBM_WRCREAT(),0640)) {
 6677: 	    foreach my $url (keys %newhash) {
 6678: 		next if ($url eq 'last_known'
 6679: 			 && $env{'form.no_update_last_known'});
 6680: 		$hash{declutter($url)}=&encode_symb($mapname,
 6681: 						    $newhash{$url}->[1],
 6682: 						    $newhash{$url}->[0]);
 6683:             }
 6684:             if (untie(%hash)) {
 6685: 		return 'ok';
 6686:             }
 6687:         }
 6688:     }
 6689:     return 'error';
 6690: }
 6691: 
 6692: # --------------------------------------------------------------- Verify a symb
 6693: 
 6694: sub symbverify {
 6695:     my ($symb,$thisurl)=@_;
 6696:     my $thisfn=$thisurl;
 6697:     $thisfn=&declutter($thisfn);
 6698: # direct jump to resource in page or to a sequence - will construct own symbs
 6699:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6700: # check URL part
 6701:     my ($map,$resid,$url)=&decode_symb($symb);
 6702: 
 6703:     unless ($url eq $thisfn) { return 0; }
 6704: 
 6705:     $symb=&symbclean($symb);
 6706:     $thisurl=&deversion($thisurl);
 6707:     $thisfn=&deversion($thisfn);
 6708: 
 6709:     my %bighash;
 6710:     my $okay=0;
 6711: 
 6712:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6713:                             &GDBM_READER(),0640)) {
 6714:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6715:         unless ($ids) { 
 6716:            $ids=$bighash{'ids_/'.$thisurl};
 6717:         }
 6718:         if ($ids) {
 6719: # ------------------------------------------------------------------- Has ID(s)
 6720: 	    foreach my $id (split(/\,/,$ids)) {
 6721: 	       my ($mapid,$resid)=split(/\./,$id);
 6722:                if (
 6723:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6724:    eq $symb) { 
 6725: 		   if (($env{'request.role.adv'}) ||
 6726: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6727: 		       $okay=1; 
 6728: 		   }
 6729: 	       }
 6730: 	   }
 6731:         }
 6732: 	untie(%bighash);
 6733:     }
 6734:     return $okay;
 6735: }
 6736: 
 6737: # --------------------------------------------------------------- Clean-up symb
 6738: 
 6739: sub symbclean {
 6740:     my $symb=shift;
 6741:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6742: # remove version from map
 6743:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6744: 
 6745: # remove version from URL
 6746:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6747: 
 6748: # remove wrapper
 6749: 
 6750:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6751:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6752:     return $symb;
 6753: }
 6754: 
 6755: # ---------------------------------------------- Split symb to find map and url
 6756: 
 6757: sub encode_symb {
 6758:     my ($map,$resid,$url)=@_;
 6759:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6760: }
 6761: 
 6762: sub decode_symb {
 6763:     my $symb=shift;
 6764:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6765:     my ($map,$resid,$url)=split(/___/,$symb);
 6766:     return (&fixversion($map),$resid,&fixversion($url));
 6767: }
 6768: 
 6769: sub fixversion {
 6770:     my $fn=shift;
 6771:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6772:     my %bighash;
 6773:     my $uri=&clutter($fn);
 6774:     my $key=$env{'request.course.id'}.'_'.$uri;
 6775: # is this cached?
 6776:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6777:     if (defined($cached)) { return $result; }
 6778: # unfortunately not cached, or expired
 6779:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6780: 	    &GDBM_READER(),0640)) {
 6781:  	if ($bighash{'version_'.$uri}) {
 6782:  	    my $version=$bighash{'version_'.$uri};
 6783:  	    unless (($version eq 'mostrecent') || 
 6784: 		    ($version==&getversion($uri))) {
 6785:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6786:  	    }
 6787:  	}
 6788:  	untie %bighash;
 6789:     }
 6790:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6791: }
 6792: 
 6793: sub deversion {
 6794:     my $url=shift;
 6795:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6796:     return $url;
 6797: }
 6798: 
 6799: # ------------------------------------------------------ Return symb list entry
 6800: 
 6801: sub symbread {
 6802:     my ($thisfn,$donotrecurse)=@_;
 6803:     my $cache_str='request.symbread.cached.'.$thisfn;
 6804:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6805: # no filename provided? try from environment
 6806:     unless ($thisfn) {
 6807:         if ($env{'request.symb'}) {
 6808: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6809: 	}
 6810: 	$thisfn=$env{'request.filename'};
 6811:     }
 6812:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6813: # is that filename actually a symb? Verify, clean, and return
 6814:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6815: 	if (&symbverify($thisfn,$1)) {
 6816: 	    return $env{$cache_str}=&symbclean($thisfn);
 6817: 	}
 6818:     }
 6819:     $thisfn=declutter($thisfn);
 6820:     my %hash;
 6821:     my %bighash;
 6822:     my $syval='';
 6823:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6824:         my $targetfn = $thisfn;
 6825:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6826:             $targetfn = 'adm/wrapper/'.$thisfn;
 6827:         }
 6828: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6829: 	    $targetfn=$1;
 6830: 	}
 6831:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6832:                       &GDBM_READER(),0640)) {
 6833: 	    $syval=$hash{$targetfn};
 6834:             untie(%hash);
 6835:         }
 6836: # ---------------------------------------------------------- There was an entry
 6837:         if ($syval) {
 6838: 	    #unless ($syval=~/\_\d+$/) {
 6839: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6840: 		    #&appenv('request.ambiguous' => $thisfn);
 6841: 		    #return $env{$cache_str}='';
 6842: 		#}    
 6843: 		#$syval.=$1;
 6844: 	    #}
 6845:         } else {
 6846: # ------------------------------------------------------- Was not in symb table
 6847:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6848:                             &GDBM_READER(),0640)) {
 6849: # ---------------------------------------------- Get ID(s) for current resource
 6850:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6851:               unless ($ids) { 
 6852:                  $ids=$bighash{'ids_/'.$thisfn};
 6853:               }
 6854:               unless ($ids) {
 6855: # alias?
 6856: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6857:               }
 6858:               if ($ids) {
 6859: # ------------------------------------------------------------------- Has ID(s)
 6860:                  my @possibilities=split(/\,/,$ids);
 6861:                  if ($#possibilities==0) {
 6862: # ----------------------------------------------- There is only one possibility
 6863: 		     my ($mapid,$resid)=split(/\./,$ids);
 6864: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6865: 						    $resid,$thisfn);
 6866:                  } elsif (!$donotrecurse) {
 6867: # ------------------------------------------ There is more than one possibility
 6868:                      my $realpossible=0;
 6869:                      foreach my $id (@possibilities) {
 6870: 			 my $file=$bighash{'src_'.$id};
 6871:                          if (&allowed('bre',$file)) {
 6872:          		    my ($mapid,$resid)=split(/\./,$id);
 6873:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6874: 				$realpossible++;
 6875:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6876: 						    $resid,$thisfn);
 6877:                             }
 6878: 			 }
 6879:                      }
 6880: 		     if ($realpossible!=1) { $syval=''; }
 6881:                  } else {
 6882:                      $syval='';
 6883:                  }
 6884: 	      }
 6885:               untie(%bighash)
 6886:            }
 6887:         }
 6888:         if ($syval) {
 6889: 	    return $env{$cache_str}=$syval;
 6890:         }
 6891:     }
 6892:     &appenv('request.ambiguous' => $thisfn);
 6893:     return $env{$cache_str}='';
 6894: }
 6895: 
 6896: # ---------------------------------------------------------- Return random seed
 6897: 
 6898: sub numval {
 6899:     my $txt=shift;
 6900:     $txt=~tr/A-J/0-9/;
 6901:     $txt=~tr/a-j/0-9/;
 6902:     $txt=~tr/K-T/0-9/;
 6903:     $txt=~tr/k-t/0-9/;
 6904:     $txt=~tr/U-Z/0-5/;
 6905:     $txt=~tr/u-z/0-5/;
 6906:     $txt=~s/\D//g;
 6907:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6908:     return int($txt);
 6909: }
 6910: 
 6911: sub numval2 {
 6912:     my $txt=shift;
 6913:     $txt=~tr/A-J/0-9/;
 6914:     $txt=~tr/a-j/0-9/;
 6915:     $txt=~tr/K-T/0-9/;
 6916:     $txt=~tr/k-t/0-9/;
 6917:     $txt=~tr/U-Z/0-5/;
 6918:     $txt=~tr/u-z/0-5/;
 6919:     $txt=~s/\D//g;
 6920:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6921:     my $total;
 6922:     foreach my $val (@txts) { $total+=$val; }
 6923:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6924:     return int($total);
 6925: }
 6926: 
 6927: sub numval3 {
 6928:     use integer;
 6929:     my $txt=shift;
 6930:     $txt=~tr/A-J/0-9/;
 6931:     $txt=~tr/a-j/0-9/;
 6932:     $txt=~tr/K-T/0-9/;
 6933:     $txt=~tr/k-t/0-9/;
 6934:     $txt=~tr/U-Z/0-5/;
 6935:     $txt=~tr/u-z/0-5/;
 6936:     $txt=~s/\D//g;
 6937:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6938:     my $total;
 6939:     foreach my $val (@txts) { $total+=$val; }
 6940:     if ($_64bit) { $total=(($total<<32)>>32); }
 6941:     return $total;
 6942: }
 6943: 
 6944: sub digest {
 6945:     my ($data)=@_;
 6946:     my $digest=&Digest::MD5::md5($data);
 6947:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6948:     my ($e,$f);
 6949:     {
 6950:         use integer;
 6951:         $e=($a+$b);
 6952:         $f=($c+$d);
 6953:         if ($_64bit) {
 6954:             $e=(($e<<32)>>32);
 6955:             $f=(($f<<32)>>32);
 6956:         }
 6957:     }
 6958:     if (wantarray) {
 6959: 	return ($e,$f);
 6960:     } else {
 6961: 	my $g;
 6962: 	{
 6963: 	    use integer;
 6964: 	    $g=($e+$f);
 6965: 	    if ($_64bit) {
 6966: 		$g=(($g<<32)>>32);
 6967: 	    }
 6968: 	}
 6969: 	return $g;
 6970:     }
 6971: }
 6972: 
 6973: sub latest_rnd_algorithm_id {
 6974:     return '64bit5';
 6975: }
 6976: 
 6977: sub get_rand_alg {
 6978:     my ($courseid)=@_;
 6979:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6980:     if ($courseid) {
 6981: 	return $env{"course.$courseid.rndseed"};
 6982:     }
 6983:     return &latest_rnd_algorithm_id();
 6984: }
 6985: 
 6986: sub validCODE {
 6987:     my ($CODE)=@_;
 6988:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6989:     return 0;
 6990: }
 6991: 
 6992: sub getCODE {
 6993:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6994:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6995: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6996: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6997: 	return $Apache::lonhomework::history{'resource.CODE'};
 6998:     }
 6999:     return undef;
 7000: }
 7001: 
 7002: sub rndseed {
 7003:     my ($symb,$courseid,$domain,$username)=@_;
 7004:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7005:     if (!$symb) {
 7006: 	unless ($symb=$wsymb) { return time; }
 7007:     }
 7008:     if (!$courseid) { $courseid=$wcourseid; }
 7009:     if (!$domain) { $domain=$wdomain; }
 7010:     if (!$username) { $username=$wusername }
 7011:     my $which=&get_rand_alg();
 7012: 
 7013:     if (defined(&getCODE())) {
 7014: 	if ($which eq '64bit5') {
 7015: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7016: 	} elsif ($which eq '64bit4') {
 7017: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7018: 	} else {
 7019: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7020: 	}
 7021:     } elsif ($which eq '64bit5') {
 7022: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7023:     } elsif ($which eq '64bit4') {
 7024: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7025:     } elsif ($which eq '64bit3') {
 7026: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7027:     } elsif ($which eq '64bit2') {
 7028: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7029:     } elsif ($which eq '64bit') {
 7030: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7031:     }
 7032:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7033: }
 7034: 
 7035: sub rndseed_32bit {
 7036:     my ($symb,$courseid,$domain,$username)=@_;
 7037:     {
 7038: 	use integer;
 7039: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7040: 	my $symbseed=numval($symb) << 22;
 7041: 	my $namechck=unpack("%32C*",$username) << 17;
 7042: 	my $nameseed=numval($username) << 12;
 7043: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7044: 	my $courseseed=unpack("%32C*",$courseid);
 7045: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7046: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7047: 	#&logthis("rndseed :$num:$symb");
 7048: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7049: 	return $num;
 7050:     }
 7051: }
 7052: 
 7053: sub rndseed_64bit {
 7054:     my ($symb,$courseid,$domain,$username)=@_;
 7055:     {
 7056: 	use integer;
 7057: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7058: 	my $symbseed=numval($symb) << 10;
 7059: 	my $namechck=unpack("%32S*",$username);
 7060: 	
 7061: 	my $nameseed=numval($username) << 21;
 7062: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7063: 	my $courseseed=unpack("%32S*",$courseid);
 7064: 	
 7065: 	my $num1=$symbchck+$symbseed+$namechck;
 7066: 	my $num2=$nameseed+$domainseed+$courseseed;
 7067: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7068: 	#&logthis("rndseed :$num:$symb");
 7069: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7070: 	return "$num1,$num2";
 7071:     }
 7072: }
 7073: 
 7074: sub rndseed_64bit2 {
 7075:     my ($symb,$courseid,$domain,$username)=@_;
 7076:     {
 7077: 	use integer;
 7078: 	# strings need to be an even # of cahracters long, it it is odd the
 7079:         # last characters gets thrown away
 7080: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7081: 	my $symbseed=numval($symb) << 10;
 7082: 	my $namechck=unpack("%32S*",$username.' ');
 7083: 	
 7084: 	my $nameseed=numval($username) << 21;
 7085: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7086: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7087: 	
 7088: 	my $num1=$symbchck+$symbseed+$namechck;
 7089: 	my $num2=$nameseed+$domainseed+$courseseed;
 7090: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7091: 	#&logthis("rndseed :$num:$symb");
 7092: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7093: 	return "$num1,$num2";
 7094:     }
 7095: }
 7096: 
 7097: sub rndseed_64bit3 {
 7098:     my ($symb,$courseid,$domain,$username)=@_;
 7099:     {
 7100: 	use integer;
 7101: 	# strings need to be an even # of cahracters long, it it is odd the
 7102:         # last characters gets thrown away
 7103: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7104: 	my $symbseed=numval2($symb) << 10;
 7105: 	my $namechck=unpack("%32S*",$username.' ');
 7106: 	
 7107: 	my $nameseed=numval2($username) << 21;
 7108: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7109: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7110: 	
 7111: 	my $num1=$symbchck+$symbseed+$namechck;
 7112: 	my $num2=$nameseed+$domainseed+$courseseed;
 7113: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7114: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7115: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7116: 	
 7117: 	return "$num1:$num2";
 7118:     }
 7119: }
 7120: 
 7121: sub rndseed_64bit4 {
 7122:     my ($symb,$courseid,$domain,$username)=@_;
 7123:     {
 7124: 	use integer;
 7125: 	# strings need to be an even # of cahracters long, it it is odd the
 7126:         # last characters gets thrown away
 7127: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7128: 	my $symbseed=numval3($symb) << 10;
 7129: 	my $namechck=unpack("%32S*",$username.' ');
 7130: 	
 7131: 	my $nameseed=numval3($username) << 21;
 7132: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7133: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7134: 	
 7135: 	my $num1=$symbchck+$symbseed+$namechck;
 7136: 	my $num2=$nameseed+$domainseed+$courseseed;
 7137: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7138: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7139: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7140: 	
 7141: 	return "$num1:$num2";
 7142:     }
 7143: }
 7144: 
 7145: sub rndseed_64bit5 {
 7146:     my ($symb,$courseid,$domain,$username)=@_;
 7147:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7148:     return "$num1:$num2";
 7149: }
 7150: 
 7151: sub rndseed_CODE_64bit {
 7152:     my ($symb,$courseid,$domain,$username)=@_;
 7153:     {
 7154: 	use integer;
 7155: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7156: 	my $symbseed=numval2($symb);
 7157: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7158: 	my $CODEseed=numval(&getCODE());
 7159: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7160: 	my $num1=$symbseed+$CODEchck;
 7161: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7162: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7163: 	#&logthis("rndseed :$num1:$num2:$symb");
 7164: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7165: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7166: 	return "$num1:$num2";
 7167:     }
 7168: }
 7169: 
 7170: sub rndseed_CODE_64bit4 {
 7171:     my ($symb,$courseid,$domain,$username)=@_;
 7172:     {
 7173: 	use integer;
 7174: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7175: 	my $symbseed=numval3($symb);
 7176: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7177: 	my $CODEseed=numval3(&getCODE());
 7178: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7179: 	my $num1=$symbseed+$CODEchck;
 7180: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7181: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7182: 	#&logthis("rndseed :$num1:$num2:$symb");
 7183: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7184: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7185: 	return "$num1:$num2";
 7186:     }
 7187: }
 7188: 
 7189: sub rndseed_CODE_64bit5 {
 7190:     my ($symb,$courseid,$domain,$username)=@_;
 7191:     my $code = &getCODE();
 7192:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7193:     return "$num1:$num2";
 7194: }
 7195: 
 7196: sub setup_random_from_rndseed {
 7197:     my ($rndseed)=@_;
 7198:     if ($rndseed =~/([,:])/) {
 7199: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7200: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7201:     } else {
 7202: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7203:     }
 7204: }
 7205: 
 7206: sub latest_receipt_algorithm_id {
 7207:     return 'receipt3';
 7208: }
 7209: 
 7210: sub recunique {
 7211:     my $fucourseid=shift;
 7212:     my $unique;
 7213:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7214: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7215: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7216:     } else {
 7217: 	$unique=$perlvar{'lonReceipt'};
 7218:     }
 7219:     return unpack("%32C*",$unique);
 7220: }
 7221: 
 7222: sub recprefix {
 7223:     my $fucourseid=shift;
 7224:     my $prefix;
 7225:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7226: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7227: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7228:     } else {
 7229: 	$prefix=$perlvar{'lonHostID'};
 7230:     }
 7231:     return unpack("%32C*",$prefix);
 7232: }
 7233: 
 7234: sub ireceipt {
 7235:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7236: 
 7237:     my $return =&recprefix($fucourseid).'-';
 7238: 
 7239:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7240: 	$env{'request.state'} eq 'construct') {
 7241: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7242: 	return $return;
 7243:     }
 7244: 
 7245:     my $cuname=unpack("%32C*",$funame);
 7246:     my $cudom=unpack("%32C*",$fudom);
 7247:     my $cucourseid=unpack("%32C*",$fucourseid);
 7248:     my $cusymb=unpack("%32C*",$fusymb);
 7249:     my $cunique=&recunique($fucourseid);
 7250:     my $cpart=unpack("%32S*",$part);
 7251:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7252: 
 7253: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7254: 			       
 7255: 	$return.= ($cunique%$cuname+
 7256: 		   $cunique%$cudom+
 7257: 		   $cusymb%$cuname+
 7258: 		   $cusymb%$cudom+
 7259: 		   $cucourseid%$cuname+
 7260: 		   $cucourseid%$cudom+
 7261: 		   $cpart%$cuname+
 7262: 		   $cpart%$cudom);
 7263:     } else {
 7264: 	$return.= ($cunique%$cuname+
 7265: 		   $cunique%$cudom+
 7266: 		   $cusymb%$cuname+
 7267: 		   $cusymb%$cudom+
 7268: 		   $cucourseid%$cuname+
 7269: 		   $cucourseid%$cudom);
 7270:     }
 7271:     return $return;
 7272: }
 7273: 
 7274: sub receipt {
 7275:     my ($part)=@_;
 7276:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7277:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7278: }
 7279: 
 7280: sub whichuser {
 7281:     my ($passedsymb)=@_;
 7282:     my ($symb,$courseid,$domain,$name,$publicuser);
 7283:     if (defined($env{'form.grade_symb'})) {
 7284: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7285: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7286: 	if (!$allowed &&
 7287: 	    exists($env{'request.course.sec'}) &&
 7288: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7289: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7290: 			      '/'.$env{'request.course.sec'});
 7291: 	}
 7292: 	if ($allowed) {
 7293: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7294: 	    $courseid=$tmp_courseid;
 7295: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7296: 	    ($name)=&get_env_multiple('form.grade_username');
 7297: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7298: 	}
 7299:     }
 7300:     if (!$passedsymb) {
 7301: 	$symb=&symbread();
 7302:     } else {
 7303: 	$symb=$passedsymb;
 7304:     }
 7305:     $courseid=$env{'request.course.id'};
 7306:     $domain=$env{'user.domain'};
 7307:     $name=$env{'user.name'};
 7308:     if ($name eq 'public' && $domain eq 'public') {
 7309: 	if (!defined($env{'form.username'})) {
 7310: 	    $env{'form.username'}.=time.rand(10000000);
 7311: 	}
 7312: 	$name.=$env{'form.username'};
 7313:     }
 7314:     return ($symb,$courseid,$domain,$name,$publicuser);
 7315: 
 7316: }
 7317: 
 7318: # ------------------------------------------------------------ Serves up a file
 7319: # returns either the contents of the file or 
 7320: # -1 if the file doesn't exist
 7321: #
 7322: # if the target is a file that was uploaded via DOCS, 
 7323: # a check will be made to see if a current copy exists on the local server,
 7324: # if it does this will be served, otherwise a copy will be retrieved from
 7325: # the home server for the course and stored in /home/httpd/html/userfiles on
 7326: # the local server.   
 7327: 
 7328: sub getfile {
 7329:     my ($file) = @_;
 7330:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7331:     &repcopy($file);
 7332:     return &readfile($file);
 7333: }
 7334: 
 7335: sub repcopy_userfile {
 7336:     my ($file)=@_;
 7337:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7338:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7339:     my ($cdom,$cnum,$filename) = 
 7340: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7341:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7342:     if (-e "$file") {
 7343: # we already have a local copy, check it out
 7344: 	my @fileinfo = stat($file);
 7345: 	my $rtncode;
 7346: 	my $info;
 7347: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7348: 	if ($lwpresp ne 'ok') {
 7349: # there is no such file anymore, even though we had a local copy
 7350: 	    if ($rtncode eq '404') {
 7351: 		unlink($file);
 7352: 	    }
 7353: 	    return -1;
 7354: 	}
 7355: 	if ($info < $fileinfo[9]) {
 7356: # nice, the file we have is up-to-date, just say okay
 7357: 	    return 'ok';
 7358: 	} else {
 7359: # the file is outdated, get rid of it
 7360: 	    unlink($file);
 7361: 	}
 7362:     }
 7363: # one way or the other, at this point, we don't have the file
 7364: # construct the correct path for the file
 7365:     my @parts = ($cdom,$cnum); 
 7366:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7367: 	push @parts, split(/\//,$1);
 7368:     }
 7369:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7370:     foreach my $part (@parts) {
 7371: 	$path .= '/'.$part;
 7372: 	if (!-e $path) {
 7373: 	    mkdir($path,0770);
 7374: 	}
 7375:     }
 7376: # now the path exists for sure
 7377: # get a user agent
 7378:     my $ua=new LWP::UserAgent;
 7379:     my $transferfile=$file.'.in.transfer';
 7380: # FIXME: this should flock
 7381:     if (-e $transferfile) { return 'ok'; }
 7382:     my $request;
 7383:     $uri=~s/^\///;
 7384:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7385:     my $response=$ua->request($request,$transferfile);
 7386: # did it work?
 7387:     if ($response->is_error()) {
 7388: 	unlink($transferfile);
 7389: 	&logthis("Userfile repcopy failed for $uri");
 7390: 	return -1;
 7391:     }
 7392: # worked, rename the transfer file
 7393:     rename($transferfile,$file);
 7394:     return 'ok';
 7395: }
 7396: 
 7397: sub tokenwrapper {
 7398:     my $uri=shift;
 7399:     $uri=~s|^http\://([^/]+)||;
 7400:     $uri=~s|^/||;
 7401:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7402:     my $token=$1;
 7403:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7404:     if ($udom && $uname && $file) {
 7405: 	$file=~s|(\?\.*)*$||;
 7406:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7407:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7408:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7409:                                '&tokenissued='.$perlvar{'lonHostID'};
 7410:     } else {
 7411:         return '/adm/notfound.html';
 7412:     }
 7413: }
 7414: 
 7415: # call with reqtype HEAD: get last modification time
 7416: # call with reqtype GET: get the file contents
 7417: # Do not call this with reqtype GET for large files! It loads everything into memory
 7418: #
 7419: sub getuploaded {
 7420:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7421:     $uri=~s/^\///;
 7422:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7423:     my $ua=new LWP::UserAgent;
 7424:     my $request=new HTTP::Request($reqtype,$uri);
 7425:     my $response=$ua->request($request);
 7426:     $$rtncode = $response->code;
 7427:     if (! $response->is_success()) {
 7428: 	return 'failed';
 7429:     }      
 7430:     if ($reqtype eq 'HEAD') {
 7431: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7432:     } elsif ($reqtype eq 'GET') {
 7433: 	$$info = $response->content;
 7434:     }
 7435:     return 'ok';
 7436: }
 7437: 
 7438: sub readfile {
 7439:     my $file = shift;
 7440:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7441:     my $fh;
 7442:     open($fh,"<$file");
 7443:     my $a='';
 7444:     while (my $line = <$fh>) { $a .= $line; }
 7445:     return $a;
 7446: }
 7447: 
 7448: sub filelocation {
 7449:     my ($dir,$file) = @_;
 7450:     my $location;
 7451:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7452: 
 7453:     if ($file =~ m-^/adm/-) {
 7454: 	$file=~s-^/adm/wrapper/-/-;
 7455: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7456:     }
 7457:     if ($file=~m:^/~:) { # is a contruction space reference
 7458:         $location = $file;
 7459:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7460:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7461: 	# is a correct contruction space reference
 7462:         $location = $file;
 7463:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7464:         my ($udom,$uname,$filename)=
 7465:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7466:         my $home=&homeserver($uname,$udom);
 7467:         my $is_me=0;
 7468:         my @ids=&current_machine_ids();
 7469:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7470:         if ($is_me) {
 7471:   	    $location=&propath($udom,$uname).
 7472:   	      '/userfiles/'.$filename;
 7473:         } else {
 7474:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7475:   	      $udom.'/'.$uname.'/'.$filename;
 7476:         }
 7477:     } else {
 7478:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7479:         $file=~s:^/res/:/:;
 7480:         if ( !( $file =~ m:^/:) ) {
 7481:             $location = $dir. '/'.$file;
 7482:         } else {
 7483:             $location = '/home/httpd/html/res'.$file;
 7484:         }
 7485:     }
 7486:     $location=~s://+:/:g; # remove duplicate /
 7487:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7488:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7489:     return $location;
 7490: }
 7491: 
 7492: sub hreflocation {
 7493:     my ($dir,$file)=@_;
 7494:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7495: 	$file=filelocation($dir,$file);
 7496:     } elsif ($file=~m-^/adm/-) {
 7497: 	$file=~s-^/adm/wrapper/-/-;
 7498: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7499:     }
 7500:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7501: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7502:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7503: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7504:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7505: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7506: 	    -/uploaded/$1/$2/-x;
 7507:     }
 7508:     return $file;
 7509: }
 7510: 
 7511: sub current_machine_domains {
 7512:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7513: }
 7514: 
 7515: sub machine_domains {
 7516:     my ($hostname) = @_;
 7517:     my @domains;
 7518:     my %hostname = &all_hostnames();
 7519:     while( my($id, $name) = each(%hostname)) {
 7520: #	&logthis("-$id-$name-$hostname-");
 7521: 	if ($hostname eq $name) {
 7522: 	    push(@domains,&host_domain($id));
 7523: 	}
 7524:     }
 7525:     return @domains;
 7526: }
 7527: 
 7528: sub current_machine_ids {
 7529:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7530: }
 7531: 
 7532: sub machine_ids {
 7533:     my ($hostname) = @_;
 7534:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7535:     my @ids;
 7536:     my %hostname = &all_hostnames();
 7537:     while( my($id, $name) = each(%hostname)) {
 7538: #	&logthis("-$id-$name-$hostname-");
 7539: 	if ($hostname eq $name) {
 7540: 	    push(@ids,$id);
 7541: 	}
 7542:     }
 7543:     return @ids;
 7544: }
 7545: 
 7546: sub additional_machine_domains {
 7547:     my @domains;
 7548:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7549:     while( my $line = <$fh>) {
 7550:         $line =~ s/\s//g;
 7551:         push(@domains,$line);
 7552:     }
 7553:     return @domains;
 7554: }
 7555: 
 7556: sub default_login_domain {
 7557:     my $domain = $perlvar{'lonDefDomain'};
 7558:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7559:     foreach my $posdom (&current_machine_domains(),
 7560:                         &additional_machine_domains()) {
 7561:         if (lc($posdom) eq lc($testdomain)) {
 7562:             $domain=$posdom;
 7563:             last;
 7564:         }
 7565:     }
 7566:     return $domain;
 7567: }
 7568: 
 7569: # ------------------------------------------------------------- Declutters URLs
 7570: 
 7571: sub declutter {
 7572:     my $thisfn=shift;
 7573:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7574:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7575:     $thisfn=~s/^\///;
 7576:     $thisfn=~s|^adm/wrapper/||;
 7577:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7578:     $thisfn=~s/^res\///;
 7579:     $thisfn=~s/\?.+$//;
 7580:     return $thisfn;
 7581: }
 7582: 
 7583: # ------------------------------------------------------------- Clutter up URLs
 7584: 
 7585: sub clutter {
 7586:     my $thisfn='/'.&declutter(shift);
 7587:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7588:        $thisfn='/res'.$thisfn; 
 7589:     }
 7590:     if ($thisfn !~m|/adm|) {
 7591: 	if ($thisfn =~ m|/ext/|) {
 7592: 	    $thisfn='/adm/wrapper'.$thisfn;
 7593: 	} else {
 7594: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7595: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7596: 	    if ($embstyle eq 'ssi'
 7597: 		|| ($embstyle eq 'hdn')
 7598: 		|| ($embstyle eq 'rat')
 7599: 		|| ($embstyle eq 'prv')
 7600: 		|| ($embstyle eq 'ign')) {
 7601: 		#do nothing with these
 7602: 	    } elsif (($embstyle eq 'img') 
 7603: 		|| ($embstyle eq 'emb')
 7604: 		|| ($embstyle eq 'wrp')) {
 7605: 		$thisfn='/adm/wrapper'.$thisfn;
 7606: 	    } elsif ($embstyle eq 'unk'
 7607: 		     && $thisfn!~/\.(sequence|page)$/) {
 7608: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7609: 	    } else {
 7610: #		&logthis("Got a blank emb style");
 7611: 	    }
 7612: 	}
 7613:     }
 7614:     return $thisfn;
 7615: }
 7616: 
 7617: sub clutter_with_no_wrapper {
 7618:     my $uri = &clutter(shift);
 7619:     if ($uri =~ m-^/adm/-) {
 7620: 	$uri =~ s-^/adm/wrapper/-/-;
 7621: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7622:     }
 7623:     return $uri;
 7624: }
 7625: 
 7626: sub freeze_escape {
 7627:     my ($value)=@_;
 7628:     if (ref($value)) {
 7629: 	$value=&nfreeze($value);
 7630: 	return '__FROZEN__'.&escape($value);
 7631:     }
 7632:     return &escape($value);
 7633: }
 7634: 
 7635: 
 7636: sub thaw_unescape {
 7637:     my ($value)=@_;
 7638:     if ($value =~ /^__FROZEN__/) {
 7639: 	substr($value,0,10,undef);
 7640: 	$value=&unescape($value);
 7641: 	return &thaw($value);
 7642:     }
 7643:     return &unescape($value);
 7644: }
 7645: 
 7646: sub correct_line_ends {
 7647:     my ($result)=@_;
 7648:     $$result =~s/\r\n/\n/mg;
 7649:     $$result =~s/\r/\n/mg;
 7650: }
 7651: # ================================================================ Main Program
 7652: 
 7653: sub goodbye {
 7654:    &logthis("Starting Shut down");
 7655: #not converted to using infrastruture and probably shouldn't be
 7656:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7657: #converted
 7658: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7659:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7660: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7661: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7662: #1.1 only
 7663: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7664: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7665: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7666: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7667:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7668:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7669:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7670:    &flushcourselogs();
 7671:    &logthis("Shutting down");
 7672: }
 7673: 
 7674: sub get_dns {
 7675:     my ($url,$func) = @_;
 7676:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7677:     foreach my $dns (<$config>) {
 7678: 	next if ($dns !~ /^\^(\S*)/x);
 7679: 	$dns = $1;
 7680: 	my $ua=new LWP::UserAgent;
 7681: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7682: 	my $response=$ua->request($request);
 7683: 	next if ($response->is_error());
 7684: 	my @content = split("\n",$response->content);
 7685: 	&$func(\@content);
 7686:     }
 7687:     close($config);
 7688: }
 7689: # ------------------------------------------------------------ Read domain file
 7690: {
 7691:     my $loaded;
 7692:     my %domain;
 7693: 
 7694:     sub parse_domain_tab {
 7695: 	my ($lines) = @_;
 7696: 	foreach my $line (@$lines) {
 7697: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7698: 
 7699: 	    chomp($line);
 7700: 	    my ($name,@elements) = split(/:/,$line,9);
 7701: 	    my %this_domain;
 7702: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7703: 			       'lang_def', 'city', 'longi', 'lati',
 7704: 			       'primary') {
 7705: 		$this_domain{$field} = shift(@elements);
 7706: 	    }
 7707: 	    $domain{$name} = \%this_domain;
 7708: 	}
 7709:     }
 7710: 
 7711:     sub reset_domain_info {
 7712: 	undef($loaded);
 7713: 	undef(%domain);
 7714:     }
 7715: 
 7716:     sub load_domain_tab {
 7717: 	&get_dns('/adm/dns/domain',\&parse_domain_tab);
 7718: 	my $fh;
 7719: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7720: 	    my @lines = <$fh>;
 7721: 	    &parse_domain_tab(\@lines);
 7722: 	}
 7723: 	close($fh);
 7724: 	$loaded = 1;
 7725:     }
 7726: 
 7727:     sub domain {
 7728: 	&load_domain_tab() if (!$loaded);
 7729: 
 7730: 	my ($name,$what) = @_;
 7731: 	return if ( !exists($domain{$name}) );
 7732: 
 7733: 	if (!$what) {
 7734: 	    return $domain{$name}{'description'};
 7735: 	}
 7736: 	return $domain{$name}{$what};
 7737:     }
 7738: }
 7739: 
 7740: 
 7741: # ------------------------------------------------------------- Read hosts file
 7742: {
 7743:     my %hostname;
 7744:     my %hostdom;
 7745:     my %libserv;
 7746:     my $loaded;
 7747: 
 7748:     sub parse_hosts_tab {
 7749: 	my ($file) = @_;
 7750: 	foreach my $configline (@$file) {
 7751: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7752: 	    next if ($configline =~ /^\^/);
 7753: 	    chomp($configline);
 7754: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7755: 	    $name=~s/\s//g;
 7756: 	    if ($id && $domain && $role && $name) {
 7757: 		$hostname{$id}=$name;
 7758: 		$hostdom{$id}=$domain;
 7759: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7760: 	    }
 7761: 	}
 7762:     }
 7763:     
 7764:     sub reset_hosts_info {
 7765: 	&reset_domain_info();
 7766: 	&reset_hosts_ip_info();
 7767: 	undef(%hostname);
 7768: 	undef(%hostdom);
 7769: 	undef(%libserv);
 7770: 	undef($loaded);
 7771:     }
 7772: 
 7773:     sub load_hosts_tab {
 7774: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab);
 7775: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7776: 	my @config = <$config>;
 7777: 	&parse_hosts_tab(\@config);
 7778: 	close($config);
 7779: 	$loaded=1;
 7780:     }
 7781: 
 7782:     sub hostname {
 7783: 	&load_hosts_tab() if (!$loaded);
 7784: 
 7785: 	my ($lonid) = @_;
 7786: 	return $hostname{$lonid};
 7787:     }
 7788: 
 7789:     sub all_hostnames {
 7790: 	&load_hosts_tab() if (!$loaded);
 7791: 
 7792: 	return %hostname;
 7793:     }
 7794: 
 7795:     sub is_library {
 7796: 	&load_hosts_tab() if (!$loaded);
 7797: 
 7798: 	return exists($libserv{$_[0]});
 7799:     }
 7800: 
 7801:     sub all_library {
 7802: 	&load_hosts_tab() if (!$loaded);
 7803: 
 7804: 	return %libserv;
 7805:     }
 7806: 
 7807:     sub get_servers {
 7808: 	&load_hosts_tab() if (!$loaded);
 7809: 
 7810: 	my ($domain,$type) = @_;
 7811: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7812: 	                                          : %hostname;
 7813: 	my %result;
 7814: 	if (ref($domain) eq 'ARRAY') {
 7815: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7816: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7817: 		    $result{$host} = $hostname;
 7818: 		}
 7819: 	    }
 7820: 	} else {
 7821: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7822: 		if ($hostdom{$host} eq $domain) {
 7823: 		    $result{$host} = $hostname;
 7824: 		}
 7825: 	    }
 7826: 	}
 7827: 	return %result;
 7828:     }
 7829: 
 7830:     sub host_domain {
 7831: 	&load_hosts_tab() if (!$loaded);
 7832: 
 7833: 	my ($lonid) = @_;
 7834: 	return $hostdom{$lonid};
 7835:     }
 7836: 
 7837:     sub all_domains {
 7838: 	&load_hosts_tab() if (!$loaded);
 7839: 
 7840: 	my %seen;
 7841: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7842: 	return @uniq;
 7843:     }
 7844: }
 7845: 
 7846: { 
 7847:     my %iphost;
 7848:     my %name_to_ip;
 7849:     my %lonid_to_ip;
 7850:     sub get_hosts_from_ip {
 7851: 	my ($ip) = @_;
 7852: 	my %iphosts = &get_iphost();
 7853: 	if (ref($iphosts{$ip})) {
 7854: 	    return @{$iphosts{$ip}};
 7855: 	}
 7856: 	return;
 7857:     }
 7858:     
 7859:     sub reset_hosts_ip_info {
 7860: 	undef(%iphost);
 7861: 	undef(%name_to_ip);
 7862: 	undef(%lonid_to_ip);
 7863:     }
 7864: 
 7865:     sub get_host_ip {
 7866: 	my ($lonid) = @_;
 7867: 	if (exists($lonid_to_ip{$lonid})) {
 7868: 	    return $lonid_to_ip{$lonid};
 7869: 	}
 7870: 	my $name=&hostname($lonid);
 7871:    	my $ip = gethostbyname($name);
 7872: 	return if (!$ip || length($ip) ne 4);
 7873: 	$ip=inet_ntoa($ip);
 7874: 	$name_to_ip{$name}   = $ip;
 7875: 	$lonid_to_ip{$lonid} = $ip;
 7876: 	return $ip;
 7877:     }
 7878:     
 7879:     sub get_iphost {
 7880: 	if (%iphost) { return %iphost; }
 7881: 	my %hostname = &all_hostnames();
 7882: 	foreach my $id (keys(%hostname)) {
 7883: 	    my $name=&hostname($id);
 7884: 	    my $ip;
 7885: 	    if (!exists($name_to_ip{$name})) {
 7886: 		$ip = gethostbyname($name);
 7887: 		if (!$ip || length($ip) ne 4) {
 7888: 		    &logthis("Skipping host $id name $name no IP found");
 7889: 		    next;
 7890: 		}
 7891: 		$ip=inet_ntoa($ip);
 7892: 		$name_to_ip{$name} = $ip;
 7893: 	    } else {
 7894: 		$ip = $name_to_ip{$name};
 7895: 	    }
 7896: 	    $lonid_to_ip{$id} = $ip;
 7897: 	    push(@{$iphost{$ip}},$id);
 7898: 	}
 7899: 	return %iphost;
 7900:     }
 7901: }
 7902: 
 7903: BEGIN {
 7904: 
 7905: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7906:     unless ($readit) {
 7907: {
 7908:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7909:     %perlvar = (%perlvar,%{$configvars});
 7910: }
 7911: 
 7912: 
 7913: # ------------------------------------------------------ Read spare server file
 7914: {
 7915:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7916: 
 7917:     while (my $configline=<$config>) {
 7918:        chomp($configline);
 7919:        if ($configline) {
 7920: 	   my ($host,$type) = split(':',$configline,2);
 7921: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7922: 	   push(@{ $spareid{$type} }, $host);
 7923:        }
 7924:     }
 7925:     close($config);
 7926: }
 7927: # ------------------------------------------------------------ Read permissions
 7928: {
 7929:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7930: 
 7931:     while (my $configline=<$config>) {
 7932: 	chomp($configline);
 7933: 	if ($configline) {
 7934: 	    my ($role,$perm)=split(/ /,$configline);
 7935: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7936: 	}
 7937:     }
 7938:     close($config);
 7939: }
 7940: 
 7941: # -------------------------------------------- Read plain texts for permissions
 7942: {
 7943:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7944: 
 7945:     while (my $configline=<$config>) {
 7946: 	chomp($configline);
 7947: 	if ($configline) {
 7948: 	    my ($short,@plain)=split(/:/,$configline);
 7949:             %{$prp{$short}} = ();
 7950: 	    if (@plain > 0) {
 7951:                 $prp{$short}{'std'} = $plain[0];
 7952:                 for (my $i=1; $i<@plain; $i++) {
 7953:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7954:                 }
 7955:             }
 7956: 	}
 7957:     }
 7958:     close($config);
 7959: }
 7960: 
 7961: # ---------------------------------------------------------- Read package table
 7962: {
 7963:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7964: 
 7965:     while (my $configline=<$config>) {
 7966: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7967: 	chomp($configline);
 7968: 	my ($short,$plain)=split(/:/,$configline);
 7969: 	my ($pack,$name)=split(/\&/,$short);
 7970: 	if ($plain ne '') {
 7971: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7972: 	    $packagetab{$short}=$plain; 
 7973: 	}
 7974:     }
 7975:     close($config);
 7976: }
 7977: 
 7978: # ------------- set up temporary directory
 7979: {
 7980:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7981: 
 7982: }
 7983: 
 7984: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7985: 				'compress_threshold'=> 20_000,
 7986:  			        });
 7987: 
 7988: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7989: $dumpcount=0;
 7990: 
 7991: &logtouch();
 7992: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7993: $readit=1;
 7994:     {
 7995: 	use integer;
 7996: 	my $test=(2**32)+1;
 7997: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7998: 	&logthis(" Detected 64bit platform ($_64bit)");
 7999:     }
 8000: }
 8001: }
 8002: 
 8003: 1;
 8004: __END__
 8005: 
 8006: =pod
 8007: 
 8008: =head1 NAME
 8009: 
 8010: Apache::lonnet - Subroutines to ask questions about things in the network.
 8011: 
 8012: =head1 SYNOPSIS
 8013: 
 8014: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8015: 
 8016:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8017: 
 8018: Common parameters:
 8019: 
 8020: =over 4
 8021: 
 8022: =item *
 8023: 
 8024: $uname : an internal username (if $cname expecting a course Id specifically)
 8025: 
 8026: =item *
 8027: 
 8028: $udom : a domain (if $cdom expecting a course's domain specifically)
 8029: 
 8030: =item *
 8031: 
 8032: $symb : a resource instance identifier
 8033: 
 8034: =item *
 8035: 
 8036: $namespace : the name of a .db file that contains the data needed or
 8037: being set.
 8038: 
 8039: =back
 8040: 
 8041: =head1 OVERVIEW
 8042: 
 8043: lonnet provides subroutines which interact with the
 8044: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8045: about classes, users, and resources.
 8046: 
 8047: For many of these objects you can also use this to store data about
 8048: them or modify them in various ways.
 8049: 
 8050: =head2 Symbs
 8051: 
 8052: To identify a specific instance of a resource, LON-CAPA uses symbols
 8053: or "symbs"X<symb>. These identifiers are built from the URL of the
 8054: map, the resource number of the resource in the map, and the URL of
 8055: the resource itself. The latter is somewhat redundant, but might help
 8056: if maps change.
 8057: 
 8058: An example is
 8059: 
 8060:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8061: 
 8062: The respective map entry is
 8063: 
 8064:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8065:   title="Problem 2">
 8066:  </resource>
 8067: 
 8068: Symbs are used by the random number generator, as well as to store and
 8069: restore data specific to a certain instance of for example a problem.
 8070: 
 8071: =head2 Storing And Retrieving Data
 8072: 
 8073: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8074: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8075: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8076: is is the non-critical message twin of cstore. These functions are for
 8077: handlers to store a perl hash to a user's permanent data space in an
 8078: easy manner, and to retrieve it again on another call. It is expected
 8079: that a handler would use this once at the beginning to retrieve data,
 8080: and then again once at the end to send only the new data back.
 8081: 
 8082: The data is stored in the user's data directory on the user's
 8083: homeserver under the ID of the course.
 8084: 
 8085: The hash that is returned by restore will have all of the previous
 8086: value for all of the elements of the hash.
 8087: 
 8088: Example:
 8089: 
 8090:  #creating a hash
 8091:  my %hash;
 8092:  $hash{'foo'}='bar';
 8093: 
 8094:  #storing it
 8095:  &Apache::lonnet::cstore(\%hash);
 8096: 
 8097:  #changing a value
 8098:  $hash{'foo'}='notbar';
 8099: 
 8100:  #adding a new value
 8101:  $hash{'bar'}='foo';
 8102:  &Apache::lonnet::cstore(\%hash);
 8103: 
 8104:  #retrieving the hash
 8105:  my %history=&Apache::lonnet::restore();
 8106: 
 8107:  #print the hash
 8108:  foreach my $key (sort(keys(%history))) {
 8109:    print("\%history{$key} = $history{$key}");
 8110:  }
 8111: 
 8112: Will print out:
 8113: 
 8114:  %history{1:foo} = bar
 8115:  %history{1:keys} = foo:timestamp
 8116:  %history{1:timestamp} = 990455579
 8117:  %history{2:bar} = foo
 8118:  %history{2:foo} = notbar
 8119:  %history{2:keys} = foo:bar:timestamp
 8120:  %history{2:timestamp} = 990455580
 8121:  %history{bar} = foo
 8122:  %history{foo} = notbar
 8123:  %history{timestamp} = 990455580
 8124:  %history{version} = 2
 8125: 
 8126: Note that the special hash entries C<keys>, C<version> and
 8127: C<timestamp> were added to the hash. C<version> will be equal to the
 8128: total number of versions of the data that have been stored. The
 8129: C<timestamp> attribute will be the UNIX time the hash was
 8130: stored. C<keys> is available in every historical section to list which
 8131: keys were added or changed at a specific historical revision of a
 8132: hash.
 8133: 
 8134: B<Warning>: do not store the hash that restore returns directly. This
 8135: will cause a mess since it will restore the historical keys as if the
 8136: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8137: 
 8138: Calling convention:
 8139: 
 8140:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8141:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8142: 
 8143: For more detailed information, see lonnet specific documentation.
 8144: 
 8145: =head1 RETURN MESSAGES
 8146: 
 8147: =over 4
 8148: 
 8149: =item * B<con_lost>: unable to contact remote host
 8150: 
 8151: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8152: when the connection is brought back up
 8153: 
 8154: =item * B<con_failed>: unable to contact remote host and unable to save message
 8155: for later delivery
 8156: 
 8157: =item * B<error:>: an error a occured, a description of the error follows the :
 8158: 
 8159: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8160: that was requested
 8161: 
 8162: =back
 8163: 
 8164: =head1 PUBLIC SUBROUTINES
 8165: 
 8166: =head2 Session Environment Functions
 8167: 
 8168: =over 4
 8169: 
 8170: =item * 
 8171: X<appenv()>
 8172: B<appenv(%hash)>: the value of %hash is written to
 8173: the user envirnoment file, and will be restored for each access this
 8174: user makes during this session, also modifies the %env for the current
 8175: process
 8176: 
 8177: =item *
 8178: X<delenv()>
 8179: B<delenv($regexp)>: removes all items from the session
 8180: environment file that matches the regular expression in $regexp. The
 8181: values are also delted from the current processes %env.
 8182: 
 8183: =item * get_env_multiple($name) 
 8184: 
 8185: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8186: values may be defined and end up as an array ref.
 8187: 
 8188: returns an array of values
 8189: 
 8190: =back
 8191: 
 8192: =head2 User Information
 8193: 
 8194: =over 4
 8195: 
 8196: =item *
 8197: X<queryauthenticate()>
 8198: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8199: authentication scheme
 8200: 
 8201: =item *
 8202: X<authenticate()>
 8203: B<authenticate($uname,$upass,$udom)>: try to
 8204: authenticate user from domain's lib servers (first use the current
 8205: one). C<$upass> should be the users password.
 8206: 
 8207: =item *
 8208: X<homeserver()>
 8209: B<homeserver($uname,$udom)>: find the server which has
 8210: the user's directory and files (there must be only one), this caches
 8211: the answer, and also caches if there is a borken connection.
 8212: 
 8213: =item *
 8214: X<idget()>
 8215: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8216: (IDs are a unique resource in a domain, there must be only 1 ID per
 8217: username, and only 1 username per ID in a specific domain) (returns
 8218: hash: id=>name,id=>name)
 8219: 
 8220: =item *
 8221: X<idrget()>
 8222: B<idrget($udom,@unames)>: find the IDs behind a list of
 8223: usernames (returns hash: name=>id,name=>id)
 8224: 
 8225: =item *
 8226: X<idput()>
 8227: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8228: 
 8229: =item *
 8230: X<rolesinit()>
 8231: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8232: 
 8233: =item *
 8234: X<getsection()>
 8235: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8236: course $cname, return section name/number or '' for "not in course"
 8237: and '-1' for "no section"
 8238: 
 8239: =item *
 8240: X<userenvironment()>
 8241: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8242: passed in @what from the requested user's environment, returns a hash
 8243: 
 8244: =item * 
 8245: X<userlog_query()>
 8246: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8247: activity.log file. %filters defines filters applied when parsing the
 8248: log file. These can be start or end timestamps, or the type of action
 8249: - log to look for Login or Logout events, check for Checkin or
 8250: Checkout, role for role selection. The response is in the form
 8251: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8252: escaped strings of the action recorded in the activity.log file.
 8253: 
 8254: =back
 8255: 
 8256: =head2 User Roles
 8257: 
 8258: =over 4
 8259: 
 8260: =item *
 8261: 
 8262: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8263:  F: full access
 8264:  U,I,K: authentication modes (cxx only)
 8265:  '': forbidden
 8266:  1: user needs to choose course
 8267:  2: browse allowed
 8268:  A: passphrase authentication needed
 8269: 
 8270: =item *
 8271: 
 8272: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8273: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8274: and course level
 8275: 
 8276: =item *
 8277: 
 8278: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8279: explanation of a user role term
 8280: 
 8281: =item *
 8282: 
 8283: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8284: All arguments are optional. Returns a hash of a roles, either for
 8285: co-author/assistant author roles for a user's Construction Space
 8286: (default), or if $context is 'user', roles for the user himself,
 8287: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8288: and value is set to colon-separated start and end times for the role.
 8289: If no username and domain are specified, will default to current
 8290: user/domain. Types, roles, and roledoms are references to arrays,
 8291: of role statuses (active, future or previous), roles 
 8292: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8293: to restrict the list of roles reported. If no array ref is 
 8294: provided for types, will default to return only active roles.
 8295: 
 8296: =back
 8297: 
 8298: =head2 User Modification
 8299: 
 8300: =over 4
 8301: 
 8302: =item *
 8303: 
 8304: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8305: user for the level given by URL.  Optional start and end dates (leave empty
 8306: string or zero for "no date")
 8307: 
 8308: =item *
 8309: 
 8310: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8311: change a users, password, possible return values are: ok,
 8312: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8313: refused
 8314: 
 8315: =item *
 8316: 
 8317: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8318: 
 8319: =item *
 8320: 
 8321: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8322: modify user
 8323: 
 8324: =item *
 8325: 
 8326: modifystudent
 8327: 
 8328: modify a students enrollment and identification information.
 8329: The course id is resolved based on the current users environment.  
 8330: This means the envoking user must be a course coordinator or otherwise
 8331: associated with a course.
 8332: 
 8333: This call is essentially a wrapper for lonnet::modifyuser and
 8334: lonnet::modify_student_enrollment
 8335: 
 8336: Inputs: 
 8337: 
 8338: =over 4
 8339: 
 8340: =item B<$udom> Students loncapa domain
 8341: 
 8342: =item B<$uname> Students loncapa login name
 8343: 
 8344: =item B<$uid> Students id/student number
 8345: 
 8346: =item B<$umode> Students authentication mode
 8347: 
 8348: =item B<$upass> Students password
 8349: 
 8350: =item B<$first> Students first name
 8351: 
 8352: =item B<$middle> Students middle name
 8353: 
 8354: =item B<$last> Students last name
 8355: 
 8356: =item B<$gene> Students generation
 8357: 
 8358: =item B<$usec> Students section in course
 8359: 
 8360: =item B<$end> Unix time of the roles expiration
 8361: 
 8362: =item B<$start> Unix time of the roles start date
 8363: 
 8364: =item B<$forceid> If defined, allow $uid to be changed
 8365: 
 8366: =item B<$desiredhome> server to use as home server for student
 8367: 
 8368: =back
 8369: 
 8370: =item *
 8371: 
 8372: modify_student_enrollment
 8373: 
 8374: Change a students enrollment status in a class.  The environment variable
 8375: 'role.request.course' must be defined for this function to proceed.
 8376: 
 8377: Inputs:
 8378: 
 8379: =over 4
 8380: 
 8381: =item $udom, students domain
 8382: 
 8383: =item $uname, students name
 8384: 
 8385: =item $uid, students user id
 8386: 
 8387: =item $first, students first name
 8388: 
 8389: =item $middle
 8390: 
 8391: =item $last
 8392: 
 8393: =item $gene
 8394: 
 8395: =item $usec
 8396: 
 8397: =item $end
 8398: 
 8399: =item $start
 8400: 
 8401: =back
 8402: 
 8403: 
 8404: =item *
 8405: 
 8406: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8407: custom role; give a custom role to a user for the level given by URL.  Specify
 8408: name and domain of role author, and role name
 8409: 
 8410: =item *
 8411: 
 8412: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8413: 
 8414: =item *
 8415: 
 8416: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8417: 
 8418: =back
 8419: 
 8420: =head2 Course Infomation
 8421: 
 8422: =over 4
 8423: 
 8424: =item *
 8425: 
 8426: coursedescription($courseid) : returns a hash of information about the
 8427: specified course id, including all environment settings for the
 8428: course, the description of the course will be in the hash under the
 8429: key 'description'
 8430: 
 8431: =item *
 8432: 
 8433: resdata($name,$domain,$type,@which) : request for current parameter
 8434: setting for a specific $type, where $type is either 'course' or 'user',
 8435: @what should be a list of parameters to ask about. This routine caches
 8436: answers for 5 minutes.
 8437: 
 8438: =back
 8439: 
 8440: =head2 Course Modification
 8441: 
 8442: =over 4
 8443: 
 8444: =item *
 8445: 
 8446: writecoursepref($courseid,%prefs) : write preferences (environment
 8447: database) for a course
 8448: 
 8449: =item *
 8450: 
 8451: createcourse($udom,$description,$url) : make/modify course
 8452: 
 8453: =back
 8454: 
 8455: =head2 Resource Subroutines
 8456: 
 8457: =over 4
 8458: 
 8459: =item *
 8460: 
 8461: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8462: 
 8463: =item *
 8464: 
 8465: repcopy($filename) : subscribes to the requested file, and attempts to
 8466: replicate from the owning library server, Might return
 8467: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8468: 'bad_request', also attempts to grab the metadata for the
 8469: resource. Expects the local filesystem pathname
 8470: (/home/httpd/html/res/....)
 8471: 
 8472: =back
 8473: 
 8474: =head2 Resource Information
 8475: 
 8476: =over 4
 8477: 
 8478: =item *
 8479: 
 8480: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8481: a vairety of different possible values, $varname should be a request
 8482: string, and the other parameters can be used to specify who and what
 8483: one is asking about.
 8484: 
 8485: Possible values for $varname are environment.lastname (or other item
 8486: from the envirnment hash), user.name (or someother aspect about the
 8487: user), resource.0.maxtries (or some other part and parameter of a
 8488: resource)
 8489: 
 8490: =item *
 8491: 
 8492: directcondval($number) : get current value of a condition; reads from a state
 8493: string
 8494: 
 8495: =item *
 8496: 
 8497: condval($condidx) : value of condition index based on state
 8498: 
 8499: =item *
 8500: 
 8501: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8502: resource's metadata, $what should be either a specific key, or either
 8503: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8504: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8505: 
 8506: this function automatically caches all requests
 8507: 
 8508: =item *
 8509: 
 8510: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8511: network of library servers; returns file handle of where SQL and regex results
 8512: will be stored for query
 8513: 
 8514: =item *
 8515: 
 8516: symbread($filename) : return symbolic list entry (filename argument optional);
 8517: returns the data handle
 8518: 
 8519: =item *
 8520: 
 8521: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8522: a possible symb for the URL in $thisfn, and if is an encryypted
 8523: resource that the user accessed using /enc/ returns a 1 on success, 0
 8524: on failure, user must be in a course, as it assumes the existance of
 8525: the course initial hash, and uses $env('request.course.id'}
 8526: 
 8527: 
 8528: =item *
 8529: 
 8530: symbclean($symb) : removes versions numbers from a symb, returns the
 8531: cleaned symb
 8532: 
 8533: =item *
 8534: 
 8535: is_on_map($uri) : checks if the $uri is somewhere on the current
 8536: course map, user must be in a course for it to work.
 8537: 
 8538: =item *
 8539: 
 8540: numval($salt) : return random seed value (addend for rndseed)
 8541: 
 8542: =item *
 8543: 
 8544: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8545: a random seed, all arguments are optional, if they aren't sent it uses the
 8546: environment to derive them. Note: if symb isn't sent and it can't get one
 8547: from &symbread it will use the current time as its return value
 8548: 
 8549: =item *
 8550: 
 8551: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8552: unfakeable, receipt
 8553: 
 8554: =item *
 8555: 
 8556: receipt() : API to ireceipt working off of env values; given out to users
 8557: 
 8558: =item *
 8559: 
 8560: countacc($url) : count the number of accesses to a given URL
 8561: 
 8562: =item *
 8563: 
 8564: 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
 8565: 
 8566: =item *
 8567: 
 8568: 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)
 8569: 
 8570: =item *
 8571: 
 8572: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8573: 
 8574: =item *
 8575: 
 8576: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8577: forcing spreadsheet to reevaluate the resource scores next time.
 8578: 
 8579: =back
 8580: 
 8581: =head2 Storing/Retreiving Data
 8582: 
 8583: =over 4
 8584: 
 8585: =item *
 8586: 
 8587: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8588: for this url; hashref needs to be given and should be a \%hashname; the
 8589: remaining args aren't required and if they aren't passed or are '' they will
 8590: be derived from the env
 8591: 
 8592: =item *
 8593: 
 8594: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8595: uses critical subroutine
 8596: 
 8597: =item *
 8598: 
 8599: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8600: all args are optional
 8601: 
 8602: =item *
 8603: 
 8604: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8605: dumps the complete (or key matching regexp) namespace into a hash
 8606: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8607: normally &store()ed into
 8608: 
 8609: $range should be either an integer '100' (give me the first 100
 8610:                                            matching records)
 8611:               or be  two integers sperated by a - with no spaces
 8612:                  '30-50' (give me the 30th through the 50th matching
 8613:                           records)
 8614: 
 8615: 
 8616: =item *
 8617: 
 8618: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8619: replaces a &store() version of data with a replacement set of data
 8620: for a particular resource in a namespace passed in the $storehash hash 
 8621: reference
 8622: 
 8623: =item *
 8624: 
 8625: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8626: works very similar to store/cstore, but all data is stored in a
 8627: temporary location and can be reset using tmpreset, $storehash should
 8628: be a hash reference, returns nothing on success
 8629: 
 8630: =item *
 8631: 
 8632: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8633: similar to restore, but all data is stored in a temporary location and
 8634: can be reset using tmpreset. Returns a hash of values on success,
 8635: error string otherwise.
 8636: 
 8637: =item *
 8638: 
 8639: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8640: deltes all keys for $symb form the temporary storage hash.
 8641: 
 8642: =item *
 8643: 
 8644: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8645: reference filled in from namesp ($udom and $uname are optional)
 8646: 
 8647: =item *
 8648: 
 8649: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8650: namesp ($udom and $uname are optional)
 8651: 
 8652: =item *
 8653: 
 8654: dump($namespace,$udom,$uname,$regexp,$range) : 
 8655: dumps the complete (or key matching regexp) namespace into a hash
 8656: ($udom, $uname, $regexp, $range are optional)
 8657: 
 8658: $range should be either an integer '100' (give me the first 100
 8659:                                            matching records)
 8660:               or be  two integers sperated by a - with no spaces
 8661:                  '30-50' (give me the 30th through the 50th matching
 8662:                           records)
 8663: =item *
 8664: 
 8665: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8666: $store can be a scalar, an array reference, or if the amount to be 
 8667: incremented is > 1, a hash reference.
 8668: 
 8669: ($udom and $uname are optional)
 8670: 
 8671: =item *
 8672: 
 8673: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8674: ($udom and $uname are optional)
 8675: 
 8676: =item *
 8677: 
 8678: cput($namespace,$storehash,$udom,$uname) : critical put
 8679: ($udom and $uname are optional)
 8680: 
 8681: =item *
 8682: 
 8683: newput($namespace,$storehash,$udom,$uname) :
 8684: 
 8685: Attempts to store the items in the $storehash, but only if they don't
 8686: currently exist, if this succeeds you can be certain that you have 
 8687: successfully created a new key value pair in the $namespace db.
 8688: 
 8689: 
 8690: Args:
 8691:  $namespace: name of database to store values to
 8692:  $storehash: hashref to store to the db
 8693:  $udom: (optional) domain of user containing the db
 8694:  $uname: (optional) name of user caontaining the db
 8695: 
 8696: Returns:
 8697:  'ok' -> succeeded in storing all keys of $storehash
 8698:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8699:                         least <key> already existed in the db (other
 8700:                         requested keys may also already exist)
 8701:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8702:  'con_lost' -> unable to contact request server
 8703:  'refused' -> action was not allowed by remote machine
 8704: 
 8705: 
 8706: =item *
 8707: 
 8708: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8709: reference filled in from namesp (encrypts the return communication)
 8710: ($udom and $uname are optional)
 8711: 
 8712: =item *
 8713: 
 8714: log($udom,$name,$home,$message) : write to permanent log for user; use
 8715: critical subroutine
 8716: 
 8717: =item *
 8718: 
 8719: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8720: array reference filled in from namespace found in domain level on either
 8721: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8722: 
 8723: =item *
 8724: 
 8725: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8726: domain level either on specified domain server ($uhome) or primary domain 
 8727: server ($udom and $uhome are optional)
 8728: 
 8729: =back
 8730: 
 8731: =head2 Network Status Functions
 8732: 
 8733: =over 4
 8734: 
 8735: =item *
 8736: 
 8737: dirlist($uri) : return directory list based on URI
 8738: 
 8739: =item *
 8740: 
 8741: spareserver() : find server with least workload from spare.tab
 8742: 
 8743: =back
 8744: 
 8745: =head2 Apache Request
 8746: 
 8747: =over 4
 8748: 
 8749: =item *
 8750: 
 8751: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8752: localhost, posts hash
 8753: 
 8754: =back
 8755: 
 8756: =head2 Data to String to Data
 8757: 
 8758: =over 4
 8759: 
 8760: =item *
 8761: 
 8762: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8763: and '&' separators, supports elements that are arrayrefs and hashrefs
 8764: 
 8765: =item *
 8766: 
 8767: hashref2str($hashref) : convert a hashref into a string complete with
 8768: escaping and '=' and '&' separators, supports elements that are
 8769: arrayrefs and hashrefs
 8770: 
 8771: =item *
 8772: 
 8773: arrayref2str($arrayref) : convert an arrayref into a string complete
 8774: with escaping and '&' separators, supports elements that are arrayrefs
 8775: and hashrefs
 8776: 
 8777: =item *
 8778: 
 8779: str2hash($string) : convert string to hash using unescaping and
 8780: splitting on '=' and '&', supports elements that are arrayrefs and
 8781: hashrefs
 8782: 
 8783: =item *
 8784: 
 8785: str2array($string) : convert string to hash using unescaping and
 8786: splitting on '&', supports elements that are arrayrefs and hashrefs
 8787: 
 8788: =back
 8789: 
 8790: =head2 Logging Routines
 8791: 
 8792: =over 4
 8793: 
 8794: These routines allow one to make log messages in the lonnet.log and
 8795: lonnet.perm logfiles.
 8796: 
 8797: =item *
 8798: 
 8799: logtouch() : make sure the logfile, lonnet.log, exists
 8800: 
 8801: =item *
 8802: 
 8803: logthis() : append message to the normal lonnet.log file, it gets
 8804: preiodically rolled over and deleted.
 8805: 
 8806: =item *
 8807: 
 8808: logperm() : append a permanent message to lonnet.perm.log, this log
 8809: file never gets deleted by any automated portion of the system, only
 8810: messages of critical importance should go in here.
 8811: 
 8812: =back
 8813: 
 8814: =head2 General File Helper Routines
 8815: 
 8816: =over 4
 8817: 
 8818: =item *
 8819: 
 8820: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8821: (a) files in /uploaded
 8822:   (i) If a local copy of the file exists - 
 8823:       compares modification date of local copy with last-modified date for 
 8824:       definitive version stored on home server for course. If local copy is 
 8825:       stale, requests a new version from the home server and stores it. 
 8826:       If the original has been removed from the home server, then local copy 
 8827:       is unlinked.
 8828:   (ii) If local copy does not exist -
 8829:       requests the file from the home server and stores it. 
 8830:   
 8831:   If $caller is 'uploadrep':  
 8832:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8833:     for request for files originally uploaded via DOCS. 
 8834:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8835:   
 8836:   Otherwise:
 8837:      This indicates a call from the content generation phase of the request.
 8838:      -  returns the entire contents of the file or -1.
 8839:      
 8840: (b) files in /res
 8841:    - returns the entire contents of a file or -1; 
 8842:    it properly subscribes to and replicates the file if neccessary.
 8843: 
 8844: 
 8845: =item *
 8846: 
 8847: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8848:                   reference
 8849: 
 8850: returns either a stat() list of data about the file or an empty list
 8851: if the file doesn't exist or couldn't find out about it (connection
 8852: problems or user unknown)
 8853: 
 8854: =item *
 8855: 
 8856: filelocation($dir,$file) : returns file system location of a file
 8857: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8858: directory that relative $file lookups are to looked in ($dir of /a/dir
 8859: and a file of ../bob will become /a/bob)
 8860: 
 8861: =item *
 8862: 
 8863: hreflocation($dir,$file) : returns file system location or a URL; same as
 8864: filelocation except for hrefs
 8865: 
 8866: =item *
 8867: 
 8868: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8869: 
 8870: =back
 8871: 
 8872: =head2 Usererfile file routines (/uploaded*)
 8873: 
 8874: =over 4
 8875: 
 8876: =item *
 8877: 
 8878: userfileupload(): main rotine for putting a file in a user or course's
 8879:                   filespace, arguments are,
 8880: 
 8881:  formname - required - this is the name of the element in $env where the
 8882:            filename, and the contents of the file to create/modifed exist
 8883:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8884:            contents of the file is located in $env{'form.'.$formname}
 8885:  coursedoc - if true, store the file in the course of the active role
 8886:              of the current user
 8887:  subdir - required - subdirectory to put the file in under ../userfiles/
 8888:          if undefined, it will be placed in "unknown"
 8889: 
 8890:  (This routine calls clean_filename() to remove any dangerous
 8891:  characters from the filename, and then calls finuserfileupload() to
 8892:  complete the transaction)
 8893: 
 8894:  returns either the url of the uploaded file (/uploaded/....) if successful
 8895:  and /adm/notfound.html if unsuccessful
 8896: 
 8897: =item *
 8898: 
 8899: clean_filename(): routine for cleaing a filename up for storage in
 8900:                  userfile space, argument is:
 8901: 
 8902:  filename - proposed filename
 8903: 
 8904: returns: the new clean filename
 8905: 
 8906: =item *
 8907: 
 8908: finishuserfileupload(): routine that creaes and sends the file to
 8909: userspace, probably shouldn't be called directly
 8910: 
 8911:   docuname: username or courseid of destination for the file
 8912:   docudom: domain of user/course of destination for the file
 8913:   formname: same as for userfileupload()
 8914:   fname: filename (inculding subdirectories) for the file
 8915: 
 8916:  returns either the url of the uploaded file (/uploaded/....) if successful
 8917:  and /adm/notfound.html if unsuccessful
 8918: 
 8919: =item *
 8920: 
 8921: renameuserfile(): renames an existing userfile to a new name
 8922: 
 8923:   Args:
 8924:    docuname: username or courseid of destination for the file
 8925:    docudom: domain of user/course of destination for the file
 8926:    old: current file name (including any subdirs under userfiles)
 8927:    new: desired file name (including any subdirs under userfiles)
 8928: 
 8929: =item *
 8930: 
 8931: mkdiruserfile(): creates a directory is a userfiles dir
 8932: 
 8933:   Args:
 8934:    docuname: username or courseid of destination for the file
 8935:    docudom: domain of user/course of destination for the file
 8936:    dir: dir to create (including any subdirs under userfiles)
 8937: 
 8938: =item *
 8939: 
 8940: removeuserfile(): removes a file that exists in userfiles
 8941: 
 8942:   Args:
 8943:    docuname: username or courseid of destination for the file
 8944:    docudom: domain of user/course of destination for the file
 8945:    fname: filname to delete (including any subdirs under userfiles)
 8946: 
 8947: =item *
 8948: 
 8949: removeuploadedurl(): convience function for removeuserfile()
 8950: 
 8951:   Args:
 8952:    url:  a full /uploaded/... url to delete
 8953: 
 8954: =item * 
 8955: 
 8956: get_portfile_permissions():
 8957:   Args:
 8958:     domain: domain of user or course contain the portfolio files
 8959:     user: name of user or num of course contain the portfolio files
 8960:   Returns:
 8961:     hashref of a dump of the proper file_permissions.db
 8962:    
 8963: 
 8964: =item * 
 8965: 
 8966: get_access_controls():
 8967: 
 8968: Args:
 8969:   current_permissions: the hash ref returned from get_portfile_permissions()
 8970:   group: (optional) the group you want the files associated with
 8971:   file: (optional) the file you want access info on
 8972: 
 8973: Returns:
 8974:     a hash (keys are file names) of hashes containing
 8975:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8976:         values are XML containing access control settings (see below) 
 8977: 
 8978: Internal notes:
 8979: 
 8980:  access controls are stored in file_permissions.db as key=value pairs.
 8981:     key -> path to file/file_name\0uniqueID:scope_end_start
 8982:         where scope -> public,guest,course,group,domains or users.
 8983:               end -> UNIX time for end of access (0 -> no end date)
 8984:               start -> UNIX time for start of access
 8985: 
 8986:     value -> XML description of access control
 8987:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8988:             <start></start>
 8989:             <end></end>
 8990: 
 8991:             <password></password>  for scope type = guest
 8992: 
 8993:             <domain></domain>     for scope type = course or group
 8994:             <number></number>
 8995:             <roles id="">
 8996:              <role></role>
 8997:              <access></access>
 8998:              <section></section>
 8999:              <group></group>
 9000:             </roles>
 9001: 
 9002:             <dom></dom>         for scope type = domains
 9003: 
 9004:             <users>             for scope type = users
 9005:              <user>
 9006:               <uname></uname>
 9007:               <udom></udom>
 9008:              </user>
 9009:             </users>
 9010:            </scope> 
 9011:               
 9012:  Access data is also aggregated for each file in an additional key=value pair:
 9013:  key -> path to file/file_name\0accesscontrol 
 9014:  value -> reference to hash
 9015:           hash contains key = value pairs
 9016:           where key = uniqueID:scope_end_start
 9017:                 value = UNIX time record was last updated
 9018: 
 9019:           Used to improve speed of look-ups of access controls for each file.  
 9020:  
 9021:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9022: 
 9023: modify_access_controls():
 9024: 
 9025: Modifies access controls for a portfolio file
 9026: Args
 9027: 1. file name
 9028: 2. reference to hash of required changes,
 9029: 3. domain
 9030: 4. username
 9031:   where domain,username are the domain of the portfolio owner 
 9032:   (either a user or a course) 
 9033: 
 9034: Returns:
 9035: 1. result of additions or updates ('ok' or 'error', with error message). 
 9036: 2. result of deletions ('ok' or 'error', with error message).
 9037: 3. reference to hash of any new or updated access controls.
 9038: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9039:    key = integer (inbound ID)
 9040:    value = uniqueID  
 9041: 
 9042: =back
 9043: 
 9044: =head2 HTTP Helper Routines
 9045: 
 9046: =over 4
 9047: 
 9048: =item *
 9049: 
 9050: escape() : unpack non-word characters into CGI-compatible hex codes
 9051: 
 9052: =item *
 9053: 
 9054: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9055: 
 9056: =back
 9057: 
 9058: =head1 PRIVATE SUBROUTINES
 9059: 
 9060: =head2 Underlying communication routines (Shouldn't call)
 9061: 
 9062: =over 4
 9063: 
 9064: =item *
 9065: 
 9066: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9067: 
 9068: =item *
 9069: 
 9070: reply() : uses subreply to send a message to remote machine, logs all failures
 9071: 
 9072: =item *
 9073: 
 9074: critical() : passes a critical message to another server; if cannot
 9075: get through then place message in connection buffer directory and
 9076: returns con_delayed, if incapable of saving message, returns
 9077: con_failed
 9078: 
 9079: =item *
 9080: 
 9081: reconlonc() : tries to reconnect lonc client processes.
 9082: 
 9083: =back
 9084: 
 9085: =head2 Resource Access Logging
 9086: 
 9087: =over 4
 9088: 
 9089: =item *
 9090: 
 9091: flushcourselogs() : flush (save) buffer logs and access logs
 9092: 
 9093: =item *
 9094: 
 9095: courselog($what) : save message for course in hash
 9096: 
 9097: =item *
 9098: 
 9099: courseacclog($what) : save message for course using &courselog().  Perform
 9100: special processing for specific resource types (problems, exams, quizzes, etc).
 9101: 
 9102: =item *
 9103: 
 9104: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9105: as a PerlChildExitHandler
 9106: 
 9107: =back
 9108: 
 9109: =head2 Other
 9110: 
 9111: =over 4
 9112: 
 9113: =item *
 9114: 
 9115: symblist($mapname,%newhash) : update symbolic storage links
 9116: 
 9117: =back
 9118: 
 9119: =cut

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