File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.857: download - view: text, annotated - select for diffs
Tue Apr 3 00:49:14 2007 UTC (17 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- rmeove some log spew

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.857 2007/04/03 00:49:14 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %badServerCache %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)=@_;
  738:     my $items='';
  739:     foreach my $item (@$storearr) {
  740:         $items.=&escape($item).'&';
  741:     }
  742:     $items=~s/\&$//;
  743:     if (!$udom) { $udom=$env{'user.domain'}; }
  744:     if (defined(&domain($udom,'primary'))) {
  745:         my $uhome=&domain($udom,'primary');
  746:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  747:         my @pairs=split(/\&/,$rep);
  748:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  749:             return @pairs;
  750:         }
  751:         my %returnhash=();
  752:         my $i=0;
  753:         foreach my $item (@$storearr) {
  754:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  755:             $i++;
  756:         }
  757:         return %returnhash;
  758:     } else {
  759:         &logthis("get_dom failed - no primary domain server for $udom");
  760:     }
  761: }
  762: 
  763: # -------------------------------------------- put items in domain db files 
  764: 
  765: sub put_dom {
  766:     my ($namespace,$storehash,$udom)=@_;
  767:     if (!$udom) { $udom=$env{'user.domain'}; }
  768:     if (defined(&domain($udom,'primary'))) {
  769:         my $uhome=&domain($udom,'primary');
  770:         my $items='';
  771:         foreach my $item (keys(%$storehash)) {
  772:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  773:         }
  774:         $items=~s/\&$//;
  775:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  776:     } else {
  777:         &logthis("put_dom failed - no primary domain server for $udom");
  778:     }
  779: }
  780: 
  781: sub retrieve_inst_usertypes {
  782:     my ($udom) = @_;
  783:     my (%returnhash,@order);
  784:     if (defined(&domain($udom,'primary'))) {
  785:         my $uhome=&domain($udom,'primary');
  786:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  787:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  788:         my @pairs=split(/\&/,$hashitems);
  789:         foreach my $item (@pairs) {
  790:             my ($key,$value)=split(/=/,$item,2);
  791:             $key = &unescape($key);
  792:             next if ($key =~ /^error: 2 /);
  793:             $returnhash{$key}=&thaw_unescape($value);
  794:         }
  795:         my @esc_order = split(/\&/,$orderitems);
  796:         foreach my $item (@esc_order) {
  797:             push(@order,&unescape($item));
  798:         }
  799:     } else {
  800:         &logthis("get_dom failed - no primary domain server for $udom");
  801:     }
  802:     return (\%returnhash,\@order);
  803: }
  804: 
  805: # --------------------------------------------------- Assign a key to a student
  806: 
  807: sub assign_access_key {
  808: #
  809: # a valid key looks like uname:udom#comments
  810: # comments are being appended
  811: #
  812:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  813:     $kdom=
  814:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  815:     $knum=
  816:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  817:     $cdom=
  818:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  819:     $cnum=
  820:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  821:     $udom=$env{'user.name'} unless (defined($udom));
  822:     $uname=$env{'user.domain'} unless (defined($uname));
  823:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  824:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  825:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  826:                                                   # assigned to this person
  827:                                                   # - this should not happen,
  828:                                                   # unless something went wrong
  829:                                                   # the first time around
  830: # ready to assign
  831:         $logentry=$1.'; '.$logentry;
  832:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  833:                                                  $kdom,$knum) eq 'ok') {
  834: # key now belongs to user
  835: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  836:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  837:                 &appenv('environment.'.$envkey => $ckey);
  838:                 return 'ok';
  839:             } else {
  840:                 return 
  841:   'error: Count not permanently assign key, will need to be re-entered later.';
  842: 	    }
  843:         } else {
  844:             return 'error: Could not assign key, try again later.';
  845:         }
  846:     } elsif (!$existing{$ckey}) {
  847: # the key does not exist
  848: 	return 'error: The key does not exist';
  849:     } else {
  850: # the key is somebody else's
  851: 	return 'error: The key is already in use';
  852:     }
  853: }
  854: 
  855: # ------------------------------------------ put an additional comment on a key
  856: 
  857: sub comment_access_key {
  858: #
  859: # a valid key looks like uname:udom#comments
  860: # comments are being appended
  861: #
  862:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  863:     $cdom=
  864:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  865:     $cnum=
  866:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  867:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  868:     if ($existing{$ckey}) {
  869:         $existing{$ckey}.='; '.$logentry;
  870: # ready to assign
  871:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  872:                                                  $cdom,$cnum) eq 'ok') {
  873: 	    return 'ok';
  874:         } else {
  875: 	    return 'error: Count not store comment.';
  876:         }
  877:     } else {
  878: # the key does not exist
  879: 	return 'error: The key does not exist';
  880:     }
  881: }
  882: 
  883: # ------------------------------------------------------ Generate a set of keys
  884: 
  885: sub generate_access_keys {
  886:     my ($number,$cdom,$cnum,$logentry)=@_;
  887:     $cdom=
  888:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  889:     $cnum=
  890:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  891:     unless (&allowed('mky',$cdom)) { return 0; }
  892:     unless (($cdom) && ($cnum)) { return 0; }
  893:     if ($number>10000) { return 0; }
  894:     sleep(2); # make sure don't get same seed twice
  895:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  896:     my $total=0;
  897:     for (my $i=1;$i<=$number;$i++) {
  898:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  899:                   sprintf("%lx",int(100000*rand)).'-'.
  900:                   sprintf("%lx",int(100000*rand));
  901:        $newkey=~s/1/g/g; # folks mix up 1 and l
  902:        $newkey=~s/0/h/g; # and also 0 and O
  903:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  904:        if ($existing{$newkey}) {
  905:            $i--;
  906:        } else {
  907: 	  if (&put('accesskeys',
  908:               { $newkey => '# generated '.localtime().
  909:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  910:                            '; '.$logentry },
  911: 		   $cdom,$cnum) eq 'ok') {
  912:               $total++;
  913: 	  }
  914:        }
  915:     }
  916:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  917:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  918:     return $total;
  919: }
  920: 
  921: # ------------------------------------------------------- Validate an accesskey
  922: 
  923: sub validate_access_key {
  924:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  925:     $cdom=
  926:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  927:     $cnum=
  928:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  929:     $udom=$env{'user.domain'} unless (defined($udom));
  930:     $uname=$env{'user.name'} unless (defined($uname));
  931:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  932:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  933: }
  934: 
  935: # ------------------------------------- Find the section of student in a course
  936: sub devalidate_getsection_cache {
  937:     my ($udom,$unam,$courseid)=@_;
  938:     my $hashid="$udom:$unam:$courseid";
  939:     &devalidate_cache_new('getsection',$hashid);
  940: }
  941: 
  942: sub courseid_to_courseurl {
  943:     my ($courseid) = @_;
  944:     #already url style courseid
  945:     return $courseid if ($courseid =~ m{^/});
  946: 
  947:     if (exists($env{'course.'.$courseid.'.num'})) {
  948: 	my $cnum = $env{'course.'.$courseid.'.num'};
  949: 	my $cdom = $env{'course.'.$courseid.'.domain'};
  950: 	return "/$cdom/$cnum";
  951:     }
  952: 
  953:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
  954:     if (exists($courseinfo{'num'})) {
  955: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
  956:     }
  957: 
  958:     return undef;
  959: }
  960: 
  961: sub getsection {
  962:     my ($udom,$unam,$courseid)=@_;
  963:     my $cachetime=1800;
  964: 
  965:     my $hashid="$udom:$unam:$courseid";
  966:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  967:     if (defined($cached)) { return $result; }
  968: 
  969:     my %Pending; 
  970:     my %Expired;
  971:     #
  972:     # Each role can either have not started yet (pending), be active, 
  973:     #    or have expired.
  974:     #
  975:     # If there is an active role, we are done.
  976:     #
  977:     # If there is more than one role which has not started yet, 
  978:     #     choose the one which will start sooner
  979:     # If there is one role which has not started yet, return it.
  980:     #
  981:     # If there is more than one expired role, choose the one which ended last.
  982:     # If there is a role which has expired, return it.
  983:     #
  984:     $courseid = &courseid_to_courseurl($courseid);
  985:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
  986:     foreach my $key (keys(%roleshash)) {
  987:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  988:         my $section=$1;
  989:         if ($key eq $courseid.'_st') { $section=''; }
  990:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
  991:         my $now=time;
  992:         if (defined($end) && $end && ($now > $end)) {
  993:             $Expired{$end}=$section;
  994:             next;
  995:         }
  996:         if (defined($start) && $start && ($now < $start)) {
  997:             $Pending{$start}=$section;
  998:             next;
  999:         }
 1000:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1001:     }
 1002:     #
 1003:     # Presumedly there will be few matching roles from the above
 1004:     # loop and the sorting time will be negligible.
 1005:     if (scalar(keys(%Pending))) {
 1006:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1007:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1008:     } 
 1009:     if (scalar(keys(%Expired))) {
 1010:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1011:         my $time = pop(@sorted);
 1012:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1013:     }
 1014:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1015: }
 1016: 
 1017: sub save_cache {
 1018:     &purge_remembered();
 1019:     #&Apache::loncommon::validate_page();
 1020:     undef(%env);
 1021:     undef($env_loaded);
 1022: }
 1023: 
 1024: my $to_remember=-1;
 1025: my %remembered;
 1026: my %accessed;
 1027: my $kicks=0;
 1028: my $hits=0;
 1029: sub make_key {
 1030:     my ($name,$id) = @_;
 1031:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
 1032:     return &escape($name.':'.$id);
 1033: }
 1034: 
 1035: sub devalidate_cache_new {
 1036:     my ($name,$id,$debug) = @_;
 1037:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1038:     $id=&make_key($name,$id);
 1039:     $memcache->delete($id);
 1040:     delete($remembered{$id});
 1041:     delete($accessed{$id});
 1042: }
 1043: 
 1044: sub is_cached_new {
 1045:     my ($name,$id,$debug) = @_;
 1046:     $id=&make_key($name,$id);
 1047:     if (exists($remembered{$id})) {
 1048: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1049: 	$accessed{$id}=[&gettimeofday()];
 1050: 	$hits++;
 1051: 	return ($remembered{$id},1);
 1052:     }
 1053:     my $value = $memcache->get($id);
 1054:     if (!(defined($value))) {
 1055: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1056: 	return (undef,undef);
 1057:     }
 1058:     if ($value eq '__undef__') {
 1059: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1060: 	$value=undef;
 1061:     }
 1062:     &make_room($id,$value,$debug);
 1063:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1064:     return ($value,1);
 1065: }
 1066: 
 1067: sub do_cache_new {
 1068:     my ($name,$id,$value,$time,$debug) = @_;
 1069:     $id=&make_key($name,$id);
 1070:     my $setvalue=$value;
 1071:     if (!defined($setvalue)) {
 1072: 	$setvalue='__undef__';
 1073:     }
 1074:     if (!defined($time) ) {
 1075: 	$time=600;
 1076:     }
 1077:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1078:     $memcache->set($id,$setvalue,$time);
 1079:     # need to make a copy of $value
 1080:     #&make_room($id,$value,$debug);
 1081:     return $value;
 1082: }
 1083: 
 1084: sub make_room {
 1085:     my ($id,$value,$debug)=@_;
 1086:     $remembered{$id}=$value;
 1087:     if ($to_remember<0) { return; }
 1088:     $accessed{$id}=[&gettimeofday()];
 1089:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1090:     my $to_kick;
 1091:     my $max_time=0;
 1092:     foreach my $other (keys(%accessed)) {
 1093: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1094: 	    $to_kick=$other;
 1095: 	    $max_time=&tv_interval($accessed{$other});
 1096: 	}
 1097:     }
 1098:     delete($remembered{$to_kick});
 1099:     delete($accessed{$to_kick});
 1100:     $kicks++;
 1101:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1102:     return;
 1103: }
 1104: 
 1105: sub purge_remembered {
 1106:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1107:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1108:     undef(%remembered);
 1109:     undef(%accessed);
 1110: }
 1111: # ------------------------------------- Read an entry from a user's environment
 1112: 
 1113: sub userenvironment {
 1114:     my ($udom,$unam,@what)=@_;
 1115:     my %returnhash=();
 1116:     my @answer=split(/\&/,
 1117:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1118:                       &homeserver($unam,$udom)));
 1119:     my $i;
 1120:     for ($i=0;$i<=$#what;$i++) {
 1121: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1122:     }
 1123:     return %returnhash;
 1124: }
 1125: 
 1126: # ---------------------------------------------------------- Get a studentphoto
 1127: sub studentphoto {
 1128:     my ($udom,$unam,$ext) = @_;
 1129:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1130:     if (defined($env{'request.course.id'})) {
 1131:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1132:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1133:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1134:             } else {
 1135:                 my ($result,$perm_reqd)=
 1136: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1137:                 if ($result eq 'ok') {
 1138:                     if (!($perm_reqd eq 'yes')) {
 1139:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1140:                     }
 1141:                 }
 1142:             }
 1143:         }
 1144:     } else {
 1145:         my ($result,$perm_reqd) = 
 1146: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1147:         if ($result eq 'ok') {
 1148:             if (!($perm_reqd eq 'yes')) {
 1149:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1150:             }
 1151:         }
 1152:     }
 1153:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1154: }
 1155: 
 1156: sub retrievestudentphoto {
 1157:     my ($udom,$unam,$ext,$type) = @_;
 1158:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1159:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1160:     if ($ret eq 'ok') {
 1161:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1162:         if ($type eq 'thumbnail') {
 1163:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1164:         }
 1165:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1166:         return $tokenurl;
 1167:     } else {
 1168:         if ($type eq 'thumbnail') {
 1169:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1170:         } else { 
 1171:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1172:         }
 1173:     }
 1174: }
 1175: 
 1176: # -------------------------------------------------------------------- New chat
 1177: 
 1178: sub chatsend {
 1179:     my ($newentry,$anon,$group)=@_;
 1180:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1181:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1182:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1183:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1184: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1185: 		   &escape($newentry)).':'.$group,$chome);
 1186: }
 1187: 
 1188: # ------------------------------------------ Find current version of a resource
 1189: 
 1190: sub getversion {
 1191:     my $fname=&clutter(shift);
 1192:     unless ($fname=~/^\/res\//) { return -1; }
 1193:     return &currentversion(&filelocation('',$fname));
 1194: }
 1195: 
 1196: sub currentversion {
 1197:     my $fname=shift;
 1198:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1199:     if (defined($cached)) { return $result; }
 1200:     my $author=$fname;
 1201:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1202:     my ($udom,$uname)=split(/\//,$author);
 1203:     my $home=homeserver($uname,$udom);
 1204:     if ($home eq 'no_host') { 
 1205:         return -1; 
 1206:     }
 1207:     my $answer=reply("currentversion:$fname",$home);
 1208:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1209: 	return -1;
 1210:     }
 1211:     return &do_cache_new('resversion',$fname,$answer,600);
 1212: }
 1213: 
 1214: # ----------------------------- Subscribe to a resource, return URL if possible
 1215: 
 1216: sub subscribe {
 1217:     my $fname=shift;
 1218:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1219:     $fname=~s/[\n\r]//g;
 1220:     my $author=$fname;
 1221:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1222:     my ($udom,$uname)=split(/\//,$author);
 1223:     my $home=homeserver($uname,$udom);
 1224:     if ($home eq 'no_host') {
 1225:         return 'not_found';
 1226:     }
 1227:     my $answer=reply("sub:$fname",$home);
 1228:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1229: 	$answer.=' by '.$home;
 1230:     }
 1231:     return $answer;
 1232: }
 1233:     
 1234: # -------------------------------------------------------------- Replicate file
 1235: 
 1236: sub repcopy {
 1237:     my $filename=shift;
 1238:     $filename=~s/\/+/\//g;
 1239:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1240:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1241:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1242: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1243: 	return &repcopy_userfile($filename);
 1244:     }
 1245:     $filename=~s/[\n\r]//g;
 1246:     my $transname="$filename.in.transfer";
 1247: # FIXME: this should flock
 1248:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1249:     my $remoteurl=subscribe($filename);
 1250:     if ($remoteurl =~ /^con_lost by/) {
 1251: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1252:            return 'unavailable';
 1253:     } elsif ($remoteurl eq 'not_found') {
 1254: 	   #&logthis("Subscribe returned not_found: $filename");
 1255: 	   return 'not_found';
 1256:     } elsif ($remoteurl =~ /^rejected by/) {
 1257: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1258:            return 'forbidden';
 1259:     } elsif ($remoteurl eq 'directory') {
 1260:            return 'ok';
 1261:     } else {
 1262:         my $author=$filename;
 1263:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1264:         my ($udom,$uname)=split(/\//,$author);
 1265:         my $home=homeserver($uname,$udom);
 1266:         unless ($home eq $perlvar{'lonHostID'}) {
 1267:            my @parts=split(/\//,$filename);
 1268:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1269:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1270:                &logthis("Malconfiguration for replication: $filename");
 1271: 	       return 'bad_request';
 1272:            }
 1273:            my $count;
 1274:            for ($count=5;$count<$#parts;$count++) {
 1275:                $path.="/$parts[$count]";
 1276:                if ((-e $path)!=1) {
 1277: 		   mkdir($path,0777);
 1278:                }
 1279:            }
 1280:            my $ua=new LWP::UserAgent;
 1281:            my $request=new HTTP::Request('GET',"$remoteurl");
 1282:            my $response=$ua->request($request,$transname);
 1283:            if ($response->is_error()) {
 1284: 	       unlink($transname);
 1285:                my $message=$response->status_line;
 1286:                &logthis("<font color=\"blue\">WARNING:"
 1287:                        ." LWP get: $message: $filename</font>");
 1288:                return 'unavailable';
 1289:            } else {
 1290: 	       if ($remoteurl!~/\.meta$/) {
 1291:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1292:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1293:                   if ($mresponse->is_error()) {
 1294: 		      unlink($filename.'.meta');
 1295:                       &logthis(
 1296:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1297:                   }
 1298: 	       }
 1299:                rename($transname,$filename);
 1300:                return 'ok';
 1301:            }
 1302:        }
 1303:     }
 1304: }
 1305: 
 1306: # ------------------------------------------------ Get server side include body
 1307: sub ssi_body {
 1308:     my ($filelink,%form)=@_;
 1309:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1310:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1311:     }
 1312:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1313:                                      &ssi($filelink,%form));
 1314:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1315:     $output=~s/^.*?\<body[^\>]*\>//si;
 1316:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1317:     return $output;
 1318: }
 1319: 
 1320: # --------------------------------------------------------- Server Side Include
 1321: 
 1322: sub absolute_url {
 1323:     my ($host_name) = @_;
 1324:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1325:     if ($host_name eq '') {
 1326: 	$host_name = $ENV{'SERVER_NAME'};
 1327:     }
 1328:     return $protocol.$host_name;
 1329: }
 1330: 
 1331: sub ssi {
 1332: 
 1333:     my ($fn,%form)=@_;
 1334: 
 1335:     my $ua=new LWP::UserAgent;
 1336:     
 1337:     my $request;
 1338: 
 1339:     $form{'no_update_last_known'}=1;
 1340: 
 1341:     if (%form) {
 1342:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1343:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1344:     } else {
 1345:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1346:     }
 1347: 
 1348:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1349:     my $response=$ua->request($request);
 1350: 
 1351:     return $response->content;
 1352: }
 1353: 
 1354: sub externalssi {
 1355:     my ($url)=@_;
 1356:     my $ua=new LWP::UserAgent;
 1357:     my $request=new HTTP::Request('GET',$url);
 1358:     my $response=$ua->request($request);
 1359:     return $response->content;
 1360: }
 1361: 
 1362: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1363: 
 1364: sub allowuploaded {
 1365:     my ($srcurl,$url)=@_;
 1366:     $url=&clutter(&declutter($url));
 1367:     my $dir=$url;
 1368:     $dir=~s/\/[^\/]+$//;
 1369:     my %httpref=();
 1370:     my $httpurl=&hreflocation('',$url);
 1371:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1372:     &Apache::lonnet::appenv(%httpref);
 1373: }
 1374: 
 1375: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1376: # input: action, courseID, current domain, intended
 1377: #        path to file, source of file, instruction to parse file for objects,
 1378: #        ref to hash for embedded objects,
 1379: #        ref to hash for codebase of java objects.
 1380: #
 1381: # output: url to file (if action was uploaddoc), 
 1382: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1383: #
 1384: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1385: # course.
 1386: #
 1387: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1388: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1389: #          course's home server.
 1390: #
 1391: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1392: #          be copied from $source (current location) to 
 1393: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1394: #         and will then be copied to
 1395: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1396: #         course's home server.
 1397: #
 1398: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1399: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1400: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1401: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1402: #         in course's home server.
 1403: #
 1404: 
 1405: sub process_coursefile {
 1406:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1407:     my $fetchresult;
 1408:     my $home=&homeserver($docuname,$docudom);
 1409:     if ($action eq 'propagate') {
 1410:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1411: 			     $home);
 1412:     } else {
 1413:         my $fpath = '';
 1414:         my $fname = $file;
 1415:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1416:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1417:         my $filepath = &build_filepath($fpath);
 1418:         if ($action eq 'copy') {
 1419:             if ($source eq '') {
 1420:                 $fetchresult = 'no source file';
 1421:                 return $fetchresult;
 1422:             } else {
 1423:                 my $destination = $filepath.'/'.$fname;
 1424:                 rename($source,$destination);
 1425:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1426:                                  $home);
 1427:             }
 1428:         } elsif ($action eq 'uploaddoc') {
 1429:             open(my $fh,'>'.$filepath.'/'.$fname);
 1430:             print $fh $env{'form.'.$source};
 1431:             close($fh);
 1432:             if ($parser eq 'parse') {
 1433:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1434:                 unless ($parse_result eq 'ok') {
 1435:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1436:                 }
 1437:             }
 1438:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1439:                                  $home);
 1440:             if ($fetchresult eq 'ok') {
 1441:                 return '/uploaded/'.$fpath.'/'.$fname;
 1442:             } else {
 1443:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1444:                         ' to host '.$home.': '.$fetchresult);
 1445:                 return '/adm/notfound.html';
 1446:             }
 1447:         }
 1448:     }
 1449:     unless ( $fetchresult eq 'ok') {
 1450:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1451:              ' to host '.$home.': '.$fetchresult);
 1452:     }
 1453:     return $fetchresult;
 1454: }
 1455: 
 1456: sub build_filepath {
 1457:     my ($fpath) = @_;
 1458:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1459:     unless ($fpath eq '') {
 1460:         my @parts=split('/',$fpath);
 1461:         foreach my $part (@parts) {
 1462:             $filepath.= '/'.$part;
 1463:             if ((-e $filepath)!=1) {
 1464:                 mkdir($filepath,0777);
 1465:             }
 1466:         }
 1467:     }
 1468:     return $filepath;
 1469: }
 1470: 
 1471: sub store_edited_file {
 1472:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1473:     my $file = $primary_url;
 1474:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1475:     my $fpath = '';
 1476:     my $fname = $file;
 1477:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1478:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1479:     my $filepath = &build_filepath($fpath);
 1480:     open(my $fh,'>'.$filepath.'/'.$fname);
 1481:     print $fh $content;
 1482:     close($fh);
 1483:     my $home=&homeserver($docuname,$docudom);
 1484:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1485: 			  $home);
 1486:     if ($$fetchresult eq 'ok') {
 1487:         return '/uploaded/'.$fpath.'/'.$fname;
 1488:     } else {
 1489:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1490: 		 ' to host '.$home.': '.$$fetchresult);
 1491:         return '/adm/notfound.html';
 1492:     }
 1493: }
 1494: 
 1495: sub clean_filename {
 1496:     my ($fname,$args)=@_;
 1497: # Replace Windows backslashes by forward slashes
 1498:     $fname=~s/\\/\//g;
 1499:     if (!$args->{'keep_path'}) {
 1500:         # Get rid of everything but the actual filename
 1501: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1502:     }
 1503: # Replace spaces by underscores
 1504:     $fname=~s/\s+/\_/g;
 1505: # Replace all other weird characters by nothing
 1506:     $fname=~s{[^/\w\.\-]}{}g;
 1507: # Replace all .\d. sequences with _\d. so they no longer look like version
 1508: # numbers
 1509:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1510:     return $fname;
 1511: }
 1512: 
 1513: # --------------- Take an uploaded file and put it into the userfiles directory
 1514: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1515: #                    the desired filenam is in $env{"form.$formname.filename"}
 1516: #        $coursedoc - if true up to the current course
 1517: #                     if false
 1518: #        $subdir - directory in userfile to store the file into
 1519: #        $parser, $allfiles, $codebase - unknown
 1520: #
 1521: # output: url of file in userspace, or error: <message> 
 1522: #             or /adm/notfound.html if failure to upload occurse
 1523: 
 1524: 
 1525: sub userfileupload {
 1526:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1527:     if (!defined($subdir)) { $subdir='unknown'; }
 1528:     my $fname=$env{'form.'.$formname.'.filename'};
 1529:     $fname=&clean_filename($fname);
 1530: # See if there is anything left
 1531:     unless ($fname) { return 'error: no uploaded file'; }
 1532:     chop($env{'form.'.$formname});
 1533:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1534:         my $now = time;
 1535:         my $filepath = 'tmp/helprequests/'.$now;
 1536:         my @parts=split(/\//,$filepath);
 1537:         my $fullpath = $perlvar{'lonDaemons'};
 1538:         for (my $i=0;$i<@parts;$i++) {
 1539:             $fullpath .= '/'.$parts[$i];
 1540:             if ((-e $fullpath)!=1) {
 1541:                 mkdir($fullpath,0777);
 1542:             }
 1543:         }
 1544:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1545:         print $fh $env{'form.'.$formname};
 1546:         close($fh);
 1547:         return $fullpath.'/'.$fname;
 1548:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1549:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1550:                        '_'.$env{'user.domain'}.'/pending';
 1551:         my @parts=split(/\//,$filepath);
 1552:         my $fullpath = $perlvar{'lonDaemons'};
 1553:         for (my $i=0;$i<@parts;$i++) {
 1554:             $fullpath .= '/'.$parts[$i];
 1555:             if ((-e $fullpath)!=1) {
 1556:                 mkdir($fullpath,0777);
 1557:             }
 1558:         }
 1559:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1560:         print $fh $env{'form.'.$formname};
 1561:         close($fh);
 1562:         return $fullpath.'/'.$fname;
 1563:     }
 1564:     
 1565: # Create the directory if not present
 1566:     $fname="$subdir/$fname";
 1567:     if ($coursedoc) {
 1568: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1569: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1570:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1571:             return &finishuserfileupload($docuname,$docudom,
 1572: 					 $formname,$fname,$parser,$allfiles,
 1573: 					 $codebase);
 1574:         } else {
 1575:             $fname=$env{'form.folder'}.'/'.$fname;
 1576:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1577: 				       $fname,$formname,$parser,
 1578: 				       $allfiles,$codebase);
 1579:         }
 1580:     } elsif (defined($destuname)) {
 1581:         my $docuname=$destuname;
 1582:         my $docudom=$destudom;
 1583: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1584: 				     $fname,$parser,$allfiles,$codebase);
 1585:         
 1586:     } else {
 1587:         my $docuname=$env{'user.name'};
 1588:         my $docudom=$env{'user.domain'};
 1589:         if (exists($env{'form.group'})) {
 1590:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1591:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1592:         }
 1593: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1594: 				     $fname,$parser,$allfiles,$codebase);
 1595:     }
 1596: }
 1597: 
 1598: sub finishuserfileupload {
 1599:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1600:     my $path=$docudom.'/'.$docuname.'/';
 1601:     my $filepath=$perlvar{'lonDocRoot'};
 1602:     my ($fnamepath,$file);
 1603:     $file=$fname;
 1604:     if ($fname=~m|/|) {
 1605:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1606: 	$path.=$fnamepath.'/';
 1607:     }
 1608:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1609:     my $count;
 1610:     for ($count=4;$count<=$#parts;$count++) {
 1611:         $filepath.="/$parts[$count]";
 1612:         if ((-e $filepath)!=1) {
 1613: 	    mkdir($filepath,0777);
 1614:         }
 1615:     }
 1616: # Save the file
 1617:     {
 1618: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1619: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1620: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1621: 	    return '/adm/notfound.html';
 1622: 	}
 1623: 	if (!print FH ($env{'form.'.$formname})) {
 1624: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1625: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1626: 	    return '/adm/notfound.html';
 1627: 	}
 1628: 	close(FH);
 1629:     }
 1630:     if ($parser eq 'parse') {
 1631:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1632: 						   $codebase);
 1633:         unless ($parse_result eq 'ok') {
 1634:             &logthis('Failed to parse '.$filepath.$file.
 1635: 		     ' for embedded media: '.$parse_result); 
 1636:         }
 1637:     }
 1638: # Notify homeserver to grep it
 1639: #
 1640:     my $docuhome=&homeserver($docuname,$docudom);
 1641:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1642:     if ($fetchresult eq 'ok') {
 1643: #
 1644: # Return the URL to it
 1645:         return '/uploaded/'.$path.$file;
 1646:     } else {
 1647:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1648: 		 ': '.$fetchresult);
 1649:         return '/adm/notfound.html';
 1650:     }    
 1651: }
 1652: 
 1653: sub extract_embedded_items {
 1654:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1655:     my @state = ();
 1656:     my %javafiles = (
 1657:                       codebase => '',
 1658:                       code => '',
 1659:                       archive => ''
 1660:                     );
 1661:     my %mediafiles = (
 1662:                       src => '',
 1663:                       movie => '',
 1664:                      );
 1665:     my $p;
 1666:     if ($content) {
 1667:         $p = HTML::LCParser->new($content);
 1668:     } else {
 1669:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1670:     }
 1671:     while (my $t=$p->get_token()) {
 1672: 	if ($t->[0] eq 'S') {
 1673: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1674: 	    push (@state, $tagname);
 1675:             if (lc($tagname) eq 'allow') {
 1676:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1677:             }
 1678: 	    if (lc($tagname) eq 'img') {
 1679: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1680: 	    }
 1681:             if (lc($tagname) eq 'script') {
 1682:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1683:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1684:                 } else {
 1685:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1686:                 }
 1687:             }
 1688:             if (lc($tagname) eq 'link') {
 1689:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1690:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1691:                 }
 1692:             }
 1693: 	    if (lc($tagname) eq 'object' ||
 1694: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1695: 		foreach my $item (keys(%javafiles)) {
 1696: 		    $javafiles{$item} = '';
 1697: 		}
 1698: 	    }
 1699: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1700: 		my $name = lc($attr->{'name'});
 1701: 		foreach my $item (keys(%javafiles)) {
 1702: 		    if ($name eq $item) {
 1703: 			$javafiles{$item} = $attr->{'value'};
 1704: 			last;
 1705: 		    }
 1706: 		}
 1707: 		foreach my $item (keys(%mediafiles)) {
 1708: 		    if ($name eq $item) {
 1709: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1710: 			last;
 1711: 		    }
 1712: 		}
 1713: 	    }
 1714: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1715: 		foreach my $item (keys(%javafiles)) {
 1716: 		    if ($attr->{$item}) {
 1717: 			$javafiles{$item} = $attr->{$item};
 1718: 			last;
 1719: 		    }
 1720: 		}
 1721: 		foreach my $item (keys(%mediafiles)) {
 1722: 		    if ($attr->{$item}) {
 1723: 			&add_filetype($allfiles,$attr->{$item},$item);
 1724: 			last;
 1725: 		    }
 1726: 		}
 1727: 	    }
 1728: 	} elsif ($t->[0] eq 'E') {
 1729: 	    my ($tagname) = ($t->[1]);
 1730: 	    if ($javafiles{'codebase'} ne '') {
 1731: 		$javafiles{'codebase'} .= '/';
 1732: 	    }  
 1733: 	    if (lc($tagname) eq 'applet' ||
 1734: 		lc($tagname) eq 'object' ||
 1735: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1736: 		) {
 1737: 		foreach my $item (keys(%javafiles)) {
 1738: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1739: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1740: 			&add_filetype($allfiles,$file,$item);
 1741: 		    }
 1742: 		}
 1743: 	    } 
 1744: 	    pop @state;
 1745: 	}
 1746:     }
 1747:     return 'ok';
 1748: }
 1749: 
 1750: sub add_filetype {
 1751:     my ($allfiles,$file,$type)=@_;
 1752:     if (exists($allfiles->{$file})) {
 1753: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1754: 	    push(@{$allfiles->{$file}}, &escape($type));
 1755: 	}
 1756:     } else {
 1757: 	@{$allfiles->{$file}} = (&escape($type));
 1758:     }
 1759: }
 1760: 
 1761: sub removeuploadedurl {
 1762:     my ($url)=@_;
 1763:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1764:     return &removeuserfile($uname,$udom,$fname);
 1765: }
 1766: 
 1767: sub removeuserfile {
 1768:     my ($docuname,$docudom,$fname)=@_;
 1769:     my $home=&homeserver($docuname,$docudom);
 1770:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1771:     if ($result eq 'ok') {
 1772:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1773:             my $metafile = $fname.'.meta';
 1774:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1775: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1776:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1777:             my $sqlresult = 
 1778:                 &update_portfolio_table($docuname,$docudom,$file,
 1779:                                         'portfolio_metadata',$group,
 1780:                                         'delete');
 1781:         }
 1782:     }
 1783:     return $result;
 1784: }
 1785: 
 1786: sub mkdiruserfile {
 1787:     my ($docuname,$docudom,$dir)=@_;
 1788:     my $home=&homeserver($docuname,$docudom);
 1789:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1790: }
 1791: 
 1792: sub renameuserfile {
 1793:     my ($docuname,$docudom,$old,$new)=@_;
 1794:     my $home=&homeserver($docuname,$docudom);
 1795:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1796:                         &escape("$old").':'.&escape("$new"),$home);
 1797:     if ($result eq 'ok') {
 1798:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1799:             my $oldmeta = $old.'.meta';
 1800:             my $newmeta = $new.'.meta';
 1801:             my $metaresult = 
 1802:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1803: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1804:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1805:             my $sqlresult = 
 1806:                 &update_portfolio_table($docuname,$docudom,$file,
 1807:                                         'portfolio_metadata',$group,
 1808:                                         'delete');
 1809:         }
 1810:     }
 1811:     return $result;
 1812: }
 1813: 
 1814: # ------------------------------------------------------------------------- Log
 1815: 
 1816: sub log {
 1817:     my ($dom,$nam,$hom,$what)=@_;
 1818:     return critical("log:$dom:$nam:$what",$hom);
 1819: }
 1820: 
 1821: # ------------------------------------------------------------------ Course Log
 1822: #
 1823: # This routine flushes several buffers of non-mission-critical nature
 1824: #
 1825: 
 1826: sub flushcourselogs {
 1827:     &logthis('Flushing log buffers');
 1828: #
 1829: # course logs
 1830: # This is a log of all transactions in a course, which can be used
 1831: # for data mining purposes
 1832: #
 1833: # It also collects the courseid database, which lists last transaction
 1834: # times and course titles for all courseids
 1835: #
 1836:     my %courseidbuffer=();
 1837:     foreach my $crsid (keys %courselogs) {
 1838:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1839: 		          &escape($courselogs{$crsid}),
 1840: 		          $coursehombuf{$crsid}) eq 'ok') {
 1841: 	    delete $courselogs{$crsid};
 1842:         } else {
 1843:             &logthis('Failed to flush log buffer for '.$crsid);
 1844:             if (length($courselogs{$crsid})>40000) {
 1845:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1846:                         " exceeded maximum size, deleting.</font>");
 1847:                delete $courselogs{$crsid};
 1848:             }
 1849:         }
 1850:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1851:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1852: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1853:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1854:         } else {
 1855:            $courseidbuffer{$coursehombuf{$crsid}}=
 1856: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1857:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1858:         }
 1859:     }
 1860: #
 1861: # Write course id database (reverse lookup) to homeserver of courses 
 1862: # Is used in pickcourse
 1863: #
 1864:     foreach my $crs_home (keys(%courseidbuffer)) {
 1865:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1866: 		     $crs_home);
 1867:     }
 1868: #
 1869: # File accesses
 1870: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1871: #
 1872:     foreach my $entry (keys(%accesshash)) {
 1873:         if ($entry =~ /___count$/) {
 1874:             my ($dom,$name);
 1875:             ($dom,$name,undef)=
 1876: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1877:             if (! defined($dom) || $dom eq '' || 
 1878:                 ! defined($name) || $name eq '') {
 1879:                 my $cid = $env{'request.course.id'};
 1880:                 $dom  = $env{'request.'.$cid.'.domain'};
 1881:                 $name = $env{'request.'.$cid.'.num'};
 1882:             }
 1883:             my $value = $accesshash{$entry};
 1884:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1885:             my %temphash=($url => $value);
 1886:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1887:             if ($result eq 'ok') {
 1888:                 delete $accesshash{$entry};
 1889:             } elsif ($result eq 'unknown_cmd') {
 1890:                 # Target server has old code running on it.
 1891:                 my %temphash=($entry => $value);
 1892:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1893:                     delete $accesshash{$entry};
 1894:                 }
 1895:             }
 1896:         } else {
 1897:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1898:             my %temphash=($entry => $accesshash{$entry});
 1899:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1900:                 delete $accesshash{$entry};
 1901:             }
 1902:         }
 1903:     }
 1904: #
 1905: # Roles
 1906: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1907: #
 1908:     foreach my $entry (keys(%userrolehash)) {
 1909:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1910: 	    split(/\:/,$entry);
 1911:         if (&Apache::lonnet::put('nohist_userroles',
 1912:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1913:                 $rudom,$runame) eq 'ok') {
 1914: 	    delete $userrolehash{$entry};
 1915:         }
 1916:     }
 1917: #
 1918: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1919: #
 1920:     my %domrolebuffer = ();
 1921:     foreach my $entry (keys %domainrolehash) {
 1922:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1923:         if ($domrolebuffer{$rudom}) {
 1924:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1925:                       '='.&escape($domainrolehash{$entry});
 1926:         } else {
 1927:             $domrolebuffer{$rudom}.=&escape($entry).
 1928:                       '='.&escape($domainrolehash{$entry});
 1929:         }
 1930:         delete $domainrolehash{$entry};
 1931:     }
 1932:     foreach my $dom (keys(%domrolebuffer)) {
 1933: 	my %servers = &get_servers($dom,'library');
 1934: 	foreach my $tryserver (keys(%servers)) {
 1935: 	    unless (&reply('domroleput:'.$dom.':'.
 1936: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1937: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1938: 	    }
 1939:         }
 1940:     }
 1941:     $dumpcount++;
 1942: }
 1943: 
 1944: sub courselog {
 1945:     my $what=shift;
 1946:     $what=time.':'.$what;
 1947:     unless ($env{'request.course.id'}) { return ''; }
 1948:     $coursedombuf{$env{'request.course.id'}}=
 1949:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1950:     $coursenumbuf{$env{'request.course.id'}}=
 1951:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1952:     $coursehombuf{$env{'request.course.id'}}=
 1953:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1954:     $coursedescrbuf{$env{'request.course.id'}}=
 1955:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1956:     $courseinstcodebuf{$env{'request.course.id'}}=
 1957:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1958:     $courseownerbuf{$env{'request.course.id'}}=
 1959:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1960:     $coursetypebuf{$env{'request.course.id'}}=
 1961:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1962:     if (defined $courselogs{$env{'request.course.id'}}) {
 1963: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1964:     } else {
 1965: 	$courselogs{$env{'request.course.id'}}.=$what;
 1966:     }
 1967:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1968: 	&flushcourselogs();
 1969:     }
 1970: }
 1971: 
 1972: sub courseacclog {
 1973:     my $fnsymb=shift;
 1974:     unless ($env{'request.course.id'}) { return ''; }
 1975:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1976:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1977:         $what.=':POST';
 1978:         # FIXME: Probably ought to escape things....
 1979: 	foreach my $key (keys(%env)) {
 1980:             if ($key=~/^form\.(.*)/) {
 1981: 		$what.=':'.$1.'='.$env{$key};
 1982:             }
 1983:         }
 1984:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1985:         # FIXME: We should not be depending on a form parameter that someone
 1986:         # editing lonsearchcat.pm might change in the future.
 1987:         if ($env{'form.phase'} eq 'course_search') {
 1988:             $what.= ':POST';
 1989:             # FIXME: Probably ought to escape things....
 1990:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1991:                                  'crsdiscuss') {
 1992:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1993:             }
 1994:         }
 1995:     }
 1996:     &courselog($what);
 1997: }
 1998: 
 1999: sub countacc {
 2000:     my $url=&declutter(shift);
 2001:     return if (! defined($url) || $url eq '');
 2002:     unless ($env{'request.course.id'}) { return ''; }
 2003:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2004:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2005:     $accesshash{$key}++;
 2006: }
 2007: 
 2008: sub linklog {
 2009:     my ($from,$to)=@_;
 2010:     $from=&declutter($from);
 2011:     $to=&declutter($to);
 2012:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2013:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2014: }
 2015:   
 2016: sub userrolelog {
 2017:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2018:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2019:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2020:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2021:         ($trole=~/^ta/)) {
 2022:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2023:        $userrolehash
 2024:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2025:                     =$tend.':'.$tstart;
 2026:     }
 2027:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2028:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2029:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2030:         ($trole=~/^sc/)) {
 2031:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2032:        $domainrolehash
 2033:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2034:                     = $tend.':'.$tstart;
 2035:     }
 2036: }
 2037: 
 2038: sub get_course_adv_roles {
 2039:     my $cid=shift;
 2040:     $cid=$env{'request.course.id'} unless (defined($cid));
 2041:     my %coursehash=&coursedescription($cid);
 2042:     my %nothide=();
 2043:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2044: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2045:     }
 2046:     my %returnhash=();
 2047:     my %dumphash=
 2048:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2049:     my $now=time;
 2050:     foreach my $entry (keys %dumphash) {
 2051: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2052:         if (($tstart) && ($tstart<0)) { next; }
 2053:         if (($tend) && ($tend<$now)) { next; }
 2054:         if (($tstart) && ($now<$tstart)) { next; }
 2055:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2056: 	if ($username eq '' || $domain eq '') { next; }
 2057: 	if ((&privileged($username,$domain)) && 
 2058: 	    (!$nothide{$username.':'.$domain})) { next; }
 2059: 	if ($role eq 'cr') { next; }
 2060:         my $key=&plaintext($role);
 2061:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2062:         if ($returnhash{$key}) {
 2063: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2064:         } else {
 2065:             $returnhash{$key}=$username.':'.$domain;
 2066:         }
 2067:      }
 2068:     return %returnhash;
 2069: }
 2070: 
 2071: sub get_my_roles {
 2072:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
 2073:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2074:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2075:     my %dumphash=
 2076:             &dump('nohist_userroles',$udom,$uname);
 2077:     my %returnhash=();
 2078:     my $now=time;
 2079:     foreach my $entry (keys(%dumphash)) {
 2080: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2081:         if (($tstart) && ($tstart<0)) { next; }
 2082:         my $status = 'active';
 2083:         if (($tend) && ($tend<$now)) {
 2084:             $status = 'previous';
 2085:         } 
 2086:         if (($tstart) && ($now<$tstart)) {
 2087:             $status = 'future';
 2088:         }
 2089:         if (ref($types) eq 'ARRAY') {
 2090:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2091:                 next;
 2092:             } 
 2093:         } else {
 2094:             if ($status ne 'active') {
 2095:                 next;
 2096:             }
 2097:         }
 2098:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2099:         if (ref($roledoms) eq 'ARRAY') {
 2100:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2101:                 next;
 2102:             }
 2103:         }
 2104:         if (ref($roles) eq 'ARRAY') {
 2105:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2106:                 next;
 2107:             }
 2108:         } 
 2109: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2110:     }
 2111:     return %returnhash;
 2112: }
 2113: 
 2114: # ----------------------------------------------------- Frontpage Announcements
 2115: #
 2116: #
 2117: 
 2118: sub postannounce {
 2119:     my ($server,$text)=@_;
 2120:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2121:     unless ($text=~/\w/) { $text=''; }
 2122:     return &reply('setannounce:'.&escape($text),$server);
 2123: }
 2124: 
 2125: sub getannounce {
 2126: 
 2127:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2128: 	my $announcement='';
 2129: 	while (my $line = <$fh>) { $announcement .= $line; }
 2130: 	close($fh);
 2131: 	if ($announcement=~/\w/) { 
 2132: 	    return 
 2133:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2134:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2135: 	} else {
 2136: 	    return '';
 2137: 	}
 2138:     } else {
 2139: 	return '';
 2140:     }
 2141: }
 2142: 
 2143: # ---------------------------------------------------------- Course ID routines
 2144: # Deal with domain's nohist_courseid.db files
 2145: #
 2146: 
 2147: sub courseidput {
 2148:     my ($domain,$what,$coursehome)=@_;
 2149:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2150: }
 2151: 
 2152: sub courseiddump {
 2153:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2154:     my %returnhash=();
 2155:     unless ($domfilter) { $domfilter=''; }
 2156:     my %libserv = &all_library();
 2157:     foreach my $tryserver (keys(%libserv)) {
 2158:         if ( (  $hostidflag == 1 
 2159: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2160: 	     || (!defined($hostidflag)) ) {
 2161: 
 2162: 	    if ($domfilter eq ''
 2163: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2164: 	        foreach my $line (
 2165:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2166: 			       $sincefilter.':'.&escape($descfilter).':'.
 2167:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2168:                                $tryserver))) {
 2169: 		    my ($key,$value)=split(/\=/,$line,2);
 2170:                     if (($key) && ($value)) {
 2171: 		        $returnhash{&unescape($key)}=$value;
 2172:                     }
 2173:                 }
 2174:             }
 2175:         }
 2176:     }
 2177:     return %returnhash;
 2178: }
 2179: 
 2180: # ---------------------------------------------------------- DC e-mail
 2181: 
 2182: sub dcmailput {
 2183:     my ($domain,$msgid,$message,$server)=@_;
 2184:     my $status = &Apache::lonnet::critical(
 2185:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2186:        &escape($message),$server);
 2187:     return $status;
 2188: }
 2189: 
 2190: sub dcmaildump {
 2191:     my ($dom,$startdate,$enddate,$senders) = @_;
 2192:     my %returnhash=();
 2193: 
 2194:     if (defined(&domain($dom,'primary'))) {
 2195:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2196:                                                          &escape($enddate).':';
 2197: 	my @esc_senders=map { &escape($_)} @$senders;
 2198: 	$cmd.=&escape(join('&',@esc_senders));
 2199: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2200:             my ($key,$value) = split(/\=/,$line,2);
 2201:             if (($key) && ($value)) {
 2202:                 $returnhash{&unescape($key)} = &unescape($value);
 2203:             }
 2204:         }
 2205:     }
 2206:     return %returnhash;
 2207: }
 2208: # ---------------------------------------------------------- Domain roles
 2209: 
 2210: sub get_domain_roles {
 2211:     my ($dom,$roles,$startdate,$enddate)=@_;
 2212:     if (undef($startdate) || $startdate eq '') {
 2213:         $startdate = '.';
 2214:     }
 2215:     if (undef($enddate) || $enddate eq '') {
 2216:         $enddate = '.';
 2217:     }
 2218:     my $rolelist = join(':',@{$roles});
 2219:     my %personnel = ();
 2220: 
 2221:     my %servers = &get_servers($dom,'library');
 2222:     foreach my $tryserver (keys(%servers)) {
 2223: 	%{$personnel{$tryserver}}=();
 2224: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2225: 					    &escape($startdate).':'.
 2226: 					    &escape($enddate).':'.
 2227: 					    &escape($rolelist), $tryserver))) {
 2228: 	    my ($key,$value) = split(/\=/,$line,2);
 2229: 	    if (($key) && ($value)) {
 2230: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2231: 	    }
 2232: 	}
 2233:     }
 2234:     return %personnel;
 2235: }
 2236: 
 2237: # ----------------------------------------------------------- Check out an item
 2238: 
 2239: sub get_first_access {
 2240:     my ($type,$argsymb)=@_;
 2241:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2242:     if ($argsymb) { $symb=$argsymb; }
 2243:     my ($map,$id,$res)=&decode_symb($symb);
 2244:     if ($type eq 'map') {
 2245: 	$res=&symbread($map);
 2246:     } else {
 2247: 	$res=$symb;
 2248:     }
 2249:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2250:     return $times{"$courseid\0$res"};
 2251: }
 2252: 
 2253: sub set_first_access {
 2254:     my ($type)=@_;
 2255:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2256:     my ($map,$id,$res)=&decode_symb($symb);
 2257:     if ($type eq 'map') {
 2258: 	$res=&symbread($map);
 2259:     } else {
 2260: 	$res=$symb;
 2261:     }
 2262:     my $firstaccess=&get_first_access($type,$symb);
 2263:     if (!$firstaccess) {
 2264: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2265:     }
 2266:     return 'already_set';
 2267: }
 2268: 
 2269: sub checkout {
 2270:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2271:     my $now=time;
 2272:     my $lonhost=$perlvar{'lonHostID'};
 2273:     my $infostr=&escape(
 2274:                  'CHECKOUTTOKEN&'.
 2275:                  $tuname.'&'.
 2276:                  $tudom.'&'.
 2277:                  $tcrsid.'&'.
 2278:                  $symb.'&'.
 2279: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2280:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2281:     if ($token=~/^error\:/) { 
 2282:         &logthis("<font color=\"blue\">WARNING: ".
 2283:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2284:                  "</font>");
 2285:         return ''; 
 2286:     }
 2287: 
 2288:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2289:     $token=~tr/a-z/A-Z/;
 2290: 
 2291:     my %infohash=('resource.0.outtoken' => $token,
 2292:                   'resource.0.checkouttime' => $now,
 2293:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2294: 
 2295:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2296:        return '';
 2297:     } else {
 2298:         &logthis("<font color=\"blue\">WARNING: ".
 2299:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2300:                  "</font>");
 2301:     }    
 2302: 
 2303:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2304:                          &escape('Checkout '.$infostr.' - '.
 2305:                                                  $token)) ne 'ok') {
 2306: 	return '';
 2307:     } else {
 2308:         &logthis("<font color=\"blue\">WARNING: ".
 2309:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2310:                  "</font>");
 2311:     }
 2312:     return $token;
 2313: }
 2314: 
 2315: # ------------------------------------------------------------ Check in an item
 2316: 
 2317: sub checkin {
 2318:     my $token=shift;
 2319:     my $now=time;
 2320:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2321:     $lonhost=~tr/A-Z/a-z/;
 2322:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2323:     $dtoken=~s/\W/\_/g;
 2324:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2325:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2326: 
 2327:     unless (($tuname) && ($tudom)) {
 2328:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2329:         return '';
 2330:     }
 2331:     
 2332:     unless (&allowed('mgr',$tcrsid)) {
 2333:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2334:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2335:         return '';
 2336:     }
 2337: 
 2338:     my %infohash=('resource.0.intoken' => $token,
 2339:                   'resource.0.checkintime' => $now,
 2340:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2341: 
 2342:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2343:        return '';
 2344:     }    
 2345: 
 2346:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2347:                          &escape('Checkin - '.$token)) ne 'ok') {
 2348: 	return '';
 2349:     }
 2350: 
 2351:     return ($symb,$tuname,$tudom,$tcrsid);    
 2352: }
 2353: 
 2354: # --------------------------------------------- Set Expire Date for Spreadsheet
 2355: 
 2356: sub expirespread {
 2357:     my ($uname,$udom,$stype,$usymb)=@_;
 2358:     my $cid=$env{'request.course.id'}; 
 2359:     if ($cid) {
 2360:        my $now=time;
 2361:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2362:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2363:                             $env{'course.'.$cid.'.num'}.
 2364: 	        	    ':nohist_expirationdates:'.
 2365:                             &escape($key).'='.$now,
 2366:                             $env{'course.'.$cid.'.home'})
 2367:     }
 2368:     return 'ok';
 2369: }
 2370: 
 2371: # ----------------------------------------------------- Devalidate Spreadsheets
 2372: 
 2373: sub devalidate {
 2374:     my ($symb,$uname,$udom)=@_;
 2375:     my $cid=$env{'request.course.id'}; 
 2376:     if ($cid) {
 2377:         # delete the stored spreadsheets for
 2378:         # - the student level sheet of this user in course's homespace
 2379:         # - the assessment level sheet for this resource 
 2380:         #   for this user in user's homespace
 2381: 	# - current conditional state info
 2382: 	my $key=$uname.':'.$udom.':';
 2383:         my $status=
 2384: 	    &del('nohist_calculatedsheets',
 2385: 		 [$key.'studentcalc:'],
 2386: 		 $env{'course.'.$cid.'.domain'},
 2387: 		 $env{'course.'.$cid.'.num'})
 2388: 		.' '.
 2389: 	    &del('nohist_calculatedsheets_'.$cid,
 2390: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2391:         unless ($status eq 'ok ok') {
 2392:            &logthis('Could not devalidate spreadsheet '.
 2393:                     $uname.' at '.$udom.' for '.
 2394: 		    $symb.': '.$status);
 2395:         }
 2396: 	&delenv('user.state.'.$cid);
 2397:     }
 2398: }
 2399: 
 2400: sub get_scalar {
 2401:     my ($string,$end) = @_;
 2402:     my $value;
 2403:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2404: 	$value = $1;
 2405:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2406: 	$value = $1;
 2407:     }
 2408:     return &unescape($value);
 2409: }
 2410: 
 2411: sub array2str {
 2412:   my (@array) = @_;
 2413:   my $result=&arrayref2str(\@array);
 2414:   $result=~s/^__ARRAY_REF__//;
 2415:   $result=~s/__END_ARRAY_REF__$//;
 2416:   return $result;
 2417: }
 2418: 
 2419: sub arrayref2str {
 2420:   my ($arrayref) = @_;
 2421:   my $result='__ARRAY_REF__';
 2422:   foreach my $elem (@$arrayref) {
 2423:     if(ref($elem) eq 'ARRAY') {
 2424:       $result.=&arrayref2str($elem).'&';
 2425:     } elsif(ref($elem) eq 'HASH') {
 2426:       $result.=&hashref2str($elem).'&';
 2427:     } elsif(ref($elem)) {
 2428:       #print("Got a ref of ".(ref($elem))." skipping.");
 2429:     } else {
 2430:       $result.=&escape($elem).'&';
 2431:     }
 2432:   }
 2433:   $result=~s/\&$//;
 2434:   $result .= '__END_ARRAY_REF__';
 2435:   return $result;
 2436: }
 2437: 
 2438: sub hash2str {
 2439:   my (%hash) = @_;
 2440:   my $result=&hashref2str(\%hash);
 2441:   $result=~s/^__HASH_REF__//;
 2442:   $result=~s/__END_HASH_REF__$//;
 2443:   return $result;
 2444: }
 2445: 
 2446: sub hashref2str {
 2447:   my ($hashref)=@_;
 2448:   my $result='__HASH_REF__';
 2449:   foreach my $key (sort(keys(%$hashref))) {
 2450:     if (ref($key) eq 'ARRAY') {
 2451:       $result.=&arrayref2str($key).'=';
 2452:     } elsif (ref($key) eq 'HASH') {
 2453:       $result.=&hashref2str($key).'=';
 2454:     } elsif (ref($key)) {
 2455:       $result.='=';
 2456:       #print("Got a ref of ".(ref($key))." skipping.");
 2457:     } else {
 2458: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2459:     }
 2460: 
 2461:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2462:       $result.=&arrayref2str($hashref->{$key}).'&';
 2463:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2464:       $result.=&hashref2str($hashref->{$key}).'&';
 2465:     } elsif(ref($hashref->{$key})) {
 2466:        $result.='&';
 2467:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2468:     } else {
 2469:       $result.=&escape($hashref->{$key}).'&';
 2470:     }
 2471:   }
 2472:   $result=~s/\&$//;
 2473:   $result .= '__END_HASH_REF__';
 2474:   return $result;
 2475: }
 2476: 
 2477: sub str2hash {
 2478:     my ($string)=@_;
 2479:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2480:     return %$hash;
 2481: }
 2482: 
 2483: sub str2hashref {
 2484:   my ($string) = @_;
 2485: 
 2486:   my %hash;
 2487: 
 2488:   if($string !~ /^__HASH_REF__/) {
 2489:       if (! ($string eq '' || !defined($string))) {
 2490: 	  $hash{'error'}='Not hash reference';
 2491:       }
 2492:       return (\%hash, $string);
 2493:   }
 2494: 
 2495:   $string =~ s/^__HASH_REF__//;
 2496: 
 2497:   while($string !~ /^__END_HASH_REF__/) {
 2498:       #key
 2499:       my $key='';
 2500:       if($string =~ /^__HASH_REF__/) {
 2501:           ($key, $string)=&str2hashref($string);
 2502:           if(defined($key->{'error'})) {
 2503:               $hash{'error'}='Bad data';
 2504:               return (\%hash, $string);
 2505:           }
 2506:       } elsif($string =~ /^__ARRAY_REF__/) {
 2507:           ($key, $string)=&str2arrayref($string);
 2508:           if($key->[0] eq 'Array reference error') {
 2509:               $hash{'error'}='Bad data';
 2510:               return (\%hash, $string);
 2511:           }
 2512:       } else {
 2513:           $string =~ s/^(.*?)=//;
 2514: 	  $key=&unescape($1);
 2515:       }
 2516:       $string =~ s/^=//;
 2517: 
 2518:       #value
 2519:       my $value='';
 2520:       if($string =~ /^__HASH_REF__/) {
 2521:           ($value, $string)=&str2hashref($string);
 2522:           if(defined($value->{'error'})) {
 2523:               $hash{'error'}='Bad data';
 2524:               return (\%hash, $string);
 2525:           }
 2526:       } elsif($string =~ /^__ARRAY_REF__/) {
 2527:           ($value, $string)=&str2arrayref($string);
 2528:           if($value->[0] eq 'Array reference error') {
 2529:               $hash{'error'}='Bad data';
 2530:               return (\%hash, $string);
 2531:           }
 2532:       } else {
 2533: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2534:       }
 2535:       $string =~ s/^&//;
 2536: 
 2537:       $hash{$key}=$value;
 2538:   }
 2539: 
 2540:   $string =~ s/^__END_HASH_REF__//;
 2541: 
 2542:   return (\%hash, $string);
 2543: }
 2544: 
 2545: sub str2array {
 2546:     my ($string)=@_;
 2547:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2548:     return @$array;
 2549: }
 2550: 
 2551: sub str2arrayref {
 2552:   my ($string) = @_;
 2553:   my @array;
 2554: 
 2555:   if($string !~ /^__ARRAY_REF__/) {
 2556:       if (! ($string eq '' || !defined($string))) {
 2557: 	  $array[0]='Array reference error';
 2558:       }
 2559:       return (\@array, $string);
 2560:   }
 2561: 
 2562:   $string =~ s/^__ARRAY_REF__//;
 2563: 
 2564:   while($string !~ /^__END_ARRAY_REF__/) {
 2565:       my $value='';
 2566:       if($string =~ /^__HASH_REF__/) {
 2567:           ($value, $string)=&str2hashref($string);
 2568:           if(defined($value->{'error'})) {
 2569:               $array[0] ='Array reference error';
 2570:               return (\@array, $string);
 2571:           }
 2572:       } elsif($string =~ /^__ARRAY_REF__/) {
 2573:           ($value, $string)=&str2arrayref($string);
 2574:           if($value->[0] eq 'Array reference error') {
 2575:               $array[0] ='Array reference error';
 2576:               return (\@array, $string);
 2577:           }
 2578:       } else {
 2579: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2580:       }
 2581:       $string =~ s/^&//;
 2582: 
 2583:       push(@array, $value);
 2584:   }
 2585: 
 2586:   $string =~ s/^__END_ARRAY_REF__//;
 2587: 
 2588:   return (\@array, $string);
 2589: }
 2590: 
 2591: # -------------------------------------------------------------------Temp Store
 2592: 
 2593: sub tmpreset {
 2594:   my ($symb,$namespace,$domain,$stuname) = @_;
 2595:   if (!$symb) {
 2596:     $symb=&symbread();
 2597:     if (!$symb) { $symb= $env{'request.url'}; }
 2598:   }
 2599:   $symb=escape($symb);
 2600: 
 2601:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2602:   $namespace=~s/\//\_/g;
 2603:   $namespace=~s/\W//g;
 2604: 
 2605:   if (!$domain) { $domain=$env{'user.domain'}; }
 2606:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2607:   if ($domain eq 'public' && $stuname eq 'public') {
 2608:       $stuname=$ENV{'REMOTE_ADDR'};
 2609:   }
 2610:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2611:   my %hash;
 2612:   if (tie(%hash,'GDBM_File',
 2613: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2614: 	  &GDBM_WRCREAT(),0640)) {
 2615:     foreach my $key (keys %hash) {
 2616:       if ($key=~ /:$symb/) {
 2617: 	delete($hash{$key});
 2618:       }
 2619:     }
 2620:   }
 2621: }
 2622: 
 2623: sub tmpstore {
 2624:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2625: 
 2626:   if (!$symb) {
 2627:     $symb=&symbread();
 2628:     if (!$symb) { $symb= $env{'request.url'}; }
 2629:   }
 2630:   $symb=escape($symb);
 2631: 
 2632:   if (!$namespace) {
 2633:     # I don't think we would ever want to store this for a course.
 2634:     # it seems this will only be used if we don't have a course.
 2635:     #$namespace=$env{'request.course.id'};
 2636:     #if (!$namespace) {
 2637:       $namespace=$env{'request.state'};
 2638:     #}
 2639:   }
 2640:   $namespace=~s/\//\_/g;
 2641:   $namespace=~s/\W//g;
 2642:   if (!$domain) { $domain=$env{'user.domain'}; }
 2643:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2644:   if ($domain eq 'public' && $stuname eq 'public') {
 2645:       $stuname=$ENV{'REMOTE_ADDR'};
 2646:   }
 2647:   my $now=time;
 2648:   my %hash;
 2649:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2650:   if (tie(%hash,'GDBM_File',
 2651: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2652: 	  &GDBM_WRCREAT(),0640)) {
 2653:     $hash{"version:$symb"}++;
 2654:     my $version=$hash{"version:$symb"};
 2655:     my $allkeys=''; 
 2656:     foreach my $key (keys(%$storehash)) {
 2657:       $allkeys.=$key.':';
 2658:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2659:     }
 2660:     $hash{"$version:$symb:timestamp"}=$now;
 2661:     $allkeys.='timestamp';
 2662:     $hash{"$version:keys:$symb"}=$allkeys;
 2663:     if (untie(%hash)) {
 2664:       return 'ok';
 2665:     } else {
 2666:       return "error:$!";
 2667:     }
 2668:   } else {
 2669:     return "error:$!";
 2670:   }
 2671: }
 2672: 
 2673: # -----------------------------------------------------------------Temp Restore
 2674: 
 2675: sub tmprestore {
 2676:   my ($symb,$namespace,$domain,$stuname) = @_;
 2677: 
 2678:   if (!$symb) {
 2679:     $symb=&symbread();
 2680:     if (!$symb) { $symb= $env{'request.url'}; }
 2681:   }
 2682:   $symb=escape($symb);
 2683: 
 2684:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2685: 
 2686:   if (!$domain) { $domain=$env{'user.domain'}; }
 2687:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2688:   if ($domain eq 'public' && $stuname eq 'public') {
 2689:       $stuname=$ENV{'REMOTE_ADDR'};
 2690:   }
 2691:   my %returnhash;
 2692:   $namespace=~s/\//\_/g;
 2693:   $namespace=~s/\W//g;
 2694:   my %hash;
 2695:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2696:   if (tie(%hash,'GDBM_File',
 2697: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2698: 	  &GDBM_READER(),0640)) {
 2699:     my $version=$hash{"version:$symb"};
 2700:     $returnhash{'version'}=$version;
 2701:     my $scope;
 2702:     for ($scope=1;$scope<=$version;$scope++) {
 2703:       my $vkeys=$hash{"$scope:keys:$symb"};
 2704:       my @keys=split(/:/,$vkeys);
 2705:       my $key;
 2706:       $returnhash{"$scope:keys"}=$vkeys;
 2707:       foreach $key (@keys) {
 2708: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2709: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2710:       }
 2711:     }
 2712:     if (!(untie(%hash))) {
 2713:       return "error:$!";
 2714:     }
 2715:   } else {
 2716:     return "error:$!";
 2717:   }
 2718:   return %returnhash;
 2719: }
 2720: 
 2721: # ----------------------------------------------------------------------- Store
 2722: 
 2723: sub store {
 2724:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2725:     my $home='';
 2726: 
 2727:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2728: 
 2729:     $symb=&symbclean($symb);
 2730:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2731: 
 2732:     if (!$domain) { $domain=$env{'user.domain'}; }
 2733:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2734: 
 2735:     &devalidate($symb,$stuname,$domain);
 2736: 
 2737:     $symb=escape($symb);
 2738:     if (!$namespace) { 
 2739:        unless ($namespace=$env{'request.course.id'}) { 
 2740:           return ''; 
 2741:        } 
 2742:     }
 2743:     if (!$home) { $home=$env{'user.home'}; }
 2744: 
 2745:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2746:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2747: 
 2748:     my $namevalue='';
 2749:     foreach my $key (keys(%$storehash)) {
 2750:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2751:     }
 2752:     $namevalue=~s/\&$//;
 2753:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2754:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2755: }
 2756: 
 2757: # -------------------------------------------------------------- Critical Store
 2758: 
 2759: sub cstore {
 2760:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2761:     my $home='';
 2762: 
 2763:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2764: 
 2765:     $symb=&symbclean($symb);
 2766:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2767: 
 2768:     if (!$domain) { $domain=$env{'user.domain'}; }
 2769:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2770: 
 2771:     &devalidate($symb,$stuname,$domain);
 2772: 
 2773:     $symb=escape($symb);
 2774:     if (!$namespace) { 
 2775:        unless ($namespace=$env{'request.course.id'}) { 
 2776:           return ''; 
 2777:        } 
 2778:     }
 2779:     if (!$home) { $home=$env{'user.home'}; }
 2780: 
 2781:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2782:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2783: 
 2784:     my $namevalue='';
 2785:     foreach my $key (keys(%$storehash)) {
 2786:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2787:     }
 2788:     $namevalue=~s/\&$//;
 2789:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2790:     return critical
 2791:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2792: }
 2793: 
 2794: # --------------------------------------------------------------------- Restore
 2795: 
 2796: sub restore {
 2797:     my ($symb,$namespace,$domain,$stuname) = @_;
 2798:     my $home='';
 2799: 
 2800:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2801: 
 2802:     if (!$symb) {
 2803:       unless ($symb=escape(&symbread())) { return ''; }
 2804:     } else {
 2805:       $symb=&escape(&symbclean($symb));
 2806:     }
 2807:     if (!$namespace) { 
 2808:        unless ($namespace=$env{'request.course.id'}) { 
 2809:           return ''; 
 2810:        } 
 2811:     }
 2812:     if (!$domain) { $domain=$env{'user.domain'}; }
 2813:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2814:     if (!$home) { $home=$env{'user.home'}; }
 2815:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2816: 
 2817:     my %returnhash=();
 2818:     foreach my $line (split(/\&/,$answer)) {
 2819: 	my ($name,$value)=split(/\=/,$line);
 2820:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2821:     }
 2822:     my $version;
 2823:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2824:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2825:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2826:        }
 2827:     }
 2828:     return %returnhash;
 2829: }
 2830: 
 2831: # ---------------------------------------------------------- Course Description
 2832: 
 2833: sub coursedescription {
 2834:     my ($courseid,$args)=@_;
 2835:     $courseid=~s/^\///;
 2836:     $courseid=~s/\_/\//g;
 2837:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2838:     my $chome=&homeserver($cnum,$cdomain);
 2839:     my $normalid=$cdomain.'_'.$cnum;
 2840:     # need to always cache even if we get errors otherwise we keep 
 2841:     # trying and trying and trying to get the course description.
 2842:     my %envhash=();
 2843:     my %returnhash=();
 2844:     
 2845:     my $expiretime=600;
 2846:     if ($env{'request.course.id'} eq $normalid) {
 2847: 	$expiretime=120;
 2848:     }
 2849: 
 2850:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2851:     if (!$args->{'freshen_cache'}
 2852: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2853: 	foreach my $key (keys(%env)) {
 2854: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2855: 	    my ($setting) = $1;
 2856: 	    $returnhash{$setting} = $env{$key};
 2857: 	}
 2858: 	return %returnhash;
 2859:     }
 2860: 
 2861:     # get the data agin
 2862:     if (!$args->{'one_time'}) {
 2863: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2864:     }
 2865: 
 2866:     if ($chome ne 'no_host') {
 2867:        %returnhash=&dump('environment',$cdomain,$cnum);
 2868:        if (!exists($returnhash{'con_lost'})) {
 2869:            $returnhash{'home'}= $chome;
 2870: 	   $returnhash{'domain'} = $cdomain;
 2871: 	   $returnhash{'num'} = $cnum;
 2872:            if (!defined($returnhash{'type'})) {
 2873:                $returnhash{'type'} = 'Course';
 2874:            }
 2875:            while (my ($name,$value) = each %returnhash) {
 2876:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2877:            }
 2878:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2879:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2880: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2881:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2882:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2883:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2884:        }
 2885:     }
 2886:     if (!$args->{'one_time'}) {
 2887: 	&appenv(%envhash);
 2888:     }
 2889:     return %returnhash;
 2890: }
 2891: 
 2892: # -------------------------------------------------See if a user is privileged
 2893: 
 2894: sub privileged {
 2895:     my ($username,$domain)=@_;
 2896:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2897: 			&homeserver($username,$domain));
 2898:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2899:     my $now=time;
 2900:     if ($rolesdump ne '') {
 2901:         foreach my $entry (split(/&/,$rolesdump)) {
 2902: 	    if ($entry!~/^rolesdef_/) {
 2903: 		my ($area,$role)=split(/=/,$entry);
 2904: 		$area=~s/\_\w\w$//;
 2905: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2906: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2907: 		    my $active=1;
 2908: 		    if ($tend) {
 2909: 			if ($tend<$now) { $active=0; }
 2910: 		    }
 2911: 		    if ($tstart) {
 2912: 			if ($tstart>$now) { $active=0; }
 2913: 		    }
 2914: 		    if ($active) { return 1; }
 2915: 		}
 2916: 	    }
 2917: 	}
 2918:     }
 2919:     return 0;
 2920: }
 2921: 
 2922: # -------------------------------------------------------- Get user privileges
 2923: 
 2924: sub rolesinit {
 2925:     my ($domain,$username,$authhost)=@_;
 2926:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2927:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2928:     my %allroles=();
 2929:     my %allgroups=();   
 2930:     my $now=time;
 2931:     my %userroles = ('user.login.time' => $now);
 2932:     my $group_privs;
 2933: 
 2934:     if ($rolesdump ne '') {
 2935:         foreach my $entry (split(/&/,$rolesdump)) {
 2936: 	  if ($entry!~/^rolesdef_/) {
 2937:             my ($area,$role)=split(/=/,$entry);
 2938: 	    $area=~s/\_\w\w$//;
 2939:             my ($trole,$tend,$tstart,$group_privs);
 2940: 	    if ($role=~/^cr/) { 
 2941: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 2942: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 2943: 		    ($tend,$tstart)=split('_',$trest);
 2944: 		} else {
 2945: 		    $trole=$role;
 2946: 		}
 2947:             } elsif ($role =~ m|^gr/|) {
 2948:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2949:                 ($trole,$group_privs) = split(/\//,$trole);
 2950:                 $group_privs = &unescape($group_privs);
 2951: 	    } else {
 2952: 		($trole,$tend,$tstart)=split(/_/,$role);
 2953: 	    }
 2954: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2955: 					 $username);
 2956: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2957:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2958:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2959:             if (($area ne '') && ($trole ne '')) {
 2960: 		my $spec=$trole.'.'.$area;
 2961: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2962: 		if ($trole =~ /^cr\//) {
 2963:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2964:                 } elsif ($trole eq 'gr') {
 2965:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2966: 		} else {
 2967:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2968: 		}
 2969:             }
 2970:           }
 2971:         }
 2972:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2973:         $userroles{'user.adv'}    = $adv;
 2974: 	$userroles{'user.author'} = $author;
 2975:         $env{'user.adv'}=$adv;
 2976:     }
 2977:     return \%userroles;  
 2978: }
 2979: 
 2980: sub set_arearole {
 2981:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2982: # log the associated role with the area
 2983:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2984:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2985: }
 2986: 
 2987: sub custom_roleprivs {
 2988:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2989:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2990:     my $homsvr=homeserver($rauthor,$rdomain);
 2991:     if (&hostname($homsvr) ne '') {
 2992:         my ($rdummy,$roledef)=
 2993:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2994:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2995:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2996:             if (defined($syspriv)) {
 2997:                 $$allroles{'cm./'}.=':'.$syspriv;
 2998:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2999:             }
 3000:             if ($tdomain ne '') {
 3001:                 if (defined($dompriv)) {
 3002:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3003:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3004:                 }
 3005:                 if (($trest ne '') && (defined($coursepriv))) {
 3006:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3007:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3008:                 }
 3009:             }
 3010:         }
 3011:     }
 3012: }
 3013: 
 3014: sub group_roleprivs {
 3015:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3016:     my $access = 1;
 3017:     my $now = time;
 3018:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3019:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3020:     if ($access) {
 3021:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3022:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3023:     }
 3024: }
 3025: 
 3026: sub standard_roleprivs {
 3027:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3028:     if (defined($pr{$trole.':s'})) {
 3029:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3030:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3031:     }
 3032:     if ($tdomain ne '') {
 3033:         if (defined($pr{$trole.':d'})) {
 3034:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3035:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3036:         }
 3037:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3038:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3039:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3040:         }
 3041:     }
 3042: }
 3043: 
 3044: sub set_userprivs {
 3045:     my ($userroles,$allroles,$allgroups) = @_; 
 3046:     my $author=0;
 3047:     my $adv=0;
 3048:     my %grouproles = ();
 3049:     if (keys(%{$allgroups}) > 0) {
 3050:         foreach my $role (keys %{$allroles}) {
 3051:             my ($trole,$area,$sec,$extendedarea);
 3052:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
 3053:                 $trole = $1;
 3054:                 $area = $2;
 3055:                 $sec = $3;
 3056:                 $extendedarea = $area.$sec;
 3057:                 if (exists($$allgroups{$area})) {
 3058:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3059:                         my $spec = $trole.'.'.$extendedarea;
 3060:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3061:                                                 $$allgroups{$area}{$group};
 3062:                     }
 3063:                 }
 3064:             }
 3065:         }
 3066:     }
 3067:     foreach my $group (keys(%grouproles)) {
 3068:         $$allroles{$group} = $grouproles{$group};
 3069:     }
 3070:     foreach my $role (keys(%{$allroles})) {
 3071:         my %thesepriv;
 3072:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3073:         foreach my $item (split(/:/,$$allroles{$role})) {
 3074:             if ($item ne '') {
 3075:                 my ($privilege,$restrictions)=split(/&/,$item);
 3076:                 if ($restrictions eq '') {
 3077:                     $thesepriv{$privilege}='F';
 3078:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3079:                     $thesepriv{$privilege}.=$restrictions;
 3080:                 }
 3081:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3082:             }
 3083:         }
 3084:         my $thesestr='';
 3085:         foreach my $priv (keys(%thesepriv)) {
 3086: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3087: 	}
 3088:         $userroles->{'user.priv.'.$role} = $thesestr;
 3089:     }
 3090:     return ($author,$adv);
 3091: }
 3092: 
 3093: # --------------------------------------------------------------- get interface
 3094: 
 3095: sub get {
 3096:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3097:    my $items='';
 3098:    foreach my $item (@$storearr) {
 3099:        $items.=&escape($item).'&';
 3100:    }
 3101:    $items=~s/\&$//;
 3102:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3103:    if (!$uname) { $uname=$env{'user.name'}; }
 3104:    my $uhome=&homeserver($uname,$udomain);
 3105: 
 3106:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3107:    my @pairs=split(/\&/,$rep);
 3108:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3109:      return @pairs;
 3110:    }
 3111:    my %returnhash=();
 3112:    my $i=0;
 3113:    foreach my $item (@$storearr) {
 3114:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3115:       $i++;
 3116:    }
 3117:    return %returnhash;
 3118: }
 3119: 
 3120: # --------------------------------------------------------------- del interface
 3121: 
 3122: sub del {
 3123:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3124:    my $items='';
 3125:    foreach my $item (@$storearr) {
 3126:        $items.=&escape($item).'&';
 3127:    }
 3128:    $items=~s/\&$//;
 3129:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3130:    if (!$uname) { $uname=$env{'user.name'}; }
 3131:    my $uhome=&homeserver($uname,$udomain);
 3132: 
 3133:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3134: }
 3135: 
 3136: # -------------------------------------------------------------- dump interface
 3137: 
 3138: sub dump {
 3139:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3140:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3141:     if (!$uname) { $uname=$env{'user.name'}; }
 3142:     my $uhome=&homeserver($uname,$udomain);
 3143:     if ($regexp) {
 3144: 	$regexp=&escape($regexp);
 3145:     } else {
 3146: 	$regexp='.';
 3147:     }
 3148:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3149:     my @pairs=split(/\&/,$rep);
 3150:     my %returnhash=();
 3151:     foreach my $item (@pairs) {
 3152: 	my ($key,$value)=split(/=/,$item,2);
 3153: 	$key = &unescape($key);
 3154: 	next if ($key =~ /^error: 2 /);
 3155: 	$returnhash{$key}=&thaw_unescape($value);
 3156:     }
 3157:     return %returnhash;
 3158: }
 3159: 
 3160: # --------------------------------------------------------- dumpstore interface
 3161: 
 3162: sub dumpstore {
 3163:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3164:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3165:    if (!$uname) { $uname=$env{'user.name'}; }
 3166:    my $uhome=&homeserver($uname,$udomain);
 3167:    if ($regexp) {
 3168:        $regexp=&escape($regexp);
 3169:    } else {
 3170:        $regexp='.';
 3171:    }
 3172:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3173:    my @pairs=split(/\&/,$rep);
 3174:    my %returnhash=();
 3175:    foreach my $item (@pairs) {
 3176:        my ($key,$value)=split(/=/,$item,2);
 3177:        next if ($key =~ /^error: 2 /);
 3178:        $returnhash{$key}=&thaw_unescape($value);
 3179:    }
 3180:    return %returnhash;
 3181: }
 3182: 
 3183: # -------------------------------------------------------------- keys interface
 3184: 
 3185: sub getkeys {
 3186:    my ($namespace,$udomain,$uname)=@_;
 3187:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3188:    if (!$uname) { $uname=$env{'user.name'}; }
 3189:    my $uhome=&homeserver($uname,$udomain);
 3190:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3191:    my @keyarray=();
 3192:    foreach my $key (split(/\&/,$rep)) {
 3193:       next if ($key =~ /^error: 2 /);
 3194:       push(@keyarray,&unescape($key));
 3195:    }
 3196:    return @keyarray;
 3197: }
 3198: 
 3199: # --------------------------------------------------------------- currentdump
 3200: sub currentdump {
 3201:    my ($courseid,$sdom,$sname)=@_;
 3202:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3203:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3204:    $sname    = $env{'user.name'}         if (! defined($sname));
 3205:    my $uhome = &homeserver($sname,$sdom);
 3206:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3207:    return if ($rep =~ /^(error:|no_such_host)/);
 3208:    #
 3209:    my %returnhash=();
 3210:    #
 3211:    if ($rep eq "unknown_cmd") { 
 3212:        # an old lond will not know currentdump
 3213:        # Do a dump and make it look like a currentdump
 3214:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3215:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3216:        my %hash = @tmp;
 3217:        @tmp=();
 3218:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3219:    } else {
 3220:        my @pairs=split(/\&/,$rep);
 3221:        foreach my $pair (@pairs) {
 3222:            my ($key,$value)=split(/=/,$pair,2);
 3223:            my ($symb,$param) = split(/:/,$key);
 3224:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3225:                                                         &thaw_unescape($value);
 3226:        }
 3227:    }
 3228:    return %returnhash;
 3229: }
 3230: 
 3231: sub convert_dump_to_currentdump{
 3232:     my %hash = %{shift()};
 3233:     my %returnhash;
 3234:     # Code ripped from lond, essentially.  The only difference
 3235:     # here is the unescaping done by lonnet::dump().  Conceivably
 3236:     # we might run in to problems with parameter names =~ /^v\./
 3237:     while (my ($key,$value) = each(%hash)) {
 3238:         my ($v,$symb,$param) = split(/:/,$key);
 3239: 	$symb  = &unescape($symb);
 3240: 	$param = &unescape($param);
 3241:         next if ($v eq 'version' || $symb eq 'keys');
 3242:         next if (exists($returnhash{$symb}) &&
 3243:                  exists($returnhash{$symb}->{$param}) &&
 3244:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3245:         $returnhash{$symb}->{$param}=$value;
 3246:         $returnhash{$symb}->{'v.'.$param}=$v;
 3247:     }
 3248:     #
 3249:     # Remove all of the keys in the hashes which keep track of
 3250:     # the version of the parameter.
 3251:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3252:         # use a foreach because we are going to delete from the hash.
 3253:         foreach my $key (keys(%$param_hash)) {
 3254:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3255:         }
 3256:     }
 3257:     return \%returnhash;
 3258: }
 3259: 
 3260: # ------------------------------------------------------ critical inc interface
 3261: 
 3262: sub cinc {
 3263:     return &inc(@_,'critical');
 3264: }
 3265: 
 3266: # --------------------------------------------------------------- inc interface
 3267: 
 3268: sub inc {
 3269:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3270:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3271:     if (!$uname) { $uname=$env{'user.name'}; }
 3272:     my $uhome=&homeserver($uname,$udomain);
 3273:     my $items='';
 3274:     if (! ref($store)) {
 3275:         # got a single value, so use that instead
 3276:         $items = &escape($store).'=&';
 3277:     } elsif (ref($store) eq 'SCALAR') {
 3278:         $items = &escape($$store).'=&';        
 3279:     } elsif (ref($store) eq 'ARRAY') {
 3280:         $items = join('=&',map {&escape($_);} @{$store});
 3281:     } elsif (ref($store) eq 'HASH') {
 3282:         while (my($key,$value) = each(%{$store})) {
 3283:             $items.= &escape($key).'='.&escape($value).'&';
 3284:         }
 3285:     }
 3286:     $items=~s/\&$//;
 3287:     if ($critical) {
 3288: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3289:     } else {
 3290: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3291:     }
 3292: }
 3293: 
 3294: # --------------------------------------------------------------- put interface
 3295: 
 3296: sub put {
 3297:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3298:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3299:    if (!$uname) { $uname=$env{'user.name'}; }
 3300:    my $uhome=&homeserver($uname,$udomain);
 3301:    my $items='';
 3302:    foreach my $item (keys(%$storehash)) {
 3303:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3304:    }
 3305:    $items=~s/\&$//;
 3306:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3307: }
 3308: 
 3309: # ------------------------------------------------------------ newput interface
 3310: 
 3311: sub newput {
 3312:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3313:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3314:    if (!$uname) { $uname=$env{'user.name'}; }
 3315:    my $uhome=&homeserver($uname,$udomain);
 3316:    my $items='';
 3317:    foreach my $key (keys(%$storehash)) {
 3318:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3319:    }
 3320:    $items=~s/\&$//;
 3321:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3322: }
 3323: 
 3324: # ---------------------------------------------------------  putstore interface
 3325: 
 3326: sub putstore {
 3327:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3328:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3329:    if (!$uname) { $uname=$env{'user.name'}; }
 3330:    my $uhome=&homeserver($uname,$udomain);
 3331:    my $items='';
 3332:    foreach my $key (keys(%$storehash)) {
 3333:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3334:    }
 3335:    $items=~s/\&$//;
 3336:    my $esc_symb=&escape($symb);
 3337:    my $esc_v=&escape($version);
 3338:    my $reply =
 3339:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3340: 	      $uhome);
 3341:    if ($reply eq 'unknown_cmd') {
 3342:        # gfall back to way things use to be done
 3343:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3344: 			    $uname);
 3345:    }
 3346:    return $reply;
 3347: }
 3348: 
 3349: sub old_putstore {
 3350:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3351:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3352:     if (!$uname) { $uname=$env{'user.name'}; }
 3353:     my $uhome=&homeserver($uname,$udomain);
 3354:     my %newstorehash;
 3355:     foreach my $item (keys(%$storehash)) {
 3356: 	my $key = $version.':'.&escape($symb).':'.$item;
 3357: 	$newstorehash{$key} = $storehash->{$item};
 3358:     }
 3359:     my $items='';
 3360:     my %allitems = ();
 3361:     foreach my $item (keys(%newstorehash)) {
 3362: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3363: 	    my $key = $1.':keys:'.$2;
 3364: 	    $allitems{$key} .= $3.':';
 3365: 	}
 3366: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3367:     }
 3368:     foreach my $item (keys(%allitems)) {
 3369: 	$allitems{$item} =~ s/\:$//;
 3370: 	$items.= $item.'='.$allitems{$item}.'&';
 3371:     }
 3372:     $items=~s/\&$//;
 3373:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3374: }
 3375: 
 3376: # ------------------------------------------------------ critical put interface
 3377: 
 3378: sub cput {
 3379:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3380:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3381:    if (!$uname) { $uname=$env{'user.name'}; }
 3382:    my $uhome=&homeserver($uname,$udomain);
 3383:    my $items='';
 3384:    foreach my $item (keys(%$storehash)) {
 3385:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3386:    }
 3387:    $items=~s/\&$//;
 3388:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3389: }
 3390: 
 3391: # -------------------------------------------------------------- eget interface
 3392: 
 3393: sub eget {
 3394:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3395:    my $items='';
 3396:    foreach my $item (@$storearr) {
 3397:        $items.=&escape($item).'&';
 3398:    }
 3399:    $items=~s/\&$//;
 3400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3401:    if (!$uname) { $uname=$env{'user.name'}; }
 3402:    my $uhome=&homeserver($uname,$udomain);
 3403:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3404:    my @pairs=split(/\&/,$rep);
 3405:    my %returnhash=();
 3406:    my $i=0;
 3407:    foreach my $item (@$storearr) {
 3408:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3409:       $i++;
 3410:    }
 3411:    return %returnhash;
 3412: }
 3413: 
 3414: # ------------------------------------------------------------ tmpput interface
 3415: sub tmpput {
 3416:     my ($storehash,$server,$context)=@_;
 3417:     my $items='';
 3418:     foreach my $item (keys(%$storehash)) {
 3419: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3420:     }
 3421:     $items=~s/\&$//;
 3422:     if (defined($context)) {
 3423:         $items .= ':'.&escape($context);
 3424:     }
 3425:     return &reply("tmpput:$items",$server);
 3426: }
 3427: 
 3428: # ------------------------------------------------------------ tmpget interface
 3429: sub tmpget {
 3430:     my ($token,$server)=@_;
 3431:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3432:     my $rep=&reply("tmpget:$token",$server);
 3433:     my %returnhash;
 3434:     foreach my $item (split(/\&/,$rep)) {
 3435: 	my ($key,$value)=split(/=/,$item);
 3436: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3437:     }
 3438:     return %returnhash;
 3439: }
 3440: 
 3441: # ------------------------------------------------------------ tmpget interface
 3442: sub tmpdel {
 3443:     my ($token,$server)=@_;
 3444:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3445:     return &reply("tmpdel:$token",$server);
 3446: }
 3447: 
 3448: # -------------------------------------------------- portfolio access checking
 3449: 
 3450: sub portfolio_access {
 3451:     my ($requrl) = @_;
 3452:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3453:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3454:     if ($result) {
 3455:         my %setters;
 3456:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3457:             my ($startblock,$endblock) =
 3458:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3459:             if ($startblock && $endblock) {
 3460:                 return 'B';
 3461:             }
 3462:         } else {
 3463:             my ($startblock,$endblock) =
 3464:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3465:             if ($startblock && $endblock) {
 3466:                 return 'B';
 3467:             }
 3468:         }
 3469:     }
 3470:     if ($result eq 'ok') {
 3471:        return 'F';
 3472:     } elsif ($result =~ /^[^:]+:guest_/) {
 3473:        return 'A';
 3474:     }
 3475:     return '';
 3476: }
 3477: 
 3478: sub get_portfolio_access {
 3479:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3480: 
 3481:     if (!ref($access_hash)) {
 3482: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3483: 	my %access_controls = &get_access_controls($current_perms,$group,
 3484: 						   $file_name);
 3485: 	$access_hash = $access_controls{$file_name};
 3486:     }
 3487: 
 3488:     my ($public,$guest,@domains,@users,@courses,@groups);
 3489:     my $now = time;
 3490:     if (ref($access_hash) eq 'HASH') {
 3491:         foreach my $key (keys(%{$access_hash})) {
 3492:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3493:             if ($start > $now) {
 3494:                 next;
 3495:             }
 3496:             if ($end && $end<$now) {
 3497:                 next;
 3498:             }
 3499:             if ($scope eq 'public') {
 3500:                 $public = $key;
 3501:                 last;
 3502:             } elsif ($scope eq 'guest') {
 3503:                 $guest = $key;
 3504:             } elsif ($scope eq 'domains') {
 3505:                 push(@domains,$key);
 3506:             } elsif ($scope eq 'users') {
 3507:                 push(@users,$key);
 3508:             } elsif ($scope eq 'course') {
 3509:                 push(@courses,$key);
 3510:             } elsif ($scope eq 'group') {
 3511:                 push(@groups,$key);
 3512:             }
 3513:         }
 3514:         if ($public) {
 3515:             return 'ok';
 3516:         }
 3517:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3518:             if ($guest) {
 3519:                 return $guest;
 3520:             }
 3521:         } else {
 3522:             if (@domains > 0) {
 3523:                 foreach my $domkey (@domains) {
 3524:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3525:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3526:                             return 'ok';
 3527:                         }
 3528:                     }
 3529:                 }
 3530:             }
 3531:             if (@users > 0) {
 3532:                 foreach my $userkey (@users) {
 3533:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3534:                         return 'ok';
 3535:                     }
 3536:                 }
 3537:             }
 3538:             my %roleshash;
 3539:             my @courses_and_groups = @courses;
 3540:             push(@courses_and_groups,@groups); 
 3541:             if (@courses_and_groups > 0) {
 3542:                 my (%allgroups,%allroles); 
 3543:                 my ($start,$end,$role,$sec,$group);
 3544:                 foreach my $envkey (%env) {
 3545:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3546:                         my $cid = $2.'_'.$3; 
 3547:                         if ($1 eq 'gr') {
 3548:                             $group = $4;
 3549:                             $allgroups{$cid}{$group} = $env{$envkey};
 3550:                         } else {
 3551:                             if ($4 eq '') {
 3552:                                 $sec = 'none';
 3553:                             } else {
 3554:                                 $sec = $4;
 3555:                             }
 3556:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3557:                         }
 3558:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3559:                         my $cid = $2.'_'.$3;
 3560:                         if ($4 eq '') {
 3561:                             $sec = 'none';
 3562:                         } else {
 3563:                             $sec = $4;
 3564:                         }
 3565:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3566:                     }
 3567:                 }
 3568:                 if (keys(%allroles) == 0) {
 3569:                     return;
 3570:                 }
 3571:                 foreach my $key (@courses_and_groups) {
 3572:                     my %content = %{$$access_hash{$key}};
 3573:                     my $cnum = $content{'number'};
 3574:                     my $cdom = $content{'domain'};
 3575:                     my $cid = $cdom.'_'.$cnum;
 3576:                     if (!exists($allroles{$cid})) {
 3577:                         next;
 3578:                     }    
 3579:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3580:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3581:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3582:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3583:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3584:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3585:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3586:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3587:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3588:                                         if (grep/^all$/,@sections) {
 3589:                                             return 'ok';
 3590:                                         } else {
 3591:                                             if (grep/^$sec$/,@sections) {
 3592:                                                 return 'ok';
 3593:                                             }
 3594:                                         }
 3595:                                     }
 3596:                                 }
 3597:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3598:                                     if (grep/^none$/,@groups) {
 3599:                                         return 'ok';
 3600:                                     }
 3601:                                 } else {
 3602:                                     if (grep/^all$/,@groups) {
 3603:                                         return 'ok';
 3604:                                     } 
 3605:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3606:                                         if (grep/^$group$/,@groups) {
 3607:                                             return 'ok';
 3608:                                         }
 3609:                                     }
 3610:                                 } 
 3611:                             }
 3612:                         }
 3613:                     }
 3614:                 }
 3615:             }
 3616:             if ($guest) {
 3617:                 return $guest;
 3618:             }
 3619:         }
 3620:     }
 3621:     return;
 3622: }
 3623: 
 3624: sub course_group_datechecker {
 3625:     my ($dates,$now,$status) = @_;
 3626:     my ($start,$end) = split(/\./,$dates);
 3627:     if (!$start && !$end) {
 3628:         return 'ok';
 3629:     }
 3630:     if (grep/^active$/,@{$status}) {
 3631:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3632:             return 'ok';
 3633:         }
 3634:     }
 3635:     if (grep/^previous$/,@{$status}) {
 3636:         if ($end > $now ) {
 3637:             return 'ok';
 3638:         }
 3639:     }
 3640:     if (grep/^future$/,@{$status}) {
 3641:         if ($start > $now) {
 3642:             return 'ok';
 3643:         }
 3644:     }
 3645:     return; 
 3646: }
 3647: 
 3648: sub parse_portfolio_url {
 3649:     my ($url) = @_;
 3650: 
 3651:     my ($type,$udom,$unum,$group,$file_name);
 3652:     
 3653:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3654: 	$type = 1;
 3655:         $udom = $1;
 3656:         $unum = $2;
 3657:         $file_name = $3;
 3658:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3659: 	$type = 2;
 3660:         $udom = $1;
 3661:         $unum = $2;
 3662:         $group = $3;
 3663:         $file_name = $3.'/'.$4;
 3664:     }
 3665:     if (wantarray) {
 3666: 	return ($type,$udom,$unum,$file_name,$group);
 3667:     }
 3668:     return $type;
 3669: }
 3670: 
 3671: sub is_portfolio_url {
 3672:     my ($url) = @_;
 3673:     return scalar(&parse_portfolio_url($url));
 3674: }
 3675: 
 3676: sub is_portfolio_file {
 3677:     my ($file) = @_;
 3678:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3679:         return 1;
 3680:     }
 3681:     return;
 3682: }
 3683: 
 3684: 
 3685: # ---------------------------------------------- Custom access rule evaluation
 3686: 
 3687: sub customaccess {
 3688:     my ($priv,$uri)=@_;
 3689:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3690:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3691:     $udom = &LONCAPA::clean_domain($udom);
 3692:     $ucrs = &LONCAPA::clean_username($ucrs);
 3693:     my $access=0;
 3694:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3695: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3696:         if ($role) {
 3697: 	   if ($role ne $urole) { next; }
 3698:         }
 3699:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3700:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3701:             if ($tdom) {
 3702: 		if ($tdom ne $udom) { next; }
 3703:             }
 3704:             if ($tcrs) {
 3705: 		if ($tcrs ne $ucrs) { next; }
 3706:             }
 3707:             if ($tsec) {
 3708: 		if ($tsec ne $usec) { next; }
 3709:             }
 3710:             $access=($effect eq 'allow');
 3711:             last;
 3712:         }
 3713: 	if ($realm eq '' && $role eq '') {
 3714:             $access=($effect eq 'allow');
 3715: 	}
 3716:     }
 3717:     return $access;
 3718: }
 3719: 
 3720: # ------------------------------------------------- Check for a user privilege
 3721: 
 3722: sub allowed {
 3723:     my ($priv,$uri,$symb,$role)=@_;
 3724:     my $ver_orguri=$uri;
 3725:     $uri=&deversion($uri);
 3726:     my $orguri=$uri;
 3727:     $uri=&declutter($uri);
 3728: 
 3729:     if ($priv eq 'evb') {
 3730: # Evade communication block restrictions for specified role in a course
 3731:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3732:             return $1;
 3733:         } else {
 3734:             return;
 3735:         }
 3736:     }
 3737: 
 3738:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3739: # Free bre access to adm and meta resources
 3740:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3741: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3742: 	&& ($priv eq 'bre')) {
 3743: 	return 'F';
 3744:     }
 3745: 
 3746: # Free bre access to user's own portfolio contents
 3747:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3748:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3749: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3750:         my %setters;
 3751:         my ($startblock,$endblock) = 
 3752:             &Apache::loncommon::blockcheck(\%setters,'port');
 3753:         if ($startblock && $endblock) {
 3754:             return 'B';
 3755:         } else {
 3756:             return 'F';
 3757:         }
 3758:     }
 3759: 
 3760: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3761:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3762:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3763:         if (exists($env{'request.course.id'})) {
 3764:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3765:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3766:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3767:                 my $courseprivid=$env{'request.course.id'};
 3768:                 $courseprivid=~s/\_/\//;
 3769:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3770:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3771:                     return $1; 
 3772:                 } else {
 3773:                     if ($env{'request.course.sec'}) {
 3774:                         $courseprivid.='/'.$env{'request.course.sec'};
 3775:                     }
 3776:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3777:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3778:                         return $2;
 3779:                     }
 3780:                 }
 3781:             }
 3782:         }
 3783:     }
 3784: 
 3785: # Free bre to public access
 3786: 
 3787:     if ($priv eq 'bre') {
 3788:         my $copyright=&metadata($uri,'copyright');
 3789: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3790:            return 'F'; 
 3791:         }
 3792:         if ($copyright eq 'priv') {
 3793:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3794: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3795: 		return '';
 3796:             }
 3797:         }
 3798:         if ($copyright eq 'domain') {
 3799:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3800: 	    unless (($env{'user.domain'} eq $1) ||
 3801:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3802: 		return '';
 3803:             }
 3804:         }
 3805:         if ($env{'request.role'}=~ /li\.\//) {
 3806:             # Library role, so allow browsing of resources in this domain.
 3807:             return 'F';
 3808:         }
 3809:         if ($copyright eq 'custom') {
 3810: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3811:         }
 3812:     }
 3813:     # Domain coordinator is trying to create a course
 3814:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3815:         # uri is the requested domain in this case.
 3816:         # comparison to 'request.role.domain' shows if the user has selected
 3817:         # a role of dc for the domain in question.
 3818:         return 'F' if ($uri eq $env{'request.role.domain'});
 3819:     }
 3820: 
 3821:     my $thisallowed='';
 3822:     my $statecond=0;
 3823:     my $courseprivid='';
 3824: 
 3825: # Course
 3826: 
 3827:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3828:        $thisallowed.=$1;
 3829:     }
 3830: 
 3831: # Domain
 3832: 
 3833:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3834:        =~/\Q$priv\E\&([^\:]*)/) {
 3835:        $thisallowed.=$1;
 3836:     }
 3837: 
 3838: # Course: uri itself is a course
 3839:     my $courseuri=$uri;
 3840:     $courseuri=~s/\_(\d)/\/$1/;
 3841:     $courseuri=~s/^([^\/])/\/$1/;
 3842: 
 3843:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3844:        =~/\Q$priv\E\&([^\:]*)/) {
 3845:        $thisallowed.=$1;
 3846:     }
 3847: 
 3848: # URI is an uploaded document for this course, default permissions don't matter
 3849: # not allowing 'edit' access (editupload) to uploaded course docs
 3850:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3851: 	$thisallowed='';
 3852:         my ($match)=&is_on_map($uri);
 3853:         if ($match) {
 3854:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3855:                   =~/\Q$priv\E\&([^\:]*)/) {
 3856:                 $thisallowed.=$1;
 3857:             }
 3858:         } else {
 3859:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3860:             if ($refuri) {
 3861:                 if ($refuri =~ m|^/adm/|) {
 3862:                     $thisallowed='F';
 3863:                 } else {
 3864:                     $refuri=&declutter($refuri);
 3865:                     my ($match) = &is_on_map($refuri);
 3866:                     if ($match) {
 3867:                         $thisallowed='F';
 3868:                     }
 3869:                 }
 3870:             }
 3871:         }
 3872:     }
 3873: 
 3874:     if ($priv eq 'bre'
 3875: 	&& $thisallowed ne 'F' 
 3876: 	&& $thisallowed ne '2'
 3877: 	&& &is_portfolio_url($uri)) {
 3878: 	$thisallowed = &portfolio_access($uri);
 3879:     }
 3880:     
 3881: # Full access at system, domain or course-wide level? Exit.
 3882: 
 3883:     if ($thisallowed=~/F/) {
 3884: 	return 'F';
 3885:     }
 3886: 
 3887: # If this is generating or modifying users, exit with special codes
 3888: 
 3889:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3890: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3891: 	    my ($audom,$auname)=split('/',$uri);
 3892: # no author name given, so this just checks on the general right to make a co-author in this domain
 3893: 	    unless ($auname) { return $thisallowed; }
 3894: # an author name is given, so we are about to actually make a co-author for a certain account
 3895: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3896: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3897: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3898: 	}
 3899: 	return $thisallowed;
 3900:     }
 3901: #
 3902: # Gathered so far: system, domain and course wide privileges
 3903: #
 3904: # Course: See if uri or referer is an individual resource that is part of 
 3905: # the course
 3906: 
 3907:     if ($env{'request.course.id'}) {
 3908: 
 3909:        $courseprivid=$env{'request.course.id'};
 3910:        if ($env{'request.course.sec'}) {
 3911:           $courseprivid.='/'.$env{'request.course.sec'};
 3912:        }
 3913:        $courseprivid=~s/\_/\//;
 3914:        my $checkreferer=1;
 3915:        my ($match,$cond)=&is_on_map($uri);
 3916:        if ($match) {
 3917:            $statecond=$cond;
 3918:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3919:                =~/\Q$priv\E\&([^\:]*)/) {
 3920:                $thisallowed.=$1;
 3921:                $checkreferer=0;
 3922:            }
 3923:        }
 3924:        
 3925:        if ($checkreferer) {
 3926: 	  my $refuri=$env{'httpref.'.$orguri};
 3927:             unless ($refuri) {
 3928:                 foreach my $key (keys(%env)) {
 3929: 		    if ($key=~/^httpref\..*\*/) {
 3930: 			my $pattern=$key;
 3931:                         $pattern=~s/^httpref\.\/res\///;
 3932:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3933:                         $pattern=~s/\//\\\//g;
 3934:                         if ($orguri=~/$pattern/) {
 3935: 			    $refuri=$env{$key};
 3936:                         }
 3937:                     }
 3938:                 }
 3939:             }
 3940: 
 3941:          if ($refuri) { 
 3942: 	  $refuri=&declutter($refuri);
 3943:           my ($match,$cond)=&is_on_map($refuri);
 3944:             if ($match) {
 3945:               my $refstatecond=$cond;
 3946:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3947:                   =~/\Q$priv\E\&([^\:]*)/) {
 3948:                   $thisallowed.=$1;
 3949:                   $uri=$refuri;
 3950:                   $statecond=$refstatecond;
 3951:               }
 3952:           }
 3953:         }
 3954:        }
 3955:    }
 3956: 
 3957: #
 3958: # Gathered now: all privileges that could apply, and condition number
 3959: # 
 3960: #
 3961: # Full or no access?
 3962: #
 3963: 
 3964:     if ($thisallowed=~/F/) {
 3965: 	return 'F';
 3966:     }
 3967: 
 3968:     unless ($thisallowed) {
 3969:         return '';
 3970:     }
 3971: 
 3972: # Restrictions exist, deal with them
 3973: #
 3974: #   C:according to course preferences
 3975: #   R:according to resource settings
 3976: #   L:unless locked
 3977: #   X:according to user session state
 3978: #
 3979: 
 3980: # Possibly locked functionality, check all courses
 3981: # Locks might take effect only after 10 minutes cache expiration for other
 3982: # courses, and 2 minutes for current course
 3983: 
 3984:     my $envkey;
 3985:     if ($thisallowed=~/L/) {
 3986:         foreach $envkey (keys %env) {
 3987:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3988:                my $courseid=$2;
 3989:                my $roleid=$1.'.'.$2;
 3990:                $courseid=~s/^\///;
 3991:                my $expiretime=600;
 3992:                if ($env{'request.role'} eq $roleid) {
 3993: 		  $expiretime=120;
 3994:                }
 3995: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3996:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3997:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3998: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3999:                }
 4000:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4001:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4002: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4003:                        &log($env{'user.domain'},$env{'user.name'},
 4004:                             $env{'user.home'},
 4005:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4006:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4007:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4008: 		       return '';
 4009:                    }
 4010:                }
 4011:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4012:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4013: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4014:                        &log($env{'user.domain'},$env{'user.name'},
 4015:                             $env{'user.home'},
 4016:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4017:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4018:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4019: 		       return '';
 4020:                    }
 4021:                }
 4022: 	   }
 4023:        }
 4024:     }
 4025:    
 4026: #
 4027: # Rest of the restrictions depend on selected course
 4028: #
 4029: 
 4030:     unless ($env{'request.course.id'}) {
 4031: 	if ($thisallowed eq 'A') {
 4032: 	    return 'A';
 4033:         } elsif ($thisallowed eq 'B') {
 4034:             return 'B';
 4035: 	} else {
 4036: 	    return '1';
 4037: 	}
 4038:     }
 4039: 
 4040: #
 4041: # Now user is definitely in a course
 4042: #
 4043: 
 4044: 
 4045: # Course preferences
 4046: 
 4047:    if ($thisallowed=~/C/) {
 4048:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4049:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4050:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4051: 	   =~/\Q$rolecode\E/) {
 4052: 	   if ($priv ne 'pch') { 
 4053: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4054: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4055: 			$env{'request.course.id'});
 4056: 	   }
 4057:            return '';
 4058:        }
 4059: 
 4060:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4061: 	   =~/\Q$unamedom\E/) {
 4062: 	   if ($priv ne 'pch') { 
 4063: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4064: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4065: 			$env{'request.course.id'});
 4066: 	   }
 4067:            return '';
 4068:        }
 4069:    }
 4070: 
 4071: # Resource preferences
 4072: 
 4073:    if ($thisallowed=~/R/) {
 4074:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4075:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4076: 	   if ($priv ne 'pch') { 
 4077: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4078: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4079: 	   }
 4080: 	   return '';
 4081:        }
 4082:    }
 4083: 
 4084: # Restricted by state or randomout?
 4085: 
 4086:    if ($thisallowed=~/X/) {
 4087:       if ($env{'acc.randomout'}) {
 4088: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4089:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4090:             return ''; 
 4091:          }
 4092:       }
 4093:       if (&condval($statecond)) {
 4094: 	 return '2';
 4095:       } else {
 4096:          return '';
 4097:       }
 4098:    }
 4099: 
 4100:     if ($thisallowed eq 'A') {
 4101: 	return 'A';
 4102:     } elsif ($thisallowed eq 'B') {
 4103:         return 'B';
 4104:     }
 4105:    return 'F';
 4106: }
 4107: 
 4108: sub split_uri_for_cond {
 4109:     my $uri=&deversion(&declutter(shift));
 4110:     my @uriparts=split(/\//,$uri);
 4111:     my $filename=pop(@uriparts);
 4112:     my $pathname=join('/',@uriparts);
 4113:     return ($pathname,$filename);
 4114: }
 4115: # --------------------------------------------------- Is a resource on the map?
 4116: 
 4117: sub is_on_map {
 4118:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4119:     #Trying to find the conditional for the file
 4120:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4121: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4122:     if ($match) {
 4123: 	return (1,$1);
 4124:     } else {
 4125: 	return (0,0);
 4126:     }
 4127: }
 4128: 
 4129: # --------------------------------------------------------- Get symb from alias
 4130: 
 4131: sub get_symb_from_alias {
 4132:     my $symb=shift;
 4133:     my ($map,$resid,$url)=&decode_symb($symb);
 4134: # Already is a symb
 4135:     if ($url) { return $symb; }
 4136: # Must be an alias
 4137:     my $aliassymb='';
 4138:     my %bighash;
 4139:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4140:                             &GDBM_READER(),0640)) {
 4141:         my $rid=$bighash{'mapalias_'.$symb};
 4142: 	if ($rid) {
 4143: 	    my ($mapid,$resid)=split(/\./,$rid);
 4144: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4145: 				    $resid,$bighash{'src_'.$rid});
 4146: 	}
 4147:         untie %bighash;
 4148:     }
 4149:     return $aliassymb;
 4150: }
 4151: 
 4152: # ----------------------------------------------------------------- Define Role
 4153: 
 4154: sub definerole {
 4155:   if (allowed('mcr','/')) {
 4156:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4157:     foreach my $role (split(':',$sysrole)) {
 4158: 	my ($crole,$cqual)=split(/\&/,$role);
 4159:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4160:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4161: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4162:                return "refused:s:$crole&$cqual"; 
 4163:             }
 4164:         }
 4165:     }
 4166:     foreach my $role (split(':',$domrole)) {
 4167: 	my ($crole,$cqual)=split(/\&/,$role);
 4168:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4169:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4170: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4171:                return "refused:d:$crole&$cqual"; 
 4172:             }
 4173:         }
 4174:     }
 4175:     foreach my $role (split(':',$courole)) {
 4176: 	my ($crole,$cqual)=split(/\&/,$role);
 4177:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4178:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4179: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4180:                return "refused:c:$crole&$cqual"; 
 4181:             }
 4182:         }
 4183:     }
 4184:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4185:                 "$env{'user.domain'}:$env{'user.name'}:".
 4186: 	        "rolesdef_$rolename=".
 4187:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4188:     return reply($command,$env{'user.home'});
 4189:   } else {
 4190:     return 'refused';
 4191:   }
 4192: }
 4193: 
 4194: # ---------------- Make a metadata query against the network of library servers
 4195: 
 4196: sub metadata_query {
 4197:     my ($query,$custom,$customshow,$server_array)=@_;
 4198:     my %rhash;
 4199:     my %libserv = &all_library();
 4200:     my @server_list = (defined($server_array) ? @$server_array
 4201:                                               : keys(%libserv) );
 4202:     for my $server (@server_list) {
 4203: 	unless ($custom or $customshow) {
 4204: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4205: 	    $rhash{$server}=$reply;
 4206: 	}
 4207: 	else {
 4208: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4209: 			     &escape($custom).':'.&escape($customshow),
 4210: 			     $server);
 4211: 	    $rhash{$server}=$reply;
 4212: 	}
 4213:     }
 4214:     return \%rhash;
 4215: }
 4216: 
 4217: # ----------------------------------------- Send log queries and wait for reply
 4218: 
 4219: sub log_query {
 4220:     my ($uname,$udom,$query,%filters)=@_;
 4221:     my $uhome=&homeserver($uname,$udom);
 4222:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4223:     my $uhost=&hostname($uhome);
 4224:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4225:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4226:                        $uhome);
 4227:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4228:     return get_query_reply($queryid);
 4229: }
 4230: 
 4231: # -------------------------- Update MySQL table for portfolio file
 4232: 
 4233: sub update_portfolio_table {
 4234:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4235:     my $homeserver = &homeserver($uname,$udom);
 4236:     my $queryid=
 4237:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4238:                ':'.&escape($file_name).':'.$action,$homeserver);
 4239:     my $reply = &get_query_reply($queryid);
 4240:     return $reply;
 4241: }
 4242: 
 4243: # ------- Request retrieval of institutional classlists for course(s)
 4244: 
 4245: sub fetch_enrollment_query {
 4246:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4247:     my $homeserver;
 4248:     my $maxtries = 1;
 4249:     if ($context eq 'automated') {
 4250:         $homeserver = $perlvar{'lonHostID'};
 4251:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4252:     } else {
 4253:         $homeserver = &homeserver($cnum,$dom);
 4254:     }
 4255:     my $host=&hostname($homeserver);
 4256:     my $cmd = '';
 4257:     foreach my $affiliate (keys %{$affiliatesref}) {
 4258:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4259:     }
 4260:     $cmd =~ s/%%$//;
 4261:     $cmd = &escape($cmd);
 4262:     my $query = 'fetchenrollment';
 4263:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4264:     unless ($queryid=~/^\Q$host\E\_/) { 
 4265:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4266:         return 'error: '.$queryid;
 4267:     }
 4268:     my $reply = &get_query_reply($queryid);
 4269:     my $tries = 1;
 4270:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4271:         $reply = &get_query_reply($queryid);
 4272:         $tries ++;
 4273:     }
 4274:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4275:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4276:     } else {
 4277:         my @responses = split/:/,$reply;
 4278:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4279:             foreach my $line (@responses) {
 4280:                 my ($key,$value) = split(/=/,$line,2);
 4281:                 $$replyref{$key} = $value;
 4282:             }
 4283:         } else {
 4284:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4285:             foreach my $line (@responses) {
 4286:                 my ($key,$value) = split(/=/,$line);
 4287:                 $$replyref{$key} = $value;
 4288:                 if ($value > 0) {
 4289:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4290:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4291:                         my $destname = $pathname.'/'.$filename;
 4292:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4293:                         if ($xml_classlist =~ /^error/) {
 4294:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4295:                         } else {
 4296:                             if ( open(FILE,">$destname") ) {
 4297:                                 print FILE &unescape($xml_classlist);
 4298:                                 close(FILE);
 4299:                             } else {
 4300:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4301:                             }
 4302:                         }
 4303:                     }
 4304:                 }
 4305:             }
 4306:         }
 4307:         return 'ok';
 4308:     }
 4309:     return 'error';
 4310: }
 4311: 
 4312: sub get_query_reply {
 4313:     my $queryid=shift;
 4314:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4315:     my $reply='';
 4316:     for (1..100) {
 4317: 	sleep 2;
 4318:         if (-e $replyfile.'.end') {
 4319: 	    if (open(my $fh,$replyfile)) {
 4320:                $reply.=<$fh>;
 4321:                close($fh);
 4322: 	   } else { return 'error: reply_file_error'; }
 4323:            return &unescape($reply);
 4324: 	}
 4325:     }
 4326:     return 'timeout:'.$queryid;
 4327: }
 4328: 
 4329: sub courselog_query {
 4330: #
 4331: # possible filters:
 4332: # url: url or symb
 4333: # username
 4334: # domain
 4335: # action: view, submit, grade
 4336: # start: timestamp
 4337: # end: timestamp
 4338: #
 4339:     my (%filters)=@_;
 4340:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4341:     if ($filters{'url'}) {
 4342: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4343:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4344:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4345:     }
 4346:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4347:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4348:     return &log_query($cname,$cdom,'courselog',%filters);
 4349: }
 4350: 
 4351: sub userlog_query {
 4352:     my ($uname,$udom,%filters)=@_;
 4353:     return &log_query($uname,$udom,'userlog',%filters);
 4354: }
 4355: 
 4356: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4357: 
 4358: sub auto_run {
 4359:     my ($cnum,$cdom) = @_;
 4360:     my $homeserver = &homeserver($cnum,$cdom);
 4361:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4362:     return $response;
 4363: }
 4364: 
 4365: sub auto_get_sections {
 4366:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4367:     my $homeserver = &homeserver($cnum,$cdom);
 4368:     my @secs = ();
 4369:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4370:     unless ($response eq 'refused') {
 4371:         @secs = split/:/,$response;
 4372:     }
 4373:     return @secs;
 4374: }
 4375: 
 4376: sub auto_new_course {
 4377:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4378:     my $homeserver = &homeserver($cnum,$cdom);
 4379:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4380:     return $response;
 4381: }
 4382: 
 4383: sub auto_validate_courseID {
 4384:     my ($cnum,$cdom,$inst_course_id) = @_;
 4385:     my $homeserver = &homeserver($cnum,$cdom);
 4386:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4387:     return $response;
 4388: }
 4389: 
 4390: sub auto_create_password {
 4391:     my ($cnum,$cdom,$authparam) = @_;
 4392:     my $homeserver = &homeserver($cnum,$cdom); 
 4393:     my $create_passwd = 0;
 4394:     my $authchk = '';
 4395:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4396:     if ($response eq 'refused') {
 4397:         $authchk = 'refused';
 4398:     } else {
 4399:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4400:     }
 4401:     return ($authparam,$create_passwd,$authchk);
 4402: }
 4403: 
 4404: sub auto_photo_permission {
 4405:     my ($cnum,$cdom,$students) = @_;
 4406:     my $homeserver = &homeserver($cnum,$cdom);
 4407:     my ($outcome,$perm_reqd,$conditions) = 
 4408: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4409:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4410: 	return (undef,undef);
 4411:     }
 4412:     return ($outcome,$perm_reqd,$conditions);
 4413: }
 4414: 
 4415: sub auto_checkphotos {
 4416:     my ($uname,$udom,$pid) = @_;
 4417:     my $homeserver = &homeserver($uname,$udom);
 4418:     my ($result,$resulttype);
 4419:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4420: 				   &escape($uname).':'.&escape($pid),
 4421: 				   $homeserver));
 4422:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4423: 	return (undef,undef);
 4424:     }
 4425:     if ($outcome) {
 4426:         ($result,$resulttype) = split(/:/,$outcome);
 4427:     } 
 4428:     return ($result,$resulttype);
 4429: }
 4430: 
 4431: sub auto_photochoice {
 4432:     my ($cnum,$cdom) = @_;
 4433:     my $homeserver = &homeserver($cnum,$cdom);
 4434:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4435: 						       &escape($cdom),
 4436: 						       $homeserver)));
 4437:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4438: 	return (undef,undef);
 4439:     }
 4440:     return ($update,$comment);
 4441: }
 4442: 
 4443: sub auto_photoupdate {
 4444:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4445:     my $homeserver = &homeserver($cnum,$dom);
 4446:     my $host=&hostname($homeserver);
 4447:     my $cmd = '';
 4448:     my $maxtries = 1;
 4449:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4450:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4451:     }
 4452:     $cmd =~ s/%%$//;
 4453:     $cmd = &escape($cmd);
 4454:     my $query = 'institutionalphotos';
 4455:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4456:     unless ($queryid=~/^\Q$host\E\_/) {
 4457:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4458:         return 'error: '.$queryid;
 4459:     }
 4460:     my $reply = &get_query_reply($queryid);
 4461:     my $tries = 1;
 4462:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4463:         $reply = &get_query_reply($queryid);
 4464:         $tries ++;
 4465:     }
 4466:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4467:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4468:     } else {
 4469:         my @responses = split(/:/,$reply);
 4470:         my $outcome = shift(@responses); 
 4471:         foreach my $item (@responses) {
 4472:             my ($key,$value) = split(/=/,$item);
 4473:             $$photo{$key} = $value;
 4474:         }
 4475:         return $outcome;
 4476:     }
 4477:     return 'error';
 4478: }
 4479: 
 4480: sub auto_instcode_format {
 4481:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4482: 	$cat_order) = @_;
 4483:     my $courses = '';
 4484:     my @homeservers;
 4485:     if ($caller eq 'global') {
 4486: 	my %servers = &get_servers($codedom,'library');
 4487: 	foreach my $tryserver (keys(%servers)) {
 4488: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4489: 		push(@homeservers,$tryserver);
 4490: 	    }
 4491:         }
 4492:     } else {
 4493:         push(@homeservers,&homeserver($caller,$codedom));
 4494:     }
 4495:     foreach my $code (keys(%{$instcodes})) {
 4496:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4497:     }
 4498:     chop($courses);
 4499:     my $ok_response = 0;
 4500:     my $response;
 4501:     while (@homeservers > 0 && $ok_response == 0) {
 4502:         my $server = shift(@homeservers); 
 4503:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4504:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4505:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4506: 		split/:/,$response;
 4507:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4508:             push(@{$codetitles},&str2array($codetitles_str));
 4509:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4510:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4511:             $ok_response = 1;
 4512:         }
 4513:     }
 4514:     if ($ok_response) {
 4515:         return 'ok';
 4516:     } else {
 4517:         return $response;
 4518:     }
 4519: }
 4520: 
 4521: sub auto_instcode_defaults {
 4522:     my ($domain,$returnhash,$code_order) = @_;
 4523:     my @homeservers;
 4524: 
 4525:     my %servers = &get_servers($domain,'library');
 4526:     foreach my $tryserver (keys(%servers)) {
 4527: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4528: 	    push(@homeservers,$tryserver);
 4529: 	}
 4530:     }
 4531: 
 4532:     my $response;
 4533:     foreach my $server (@homeservers) {
 4534:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4535:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4536: 	
 4537: 	foreach my $pair (split(/\&/,$response)) {
 4538: 	    my ($name,$value)=split(/\=/,$pair);
 4539: 	    if ($name eq 'code_order') {
 4540: 		@{$code_order} = split(/\&/,&unescape($value));
 4541: 	    } else {
 4542: 		$returnhash->{&unescape($name)}=&unescape($value);
 4543: 	    }
 4544: 	}
 4545: 	return 'ok';
 4546:     }
 4547: 
 4548:     return $response;
 4549: } 
 4550: 
 4551: sub auto_validate_class_sec {
 4552:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4553:     my $homeserver = &homeserver($cnum,$cdom);
 4554:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4555:                         &escape($owner).':'.$cdom,$homeserver);
 4556:     return $response;
 4557: }
 4558: 
 4559: # ------------------------------------------------------- Course Group routines
 4560: 
 4561: sub get_coursegroups {
 4562:     my ($cdom,$cnum,$group,$namespace) = @_;
 4563:     return(&dump($namespace,$cdom,$cnum,$group));
 4564: }
 4565: 
 4566: sub modify_coursegroup {
 4567:     my ($cdom,$cnum,$groupsettings) = @_;
 4568:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4569: }
 4570: 
 4571: sub toggle_coursegroup_status {
 4572:     my ($cdom,$cnum,$group,$action) = @_;
 4573:     my ($from_namespace,$to_namespace);
 4574:     if ($action eq 'delete') {
 4575:         $from_namespace = 'coursegroups';
 4576:         $to_namespace = 'deleted_groups';
 4577:     } else {
 4578:         $from_namespace = 'deleted_groups';
 4579:         $to_namespace = 'coursegroups';
 4580:     }
 4581:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4582:     if (my $tmp = &error(%curr_group)) {
 4583:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4584:         return ('read error',$tmp);
 4585:     } else {
 4586:         my %savedsettings = %curr_group; 
 4587:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4588:         my $deloutcome;
 4589:         if ($result eq 'ok') {
 4590:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4591:         } else {
 4592:             return ('write error',$result);
 4593:         }
 4594:         if ($deloutcome eq 'ok') {
 4595:             return 'ok';
 4596:         } else {
 4597:             return ('delete error',$deloutcome);
 4598:         }
 4599:     }
 4600: }
 4601: 
 4602: sub modify_group_roles {
 4603:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4604:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4605:     my $role = 'gr/'.&escape($userprivs);
 4606:     my ($uname,$udom) = split(/:/,$user);
 4607:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4608:     if ($result eq 'ok') {
 4609:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4610:     }
 4611:     return $result;
 4612: }
 4613: 
 4614: sub modify_coursegroup_membership {
 4615:     my ($cdom,$cnum,$membership) = @_;
 4616:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4617:     return $result;
 4618: }
 4619: 
 4620: sub get_active_groups {
 4621:     my ($udom,$uname,$cdom,$cnum) = @_;
 4622:     my $now = time;
 4623:     my %groups = ();
 4624:     foreach my $key (keys(%env)) {
 4625:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4626:             my ($start,$end) = split(/\./,$env{$key});
 4627:             if (($end!=0) && ($end<$now)) { next; }
 4628:             if (($start!=0) && ($start>$now)) { next; }
 4629:             if ($1 eq $cdom && $2 eq $cnum) {
 4630:                 $groups{$3} = $env{$key} ;
 4631:             }
 4632:         }
 4633:     }
 4634:     return %groups;
 4635: }
 4636: 
 4637: sub get_group_membership {
 4638:     my ($cdom,$cnum,$group) = @_;
 4639:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4640: }
 4641: 
 4642: sub get_users_groups {
 4643:     my ($udom,$uname,$courseid) = @_;
 4644:     my @usersgroups;
 4645:     my $cachetime=1800;
 4646: 
 4647:     my $hashid="$udom:$uname:$courseid";
 4648:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4649:     if (defined($cached)) {
 4650:         @usersgroups = split(/:/,$grouplist);
 4651:     } else {  
 4652:         $grouplist = '';
 4653:         my $courseurl = &courseid_to_courseurl($courseid);
 4654:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4655:         my $access_end = $env{'course.'.$courseid.
 4656:                               '.default_enrollment_end_date'};
 4657:         my $now = time;
 4658:         foreach my $key (keys(%roleshash)) {
 4659:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4660:                 my $group = $1;
 4661:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4662:                     my $start = $2;
 4663:                     my $end = $1;
 4664:                     if ($start == -1) { next; } # deleted from group
 4665:                     if (($start!=0) && ($start>$now)) { next; }
 4666:                     if (($end!=0) && ($end<$now)) {
 4667:                         if ($access_end && $access_end < $now) {
 4668:                             if ($access_end - $end < 86400) {
 4669:                                 push(@usersgroups,$group);
 4670:                             }
 4671:                         }
 4672:                         next;
 4673:                     }
 4674:                     push(@usersgroups,$group);
 4675:                 }
 4676:             }
 4677:         }
 4678:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4679:         $grouplist = join(':',@usersgroups);
 4680:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4681:     }
 4682:     return @usersgroups;
 4683: }
 4684: 
 4685: sub devalidate_getgroups_cache {
 4686:     my ($udom,$uname,$cdom,$cnum)=@_;
 4687:     my $courseid = $cdom.'_'.$cnum;
 4688: 
 4689:     my $hashid="$udom:$uname:$courseid";
 4690:     &devalidate_cache_new('getgroups',$hashid);
 4691: }
 4692: 
 4693: # ------------------------------------------------------------------ Plain Text
 4694: 
 4695: sub plaintext {
 4696:     my ($short,$type,$cid) = @_;
 4697:     if ($short =~ /^cr/) {
 4698: 	return (split('/',$short))[-1];
 4699:     }
 4700:     if (!defined($cid)) {
 4701:         $cid = $env{'request.course.id'};
 4702:     }
 4703:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4704:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4705:                                           '.plaintext'});
 4706:     }
 4707:     my %rolenames = (
 4708:                       Course => 'std',
 4709:                       Group => 'alt1',
 4710:                     );
 4711:     if (defined($type) && 
 4712:          defined($rolenames{$type}) && 
 4713:          defined($prp{$short}{$rolenames{$type}})) {
 4714:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4715:     } else {
 4716:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4717:     }
 4718: }
 4719: 
 4720: # ----------------------------------------------------------------- Assign Role
 4721: 
 4722: sub assignrole {
 4723:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4724:     my $mrole;
 4725:     if ($role =~ /^cr\//) {
 4726:         my $cwosec=$url;
 4727:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4728: 	unless (&allowed('ccr',$cwosec)) {
 4729:            &logthis('Refused custom assignrole: '.
 4730:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4731: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4732:            return 'refused'; 
 4733:         }
 4734:         $mrole='cr';
 4735:     } elsif ($role =~ /^gr\//) {
 4736:         my $cwogrp=$url;
 4737:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4738:         unless (&allowed('mdg',$cwogrp)) {
 4739:             &logthis('Refused group assignrole: '.
 4740:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4741:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4742:             return 'refused';
 4743:         }
 4744:         $mrole='gr';
 4745:     } else {
 4746:         my $cwosec=$url;
 4747:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4748:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4749:            &logthis('Refused assignrole: '.
 4750:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4751: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4752:            return 'refused'; 
 4753:         }
 4754:         $mrole=$role;
 4755:     }
 4756:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4757:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4758:     if ($end) { $command.='_'.$end; }
 4759:     if ($start) {
 4760: 	if ($end) { 
 4761:            $command.='_'.$start; 
 4762:         } else {
 4763:            $command.='_0_'.$start;
 4764:         }
 4765:     }
 4766:     my $origstart = $start;
 4767:     my $origend = $end;
 4768: # actually delete
 4769:     if ($deleteflag) {
 4770: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4771: # modify command to delete the role
 4772:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4773:                 "$udom:$uname:$url".'_'."$mrole";
 4774: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4775: # set start and finish to negative values for userrolelog
 4776:            $start=-1;
 4777:            $end=-1;
 4778:         }
 4779:     }
 4780: # send command
 4781:     my $answer=&reply($command,&homeserver($uname,$udom));
 4782: # log new user role if status is ok
 4783:     if ($answer eq 'ok') {
 4784: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4785: # for course roles, perform group memberships changes triggered by role change.
 4786:         unless ($role =~ /^gr/) {
 4787:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4788:                                              $origstart);
 4789:         }
 4790:     }
 4791:     return $answer;
 4792: }
 4793: 
 4794: # -------------------------------------------------- Modify user authentication
 4795: # Overrides without validation
 4796: 
 4797: sub modifyuserauth {
 4798:     my ($udom,$uname,$umode,$upass)=@_;
 4799:     my $uhome=&homeserver($uname,$udom);
 4800:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4801:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4802:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4803:              ' in domain '.$env{'request.role.domain'});  
 4804:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4805: 		     &escape($upass),$uhome);
 4806:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4807:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4808:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4809:     &log($udom,,$uname,$uhome,
 4810:         'Authentication changed by '.$env{'user.domain'}.', '.
 4811:                                      $env{'user.name'}.', '.$umode.
 4812:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4813:     unless ($reply eq 'ok') {
 4814:         &logthis('Authentication mode error: '.$reply);
 4815: 	return 'error: '.$reply;
 4816:     }   
 4817:     return 'ok';
 4818: }
 4819: 
 4820: # --------------------------------------------------------------- Modify a user
 4821: 
 4822: sub modifyuser {
 4823:     my ($udom,    $uname, $uid,
 4824:         $umode,   $upass, $first,
 4825:         $middle,  $last,  $gene,
 4826:         $forceid, $desiredhome, $email)=@_;
 4827:     $udom= &LONCAPA::clean_domain($udom);
 4828:     $uname=&LONCAPA::clean_username($uname);
 4829:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4830:              $umode.', '.$first.', '.$middle.', '.
 4831: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4832:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4833:                                      ' desiredhome not specified'). 
 4834:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4835:              ' in domain '.$env{'request.role.domain'});
 4836:     my $uhome=&homeserver($uname,$udom,'true');
 4837: # ----------------------------------------------------------------- Create User
 4838:     if (($uhome eq 'no_host') && 
 4839: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4840:         my $unhome='';
 4841:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4842:             $unhome = $desiredhome;
 4843: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4844: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4845:         } else { # load balancing routine for determining $unhome
 4846:             my $loadm=10000000;
 4847: 	    my %servers = &get_servers($udom,'library');
 4848: 	    foreach my $tryserver (keys(%servers)) {
 4849: 		my $answer=reply('load',$tryserver);
 4850: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4851: 		    $loadm=$answer;
 4852: 		    $unhome=$tryserver;
 4853: 		}
 4854: 	    }
 4855:         }
 4856:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4857: 	    return 'error: unable to find a home server for '.$uname.
 4858:                    ' in domain '.$udom;
 4859:         }
 4860:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4861:                          &escape($upass),$unhome);
 4862: 	unless ($reply eq 'ok') {
 4863:             return 'error: '.$reply;
 4864:         }   
 4865:         $uhome=&homeserver($uname,$udom,'true');
 4866:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4867: 	    return 'error: unable verify users home machine.';
 4868:         }
 4869:     }   # End of creation of new user
 4870: # ---------------------------------------------------------------------- Add ID
 4871:     if ($uid) {
 4872:        $uid=~tr/A-Z/a-z/;
 4873:        my %uidhash=&idrget($udom,$uname);
 4874:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4875:          && (!$forceid)) {
 4876: 	  unless ($uid eq $uidhash{$uname}) {
 4877: 	      return 'error: user id "'.$uid.'" does not match '.
 4878:                   'current user id "'.$uidhash{$uname}.'".';
 4879:           }
 4880:        } else {
 4881: 	  &idput($udom,($uname => $uid));
 4882:        }
 4883:     }
 4884: # -------------------------------------------------------------- Add names, etc
 4885:     my @tmp=&get('environment',
 4886: 		   ['firstname','middlename','lastname','generation'],
 4887: 		   $udom,$uname);
 4888:     my %names;
 4889:     if ($tmp[0] =~ m/^error:.*/) { 
 4890:         %names=(); 
 4891:     } else {
 4892:         %names = @tmp;
 4893:     }
 4894: #
 4895: # Make sure to not trash student environment if instructor does not bother
 4896: # to supply name and email information
 4897: #
 4898:     if ($first)  { $names{'firstname'}  = $first; }
 4899:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4900:     if ($last)   { $names{'lastname'}   = $last; }
 4901:     if (defined($gene))   { $names{'generation'} = $gene; }
 4902:     if ($email) {
 4903:        $email=~s/[^\w\@\.\-\,]//gs;
 4904:        if ($email=~/\@/) { $names{'notification'} = $email;
 4905: 			   $names{'critnotification'} = $email;
 4906: 			   $names{'permanentemail'} = $email; }
 4907:     }
 4908:     my $reply = &put('environment', \%names, $udom,$uname);
 4909:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4910:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4911:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4912:              $umode.', '.$first.', '.$middle.', '.
 4913: 	     $last.', '.$gene.' by '.
 4914:              $env{'user.name'}.' at '.$env{'user.domain'});
 4915:     return 'ok';
 4916: }
 4917: 
 4918: # -------------------------------------------------------------- Modify student
 4919: 
 4920: sub modifystudent {
 4921:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4922:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4923:     if (!$cid) {
 4924: 	unless ($cid=$env{'request.course.id'}) {
 4925: 	    return 'not_in_class';
 4926: 	}
 4927:     }
 4928: # --------------------------------------------------------------- Make the user
 4929:     my $reply=&modifyuser
 4930: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4931:          $desiredhome,$email);
 4932:     unless ($reply eq 'ok') { return $reply; }
 4933:     # This will cause &modify_student_enrollment to get the uid from the
 4934:     # students environment
 4935:     $uid = undef if (!$forceid);
 4936:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4937: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4938:     return $reply;
 4939: }
 4940: 
 4941: sub modify_student_enrollment {
 4942:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4943:     my ($cdom,$cnum,$chome);
 4944:     if (!$cid) {
 4945: 	unless ($cid=$env{'request.course.id'}) {
 4946: 	    return 'not_in_class';
 4947: 	}
 4948: 	$cdom=$env{'course.'.$cid.'.domain'};
 4949: 	$cnum=$env{'course.'.$cid.'.num'};
 4950:     } else {
 4951: 	($cdom,$cnum)=split(/_/,$cid);
 4952:     }
 4953:     $chome=$env{'course.'.$cid.'.home'};
 4954:     if (!$chome) {
 4955: 	$chome=&homeserver($cnum,$cdom);
 4956:     }
 4957:     if (!$chome) { return 'unknown_course'; }
 4958:     # Make sure the user exists
 4959:     my $uhome=&homeserver($uname,$udom);
 4960:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4961: 	return 'error: no such user';
 4962:     }
 4963:     # Get student data if we were not given enough information
 4964:     if (!defined($first)  || $first  eq '' || 
 4965:         !defined($last)   || $last   eq '' || 
 4966:         !defined($uid)    || $uid    eq '' || 
 4967:         !defined($middle) || $middle eq '' || 
 4968:         !defined($gene)   || $gene   eq '') {
 4969:         # They did not supply us with enough data to enroll the student, so
 4970:         # we need to pick up more information.
 4971:         my %tmp = &get('environment',
 4972:                        ['firstname','middlename','lastname', 'generation','id']
 4973:                        ,$udom,$uname);
 4974: 
 4975:         #foreach my $key (keys(%tmp)) {
 4976:         #    &logthis("key $key = ".$tmp{$key});
 4977:         #}
 4978:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4979:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4980:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4981:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4982:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4983:     }
 4984:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4985:     my $reply=cput('classlist',
 4986: 		   {"$uname:$udom" => 
 4987: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4988: 		   $cdom,$cnum);
 4989:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4990: 	return 'error: '.$reply;
 4991:     } else {
 4992: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4993:     }
 4994:     # Add student role to user
 4995:     my $uurl='/'.$cid;
 4996:     $uurl=~s/\_/\//g;
 4997:     if ($usec) {
 4998: 	$uurl.='/'.$usec;
 4999:     }
 5000:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5001: }
 5002: 
 5003: sub format_name {
 5004:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5005:     my $name;
 5006:     if ($first ne 'lastname') {
 5007: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5008:     } else {
 5009: 	if ($lastname=~/\S/) {
 5010: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5011: 	    $name=~s/\s+,/,/;
 5012: 	} else {
 5013: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5014: 	}
 5015:     }
 5016:     $name=~s/^\s+//;
 5017:     $name=~s/\s+$//;
 5018:     $name=~s/\s+/ /g;
 5019:     return $name;
 5020: }
 5021: 
 5022: # ------------------------------------------------- Write to course preferences
 5023: 
 5024: sub writecoursepref {
 5025:     my ($courseid,%prefs)=@_;
 5026:     $courseid=~s/^\///;
 5027:     $courseid=~s/\_/\//g;
 5028:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5029:     my $chome=homeserver($cnum,$cdomain);
 5030:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5031: 	return 'error: no such course';
 5032:     }
 5033:     my $cstring='';
 5034:     foreach my $pref (keys(%prefs)) {
 5035: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5036:     }
 5037:     $cstring=~s/\&$//;
 5038:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5039: }
 5040: 
 5041: # ---------------------------------------------------------- Make/modify course
 5042: 
 5043: sub createcourse {
 5044:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5045:         $course_owner,$crstype)=@_;
 5046:     $url=&declutter($url);
 5047:     my $cid='';
 5048:     unless (&allowed('ccc',$udom)) {
 5049:         return 'refused';
 5050:     }
 5051: # ------------------------------------------------------------------- Create ID
 5052:    my $uname=int(1+rand(9)).
 5053:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5054:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5055:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5056: # ----------------------------------------------- Make sure that does not exist
 5057:    my $uhome=&homeserver($uname,$udom,'true');
 5058:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5059:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5060:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5061:        $uhome=&homeserver($uname,$udom,'true');       
 5062:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5063:            return 'error: unable to generate unique course-ID';
 5064:        } 
 5065:    }
 5066: # ------------------------------------------------ Check supplied server name
 5067:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5068:     if (! &is_library($course_server)) {
 5069:         return 'error:bad server name '.$course_server;
 5070:     }
 5071: # ------------------------------------------------------------- Make the course
 5072:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5073:                       $course_server);
 5074:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5075:     $uhome=&homeserver($uname,$udom,'true');
 5076:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5077: 	return 'error: no such course';
 5078:     }
 5079: # ----------------------------------------------------------------- Course made
 5080: # log existence
 5081:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5082:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5083:                   &escape($crstype),$uhome);
 5084:     &flushcourselogs();
 5085: # set toplevel url
 5086:     my $topurl=$url;
 5087:     unless ($nonstandard) {
 5088: # ------------------------------------------ For standard courses, make top url
 5089:         my $mapurl=&clutter($url);
 5090:         if ($mapurl eq '/res/') { $mapurl=''; }
 5091:         $env{'form.initmap'}=(<<ENDINITMAP);
 5092: <map>
 5093: <resource id="1" type="start"></resource>
 5094: <resource id="2" src="$mapurl"></resource>
 5095: <resource id="3" type="finish"></resource>
 5096: <link index="1" from="1" to="2"></link>
 5097: <link index="2" from="2" to="3"></link>
 5098: </map>
 5099: ENDINITMAP
 5100:         $topurl=&declutter(
 5101:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5102:                           );
 5103:     }
 5104: # ----------------------------------------------------------- Write preferences
 5105:     &writecoursepref($udom.'_'.$uname,
 5106:                      ('description' => $description,
 5107:                       'url'         => $topurl));
 5108:     return '/'.$udom.'/'.$uname;
 5109: }
 5110: 
 5111: sub is_course {
 5112:     my ($cdom,$cnum) = @_;
 5113:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5114: 				undef,'.');
 5115:     if (exists($courses{$cdom.'_'.$cnum})) {
 5116:         return 1;
 5117:     }
 5118:     return 0;
 5119: }
 5120: 
 5121: # ---------------------------------------------------------- Assign Custom Role
 5122: 
 5123: sub assigncustomrole {
 5124:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5125:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5126:                        $end,$start,$deleteflag);
 5127: }
 5128: 
 5129: # ----------------------------------------------------------------- Revoke Role
 5130: 
 5131: sub revokerole {
 5132:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5133:     my $now=time;
 5134:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5135: }
 5136: 
 5137: # ---------------------------------------------------------- Revoke Custom Role
 5138: 
 5139: sub revokecustomrole {
 5140:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5141:     my $now=time;
 5142:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5143:            $deleteflag);
 5144: }
 5145: 
 5146: # ------------------------------------------------------------ Disk usage
 5147: sub diskusage {
 5148:     my ($udom,$uname,$directoryRoot)=@_;
 5149:     $directoryRoot =~ s/\/$//;
 5150:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5151:     return $listing;
 5152: }
 5153: 
 5154: sub is_locked {
 5155:     my ($file_name, $domain, $user) = @_;
 5156:     my @check;
 5157:     my $is_locked;
 5158:     push @check, $file_name;
 5159:     my %locked = &get('file_permissions',\@check,
 5160: 		      $env{'user.domain'},$env{'user.name'});
 5161:     my ($tmp)=keys(%locked);
 5162:     if ($tmp=~/^error:/) { undef(%locked); }
 5163:     
 5164:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5165:         $is_locked = 'false';
 5166:         foreach my $entry (@{$locked{$file_name}}) {
 5167:            if (ref($entry) eq 'ARRAY') { 
 5168:                $is_locked = 'true';
 5169:                last;
 5170:            }
 5171:        }
 5172:     } else {
 5173:         $is_locked = 'false';
 5174:     }
 5175: }
 5176: 
 5177: sub declutter_portfile {
 5178:     my ($file) = @_;
 5179:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5180:     return $file;
 5181: }
 5182: 
 5183: # ------------------------------------------------------------- Mark as Read Only
 5184: 
 5185: sub mark_as_readonly {
 5186:     my ($domain,$user,$files,$what) = @_;
 5187:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5188:     my ($tmp)=keys(%current_permissions);
 5189:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5190:     foreach my $file (@{$files}) {
 5191: 	$file = &declutter_portfile($file);
 5192:         push(@{$current_permissions{$file}},$what);
 5193:     }
 5194:     &put('file_permissions',\%current_permissions,$domain,$user);
 5195:     return;
 5196: }
 5197: 
 5198: # ------------------------------------------------------------Save Selected Files
 5199: 
 5200: sub save_selected_files {
 5201:     my ($user, $path, @files) = @_;
 5202:     my $filename = $user."savedfiles";
 5203:     my @other_files = &files_not_in_path($user, $path);
 5204:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5205:     foreach my $file (@files) {
 5206:         print (OUT $env{'form.currentpath'}.$file."\n");
 5207:     }
 5208:     foreach my $file (@other_files) {
 5209:         print (OUT $file."\n");
 5210:     }
 5211:     close (OUT);
 5212:     return 'ok';
 5213: }
 5214: 
 5215: sub clear_selected_files {
 5216:     my ($user) = @_;
 5217:     my $filename = $user."savedfiles";
 5218:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5219:     print (OUT undef);
 5220:     close (OUT);
 5221:     return ("ok");    
 5222: }
 5223: 
 5224: sub files_in_path {
 5225:     my ($user, $path) = @_;
 5226:     my $filename = $user."savedfiles";
 5227:     my %return_files;
 5228:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5229:     while (my $line_in = <IN>) {
 5230:         chomp ($line_in);
 5231:         my @paths_and_file = split (m!/!, $line_in);
 5232:         my $file_part = pop (@paths_and_file);
 5233:         my $path_part = join ('/', @paths_and_file);
 5234:         $path_part.='/';
 5235:         my $path_and_file = $path_part.$file_part;
 5236:         if ($path_part eq $path) {
 5237:             $return_files{$file_part}= 'selected';
 5238:         }
 5239:     }
 5240:     close (IN);
 5241:     return (\%return_files);
 5242: }
 5243: 
 5244: # called in portfolio select mode, to show files selected NOT in current directory
 5245: sub files_not_in_path {
 5246:     my ($user, $path) = @_;
 5247:     my $filename = $user."savedfiles";
 5248:     my @return_files;
 5249:     my $path_part;
 5250:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5251:     while (my $line = <IN>) {
 5252:         #ok, I know it's clunky, but I want it to work
 5253:         my @paths_and_file = split(m|/|, $line);
 5254:         my $file_part = pop(@paths_and_file);
 5255:         chomp($file_part);
 5256:         my $path_part = join('/', @paths_and_file);
 5257:         $path_part .= '/';
 5258:         my $path_and_file = $path_part.$file_part;
 5259:         if ($path_part ne $path) {
 5260:             push(@return_files, ($path_and_file));
 5261:         }
 5262:     }
 5263:     close(OUT);
 5264:     return (@return_files);
 5265: }
 5266: 
 5267: #----------------------------------------------Get portfolio file permissions
 5268: 
 5269: sub get_portfile_permissions {
 5270:     my ($domain,$user) = @_;
 5271:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5272:     my ($tmp)=keys(%current_permissions);
 5273:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5274:     return \%current_permissions;
 5275: }
 5276: 
 5277: #---------------------------------------------Get portfolio file access controls
 5278: 
 5279: sub get_access_controls {
 5280:     my ($current_permissions,$group,$file) = @_;
 5281:     my %access;
 5282:     my $real_file = $file;
 5283:     $file =~ s/\.meta$//;
 5284:     if (defined($file)) {
 5285:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5286:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5287:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5288:             }
 5289:         }
 5290:     } else {
 5291:         foreach my $key (keys(%{$current_permissions})) {
 5292:             if ($key =~ /\0accesscontrol$/) {
 5293:                 if (defined($group)) {
 5294:                     if ($key !~ m-^\Q$group\E/-) {
 5295:                         next;
 5296:                     }
 5297:                 }
 5298:                 my ($fullpath) = split(/\0/,$key);
 5299:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5300:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5301:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5302:                     }
 5303:                 }
 5304:             }
 5305:         }
 5306:     }
 5307:     return %access;
 5308: }
 5309: 
 5310: sub modify_access_controls {
 5311:     my ($file_name,$changes,$domain,$user)=@_;
 5312:     my ($outcome,$deloutcome);
 5313:     my %store_permissions;
 5314:     my %new_values;
 5315:     my %new_control;
 5316:     my %translation;
 5317:     my @deletions = ();
 5318:     my $now = time;
 5319:     if (exists($$changes{'activate'})) {
 5320:         if (ref($$changes{'activate'}) eq 'HASH') {
 5321:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5322:             my $numnew = scalar(@newitems);
 5323:             for (my $i=0; $i<$numnew; $i++) {
 5324:                 my $newkey = $newitems[$i];
 5325:                 my $newid = &Apache::loncommon::get_cgi_id();
 5326:                 if ($newkey =~ /^\d+:/) { 
 5327:                     $newkey =~ s/^(\d+)/$newid/;
 5328:                     $translation{$1} = $newid;
 5329:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5330:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5331:                     $translation{$1} = $newid;
 5332:                 }
 5333:                 $new_values{$file_name."\0".$newkey} = 
 5334:                                           $$changes{'activate'}{$newitems[$i]};
 5335:                 $new_control{$newkey} = $now;
 5336:             }
 5337:         }
 5338:     }
 5339:     my %todelete;
 5340:     my %changed_items;
 5341:     foreach my $action ('delete','update') {
 5342:         if (exists($$changes{$action})) {
 5343:             if (ref($$changes{$action}) eq 'HASH') {
 5344:                 foreach my $key (keys(%{$$changes{$action}})) {
 5345:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5346:                     if ($action eq 'delete') { 
 5347:                         $todelete{$itemnum} = 1;
 5348:                     } else {
 5349:                         $changed_items{$itemnum} = $key;
 5350:                     }
 5351:                 }
 5352:             }
 5353:         }
 5354:     }
 5355:     # get lock on access controls for file.
 5356:     my $lockhash = {
 5357:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5358:                                                        ':'.$env{'user.domain'},
 5359:                    }; 
 5360:     my $tries = 0;
 5361:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5362:    
 5363:     while (($gotlock ne 'ok') && $tries <3) {
 5364:         $tries ++;
 5365:         sleep 1;
 5366:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5367:     }
 5368:     if ($gotlock eq 'ok') {
 5369:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5370:         my ($tmp)=keys(%curr_permissions);
 5371:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5372:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5373:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5374:             if (ref($curr_controls) eq 'HASH') {
 5375:                 foreach my $control_item (keys(%{$curr_controls})) {
 5376:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5377:                     if (defined($todelete{$itemnum})) {
 5378:                         push(@deletions,$file_name."\0".$control_item);
 5379:                     } else {
 5380:                         if (defined($changed_items{$itemnum})) {
 5381:                             $new_control{$changed_items{$itemnum}} = $now;
 5382:                             push(@deletions,$file_name."\0".$control_item);
 5383:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5384:                         } else {
 5385:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5386:                         }
 5387:                     }
 5388:                 }
 5389:             }
 5390:         }
 5391:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5392:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5393:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5394:         #  remove lock
 5395:         my @del_lock = ($file_name."\0".'locked_access_records');
 5396:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5397:         my ($file,$group);
 5398:         if (&is_course($domain,$user)) {
 5399:             ($group,$file) = split(/\//,$file_name,2);
 5400:         } else {
 5401:             $file = $file_name;
 5402:         }
 5403:         my $sqlresult =
 5404:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5405:                                     $group);
 5406:     } else {
 5407:         $outcome = "error: could not obtain lockfile\n";  
 5408:     }
 5409:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5410: }
 5411: 
 5412: sub make_public_indefinitely {
 5413:     my ($requrl) = @_;
 5414:     my $now = time;
 5415:     my $action = 'activate';
 5416:     my $aclnum = 0;
 5417:     if (&is_portfolio_url($requrl)) {
 5418:         my (undef,$udom,$unum,$file_name,$group) =
 5419:             &parse_portfolio_url($requrl);
 5420:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5421:         my %access_controls = &get_access_controls($current_perms,
 5422:                                                    $group,$file_name);
 5423:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5424:             my ($num,$scope,$end,$start) = 
 5425:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5426:             if ($scope eq 'public') {
 5427:                 if ($start <= $now && $end == 0) {
 5428:                     $action = 'none';
 5429:                 } else {
 5430:                     $action = 'update';
 5431:                     $aclnum = $num;
 5432:                 }
 5433:                 last;
 5434:             }
 5435:         }
 5436:         if ($action eq 'none') {
 5437:              return 'ok';
 5438:         } else {
 5439:             my %changes;
 5440:             my $newend = 0;
 5441:             my $newstart = $now;
 5442:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5443:             $changes{$action}{$newkey} = {
 5444:                 type => 'public',
 5445:                 time => {
 5446:                     start => $newstart,
 5447:                     end   => $newend,
 5448:                 },
 5449:             };
 5450:             my ($outcome,$deloutcome,$new_values,$translation) =
 5451:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5452:             return $outcome;
 5453:         }
 5454:     } else {
 5455:         return 'invalid';
 5456:     }
 5457: }
 5458: 
 5459: #------------------------------------------------------Get Marked as Read Only
 5460: 
 5461: sub get_marked_as_readonly {
 5462:     my ($domain,$user,$what,$group) = @_;
 5463:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5464:     my @readonly_files;
 5465:     my $cmp1=$what;
 5466:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5467:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5468:         if (defined($group)) {
 5469:             if ($file_name !~ m-^\Q$group\E/-) {
 5470:                 next;
 5471:             }
 5472:         }
 5473:         if (ref($value) eq "ARRAY"){
 5474:             foreach my $stored_what (@{$value}) {
 5475:                 my $cmp2=$stored_what;
 5476:                 if (ref($stored_what) eq 'ARRAY') {
 5477:                     $cmp2=join('',@{$stored_what});
 5478:                 }
 5479:                 if ($cmp1 eq $cmp2) {
 5480:                     push(@readonly_files, $file_name);
 5481:                     last;
 5482:                 } elsif (!defined($what)) {
 5483:                     push(@readonly_files, $file_name);
 5484:                     last;
 5485:                 }
 5486:             }
 5487:         }
 5488:     }
 5489:     return @readonly_files;
 5490: }
 5491: #-----------------------------------------------------------Get Marked as Read Only Hash
 5492: 
 5493: sub get_marked_as_readonly_hash {
 5494:     my ($current_permissions,$group,$what) = @_;
 5495:     my %readonly_files;
 5496:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5497:         if (defined($group)) {
 5498:             if ($file_name !~ m-^\Q$group\E/-) {
 5499:                 next;
 5500:             }
 5501:         }
 5502:         if (ref($value) eq "ARRAY"){
 5503:             foreach my $stored_what (@{$value}) {
 5504:                 if (ref($stored_what) eq 'ARRAY') {
 5505:                     foreach my $lock_descriptor(@{$stored_what}) {
 5506:                         if ($lock_descriptor eq 'graded') {
 5507:                             $readonly_files{$file_name} = 'graded';
 5508:                         } elsif ($lock_descriptor eq 'handback') {
 5509:                             $readonly_files{$file_name} = 'handback';
 5510:                         } else {
 5511:                             if (!exists($readonly_files{$file_name})) {
 5512:                                 $readonly_files{$file_name} = 'locked';
 5513:                             }
 5514:                         }
 5515:                     }
 5516:                 } 
 5517:             }
 5518:         } 
 5519:     }
 5520:     return %readonly_files;
 5521: }
 5522: # ------------------------------------------------------------ Unmark as Read Only
 5523: 
 5524: sub unmark_as_readonly {
 5525:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5526:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5527:     my ($domain,$user,$what,$file_name,$group) = @_;
 5528:     $file_name = &declutter_portfile($file_name);
 5529:     my $symb_crs = $what;
 5530:     if (ref($what)) { $symb_crs=join('',@$what); }
 5531:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5532:     my ($tmp)=keys(%current_permissions);
 5533:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5534:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5535:     foreach my $file (@readonly_files) {
 5536: 	my $clean_file = &declutter_portfile($file);
 5537: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5538: 	my $current_locks = $current_permissions{$file};
 5539:         my @new_locks;
 5540:         my @del_keys;
 5541:         if (ref($current_locks) eq "ARRAY"){
 5542:             foreach my $locker (@{$current_locks}) {
 5543:                 my $compare=$locker;
 5544:                 if (ref($locker) eq 'ARRAY') {
 5545:                     $compare=join('',@{$locker});
 5546:                     if ($compare ne $symb_crs) {
 5547:                         push(@new_locks, $locker);
 5548:                     }
 5549:                 }
 5550:             }
 5551:             if (scalar(@new_locks) > 0) {
 5552:                 $current_permissions{$file} = \@new_locks;
 5553:             } else {
 5554:                 push(@del_keys, $file);
 5555:                 &del('file_permissions',\@del_keys, $domain, $user);
 5556:                 delete($current_permissions{$file});
 5557:             }
 5558:         }
 5559:     }
 5560:     &put('file_permissions',\%current_permissions,$domain,$user);
 5561:     return;
 5562: }
 5563: 
 5564: # ------------------------------------------------------------ Directory lister
 5565: 
 5566: sub dirlist {
 5567:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5568: 
 5569:     $uri=~s/^\///;
 5570:     $uri=~s/\/$//;
 5571:     my ($udom, $uname);
 5572:     (undef,$udom,$uname)=split(/\//,$uri);
 5573:     if(defined($userdomain)) {
 5574:         $udom = $userdomain;
 5575:     }
 5576:     if(defined($username)) {
 5577:         $uname = $username;
 5578:     }
 5579: 
 5580:     my $dirRoot = $perlvar{'lonDocRoot'};
 5581:     if(defined($alternateDirectoryRoot)) {
 5582:         $dirRoot = $alternateDirectoryRoot;
 5583:         $dirRoot =~ s/\/$//;
 5584:     }
 5585: 
 5586:     if($udom) {
 5587:         if($uname) {
 5588:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5589: 				 &homeserver($uname,$udom));
 5590:             my @listing_results;
 5591:             if ($listing eq 'unknown_cmd') {
 5592:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5593: 				  &homeserver($uname,$udom));
 5594:                 @listing_results = split(/:/,$listing);
 5595:             } else {
 5596:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5597:             }
 5598:             return @listing_results;
 5599:         } elsif(!defined($alternateDirectoryRoot)) {
 5600:             my %allusers;
 5601: 	    my %servers = &get_servers($udom,'library');
 5602: 	    foreach my $tryserver (keys(%servers)) {
 5603: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5604: 				     $udom, $tryserver);
 5605: 		my @listing_results;
 5606: 		if ($listing eq 'unknown_cmd') {
 5607: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5608: 				      $udom, $tryserver);
 5609: 		    @listing_results = split(/:/,$listing);
 5610: 		} else {
 5611: 		    @listing_results =
 5612: 			map { &unescape($_); } split(/:/,$listing);
 5613: 		}
 5614: 		if ($listing_results[0] ne 'no_such_dir' && 
 5615: 		    $listing_results[0] ne 'empty'       &&
 5616: 		    $listing_results[0] ne 'con_lost') {
 5617: 		    foreach my $line (@listing_results) {
 5618: 			my ($entry) = split(/&/,$line,2);
 5619: 			$allusers{$entry} = 1;
 5620: 		    }
 5621: 		}
 5622:             }
 5623:             my $alluserstr='';
 5624:             foreach my $user (sort(keys(%allusers))) {
 5625:                 $alluserstr.=$user.'&user:';
 5626:             }
 5627:             $alluserstr=~s/:$//;
 5628:             return split(/:/,$alluserstr);
 5629:         } else {
 5630:             return ('missing user name');
 5631:         }
 5632:     } elsif(!defined($alternateDirectoryRoot)) {
 5633:         my @all_domains = sort(&all_domains());
 5634:          foreach my $domain (@all_domains) {
 5635:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5636:          }
 5637:          return @all_domains;
 5638:      } else {
 5639:         return ('missing domain');
 5640:     }
 5641: }
 5642: 
 5643: # --------------------------------------------- GetFileTimestamp
 5644: # This function utilizes dirlist and returns the date stamp for
 5645: # when it was last modified.  It will also return an error of -1
 5646: # if an error occurs
 5647: 
 5648: ##
 5649: ## FIXME: This subroutine assumes its caller knows something about the
 5650: ## directory structure of the home server for the student ($root).
 5651: ## Not a good assumption to make.  Since this is for looking up files
 5652: ## in user directories, the full path should be constructed by lond, not
 5653: ## whatever machine we request data from.
 5654: ##
 5655: sub GetFileTimestamp {
 5656:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5657:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5658:     $studentName   = &LONCAPA::clean_username($studentName);
 5659:     my $subdir=$studentName.'__';
 5660:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5661:     my $proname="$studentDomain/$subdir/$studentName";
 5662:     $proname .= '/'.$filename;
 5663:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5664:                                               $studentName, $root);
 5665:     my @stats = split('&', $fileStat);
 5666:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5667:         # @stats contains first the filename, then the stat output
 5668:         return $stats[10]; # so this is 10 instead of 9.
 5669:     } else {
 5670:         return -1;
 5671:     }
 5672: }
 5673: 
 5674: sub stat_file {
 5675:     my ($uri) = @_;
 5676:     $uri = &clutter_with_no_wrapper($uri);
 5677: 
 5678:     my ($udom,$uname,$file,$dir);
 5679:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5680: 	($udom,$uname,$file) =
 5681: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5682: 	$file = 'userfiles/'.$file;
 5683: 	$dir = &propath($udom,$uname);
 5684:     }
 5685:     if ($uri =~ m-^/res/-) {
 5686: 	($udom,$uname) = 
 5687: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5688: 	$file = $uri;
 5689:     }
 5690: 
 5691:     if (!$udom || !$uname || !$file) {
 5692: 	# unable to handle the uri
 5693: 	return ();
 5694:     }
 5695: 
 5696:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5697:     my @stats = split('&', $result);
 5698:     
 5699:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5700: 	shift(@stats); #filename is first
 5701: 	return @stats;
 5702:     }
 5703:     return ();
 5704: }
 5705: 
 5706: # -------------------------------------------------------- Value of a Condition
 5707: 
 5708: # gets the value of a specific preevaluated condition
 5709: #    stored in the string  $env{user.state.<cid>}
 5710: # or looks up a condition reference in the bighash and if if hasn't
 5711: # already been evaluated recurses into docondval to get the value of
 5712: # the condition, then memoizing it to 
 5713: #   $env{user.state.<cid>.<condition>}
 5714: sub directcondval {
 5715:     my $number=shift;
 5716:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5717: 	&Apache::lonuserstate::evalstate();
 5718:     }
 5719:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5720: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5721:     } elsif ($number =~ /^_/) {
 5722: 	my $sub_condition;
 5723: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5724: 		&GDBM_READER(),0640)) {
 5725: 	    $sub_condition=$bighash{'conditions'.$number};
 5726: 	    untie(%bighash);
 5727: 	}
 5728: 	my $value = &docondval($sub_condition);
 5729: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5730: 	return $value;
 5731:     }
 5732:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5733:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5734:     } else {
 5735:        return 2;
 5736:     }
 5737: }
 5738: 
 5739: # get the collection of conditions for this resource
 5740: sub condval {
 5741:     my $condidx=shift;
 5742:     my $allpathcond='';
 5743:     foreach my $cond (split(/\|/,$condidx)) {
 5744: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5745: 	    $allpathcond.=
 5746: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5747: 	}
 5748:     }
 5749:     $allpathcond=~s/\|$//;
 5750:     return &docondval($allpathcond);
 5751: }
 5752: 
 5753: #evaluates an expression of conditions
 5754: sub docondval {
 5755:     my ($allpathcond) = @_;
 5756:     my $result=0;
 5757:     if ($env{'request.course.id'}
 5758: 	&& defined($allpathcond)) {
 5759: 	my $operand='|';
 5760: 	my @stack;
 5761: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5762: 	    if ($chunk eq '(') {
 5763: 		push @stack,($operand,$result);
 5764: 	    } elsif ($chunk eq ')') {
 5765: 		my $before=pop @stack;
 5766: 		if (pop @stack eq '&') {
 5767: 		    $result=$result>$before?$before:$result;
 5768: 		} else {
 5769: 		    $result=$result>$before?$result:$before;
 5770: 		}
 5771: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5772: 		$operand=$chunk;
 5773: 	    } else {
 5774: 		my $new=directcondval($chunk);
 5775: 		if ($operand eq '&') {
 5776: 		    $result=$result>$new?$new:$result;
 5777: 		} else {
 5778: 		    $result=$result>$new?$result:$new;
 5779: 		}
 5780: 	    }
 5781: 	}
 5782:     }
 5783:     return $result;
 5784: }
 5785: 
 5786: # ---------------------------------------------------- Devalidate courseresdata
 5787: 
 5788: sub devalidatecourseresdata {
 5789:     my ($coursenum,$coursedomain)=@_;
 5790:     my $hashid=$coursenum.':'.$coursedomain;
 5791:     &devalidate_cache_new('courseres',$hashid);
 5792: }
 5793: 
 5794: 
 5795: # --------------------------------------------------- Course Resourcedata Query
 5796: 
 5797: sub get_courseresdata {
 5798:     my ($coursenum,$coursedomain)=@_;
 5799:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5800:     my $hashid=$coursenum.':'.$coursedomain;
 5801:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5802:     my %dumpreply;
 5803:     unless (defined($cached)) {
 5804: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5805: 	$result=\%dumpreply;
 5806: 	my ($tmp) = keys(%dumpreply);
 5807: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5808: 	    &do_cache_new('courseres',$hashid,$result,600);
 5809: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5810: 	    return $tmp;
 5811: 	} elsif ($tmp =~ /^(error)/) {
 5812: 	    $result=undef;
 5813: 	    &do_cache_new('courseres',$hashid,$result,600);
 5814: 	}
 5815:     }
 5816:     return $result;
 5817: }
 5818: 
 5819: sub devalidateuserresdata {
 5820:     my ($uname,$udom)=@_;
 5821:     my $hashid="$udom:$uname";
 5822:     &devalidate_cache_new('userres',$hashid);
 5823: }
 5824: 
 5825: sub get_userresdata {
 5826:     my ($uname,$udom)=@_;
 5827:     #most student don\'t have any data set, check if there is some data
 5828:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5829: 
 5830:     my $hashid="$udom:$uname";
 5831:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5832:     if (!defined($cached)) {
 5833: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5834: 	$result=\%resourcedata;
 5835: 	&do_cache_new('userres',$hashid,$result,600);
 5836:     }
 5837:     my ($tmp)=keys(%$result);
 5838:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5839: 	return $result;
 5840:     }
 5841:     #error 2 occurs when the .db doesn't exist
 5842:     if ($tmp!~/error: 2 /) {
 5843: 	&logthis("<font color=\"blue\">WARNING:".
 5844: 		 " Trying to get resource data for ".
 5845: 		 $uname." at ".$udom.": ".
 5846: 		 $tmp."</font>");
 5847:     } elsif ($tmp=~/error: 2 /) {
 5848: 	#&EXT_cache_set($udom,$uname);
 5849: 	&do_cache_new('userres',$hashid,undef,600);
 5850: 	undef($tmp); # not really an error so don't send it back
 5851:     }
 5852:     return $tmp;
 5853: }
 5854: 
 5855: sub resdata {
 5856:     my ($name,$domain,$type,@which)=@_;
 5857:     my $result;
 5858:     if ($type eq 'course') {
 5859: 	$result=&get_courseresdata($name,$domain);
 5860:     } elsif ($type eq 'user') {
 5861: 	$result=&get_userresdata($name,$domain);
 5862:     }
 5863:     if (!ref($result)) { return $result; }    
 5864:     foreach my $item (@which) {
 5865: 	if (defined($result->{$item})) {
 5866: 	    return $result->{$item};
 5867: 	}
 5868:     }
 5869:     return undef;
 5870: }
 5871: 
 5872: #
 5873: # EXT resource caching routines
 5874: #
 5875: 
 5876: sub clear_EXT_cache_status {
 5877:     &delenv('cache.EXT.');
 5878: }
 5879: 
 5880: sub EXT_cache_status {
 5881:     my ($target_domain,$target_user) = @_;
 5882:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5883:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5884:         # We know already the user has no data
 5885:         return 1;
 5886:     } else {
 5887:         return 0;
 5888:     }
 5889: }
 5890: 
 5891: sub EXT_cache_set {
 5892:     my ($target_domain,$target_user) = @_;
 5893:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5894:     #&appenv($cachename => time);
 5895: }
 5896: 
 5897: # --------------------------------------------------------- Value of a Variable
 5898: sub EXT {
 5899: 
 5900:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5901:     unless ($varname) { return ''; }
 5902:     #get real user name/domain, courseid and symb
 5903:     my $courseid;
 5904:     my $publicuser;
 5905:     if ($symbparm) {
 5906: 	$symbparm=&get_symb_from_alias($symbparm);
 5907:     }
 5908:     if (!($uname && $udom)) {
 5909:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5910:       if (!$symbparm) {	$symbparm=$cursymb; }
 5911:     } else {
 5912: 	$courseid=$env{'request.course.id'};
 5913:     }
 5914:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5915:     my $rest;
 5916:     if (defined($therest[0])) {
 5917:        $rest=join('.',@therest);
 5918:     } else {
 5919:        $rest='';
 5920:     }
 5921: 
 5922:     my $qualifierrest=$qualifier;
 5923:     if ($rest) { $qualifierrest.='.'.$rest; }
 5924:     my $spacequalifierrest=$space;
 5925:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5926:     if ($realm eq 'user') {
 5927: # --------------------------------------------------------------- user.resource
 5928: 	if ($space eq 'resource') {
 5929: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5930: 		  || defined($Apache::lonhomework::parsing_a_task))
 5931: 		 &&
 5932: 		 ($symbparm eq &symbread()) ) {	
 5933: 		# if we are in the middle of processing the resource the
 5934: 		# get the value we are planning on committing
 5935:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5936:                     return $Apache::lonhomework::results{$qualifierrest};
 5937:                 } else {
 5938:                     return $Apache::lonhomework::history{$qualifierrest};
 5939:                 }
 5940: 	    } else {
 5941: 		my %restored;
 5942: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5943: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5944: 		} else {
 5945: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5946: 		}
 5947: 		return $restored{$qualifierrest};
 5948: 	    }
 5949: # ----------------------------------------------------------------- user.access
 5950:         } elsif ($space eq 'access') {
 5951: 	    # FIXME - not supporting calls for a specific user
 5952:             return &allowed($qualifier,$rest);
 5953: # ------------------------------------------ user.preferences, user.environment
 5954:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5955: 	    if (($uname eq $env{'user.name'}) &&
 5956: 		($udom eq $env{'user.domain'})) {
 5957: 		return $env{join('.',('environment',$qualifierrest))};
 5958: 	    } else {
 5959: 		my %returnhash;
 5960: 		if (!$publicuser) {
 5961: 		    %returnhash=&userenvironment($udom,$uname,
 5962: 						 $qualifierrest);
 5963: 		}
 5964: 		return $returnhash{$qualifierrest};
 5965: 	    }
 5966: # ----------------------------------------------------------------- user.course
 5967:         } elsif ($space eq 'course') {
 5968: 	    # FIXME - not supporting calls for a specific user
 5969:             return $env{join('.',('request.course',$qualifier))};
 5970: # ------------------------------------------------------------------- user.role
 5971:         } elsif ($space eq 'role') {
 5972: 	    # FIXME - not supporting calls for a specific user
 5973:             my ($role,$where)=split(/\./,$env{'request.role'});
 5974:             if ($qualifier eq 'value') {
 5975: 		return $role;
 5976:             } elsif ($qualifier eq 'extent') {
 5977:                 return $where;
 5978:             }
 5979: # ----------------------------------------------------------------- user.domain
 5980:         } elsif ($space eq 'domain') {
 5981:             return $udom;
 5982: # ------------------------------------------------------------------- user.name
 5983:         } elsif ($space eq 'name') {
 5984:             return $uname;
 5985: # ---------------------------------------------------- Any other user namespace
 5986:         } else {
 5987: 	    my %reply;
 5988: 	    if (!$publicuser) {
 5989: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5990: 	    }
 5991: 	    return $reply{$qualifierrest};
 5992:         }
 5993:     } elsif ($realm eq 'query') {
 5994: # ---------------------------------------------- pull stuff out of query string
 5995:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5996: 						[$spacequalifierrest]);
 5997: 	return $env{'form.'.$spacequalifierrest}; 
 5998:    } elsif ($realm eq 'request') {
 5999: # ------------------------------------------------------------- request.browser
 6000:         if ($space eq 'browser') {
 6001: 	    if ($qualifier eq 'textremote') {
 6002: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6003: 		    return 1;
 6004: 		} else {
 6005: 		    return 0;
 6006: 		}
 6007: 	    } else {
 6008: 		return $env{'browser.'.$qualifier};
 6009: 	    }
 6010: # ------------------------------------------------------------ request.filename
 6011:         } else {
 6012:             return $env{'request.'.$spacequalifierrest};
 6013:         }
 6014:     } elsif ($realm eq 'course') {
 6015: # ---------------------------------------------------------- course.description
 6016:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6017:     } elsif ($realm eq 'resource') {
 6018: 
 6019: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6020: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6021: 	}
 6022: 
 6023: 	if ($space eq 'title') {
 6024: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6025: 	    return &gettitle($symbparm);
 6026: 	}
 6027: 	
 6028: 	if ($space eq 'map') {
 6029: 	    my ($map) = &decode_symb($symbparm);
 6030: 	    return &symbread($map);
 6031: 	}
 6032: 
 6033: 	my ($section, $group, @groups);
 6034: 	my ($courselevelm,$courselevel);
 6035: 	if ($symbparm && defined($courseid) && 
 6036: 	    $courseid eq $env{'request.course.id'}) {
 6037: 
 6038: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6039: 
 6040: # ----------------------------------------------------- Cascading lookup scheme
 6041: 	    my $symbp=$symbparm;
 6042: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6043: 
 6044: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6045: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6046: 
 6047: 	    if (($env{'user.name'} eq $uname) &&
 6048: 		($env{'user.domain'} eq $udom)) {
 6049: 		$section=$env{'request.course.sec'};
 6050:                 @groups = split(/:/,$env{'request.course.groups'});  
 6051:                 @groups=&sort_course_groups($courseid,@groups); 
 6052: 	    } else {
 6053: 		if (! defined($usection)) {
 6054: 		    $section=&getsection($udom,$uname,$courseid);
 6055: 		} else {
 6056: 		    $section = $usection;
 6057: 		}
 6058:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6059: 	    }
 6060: 
 6061: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6062: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6063: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6064: 
 6065: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6066: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6067: 	    $courselevelm=$courseid.'.'.$mapparm;
 6068: 
 6069: # ----------------------------------------------------------- first, check user
 6070: 
 6071: 	    my $userreply=&resdata($uname,$udom,'user',
 6072: 				       ($courselevelr,$courselevelm,
 6073: 					$courselevel));
 6074: 	    if (defined($userreply)) { return $userreply; }
 6075: 
 6076: # ------------------------------------------------ second, check some of course
 6077:             my $coursereply;
 6078:             if (@groups > 0) {
 6079:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6080:                                        $mapparm,$spacequalifierrest);
 6081:                 if (defined($coursereply)) { return $coursereply; }
 6082:             }
 6083: 
 6084: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6085: 				     $env{'course.'.$courseid.'.domain'},
 6086: 				     'course',
 6087: 				     ($seclevelr,$seclevelm,$seclevel,
 6088: 				      $courselevelr));
 6089: 	    if (defined($coursereply)) { return $coursereply; }
 6090: 
 6091: # ------------------------------------------------------ third, check map parms
 6092: 	    my %parmhash=();
 6093: 	    my $thisparm='';
 6094: 	    if (tie(%parmhash,'GDBM_File',
 6095: 		    $env{'request.course.fn'}.'_parms.db',
 6096: 		    &GDBM_READER(),0640)) {
 6097: 		$thisparm=$parmhash{$symbparm};
 6098: 		untie(%parmhash);
 6099: 	    }
 6100: 	    if ($thisparm) { return $thisparm; }
 6101: 	}
 6102: # ------------------------------------------ fourth, look in resource metadata
 6103: 
 6104: 	$spacequalifierrest=~s/\./\_/;
 6105: 	my $filename;
 6106: 	if (!$symbparm) { $symbparm=&symbread(); }
 6107: 	if ($symbparm) {
 6108: 	    $filename=(&decode_symb($symbparm))[2];
 6109: 	} else {
 6110: 	    $filename=$env{'request.filename'};
 6111: 	}
 6112: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6113: 	if (defined($metadata)) { return $metadata; }
 6114: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6115: 	if (defined($metadata)) { return $metadata; }
 6116: 
 6117: # ---------------------------------------------- fourth, look in rest pf course
 6118: 	if ($symbparm && defined($courseid) && 
 6119: 	    $courseid eq $env{'request.course.id'}) {
 6120: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6121: 				     $env{'course.'.$courseid.'.domain'},
 6122: 				     'course',
 6123: 				     ($courselevelm,$courselevel));
 6124: 	    if (defined($coursereply)) { return $coursereply; }
 6125: 	}
 6126: # ------------------------------------------------------------------ Cascade up
 6127: 	unless ($space eq '0') {
 6128: 	    my @parts=split(/_/,$space);
 6129: 	    my $id=pop(@parts);
 6130: 	    my $part=join('_',@parts);
 6131: 	    if ($part eq '') { $part='0'; }
 6132: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6133: 				 $symbparm,$udom,$uname,$section,1);
 6134: 	    if (defined($partgeneral)) { return $partgeneral; }
 6135: 	}
 6136: 	if ($recurse) { return undef; }
 6137: 	my $pack_def=&packages_tab_default($filename,$varname);
 6138: 	if (defined($pack_def)) { return $pack_def; }
 6139: 
 6140: # ---------------------------------------------------- Any other user namespace
 6141:     } elsif ($realm eq 'environment') {
 6142: # ----------------------------------------------------------------- environment
 6143: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6144: 	    return $env{'environment.'.$spacequalifierrest};
 6145: 	} else {
 6146: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6147: 		return '';
 6148: 	    }
 6149: 	    my %returnhash=&userenvironment($udom,$uname,
 6150: 					    $spacequalifierrest);
 6151: 	    return $returnhash{$spacequalifierrest};
 6152: 	}
 6153:     } elsif ($realm eq 'system') {
 6154: # ----------------------------------------------------------------- system.time
 6155: 	if ($space eq 'time') {
 6156: 	    return time;
 6157:         }
 6158:     } elsif ($realm eq 'server') {
 6159: # ----------------------------------------------------------------- system.time
 6160: 	if ($space eq 'name') {
 6161: 	    return $ENV{'SERVER_NAME'};
 6162:         }
 6163:     }
 6164:     return '';
 6165: }
 6166: 
 6167: sub check_group_parms {
 6168:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6169:     my @groupitems = ();
 6170:     my $resultitem;
 6171:     my @levels = ($symbparm,$mapparm,$what);
 6172:     foreach my $group (@{$groups}) {
 6173:         foreach my $level (@levels) {
 6174:              my $item = $courseid.'.['.$group.'].'.$level;
 6175:              push(@groupitems,$item);
 6176:         }
 6177:     }
 6178:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6179:                             $env{'course.'.$courseid.'.domain'},
 6180:                                      'course',@groupitems);
 6181:     return $coursereply;
 6182: }
 6183: 
 6184: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6185:     my ($courseid,@groups) = @_;
 6186:     @groups = sort(@groups);
 6187:     return @groups;
 6188: }
 6189: 
 6190: sub packages_tab_default {
 6191:     my ($uri,$varname)=@_;
 6192:     my (undef,$part,$name)=split(/\./,$varname);
 6193: 
 6194:     my (@extension,@specifics,$do_default);
 6195:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6196: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6197: 	if ($pack_type eq 'default') {
 6198: 	    $do_default=1;
 6199: 	} elsif ($pack_type eq 'extension') {
 6200: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6201: 	} elsif ($pack_part eq $part) {
 6202: 	    # only look at packages defaults for packages that this id is
 6203: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6204: 	}
 6205:     }
 6206:     # first look for a package that matches the requested part id
 6207:     foreach my $package (@specifics) {
 6208: 	my (undef,$pack_type,$pack_part)=@{$package};
 6209: 	next if ($pack_part ne $part);
 6210: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6211: 	    return $packagetab{"$pack_type&$name&default"};
 6212: 	}
 6213:     }
 6214:     # look for any possible matching non extension_ package
 6215:     foreach my $package (@specifics) {
 6216: 	my (undef,$pack_type,$pack_part)=@{$package};
 6217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6218: 	    return $packagetab{"$pack_type&$name&default"};
 6219: 	}
 6220: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6221: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6222: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6223: 	}
 6224:     }
 6225:     # look for any posible extension_ match
 6226:     foreach my $package (@extension) {
 6227: 	my ($package,$pack_type)=@{$package};
 6228: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6229: 	    return $packagetab{"$pack_type&$name&default"};
 6230: 	}
 6231: 	if (defined($packagetab{$package."&$name&default"})) {
 6232: 	    return $packagetab{$package."&$name&default"};
 6233: 	}
 6234:     }
 6235:     # look for a global default setting
 6236:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6237: 	return $packagetab{"default&$name&default"};
 6238:     }
 6239:     return undef;
 6240: }
 6241: 
 6242: sub add_prefix_and_part {
 6243:     my ($prefix,$part)=@_;
 6244:     my $keyroot;
 6245:     if (defined($prefix) && $prefix !~ /^__/) {
 6246: 	# prefix that has a part already
 6247: 	$keyroot=$prefix;
 6248:     } elsif (defined($prefix)) {
 6249: 	# prefix that is missing a part
 6250: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6251:     } else {
 6252: 	# no prefix at all
 6253: 	if (defined($part)) { $keyroot='_'.$part; }
 6254:     }
 6255:     return $keyroot;
 6256: }
 6257: 
 6258: # ---------------------------------------------------------------- Get metadata
 6259: 
 6260: my %metaentry;
 6261: sub metadata {
 6262:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6263:     $uri=&declutter($uri);
 6264:     # if it is a non metadata possible uri return quickly
 6265:     if (($uri eq '') || 
 6266: 	(($uri =~ m|^/*adm/|) && 
 6267: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6268:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6269: 	($uri =~ m|home/$match_username/public_html/|)) {
 6270: 	return undef;
 6271:     }
 6272:     my $filename=$uri;
 6273:     $uri=~s/\.meta$//;
 6274: #
 6275: # Is the metadata already cached?
 6276: # Look at timestamp of caching
 6277: # Everything is cached by the main uri, libraries are never directly cached
 6278: #
 6279:     if (!defined($liburi)) {
 6280: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6281: 	if (defined($cached)) { return $result->{':'.$what}; }
 6282:     }
 6283:     {
 6284: #
 6285: # Is this a recursive call for a library?
 6286: #
 6287: #	if (! exists($metacache{$uri})) {
 6288: #	    $metacache{$uri}={};
 6289: #	}
 6290:         if ($liburi) {
 6291: 	    $liburi=&declutter($liburi);
 6292:             $filename=$liburi;
 6293:         } else {
 6294: 	    &devalidate_cache_new('meta',$uri);
 6295: 	    undef(%metaentry);
 6296: 	}
 6297:         my %metathesekeys=();
 6298:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6299: 	my $metastring;
 6300: 	if ($uri !~ m -^(editupload)/-) {
 6301: 	    my $file=&filelocation('',&clutter($filename));
 6302: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6303: 	    $metastring=&getfile($file);
 6304: 	}
 6305:         my $parser=HTML::LCParser->new(\$metastring);
 6306:         my $token;
 6307:         undef %metathesekeys;
 6308:         while ($token=$parser->get_token) {
 6309: 	    if ($token->[0] eq 'S') {
 6310: 		if (defined($token->[2]->{'package'})) {
 6311: #
 6312: # This is a package - get package info
 6313: #
 6314: 		    my $package=$token->[2]->{'package'};
 6315: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6316: 		    if (defined($token->[2]->{'id'})) { 
 6317: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6318: 		    }
 6319: 		    if ($metaentry{':packages'}) {
 6320: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6321: 		    } else {
 6322: 			$metaentry{':packages'}=$package.$keyroot;
 6323: 		    }
 6324: 		    foreach my $pack_entry (keys(%packagetab)) {
 6325: 			my $part=$keyroot;
 6326: 			$part=~s/^\_//;
 6327: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6328: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6329: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6330: 			    # ignore package.tab specified default values
 6331:                             # here &package_tab_default() will fetch those
 6332: 			    if ($subp eq 'default') { next; }
 6333: 			    my $value=$packagetab{$pack_entry};
 6334: 			    my $unikey;
 6335: 			    if ($pack =~ /_0$/) {
 6336: 				$unikey='parameter_0_'.$name;
 6337: 				$part=0;
 6338: 			    } else {
 6339: 				$unikey='parameter'.$keyroot.'_'.$name;
 6340: 			    }
 6341: 			    if ($subp eq 'display') {
 6342: 				$value.=' [Part: '.$part.']';
 6343: 			    }
 6344: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6345: 			    $metathesekeys{$unikey}=1;
 6346: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6347: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6348: 			    }
 6349: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6350: 				$metaentry{':'.$unikey}=
 6351: 				    $metaentry{':'.$unikey.'.default'};
 6352: 			    }
 6353: 			}
 6354: 		    }
 6355: 		} else {
 6356: #
 6357: # This is not a package - some other kind of start tag
 6358: #
 6359: 		    my $entry=$token->[1];
 6360: 		    my $unikey;
 6361: 		    if ($entry eq 'import') {
 6362: 			$unikey='';
 6363: 		    } else {
 6364: 			$unikey=$entry;
 6365: 		    }
 6366: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6367: 
 6368: 		    if (defined($token->[2]->{'id'})) { 
 6369: 			$unikey.='_'.$token->[2]->{'id'}; 
 6370: 		    }
 6371: 
 6372: 		    if ($entry eq 'import') {
 6373: #
 6374: # Importing a library here
 6375: #
 6376: 			if ($depthcount<20) {
 6377: 			    my $location=$parser->get_text('/import');
 6378: 			    my $dir=$filename;
 6379: 			    $dir=~s|[^/]*$||;
 6380: 			    $location=&filelocation($dir,$location);
 6381: 			    my $metadata = 
 6382: 				&metadata($uri,'keys', $location,$unikey,
 6383: 					  $depthcount+1);
 6384: 			    foreach my $meta (split(',',$metadata)) {
 6385: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6386: 				$metathesekeys{$meta}=1;
 6387: 			    }
 6388: 			}
 6389: 		    } else { 
 6390: 			
 6391: 			if (defined($token->[2]->{'name'})) { 
 6392: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6393: 			}
 6394: 			$metathesekeys{$unikey}=1;
 6395: 			foreach my $param (@{$token->[3]}) {
 6396: 			    $metaentry{':'.$unikey.'.'.$param} =
 6397: 				$token->[2]->{$param};
 6398: 			}
 6399: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6400: 			my $default=$metaentry{':'.$unikey.'.default'};
 6401: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6402: 		 # only ws inside the tag, and not in default, so use default
 6403: 		 # as value
 6404: 			    $metaentry{':'.$unikey}=$default;
 6405: 			} else {
 6406: 		  # either something interesting inside the tag or default
 6407:                   # uninteresting
 6408: 			    $metaentry{':'.$unikey}=$internaltext;
 6409: 			}
 6410: # end of not-a-package not-a-library import
 6411: 		    }
 6412: # end of not-a-package start tag
 6413: 		}
 6414: # the next is the end of "start tag"
 6415: 	    }
 6416: 	}
 6417: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6418: 	foreach my $key (keys(%packagetab)) {
 6419: 	    #no specific packages #how's our extension
 6420: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6421: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6422: 					 \%metathesekeys);
 6423: 	}
 6424: 	if (!exists($metaentry{':packages'})) {
 6425: 	    foreach my $key (keys(%packagetab)) {
 6426: 		#no specific packages well let's get default then
 6427: 		if ($key!~/^default&/) { next; }
 6428: 		&metadata_create_package_def($uri,$key,'default',
 6429: 					     \%metathesekeys);
 6430: 	    }
 6431: 	}
 6432: # are there custom rights to evaluate
 6433: 	if ($metaentry{':copyright'} eq 'custom') {
 6434: 
 6435:     #
 6436:     # Importing a rights file here
 6437:     #
 6438: 	    unless ($depthcount) {
 6439: 		my $location=$metaentry{':customdistributionfile'};
 6440: 		my $dir=$filename;
 6441: 		$dir=~s|[^/]*$||;
 6442: 		$location=&filelocation($dir,$location);
 6443: 		my $rights_metadata =
 6444: 		    &metadata($uri,'keys',$location,'_rights',
 6445: 			      $depthcount+1);
 6446: 		foreach my $rights (split(',',$rights_metadata)) {
 6447: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6448: 		    $metathesekeys{$rights}=1;
 6449: 		}
 6450: 	    }
 6451: 	}
 6452: 	# uniqifiy package listing
 6453: 	my %seen;
 6454: 	my @uniq_packages =
 6455: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6456: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6457: 
 6458: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6459: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6460: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6461: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6462: # this is the end of "was not already recently cached
 6463:     }
 6464:     return $metaentry{':'.$what};
 6465: }
 6466: 
 6467: sub metadata_create_package_def {
 6468:     my ($uri,$key,$package,$metathesekeys)=@_;
 6469:     my ($pack,$name,$subp)=split(/\&/,$key);
 6470:     if ($subp eq 'default') { next; }
 6471:     
 6472:     if (defined($metaentry{':packages'})) {
 6473: 	$metaentry{':packages'}.=','.$package;
 6474:     } else {
 6475: 	$metaentry{':packages'}=$package;
 6476:     }
 6477:     my $value=$packagetab{$key};
 6478:     my $unikey;
 6479:     $unikey='parameter_0_'.$name;
 6480:     $metaentry{':'.$unikey.'.part'}=0;
 6481:     $$metathesekeys{$unikey}=1;
 6482:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6483: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6484:     }
 6485:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6486: 	$metaentry{':'.$unikey}=
 6487: 	    $metaentry{':'.$unikey.'.default'};
 6488:     }
 6489: }
 6490: 
 6491: sub metadata_generate_part0 {
 6492:     my ($metadata,$metacache,$uri) = @_;
 6493:     my %allnames;
 6494:     foreach my $metakey (keys(%$metadata)) {
 6495: 	if ($metakey=~/^parameter\_(.*)/) {
 6496: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6497: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6498: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6499: 	    $allnames{$name}=$part;
 6500: 	  }
 6501: 	}
 6502:     }
 6503:     foreach my $name (keys(%allnames)) {
 6504:       $$metadata{"parameter_0_$name"}=1;
 6505:       my $key=":parameter_0_$name";
 6506:       $$metacache{"$key.part"}='0';
 6507:       $$metacache{"$key.name"}=$name;
 6508:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6509: 					   $allnames{$name}.'_'.$name.
 6510: 					   '.type'};
 6511:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6512: 			     '.display'};
 6513:       my $expr='[Part: '.$allnames{$name}.']';
 6514:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6515:       $$metacache{"$key.display"}=$olddis;
 6516:     }
 6517: }
 6518: 
 6519: # ------------------------------------------------------ Devalidate title cache
 6520: 
 6521: sub devalidate_title_cache {
 6522:     my ($url)=@_;
 6523:     if (!$env{'request.course.id'}) { return; }
 6524:     my $symb=&symbread($url);
 6525:     if (!$symb) { return; }
 6526:     my $key=$env{'request.course.id'}."\0".$symb;
 6527:     &devalidate_cache_new('title',$key);
 6528: }
 6529: 
 6530: # ------------------------------------------------- Get the title of a resource
 6531: 
 6532: sub gettitle {
 6533:     my $urlsymb=shift;
 6534:     my $symb=&symbread($urlsymb);
 6535:     if ($symb) {
 6536: 	my $key=$env{'request.course.id'}."\0".$symb;
 6537: 	my ($result,$cached)=&is_cached_new('title',$key);
 6538: 	if (defined($cached)) { 
 6539: 	    return $result;
 6540: 	}
 6541: 	my ($map,$resid,$url)=&decode_symb($symb);
 6542: 	my $title='';
 6543: 	my %bighash;
 6544: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6545: 		&GDBM_READER(),0640)) {
 6546: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6547: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6548: 	    untie %bighash;
 6549: 	}
 6550: 	$title=~s/\&colon\;/\:/gs;
 6551: 	if ($title) {
 6552: 	    return &do_cache_new('title',$key,$title,600);
 6553: 	}
 6554: 	$urlsymb=$url;
 6555:     }
 6556:     my $title=&metadata($urlsymb,'title');
 6557:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6558:     return $title;
 6559: }
 6560: 
 6561: sub get_slot {
 6562:     my ($which,$cnum,$cdom)=@_;
 6563:     if (!$cnum || !$cdom) {
 6564: 	(undef,my $courseid)=&whichuser();
 6565: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6566: 	$cnum=$env{'course.'.$courseid.'.num'};
 6567:     }
 6568:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6569:     my %slotinfo;
 6570:     if (exists($remembered{$key})) {
 6571: 	$slotinfo{$which} = $remembered{$key};
 6572:     } else {
 6573: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6574: 	&Apache::lonhomework::showhash(%slotinfo);
 6575: 	my ($tmp)=keys(%slotinfo);
 6576: 	if ($tmp=~/^error:/) { return (); }
 6577: 	$remembered{$key} = $slotinfo{$which};
 6578:     }
 6579:     if (ref($slotinfo{$which}) eq 'HASH') {
 6580: 	return %{$slotinfo{$which}};
 6581:     }
 6582:     return $slotinfo{$which};
 6583: }
 6584: # ------------------------------------------------- Update symbolic store links
 6585: 
 6586: sub symblist {
 6587:     my ($mapname,%newhash)=@_;
 6588:     $mapname=&deversion(&declutter($mapname));
 6589:     my %hash;
 6590:     if (($env{'request.course.fn'}) && (%newhash)) {
 6591:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6592:                       &GDBM_WRCREAT(),0640)) {
 6593: 	    foreach my $url (keys %newhash) {
 6594: 		next if ($url eq 'last_known'
 6595: 			 && $env{'form.no_update_last_known'});
 6596: 		$hash{declutter($url)}=&encode_symb($mapname,
 6597: 						    $newhash{$url}->[1],
 6598: 						    $newhash{$url}->[0]);
 6599:             }
 6600:             if (untie(%hash)) {
 6601: 		return 'ok';
 6602:             }
 6603:         }
 6604:     }
 6605:     return 'error';
 6606: }
 6607: 
 6608: # --------------------------------------------------------------- Verify a symb
 6609: 
 6610: sub symbverify {
 6611:     my ($symb,$thisurl)=@_;
 6612:     my $thisfn=$thisurl;
 6613:     $thisfn=&declutter($thisfn);
 6614: # direct jump to resource in page or to a sequence - will construct own symbs
 6615:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6616: # check URL part
 6617:     my ($map,$resid,$url)=&decode_symb($symb);
 6618: 
 6619:     unless ($url eq $thisfn) { return 0; }
 6620: 
 6621:     $symb=&symbclean($symb);
 6622:     $thisurl=&deversion($thisurl);
 6623:     $thisfn=&deversion($thisfn);
 6624: 
 6625:     my %bighash;
 6626:     my $okay=0;
 6627: 
 6628:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6629:                             &GDBM_READER(),0640)) {
 6630:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6631:         unless ($ids) { 
 6632:            $ids=$bighash{'ids_/'.$thisurl};
 6633:         }
 6634:         if ($ids) {
 6635: # ------------------------------------------------------------------- Has ID(s)
 6636: 	    foreach my $id (split(/\,/,$ids)) {
 6637: 	       my ($mapid,$resid)=split(/\./,$id);
 6638:                if (
 6639:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6640:    eq $symb) { 
 6641: 		   if (($env{'request.role.adv'}) ||
 6642: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6643: 		       $okay=1; 
 6644: 		   }
 6645: 	       }
 6646: 	   }
 6647:         }
 6648: 	untie(%bighash);
 6649:     }
 6650:     return $okay;
 6651: }
 6652: 
 6653: # --------------------------------------------------------------- Clean-up symb
 6654: 
 6655: sub symbclean {
 6656:     my $symb=shift;
 6657:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6658: # remove version from map
 6659:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6660: 
 6661: # remove version from URL
 6662:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6663: 
 6664: # remove wrapper
 6665: 
 6666:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6667:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6668:     return $symb;
 6669: }
 6670: 
 6671: # ---------------------------------------------- Split symb to find map and url
 6672: 
 6673: sub encode_symb {
 6674:     my ($map,$resid,$url)=@_;
 6675:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6676: }
 6677: 
 6678: sub decode_symb {
 6679:     my $symb=shift;
 6680:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6681:     my ($map,$resid,$url)=split(/___/,$symb);
 6682:     return (&fixversion($map),$resid,&fixversion($url));
 6683: }
 6684: 
 6685: sub fixversion {
 6686:     my $fn=shift;
 6687:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6688:     my %bighash;
 6689:     my $uri=&clutter($fn);
 6690:     my $key=$env{'request.course.id'}.'_'.$uri;
 6691: # is this cached?
 6692:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6693:     if (defined($cached)) { return $result; }
 6694: # unfortunately not cached, or expired
 6695:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6696: 	    &GDBM_READER(),0640)) {
 6697:  	if ($bighash{'version_'.$uri}) {
 6698:  	    my $version=$bighash{'version_'.$uri};
 6699:  	    unless (($version eq 'mostrecent') || 
 6700: 		    ($version==&getversion($uri))) {
 6701:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6702:  	    }
 6703:  	}
 6704:  	untie %bighash;
 6705:     }
 6706:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6707: }
 6708: 
 6709: sub deversion {
 6710:     my $url=shift;
 6711:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6712:     return $url;
 6713: }
 6714: 
 6715: # ------------------------------------------------------ Return symb list entry
 6716: 
 6717: sub symbread {
 6718:     my ($thisfn,$donotrecurse)=@_;
 6719:     my $cache_str='request.symbread.cached.'.$thisfn;
 6720:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6721: # no filename provided? try from environment
 6722:     unless ($thisfn) {
 6723:         if ($env{'request.symb'}) {
 6724: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6725: 	}
 6726: 	$thisfn=$env{'request.filename'};
 6727:     }
 6728:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6729: # is that filename actually a symb? Verify, clean, and return
 6730:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6731: 	if (&symbverify($thisfn,$1)) {
 6732: 	    return $env{$cache_str}=&symbclean($thisfn);
 6733: 	}
 6734:     }
 6735:     $thisfn=declutter($thisfn);
 6736:     my %hash;
 6737:     my %bighash;
 6738:     my $syval='';
 6739:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6740:         my $targetfn = $thisfn;
 6741:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6742:             $targetfn = 'adm/wrapper/'.$thisfn;
 6743:         }
 6744: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6745: 	    $targetfn=$1;
 6746: 	}
 6747:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6748:                       &GDBM_READER(),0640)) {
 6749: 	    $syval=$hash{$targetfn};
 6750:             untie(%hash);
 6751:         }
 6752: # ---------------------------------------------------------- There was an entry
 6753:         if ($syval) {
 6754: 	    #unless ($syval=~/\_\d+$/) {
 6755: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6756: 		    #&appenv('request.ambiguous' => $thisfn);
 6757: 		    #return $env{$cache_str}='';
 6758: 		#}    
 6759: 		#$syval.=$1;
 6760: 	    #}
 6761:         } else {
 6762: # ------------------------------------------------------- Was not in symb table
 6763:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6764:                             &GDBM_READER(),0640)) {
 6765: # ---------------------------------------------- Get ID(s) for current resource
 6766:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6767:               unless ($ids) { 
 6768:                  $ids=$bighash{'ids_/'.$thisfn};
 6769:               }
 6770:               unless ($ids) {
 6771: # alias?
 6772: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6773:               }
 6774:               if ($ids) {
 6775: # ------------------------------------------------------------------- Has ID(s)
 6776:                  my @possibilities=split(/\,/,$ids);
 6777:                  if ($#possibilities==0) {
 6778: # ----------------------------------------------- There is only one possibility
 6779: 		     my ($mapid,$resid)=split(/\./,$ids);
 6780: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6781: 						    $resid,$thisfn);
 6782:                  } elsif (!$donotrecurse) {
 6783: # ------------------------------------------ There is more than one possibility
 6784:                      my $realpossible=0;
 6785:                      foreach my $id (@possibilities) {
 6786: 			 my $file=$bighash{'src_'.$id};
 6787:                          if (&allowed('bre',$file)) {
 6788:          		    my ($mapid,$resid)=split(/\./,$id);
 6789:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6790: 				$realpossible++;
 6791:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6792: 						    $resid,$thisfn);
 6793:                             }
 6794: 			 }
 6795:                      }
 6796: 		     if ($realpossible!=1) { $syval=''; }
 6797:                  } else {
 6798:                      $syval='';
 6799:                  }
 6800: 	      }
 6801:               untie(%bighash)
 6802:            }
 6803:         }
 6804:         if ($syval) {
 6805: 	    return $env{$cache_str}=$syval;
 6806:         }
 6807:     }
 6808:     &appenv('request.ambiguous' => $thisfn);
 6809:     return $env{$cache_str}='';
 6810: }
 6811: 
 6812: # ---------------------------------------------------------- Return random seed
 6813: 
 6814: sub numval {
 6815:     my $txt=shift;
 6816:     $txt=~tr/A-J/0-9/;
 6817:     $txt=~tr/a-j/0-9/;
 6818:     $txt=~tr/K-T/0-9/;
 6819:     $txt=~tr/k-t/0-9/;
 6820:     $txt=~tr/U-Z/0-5/;
 6821:     $txt=~tr/u-z/0-5/;
 6822:     $txt=~s/\D//g;
 6823:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6824:     return int($txt);
 6825: }
 6826: 
 6827: sub numval2 {
 6828:     my $txt=shift;
 6829:     $txt=~tr/A-J/0-9/;
 6830:     $txt=~tr/a-j/0-9/;
 6831:     $txt=~tr/K-T/0-9/;
 6832:     $txt=~tr/k-t/0-9/;
 6833:     $txt=~tr/U-Z/0-5/;
 6834:     $txt=~tr/u-z/0-5/;
 6835:     $txt=~s/\D//g;
 6836:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6837:     my $total;
 6838:     foreach my $val (@txts) { $total+=$val; }
 6839:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6840:     return int($total);
 6841: }
 6842: 
 6843: sub numval3 {
 6844:     use integer;
 6845:     my $txt=shift;
 6846:     $txt=~tr/A-J/0-9/;
 6847:     $txt=~tr/a-j/0-9/;
 6848:     $txt=~tr/K-T/0-9/;
 6849:     $txt=~tr/k-t/0-9/;
 6850:     $txt=~tr/U-Z/0-5/;
 6851:     $txt=~tr/u-z/0-5/;
 6852:     $txt=~s/\D//g;
 6853:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6854:     my $total;
 6855:     foreach my $val (@txts) { $total+=$val; }
 6856:     if ($_64bit) { $total=(($total<<32)>>32); }
 6857:     return $total;
 6858: }
 6859: 
 6860: sub digest {
 6861:     my ($data)=@_;
 6862:     my $digest=&Digest::MD5::md5($data);
 6863:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6864:     my ($e,$f);
 6865:     {
 6866:         use integer;
 6867:         $e=($a+$b);
 6868:         $f=($c+$d);
 6869:         if ($_64bit) {
 6870:             $e=(($e<<32)>>32);
 6871:             $f=(($f<<32)>>32);
 6872:         }
 6873:     }
 6874:     if (wantarray) {
 6875: 	return ($e,$f);
 6876:     } else {
 6877: 	my $g;
 6878: 	{
 6879: 	    use integer;
 6880: 	    $g=($e+$f);
 6881: 	    if ($_64bit) {
 6882: 		$g=(($g<<32)>>32);
 6883: 	    }
 6884: 	}
 6885: 	return $g;
 6886:     }
 6887: }
 6888: 
 6889: sub latest_rnd_algorithm_id {
 6890:     return '64bit5';
 6891: }
 6892: 
 6893: sub get_rand_alg {
 6894:     my ($courseid)=@_;
 6895:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6896:     if ($courseid) {
 6897: 	return $env{"course.$courseid.rndseed"};
 6898:     }
 6899:     return &latest_rnd_algorithm_id();
 6900: }
 6901: 
 6902: sub validCODE {
 6903:     my ($CODE)=@_;
 6904:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6905:     return 0;
 6906: }
 6907: 
 6908: sub getCODE {
 6909:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6910:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6911: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6912: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6913: 	return $Apache::lonhomework::history{'resource.CODE'};
 6914:     }
 6915:     return undef;
 6916: }
 6917: 
 6918: sub rndseed {
 6919:     my ($symb,$courseid,$domain,$username)=@_;
 6920: 
 6921:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6922:     if (!$symb) {
 6923: 	unless ($symb=$wsymb) { return time; }
 6924:     }
 6925:     if (!$courseid) { $courseid=$wcourseid; }
 6926:     if (!$domain) { $domain=$wdomain; }
 6927:     if (!$username) { $username=$wusername }
 6928:     my $which=&get_rand_alg();
 6929: 
 6930:     if (defined(&getCODE())) {
 6931: 	if ($which eq '64bit5') {
 6932: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6933: 	} elsif ($which eq '64bit4') {
 6934: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6935: 	} else {
 6936: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6937: 	}
 6938:     } elsif ($which eq '64bit5') {
 6939: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6940:     } elsif ($which eq '64bit4') {
 6941: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6942:     } elsif ($which eq '64bit3') {
 6943: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6944:     } elsif ($which eq '64bit2') {
 6945: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6946:     } elsif ($which eq '64bit') {
 6947: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6948:     }
 6949:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6950: }
 6951: 
 6952: sub rndseed_32bit {
 6953:     my ($symb,$courseid,$domain,$username)=@_;
 6954:     {
 6955: 	use integer;
 6956: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6957: 	my $symbseed=numval($symb) << 22;
 6958: 	my $namechck=unpack("%32C*",$username) << 17;
 6959: 	my $nameseed=numval($username) << 12;
 6960: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6961: 	my $courseseed=unpack("%32C*",$courseid);
 6962: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6963: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6964: 	#&logthis("rndseed :$num:$symb");
 6965: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6966: 	return $num;
 6967:     }
 6968: }
 6969: 
 6970: sub rndseed_64bit {
 6971:     my ($symb,$courseid,$domain,$username)=@_;
 6972:     {
 6973: 	use integer;
 6974: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6975: 	my $symbseed=numval($symb) << 10;
 6976: 	my $namechck=unpack("%32S*",$username);
 6977: 	
 6978: 	my $nameseed=numval($username) << 21;
 6979: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6980: 	my $courseseed=unpack("%32S*",$courseid);
 6981: 	
 6982: 	my $num1=$symbchck+$symbseed+$namechck;
 6983: 	my $num2=$nameseed+$domainseed+$courseseed;
 6984: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6985: 	#&logthis("rndseed :$num:$symb");
 6986: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6987: 	return "$num1,$num2";
 6988:     }
 6989: }
 6990: 
 6991: sub rndseed_64bit2 {
 6992:     my ($symb,$courseid,$domain,$username)=@_;
 6993:     {
 6994: 	use integer;
 6995: 	# strings need to be an even # of cahracters long, it it is odd the
 6996:         # last characters gets thrown away
 6997: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6998: 	my $symbseed=numval($symb) << 10;
 6999: 	my $namechck=unpack("%32S*",$username.' ');
 7000: 	
 7001: 	my $nameseed=numval($username) << 21;
 7002: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7003: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7004: 	
 7005: 	my $num1=$symbchck+$symbseed+$namechck;
 7006: 	my $num2=$nameseed+$domainseed+$courseseed;
 7007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7008: 	#&logthis("rndseed :$num:$symb");
 7009: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7010: 	return "$num1,$num2";
 7011:     }
 7012: }
 7013: 
 7014: sub rndseed_64bit3 {
 7015:     my ($symb,$courseid,$domain,$username)=@_;
 7016:     {
 7017: 	use integer;
 7018: 	# strings need to be an even # of cahracters long, it it is odd the
 7019:         # last characters gets thrown away
 7020: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7021: 	my $symbseed=numval2($symb) << 10;
 7022: 	my $namechck=unpack("%32S*",$username.' ');
 7023: 	
 7024: 	my $nameseed=numval2($username) << 21;
 7025: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7026: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7027: 	
 7028: 	my $num1=$symbchck+$symbseed+$namechck;
 7029: 	my $num2=$nameseed+$domainseed+$courseseed;
 7030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7031: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7032: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7033: 	
 7034: 	return "$num1:$num2";
 7035:     }
 7036: }
 7037: 
 7038: sub rndseed_64bit4 {
 7039:     my ($symb,$courseid,$domain,$username)=@_;
 7040:     {
 7041: 	use integer;
 7042: 	# strings need to be an even # of cahracters long, it it is odd the
 7043:         # last characters gets thrown away
 7044: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7045: 	my $symbseed=numval3($symb) << 10;
 7046: 	my $namechck=unpack("%32S*",$username.' ');
 7047: 	
 7048: 	my $nameseed=numval3($username) << 21;
 7049: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7050: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7051: 	
 7052: 	my $num1=$symbchck+$symbseed+$namechck;
 7053: 	my $num2=$nameseed+$domainseed+$courseseed;
 7054: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7055: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7056: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7057: 	
 7058: 	return "$num1:$num2";
 7059:     }
 7060: }
 7061: 
 7062: sub rndseed_64bit5 {
 7063:     my ($symb,$courseid,$domain,$username)=@_;
 7064:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7065:     return "$num1:$num2";
 7066: }
 7067: 
 7068: sub rndseed_CODE_64bit {
 7069:     my ($symb,$courseid,$domain,$username)=@_;
 7070:     {
 7071: 	use integer;
 7072: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7073: 	my $symbseed=numval2($symb);
 7074: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7075: 	my $CODEseed=numval(&getCODE());
 7076: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7077: 	my $num1=$symbseed+$CODEchck;
 7078: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7079: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7080: 	#&logthis("rndseed :$num1:$num2:$symb");
 7081: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7082: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7083: 	return "$num1:$num2";
 7084:     }
 7085: }
 7086: 
 7087: sub rndseed_CODE_64bit4 {
 7088:     my ($symb,$courseid,$domain,$username)=@_;
 7089:     {
 7090: 	use integer;
 7091: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7092: 	my $symbseed=numval3($symb);
 7093: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7094: 	my $CODEseed=numval3(&getCODE());
 7095: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7096: 	my $num1=$symbseed+$CODEchck;
 7097: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7098: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7099: 	#&logthis("rndseed :$num1:$num2:$symb");
 7100: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7101: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7102: 	return "$num1:$num2";
 7103:     }
 7104: }
 7105: 
 7106: sub rndseed_CODE_64bit5 {
 7107:     my ($symb,$courseid,$domain,$username)=@_;
 7108:     my $code = &getCODE();
 7109:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7110:     return "$num1:$num2";
 7111: }
 7112: 
 7113: sub setup_random_from_rndseed {
 7114:     my ($rndseed)=@_;
 7115:     if ($rndseed =~/([,:])/) {
 7116: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7117: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7118:     } else {
 7119: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7120:     }
 7121: }
 7122: 
 7123: sub latest_receipt_algorithm_id {
 7124:     return 'receipt3';
 7125: }
 7126: 
 7127: sub recunique {
 7128:     my $fucourseid=shift;
 7129:     my $unique;
 7130:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7131: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7132: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7133:     } else {
 7134: 	$unique=$perlvar{'lonReceipt'};
 7135:     }
 7136:     return unpack("%32C*",$unique);
 7137: }
 7138: 
 7139: sub recprefix {
 7140:     my $fucourseid=shift;
 7141:     my $prefix;
 7142:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7143: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7144: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7145:     } else {
 7146: 	$prefix=$perlvar{'lonHostID'};
 7147:     }
 7148:     return unpack("%32C*",$prefix);
 7149: }
 7150: 
 7151: sub ireceipt {
 7152:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7153: 
 7154:     my $return =&recprefix($fucourseid).'-';
 7155: 
 7156:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7157: 	$env{'request.state'} eq 'construct') {
 7158: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7159: 	return $return;
 7160:     }
 7161: 
 7162:     my $cuname=unpack("%32C*",$funame);
 7163:     my $cudom=unpack("%32C*",$fudom);
 7164:     my $cucourseid=unpack("%32C*",$fucourseid);
 7165:     my $cusymb=unpack("%32C*",$fusymb);
 7166:     my $cunique=&recunique($fucourseid);
 7167:     my $cpart=unpack("%32S*",$part);
 7168:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7169: 
 7170: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7171: 			       
 7172: 	$return.= ($cunique%$cuname+
 7173: 		   $cunique%$cudom+
 7174: 		   $cusymb%$cuname+
 7175: 		   $cusymb%$cudom+
 7176: 		   $cucourseid%$cuname+
 7177: 		   $cucourseid%$cudom+
 7178: 		   $cpart%$cuname+
 7179: 		   $cpart%$cudom);
 7180:     } else {
 7181: 	$return.= ($cunique%$cuname+
 7182: 		   $cunique%$cudom+
 7183: 		   $cusymb%$cuname+
 7184: 		   $cusymb%$cudom+
 7185: 		   $cucourseid%$cuname+
 7186: 		   $cucourseid%$cudom);
 7187:     }
 7188:     return $return;
 7189: }
 7190: 
 7191: sub receipt {
 7192:     my ($part)=@_;
 7193:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7194:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7195: }
 7196: 
 7197: sub whichuser {
 7198:     my ($passedsymb)=@_;
 7199:     my ($symb,$courseid,$domain,$name,$publicuser);
 7200:     if (defined($env{'form.grade_symb'})) {
 7201: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7202: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7203: 	if (!$allowed &&
 7204: 	    exists($env{'request.course.sec'}) &&
 7205: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7206: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7207: 			      '/'.$env{'request.course.sec'});
 7208: 	}
 7209: 	if ($allowed) {
 7210: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7211: 	    $courseid=$tmp_courseid;
 7212: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7213: 	    ($name)=&get_env_multiple('form.grade_username');
 7214: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7215: 	}
 7216:     }
 7217:     if (!$passedsymb) {
 7218: 	$symb=&symbread();
 7219:     } else {
 7220: 	$symb=$passedsymb;
 7221:     }
 7222:     $courseid=$env{'request.course.id'};
 7223:     $domain=$env{'user.domain'};
 7224:     $name=$env{'user.name'};
 7225:     if ($name eq 'public' && $domain eq 'public') {
 7226: 	if (!defined($env{'form.username'})) {
 7227: 	    $env{'form.username'}.=time.rand(10000000);
 7228: 	}
 7229: 	$name.=$env{'form.username'};
 7230:     }
 7231:     return ($symb,$courseid,$domain,$name,$publicuser);
 7232: 
 7233: }
 7234: 
 7235: # ------------------------------------------------------------ Serves up a file
 7236: # returns either the contents of the file or 
 7237: # -1 if the file doesn't exist
 7238: #
 7239: # if the target is a file that was uploaded via DOCS, 
 7240: # a check will be made to see if a current copy exists on the local server,
 7241: # if it does this will be served, otherwise a copy will be retrieved from
 7242: # the home server for the course and stored in /home/httpd/html/userfiles on
 7243: # the local server.   
 7244: 
 7245: sub getfile {
 7246:     my ($file) = @_;
 7247:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7248:     &repcopy($file);
 7249:     return &readfile($file);
 7250: }
 7251: 
 7252: sub repcopy_userfile {
 7253:     my ($file)=@_;
 7254:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7255:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7256:     my ($cdom,$cnum,$filename) = 
 7257: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7258:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7259:     if (-e "$file") {
 7260: # we already have a local copy, check it out
 7261: 	my @fileinfo = stat($file);
 7262: 	my $rtncode;
 7263: 	my $info;
 7264: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7265: 	if ($lwpresp ne 'ok') {
 7266: # there is no such file anymore, even though we had a local copy
 7267: 	    if ($rtncode eq '404') {
 7268: 		unlink($file);
 7269: 	    }
 7270: 	    return -1;
 7271: 	}
 7272: 	if ($info < $fileinfo[9]) {
 7273: # nice, the file we have is up-to-date, just say okay
 7274: 	    return 'ok';
 7275: 	} else {
 7276: # the file is outdated, get rid of it
 7277: 	    unlink($file);
 7278: 	}
 7279:     }
 7280: # one way or the other, at this point, we don't have the file
 7281: # construct the correct path for the file
 7282:     my @parts = ($cdom,$cnum); 
 7283:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7284: 	push @parts, split(/\//,$1);
 7285:     }
 7286:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7287:     foreach my $part (@parts) {
 7288: 	$path .= '/'.$part;
 7289: 	if (!-e $path) {
 7290: 	    mkdir($path,0770);
 7291: 	}
 7292:     }
 7293: # now the path exists for sure
 7294: # get a user agent
 7295:     my $ua=new LWP::UserAgent;
 7296:     my $transferfile=$file.'.in.transfer';
 7297: # FIXME: this should flock
 7298:     if (-e $transferfile) { return 'ok'; }
 7299:     my $request;
 7300:     $uri=~s/^\///;
 7301:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7302:     my $response=$ua->request($request,$transferfile);
 7303: # did it work?
 7304:     if ($response->is_error()) {
 7305: 	unlink($transferfile);
 7306: 	&logthis("Userfile repcopy failed for $uri");
 7307: 	return -1;
 7308:     }
 7309: # worked, rename the transfer file
 7310:     rename($transferfile,$file);
 7311:     return 'ok';
 7312: }
 7313: 
 7314: sub tokenwrapper {
 7315:     my $uri=shift;
 7316:     $uri=~s|^http\://([^/]+)||;
 7317:     $uri=~s|^/||;
 7318:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7319:     my $token=$1;
 7320:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7321:     if ($udom && $uname && $file) {
 7322: 	$file=~s|(\?\.*)*$||;
 7323:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7324:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7325:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7326:                                '&tokenissued='.$perlvar{'lonHostID'};
 7327:     } else {
 7328:         return '/adm/notfound.html';
 7329:     }
 7330: }
 7331: 
 7332: # call with reqtype HEAD: get last modification time
 7333: # call with reqtype GET: get the file contents
 7334: # Do not call this with reqtype GET for large files! It loads everything into memory
 7335: #
 7336: sub getuploaded {
 7337:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7338:     $uri=~s/^\///;
 7339:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7340:     my $ua=new LWP::UserAgent;
 7341:     my $request=new HTTP::Request($reqtype,$uri);
 7342:     my $response=$ua->request($request);
 7343:     $$rtncode = $response->code;
 7344:     if (! $response->is_success()) {
 7345: 	return 'failed';
 7346:     }      
 7347:     if ($reqtype eq 'HEAD') {
 7348: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7349:     } elsif ($reqtype eq 'GET') {
 7350: 	$$info = $response->content;
 7351:     }
 7352:     return 'ok';
 7353: }
 7354: 
 7355: sub readfile {
 7356:     my $file = shift;
 7357:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7358:     my $fh;
 7359:     open($fh,"<$file");
 7360:     my $a='';
 7361:     while (my $line = <$fh>) { $a .= $line; }
 7362:     return $a;
 7363: }
 7364: 
 7365: sub filelocation {
 7366:     my ($dir,$file) = @_;
 7367:     my $location;
 7368:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7369: 
 7370:     if ($file =~ m-^/adm/-) {
 7371: 	$file=~s-^/adm/wrapper/-/-;
 7372: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7373:     }
 7374:     if ($file=~m:^/~:) { # is a contruction space reference
 7375:         $location = $file;
 7376:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7377:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7378: 	# is a correct contruction space reference
 7379:         $location = $file;
 7380:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7381:         my ($udom,$uname,$filename)=
 7382:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7383:         my $home=&homeserver($uname,$udom);
 7384:         my $is_me=0;
 7385:         my @ids=&current_machine_ids();
 7386:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7387:         if ($is_me) {
 7388:   	    $location=&propath($udom,$uname).
 7389:   	      '/userfiles/'.$filename;
 7390:         } else {
 7391:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7392:   	      $udom.'/'.$uname.'/'.$filename;
 7393:         }
 7394:     } else {
 7395:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7396:         $file=~s:^/res/:/:;
 7397:         if ( !( $file =~ m:^/:) ) {
 7398:             $location = $dir. '/'.$file;
 7399:         } else {
 7400:             $location = '/home/httpd/html/res'.$file;
 7401:         }
 7402:     }
 7403:     $location=~s://+:/:g; # remove duplicate /
 7404:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7405:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7406:     return $location;
 7407: }
 7408: 
 7409: sub hreflocation {
 7410:     my ($dir,$file)=@_;
 7411:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7412: 	$file=filelocation($dir,$file);
 7413:     } elsif ($file=~m-^/adm/-) {
 7414: 	$file=~s-^/adm/wrapper/-/-;
 7415: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7416:     }
 7417:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7418: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7419:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7420: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7421:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7422: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7423: 	    -/uploaded/$1/$2/-x;
 7424:     }
 7425:     return $file;
 7426: }
 7427: 
 7428: sub current_machine_domains {
 7429:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7430: }
 7431: 
 7432: sub machine_domains {
 7433:     my ($hostname) = @_;
 7434:     my @domains;
 7435:     my %hostname = &all_hostnames();
 7436:     while( my($id, $name) = each(%hostname)) {
 7437: #	&logthis("-$id-$name-$hostname-");
 7438: 	if ($hostname eq $name) {
 7439: 	    push(@domains,&host_domain($id));
 7440: 	}
 7441:     }
 7442:     return @domains;
 7443: }
 7444: 
 7445: sub current_machine_ids {
 7446:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7447: }
 7448: 
 7449: sub machine_ids {
 7450:     my ($hostname) = @_;
 7451:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7452:     my @ids;
 7453:     my %hostname = &all_hostnames();
 7454:     while( my($id, $name) = each(%hostname)) {
 7455: #	&logthis("-$id-$name-$hostname-");
 7456: 	if ($hostname eq $name) {
 7457: 	    push(@ids,$id);
 7458: 	}
 7459:     }
 7460:     return @ids;
 7461: }
 7462: 
 7463: sub additional_machine_domains {
 7464:     my @domains;
 7465:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7466:     while( my $line = <$fh>) {
 7467:         $line =~ s/\s//g;
 7468:         push(@domains,$line);
 7469:     }
 7470:     return @domains;
 7471: }
 7472: 
 7473: sub default_login_domain {
 7474:     my $domain = $perlvar{'lonDefDomain'};
 7475:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7476:     foreach my $posdom (&current_machine_domains(),
 7477:                         &additional_machine_domains()) {
 7478:         if (lc($posdom) eq lc($testdomain)) {
 7479:             $domain=$posdom;
 7480:             last;
 7481:         }
 7482:     }
 7483:     return $domain;
 7484: }
 7485: 
 7486: # ------------------------------------------------------------- Declutters URLs
 7487: 
 7488: sub declutter {
 7489:     my $thisfn=shift;
 7490:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7491:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7492:     $thisfn=~s/^\///;
 7493:     $thisfn=~s|^adm/wrapper/||;
 7494:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7495:     $thisfn=~s/^res\///;
 7496:     $thisfn=~s/\?.+$//;
 7497:     return $thisfn;
 7498: }
 7499: 
 7500: # ------------------------------------------------------------- Clutter up URLs
 7501: 
 7502: sub clutter {
 7503:     my $thisfn='/'.&declutter(shift);
 7504:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7505:        $thisfn='/res'.$thisfn; 
 7506:     }
 7507:     if ($thisfn !~m|/adm|) {
 7508: 	if ($thisfn =~ m|/ext/|) {
 7509: 	    $thisfn='/adm/wrapper'.$thisfn;
 7510: 	} else {
 7511: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7512: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7513: 	    if ($embstyle eq 'ssi'
 7514: 		|| ($embstyle eq 'hdn')
 7515: 		|| ($embstyle eq 'rat')
 7516: 		|| ($embstyle eq 'prv')
 7517: 		|| ($embstyle eq 'ign')) {
 7518: 		#do nothing with these
 7519: 	    } elsif (($embstyle eq 'img') 
 7520: 		|| ($embstyle eq 'emb')
 7521: 		|| ($embstyle eq 'wrp')) {
 7522: 		$thisfn='/adm/wrapper'.$thisfn;
 7523: 	    } elsif ($embstyle eq 'unk'
 7524: 		     && $thisfn!~/\.(sequence|page)$/) {
 7525: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7526: 	    } else {
 7527: #		&logthis("Got a blank emb style");
 7528: 	    }
 7529: 	}
 7530:     }
 7531:     return $thisfn;
 7532: }
 7533: 
 7534: sub clutter_with_no_wrapper {
 7535:     my $uri = &clutter(shift);
 7536:     if ($uri =~ m-^/adm/-) {
 7537: 	$uri =~ s-^/adm/wrapper/-/-;
 7538: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7539:     }
 7540:     return $uri;
 7541: }
 7542: 
 7543: sub freeze_escape {
 7544:     my ($value)=@_;
 7545:     if (ref($value)) {
 7546: 	$value=&nfreeze($value);
 7547: 	return '__FROZEN__'.&escape($value);
 7548:     }
 7549:     return &escape($value);
 7550: }
 7551: 
 7552: 
 7553: sub thaw_unescape {
 7554:     my ($value)=@_;
 7555:     if ($value =~ /^__FROZEN__/) {
 7556: 	substr($value,0,10,undef);
 7557: 	$value=&unescape($value);
 7558: 	return &thaw($value);
 7559:     }
 7560:     return &unescape($value);
 7561: }
 7562: 
 7563: sub correct_line_ends {
 7564:     my ($result)=@_;
 7565:     $$result =~s/\r\n/\n/mg;
 7566:     $$result =~s/\r/\n/mg;
 7567: }
 7568: # ================================================================ Main Program
 7569: 
 7570: sub goodbye {
 7571:    &logthis("Starting Shut down");
 7572: #not converted to using infrastruture and probably shouldn't be
 7573:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7574: #converted
 7575: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7576:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7577: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7578: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7579: #1.1 only
 7580: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7581: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7582: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7583: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7584:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7585:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7586:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7587:    &flushcourselogs();
 7588:    &logthis("Shutting down");
 7589: }
 7590: 
 7591: BEGIN {
 7592: 
 7593: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7594:     unless ($readit) {
 7595: {
 7596:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7597:     %perlvar = (%perlvar,%{$configvars});
 7598: }
 7599: 
 7600: sub get_dns {
 7601:     my ($url,$func) = @_;
 7602:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7603:     foreach my $dns (<$config>) {
 7604: 	next if ($dns !~ /^\^(\S*)/x);
 7605: 	$dns = $1;
 7606: 	my $ua=new LWP::UserAgent;
 7607: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7608: 	my $response=$ua->request($request);
 7609: 	next if ($response->is_error());
 7610: 	my @content = split("\n",$response->content);
 7611: 	&$func(\@content);
 7612:     }
 7613:     close($config);
 7614: }
 7615: # ------------------------------------------------------------ Read domain file
 7616: {
 7617:     my $loaded;
 7618:     my %domain;
 7619: 
 7620:     sub parse_domain_tab {
 7621: 	my ($lines) = @_;
 7622: 	foreach my $line (@$lines) {
 7623: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7624: 
 7625: 	    chomp($line);
 7626: 	    my ($name,@elements) = split(/:/,$line,9);
 7627: 	    my %this_domain;
 7628: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7629: 			       'lang_def', 'city', 'longi', 'lati',
 7630: 			       'primary') {
 7631: 		$this_domain{$field} = shift(@elements);
 7632: 	    }
 7633: 	    $domain{$name} = \%this_domain;
 7634: 	    &logthis("Domain.tab: $name ".$domain{$name}{'description'} );
 7635: 	}
 7636:     }
 7637:     
 7638:     sub load_domain_tab {
 7639: 	&get_dns('/adm/dns/domain',\&parse_domain_tab);
 7640: 	my $fh;
 7641: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7642: 	    my @lines = <$fh>;
 7643: 	    &parse_domain_tab(\@lines);
 7644: 	}
 7645: 	close($fh);
 7646: 	$loaded = 1;
 7647:     }
 7648: 
 7649:     sub domain {
 7650: 	&load_domain_tab() if (!$loaded);
 7651: 
 7652: 	my ($name,$what) = @_;
 7653: 	return if ( !exists($domain{$name}) );
 7654: 
 7655: 	if (!$what) {
 7656: 	    return $domain{$name}{'description'};
 7657: 	}
 7658: 	return $domain{$name}{$what};
 7659:     }
 7660: }
 7661: 
 7662: 
 7663: # ------------------------------------------------------------- Read hosts file
 7664: {
 7665:     my %hostname;
 7666:     my %hostdom;
 7667:     my %libserv;
 7668:     my $loaded;
 7669: 
 7670:     sub parse_hosts_tab {
 7671: 	my ($file) = @_;
 7672: 	foreach my $configline (@$file) {
 7673: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7674: 	    next if ($configline =~ /^\^/);
 7675: 	    chomp($configline);
 7676: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7677: 	    $name=~s/\s//g;
 7678: 	    if ($id && $domain && $role && $name) {
 7679: 		$hostname{$id}=$name;
 7680: 		$hostdom{$id}=$domain;
 7681: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7682: 	    }
 7683: 	    &logthis("Hosts.tab: $name ".$id );
 7684: 	}
 7685:     }
 7686: 
 7687:     sub load_hosts_tab {
 7688: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab);
 7689: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7690: 	my @config = <$config>;
 7691: 	&parse_hosts_tab(\@config);
 7692: 	close($config);
 7693: 	$loaded=1;
 7694:     }
 7695: 
 7696:     # FIXME: dev server don't want this, production servers _do_ want this
 7697:     #&get_iphost();
 7698: 
 7699:     sub hostname {
 7700: 	&load_hosts_tab() if (!$loaded);
 7701: 
 7702: 	my ($lonid) = @_;
 7703: 	return $hostname{$lonid};
 7704:     }
 7705: 
 7706:     sub all_hostnames {
 7707: 	&load_hosts_tab() if (!$loaded);
 7708: 
 7709: 	return %hostname;
 7710:     }
 7711: 
 7712:     sub is_library {
 7713: 	&load_hosts_tab() if (!$loaded);
 7714: 
 7715: 	return exists($libserv{$_[0]});
 7716:     }
 7717: 
 7718:     sub all_library {
 7719: 	&load_hosts_tab() if (!$loaded);
 7720: 
 7721: 	return %libserv;
 7722:     }
 7723: 
 7724:     sub get_servers {
 7725: 	&load_hosts_tab() if (!$loaded);
 7726: 
 7727: 	my ($domain,$type) = @_;
 7728: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7729: 	                                          : %hostname;
 7730: 	my %result;
 7731: 	if (ref($domain) eq 'ARRAY') {
 7732: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7733: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7734: 		    $result{$host} = $hostname;
 7735: 		}
 7736: 	    }
 7737: 	} else {
 7738: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7739: 		if ($hostdom{$host} eq $domain) {
 7740: 		    $result{$host} = $hostname;
 7741: 		}
 7742: 	    }
 7743: 	}
 7744: 	return %result;
 7745:     }
 7746: 
 7747:     sub host_domain {
 7748: 	&load_hosts_tab() if (!$loaded);
 7749: 
 7750: 	my ($lonid) = @_;
 7751: 	return $hostdom{$lonid};
 7752:     }
 7753: 
 7754:     sub all_domains {
 7755: 	&load_hosts_tab() if (!$loaded);
 7756: 
 7757: 	my %seen;
 7758: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7759: 	return @uniq;
 7760:     }
 7761: }
 7762: 
 7763: { 
 7764:     my %iphost;
 7765:     my %name_to_ip;
 7766:     my %lonid_to_ip;
 7767:     sub get_hosts_from_ip {
 7768: 	my ($ip) = @_;
 7769: 	my %iphosts = &get_iphost();
 7770: 	if (ref($iphosts{$ip})) {
 7771: 	    return @{$iphosts{$ip}};
 7772: 	}
 7773: 	return;
 7774:     }
 7775: 
 7776:     sub get_host_ip {
 7777: 	my ($lonid) = @_;
 7778: 	if (exists($lonid_to_ip{$lonid})) {
 7779: 	    return $lonid_to_ip{$lonid};
 7780: 	}
 7781: 	my $name=&hostname($lonid);
 7782:    	my $ip = gethostbyname($name);
 7783: 	return if (!$ip || length($ip) ne 4);
 7784: 	$ip=inet_ntoa($ip);
 7785: 	$name_to_ip{$name}   = $ip;
 7786: 	$lonid_to_ip{$lonid} = $ip;
 7787: 	return $ip;
 7788:     }
 7789:     
 7790:     sub get_iphost {
 7791: 	if (%iphost) { return %iphost; }
 7792: 	my %hostname = &all_hostnames();
 7793: 	foreach my $id (keys(%hostname)) {
 7794: 	    my $name=$hostname{$id};
 7795: 	    my $ip;
 7796: 	    if (!exists($name_to_ip{$name})) {
 7797: 		$ip = gethostbyname($name);
 7798: 		if (!$ip || length($ip) ne 4) {
 7799: 		    &logthis("Skipping host $id name $name no IP found");
 7800: 		    next;
 7801: 		}
 7802: 		$ip=inet_ntoa($ip);
 7803: 		$name_to_ip{$name} = $ip;
 7804: 	    } else {
 7805: 		$ip = $name_to_ip{$name};
 7806: 	    }
 7807: 	    $lonid_to_ip{$id} = $ip;
 7808: 	    push(@{$iphost{$ip}},$id);
 7809: 	}
 7810: 	return %iphost;
 7811:     }
 7812: }
 7813: 
 7814: # ------------------------------------------------------ Read spare server file
 7815: {
 7816:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7817: 
 7818:     while (my $configline=<$config>) {
 7819:        chomp($configline);
 7820:        if ($configline) {
 7821: 	   my ($host,$type) = split(':',$configline,2);
 7822: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7823: 	   push(@{ $spareid{$type} }, $host);
 7824:        }
 7825:     }
 7826:     close($config);
 7827: }
 7828: # ------------------------------------------------------------ Read permissions
 7829: {
 7830:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7831: 
 7832:     while (my $configline=<$config>) {
 7833: 	chomp($configline);
 7834: 	if ($configline) {
 7835: 	    my ($role,$perm)=split(/ /,$configline);
 7836: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7837: 	}
 7838:     }
 7839:     close($config);
 7840: }
 7841: 
 7842: # -------------------------------------------- Read plain texts for permissions
 7843: {
 7844:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7845: 
 7846:     while (my $configline=<$config>) {
 7847: 	chomp($configline);
 7848: 	if ($configline) {
 7849: 	    my ($short,@plain)=split(/:/,$configline);
 7850:             %{$prp{$short}} = ();
 7851: 	    if (@plain > 0) {
 7852:                 $prp{$short}{'std'} = $plain[0];
 7853:                 for (my $i=1; $i<@plain; $i++) {
 7854:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7855:                 }
 7856:             }
 7857: 	}
 7858:     }
 7859:     close($config);
 7860: }
 7861: 
 7862: # ---------------------------------------------------------- Read package table
 7863: {
 7864:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7865: 
 7866:     while (my $configline=<$config>) {
 7867: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7868: 	chomp($configline);
 7869: 	my ($short,$plain)=split(/:/,$configline);
 7870: 	my ($pack,$name)=split(/\&/,$short);
 7871: 	if ($plain ne '') {
 7872: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7873: 	    $packagetab{$short}=$plain; 
 7874: 	}
 7875:     }
 7876:     close($config);
 7877: }
 7878: 
 7879: # ------------- set up temporary directory
 7880: {
 7881:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7882: 
 7883: }
 7884: 
 7885: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7886: 				'compress_threshold'=> 20_000,
 7887:  			        });
 7888: 
 7889: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7890: $dumpcount=0;
 7891: 
 7892: &logtouch();
 7893: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7894: $readit=1;
 7895:     {
 7896: 	use integer;
 7897: 	my $test=(2**32)+1;
 7898: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7899: 	&logthis(" Detected 64bit platform ($_64bit)");
 7900:     }
 7901: }
 7902: }
 7903: 
 7904: 1;
 7905: __END__
 7906: 
 7907: =pod
 7908: 
 7909: =head1 NAME
 7910: 
 7911: Apache::lonnet - Subroutines to ask questions about things in the network.
 7912: 
 7913: =head1 SYNOPSIS
 7914: 
 7915: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7916: 
 7917:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7918: 
 7919: Common parameters:
 7920: 
 7921: =over 4
 7922: 
 7923: =item *
 7924: 
 7925: $uname : an internal username (if $cname expecting a course Id specifically)
 7926: 
 7927: =item *
 7928: 
 7929: $udom : a domain (if $cdom expecting a course's domain specifically)
 7930: 
 7931: =item *
 7932: 
 7933: $symb : a resource instance identifier
 7934: 
 7935: =item *
 7936: 
 7937: $namespace : the name of a .db file that contains the data needed or
 7938: being set.
 7939: 
 7940: =back
 7941: 
 7942: =head1 OVERVIEW
 7943: 
 7944: lonnet provides subroutines which interact with the
 7945: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7946: about classes, users, and resources.
 7947: 
 7948: For many of these objects you can also use this to store data about
 7949: them or modify them in various ways.
 7950: 
 7951: =head2 Symbs
 7952: 
 7953: To identify a specific instance of a resource, LON-CAPA uses symbols
 7954: or "symbs"X<symb>. These identifiers are built from the URL of the
 7955: map, the resource number of the resource in the map, and the URL of
 7956: the resource itself. The latter is somewhat redundant, but might help
 7957: if maps change.
 7958: 
 7959: An example is
 7960: 
 7961:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7962: 
 7963: The respective map entry is
 7964: 
 7965:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7966:   title="Problem 2">
 7967:  </resource>
 7968: 
 7969: Symbs are used by the random number generator, as well as to store and
 7970: restore data specific to a certain instance of for example a problem.
 7971: 
 7972: =head2 Storing And Retrieving Data
 7973: 
 7974: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7975: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7976: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7977: is is the non-critical message twin of cstore. These functions are for
 7978: handlers to store a perl hash to a user's permanent data space in an
 7979: easy manner, and to retrieve it again on another call. It is expected
 7980: that a handler would use this once at the beginning to retrieve data,
 7981: and then again once at the end to send only the new data back.
 7982: 
 7983: The data is stored in the user's data directory on the user's
 7984: homeserver under the ID of the course.
 7985: 
 7986: The hash that is returned by restore will have all of the previous
 7987: value for all of the elements of the hash.
 7988: 
 7989: Example:
 7990: 
 7991:  #creating a hash
 7992:  my %hash;
 7993:  $hash{'foo'}='bar';
 7994: 
 7995:  #storing it
 7996:  &Apache::lonnet::cstore(\%hash);
 7997: 
 7998:  #changing a value
 7999:  $hash{'foo'}='notbar';
 8000: 
 8001:  #adding a new value
 8002:  $hash{'bar'}='foo';
 8003:  &Apache::lonnet::cstore(\%hash);
 8004: 
 8005:  #retrieving the hash
 8006:  my %history=&Apache::lonnet::restore();
 8007: 
 8008:  #print the hash
 8009:  foreach my $key (sort(keys(%history))) {
 8010:    print("\%history{$key} = $history{$key}");
 8011:  }
 8012: 
 8013: Will print out:
 8014: 
 8015:  %history{1:foo} = bar
 8016:  %history{1:keys} = foo:timestamp
 8017:  %history{1:timestamp} = 990455579
 8018:  %history{2:bar} = foo
 8019:  %history{2:foo} = notbar
 8020:  %history{2:keys} = foo:bar:timestamp
 8021:  %history{2:timestamp} = 990455580
 8022:  %history{bar} = foo
 8023:  %history{foo} = notbar
 8024:  %history{timestamp} = 990455580
 8025:  %history{version} = 2
 8026: 
 8027: Note that the special hash entries C<keys>, C<version> and
 8028: C<timestamp> were added to the hash. C<version> will be equal to the
 8029: total number of versions of the data that have been stored. The
 8030: C<timestamp> attribute will be the UNIX time the hash was
 8031: stored. C<keys> is available in every historical section to list which
 8032: keys were added or changed at a specific historical revision of a
 8033: hash.
 8034: 
 8035: B<Warning>: do not store the hash that restore returns directly. This
 8036: will cause a mess since it will restore the historical keys as if the
 8037: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8038: 
 8039: Calling convention:
 8040: 
 8041:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8042:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8043: 
 8044: For more detailed information, see lonnet specific documentation.
 8045: 
 8046: =head1 RETURN MESSAGES
 8047: 
 8048: =over 4
 8049: 
 8050: =item * B<con_lost>: unable to contact remote host
 8051: 
 8052: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8053: when the connection is brought back up
 8054: 
 8055: =item * B<con_failed>: unable to contact remote host and unable to save message
 8056: for later delivery
 8057: 
 8058: =item * B<error:>: an error a occured, a description of the error follows the :
 8059: 
 8060: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8061: that was requested
 8062: 
 8063: =back
 8064: 
 8065: =head1 PUBLIC SUBROUTINES
 8066: 
 8067: =head2 Session Environment Functions
 8068: 
 8069: =over 4
 8070: 
 8071: =item * 
 8072: X<appenv()>
 8073: B<appenv(%hash)>: the value of %hash is written to
 8074: the user envirnoment file, and will be restored for each access this
 8075: user makes during this session, also modifies the %env for the current
 8076: process
 8077: 
 8078: =item *
 8079: X<delenv()>
 8080: B<delenv($regexp)>: removes all items from the session
 8081: environment file that matches the regular expression in $regexp. The
 8082: values are also delted from the current processes %env.
 8083: 
 8084: =item * get_env_multiple($name) 
 8085: 
 8086: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8087: values may be defined and end up as an array ref.
 8088: 
 8089: returns an array of values
 8090: 
 8091: =back
 8092: 
 8093: =head2 User Information
 8094: 
 8095: =over 4
 8096: 
 8097: =item *
 8098: X<queryauthenticate()>
 8099: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8100: authentication scheme
 8101: 
 8102: =item *
 8103: X<authenticate()>
 8104: B<authenticate($uname,$upass,$udom)>: try to
 8105: authenticate user from domain's lib servers (first use the current
 8106: one). C<$upass> should be the users password.
 8107: 
 8108: =item *
 8109: X<homeserver()>
 8110: B<homeserver($uname,$udom)>: find the server which has
 8111: the user's directory and files (there must be only one), this caches
 8112: the answer, and also caches if there is a borken connection.
 8113: 
 8114: =item *
 8115: X<idget()>
 8116: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8117: (IDs are a unique resource in a domain, there must be only 1 ID per
 8118: username, and only 1 username per ID in a specific domain) (returns
 8119: hash: id=>name,id=>name)
 8120: 
 8121: =item *
 8122: X<idrget()>
 8123: B<idrget($udom,@unames)>: find the IDs behind a list of
 8124: usernames (returns hash: name=>id,name=>id)
 8125: 
 8126: =item *
 8127: X<idput()>
 8128: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8129: 
 8130: =item *
 8131: X<rolesinit()>
 8132: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8133: 
 8134: =item *
 8135: X<getsection()>
 8136: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8137: course $cname, return section name/number or '' for "not in course"
 8138: and '-1' for "no section"
 8139: 
 8140: =item *
 8141: X<userenvironment()>
 8142: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8143: passed in @what from the requested user's environment, returns a hash
 8144: 
 8145: =back
 8146: 
 8147: =head2 User Roles
 8148: 
 8149: =over 4
 8150: 
 8151: =item *
 8152: 
 8153: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8154:  F: full access
 8155:  U,I,K: authentication modes (cxx only)
 8156:  '': forbidden
 8157:  1: user needs to choose course
 8158:  2: browse allowed
 8159:  A: passphrase authentication needed
 8160: 
 8161: =item *
 8162: 
 8163: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8164: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8165: and course level
 8166: 
 8167: =item *
 8168: 
 8169: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8170: explanation of a user role term
 8171: 
 8172: =item *
 8173: 
 8174: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
 8175: optional.  Returns a hash of a user's roles, with keys set to
 8176: colon-sparated $uname,$udom,and $role, and value set to
 8177: colon-separated start and end times for the role. If no username and
 8178: domain are specified, will default to current user/domain. Types,
 8179: roles, and roledoms are references to arrays, of role statuses
 8180: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
 8181: of the roles which can be used to restrict the list if roles
 8182: reported. If no array ref is provided for types, will default to
 8183: return only active roles.
 8184: 
 8185: =back
 8186: 
 8187: =head2 User Modification
 8188: 
 8189: =over 4
 8190: 
 8191: =item *
 8192: 
 8193: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8194: user for the level given by URL.  Optional start and end dates (leave empty
 8195: string or zero for "no date")
 8196: 
 8197: =item *
 8198: 
 8199: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8200: change a users, password, possible return values are: ok,
 8201: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8202: refused
 8203: 
 8204: =item *
 8205: 
 8206: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8207: 
 8208: =item *
 8209: 
 8210: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8211: modify user
 8212: 
 8213: =item *
 8214: 
 8215: modifystudent
 8216: 
 8217: modify a students enrollment and identification information.
 8218: The course id is resolved based on the current users environment.  
 8219: This means the envoking user must be a course coordinator or otherwise
 8220: associated with a course.
 8221: 
 8222: This call is essentially a wrapper for lonnet::modifyuser and
 8223: lonnet::modify_student_enrollment
 8224: 
 8225: Inputs: 
 8226: 
 8227: =over 4
 8228: 
 8229: =item B<$udom> Students loncapa domain
 8230: 
 8231: =item B<$uname> Students loncapa login name
 8232: 
 8233: =item B<$uid> Students id/student number
 8234: 
 8235: =item B<$umode> Students authentication mode
 8236: 
 8237: =item B<$upass> Students password
 8238: 
 8239: =item B<$first> Students first name
 8240: 
 8241: =item B<$middle> Students middle name
 8242: 
 8243: =item B<$last> Students last name
 8244: 
 8245: =item B<$gene> Students generation
 8246: 
 8247: =item B<$usec> Students section in course
 8248: 
 8249: =item B<$end> Unix time of the roles expiration
 8250: 
 8251: =item B<$start> Unix time of the roles start date
 8252: 
 8253: =item B<$forceid> If defined, allow $uid to be changed
 8254: 
 8255: =item B<$desiredhome> server to use as home server for student
 8256: 
 8257: =back
 8258: 
 8259: =item *
 8260: 
 8261: modify_student_enrollment
 8262: 
 8263: Change a students enrollment status in a class.  The environment variable
 8264: 'role.request.course' must be defined for this function to proceed.
 8265: 
 8266: Inputs:
 8267: 
 8268: =over 4
 8269: 
 8270: =item $udom, students domain
 8271: 
 8272: =item $uname, students name
 8273: 
 8274: =item $uid, students user id
 8275: 
 8276: =item $first, students first name
 8277: 
 8278: =item $middle
 8279: 
 8280: =item $last
 8281: 
 8282: =item $gene
 8283: 
 8284: =item $usec
 8285: 
 8286: =item $end
 8287: 
 8288: =item $start
 8289: 
 8290: =back
 8291: 
 8292: 
 8293: =item *
 8294: 
 8295: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8296: custom role; give a custom role to a user for the level given by URL.  Specify
 8297: name and domain of role author, and role name
 8298: 
 8299: =item *
 8300: 
 8301: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8302: 
 8303: =item *
 8304: 
 8305: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8306: 
 8307: =back
 8308: 
 8309: =head2 Course Infomation
 8310: 
 8311: =over 4
 8312: 
 8313: =item *
 8314: 
 8315: coursedescription($courseid) : returns a hash of information about the
 8316: specified course id, including all environment settings for the
 8317: course, the description of the course will be in the hash under the
 8318: key 'description'
 8319: 
 8320: =item *
 8321: 
 8322: resdata($name,$domain,$type,@which) : request for current parameter
 8323: setting for a specific $type, where $type is either 'course' or 'user',
 8324: @what should be a list of parameters to ask about. This routine caches
 8325: answers for 5 minutes.
 8326: 
 8327: =back
 8328: 
 8329: =head2 Course Modification
 8330: 
 8331: =over 4
 8332: 
 8333: =item *
 8334: 
 8335: writecoursepref($courseid,%prefs) : write preferences (environment
 8336: database) for a course
 8337: 
 8338: =item *
 8339: 
 8340: createcourse($udom,$description,$url) : make/modify course
 8341: 
 8342: =back
 8343: 
 8344: =head2 Resource Subroutines
 8345: 
 8346: =over 4
 8347: 
 8348: =item *
 8349: 
 8350: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8351: 
 8352: =item *
 8353: 
 8354: repcopy($filename) : subscribes to the requested file, and attempts to
 8355: replicate from the owning library server, Might return
 8356: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8357: 'bad_request', also attempts to grab the metadata for the
 8358: resource. Expects the local filesystem pathname
 8359: (/home/httpd/html/res/....)
 8360: 
 8361: =back
 8362: 
 8363: =head2 Resource Information
 8364: 
 8365: =over 4
 8366: 
 8367: =item *
 8368: 
 8369: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8370: a vairety of different possible values, $varname should be a request
 8371: string, and the other parameters can be used to specify who and what
 8372: one is asking about.
 8373: 
 8374: Possible values for $varname are environment.lastname (or other item
 8375: from the envirnment hash), user.name (or someother aspect about the
 8376: user), resource.0.maxtries (or some other part and parameter of a
 8377: resource)
 8378: 
 8379: =item *
 8380: 
 8381: directcondval($number) : get current value of a condition; reads from a state
 8382: string
 8383: 
 8384: =item *
 8385: 
 8386: condval($condidx) : value of condition index based on state
 8387: 
 8388: =item *
 8389: 
 8390: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8391: resource's metadata, $what should be either a specific key, or either
 8392: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8393: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8394: 
 8395: this function automatically caches all requests
 8396: 
 8397: =item *
 8398: 
 8399: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8400: network of library servers; returns file handle of where SQL and regex results
 8401: will be stored for query
 8402: 
 8403: =item *
 8404: 
 8405: symbread($filename) : return symbolic list entry (filename argument optional);
 8406: returns the data handle
 8407: 
 8408: =item *
 8409: 
 8410: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8411: a possible symb for the URL in $thisfn, and if is an encryypted
 8412: resource that the user accessed using /enc/ returns a 1 on success, 0
 8413: on failure, user must be in a course, as it assumes the existance of
 8414: the course initial hash, and uses $env('request.course.id'}
 8415: 
 8416: 
 8417: =item *
 8418: 
 8419: symbclean($symb) : removes versions numbers from a symb, returns the
 8420: cleaned symb
 8421: 
 8422: =item *
 8423: 
 8424: is_on_map($uri) : checks if the $uri is somewhere on the current
 8425: course map, user must be in a course for it to work.
 8426: 
 8427: =item *
 8428: 
 8429: numval($salt) : return random seed value (addend for rndseed)
 8430: 
 8431: =item *
 8432: 
 8433: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8434: a random seed, all arguments are optional, if they aren't sent it uses the
 8435: environment to derive them. Note: if symb isn't sent and it can't get one
 8436: from &symbread it will use the current time as its return value
 8437: 
 8438: =item *
 8439: 
 8440: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8441: unfakeable, receipt
 8442: 
 8443: =item *
 8444: 
 8445: receipt() : API to ireceipt working off of env values; given out to users
 8446: 
 8447: =item *
 8448: 
 8449: countacc($url) : count the number of accesses to a given URL
 8450: 
 8451: =item *
 8452: 
 8453: 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
 8454: 
 8455: =item *
 8456: 
 8457: 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)
 8458: 
 8459: =item *
 8460: 
 8461: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8462: 
 8463: =item *
 8464: 
 8465: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8466: forcing spreadsheet to reevaluate the resource scores next time.
 8467: 
 8468: =back
 8469: 
 8470: =head2 Storing/Retreiving Data
 8471: 
 8472: =over 4
 8473: 
 8474: =item *
 8475: 
 8476: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8477: for this url; hashref needs to be given and should be a \%hashname; the
 8478: remaining args aren't required and if they aren't passed or are '' they will
 8479: be derived from the env
 8480: 
 8481: =item *
 8482: 
 8483: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8484: uses critical subroutine
 8485: 
 8486: =item *
 8487: 
 8488: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8489: all args are optional
 8490: 
 8491: =item *
 8492: 
 8493: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8494: dumps the complete (or key matching regexp) namespace into a hash
 8495: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8496: normally &store()ed into
 8497: 
 8498: $range should be either an integer '100' (give me the first 100
 8499:                                            matching records)
 8500:               or be  two integers sperated by a - with no spaces
 8501:                  '30-50' (give me the 30th through the 50th matching
 8502:                           records)
 8503: 
 8504: 
 8505: =item *
 8506: 
 8507: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8508: replaces a &store() version of data with a replacement set of data
 8509: for a particular resource in a namespace passed in the $storehash hash 
 8510: reference
 8511: 
 8512: =item *
 8513: 
 8514: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8515: works very similar to store/cstore, but all data is stored in a
 8516: temporary location and can be reset using tmpreset, $storehash should
 8517: be a hash reference, returns nothing on success
 8518: 
 8519: =item *
 8520: 
 8521: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8522: similar to restore, but all data is stored in a temporary location and
 8523: can be reset using tmpreset. Returns a hash of values on success,
 8524: error string otherwise.
 8525: 
 8526: =item *
 8527: 
 8528: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8529: deltes all keys for $symb form the temporary storage hash.
 8530: 
 8531: =item *
 8532: 
 8533: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8534: reference filled in from namesp ($udom and $uname are optional)
 8535: 
 8536: =item *
 8537: 
 8538: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8539: namesp ($udom and $uname are optional)
 8540: 
 8541: =item *
 8542: 
 8543: dump($namespace,$udom,$uname,$regexp,$range) : 
 8544: dumps the complete (or key matching regexp) namespace into a hash
 8545: ($udom, $uname, $regexp, $range are optional)
 8546: 
 8547: $range should be either an integer '100' (give me the first 100
 8548:                                            matching records)
 8549:               or be  two integers sperated by a - with no spaces
 8550:                  '30-50' (give me the 30th through the 50th matching
 8551:                           records)
 8552: =item *
 8553: 
 8554: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8555: $store can be a scalar, an array reference, or if the amount to be 
 8556: incremented is > 1, a hash reference.
 8557: 
 8558: ($udom and $uname are optional)
 8559: 
 8560: =item *
 8561: 
 8562: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8563: ($udom and $uname are optional)
 8564: 
 8565: =item *
 8566: 
 8567: cput($namespace,$storehash,$udom,$uname) : critical put
 8568: ($udom and $uname are optional)
 8569: 
 8570: =item *
 8571: 
 8572: newput($namespace,$storehash,$udom,$uname) :
 8573: 
 8574: Attempts to store the items in the $storehash, but only if they don't
 8575: currently exist, if this succeeds you can be certain that you have 
 8576: successfully created a new key value pair in the $namespace db.
 8577: 
 8578: 
 8579: Args:
 8580:  $namespace: name of database to store values to
 8581:  $storehash: hashref to store to the db
 8582:  $udom: (optional) domain of user containing the db
 8583:  $uname: (optional) name of user caontaining the db
 8584: 
 8585: Returns:
 8586:  'ok' -> succeeded in storing all keys of $storehash
 8587:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8588:                         least <key> already existed in the db (other
 8589:                         requested keys may also already exist)
 8590:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8591:  'con_lost' -> unable to contact request server
 8592:  'refused' -> action was not allowed by remote machine
 8593: 
 8594: 
 8595: =item *
 8596: 
 8597: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8598: reference filled in from namesp (encrypts the return communication)
 8599: ($udom and $uname are optional)
 8600: 
 8601: =item *
 8602: 
 8603: log($udom,$name,$home,$message) : write to permanent log for user; use
 8604: critical subroutine
 8605: 
 8606: =item *
 8607: 
 8608: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
 8609: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
 8610: 
 8611: =item *
 8612: 
 8613: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
 8614: 
 8615: =back
 8616: 
 8617: =head2 Network Status Functions
 8618: 
 8619: =over 4
 8620: 
 8621: =item *
 8622: 
 8623: dirlist($uri) : return directory list based on URI
 8624: 
 8625: =item *
 8626: 
 8627: spareserver() : find server with least workload from spare.tab
 8628: 
 8629: =back
 8630: 
 8631: =head2 Apache Request
 8632: 
 8633: =over 4
 8634: 
 8635: =item *
 8636: 
 8637: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8638: localhost, posts hash
 8639: 
 8640: =back
 8641: 
 8642: =head2 Data to String to Data
 8643: 
 8644: =over 4
 8645: 
 8646: =item *
 8647: 
 8648: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8649: and '&' separators, supports elements that are arrayrefs and hashrefs
 8650: 
 8651: =item *
 8652: 
 8653: hashref2str($hashref) : convert a hashref into a string complete with
 8654: escaping and '=' and '&' separators, supports elements that are
 8655: arrayrefs and hashrefs
 8656: 
 8657: =item *
 8658: 
 8659: arrayref2str($arrayref) : convert an arrayref into a string complete
 8660: with escaping and '&' separators, supports elements that are arrayrefs
 8661: and hashrefs
 8662: 
 8663: =item *
 8664: 
 8665: str2hash($string) : convert string to hash using unescaping and
 8666: splitting on '=' and '&', supports elements that are arrayrefs and
 8667: hashrefs
 8668: 
 8669: =item *
 8670: 
 8671: str2array($string) : convert string to hash using unescaping and
 8672: splitting on '&', supports elements that are arrayrefs and hashrefs
 8673: 
 8674: =back
 8675: 
 8676: =head2 Logging Routines
 8677: 
 8678: =over 4
 8679: 
 8680: These routines allow one to make log messages in the lonnet.log and
 8681: lonnet.perm logfiles.
 8682: 
 8683: =item *
 8684: 
 8685: logtouch() : make sure the logfile, lonnet.log, exists
 8686: 
 8687: =item *
 8688: 
 8689: logthis() : append message to the normal lonnet.log file, it gets
 8690: preiodically rolled over and deleted.
 8691: 
 8692: =item *
 8693: 
 8694: logperm() : append a permanent message to lonnet.perm.log, this log
 8695: file never gets deleted by any automated portion of the system, only
 8696: messages of critical importance should go in here.
 8697: 
 8698: =back
 8699: 
 8700: =head2 General File Helper Routines
 8701: 
 8702: =over 4
 8703: 
 8704: =item *
 8705: 
 8706: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8707: (a) files in /uploaded
 8708:   (i) If a local copy of the file exists - 
 8709:       compares modification date of local copy with last-modified date for 
 8710:       definitive version stored on home server for course. If local copy is 
 8711:       stale, requests a new version from the home server and stores it. 
 8712:       If the original has been removed from the home server, then local copy 
 8713:       is unlinked.
 8714:   (ii) If local copy does not exist -
 8715:       requests the file from the home server and stores it. 
 8716:   
 8717:   If $caller is 'uploadrep':  
 8718:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8719:     for request for files originally uploaded via DOCS. 
 8720:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8721:   
 8722:   Otherwise:
 8723:      This indicates a call from the content generation phase of the request.
 8724:      -  returns the entire contents of the file or -1.
 8725:      
 8726: (b) files in /res
 8727:    - returns the entire contents of a file or -1; 
 8728:    it properly subscribes to and replicates the file if neccessary.
 8729: 
 8730: 
 8731: =item *
 8732: 
 8733: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8734:                   reference
 8735: 
 8736: returns either a stat() list of data about the file or an empty list
 8737: if the file doesn't exist or couldn't find out about it (connection
 8738: problems or user unknown)
 8739: 
 8740: =item *
 8741: 
 8742: filelocation($dir,$file) : returns file system location of a file
 8743: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8744: directory that relative $file lookups are to looked in ($dir of /a/dir
 8745: and a file of ../bob will become /a/bob)
 8746: 
 8747: =item *
 8748: 
 8749: hreflocation($dir,$file) : returns file system location or a URL; same as
 8750: filelocation except for hrefs
 8751: 
 8752: =item *
 8753: 
 8754: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8755: 
 8756: =back
 8757: 
 8758: =head2 Usererfile file routines (/uploaded*)
 8759: 
 8760: =over 4
 8761: 
 8762: =item *
 8763: 
 8764: userfileupload(): main rotine for putting a file in a user or course's
 8765:                   filespace, arguments are,
 8766: 
 8767:  formname - required - this is the name of the element in $env where the
 8768:            filename, and the contents of the file to create/modifed exist
 8769:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8770:            contents of the file is located in $env{'form.'.$formname}
 8771:  coursedoc - if true, store the file in the course of the active role
 8772:              of the current user
 8773:  subdir - required - subdirectory to put the file in under ../userfiles/
 8774:          if undefined, it will be placed in "unknown"
 8775: 
 8776:  (This routine calls clean_filename() to remove any dangerous
 8777:  characters from the filename, and then calls finuserfileupload() to
 8778:  complete the transaction)
 8779: 
 8780:  returns either the url of the uploaded file (/uploaded/....) if successful
 8781:  and /adm/notfound.html if unsuccessful
 8782: 
 8783: =item *
 8784: 
 8785: clean_filename(): routine for cleaing a filename up for storage in
 8786:                  userfile space, argument is:
 8787: 
 8788:  filename - proposed filename
 8789: 
 8790: returns: the new clean filename
 8791: 
 8792: =item *
 8793: 
 8794: finishuserfileupload(): routine that creaes and sends the file to
 8795: userspace, probably shouldn't be called directly
 8796: 
 8797:   docuname: username or courseid of destination for the file
 8798:   docudom: domain of user/course of destination for the file
 8799:   formname: same as for userfileupload()
 8800:   fname: filename (inculding subdirectories) for the file
 8801: 
 8802:  returns either the url of the uploaded file (/uploaded/....) if successful
 8803:  and /adm/notfound.html if unsuccessful
 8804: 
 8805: =item *
 8806: 
 8807: renameuserfile(): renames an existing userfile to a new name
 8808: 
 8809:   Args:
 8810:    docuname: username or courseid of destination for the file
 8811:    docudom: domain of user/course of destination for the file
 8812:    old: current file name (including any subdirs under userfiles)
 8813:    new: desired file name (including any subdirs under userfiles)
 8814: 
 8815: =item *
 8816: 
 8817: mkdiruserfile(): creates a directory is a userfiles dir
 8818: 
 8819:   Args:
 8820:    docuname: username or courseid of destination for the file
 8821:    docudom: domain of user/course of destination for the file
 8822:    dir: dir to create (including any subdirs under userfiles)
 8823: 
 8824: =item *
 8825: 
 8826: removeuserfile(): removes a file that exists in userfiles
 8827: 
 8828:   Args:
 8829:    docuname: username or courseid of destination for the file
 8830:    docudom: domain of user/course of destination for the file
 8831:    fname: filname to delete (including any subdirs under userfiles)
 8832: 
 8833: =item *
 8834: 
 8835: removeuploadedurl(): convience function for removeuserfile()
 8836: 
 8837:   Args:
 8838:    url:  a full /uploaded/... url to delete
 8839: 
 8840: =item * 
 8841: 
 8842: get_portfile_permissions():
 8843:   Args:
 8844:     domain: domain of user or course contain the portfolio files
 8845:     user: name of user or num of course contain the portfolio files
 8846:   Returns:
 8847:     hashref of a dump of the proper file_permissions.db
 8848:    
 8849: 
 8850: =item * 
 8851: 
 8852: get_access_controls():
 8853: 
 8854: Args:
 8855:   current_permissions: the hash ref returned from get_portfile_permissions()
 8856:   group: (optional) the group you want the files associated with
 8857:   file: (optional) the file you want access info on
 8858: 
 8859: Returns:
 8860:     a hash (keys are file names) of hashes containing
 8861:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8862:         values are XML containing access control settings (see below) 
 8863: 
 8864: Internal notes:
 8865: 
 8866:  access controls are stored in file_permissions.db as key=value pairs.
 8867:     key -> path to file/file_name\0uniqueID:scope_end_start
 8868:         where scope -> public,guest,course,group,domains or users.
 8869:               end -> UNIX time for end of access (0 -> no end date)
 8870:               start -> UNIX time for start of access
 8871: 
 8872:     value -> XML description of access control
 8873:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8874:             <start></start>
 8875:             <end></end>
 8876: 
 8877:             <password></password>  for scope type = guest
 8878: 
 8879:             <domain></domain>     for scope type = course or group
 8880:             <number></number>
 8881:             <roles id="">
 8882:              <role></role>
 8883:              <access></access>
 8884:              <section></section>
 8885:              <group></group>
 8886:             </roles>
 8887: 
 8888:             <dom></dom>         for scope type = domains
 8889: 
 8890:             <users>             for scope type = users
 8891:              <user>
 8892:               <uname></uname>
 8893:               <udom></udom>
 8894:              </user>
 8895:             </users>
 8896:            </scope> 
 8897:               
 8898:  Access data is also aggregated for each file in an additional key=value pair:
 8899:  key -> path to file/file_name\0accesscontrol 
 8900:  value -> reference to hash
 8901:           hash contains key = value pairs
 8902:           where key = uniqueID:scope_end_start
 8903:                 value = UNIX time record was last updated
 8904: 
 8905:           Used to improve speed of look-ups of access controls for each file.  
 8906:  
 8907:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8908: 
 8909: modify_access_controls():
 8910: 
 8911: Modifies access controls for a portfolio file
 8912: Args
 8913: 1. file name
 8914: 2. reference to hash of required changes,
 8915: 3. domain
 8916: 4. username
 8917:   where domain,username are the domain of the portfolio owner 
 8918:   (either a user or a course) 
 8919: 
 8920: Returns:
 8921: 1. result of additions or updates ('ok' or 'error', with error message). 
 8922: 2. result of deletions ('ok' or 'error', with error message).
 8923: 3. reference to hash of any new or updated access controls.
 8924: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8925:    key = integer (inbound ID)
 8926:    value = uniqueID  
 8927: 
 8928: =back
 8929: 
 8930: =head2 HTTP Helper Routines
 8931: 
 8932: =over 4
 8933: 
 8934: =item *
 8935: 
 8936: escape() : unpack non-word characters into CGI-compatible hex codes
 8937: 
 8938: =item *
 8939: 
 8940: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8941: 
 8942: =back
 8943: 
 8944: =head1 PRIVATE SUBROUTINES
 8945: 
 8946: =head2 Underlying communication routines (Shouldn't call)
 8947: 
 8948: =over 4
 8949: 
 8950: =item *
 8951: 
 8952: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8953: 
 8954: =item *
 8955: 
 8956: reply() : uses subreply to send a message to remote machine, logs all failures
 8957: 
 8958: =item *
 8959: 
 8960: critical() : passes a critical message to another server; if cannot
 8961: get through then place message in connection buffer directory and
 8962: returns con_delayed, if incapable of saving message, returns
 8963: con_failed
 8964: 
 8965: =item *
 8966: 
 8967: reconlonc() : tries to reconnect lonc client processes.
 8968: 
 8969: =back
 8970: 
 8971: =head2 Resource Access Logging
 8972: 
 8973: =over 4
 8974: 
 8975: =item *
 8976: 
 8977: flushcourselogs() : flush (save) buffer logs and access logs
 8978: 
 8979: =item *
 8980: 
 8981: courselog($what) : save message for course in hash
 8982: 
 8983: =item *
 8984: 
 8985: courseacclog($what) : save message for course using &courselog().  Perform
 8986: special processing for specific resource types (problems, exams, quizzes, etc).
 8987: 
 8988: =item *
 8989: 
 8990: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8991: as a PerlChildExitHandler
 8992: 
 8993: =back
 8994: 
 8995: =head2 Other
 8996: 
 8997: =over 4
 8998: 
 8999: =item *
 9000: 
 9001: symblist($mapname,%newhash) : update symbolic storage links
 9002: 
 9003: =back
 9004: 
 9005: =cut

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