File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.802: download - view: text, annotated - select for diffs
Fri Nov 10 02:04:31 2006 UTC (17 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Modify tmpput handler in lond to use md5_hash of random items when creating token for password resets to provide less deterministic token.

Add an extra argument to lonnet::tmpput() so context is included when request sent to lond (if context argument was supplied).  It appears some uses of lond::tmpput make use of the number_IP_number structure of current token.

Add Forgot Password link to log-in page.

Some wording changes in reset password page.

More comprehensive check of e-mail for valid format.

Require user to provide e-mail address when requesting password change, and compare with e-mail in record associated with LON-CAPA user account.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.802 2006/11/10 02:04:31 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati %domain_primary
   44:    $tmpdir $_64bit %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use HTML::LCParser;
   49: use HTML::Parser;
   50: use Fcntl qw(:flock);
   51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   52: use Time::HiRes qw( gettimeofday tv_interval );
   53: use Cache::Memcached;
   54: use Digest::MD5;
   55: use Math::Random;
   56: use lib '/home/httpd/lib/perl';
   57: use LONCAPA;
   58: use LONCAPA::Configuration;
   59: 
   60: my $readit;
   61: my $max_connection_retries = 10;     # Or some such value.
   62: 
   63: require Exporter;
   64: 
   65: our @ISA = qw (Exporter);
   66: our @EXPORT = qw(%env);
   67: 
   68: =pod
   69: 
   70: =head1 Package Variables
   71: 
   72: These are largely undocumented, so if you decipher one please note it here.
   73: 
   74: =over 4
   75: 
   76: =item $processmarker
   77: 
   78: Contains the time this process was started and this servers host id.
   79: 
   80: =item $dumpcount
   81: 
   82: Counts the number of times a message log flush has been attempted (regardless
   83: of success) by this process.  Used as part of the filename when messages are
   84: delayed.
   85: 
   86: =back
   87: 
   88: =cut
   89: 
   90: 
   91: # --------------------------------------------------------------------- Logging
   92: {
   93:     my $logid;
   94:     sub instructor_log {
   95: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   96: 	$logid++;
   97: 	my $id=time().'00000'.$$.'00000'.$logid;
   98: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   99: 				    { $id => {
  100: 					'exe_uname' => $env{'user.name'},
  101: 					'exe_udom'  => $env{'user.domain'},
  102: 					'exe_time'  => time(),
  103: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  104: 					'delflag'   => $delflag,
  105: 					'logentry'  => $storehash,
  106: 					'uname'     => $uname,
  107: 					'udom'      => $udom,
  108: 				    }
  109: 				  },
  110: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  111: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  112: 				    );
  113:     }
  114: }
  115: 
  116: sub logtouch {
  117:     my $execdir=$perlvar{'lonDaemons'};
  118:     unless (-e "$execdir/logs/lonnet.log") {	
  119: 	open(my $fh,">>$execdir/logs/lonnet.log");
  120: 	close $fh;
  121:     }
  122:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  123:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  124: }
  125: 
  126: sub logthis {
  127:     my $message=shift;
  128:     my $execdir=$perlvar{'lonDaemons'};
  129:     my $now=time;
  130:     my $local=localtime($now);
  131:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  132: 	print $fh "$local ($$): $message\n";
  133: 	close($fh);
  134:     }
  135:     return 1;
  136: }
  137: 
  138: sub logperm {
  139:     my $message=shift;
  140:     my $execdir=$perlvar{'lonDaemons'};
  141:     my $now=time;
  142:     my $local=localtime($now);
  143:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  144: 	print $fh "$now:$message:$local\n";
  145: 	close($fh);
  146:     }
  147:     return 1;
  148: }
  149: 
  150: # -------------------------------------------------- Non-critical communication
  151: sub subreply {
  152:     my ($cmd,$server)=@_;
  153:     my $peerfile="$perlvar{'lonSockDir'}/".$hostname{$server};
  154:     #
  155:     #  With loncnew process trimming, there's a timing hole between lonc server
  156:     #  process exit and the master server picking up the listen on the AF_UNIX
  157:     #  socket.  In that time interval, a lock file will exist:
  158: 
  159:     my $lockfile=$peerfile.".lock";
  160:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  161: 	sleep(1);
  162:     }
  163:     # At this point, either a loncnew parent is listening or an old lonc
  164:     # or loncnew child is listening so we can connect or everything's dead.
  165:     #
  166:     #   We'll give the connection a few tries before abandoning it.  If
  167:     #   connection is not possible, we'll con_lost back to the client.
  168:     #   
  169:     my $client;
  170:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  171: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  172: 				      Type    => SOCK_STREAM,
  173: 				      Timeout => 10);
  174: 	if($client) {
  175: 	    last;		# Connected!
  176: 	}
  177: 	sleep(1);		# Try again later if failed connection.
  178:     }
  179:     my $answer;
  180:     if ($client) {
  181: 	print $client "sethost:$server:$cmd\n";
  182: 	$answer=<$client>;
  183: 	if (!$answer) { $answer="con_lost"; }
  184: 	chomp($answer);
  185:     } else {
  186: 	$answer = 'con_lost';	# Failed connection.
  187:     }
  188:     return $answer;
  189: }
  190: 
  191: sub reply {
  192:     my ($cmd,$server)=@_;
  193:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  194:     my $answer=subreply($cmd,$server);
  195:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  196:        &logthis("<font color=\"blue\">WARNING:".
  197:                 " $cmd to $server returned $answer</font>");
  198:     }
  199:     return $answer;
  200: }
  201: 
  202: # ----------------------------------------------------------- Send USR1 to lonc
  203: 
  204: sub reconlonc {
  205:     my $peerfile=shift;
  206:     &logthis("Trying to reconnect for $peerfile");
  207:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  208:     if (open(my $fh,"<$loncfile")) {
  209: 	my $loncpid=<$fh>;
  210:         chomp($loncpid);
  211:         if (kill 0 => $loncpid) {
  212: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  213:             kill USR1 => $loncpid;
  214:             sleep 1;
  215:             if (-e "$peerfile") { return; }
  216:             &logthis("$peerfile still not there, give it another try");
  217:             sleep 5;
  218:             if (-e "$peerfile") { return; }
  219:             &logthis(
  220:   "<font color=\"blue\">WARNING: $peerfile still not there, giving up</font>");
  221:         } else {
  222: 	    &logthis(
  223:                "<font color=\"blue\">WARNING:".
  224:                " lonc at pid $loncpid not responding, giving up</font>");
  225:         }
  226:     } else {
  227:      &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  228:     }
  229: }
  230: 
  231: # ------------------------------------------------------ Critical communication
  232: 
  233: sub critical {
  234:     my ($cmd,$server)=@_;
  235:     unless ($hostname{$server}) {
  236:         &logthis("<font color=\"blue\">WARNING:".
  237:                " Critical message to unknown server ($server)</font>");
  238:         return 'no_such_host';
  239:     }
  240:     my $answer=reply($cmd,$server);
  241:     if ($answer eq 'con_lost') {
  242: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  243: 	my $answer=reply($cmd,$server);
  244:         if ($answer eq 'con_lost') {
  245:             my $now=time;
  246:             my $middlename=$cmd;
  247:             $middlename=substr($middlename,0,16);
  248:             $middlename=~s/\W//g;
  249:             my $dfilename=
  250:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  251:             $dumpcount++;
  252:             {
  253: 		my $dfh;
  254: 		if (open($dfh,">$dfilename")) {
  255: 		    print $dfh "$cmd\n"; 
  256: 		    close($dfh);
  257: 		}
  258:             }
  259:             sleep 2;
  260:             my $wcmd='';
  261:             {
  262: 		my $dfh;
  263: 		if (open($dfh,"<$dfilename")) {
  264: 		    $wcmd=<$dfh>; 
  265: 		    close($dfh);
  266: 		}
  267:             }
  268:             chomp($wcmd);
  269:             if ($wcmd eq $cmd) {
  270: 		&logthis("<font color=\"blue\">WARNING: ".
  271:                          "Connection buffer $dfilename: $cmd</font>");
  272:                 &logperm("D:$server:$cmd");
  273: 	        return 'con_delayed';
  274:             } else {
  275:                 &logthis("<font color=\"red\">CRITICAL:"
  276:                         ." Critical connection failed: $server $cmd</font>");
  277:                 &logperm("F:$server:$cmd");
  278:                 return 'con_failed';
  279:             }
  280:         }
  281:     }
  282:     return $answer;
  283: }
  284: 
  285: # ------------------------------------------- check if return value is an error
  286: 
  287: sub error {
  288:     my ($result) = @_;
  289:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  290: 	if ($2 == 2) { return undef; }
  291: 	return $1;
  292:     }
  293:     return undef;
  294: }
  295: 
  296: sub convert_and_load_session_env {
  297:     my ($lonidsdir,$handle)=@_;
  298:     my @profile;
  299:     {
  300: 	open(my $idf,"$lonidsdir/$handle.id");
  301: 	flock($idf,LOCK_SH);
  302: 	@profile=<$idf>;
  303: 	close($idf);
  304:     }
  305:     my %temp_env;
  306:     foreach my $line (@profile) {
  307: 	if ($line !~ m/=/) {
  308: 	    return 0;
  309: 	}
  310: 	chomp($line);
  311: 	my ($envname,$envvalue)=split(/=/,$line,2);
  312: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  313:     }
  314:     unlink("$lonidsdir/$handle.id");
  315:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  316: 	    0640)) {
  317: 	%disk_env = %temp_env;
  318: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  319: 	untie(%disk_env);
  320:     }
  321:     return 1;
  322: }
  323: 
  324: # ------------------------------------------- Transfer profile into environment
  325: my $env_loaded;
  326: sub transfer_profile_to_env {
  327:     my ($lonidsdir,$handle,$force_transfer) = @_;
  328:     if (!$force_transfer && $env_loaded) { return; } 
  329: 
  330:     if (!defined($lonidsdir)) {
  331: 	$lonidsdir = $perlvar{'lonIDsDir'};
  332:     }
  333:     if (!defined($handle)) {
  334:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  335:     }
  336: 
  337:     my $convert;
  338:     {
  339:     	open(my $idf,"$lonidsdir/$handle.id");
  340: 	flock($idf,LOCK_SH);
  341: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  342: 		&GDBM_READER(),0640)) {
  343: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  344: 	    untie(%disk_env);
  345: 	} else {
  346: 	    $convert = 1;
  347: 	}
  348:     }
  349:     if ($convert) {
  350: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  351: 	    &logthis("Failed to load session, or convert session.");
  352: 	}
  353:     }
  354: 
  355:     my %remove;
  356:     while ( my $envname = each(%env) ) {
  357:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  358:             if ($time < time-300) {
  359:                 $remove{$key}++;
  360:             }
  361:         }
  362:     }
  363: 
  364:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  365:     $env_loaded=1;
  366:     foreach my $expired_key (keys(%remove)) {
  367:         &delenv($expired_key);
  368:     }
  369: }
  370: 
  371: # ---------------------------------------------------------- Append Environment
  372: 
  373: sub appenv {
  374:     my %newenv=@_;
  375:     foreach my $key (keys(%newenv)) {
  376: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  377:             &logthis("<font color=\"blue\">WARNING: ".
  378:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  379:                 .'</font>');
  380: 	    delete($newenv{$key});
  381:         } else {
  382:             $env{$key}=$newenv{$key};
  383:         }
  384:     }
  385:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
  386: 	    0640)) {
  387: 	while (my ($key,$value) = each(%newenv)) {
  388: 	    $disk_env{$key} = $value;
  389: 	}
  390: 	untie(%disk_env);
  391:     }
  392:     return 'ok';
  393: }
  394: # ----------------------------------------------------- Delete from Environment
  395: 
  396: sub delenv {
  397:     my $delthis=shift;
  398:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  399:         &logthis("<font color=\"blue\">WARNING: ".
  400:                 "Attempt to delete from environment ".$delthis);
  401:         return 'error';
  402:     }
  403:     if (tie(my %disk_env,'GDBM_File',$env{'user.environment'},&GDBM_WRITER(),
  404: 	    0640)) {
  405: 	foreach my $key (keys(%disk_env)) {
  406: 	    if ($key=~/^$delthis/) { 
  407:                 delete($env{$key});
  408:                 delete($disk_env{$key});
  409:             }
  410: 	}
  411: 	untie(%disk_env);
  412:     }
  413:     return 'ok';
  414: }
  415: 
  416: sub get_env_multiple {
  417:     my ($name) = @_;
  418:     my @values;
  419:     if (defined($env{$name})) {
  420:         # exists is it an array
  421:         if (ref($env{$name})) {
  422:             @values=@{ $env{$name} };
  423:         } else {
  424:             $values[0]=$env{$name};
  425:         }
  426:     }
  427:     return(@values);
  428: }
  429: 
  430: # ------------------------------------------ Find out current server userload
  431: # there is a copy in lond
  432: sub userload {
  433:     my $numusers=0;
  434:     {
  435: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  436: 	my $filename;
  437: 	my $curtime=time;
  438: 	while ($filename=readdir(LONIDS)) {
  439: 	    if ($filename eq '.' || $filename eq '..') {next;}
  440: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  441: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  442: 	}
  443: 	closedir(LONIDS);
  444:     }
  445:     my $userloadpercent=0;
  446:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  447:     if ($maxuserload) {
  448: 	$userloadpercent=100*$numusers/$maxuserload;
  449:     }
  450:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  451:     return $userloadpercent;
  452: }
  453: 
  454: # ------------------------------------------ Fight off request when overloaded
  455: 
  456: sub overloaderror {
  457:     my ($r,$checkserver)=@_;
  458:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  459:     my $loadavg;
  460:     if ($checkserver eq $perlvar{'lonHostID'}) {
  461:        open(my $loadfile,'/proc/loadavg');
  462:        $loadavg=<$loadfile>;
  463:        $loadavg =~ s/\s.*//g;
  464:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  465:        close($loadfile);
  466:     } else {
  467:        $loadavg=&reply('load',$checkserver);
  468:     }
  469:     my $overload=$loadavg-100;
  470:     if ($overload>0) {
  471: 	$r->err_headers_out->{'Retry-After'}=$overload;
  472:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  473:         return 413;
  474:     }    
  475:     return '';
  476: }
  477: 
  478: # ------------------------------ Find server with least workload from spare.tab
  479: 
  480: sub spareserver {
  481:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  482:     my $spare_server;
  483:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  484:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  485:                                                      :  $userloadpercent;
  486:     
  487:     foreach my $try_server (@{ $spareid{'primary'} }) {
  488: 	($spare_server, $lowest_load) =
  489: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  490:     }
  491: 
  492:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  493: 
  494:     if (!$found_server) {
  495: 	foreach my $try_server (@{ $spareid{'default'} }) {
  496: 	    ($spare_server, $lowest_load) =
  497: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  498: 	}
  499:     }
  500: 
  501:     if (!$want_server_name) {
  502: 	$spare_server="http://$hostname{$spare_server}";
  503:     }
  504:     return $spare_server;
  505: }
  506: 
  507: sub compare_server_load {
  508:     my ($try_server, $spare_server, $lowest_load) = @_;
  509: 
  510:     my $loadans     = &reply('load',    $try_server);
  511:     my $userloadans = &reply('userload',$try_server);
  512: 
  513:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  514: 	next; #didn't get a number from the server
  515:     }
  516: 
  517:     my $load;
  518:     if ($loadans =~ /\d/) {
  519: 	if ($userloadans =~ /\d/) {
  520: 	    #both are numbers, pick the bigger one
  521: 	    $load = ($loadans > $userloadans) ? $loadans 
  522: 		                              : $userloadans;
  523: 	} else {
  524: 	    $load = $loadans;
  525: 	}
  526:     } else {
  527: 	$load = $userloadans;
  528:     }
  529: 
  530:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  531: 	$spare_server = $try_server;
  532: 	$lowest_load  = $load;
  533:     }
  534:     return ($spare_server,$lowest_load);
  535: }
  536: # --------------------------------------------- Try to change a user's password
  537: 
  538: sub changepass {
  539:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  540:     $currentpass = &escape($currentpass);
  541:     $newpass     = &escape($newpass);
  542:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  543: 		       $server);
  544:     if (! $answer) {
  545: 	&logthis("No reply on password change request to $server ".
  546: 		 "by $uname in domain $udom.");
  547:     } elsif ($answer =~ "^ok") {
  548:         &logthis("$uname in $udom successfully changed their password ".
  549: 		 "on $server.");
  550:     } elsif ($answer =~ "^pwchange_failure") {
  551: 	&logthis("$uname in $udom was unable to change their password ".
  552: 		 "on $server.  The action was blocked by either lcpasswd ".
  553: 		 "or pwchange");
  554:     } elsif ($answer =~ "^non_authorized") {
  555:         &logthis("$uname in $udom did not get their password correct when ".
  556: 		 "attempting to change it on $server.");
  557:     } elsif ($answer =~ "^auth_mode_error") {
  558:         &logthis("$uname in $udom attempted to change their password despite ".
  559: 		 "not being locally or internally authenticated on $server.");
  560:     } elsif ($answer =~ "^unknown_user") {
  561:         &logthis("$uname in $udom attempted to change their password ".
  562: 		 "on $server but were unable to because $server is not ".
  563: 		 "their home server.");
  564:     } elsif ($answer =~ "^refused") {
  565: 	&logthis("$server refused to change $uname in $udom password because ".
  566: 		 "it was sent an unencrypted request to change the password.");
  567:     }
  568:     return $answer;
  569: }
  570: 
  571: # ----------------------- Try to determine user's current authentication scheme
  572: 
  573: sub queryauthenticate {
  574:     my ($uname,$udom)=@_;
  575:     my $uhome=&homeserver($uname,$udom);
  576:     if (!$uhome) {
  577: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  578: 	return 'no_host';
  579:     }
  580:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  581:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  582: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  583:     }
  584:     return $answer;
  585: }
  586: 
  587: # --------- Try to authenticate user from domain's lib servers (first this one)
  588: 
  589: sub authenticate {
  590:     my ($uname,$upass,$udom)=@_;
  591:     $upass=escape($upass);
  592:     $uname=~s/\W//g;
  593:     my $uhome=&homeserver($uname,$udom);
  594:     if (!$uhome) {
  595: 	&logthis("User $uname at $udom is unknown in authenticate");
  596: 	return 'no_host';
  597:     }
  598:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  599:     if ($answer eq 'authorized') {
  600: 	&logthis("User $uname at $udom authorized by $uhome"); 
  601: 	return $uhome; 
  602:     }
  603:     if ($answer eq 'non_authorized') {
  604: 	&logthis("User $uname at $udom rejected by $uhome");
  605: 	return 'no_host'; 
  606:     }
  607:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  608:     return 'no_host';
  609: }
  610: 
  611: # ---------------------- Find the homebase for a user from domain's lib servers
  612: 
  613: my %homecache;
  614: sub homeserver {
  615:     my ($uname,$udom,$ignoreBadCache)=@_;
  616:     my $index="$uname:$udom";
  617: 
  618:     if (exists($homecache{$index})) { return $homecache{$index}; }
  619:     my $tryserver;
  620:     foreach $tryserver (keys %libserv) {
  621:         next if ($ignoreBadCache ne 'true' && 
  622: 		 exists($badServerCache{$tryserver}));
  623: 	if ($hostdom{$tryserver} eq $udom) {
  624:            my $answer=reply("home:$udom:$uname",$tryserver);
  625:            if ($answer eq 'found') { 
  626: 	       return $homecache{$index}=$tryserver;
  627:            } elsif ($answer eq 'no_host') {
  628: 	       $badServerCache{$tryserver}=1;
  629:            }
  630:        }
  631:     }    
  632:     return 'no_host';
  633: }
  634: 
  635: # ------------------------------------- Find the usernames behind a list of IDs
  636: 
  637: sub idget {
  638:     my ($udom,@ids)=@_;
  639:     my %returnhash=();
  640:     
  641:     my $tryserver;
  642:     foreach $tryserver (keys %libserv) {
  643:        if ($hostdom{$tryserver} eq $udom) {
  644: 	  my $idlist=join('&',@ids);
  645:           $idlist=~tr/A-Z/a-z/; 
  646: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  647:           my @answer=();
  648:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  649: 	      @answer=split(/\&/,$reply);
  650:           }                    ;
  651:           my $i;
  652:           for ($i=0;$i<=$#ids;$i++) {
  653:               if ($answer[$i]) {
  654: 		  $returnhash{$ids[$i]}=$answer[$i];
  655:               } 
  656:           }
  657:        }
  658:     }    
  659:     return %returnhash;
  660: }
  661: 
  662: # ------------------------------------- Find the IDs behind a list of usernames
  663: 
  664: sub idrget {
  665:     my ($udom,@unames)=@_;
  666:     my %returnhash=();
  667:     foreach my $uname (@unames) {
  668:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  669:     }
  670:     return %returnhash;
  671: }
  672: 
  673: # ------------------------------- Store away a list of names and associated IDs
  674: 
  675: sub idput {
  676:     my ($udom,%ids)=@_;
  677:     my %servers=();
  678:     foreach my $uname (keys(%ids)) {
  679: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  680:         my $uhom=&homeserver($uname,$udom);
  681:         if ($uhom ne 'no_host') {
  682:             my $id=&escape($ids{$uname});
  683:             $id=~tr/A-Z/a-z/;
  684:             my $esc_unam=&escape($uname);
  685: 	    if ($servers{$uhom}) {
  686: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  687:             } else {
  688:                 $servers{$uhom}=$id.'='.$esc_unam;
  689:             }
  690:         }
  691:     }
  692:     foreach my $server (keys(%servers)) {
  693:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  694:     }
  695: }
  696: 
  697: # --------------------------------------------------- Assign a key to a student
  698: 
  699: sub assign_access_key {
  700: #
  701: # a valid key looks like uname:udom#comments
  702: # comments are being appended
  703: #
  704:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  705:     $kdom=
  706:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  707:     $knum=
  708:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  709:     $cdom=
  710:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  711:     $cnum=
  712:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  713:     $udom=$env{'user.name'} unless (defined($udom));
  714:     $uname=$env{'user.domain'} unless (defined($uname));
  715:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  716:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  717:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  718:                                                   # assigned to this person
  719:                                                   # - this should not happen,
  720:                                                   # unless something went wrong
  721:                                                   # the first time around
  722: # ready to assign
  723:         $logentry=$1.'; '.$logentry;
  724:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  725:                                                  $kdom,$knum) eq 'ok') {
  726: # key now belongs to user
  727: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  728:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  729:                 &appenv('environment.'.$envkey => $ckey);
  730:                 return 'ok';
  731:             } else {
  732:                 return 
  733:   'error: Count not permanently assign key, will need to be re-entered later.';
  734: 	    }
  735:         } else {
  736:             return 'error: Could not assign key, try again later.';
  737:         }
  738:     } elsif (!$existing{$ckey}) {
  739: # the key does not exist
  740: 	return 'error: The key does not exist';
  741:     } else {
  742: # the key is somebody else's
  743: 	return 'error: The key is already in use';
  744:     }
  745: }
  746: 
  747: # ------------------------------------------ put an additional comment on a key
  748: 
  749: sub comment_access_key {
  750: #
  751: # a valid key looks like uname:udom#comments
  752: # comments are being appended
  753: #
  754:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  755:     $cdom=
  756:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  757:     $cnum=
  758:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  759:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  760:     if ($existing{$ckey}) {
  761:         $existing{$ckey}.='; '.$logentry;
  762: # ready to assign
  763:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  764:                                                  $cdom,$cnum) eq 'ok') {
  765: 	    return 'ok';
  766:         } else {
  767: 	    return 'error: Count not store comment.';
  768:         }
  769:     } else {
  770: # the key does not exist
  771: 	return 'error: The key does not exist';
  772:     }
  773: }
  774: 
  775: # ------------------------------------------------------ Generate a set of keys
  776: 
  777: sub generate_access_keys {
  778:     my ($number,$cdom,$cnum,$logentry)=@_;
  779:     $cdom=
  780:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  781:     $cnum=
  782:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  783:     unless (&allowed('mky',$cdom)) { return 0; }
  784:     unless (($cdom) && ($cnum)) { return 0; }
  785:     if ($number>10000) { return 0; }
  786:     sleep(2); # make sure don't get same seed twice
  787:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  788:     my $total=0;
  789:     for (my $i=1;$i<=$number;$i++) {
  790:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  791:                   sprintf("%lx",int(100000*rand)).'-'.
  792:                   sprintf("%lx",int(100000*rand));
  793:        $newkey=~s/1/g/g; # folks mix up 1 and l
  794:        $newkey=~s/0/h/g; # and also 0 and O
  795:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  796:        if ($existing{$newkey}) {
  797:            $i--;
  798:        } else {
  799: 	  if (&put('accesskeys',
  800:               { $newkey => '# generated '.localtime().
  801:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  802:                            '; '.$logentry },
  803: 		   $cdom,$cnum) eq 'ok') {
  804:               $total++;
  805: 	  }
  806:        }
  807:     }
  808:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  809:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  810:     return $total;
  811: }
  812: 
  813: # ------------------------------------------------------- Validate an accesskey
  814: 
  815: sub validate_access_key {
  816:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  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.domain'} unless (defined($udom));
  822:     $uname=$env{'user.name'} unless (defined($uname));
  823:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  824:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  825: }
  826: 
  827: # ------------------------------------- Find the section of student in a course
  828: sub devalidate_getsection_cache {
  829:     my ($udom,$unam,$courseid)=@_;
  830:     $courseid=~s/\_/\//g;
  831:     $courseid=~s/^(\w)/\/$1/;
  832:     my $hashid="$udom:$unam:$courseid";
  833:     &devalidate_cache_new('getsection',$hashid);
  834: }
  835: 
  836: sub getsection {
  837:     my ($udom,$unam,$courseid)=@_;
  838:     my $cachetime=1800;
  839:     $courseid=~s/\_/\//g;
  840:     $courseid=~s/^(\w)/\/$1/;
  841: 
  842:     my $hashid="$udom:$unam:$courseid";
  843:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  844:     if (defined($cached)) { return $result; }
  845: 
  846:     my %Pending; 
  847:     my %Expired;
  848:     #
  849:     # Each role can either have not started yet (pending), be active, 
  850:     #    or have expired.
  851:     #
  852:     # If there is an active role, we are done.
  853:     #
  854:     # If there is more than one role which has not started yet, 
  855:     #     choose the one which will start sooner
  856:     # If there is one role which has not started yet, return it.
  857:     #
  858:     # If there is more than one expired role, choose the one which ended last.
  859:     # If there is a role which has expired, return it.
  860:     #
  861:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  862: 					&homeserver($unam,$udom)))) {
  863:         my ($key,$value)=split(/\=/,$line,2);
  864:         $key=&unescape($key);
  865:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  866:         my $section=$1;
  867:         if ($key eq $courseid.'_st') { $section=''; }
  868:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  869:         my $now=time;
  870:         if (defined($end) && $end && ($now > $end)) {
  871:             $Expired{$end}=$section;
  872:             next;
  873:         }
  874:         if (defined($start) && $start && ($now < $start)) {
  875:             $Pending{$start}=$section;
  876:             next;
  877:         }
  878:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  879:     }
  880:     #
  881:     # Presumedly there will be few matching roles from the above
  882:     # loop and the sorting time will be negligible.
  883:     if (scalar(keys(%Pending))) {
  884:         my ($time) = sort {$a <=> $b} keys(%Pending);
  885:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  886:     } 
  887:     if (scalar(keys(%Expired))) {
  888:         my @sorted = sort {$a <=> $b} keys(%Expired);
  889:         my $time = pop(@sorted);
  890:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  891:     }
  892:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  893: }
  894: 
  895: sub save_cache {
  896:     &purge_remembered();
  897:     #&Apache::loncommon::validate_page();
  898:     undef(%env);
  899:     undef($env_loaded);
  900: }
  901: 
  902: my $to_remember=-1;
  903: my %remembered;
  904: my %accessed;
  905: my $kicks=0;
  906: my $hits=0;
  907: sub devalidate_cache_new {
  908:     my ($name,$id,$debug) = @_;
  909:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  910:     $id=&escape($name.':'.$id);
  911:     $memcache->delete($id);
  912:     delete($remembered{$id});
  913:     delete($accessed{$id});
  914: }
  915: 
  916: sub is_cached_new {
  917:     my ($name,$id,$debug) = @_;
  918:     $id=&escape($name.':'.$id);
  919:     if (exists($remembered{$id})) {
  920: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  921: 	$accessed{$id}=[&gettimeofday()];
  922: 	$hits++;
  923: 	return ($remembered{$id},1);
  924:     }
  925:     my $value = $memcache->get($id);
  926:     if (!(defined($value))) {
  927: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  928: 	return (undef,undef);
  929:     }
  930:     if ($value eq '__undef__') {
  931: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  932: 	$value=undef;
  933:     }
  934:     &make_room($id,$value,$debug);
  935:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  936:     return ($value,1);
  937: }
  938: 
  939: sub do_cache_new {
  940:     my ($name,$id,$value,$time,$debug) = @_;
  941:     $id=&escape($name.':'.$id);
  942:     my $setvalue=$value;
  943:     if (!defined($setvalue)) {
  944: 	$setvalue='__undef__';
  945:     }
  946:     if (!defined($time) ) {
  947: 	$time=600;
  948:     }
  949:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  950:     $memcache->set($id,$setvalue,$time);
  951:     # need to make a copy of $value
  952:     #&make_room($id,$value,$debug);
  953:     return $value;
  954: }
  955: 
  956: sub make_room {
  957:     my ($id,$value,$debug)=@_;
  958:     $remembered{$id}=$value;
  959:     if ($to_remember<0) { return; }
  960:     $accessed{$id}=[&gettimeofday()];
  961:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  962:     my $to_kick;
  963:     my $max_time=0;
  964:     foreach my $other (keys(%accessed)) {
  965: 	if (&tv_interval($accessed{$other}) > $max_time) {
  966: 	    $to_kick=$other;
  967: 	    $max_time=&tv_interval($accessed{$other});
  968: 	}
  969:     }
  970:     delete($remembered{$to_kick});
  971:     delete($accessed{$to_kick});
  972:     $kicks++;
  973:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  974:     return;
  975: }
  976: 
  977: sub purge_remembered {
  978:     #&logthis("Tossing ".scalar(keys(%remembered)));
  979:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  980:     undef(%remembered);
  981:     undef(%accessed);
  982: }
  983: # ------------------------------------- Read an entry from a user's environment
  984: 
  985: sub userenvironment {
  986:     my ($udom,$unam,@what)=@_;
  987:     my %returnhash=();
  988:     my @answer=split(/\&/,
  989:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  990:                       &homeserver($unam,$udom)));
  991:     my $i;
  992:     for ($i=0;$i<=$#what;$i++) {
  993: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  994:     }
  995:     return %returnhash;
  996: }
  997: 
  998: # ---------------------------------------------------------- Get a studentphoto
  999: sub studentphoto {
 1000:     my ($udom,$unam,$ext) = @_;
 1001:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1002:     if (defined($env{'request.course.id'})) {
 1003:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1004:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1005:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1006:             } else {
 1007:                 my ($result,$perm_reqd)=
 1008: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1009:                 if ($result eq 'ok') {
 1010:                     if (!($perm_reqd eq 'yes')) {
 1011:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1012:                     }
 1013:                 }
 1014:             }
 1015:         }
 1016:     } else {
 1017:         my ($result,$perm_reqd) = 
 1018: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1019:         if ($result eq 'ok') {
 1020:             if (!($perm_reqd eq 'yes')) {
 1021:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1022:             }
 1023:         }
 1024:     }
 1025:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1026: }
 1027: 
 1028: sub retrievestudentphoto {
 1029:     my ($udom,$unam,$ext,$type) = @_;
 1030:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1031:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1032:     if ($ret eq 'ok') {
 1033:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1034:         if ($type eq 'thumbnail') {
 1035:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1036:         }
 1037:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1038:         return $tokenurl;
 1039:     } else {
 1040:         if ($type eq 'thumbnail') {
 1041:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1042:         } else { 
 1043:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1044:         }
 1045:     }
 1046: }
 1047: 
 1048: # -------------------------------------------------------------------- New chat
 1049: 
 1050: sub chatsend {
 1051:     my ($newentry,$anon,$group)=@_;
 1052:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1053:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1054:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1055:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1056: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1057: 		   &escape($newentry)).':'.$group,$chome);
 1058: }
 1059: 
 1060: # ------------------------------------------ Find current version of a resource
 1061: 
 1062: sub getversion {
 1063:     my $fname=&clutter(shift);
 1064:     unless ($fname=~/^\/res\//) { return -1; }
 1065:     return &currentversion(&filelocation('',$fname));
 1066: }
 1067: 
 1068: sub currentversion {
 1069:     my $fname=shift;
 1070:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1071:     if (defined($cached)) { return $result; }
 1072:     my $author=$fname;
 1073:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1074:     my ($udom,$uname)=split(/\//,$author);
 1075:     my $home=homeserver($uname,$udom);
 1076:     if ($home eq 'no_host') { 
 1077:         return -1; 
 1078:     }
 1079:     my $answer=reply("currentversion:$fname",$home);
 1080:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1081: 	return -1;
 1082:     }
 1083:     return &do_cache_new('resversion',$fname,$answer,600);
 1084: }
 1085: 
 1086: # ----------------------------- Subscribe to a resource, return URL if possible
 1087: 
 1088: sub subscribe {
 1089:     my $fname=shift;
 1090:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1091:     $fname=~s/[\n\r]//g;
 1092:     my $author=$fname;
 1093:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1094:     my ($udom,$uname)=split(/\//,$author);
 1095:     my $home=homeserver($uname,$udom);
 1096:     if ($home eq 'no_host') {
 1097:         return 'not_found';
 1098:     }
 1099:     my $answer=reply("sub:$fname",$home);
 1100:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1101: 	$answer.=' by '.$home;
 1102:     }
 1103:     return $answer;
 1104: }
 1105:     
 1106: # -------------------------------------------------------------- Replicate file
 1107: 
 1108: sub repcopy {
 1109:     my $filename=shift;
 1110:     $filename=~s/\/+/\//g;
 1111:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1112:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1113:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1114: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1115: 	return &repcopy_userfile($filename);
 1116:     }
 1117:     $filename=~s/[\n\r]//g;
 1118:     my $transname="$filename.in.transfer";
 1119:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1120:     my $remoteurl=subscribe($filename);
 1121:     if ($remoteurl =~ /^con_lost by/) {
 1122: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1123:            return 'unavailable';
 1124:     } elsif ($remoteurl eq 'not_found') {
 1125: 	   #&logthis("Subscribe returned not_found: $filename");
 1126: 	   return 'not_found';
 1127:     } elsif ($remoteurl =~ /^rejected by/) {
 1128: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1129:            return 'forbidden';
 1130:     } elsif ($remoteurl eq 'directory') {
 1131:            return 'ok';
 1132:     } else {
 1133:         my $author=$filename;
 1134:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1135:         my ($udom,$uname)=split(/\//,$author);
 1136:         my $home=homeserver($uname,$udom);
 1137:         unless ($home eq $perlvar{'lonHostID'}) {
 1138:            my @parts=split(/\//,$filename);
 1139:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1140:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1141:                &logthis("Malconfiguration for replication: $filename");
 1142: 	       return 'bad_request';
 1143:            }
 1144:            my $count;
 1145:            for ($count=5;$count<$#parts;$count++) {
 1146:                $path.="/$parts[$count]";
 1147:                if ((-e $path)!=1) {
 1148: 		   mkdir($path,0777);
 1149:                }
 1150:            }
 1151:            my $ua=new LWP::UserAgent;
 1152:            my $request=new HTTP::Request('GET',"$remoteurl");
 1153:            my $response=$ua->request($request,$transname);
 1154:            if ($response->is_error()) {
 1155: 	       unlink($transname);
 1156:                my $message=$response->status_line;
 1157:                &logthis("<font color=\"blue\">WARNING:"
 1158:                        ." LWP get: $message: $filename</font>");
 1159:                return 'unavailable';
 1160:            } else {
 1161: 	       if ($remoteurl!~/\.meta$/) {
 1162:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1163:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1164:                   if ($mresponse->is_error()) {
 1165: 		      unlink($filename.'.meta');
 1166:                       &logthis(
 1167:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1168:                   }
 1169: 	       }
 1170:                rename($transname,$filename);
 1171:                return 'ok';
 1172:            }
 1173:        }
 1174:     }
 1175: }
 1176: 
 1177: # ------------------------------------------------ Get server side include body
 1178: sub ssi_body {
 1179:     my ($filelink,%form)=@_;
 1180:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1181:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1182:     }
 1183:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1184:                                      &ssi($filelink,%form));
 1185:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1186:     $output=~s/^.*?\<body[^\>]*\>//si;
 1187:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1188:     return $output;
 1189: }
 1190: 
 1191: # --------------------------------------------------------- Server Side Include
 1192: 
 1193: sub absolute_url {
 1194:     my ($host_name) = @_;
 1195:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1196:     if ($host_name eq '') {
 1197: 	$host_name = $ENV{'SERVER_NAME'};
 1198:     }
 1199:     return $protocol.$host_name;
 1200: }
 1201: 
 1202: sub ssi {
 1203: 
 1204:     my ($fn,%form)=@_;
 1205: 
 1206:     my $ua=new LWP::UserAgent;
 1207:     
 1208:     my $request;
 1209: 
 1210:     $form{'no_update_last_known'}=1;
 1211: 
 1212:     if (%form) {
 1213:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1214:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1215:     } else {
 1216:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1217:     }
 1218: 
 1219:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1220:     my $response=$ua->request($request);
 1221: 
 1222:     return $response->content;
 1223: }
 1224: 
 1225: sub externalssi {
 1226:     my ($url)=@_;
 1227:     my $ua=new LWP::UserAgent;
 1228:     my $request=new HTTP::Request('GET',$url);
 1229:     my $response=$ua->request($request);
 1230:     return $response->content;
 1231: }
 1232: 
 1233: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1234: 
 1235: sub allowuploaded {
 1236:     my ($srcurl,$url)=@_;
 1237:     $url=&clutter(&declutter($url));
 1238:     my $dir=$url;
 1239:     $dir=~s/\/[^\/]+$//;
 1240:     my %httpref=();
 1241:     my $httpurl=&hreflocation('',$url);
 1242:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1243:     &Apache::lonnet::appenv(%httpref);
 1244: }
 1245: 
 1246: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1247: # input: action, courseID, current domain, intended
 1248: #        path to file, source of file, instruction to parse file for objects,
 1249: #        ref to hash for embedded objects,
 1250: #        ref to hash for codebase of java objects.
 1251: #
 1252: # output: url to file (if action was uploaddoc), 
 1253: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1254: #
 1255: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1256: # course.
 1257: #
 1258: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1259: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1260: #          course's home server.
 1261: #
 1262: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1263: #          be copied from $source (current location) to 
 1264: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1265: #         and will then be copied to
 1266: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1267: #         course's home server.
 1268: #
 1269: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1270: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1271: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1272: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1273: #         in course's home server.
 1274: #
 1275: 
 1276: sub process_coursefile {
 1277:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1278:     my $fetchresult;
 1279:     my $home=&homeserver($docuname,$docudom);
 1280:     if ($action eq 'propagate') {
 1281:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1282: 			     $home);
 1283:     } else {
 1284:         my $fpath = '';
 1285:         my $fname = $file;
 1286:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1287:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1288:         my $filepath = &build_filepath($fpath);
 1289:         if ($action eq 'copy') {
 1290:             if ($source eq '') {
 1291:                 $fetchresult = 'no source file';
 1292:                 return $fetchresult;
 1293:             } else {
 1294:                 my $destination = $filepath.'/'.$fname;
 1295:                 rename($source,$destination);
 1296:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1297:                                  $home);
 1298:             }
 1299:         } elsif ($action eq 'uploaddoc') {
 1300:             open(my $fh,'>'.$filepath.'/'.$fname);
 1301:             print $fh $env{'form.'.$source};
 1302:             close($fh);
 1303:             if ($parser eq 'parse') {
 1304:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1305:                 unless ($parse_result eq 'ok') {
 1306:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1307:                 }
 1308:             }
 1309:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1310:                                  $home);
 1311:             if ($fetchresult eq 'ok') {
 1312:                 return '/uploaded/'.$fpath.'/'.$fname;
 1313:             } else {
 1314:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1315:                         ' to host '.$home.': '.$fetchresult);
 1316:                 return '/adm/notfound.html';
 1317:             }
 1318:         }
 1319:     }
 1320:     unless ( $fetchresult eq 'ok') {
 1321:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1322:              ' to host '.$home.': '.$fetchresult);
 1323:     }
 1324:     return $fetchresult;
 1325: }
 1326: 
 1327: sub build_filepath {
 1328:     my ($fpath) = @_;
 1329:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1330:     unless ($fpath eq '') {
 1331:         my @parts=split('/',$fpath);
 1332:         foreach my $part (@parts) {
 1333:             $filepath.= '/'.$part;
 1334:             if ((-e $filepath)!=1) {
 1335:                 mkdir($filepath,0777);
 1336:             }
 1337:         }
 1338:     }
 1339:     return $filepath;
 1340: }
 1341: 
 1342: sub store_edited_file {
 1343:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1344:     my $file = $primary_url;
 1345:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1346:     my $fpath = '';
 1347:     my $fname = $file;
 1348:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1349:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1350:     my $filepath = &build_filepath($fpath);
 1351:     open(my $fh,'>'.$filepath.'/'.$fname);
 1352:     print $fh $content;
 1353:     close($fh);
 1354:     my $home=&homeserver($docuname,$docudom);
 1355:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1356: 			  $home);
 1357:     if ($$fetchresult eq 'ok') {
 1358:         return '/uploaded/'.$fpath.'/'.$fname;
 1359:     } else {
 1360:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1361: 		 ' to host '.$home.': '.$$fetchresult);
 1362:         return '/adm/notfound.html';
 1363:     }
 1364: }
 1365: 
 1366: sub clean_filename {
 1367:     my ($fname)=@_;
 1368: # Replace Windows backslashes by forward slashes
 1369:     $fname=~s/\\/\//g;
 1370: # Get rid of everything but the actual filename
 1371:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1372: # Replace spaces by underscores
 1373:     $fname=~s/\s+/\_/g;
 1374: # Replace all other weird characters by nothing
 1375:     $fname=~s/[^\w\.\-]//g;
 1376: # Replace all .\d. sequences with _\d. so they no longer look like version
 1377: # numbers
 1378:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1379:     return $fname;
 1380: }
 1381: 
 1382: # --------------- Take an uploaded file and put it into the userfiles directory
 1383: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1384: #                    the desired filenam is in $env{"form.$formname.filename"}
 1385: #        $coursedoc - if true up to the current course
 1386: #                     if false
 1387: #        $subdir - directory in userfile to store the file into
 1388: #        $parser, $allfiles, $codebase - unknown
 1389: #
 1390: # output: url of file in userspace, or error: <message> 
 1391: #             or /adm/notfound.html if failure to upload occurse
 1392: 
 1393: 
 1394: sub userfileupload {
 1395:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1396:     if (!defined($subdir)) { $subdir='unknown'; }
 1397:     my $fname=$env{'form.'.$formname.'.filename'};
 1398:     $fname=&clean_filename($fname);
 1399: # See if there is anything left
 1400:     unless ($fname) { return 'error: no uploaded file'; }
 1401:     chop($env{'form.'.$formname});
 1402:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1403:         my $now = time;
 1404:         my $filepath = 'tmp/helprequests/'.$now;
 1405:         my @parts=split(/\//,$filepath);
 1406:         my $fullpath = $perlvar{'lonDaemons'};
 1407:         for (my $i=0;$i<@parts;$i++) {
 1408:             $fullpath .= '/'.$parts[$i];
 1409:             if ((-e $fullpath)!=1) {
 1410:                 mkdir($fullpath,0777);
 1411:             }
 1412:         }
 1413:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1414:         print $fh $env{'form.'.$formname};
 1415:         close($fh);
 1416:         return $fullpath.'/'.$fname;
 1417:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1418:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1419:                        '_'.$env{'user.domain'}.'/pending';
 1420:         my @parts=split(/\//,$filepath);
 1421:         my $fullpath = $perlvar{'lonDaemons'};
 1422:         for (my $i=0;$i<@parts;$i++) {
 1423:             $fullpath .= '/'.$parts[$i];
 1424:             if ((-e $fullpath)!=1) {
 1425:                 mkdir($fullpath,0777);
 1426:             }
 1427:         }
 1428:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1429:         print $fh $env{'form.'.$formname};
 1430:         close($fh);
 1431:         return $fullpath.'/'.$fname;
 1432:     }
 1433:     
 1434: # Create the directory if not present
 1435:     $fname="$subdir/$fname";
 1436:     if ($coursedoc) {
 1437: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1438: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1439:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1440:             return &finishuserfileupload($docuname,$docudom,
 1441: 					 $formname,$fname,$parser,$allfiles,
 1442: 					 $codebase);
 1443:         } else {
 1444:             $fname=$env{'form.folder'}.'/'.$fname;
 1445:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1446: 				       $fname,$formname,$parser,
 1447: 				       $allfiles,$codebase);
 1448:         }
 1449:     } elsif (defined($destuname)) {
 1450:         my $docuname=$destuname;
 1451:         my $docudom=$destudom;
 1452: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1453: 				     $fname,$parser,$allfiles,$codebase);
 1454:         
 1455:     } else {
 1456:         my $docuname=$env{'user.name'};
 1457:         my $docudom=$env{'user.domain'};
 1458:         if (exists($env{'form.group'})) {
 1459:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1460:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1461:         }
 1462: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1463: 				     $fname,$parser,$allfiles,$codebase);
 1464:     }
 1465: }
 1466: 
 1467: sub finishuserfileupload {
 1468:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1469:     my $path=$docudom.'/'.$docuname.'/';
 1470:     my $filepath=$perlvar{'lonDocRoot'};
 1471:     my ($fnamepath,$file);
 1472:     $file=$fname;
 1473:     if ($fname=~m|/|) {
 1474:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1475: 	$path.=$fnamepath.'/';
 1476:     }
 1477:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1478:     my $count;
 1479:     for ($count=4;$count<=$#parts;$count++) {
 1480:         $filepath.="/$parts[$count]";
 1481:         if ((-e $filepath)!=1) {
 1482: 	    mkdir($filepath,0777);
 1483:         }
 1484:     }
 1485: # Save the file
 1486:     {
 1487: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1488: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1489: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1490: 	    return '/adm/notfound.html';
 1491: 	}
 1492: 	if (!print FH ($env{'form.'.$formname})) {
 1493: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1494: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1495: 	    return '/adm/notfound.html';
 1496: 	}
 1497: 	close(FH);
 1498:     }
 1499:     if ($parser eq 'parse') {
 1500:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1501: 						   $codebase);
 1502:         unless ($parse_result eq 'ok') {
 1503:             &logthis('Failed to parse '.$filepath.$file.
 1504: 		     ' for embedded media: '.$parse_result); 
 1505:         }
 1506:     }
 1507: # Notify homeserver to grep it
 1508: #
 1509:     my $docuhome=&homeserver($docuname,$docudom);
 1510:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1511:     if ($fetchresult eq 'ok') {
 1512: #
 1513: # Return the URL to it
 1514:         return '/uploaded/'.$path.$file;
 1515:     } else {
 1516:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1517: 		 ': '.$fetchresult);
 1518:         return '/adm/notfound.html';
 1519:     }    
 1520: }
 1521: 
 1522: sub extract_embedded_items {
 1523:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1524:     my @state = ();
 1525:     my %javafiles = (
 1526:                       codebase => '',
 1527:                       code => '',
 1528:                       archive => ''
 1529:                     );
 1530:     my %mediafiles = (
 1531:                       src => '',
 1532:                       movie => '',
 1533:                      );
 1534:     my $p;
 1535:     if ($content) {
 1536:         $p = HTML::LCParser->new($content);
 1537:     } else {
 1538:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1539:     }
 1540:     while (my $t=$p->get_token()) {
 1541: 	if ($t->[0] eq 'S') {
 1542: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1543: 	    push (@state, $tagname);
 1544:             if (lc($tagname) eq 'allow') {
 1545:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1546:             }
 1547: 	    if (lc($tagname) eq 'img') {
 1548: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1549: 	    }
 1550:             if (lc($tagname) eq 'script') {
 1551:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1552:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1553:                 } else {
 1554:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1555:                 }
 1556:             }
 1557:             if (lc($tagname) eq 'link') {
 1558:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1559:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1560:                 }
 1561:             }
 1562: 	    if (lc($tagname) eq 'object' ||
 1563: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1564: 		foreach my $item (keys(%javafiles)) {
 1565: 		    $javafiles{$item} = '';
 1566: 		}
 1567: 	    }
 1568: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1569: 		my $name = lc($attr->{'name'});
 1570: 		foreach my $item (keys(%javafiles)) {
 1571: 		    if ($name eq $item) {
 1572: 			$javafiles{$item} = $attr->{'value'};
 1573: 			last;
 1574: 		    }
 1575: 		}
 1576: 		foreach my $item (keys(%mediafiles)) {
 1577: 		    if ($name eq $item) {
 1578: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1579: 			last;
 1580: 		    }
 1581: 		}
 1582: 	    }
 1583: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1584: 		foreach my $item (keys(%javafiles)) {
 1585: 		    if ($attr->{$item}) {
 1586: 			$javafiles{$item} = $attr->{$item};
 1587: 			last;
 1588: 		    }
 1589: 		}
 1590: 		foreach my $item (keys(%mediafiles)) {
 1591: 		    if ($attr->{$item}) {
 1592: 			&add_filetype($allfiles,$attr->{$item},$item);
 1593: 			last;
 1594: 		    }
 1595: 		}
 1596: 	    }
 1597: 	} elsif ($t->[0] eq 'E') {
 1598: 	    my ($tagname) = ($t->[1]);
 1599: 	    if ($javafiles{'codebase'} ne '') {
 1600: 		$javafiles{'codebase'} .= '/';
 1601: 	    }  
 1602: 	    if (lc($tagname) eq 'applet' ||
 1603: 		lc($tagname) eq 'object' ||
 1604: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1605: 		) {
 1606: 		foreach my $item (keys(%javafiles)) {
 1607: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1608: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1609: 			&add_filetype($allfiles,$file,$item);
 1610: 		    }
 1611: 		}
 1612: 	    } 
 1613: 	    pop @state;
 1614: 	}
 1615:     }
 1616:     return 'ok';
 1617: }
 1618: 
 1619: sub add_filetype {
 1620:     my ($allfiles,$file,$type)=@_;
 1621:     if (exists($allfiles->{$file})) {
 1622: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1623: 	    push(@{$allfiles->{$file}}, &escape($type));
 1624: 	}
 1625:     } else {
 1626: 	@{$allfiles->{$file}} = (&escape($type));
 1627:     }
 1628: }
 1629: 
 1630: sub removeuploadedurl {
 1631:     my ($url)=@_;
 1632:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1633:     return &removeuserfile($uname,$udom,$fname);
 1634: }
 1635: 
 1636: sub removeuserfile {
 1637:     my ($docuname,$docudom,$fname)=@_;
 1638:     my $home=&homeserver($docuname,$docudom);
 1639:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1640:     if ($result eq 'ok') {
 1641:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1642:             my $metafile = $fname.'.meta';
 1643:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1644:         }
 1645:     }
 1646:     return $result;
 1647: }
 1648: 
 1649: sub mkdiruserfile {
 1650:     my ($docuname,$docudom,$dir)=@_;
 1651:     my $home=&homeserver($docuname,$docudom);
 1652:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1653: }
 1654: 
 1655: sub renameuserfile {
 1656:     my ($docuname,$docudom,$old,$new)=@_;
 1657:     my $home=&homeserver($docuname,$docudom);
 1658:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1659:                         &escape("$old").':'.&escape("$new"),$home);
 1660:     if ($result eq 'ok') {
 1661:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1662:             my $oldmeta = $old.'.meta';
 1663:             my $newmeta = $new.'.meta';
 1664:             my $metaresult = 
 1665:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1666:         }
 1667:     }
 1668:     return $result;
 1669: }
 1670: 
 1671: # ------------------------------------------------------------------------- Log
 1672: 
 1673: sub log {
 1674:     my ($dom,$nam,$hom,$what)=@_;
 1675:     return critical("log:$dom:$nam:$what",$hom);
 1676: }
 1677: 
 1678: # ------------------------------------------------------------------ Course Log
 1679: #
 1680: # This routine flushes several buffers of non-mission-critical nature
 1681: #
 1682: 
 1683: sub flushcourselogs {
 1684:     &logthis('Flushing log buffers');
 1685: #
 1686: # course logs
 1687: # This is a log of all transactions in a course, which can be used
 1688: # for data mining purposes
 1689: #
 1690: # It also collects the courseid database, which lists last transaction
 1691: # times and course titles for all courseids
 1692: #
 1693:     my %courseidbuffer=();
 1694:     foreach my $crsid (keys %courselogs) {
 1695:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1696: 		          &escape($courselogs{$crsid}),
 1697: 		          $coursehombuf{$crsid}) eq 'ok') {
 1698: 	    delete $courselogs{$crsid};
 1699:         } else {
 1700:             &logthis('Failed to flush log buffer for '.$crsid);
 1701:             if (length($courselogs{$crsid})>40000) {
 1702:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1703:                         " exceeded maximum size, deleting.</font>");
 1704:                delete $courselogs{$crsid};
 1705:             }
 1706:         }
 1707:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1708:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1709: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1710:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1711:         } else {
 1712:            $courseidbuffer{$coursehombuf{$crsid}}=
 1713: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1714:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1715:         }
 1716:     }
 1717: #
 1718: # Write course id database (reverse lookup) to homeserver of courses 
 1719: # Is used in pickcourse
 1720: #
 1721:     foreach my $crsid (keys(%courseidbuffer)) {
 1722:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
 1723:     }
 1724: #
 1725: # File accesses
 1726: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1727: #
 1728:     foreach my $entry (keys(%accesshash)) {
 1729:         if ($entry =~ /___count$/) {
 1730:             my ($dom,$name);
 1731:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1732:             if (! defined($dom) || $dom eq '' || 
 1733:                 ! defined($name) || $name eq '') {
 1734:                 my $cid = $env{'request.course.id'};
 1735:                 $dom  = $env{'request.'.$cid.'.domain'};
 1736:                 $name = $env{'request.'.$cid.'.num'};
 1737:             }
 1738:             my $value = $accesshash{$entry};
 1739:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1740:             my %temphash=($url => $value);
 1741:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1742:             if ($result eq 'ok') {
 1743:                 delete $accesshash{$entry};
 1744:             } elsif ($result eq 'unknown_cmd') {
 1745:                 # Target server has old code running on it.
 1746:                 my %temphash=($entry => $value);
 1747:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1748:                     delete $accesshash{$entry};
 1749:                 }
 1750:             }
 1751:         } else {
 1752:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1753:             my %temphash=($entry => $accesshash{$entry});
 1754:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1755:                 delete $accesshash{$entry};
 1756:             }
 1757:         }
 1758:     }
 1759: #
 1760: # Roles
 1761: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1762: #
 1763:     foreach my $entry (keys(%userrolehash)) {
 1764:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1765: 	    split(/\:/,$entry);
 1766:         if (&Apache::lonnet::put('nohist_userroles',
 1767:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1768:                 $rudom,$runame) eq 'ok') {
 1769: 	    delete $userrolehash{$entry};
 1770:         }
 1771:     }
 1772: #
 1773: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1774: #
 1775:     my %domrolebuffer = ();
 1776:     foreach my $entry (keys %domainrolehash) {
 1777:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1778:         if ($domrolebuffer{$rudom}) {
 1779:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1780:                       '='.&escape($domainrolehash{$entry});
 1781:         } else {
 1782:             $domrolebuffer{$rudom}.=&escape($entry).
 1783:                       '='.&escape($domainrolehash{$entry});
 1784:         }
 1785:         delete $domainrolehash{$entry};
 1786:     }
 1787:     foreach my $dom (keys(%domrolebuffer)) {
 1788:         foreach my $tryserver (keys %libserv) {
 1789:             if ($hostdom{$tryserver} eq $dom) {
 1790:                 unless (&reply('domroleput:'.$dom.':'.
 1791:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1792:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1793:                 }
 1794:             }
 1795:         }
 1796:     }
 1797:     $dumpcount++;
 1798: }
 1799: 
 1800: sub courselog {
 1801:     my $what=shift;
 1802:     $what=time.':'.$what;
 1803:     unless ($env{'request.course.id'}) { return ''; }
 1804:     $coursedombuf{$env{'request.course.id'}}=
 1805:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1806:     $coursenumbuf{$env{'request.course.id'}}=
 1807:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1808:     $coursehombuf{$env{'request.course.id'}}=
 1809:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1810:     $coursedescrbuf{$env{'request.course.id'}}=
 1811:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1812:     $courseinstcodebuf{$env{'request.course.id'}}=
 1813:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1814:     $courseownerbuf{$env{'request.course.id'}}=
 1815:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1816:     $coursetypebuf{$env{'request.course.id'}}=
 1817:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1818:     if (defined $courselogs{$env{'request.course.id'}}) {
 1819: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1820:     } else {
 1821: 	$courselogs{$env{'request.course.id'}}.=$what;
 1822:     }
 1823:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1824: 	&flushcourselogs();
 1825:     }
 1826: }
 1827: 
 1828: sub courseacclog {
 1829:     my $fnsymb=shift;
 1830:     unless ($env{'request.course.id'}) { return ''; }
 1831:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1832:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1833:         $what.=':POST';
 1834:         # FIXME: Probably ought to escape things....
 1835: 	foreach my $key (keys(%env)) {
 1836:             if ($key=~/^form\.(.*)/) {
 1837: 		$what.=':'.$1.'='.$env{$key};
 1838:             }
 1839:         }
 1840:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1841:         # FIXME: We should not be depending on a form parameter that someone
 1842:         # editing lonsearchcat.pm might change in the future.
 1843:         if ($env{'form.phase'} eq 'course_search') {
 1844:             $what.= ':POST';
 1845:             # FIXME: Probably ought to escape things....
 1846:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1847:                                  'crsdiscuss') {
 1848:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1849:             }
 1850:         }
 1851:     }
 1852:     &courselog($what);
 1853: }
 1854: 
 1855: sub countacc {
 1856:     my $url=&declutter(shift);
 1857:     return if (! defined($url) || $url eq '');
 1858:     unless ($env{'request.course.id'}) { return ''; }
 1859:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1860:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1861:     $accesshash{$key}++;
 1862: }
 1863: 
 1864: sub linklog {
 1865:     my ($from,$to)=@_;
 1866:     $from=&declutter($from);
 1867:     $to=&declutter($to);
 1868:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1869:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1870: }
 1871:   
 1872: sub userrolelog {
 1873:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1874:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1875:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1876:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1877:         ($trole=~/^ta/)) {
 1878:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1879:        $userrolehash
 1880:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1881:                     =$tend.':'.$tstart;
 1882:     }
 1883:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1884:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1885:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1886:         ($trole=~/^sc/)) {
 1887:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1888:        $domainrolehash
 1889:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1890:                     = $tend.':'.$tstart;
 1891:     }
 1892: }
 1893: 
 1894: sub get_course_adv_roles {
 1895:     my $cid=shift;
 1896:     $cid=$env{'request.course.id'} unless (defined($cid));
 1897:     my %coursehash=&coursedescription($cid);
 1898:     my %nothide=();
 1899:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1900: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 1901:     }
 1902:     my %returnhash=();
 1903:     my %dumphash=
 1904:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1905:     my $now=time;
 1906:     foreach my $entry (keys %dumphash) {
 1907: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 1908:         if (($tstart) && ($tstart<0)) { next; }
 1909:         if (($tend) && ($tend<$now)) { next; }
 1910:         if (($tstart) && ($now<$tstart)) { next; }
 1911:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 1912: 	if ($username eq '' || $domain eq '') { next; }
 1913: 	if ((&privileged($username,$domain)) && 
 1914: 	    (!$nothide{$username.':'.$domain})) { next; }
 1915: 	if ($role eq 'cr') { next; }
 1916:         my $key=&plaintext($role);
 1917:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1918:         if ($returnhash{$key}) {
 1919: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1920:         } else {
 1921:             $returnhash{$key}=$username.':'.$domain;
 1922:         }
 1923:      }
 1924:     return %returnhash;
 1925: }
 1926: 
 1927: sub get_my_roles {
 1928:     my ($uname,$udom)=@_;
 1929:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1930:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1931:     my %dumphash=
 1932:             &dump('nohist_userroles',$udom,$uname);
 1933:     my %returnhash=();
 1934:     my $now=time;
 1935:     foreach my $entry (keys(%dumphash)) {
 1936: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 1937:         if (($tstart) && ($tstart<0)) { next; }
 1938:         if (($tend) && ($tend<$now)) { next; }
 1939:         if (($tstart) && ($now<$tstart)) { next; }
 1940:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 1941: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1942:      }
 1943:     return %returnhash;
 1944: }
 1945: 
 1946: # ----------------------------------------------------- Frontpage Announcements
 1947: #
 1948: #
 1949: 
 1950: sub postannounce {
 1951:     my ($server,$text)=@_;
 1952:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1953:     unless ($text=~/\w/) { $text=''; }
 1954:     return &reply('setannounce:'.&escape($text),$server);
 1955: }
 1956: 
 1957: sub getannounce {
 1958: 
 1959:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1960: 	my $announcement='';
 1961: 	while (my $line = <$fh>) { $announcement .= $line; }
 1962: 	close($fh);
 1963: 	if ($announcement=~/\w/) { 
 1964: 	    return 
 1965:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1966:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1967: 	} else {
 1968: 	    return '';
 1969: 	}
 1970:     } else {
 1971: 	return '';
 1972:     }
 1973: }
 1974: 
 1975: # ---------------------------------------------------------- Course ID routines
 1976: # Deal with domain's nohist_courseid.db files
 1977: #
 1978: 
 1979: sub courseidput {
 1980:     my ($domain,$what,$coursehome)=@_;
 1981:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1982: }
 1983: 
 1984: sub courseiddump {
 1985:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 1986:     my %returnhash=();
 1987:     unless ($domfilter) { $domfilter=''; }
 1988:     foreach my $tryserver (keys %libserv) {
 1989:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1990: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1991: 	        foreach my $line (
 1992:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1993: 			       $sincefilter.':'.&escape($descfilter).':'.
 1994:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 1995:                                $tryserver))) {
 1996: 		    my ($key,$value)=split(/\=/,$line,2);
 1997:                     if (($key) && ($value)) {
 1998: 		        $returnhash{&unescape($key)}=$value;
 1999:                     }
 2000:                 }
 2001:             }
 2002:         }
 2003:     }
 2004:     return %returnhash;
 2005: }
 2006: 
 2007: # ---------------------------------------------------------- DC e-mail
 2008: 
 2009: sub dcmailput {
 2010:     my ($domain,$msgid,$message,$server)=@_;
 2011:     my $status = &Apache::lonnet::critical(
 2012:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2013:        &escape($message),$server);
 2014:     return $status;
 2015: }
 2016: 
 2017: sub dcmaildump {
 2018:     my ($dom,$startdate,$enddate,$senders) = @_;
 2019:     my %returnhash=();
 2020:     if (exists($domain_primary{$dom})) {
 2021:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2022:                                                          &escape($enddate).':';
 2023: 	my @esc_senders=map { &escape($_)} @$senders;
 2024: 	$cmd.=&escape(join('&',@esc_senders));
 2025: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2026:             my ($key,$value) = split(/\=/,$line,2);
 2027:             if (($key) && ($value)) {
 2028:                 $returnhash{&unescape($key)} = &unescape($value);
 2029:             }
 2030:         }
 2031:     }
 2032:     return %returnhash;
 2033: }
 2034: # ---------------------------------------------------------- Domain roles
 2035: 
 2036: sub get_domain_roles {
 2037:     my ($dom,$roles,$startdate,$enddate)=@_;
 2038:     if (undef($startdate) || $startdate eq '') {
 2039:         $startdate = '.';
 2040:     }
 2041:     if (undef($enddate) || $enddate eq '') {
 2042:         $enddate = '.';
 2043:     }
 2044:     my $rolelist = join(':',@{$roles});
 2045:     my %personnel = ();
 2046:     foreach my $tryserver (keys(%libserv)) {
 2047:         if ($hostdom{$tryserver} eq $dom) {
 2048:             %{$personnel{$tryserver}}=();
 2049:             foreach my $line (
 2050:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2051:                    &escape($startdate).':'.&escape($enddate).':'.
 2052:                    &escape($rolelist), $tryserver))) {
 2053:                 my ($key,$value) = split(/\=/,$line,2);
 2054:                 if (($key) && ($value)) {
 2055:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2056:                 }
 2057:             }
 2058:         }
 2059:     }
 2060:     return %personnel;
 2061: }
 2062: 
 2063: # ----------------------------------------------------------- Check out an item
 2064: 
 2065: sub get_first_access {
 2066:     my ($type,$argsymb)=@_;
 2067:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2068:     if ($argsymb) { $symb=$argsymb; }
 2069:     my ($map,$id,$res)=&decode_symb($symb);
 2070:     if ($type eq 'map') {
 2071: 	$res=&symbread($map);
 2072:     } else {
 2073: 	$res=$symb;
 2074:     }
 2075:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2076:     return $times{"$courseid\0$res"};
 2077: }
 2078: 
 2079: sub set_first_access {
 2080:     my ($type)=@_;
 2081:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2082:     my ($map,$id,$res)=&decode_symb($symb);
 2083:     if ($type eq 'map') {
 2084: 	$res=&symbread($map);
 2085:     } else {
 2086: 	$res=$symb;
 2087:     }
 2088:     my $firstaccess=&get_first_access($type,$symb);
 2089:     if (!$firstaccess) {
 2090: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2091:     }
 2092:     return 'already_set';
 2093: }
 2094: 
 2095: sub checkout {
 2096:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2097:     my $now=time;
 2098:     my $lonhost=$perlvar{'lonHostID'};
 2099:     my $infostr=&escape(
 2100:                  'CHECKOUTTOKEN&'.
 2101:                  $tuname.'&'.
 2102:                  $tudom.'&'.
 2103:                  $tcrsid.'&'.
 2104:                  $symb.'&'.
 2105: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2106:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2107:     if ($token=~/^error\:/) { 
 2108:         &logthis("<font color=\"blue\">WARNING: ".
 2109:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2110:                  "</font>");
 2111:         return ''; 
 2112:     }
 2113: 
 2114:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2115:     $token=~tr/a-z/A-Z/;
 2116: 
 2117:     my %infohash=('resource.0.outtoken' => $token,
 2118:                   'resource.0.checkouttime' => $now,
 2119:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2120: 
 2121:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2122:        return '';
 2123:     } else {
 2124:         &logthis("<font color=\"blue\">WARNING: ".
 2125:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2126:                  "</font>");
 2127:     }    
 2128: 
 2129:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2130:                          &escape('Checkout '.$infostr.' - '.
 2131:                                                  $token)) ne 'ok') {
 2132: 	return '';
 2133:     } else {
 2134:         &logthis("<font color=\"blue\">WARNING: ".
 2135:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2136:                  "</font>");
 2137:     }
 2138:     return $token;
 2139: }
 2140: 
 2141: # ------------------------------------------------------------ Check in an item
 2142: 
 2143: sub checkin {
 2144:     my $token=shift;
 2145:     my $now=time;
 2146:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2147:     $lonhost=~tr/A-Z/a-z/;
 2148:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2149:     $dtoken=~s/\W/\_/g;
 2150:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2151:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2152: 
 2153:     unless (($tuname) && ($tudom)) {
 2154:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2155:         return '';
 2156:     }
 2157:     
 2158:     unless (&allowed('mgr',$tcrsid)) {
 2159:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2160:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2161:         return '';
 2162:     }
 2163: 
 2164:     my %infohash=('resource.0.intoken' => $token,
 2165:                   'resource.0.checkintime' => $now,
 2166:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2167: 
 2168:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2169:        return '';
 2170:     }    
 2171: 
 2172:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2173:                          &escape('Checkin - '.$token)) ne 'ok') {
 2174: 	return '';
 2175:     }
 2176: 
 2177:     return ($symb,$tuname,$tudom,$tcrsid);    
 2178: }
 2179: 
 2180: # --------------------------------------------- Set Expire Date for Spreadsheet
 2181: 
 2182: sub expirespread {
 2183:     my ($uname,$udom,$stype,$usymb)=@_;
 2184:     my $cid=$env{'request.course.id'}; 
 2185:     if ($cid) {
 2186:        my $now=time;
 2187:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2188:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2189:                             $env{'course.'.$cid.'.num'}.
 2190: 	        	    ':nohist_expirationdates:'.
 2191:                             &escape($key).'='.$now,
 2192:                             $env{'course.'.$cid.'.home'})
 2193:     }
 2194:     return 'ok';
 2195: }
 2196: 
 2197: # ----------------------------------------------------- Devalidate Spreadsheets
 2198: 
 2199: sub devalidate {
 2200:     my ($symb,$uname,$udom)=@_;
 2201:     my $cid=$env{'request.course.id'}; 
 2202:     if ($cid) {
 2203:         # delete the stored spreadsheets for
 2204:         # - the student level sheet of this user in course's homespace
 2205:         # - the assessment level sheet for this resource 
 2206:         #   for this user in user's homespace
 2207: 	# - current conditional state info
 2208: 	my $key=$uname.':'.$udom.':';
 2209:         my $status=
 2210: 	    &del('nohist_calculatedsheets',
 2211: 		 [$key.'studentcalc:'],
 2212: 		 $env{'course.'.$cid.'.domain'},
 2213: 		 $env{'course.'.$cid.'.num'})
 2214: 		.' '.
 2215: 	    &del('nohist_calculatedsheets_'.$cid,
 2216: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2217:         unless ($status eq 'ok ok') {
 2218:            &logthis('Could not devalidate spreadsheet '.
 2219:                     $uname.' at '.$udom.' for '.
 2220: 		    $symb.': '.$status);
 2221:         }
 2222: 	&delenv('user.state.'.$cid);
 2223:     }
 2224: }
 2225: 
 2226: sub get_scalar {
 2227:     my ($string,$end) = @_;
 2228:     my $value;
 2229:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2230: 	$value = $1;
 2231:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2232: 	$value = $1;
 2233:     }
 2234:     return &unescape($value);
 2235: }
 2236: 
 2237: sub array2str {
 2238:   my (@array) = @_;
 2239:   my $result=&arrayref2str(\@array);
 2240:   $result=~s/^__ARRAY_REF__//;
 2241:   $result=~s/__END_ARRAY_REF__$//;
 2242:   return $result;
 2243: }
 2244: 
 2245: sub arrayref2str {
 2246:   my ($arrayref) = @_;
 2247:   my $result='__ARRAY_REF__';
 2248:   foreach my $elem (@$arrayref) {
 2249:     if(ref($elem) eq 'ARRAY') {
 2250:       $result.=&arrayref2str($elem).'&';
 2251:     } elsif(ref($elem) eq 'HASH') {
 2252:       $result.=&hashref2str($elem).'&';
 2253:     } elsif(ref($elem)) {
 2254:       #print("Got a ref of ".(ref($elem))." skipping.");
 2255:     } else {
 2256:       $result.=&escape($elem).'&';
 2257:     }
 2258:   }
 2259:   $result=~s/\&$//;
 2260:   $result .= '__END_ARRAY_REF__';
 2261:   return $result;
 2262: }
 2263: 
 2264: sub hash2str {
 2265:   my (%hash) = @_;
 2266:   my $result=&hashref2str(\%hash);
 2267:   $result=~s/^__HASH_REF__//;
 2268:   $result=~s/__END_HASH_REF__$//;
 2269:   return $result;
 2270: }
 2271: 
 2272: sub hashref2str {
 2273:   my ($hashref)=@_;
 2274:   my $result='__HASH_REF__';
 2275:   foreach my $key (sort(keys(%$hashref))) {
 2276:     if (ref($key) eq 'ARRAY') {
 2277:       $result.=&arrayref2str($key).'=';
 2278:     } elsif (ref($key) eq 'HASH') {
 2279:       $result.=&hashref2str($key).'=';
 2280:     } elsif (ref($key)) {
 2281:       $result.='=';
 2282:       #print("Got a ref of ".(ref($key))." skipping.");
 2283:     } else {
 2284: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2285:     }
 2286: 
 2287:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2288:       $result.=&arrayref2str($hashref->{$key}).'&';
 2289:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2290:       $result.=&hashref2str($hashref->{$key}).'&';
 2291:     } elsif(ref($hashref->{$key})) {
 2292:        $result.='&';
 2293:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2294:     } else {
 2295:       $result.=&escape($hashref->{$key}).'&';
 2296:     }
 2297:   }
 2298:   $result=~s/\&$//;
 2299:   $result .= '__END_HASH_REF__';
 2300:   return $result;
 2301: }
 2302: 
 2303: sub str2hash {
 2304:     my ($string)=@_;
 2305:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2306:     return %$hash;
 2307: }
 2308: 
 2309: sub str2hashref {
 2310:   my ($string) = @_;
 2311: 
 2312:   my %hash;
 2313: 
 2314:   if($string !~ /^__HASH_REF__/) {
 2315:       if (! ($string eq '' || !defined($string))) {
 2316: 	  $hash{'error'}='Not hash reference';
 2317:       }
 2318:       return (\%hash, $string);
 2319:   }
 2320: 
 2321:   $string =~ s/^__HASH_REF__//;
 2322: 
 2323:   while($string !~ /^__END_HASH_REF__/) {
 2324:       #key
 2325:       my $key='';
 2326:       if($string =~ /^__HASH_REF__/) {
 2327:           ($key, $string)=&str2hashref($string);
 2328:           if(defined($key->{'error'})) {
 2329:               $hash{'error'}='Bad data';
 2330:               return (\%hash, $string);
 2331:           }
 2332:       } elsif($string =~ /^__ARRAY_REF__/) {
 2333:           ($key, $string)=&str2arrayref($string);
 2334:           if($key->[0] eq 'Array reference error') {
 2335:               $hash{'error'}='Bad data';
 2336:               return (\%hash, $string);
 2337:           }
 2338:       } else {
 2339:           $string =~ s/^(.*?)=//;
 2340: 	  $key=&unescape($1);
 2341:       }
 2342:       $string =~ s/^=//;
 2343: 
 2344:       #value
 2345:       my $value='';
 2346:       if($string =~ /^__HASH_REF__/) {
 2347:           ($value, $string)=&str2hashref($string);
 2348:           if(defined($value->{'error'})) {
 2349:               $hash{'error'}='Bad data';
 2350:               return (\%hash, $string);
 2351:           }
 2352:       } elsif($string =~ /^__ARRAY_REF__/) {
 2353:           ($value, $string)=&str2arrayref($string);
 2354:           if($value->[0] eq 'Array reference error') {
 2355:               $hash{'error'}='Bad data';
 2356:               return (\%hash, $string);
 2357:           }
 2358:       } else {
 2359: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2360:       }
 2361:       $string =~ s/^&//;
 2362: 
 2363:       $hash{$key}=$value;
 2364:   }
 2365: 
 2366:   $string =~ s/^__END_HASH_REF__//;
 2367: 
 2368:   return (\%hash, $string);
 2369: }
 2370: 
 2371: sub str2array {
 2372:     my ($string)=@_;
 2373:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2374:     return @$array;
 2375: }
 2376: 
 2377: sub str2arrayref {
 2378:   my ($string) = @_;
 2379:   my @array;
 2380: 
 2381:   if($string !~ /^__ARRAY_REF__/) {
 2382:       if (! ($string eq '' || !defined($string))) {
 2383: 	  $array[0]='Array reference error';
 2384:       }
 2385:       return (\@array, $string);
 2386:   }
 2387: 
 2388:   $string =~ s/^__ARRAY_REF__//;
 2389: 
 2390:   while($string !~ /^__END_ARRAY_REF__/) {
 2391:       my $value='';
 2392:       if($string =~ /^__HASH_REF__/) {
 2393:           ($value, $string)=&str2hashref($string);
 2394:           if(defined($value->{'error'})) {
 2395:               $array[0] ='Array reference error';
 2396:               return (\@array, $string);
 2397:           }
 2398:       } elsif($string =~ /^__ARRAY_REF__/) {
 2399:           ($value, $string)=&str2arrayref($string);
 2400:           if($value->[0] eq 'Array reference error') {
 2401:               $array[0] ='Array reference error';
 2402:               return (\@array, $string);
 2403:           }
 2404:       } else {
 2405: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2406:       }
 2407:       $string =~ s/^&//;
 2408: 
 2409:       push(@array, $value);
 2410:   }
 2411: 
 2412:   $string =~ s/^__END_ARRAY_REF__//;
 2413: 
 2414:   return (\@array, $string);
 2415: }
 2416: 
 2417: # -------------------------------------------------------------------Temp Store
 2418: 
 2419: sub tmpreset {
 2420:   my ($symb,$namespace,$domain,$stuname) = @_;
 2421:   if (!$symb) {
 2422:     $symb=&symbread();
 2423:     if (!$symb) { $symb= $env{'request.url'}; }
 2424:   }
 2425:   $symb=escape($symb);
 2426: 
 2427:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2428:   $namespace=~s/\//\_/g;
 2429:   $namespace=~s/\W//g;
 2430: 
 2431:   if (!$domain) { $domain=$env{'user.domain'}; }
 2432:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2433:   if ($domain eq 'public' && $stuname eq 'public') {
 2434:       $stuname=$ENV{'REMOTE_ADDR'};
 2435:   }
 2436:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2437:   my %hash;
 2438:   if (tie(%hash,'GDBM_File',
 2439: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2440: 	  &GDBM_WRCREAT(),0640)) {
 2441:     foreach my $key (keys %hash) {
 2442:       if ($key=~ /:$symb/) {
 2443: 	delete($hash{$key});
 2444:       }
 2445:     }
 2446:   }
 2447: }
 2448: 
 2449: sub tmpstore {
 2450:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2451: 
 2452:   if (!$symb) {
 2453:     $symb=&symbread();
 2454:     if (!$symb) { $symb= $env{'request.url'}; }
 2455:   }
 2456:   $symb=escape($symb);
 2457: 
 2458:   if (!$namespace) {
 2459:     # I don't think we would ever want to store this for a course.
 2460:     # it seems this will only be used if we don't have a course.
 2461:     #$namespace=$env{'request.course.id'};
 2462:     #if (!$namespace) {
 2463:       $namespace=$env{'request.state'};
 2464:     #}
 2465:   }
 2466:   $namespace=~s/\//\_/g;
 2467:   $namespace=~s/\W//g;
 2468:   if (!$domain) { $domain=$env{'user.domain'}; }
 2469:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2470:   if ($domain eq 'public' && $stuname eq 'public') {
 2471:       $stuname=$ENV{'REMOTE_ADDR'};
 2472:   }
 2473:   my $now=time;
 2474:   my %hash;
 2475:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2476:   if (tie(%hash,'GDBM_File',
 2477: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2478: 	  &GDBM_WRCREAT(),0640)) {
 2479:     $hash{"version:$symb"}++;
 2480:     my $version=$hash{"version:$symb"};
 2481:     my $allkeys=''; 
 2482:     foreach my $key (keys(%$storehash)) {
 2483:       $allkeys.=$key.':';
 2484:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2485:     }
 2486:     $hash{"$version:$symb:timestamp"}=$now;
 2487:     $allkeys.='timestamp';
 2488:     $hash{"$version:keys:$symb"}=$allkeys;
 2489:     if (untie(%hash)) {
 2490:       return 'ok';
 2491:     } else {
 2492:       return "error:$!";
 2493:     }
 2494:   } else {
 2495:     return "error:$!";
 2496:   }
 2497: }
 2498: 
 2499: # -----------------------------------------------------------------Temp Restore
 2500: 
 2501: sub tmprestore {
 2502:   my ($symb,$namespace,$domain,$stuname) = @_;
 2503: 
 2504:   if (!$symb) {
 2505:     $symb=&symbread();
 2506:     if (!$symb) { $symb= $env{'request.url'}; }
 2507:   }
 2508:   $symb=escape($symb);
 2509: 
 2510:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2511: 
 2512:   if (!$domain) { $domain=$env{'user.domain'}; }
 2513:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2514:   if ($domain eq 'public' && $stuname eq 'public') {
 2515:       $stuname=$ENV{'REMOTE_ADDR'};
 2516:   }
 2517:   my %returnhash;
 2518:   $namespace=~s/\//\_/g;
 2519:   $namespace=~s/\W//g;
 2520:   my %hash;
 2521:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2522:   if (tie(%hash,'GDBM_File',
 2523: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2524: 	  &GDBM_READER(),0640)) {
 2525:     my $version=$hash{"version:$symb"};
 2526:     $returnhash{'version'}=$version;
 2527:     my $scope;
 2528:     for ($scope=1;$scope<=$version;$scope++) {
 2529:       my $vkeys=$hash{"$scope:keys:$symb"};
 2530:       my @keys=split(/:/,$vkeys);
 2531:       my $key;
 2532:       $returnhash{"$scope:keys"}=$vkeys;
 2533:       foreach $key (@keys) {
 2534: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2535: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2536:       }
 2537:     }
 2538:     if (!(untie(%hash))) {
 2539:       return "error:$!";
 2540:     }
 2541:   } else {
 2542:     return "error:$!";
 2543:   }
 2544:   return %returnhash;
 2545: }
 2546: 
 2547: # ----------------------------------------------------------------------- Store
 2548: 
 2549: sub store {
 2550:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2551:     my $home='';
 2552: 
 2553:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2554: 
 2555:     $symb=&symbclean($symb);
 2556:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2557: 
 2558:     if (!$domain) { $domain=$env{'user.domain'}; }
 2559:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2560: 
 2561:     &devalidate($symb,$stuname,$domain);
 2562: 
 2563:     $symb=escape($symb);
 2564:     if (!$namespace) { 
 2565:        unless ($namespace=$env{'request.course.id'}) { 
 2566:           return ''; 
 2567:        } 
 2568:     }
 2569:     if (!$home) { $home=$env{'user.home'}; }
 2570: 
 2571:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2572:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2573: 
 2574:     my $namevalue='';
 2575:     foreach my $key (keys(%$storehash)) {
 2576:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2577:     }
 2578:     $namevalue=~s/\&$//;
 2579:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2580:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2581: }
 2582: 
 2583: # -------------------------------------------------------------- Critical Store
 2584: 
 2585: sub cstore {
 2586:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2587:     my $home='';
 2588: 
 2589:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2590: 
 2591:     $symb=&symbclean($symb);
 2592:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2593: 
 2594:     if (!$domain) { $domain=$env{'user.domain'}; }
 2595:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2596: 
 2597:     &devalidate($symb,$stuname,$domain);
 2598: 
 2599:     $symb=escape($symb);
 2600:     if (!$namespace) { 
 2601:        unless ($namespace=$env{'request.course.id'}) { 
 2602:           return ''; 
 2603:        } 
 2604:     }
 2605:     if (!$home) { $home=$env{'user.home'}; }
 2606: 
 2607:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2608:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2609: 
 2610:     my $namevalue='';
 2611:     foreach my $key (keys(%$storehash)) {
 2612:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2613:     }
 2614:     $namevalue=~s/\&$//;
 2615:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2616:     return critical
 2617:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2618: }
 2619: 
 2620: # --------------------------------------------------------------------- Restore
 2621: 
 2622: sub restore {
 2623:     my ($symb,$namespace,$domain,$stuname) = @_;
 2624:     my $home='';
 2625: 
 2626:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2627: 
 2628:     if (!$symb) {
 2629:       unless ($symb=escape(&symbread())) { return ''; }
 2630:     } else {
 2631:       $symb=&escape(&symbclean($symb));
 2632:     }
 2633:     if (!$namespace) { 
 2634:        unless ($namespace=$env{'request.course.id'}) { 
 2635:           return ''; 
 2636:        } 
 2637:     }
 2638:     if (!$domain) { $domain=$env{'user.domain'}; }
 2639:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2640:     if (!$home) { $home=$env{'user.home'}; }
 2641:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2642: 
 2643:     my %returnhash=();
 2644:     foreach my $line (split(/\&/,$answer)) {
 2645: 	my ($name,$value)=split(/\=/,$line);
 2646:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2647:     }
 2648:     my $version;
 2649:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2650:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2651:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2652:        }
 2653:     }
 2654:     return %returnhash;
 2655: }
 2656: 
 2657: # ---------------------------------------------------------- Course Description
 2658: 
 2659: sub coursedescription {
 2660:     my ($courseid,$args)=@_;
 2661:     $courseid=~s/^\///;
 2662:     $courseid=~s/\_/\//g;
 2663:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2664:     my $chome=&homeserver($cnum,$cdomain);
 2665:     my $normalid=$cdomain.'_'.$cnum;
 2666:     # need to always cache even if we get errors otherwise we keep 
 2667:     # trying and trying and trying to get the course description.
 2668:     my %envhash=();
 2669:     my %returnhash=();
 2670:     
 2671:     my $expiretime=600;
 2672:     if ($env{'request.course.id'} eq $normalid) {
 2673: 	$expiretime=120;
 2674:     }
 2675: 
 2676:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2677:     if (!$args->{'freshen_cache'}
 2678: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2679: 	foreach my $key (keys(%env)) {
 2680: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2681: 	    my ($setting) = $1;
 2682: 	    $returnhash{$setting} = $env{$key};
 2683: 	}
 2684: 	return %returnhash;
 2685:     }
 2686: 
 2687:     # get the data agin
 2688:     if (!$args->{'one_time'}) {
 2689: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2690:     }
 2691:     if ($chome ne 'no_host') {
 2692:        %returnhash=&dump('environment',$cdomain,$cnum);
 2693:        if (!exists($returnhash{'con_lost'})) {
 2694:            $returnhash{'home'}= $chome;
 2695: 	   $returnhash{'domain'} = $cdomain;
 2696: 	   $returnhash{'num'} = $cnum;
 2697:            if (!defined($returnhash{'type'})) {
 2698:                $returnhash{'type'} = 'Course';
 2699:            }
 2700:            while (my ($name,$value) = each %returnhash) {
 2701:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2702:            }
 2703:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2704:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2705: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2706:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2707:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2708:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2709:        }
 2710:     }
 2711:     if (!$args->{'one_time'}) {
 2712: 	&appenv(%envhash);
 2713:     }
 2714:     return %returnhash;
 2715: }
 2716: 
 2717: # -------------------------------------------------See if a user is privileged
 2718: 
 2719: sub privileged {
 2720:     my ($username,$domain)=@_;
 2721:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2722: 			&homeserver($username,$domain));
 2723:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2724:     my $now=time;
 2725:     if ($rolesdump ne '') {
 2726:         foreach my $entry (split(/&/,$rolesdump)) {
 2727: 	    if ($entry!~/^rolesdef_/) {
 2728: 		my ($area,$role)=split(/=/,$entry);
 2729: 		$area=~s/\_\w\w$//;
 2730: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2731: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2732: 		    my $active=1;
 2733: 		    if ($tend) {
 2734: 			if ($tend<$now) { $active=0; }
 2735: 		    }
 2736: 		    if ($tstart) {
 2737: 			if ($tstart>$now) { $active=0; }
 2738: 		    }
 2739: 		    if ($active) { return 1; }
 2740: 		}
 2741: 	    }
 2742: 	}
 2743:     }
 2744:     return 0;
 2745: }
 2746: 
 2747: # -------------------------------------------------------- Get user privileges
 2748: 
 2749: sub rolesinit {
 2750:     my ($domain,$username,$authhost)=@_;
 2751:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2752:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2753:     my %allroles=();
 2754:     my %allgroups=();   
 2755:     my $now=time;
 2756:     my %userroles = ('user.login.time' => $now);
 2757:     my $group_privs;
 2758: 
 2759:     if ($rolesdump ne '') {
 2760:         foreach my $entry (split(/&/,$rolesdump)) {
 2761: 	  if ($entry!~/^rolesdef_/) {
 2762:             my ($area,$role)=split(/=/,$entry);
 2763: 	    $area=~s/\_\w\w$//;
 2764:             my ($trole,$tend,$tstart,$group_privs);
 2765: 	    if ($role=~/^cr/) { 
 2766: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2767: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2768: 		    ($tend,$tstart)=split('_',$trest);
 2769: 		} else {
 2770: 		    $trole=$role;
 2771: 		}
 2772:             } elsif ($role =~ m|^gr/|) {
 2773:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2774:                 ($trole,$group_privs) = split(/\//,$trole);
 2775:                 $group_privs = &unescape($group_privs);
 2776: 	    } else {
 2777: 		($trole,$tend,$tstart)=split(/_/,$role);
 2778: 	    }
 2779: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2780: 					 $username);
 2781: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2782:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2783:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2784:             if (($area ne '') && ($trole ne '')) {
 2785: 		my $spec=$trole.'.'.$area;
 2786: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2787: 		if ($trole =~ /^cr\//) {
 2788:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2789:                 } elsif ($trole eq 'gr') {
 2790:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2791: 		} else {
 2792:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2793: 		}
 2794:             }
 2795:           }
 2796:         }
 2797:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2798:         $userroles{'user.adv'}    = $adv;
 2799: 	$userroles{'user.author'} = $author;
 2800:         $env{'user.adv'}=$adv;
 2801:     }
 2802:     return \%userroles;  
 2803: }
 2804: 
 2805: sub set_arearole {
 2806:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2807: # log the associated role with the area
 2808:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2809:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2810: }
 2811: 
 2812: sub custom_roleprivs {
 2813:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2814:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2815:     my $homsvr=homeserver($rauthor,$rdomain);
 2816:     if ($hostname{$homsvr} ne '') {
 2817:         my ($rdummy,$roledef)=
 2818:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2819:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2820:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2821:             if (defined($syspriv)) {
 2822:                 $$allroles{'cm./'}.=':'.$syspriv;
 2823:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2824:             }
 2825:             if ($tdomain ne '') {
 2826:                 if (defined($dompriv)) {
 2827:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2828:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2829:                 }
 2830:                 if (($trest ne '') && (defined($coursepriv))) {
 2831:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2832:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2833:                 }
 2834:             }
 2835:         }
 2836:     }
 2837: }
 2838: 
 2839: sub group_roleprivs {
 2840:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2841:     my $access = 1;
 2842:     my $now = time;
 2843:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2844:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2845:     if ($access) {
 2846:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2847:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2848:     }
 2849: }
 2850: 
 2851: sub standard_roleprivs {
 2852:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2853:     if (defined($pr{$trole.':s'})) {
 2854:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2855:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2856:     }
 2857:     if ($tdomain ne '') {
 2858:         if (defined($pr{$trole.':d'})) {
 2859:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2860:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2861:         }
 2862:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2863:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2864:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2865:         }
 2866:     }
 2867: }
 2868: 
 2869: sub set_userprivs {
 2870:     my ($userroles,$allroles,$allgroups) = @_; 
 2871:     my $author=0;
 2872:     my $adv=0;
 2873:     my %grouproles = ();
 2874:     if (keys(%{$allgroups}) > 0) {
 2875:         foreach my $role (keys %{$allroles}) {
 2876:             my ($trole,$area,$sec,$extendedarea);
 2877:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
 2878:                 $trole = $1;
 2879:                 $area = $2;
 2880:                 $sec = $3;
 2881:                 $extendedarea = $area.$sec;
 2882:                 if (exists($$allgroups{$area})) {
 2883:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2884:                         my $spec = $trole.'.'.$extendedarea;
 2885:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2886:                                                 $$allgroups{$area}{$group};
 2887:                     }
 2888:                 }
 2889:             }
 2890:         }
 2891:     }
 2892:     foreach my $group (keys(%grouproles)) {
 2893:         $$allroles{$group} = $grouproles{$group};
 2894:     }
 2895:     foreach my $role (keys(%{$allroles})) {
 2896:         my %thesepriv;
 2897:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 2898:         foreach my $item (split(/:/,$$allroles{$role})) {
 2899:             if ($item ne '') {
 2900:                 my ($privilege,$restrictions)=split(/&/,$item);
 2901:                 if ($restrictions eq '') {
 2902:                     $thesepriv{$privilege}='F';
 2903:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2904:                     $thesepriv{$privilege}.=$restrictions;
 2905:                 }
 2906:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2907:             }
 2908:         }
 2909:         my $thesestr='';
 2910:         foreach my $priv (keys(%thesepriv)) {
 2911: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 2912: 	}
 2913:         $userroles->{'user.priv.'.$role} = $thesestr;
 2914:     }
 2915:     return ($author,$adv);
 2916: }
 2917: 
 2918: # --------------------------------------------------------------- get interface
 2919: 
 2920: sub get {
 2921:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2922:    my $items='';
 2923:    foreach my $item (@$storearr) {
 2924:        $items.=&escape($item).'&';
 2925:    }
 2926:    $items=~s/\&$//;
 2927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2928:    if (!$uname) { $uname=$env{'user.name'}; }
 2929:    my $uhome=&homeserver($uname,$udomain);
 2930: 
 2931:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2932:    my @pairs=split(/\&/,$rep);
 2933:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2934:      return @pairs;
 2935:    }
 2936:    my %returnhash=();
 2937:    my $i=0;
 2938:    foreach my $item (@$storearr) {
 2939:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2940:       $i++;
 2941:    }
 2942:    return %returnhash;
 2943: }
 2944: 
 2945: # --------------------------------------------------------------- del interface
 2946: 
 2947: sub del {
 2948:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2949:    my $items='';
 2950:    foreach my $item (@$storearr) {
 2951:        $items.=&escape($item).'&';
 2952:    }
 2953:    $items=~s/\&$//;
 2954:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2955:    if (!$uname) { $uname=$env{'user.name'}; }
 2956:    my $uhome=&homeserver($uname,$udomain);
 2957: 
 2958:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2959: }
 2960: 
 2961: # -------------------------------------------------------------- dump interface
 2962: 
 2963: sub dump {
 2964:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2965:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2966:     if (!$uname) { $uname=$env{'user.name'}; }
 2967:     my $uhome=&homeserver($uname,$udomain);
 2968:     if ($regexp) {
 2969: 	$regexp=&escape($regexp);
 2970:     } else {
 2971: 	$regexp='.';
 2972:     }
 2973:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 2974:     my @pairs=split(/\&/,$rep);
 2975:     my %returnhash=();
 2976:     foreach my $item (@pairs) {
 2977: 	my ($key,$value)=split(/=/,$item,2);
 2978: 	$key = &unescape($key);
 2979: 	next if ($key =~ /^error: 2 /);
 2980: 	$returnhash{$key}=&thaw_unescape($value);
 2981:     }
 2982:     return %returnhash;
 2983: }
 2984: 
 2985: # --------------------------------------------------------- dumpstore interface
 2986: 
 2987: sub dumpstore {
 2988:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 2989:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 2990: }
 2991: 
 2992: # -------------------------------------------------------------- keys interface
 2993: 
 2994: sub getkeys {
 2995:    my ($namespace,$udomain,$uname)=@_;
 2996:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2997:    if (!$uname) { $uname=$env{'user.name'}; }
 2998:    my $uhome=&homeserver($uname,$udomain);
 2999:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3000:    my @keyarray=();
 3001:    foreach my $key (split(/\&/,$rep)) {
 3002:       push(@keyarray,&unescape($key));
 3003:    }
 3004:    return @keyarray;
 3005: }
 3006: 
 3007: # --------------------------------------------------------------- currentdump
 3008: sub currentdump {
 3009:    my ($courseid,$sdom,$sname)=@_;
 3010:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3011:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3012:    $sname    = $env{'user.name'}         if (! defined($sname));
 3013:    my $uhome = &homeserver($sname,$sdom);
 3014:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3015:    return if ($rep =~ /^(error:|no_such_host)/);
 3016:    #
 3017:    my %returnhash=();
 3018:    #
 3019:    if ($rep eq "unknown_cmd") { 
 3020:        # an old lond will not know currentdump
 3021:        # Do a dump and make it look like a currentdump
 3022:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 3023:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3024:        my %hash = @tmp;
 3025:        @tmp=();
 3026:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3027:    } else {
 3028:        my @pairs=split(/\&/,$rep);
 3029:        foreach my $pair (@pairs) {
 3030:            my ($key,$value)=split(/=/,$pair,2);
 3031:            my ($symb,$param) = split(/:/,$key);
 3032:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3033:                                                         &thaw_unescape($value);
 3034:        }
 3035:    }
 3036:    return %returnhash;
 3037: }
 3038: 
 3039: sub convert_dump_to_currentdump{
 3040:     my %hash = %{shift()};
 3041:     my %returnhash;
 3042:     # Code ripped from lond, essentially.  The only difference
 3043:     # here is the unescaping done by lonnet::dump().  Conceivably
 3044:     # we might run in to problems with parameter names =~ /^v\./
 3045:     while (my ($key,$value) = each(%hash)) {
 3046:         my ($v,$symb,$param) = split(/:/,$key);
 3047:         next if ($v eq 'version' || $symb eq 'keys');
 3048:         next if (exists($returnhash{$symb}) &&
 3049:                  exists($returnhash{$symb}->{$param}) &&
 3050:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3051:         $returnhash{$symb}->{$param}=$value;
 3052:         $returnhash{$symb}->{'v.'.$param}=$v;
 3053:     }
 3054:     #
 3055:     # Remove all of the keys in the hashes which keep track of
 3056:     # the version of the parameter.
 3057:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3058:         # use a foreach because we are going to delete from the hash.
 3059:         foreach my $key (keys(%$param_hash)) {
 3060:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3061:         }
 3062:     }
 3063:     return \%returnhash;
 3064: }
 3065: 
 3066: # ------------------------------------------------------ critical inc interface
 3067: 
 3068: sub cinc {
 3069:     return &inc(@_,'critical');
 3070: }
 3071: 
 3072: # --------------------------------------------------------------- inc interface
 3073: 
 3074: sub inc {
 3075:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3076:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3077:     if (!$uname) { $uname=$env{'user.name'}; }
 3078:     my $uhome=&homeserver($uname,$udomain);
 3079:     my $items='';
 3080:     if (! ref($store)) {
 3081:         # got a single value, so use that instead
 3082:         $items = &escape($store).'=&';
 3083:     } elsif (ref($store) eq 'SCALAR') {
 3084:         $items = &escape($$store).'=&';        
 3085:     } elsif (ref($store) eq 'ARRAY') {
 3086:         $items = join('=&',map {&escape($_);} @{$store});
 3087:     } elsif (ref($store) eq 'HASH') {
 3088:         while (my($key,$value) = each(%{$store})) {
 3089:             $items.= &escape($key).'='.&escape($value).'&';
 3090:         }
 3091:     }
 3092:     $items=~s/\&$//;
 3093:     if ($critical) {
 3094: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3095:     } else {
 3096: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3097:     }
 3098: }
 3099: 
 3100: # --------------------------------------------------------------- put interface
 3101: 
 3102: sub put {
 3103:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3104:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3105:    if (!$uname) { $uname=$env{'user.name'}; }
 3106:    my $uhome=&homeserver($uname,$udomain);
 3107:    my $items='';
 3108:    foreach my $item (keys(%$storehash)) {
 3109:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3110:    }
 3111:    $items=~s/\&$//;
 3112:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3113: }
 3114: 
 3115: # ------------------------------------------------------------ newput interface
 3116: 
 3117: sub newput {
 3118:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3119:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3120:    if (!$uname) { $uname=$env{'user.name'}; }
 3121:    my $uhome=&homeserver($uname,$udomain);
 3122:    my $items='';
 3123:    foreach my $key (keys(%$storehash)) {
 3124:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3125:    }
 3126:    $items=~s/\&$//;
 3127:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3128: }
 3129: 
 3130: # ---------------------------------------------------------  putstore interface
 3131: 
 3132: sub putstore {
 3133:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3134:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3135:    if (!$uname) { $uname=$env{'user.name'}; }
 3136:    my $uhome=&homeserver($uname,$udomain);
 3137:    my $items='';
 3138:    foreach my $key (keys(%$storehash)) {
 3139:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3140:    }
 3141:    $items=~s/\&$//;
 3142:    my $esc_symb=&escape($symb);
 3143:    my $esc_v=&escape($version);
 3144:    my $reply =
 3145:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3146: 	      $uhome);
 3147:    if ($reply eq 'unknown_cmd') {
 3148:        # gfall back to way things use to be done
 3149:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3150: 			    $uname);
 3151:    }
 3152:    return $reply;
 3153: }
 3154: 
 3155: sub old_putstore {
 3156:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3157:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3158:     if (!$uname) { $uname=$env{'user.name'}; }
 3159:     my $uhome=&homeserver($uname,$udomain);
 3160:     my %newstorehash;
 3161:     foreach my $item (keys(%$storehash)) {
 3162: 	my $key = $version.':'.&escape($symb).':'.$item;
 3163: 	$newstorehash{$key} = $storehash->{$item};
 3164:     }
 3165:     my $items='';
 3166:     my %allitems = ();
 3167:     foreach my $item (keys(%newstorehash)) {
 3168: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3169: 	    my $key = $1.':keys:'.$2;
 3170: 	    $allitems{$key} .= $3.':';
 3171: 	}
 3172: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3173:     }
 3174:     foreach my $item (keys(%allitems)) {
 3175: 	$allitems{$item} =~ s/\:$//;
 3176: 	$items.= $item.'='.$allitems{$item}.'&';
 3177:     }
 3178:     $items=~s/\&$//;
 3179:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3180: }
 3181: 
 3182: # ------------------------------------------------------ critical put interface
 3183: 
 3184: sub cput {
 3185:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3186:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3187:    if (!$uname) { $uname=$env{'user.name'}; }
 3188:    my $uhome=&homeserver($uname,$udomain);
 3189:    my $items='';
 3190:    foreach my $item (keys(%$storehash)) {
 3191:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3192:    }
 3193:    $items=~s/\&$//;
 3194:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3195: }
 3196: 
 3197: # -------------------------------------------------------------- eget interface
 3198: 
 3199: sub eget {
 3200:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3201:    my $items='';
 3202:    foreach my $item (@$storearr) {
 3203:        $items.=&escape($item).'&';
 3204:    }
 3205:    $items=~s/\&$//;
 3206:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3207:    if (!$uname) { $uname=$env{'user.name'}; }
 3208:    my $uhome=&homeserver($uname,$udomain);
 3209:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3210:    my @pairs=split(/\&/,$rep);
 3211:    my %returnhash=();
 3212:    my $i=0;
 3213:    foreach my $item (@$storearr) {
 3214:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3215:       $i++;
 3216:    }
 3217:    return %returnhash;
 3218: }
 3219: 
 3220: # ------------------------------------------------------------ tmpput interface
 3221: sub tmpput {
 3222:     my ($storehash,$server,$context)=@_;
 3223:     my $items='';
 3224:     foreach my $item (keys(%$storehash)) {
 3225: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3226:     }
 3227:     $items=~s/\&$//;
 3228:     if (defined($context)) {
 3229:         $items .= ':'.&escape($context);
 3230:     }
 3231:     return &reply("tmpput:$items",$server);
 3232: }
 3233: 
 3234: # ------------------------------------------------------------ tmpget interface
 3235: sub tmpget {
 3236:     my ($token,$server)=@_;
 3237:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3238:     my $rep=&reply("tmpget:$token",$server);
 3239:     my %returnhash;
 3240:     foreach my $item (split(/\&/,$rep)) {
 3241: 	my ($key,$value)=split(/=/,$item);
 3242: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3243:     }
 3244:     return %returnhash;
 3245: }
 3246: 
 3247: # ------------------------------------------------------------ tmpget interface
 3248: sub tmpdel {
 3249:     my ($token,$server)=@_;
 3250:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3251:     return &reply("tmpdel:$token",$server);
 3252: }
 3253: 
 3254: # -------------------------------------------------- portfolio access checking
 3255: 
 3256: sub portfolio_access {
 3257:     my ($requrl) = @_;
 3258:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3259:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3260:     if ($result eq 'ok') {
 3261:        return 'F';
 3262:     } elsif ($result =~ /^[^:]+:guest_/) {
 3263:        return 'A';
 3264:     }
 3265:     return '';
 3266: }
 3267: 
 3268: sub get_portfolio_access {
 3269:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3270: 
 3271:     if (!ref($access_hash)) {
 3272: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3273: 	my %access_controls = &get_access_controls($current_perms,$group,
 3274: 						   $file_name);
 3275: 	$access_hash = $access_controls{$file_name};
 3276:     }
 3277: 
 3278:     my ($public,$guest,@domains,@users,@courses,@groups);
 3279:     my $now = time;
 3280:     if (ref($access_hash) eq 'HASH') {
 3281:         foreach my $key (keys(%{$access_hash})) {
 3282:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3283:             if ($start > $now) {
 3284:                 next;
 3285:             }
 3286:             if ($end && $end<$now) {
 3287:                 next;
 3288:             }
 3289:             if ($scope eq 'public') {
 3290:                 $public = $key;
 3291:                 last;
 3292:             } elsif ($scope eq 'guest') {
 3293:                 $guest = $key;
 3294:             } elsif ($scope eq 'domains') {
 3295:                 push(@domains,$key);
 3296:             } elsif ($scope eq 'users') {
 3297:                 push(@users,$key);
 3298:             } elsif ($scope eq 'course') {
 3299:                 push(@courses,$key);
 3300:             } elsif ($scope eq 'group') {
 3301:                 push(@groups,$key);
 3302:             }
 3303:         }
 3304:         if ($public) {
 3305:             return 'ok';
 3306:         }
 3307:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3308:             if ($guest) {
 3309:                 return $guest;
 3310:             }
 3311:         } else {
 3312:             if (@domains > 0) {
 3313:                 foreach my $domkey (@domains) {
 3314:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3315:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3316:                             return 'ok';
 3317:                         }
 3318:                     }
 3319:                 }
 3320:             }
 3321:             if (@users > 0) {
 3322:                 foreach my $userkey (@users) {
 3323:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3324:                         return 'ok';
 3325:                     }
 3326:                 }
 3327:             }
 3328:             my %roleshash;
 3329:             my @courses_and_groups = @courses;
 3330:             push(@courses_and_groups,@groups); 
 3331:             if (@courses_and_groups > 0) {
 3332:                 my (%allgroups,%allroles); 
 3333:                 my ($start,$end,$role,$sec,$group);
 3334:                 foreach my $envkey (%env) {
 3335:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
 3336:                         my $cid = $2.'_'.$3; 
 3337:                         if ($1 eq 'gr') {
 3338:                             $group = $4;
 3339:                             $allgroups{$cid}{$group} = $env{$envkey};
 3340:                         } else {
 3341:                             if ($4 eq '') {
 3342:                                 $sec = 'none';
 3343:                             } else {
 3344:                                 $sec = $4;
 3345:                             }
 3346:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3347:                         }
 3348:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
 3349:                         my $cid = $2.'_'.$3;
 3350:                         if ($4 eq '') {
 3351:                             $sec = 'none';
 3352:                         } else {
 3353:                             $sec = $4;
 3354:                         }
 3355:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3356:                     }
 3357:                 }
 3358:                 if (keys(%allroles) == 0) {
 3359:                     return;
 3360:                 }
 3361:                 foreach my $key (@courses_and_groups) {
 3362:                     my %content = %{$$access_hash{$key}};
 3363:                     my $cnum = $content{'number'};
 3364:                     my $cdom = $content{'domain'};
 3365:                     my $cid = $cdom.'_'.$cnum;
 3366:                     if (!exists($allroles{$cid})) {
 3367:                         next;
 3368:                     }    
 3369:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3370:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3371:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3372:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3373:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3374:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3375:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3376:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3377:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3378:                                         if (grep/^all$/,@sections) {
 3379:                                             return 'ok';
 3380:                                         } else {
 3381:                                             if (grep/^$sec$/,@sections) {
 3382:                                                 return 'ok';
 3383:                                             }
 3384:                                         }
 3385:                                     }
 3386:                                 }
 3387:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3388:                                     if (grep/^none$/,@groups) {
 3389:                                         return 'ok';
 3390:                                     }
 3391:                                 } else {
 3392:                                     if (grep/^all$/,@groups) {
 3393:                                         return 'ok';
 3394:                                     } 
 3395:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3396:                                         if (grep/^$group$/,@groups) {
 3397:                                             return 'ok';
 3398:                                         }
 3399:                                     }
 3400:                                 } 
 3401:                             }
 3402:                         }
 3403:                     }
 3404:                 }
 3405:             }
 3406:             if ($guest) {
 3407:                 return $guest;
 3408:             }
 3409:         }
 3410:     }
 3411:     return;
 3412: }
 3413: 
 3414: sub course_group_datechecker {
 3415:     my ($dates,$now,$status) = @_;
 3416:     my ($start,$end) = split(/\./,$dates);
 3417:     if (!$start && !$end) {
 3418:         return 'ok';
 3419:     }
 3420:     if (grep/^active$/,@{$status}) {
 3421:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3422:             return 'ok';
 3423:         }
 3424:     }
 3425:     if (grep/^previous$/,@{$status}) {
 3426:         if ($end > $now ) {
 3427:             return 'ok';
 3428:         }
 3429:     }
 3430:     if (grep/^future$/,@{$status}) {
 3431:         if ($start > $now) {
 3432:             return 'ok';
 3433:         }
 3434:     }
 3435:     return; 
 3436: }
 3437: 
 3438: sub parse_portfolio_url {
 3439:     my ($url) = @_;
 3440: 
 3441:     my ($type,$udom,$unum,$group,$file_name);
 3442:     
 3443:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
 3444: 	$type = 1;
 3445:         $udom = $1;
 3446:         $unum = $2;
 3447:         $file_name = $3;
 3448:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
 3449: 	$type = 2;
 3450:         $udom = $1;
 3451:         $unum = $2;
 3452:         $group = $3;
 3453:         $file_name = $3.'/'.$4;
 3454:     }
 3455:     if (wantarray) {
 3456: 	return ($type,$udom,$unum,$file_name,$group);
 3457:     }
 3458:     return $type;
 3459: }
 3460: 
 3461: sub is_portfolio_url {
 3462:     my ($url) = @_;
 3463:     return scalar(&parse_portfolio_url($url));
 3464: }
 3465: 
 3466: sub is_portfolio_file {
 3467:     my ($file) = @_;
 3468:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3469:         return 1;
 3470:     }
 3471:     return;
 3472: }
 3473: 
 3474: 
 3475: # ---------------------------------------------- Custom access rule evaluation
 3476: 
 3477: sub customaccess {
 3478:     my ($priv,$uri)=@_;
 3479:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3480:     $urealm=~s/^\W//;
 3481:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3482:     my $access=0;
 3483:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3484: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3485:         if ($role) {
 3486: 	   if ($role ne $urole) { next; }
 3487:         }
 3488:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3489:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3490:             if ($tdom) {
 3491: 		if ($tdom ne $udom) { next; }
 3492:             }
 3493:             if ($tcrs) {
 3494: 		if ($tcrs ne $ucrs) { next; }
 3495:             }
 3496:             if ($tsec) {
 3497: 		if ($tsec ne $usec) { next; }
 3498:             }
 3499:             $access=($effect eq 'allow');
 3500:             last;
 3501:         }
 3502: 	if ($realm eq '' && $role eq '') {
 3503:             $access=($effect eq 'allow');
 3504: 	}
 3505:     }
 3506:     return $access;
 3507: }
 3508: 
 3509: # ------------------------------------------------- Check for a user privilege
 3510: 
 3511: sub allowed {
 3512:     my ($priv,$uri,$symb)=@_;
 3513:     my $ver_orguri=$uri;
 3514:     $uri=&deversion($uri);
 3515:     my $orguri=$uri;
 3516:     $uri=&declutter($uri);
 3517:     
 3518:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3519: # Free bre access to adm and meta resources
 3520:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3521: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3522: 	&& ($priv eq 'bre')) {
 3523: 	return 'F';
 3524:     }
 3525: 
 3526: # Free bre access to user's own portfolio contents
 3527:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3528:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3529: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3530:         return 'F';
 3531:     }
 3532: 
 3533: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3534:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3535:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3536:         if (exists($env{'request.course.id'})) {
 3537:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3538:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3539:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3540:                 my $courseprivid=$env{'request.course.id'};
 3541:                 $courseprivid=~s/\_/\//;
 3542:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3543:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3544:                     return $1; 
 3545:                 } else {
 3546:                     if ($env{'request.course.sec'}) {
 3547:                         $courseprivid.='/'.$env{'request.course.sec'};
 3548:                     }
 3549:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3550:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3551:                         return $2;
 3552:                     }
 3553:                 }
 3554:             }
 3555:         }
 3556:     }
 3557: 
 3558: # Free bre to public access
 3559: 
 3560:     if ($priv eq 'bre') {
 3561:         my $copyright=&metadata($uri,'copyright');
 3562: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3563:            return 'F'; 
 3564:         }
 3565:         if ($copyright eq 'priv') {
 3566:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3567: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3568: 		return '';
 3569:             }
 3570:         }
 3571:         if ($copyright eq 'domain') {
 3572:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3573: 	    unless (($env{'user.domain'} eq $1) ||
 3574:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3575: 		return '';
 3576:             }
 3577:         }
 3578:         if ($env{'request.role'}=~ /li\.\//) {
 3579:             # Library role, so allow browsing of resources in this domain.
 3580:             return 'F';
 3581:         }
 3582:         if ($copyright eq 'custom') {
 3583: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3584:         }
 3585:     }
 3586:     # Domain coordinator is trying to create a course
 3587:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3588:         # uri is the requested domain in this case.
 3589:         # comparison to 'request.role.domain' shows if the user has selected
 3590:         # a role of dc for the domain in question.
 3591:         return 'F' if ($uri eq $env{'request.role.domain'});
 3592:     }
 3593: 
 3594:     my $thisallowed='';
 3595:     my $statecond=0;
 3596:     my $courseprivid='';
 3597: 
 3598: # Course
 3599: 
 3600:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3601:        $thisallowed.=$1;
 3602:     }
 3603: 
 3604: # Domain
 3605: 
 3606:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3607:        =~/\Q$priv\E\&([^\:]*)/) {
 3608:        $thisallowed.=$1;
 3609:     }
 3610: 
 3611: # Course: uri itself is a course
 3612:     my $courseuri=$uri;
 3613:     $courseuri=~s/\_(\d)/\/$1/;
 3614:     $courseuri=~s/^([^\/])/\/$1/;
 3615: 
 3616:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3617:        =~/\Q$priv\E\&([^\:]*)/) {
 3618:        $thisallowed.=$1;
 3619:     }
 3620: 
 3621: # URI is an uploaded document for this course, default permissions don't matter
 3622: # not allowing 'edit' access (editupload) to uploaded course docs
 3623:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3624: 	$thisallowed='';
 3625:         my ($match)=&is_on_map($uri);
 3626:         if ($match) {
 3627:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3628:                   =~/\Q$priv\E\&([^\:]*)/) {
 3629:                 $thisallowed.=$1;
 3630:             }
 3631:         } else {
 3632:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3633:             if ($refuri) {
 3634:                 if ($refuri =~ m|^/adm/|) {
 3635:                     $thisallowed='F';
 3636:                 } else {
 3637:                     $refuri=&declutter($refuri);
 3638:                     my ($match) = &is_on_map($refuri);
 3639:                     if ($match) {
 3640:                         $thisallowed='F';
 3641:                     }
 3642:                 }
 3643:             }
 3644:         }
 3645:     }
 3646: 
 3647:     if ($priv eq 'bre'
 3648: 	&& $thisallowed ne 'F' 
 3649: 	&& $thisallowed ne '2'
 3650: 	&& &is_portfolio_url($uri)) {
 3651: 	$thisallowed = &portfolio_access($uri);
 3652:     }
 3653:     
 3654: # Full access at system, domain or course-wide level? Exit.
 3655: 
 3656:     if ($thisallowed=~/F/) {
 3657: 	return 'F';
 3658:     }
 3659: 
 3660: # If this is generating or modifying users, exit with special codes
 3661: 
 3662:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3663: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3664: 	    my ($audom,$auname)=split('/',$uri);
 3665: # no author name given, so this just checks on the general right to make a co-author in this domain
 3666: 	    unless ($auname) { return $thisallowed; }
 3667: # an author name is given, so we are about to actually make a co-author for a certain account
 3668: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3669: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3670: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3671: 	}
 3672: 	return $thisallowed;
 3673:     }
 3674: #
 3675: # Gathered so far: system, domain and course wide privileges
 3676: #
 3677: # Course: See if uri or referer is an individual resource that is part of 
 3678: # the course
 3679: 
 3680:     if ($env{'request.course.id'}) {
 3681: 
 3682:        $courseprivid=$env{'request.course.id'};
 3683:        if ($env{'request.course.sec'}) {
 3684:           $courseprivid.='/'.$env{'request.course.sec'};
 3685:        }
 3686:        $courseprivid=~s/\_/\//;
 3687:        my $checkreferer=1;
 3688:        my ($match,$cond)=&is_on_map($uri);
 3689:        if ($match) {
 3690:            $statecond=$cond;
 3691:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3692:                =~/\Q$priv\E\&([^\:]*)/) {
 3693:                $thisallowed.=$1;
 3694:                $checkreferer=0;
 3695:            }
 3696:        }
 3697:        
 3698:        if ($checkreferer) {
 3699: 	  my $refuri=$env{'httpref.'.$orguri};
 3700:             unless ($refuri) {
 3701:                 foreach my $key (keys(%env)) {
 3702: 		    if ($key=~/^httpref\..*\*/) {
 3703: 			my $pattern=$key;
 3704:                         $pattern=~s/^httpref\.\/res\///;
 3705:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3706:                         $pattern=~s/\//\\\//g;
 3707:                         if ($orguri=~/$pattern/) {
 3708: 			    $refuri=$env{$key};
 3709:                         }
 3710:                     }
 3711:                 }
 3712:             }
 3713: 
 3714:          if ($refuri) { 
 3715: 	  $refuri=&declutter($refuri);
 3716:           my ($match,$cond)=&is_on_map($refuri);
 3717:             if ($match) {
 3718:               my $refstatecond=$cond;
 3719:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3720:                   =~/\Q$priv\E\&([^\:]*)/) {
 3721:                   $thisallowed.=$1;
 3722:                   $uri=$refuri;
 3723:                   $statecond=$refstatecond;
 3724:               }
 3725:           }
 3726:         }
 3727:        }
 3728:    }
 3729: 
 3730: #
 3731: # Gathered now: all privileges that could apply, and condition number
 3732: # 
 3733: #
 3734: # Full or no access?
 3735: #
 3736: 
 3737:     if ($thisallowed=~/F/) {
 3738: 	return 'F';
 3739:     }
 3740: 
 3741:     unless ($thisallowed) {
 3742:         return '';
 3743:     }
 3744: 
 3745: # Restrictions exist, deal with them
 3746: #
 3747: #   C:according to course preferences
 3748: #   R:according to resource settings
 3749: #   L:unless locked
 3750: #   X:according to user session state
 3751: #
 3752: 
 3753: # Possibly locked functionality, check all courses
 3754: # Locks might take effect only after 10 minutes cache expiration for other
 3755: # courses, and 2 minutes for current course
 3756: 
 3757:     my $envkey;
 3758:     if ($thisallowed=~/L/) {
 3759:         foreach $envkey (keys %env) {
 3760:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3761:                my $courseid=$2;
 3762:                my $roleid=$1.'.'.$2;
 3763:                $courseid=~s/^\///;
 3764:                my $expiretime=600;
 3765:                if ($env{'request.role'} eq $roleid) {
 3766: 		  $expiretime=120;
 3767:                }
 3768: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3769:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3770:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3771: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3772:                }
 3773:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3774:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3775: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3776:                        &log($env{'user.domain'},$env{'user.name'},
 3777:                             $env{'user.home'},
 3778:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3779:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3780:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3781: 		       return '';
 3782:                    }
 3783:                }
 3784:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3785:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3786: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3787:                        &log($env{'user.domain'},$env{'user.name'},
 3788:                             $env{'user.home'},
 3789:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3790:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3791:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3792: 		       return '';
 3793:                    }
 3794:                }
 3795: 	   }
 3796:        }
 3797:     }
 3798:    
 3799: #
 3800: # Rest of the restrictions depend on selected course
 3801: #
 3802: 
 3803:     unless ($env{'request.course.id'}) {
 3804: 	if ($thisallowed eq 'A') {
 3805: 	    return 'A';
 3806: 	} else {
 3807: 	    return '1';
 3808: 	}
 3809:     }
 3810: 
 3811: #
 3812: # Now user is definitely in a course
 3813: #
 3814: 
 3815: 
 3816: # Course preferences
 3817: 
 3818:    if ($thisallowed=~/C/) {
 3819:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3820:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3821:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3822: 	   =~/\Q$rolecode\E/) {
 3823: 	   if ($priv ne 'pch') { 
 3824: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3825: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3826: 			$env{'request.course.id'});
 3827: 	   }
 3828:            return '';
 3829:        }
 3830: 
 3831:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3832: 	   =~/\Q$unamedom\E/) {
 3833: 	   if ($priv ne 'pch') { 
 3834: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3835: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3836: 			$env{'request.course.id'});
 3837: 	   }
 3838:            return '';
 3839:        }
 3840:    }
 3841: 
 3842: # Resource preferences
 3843: 
 3844:    if ($thisallowed=~/R/) {
 3845:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3846:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3847: 	   if ($priv ne 'pch') { 
 3848: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3849: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3850: 	   }
 3851: 	   return '';
 3852:        }
 3853:    }
 3854: 
 3855: # Restricted by state or randomout?
 3856: 
 3857:    if ($thisallowed=~/X/) {
 3858:       if ($env{'acc.randomout'}) {
 3859: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3860:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3861:             return ''; 
 3862:          }
 3863:       }
 3864:       if (&condval($statecond)) {
 3865: 	 return '2';
 3866:       } else {
 3867:          return '';
 3868:       }
 3869:    }
 3870: 
 3871:     if ($thisallowed eq 'A') {
 3872: 	return 'A';
 3873:     }
 3874:    return 'F';
 3875: }
 3876: 
 3877: sub split_uri_for_cond {
 3878:     my $uri=&deversion(&declutter(shift));
 3879:     my @uriparts=split(/\//,$uri);
 3880:     my $filename=pop(@uriparts);
 3881:     my $pathname=join('/',@uriparts);
 3882:     return ($pathname,$filename);
 3883: }
 3884: # --------------------------------------------------- Is a resource on the map?
 3885: 
 3886: sub is_on_map {
 3887:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3888:     #Trying to find the conditional for the file
 3889:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3890: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3891:     if ($match) {
 3892: 	return (1,$1);
 3893:     } else {
 3894: 	return (0,0);
 3895:     }
 3896: }
 3897: 
 3898: # --------------------------------------------------------- Get symb from alias
 3899: 
 3900: sub get_symb_from_alias {
 3901:     my $symb=shift;
 3902:     my ($map,$resid,$url)=&decode_symb($symb);
 3903: # Already is a symb
 3904:     if ($url) { return $symb; }
 3905: # Must be an alias
 3906:     my $aliassymb='';
 3907:     my %bighash;
 3908:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3909:                             &GDBM_READER(),0640)) {
 3910:         my $rid=$bighash{'mapalias_'.$symb};
 3911: 	if ($rid) {
 3912: 	    my ($mapid,$resid)=split(/\./,$rid);
 3913: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3914: 				    $resid,$bighash{'src_'.$rid});
 3915: 	}
 3916:         untie %bighash;
 3917:     }
 3918:     return $aliassymb;
 3919: }
 3920: 
 3921: # ----------------------------------------------------------------- Define Role
 3922: 
 3923: sub definerole {
 3924:   if (allowed('mcr','/')) {
 3925:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3926:     foreach my $role (split(':',$sysrole)) {
 3927: 	my ($crole,$cqual)=split(/\&/,$role);
 3928:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3929:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3930: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3931:                return "refused:s:$crole&$cqual"; 
 3932:             }
 3933:         }
 3934:     }
 3935:     foreach my $role (split(':',$domrole)) {
 3936: 	my ($crole,$cqual)=split(/\&/,$role);
 3937:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3938:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3939: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3940:                return "refused:d:$crole&$cqual"; 
 3941:             }
 3942:         }
 3943:     }
 3944:     foreach my $role (split(':',$courole)) {
 3945: 	my ($crole,$cqual)=split(/\&/,$role);
 3946:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3947:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3948: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3949:                return "refused:c:$crole&$cqual"; 
 3950:             }
 3951:         }
 3952:     }
 3953:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3954:                 "$env{'user.domain'}:$env{'user.name'}:".
 3955: 	        "rolesdef_$rolename=".
 3956:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3957:     return reply($command,$env{'user.home'});
 3958:   } else {
 3959:     return 'refused';
 3960:   }
 3961: }
 3962: 
 3963: # ---------------- Make a metadata query against the network of library servers
 3964: 
 3965: sub metadata_query {
 3966:     my ($query,$custom,$customshow,$server_array)=@_;
 3967:     my %rhash;
 3968:     my @server_list = (defined($server_array) ? @$server_array
 3969:                                               : keys(%libserv) );
 3970:     for my $server (@server_list) {
 3971: 	unless ($custom or $customshow) {
 3972: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3973: 	    $rhash{$server}=$reply;
 3974: 	}
 3975: 	else {
 3976: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3977: 			     &escape($custom).':'.&escape($customshow),
 3978: 			     $server);
 3979: 	    $rhash{$server}=$reply;
 3980: 	}
 3981:     }
 3982:     return \%rhash;
 3983: }
 3984: 
 3985: # ----------------------------------------- Send log queries and wait for reply
 3986: 
 3987: sub log_query {
 3988:     my ($uname,$udom,$query,%filters)=@_;
 3989:     my $uhome=&homeserver($uname,$udom);
 3990:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3991:     my $uhost=$hostname{$uhome};
 3992:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 3993:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3994:                        $uhome);
 3995:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3996:     return get_query_reply($queryid);
 3997: }
 3998: 
 3999: # ------- Request retrieval of institutional classlists for course(s)
 4000: 
 4001: sub fetch_enrollment_query {
 4002:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4003:     my $homeserver;
 4004:     my $maxtries = 1;
 4005:     if ($context eq 'automated') {
 4006:         $homeserver = $perlvar{'lonHostID'};
 4007:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4008:     } else {
 4009:         $homeserver = &homeserver($cnum,$dom);
 4010:     }
 4011:     my $host=$hostname{$homeserver};
 4012:     my $cmd = '';
 4013:     foreach my $affiliate (keys %{$affiliatesref}) {
 4014:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4015:     }
 4016:     $cmd =~ s/%%$//;
 4017:     $cmd = &escape($cmd);
 4018:     my $query = 'fetchenrollment';
 4019:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4020:     unless ($queryid=~/^\Q$host\E\_/) { 
 4021:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4022:         return 'error: '.$queryid;
 4023:     }
 4024:     my $reply = &get_query_reply($queryid);
 4025:     my $tries = 1;
 4026:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4027:         $reply = &get_query_reply($queryid);
 4028:         $tries ++;
 4029:     }
 4030:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4031:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4032:     } else {
 4033:         my @responses = split/:/,$reply;
 4034:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4035:             foreach my $line (@responses) {
 4036:                 my ($key,$value) = split(/=/,$line,2);
 4037:                 $$replyref{$key} = $value;
 4038:             }
 4039:         } else {
 4040:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4041:             foreach my $line (@responses) {
 4042:                 my ($key,$value) = split(/=/,$line);
 4043:                 $$replyref{$key} = $value;
 4044:                 if ($value > 0) {
 4045:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4046:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4047:                         my $destname = $pathname.'/'.$filename;
 4048:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4049:                         if ($xml_classlist =~ /^error/) {
 4050:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4051:                         } else {
 4052:                             if ( open(FILE,">$destname") ) {
 4053:                                 print FILE &unescape($xml_classlist);
 4054:                                 close(FILE);
 4055:                             } else {
 4056:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4057:                             }
 4058:                         }
 4059:                     }
 4060:                 }
 4061:             }
 4062:         }
 4063:         return 'ok';
 4064:     }
 4065:     return 'error';
 4066: }
 4067: 
 4068: sub get_query_reply {
 4069:     my $queryid=shift;
 4070:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4071:     my $reply='';
 4072:     for (1..100) {
 4073: 	sleep 2;
 4074:         if (-e $replyfile.'.end') {
 4075: 	    if (open(my $fh,$replyfile)) {
 4076:                $reply.=<$fh>;
 4077:                close($fh);
 4078: 	   } else { return 'error: reply_file_error'; }
 4079:            return &unescape($reply);
 4080: 	}
 4081:     }
 4082:     return 'timeout:'.$queryid;
 4083: }
 4084: 
 4085: sub courselog_query {
 4086: #
 4087: # possible filters:
 4088: # url: url or symb
 4089: # username
 4090: # domain
 4091: # action: view, submit, grade
 4092: # start: timestamp
 4093: # end: timestamp
 4094: #
 4095:     my (%filters)=@_;
 4096:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4097:     if ($filters{'url'}) {
 4098: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4099:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4100:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4101:     }
 4102:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4103:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4104:     return &log_query($cname,$cdom,'courselog',%filters);
 4105: }
 4106: 
 4107: sub userlog_query {
 4108:     my ($uname,$udom,%filters)=@_;
 4109:     return &log_query($uname,$udom,'userlog',%filters);
 4110: }
 4111: 
 4112: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4113: 
 4114: sub auto_run {
 4115:     my ($cnum,$cdom) = @_;
 4116:     my $homeserver = &homeserver($cnum,$cdom);
 4117:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4118:     return $response;
 4119: }
 4120: 
 4121: sub auto_get_sections {
 4122:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4123:     my $homeserver = &homeserver($cnum,$cdom);
 4124:     my @secs = ();
 4125:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4126:     unless ($response eq 'refused') {
 4127:         @secs = split/:/,$response;
 4128:     }
 4129:     return @secs;
 4130: }
 4131: 
 4132: sub auto_new_course {
 4133:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4134:     my $homeserver = &homeserver($cnum,$cdom);
 4135:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4136:     return $response;
 4137: }
 4138: 
 4139: sub auto_validate_courseID {
 4140:     my ($cnum,$cdom,$inst_course_id) = @_;
 4141:     my $homeserver = &homeserver($cnum,$cdom);
 4142:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4143:     return $response;
 4144: }
 4145: 
 4146: sub auto_create_password {
 4147:     my ($cnum,$cdom,$authparam) = @_;
 4148:     my $homeserver = &homeserver($cnum,$cdom); 
 4149:     my $create_passwd = 0;
 4150:     my $authchk = '';
 4151:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4152:     if ($response eq 'refused') {
 4153:         $authchk = 'refused';
 4154:     } else {
 4155:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4156:     }
 4157:     return ($authparam,$create_passwd,$authchk);
 4158: }
 4159: 
 4160: sub auto_photo_permission {
 4161:     my ($cnum,$cdom,$students) = @_;
 4162:     my $homeserver = &homeserver($cnum,$cdom);
 4163:     my ($outcome,$perm_reqd,$conditions) = 
 4164: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4165:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4166: 	return (undef,undef);
 4167:     }
 4168:     return ($outcome,$perm_reqd,$conditions);
 4169: }
 4170: 
 4171: sub auto_checkphotos {
 4172:     my ($uname,$udom,$pid) = @_;
 4173:     my $homeserver = &homeserver($uname,$udom);
 4174:     my ($result,$resulttype);
 4175:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4176: 				   &escape($uname).':'.&escape($pid),
 4177: 				   $homeserver));
 4178:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4179: 	return (undef,undef);
 4180:     }
 4181:     if ($outcome) {
 4182:         ($result,$resulttype) = split(/:/,$outcome);
 4183:     } 
 4184:     return ($result,$resulttype);
 4185: }
 4186: 
 4187: sub auto_photochoice {
 4188:     my ($cnum,$cdom) = @_;
 4189:     my $homeserver = &homeserver($cnum,$cdom);
 4190:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4191: 						       &escape($cdom),
 4192: 						       $homeserver)));
 4193:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4194: 	return (undef,undef);
 4195:     }
 4196:     return ($update,$comment);
 4197: }
 4198: 
 4199: sub auto_photoupdate {
 4200:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4201:     my $homeserver = &homeserver($cnum,$dom);
 4202:     my $host=$hostname{$homeserver};
 4203:     my $cmd = '';
 4204:     my $maxtries = 1;
 4205:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4206:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4207:     }
 4208:     $cmd =~ s/%%$//;
 4209:     $cmd = &escape($cmd);
 4210:     my $query = 'institutionalphotos';
 4211:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4212:     unless ($queryid=~/^\Q$host\E\_/) {
 4213:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4214:         return 'error: '.$queryid;
 4215:     }
 4216:     my $reply = &get_query_reply($queryid);
 4217:     my $tries = 1;
 4218:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4219:         $reply = &get_query_reply($queryid);
 4220:         $tries ++;
 4221:     }
 4222:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4223:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4224:     } else {
 4225:         my @responses = split(/:/,$reply);
 4226:         my $outcome = shift(@responses); 
 4227:         foreach my $item (@responses) {
 4228:             my ($key,$value) = split(/=/,$item);
 4229:             $$photo{$key} = $value;
 4230:         }
 4231:         return $outcome;
 4232:     }
 4233:     return 'error';
 4234: }
 4235: 
 4236: sub auto_instcode_format {
 4237:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4238: 	$cat_order) = @_;
 4239:     my $courses = '';
 4240:     my @homeservers;
 4241:     if ($caller eq 'global') {
 4242:         foreach my $tryserver (keys(%libserv)) {
 4243:             if ($hostdom{$tryserver} eq $codedom) {
 4244:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4245:                     push(@homeservers,$tryserver);
 4246:                 }
 4247:             }
 4248:         }
 4249:     } else {
 4250:         push(@homeservers,&homeserver($caller,$codedom));
 4251:     }
 4252:     foreach my $code (keys(%{$instcodes})) {
 4253:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4254:     }
 4255:     chop($courses);
 4256:     my $ok_response = 0;
 4257:     my $response;
 4258:     while (@homeservers > 0 && $ok_response == 0) {
 4259:         my $server = shift(@homeservers); 
 4260:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4261:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4262:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4263: 		split/:/,$response;
 4264:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4265:             push(@{$codetitles},&str2array($codetitles_str));
 4266:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4267:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4268:             $ok_response = 1;
 4269:         }
 4270:     }
 4271:     if ($ok_response) {
 4272:         return 'ok';
 4273:     } else {
 4274:         return $response;
 4275:     }
 4276: }
 4277: 
 4278: sub auto_instcode_defaults {
 4279:     my ($domain,$returnhash,$code_order) = @_;
 4280:     my @homeservers;
 4281:     foreach my $tryserver (keys(%libserv)) {
 4282:         if ($hostdom{$tryserver} eq $domain) {
 4283:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4284:                 push(@homeservers,$tryserver);
 4285:             }
 4286:         }
 4287:     }
 4288:     my $ok_response = 0;
 4289:     my $response;
 4290:     while (@homeservers > 0 && $ok_response == 0) {
 4291:         my $server = shift(@homeservers);
 4292:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4293:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4294:             foreach my $pair (split(/\&/,$response)) {
 4295:                 my ($name,$value)=split(/\=/,$pair);
 4296:                 if ($name eq 'code_order') {
 4297:                     @{$code_order} = split(/\&/,&unescape($value));
 4298:                 } else {
 4299:                     $returnhash->{&unescape($name)}=&unescape($value);
 4300:                 }
 4301:             }
 4302:         }
 4303:         $ok_response = 1;
 4304:     }
 4305:     if ($ok_response) {
 4306:         return 'ok';
 4307:     } else {
 4308:         return $response;
 4309:     }
 4310: } 
 4311: 
 4312: sub auto_validate_class_sec {
 4313:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4314:     my $homeserver = &homeserver($cnum,$cdom);
 4315:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4316:                         &escape($owner).':'.$cdom,$homeserver);
 4317:     return $response;
 4318: }
 4319: 
 4320: # ------------------------------------------------------- Course Group routines
 4321: 
 4322: sub get_coursegroups {
 4323:     my ($cdom,$cnum,$group) = @_;
 4324:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4325: }
 4326: 
 4327: sub modify_coursegroup {
 4328:     my ($cdom,$cnum,$groupsettings) = @_;
 4329:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4330: }
 4331: 
 4332: sub modify_group_roles {
 4333:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4334:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4335:     my $role = 'gr/'.&escape($userprivs);
 4336:     my ($uname,$udom) = split(/:/,$user);
 4337:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4338:     if ($result eq 'ok') {
 4339:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4340:     }
 4341:     return $result;
 4342: }
 4343: 
 4344: sub modify_coursegroup_membership {
 4345:     my ($cdom,$cnum,$membership) = @_;
 4346:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4347:     return $result;
 4348: }
 4349: 
 4350: sub get_active_groups {
 4351:     my ($udom,$uname,$cdom,$cnum) = @_;
 4352:     my $now = time;
 4353:     my %groups = ();
 4354:     foreach my $key (keys(%env)) {
 4355:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4356:             my ($start,$end) = split(/\./,$env{$key});
 4357:             if (($end!=0) && ($end<$now)) { next; }
 4358:             if (($start!=0) && ($start>$now)) { next; }
 4359:             if ($1 eq $cdom && $2 eq $cnum) {
 4360:                 $groups{$3} = $env{$key} ;
 4361:             }
 4362:         }
 4363:     }
 4364:     return %groups;
 4365: }
 4366: 
 4367: sub get_group_membership {
 4368:     my ($cdom,$cnum,$group) = @_;
 4369:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4370: }
 4371: 
 4372: sub get_users_groups {
 4373:     my ($udom,$uname,$courseid) = @_;
 4374:     my @usersgroups;
 4375:     my $cachetime=1800;
 4376:     $courseid=~s/\_/\//g;
 4377:     $courseid=~s/^(\w)/\/$1/;
 4378: 
 4379:     my $hashid="$udom:$uname:$courseid";
 4380:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4381:     if (defined($cached)) {
 4382:         @usersgroups = split(/:/,$grouplist);
 4383:     } else {  
 4384:         $grouplist = '';
 4385:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4386:         my ($tmp) = keys(%roleshash);
 4387:         if ($tmp=~/^error:/) {
 4388:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4389:         } else {
 4390:             my $access_end = $env{'course.'.$courseid.
 4391:                                   '.default_enrollment_end_date'};
 4392:             my $now = time;
 4393:             foreach my $key (keys(%roleshash)) {
 4394:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4395:                     my $group = $1;
 4396:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4397:                         my $start = $2;
 4398:                         my $end = $1;
 4399:                         if ($start == -1) { next; } # deleted from group
 4400:                         if (($start!=0) && ($start>$now)) { next; }
 4401:                         if (($end!=0) && ($end<$now)) {
 4402:                             if ($access_end && $access_end < $now) {
 4403:                                 if ($access_end - $end < 86400) {
 4404:                                     push(@usersgroups,$group);
 4405:                                 }
 4406:                             }
 4407:                             next;
 4408:                         }
 4409:                         push(@usersgroups,$group);
 4410:                     }
 4411:                 }
 4412:             }
 4413:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4414:             $grouplist = join(':',@usersgroups);
 4415:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4416:         }
 4417:     }
 4418:     return @usersgroups;
 4419: }
 4420: 
 4421: sub devalidate_getgroups_cache {
 4422:     my ($udom,$uname,$cdom,$cnum)=@_;
 4423:     my $courseid = $cdom.'_'.$cnum;
 4424:     $courseid=~s/\_/\//g;
 4425:     $courseid=~s/^(\w)/\/$1/;
 4426:     my $hashid="$udom:$uname:$courseid";
 4427:     &devalidate_cache_new('getgroups',$hashid);
 4428: }
 4429: 
 4430: # ------------------------------------------------------------------ Plain Text
 4431: 
 4432: sub plaintext {
 4433:     my ($short,$type,$cid) = @_;
 4434:     if ($short =~ /^cr/) {
 4435: 	return (split('/',$short))[-1];
 4436:     }
 4437:     if (!defined($cid)) {
 4438:         $cid = $env{'request.course.id'};
 4439:     }
 4440:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4441:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4442:                                           '.plaintext'});
 4443:     }
 4444:     my %rolenames = (
 4445:                       Course => 'std',
 4446:                       Group => 'alt1',
 4447:                     );
 4448:     if (defined($type) && 
 4449:          defined($rolenames{$type}) && 
 4450:          defined($prp{$short}{$rolenames{$type}})) {
 4451:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4452:     } else {
 4453:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4454:     }
 4455: }
 4456: 
 4457: # ----------------------------------------------------------------- Assign Role
 4458: 
 4459: sub assignrole {
 4460:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4461:     my $mrole;
 4462:     if ($role =~ /^cr\//) {
 4463:         my $cwosec=$url;
 4464:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4465: 	unless (&allowed('ccr',$cwosec)) {
 4466:            &logthis('Refused custom assignrole: '.
 4467:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4468: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4469:            return 'refused'; 
 4470:         }
 4471:         $mrole='cr';
 4472:     } elsif ($role =~ /^gr\//) {
 4473:         my $cwogrp=$url;
 4474:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4475:         unless (&allowed('mdg',$cwogrp)) {
 4476:             &logthis('Refused group assignrole: '.
 4477:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4478:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4479:             return 'refused';
 4480:         }
 4481:         $mrole='gr';
 4482:     } else {
 4483:         my $cwosec=$url;
 4484:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4485:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4486:            &logthis('Refused assignrole: '.
 4487:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4488: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4489:            return 'refused'; 
 4490:         }
 4491:         $mrole=$role;
 4492:     }
 4493:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4494:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4495:     if ($end) { $command.='_'.$end; }
 4496:     if ($start) {
 4497: 	if ($end) { 
 4498:            $command.='_'.$start; 
 4499:         } else {
 4500:            $command.='_0_'.$start;
 4501:         }
 4502:     }
 4503:     my $origstart = $start;
 4504:     my $origend = $end;
 4505: # actually delete
 4506:     if ($deleteflag) {
 4507: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4508: # modify command to delete the role
 4509:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4510:                 "$udom:$uname:$url".'_'."$mrole";
 4511: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4512: # set start and finish to negative values for userrolelog
 4513:            $start=-1;
 4514:            $end=-1;
 4515:         }
 4516:     }
 4517: # send command
 4518:     my $answer=&reply($command,&homeserver($uname,$udom));
 4519: # log new user role if status is ok
 4520:     if ($answer eq 'ok') {
 4521: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4522: # for course roles, perform group memberships changes triggered by role change.
 4523:         unless ($role =~ /^gr/) {
 4524:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4525:                                              $origstart);
 4526:         }
 4527:     }
 4528:     return $answer;
 4529: }
 4530: 
 4531: # -------------------------------------------------- Modify user authentication
 4532: # Overrides without validation
 4533: 
 4534: sub modifyuserauth {
 4535:     my ($udom,$uname,$umode,$upass)=@_;
 4536:     my $uhome=&homeserver($uname,$udom);
 4537:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4538:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4539:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4540:              ' in domain '.$env{'request.role.domain'});  
 4541:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4542: 		     &escape($upass),$uhome);
 4543:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4544:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4545:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4546:     &log($udom,,$uname,$uhome,
 4547:         'Authentication changed by '.$env{'user.domain'}.', '.
 4548:                                      $env{'user.name'}.', '.$umode.
 4549:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4550:     unless ($reply eq 'ok') {
 4551:         &logthis('Authentication mode error: '.$reply);
 4552: 	return 'error: '.$reply;
 4553:     }   
 4554:     return 'ok';
 4555: }
 4556: 
 4557: # --------------------------------------------------------------- Modify a user
 4558: 
 4559: sub modifyuser {
 4560:     my ($udom,    $uname, $uid,
 4561:         $umode,   $upass, $first,
 4562:         $middle,  $last,  $gene,
 4563:         $forceid, $desiredhome, $email)=@_;
 4564:     $udom=~s/\W//g;
 4565:     $uname=~s/\W//g;
 4566:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4567:              $umode.', '.$first.', '.$middle.', '.
 4568: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4569:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4570:                                      ' desiredhome not specified'). 
 4571:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4572:              ' in domain '.$env{'request.role.domain'});
 4573:     my $uhome=&homeserver($uname,$udom,'true');
 4574: # ----------------------------------------------------------------- Create User
 4575:     if (($uhome eq 'no_host') && 
 4576: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4577:         my $unhome='';
 4578:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4579:             $unhome = $desiredhome;
 4580: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4581: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4582:         } else { # load balancing routine for determining $unhome
 4583:             my $tryserver;
 4584:             my $loadm=10000000;
 4585:             foreach $tryserver (keys %libserv) {
 4586: 	       if ($hostdom{$tryserver} eq $udom) {
 4587:                   my $answer=reply('load',$tryserver);
 4588:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4589: 		      $loadm=$answer;
 4590:                       $unhome=$tryserver;
 4591:                   }
 4592: 	       }
 4593: 	    }
 4594:         }
 4595:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4596: 	    return 'error: unable to find a home server for '.$uname.
 4597:                    ' in domain '.$udom;
 4598:         }
 4599:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4600:                          &escape($upass),$unhome);
 4601: 	unless ($reply eq 'ok') {
 4602:             return 'error: '.$reply;
 4603:         }   
 4604:         $uhome=&homeserver($uname,$udom,'true');
 4605:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4606: 	    return 'error: unable verify users home machine.';
 4607:         }
 4608:     }   # End of creation of new user
 4609: # ---------------------------------------------------------------------- Add ID
 4610:     if ($uid) {
 4611:        $uid=~tr/A-Z/a-z/;
 4612:        my %uidhash=&idrget($udom,$uname);
 4613:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4614:          && (!$forceid)) {
 4615: 	  unless ($uid eq $uidhash{$uname}) {
 4616: 	      return 'error: user id "'.$uid.'" does not match '.
 4617:                   'current user id "'.$uidhash{$uname}.'".';
 4618:           }
 4619:        } else {
 4620: 	  &idput($udom,($uname => $uid));
 4621:        }
 4622:     }
 4623: # -------------------------------------------------------------- Add names, etc
 4624:     my @tmp=&get('environment',
 4625: 		   ['firstname','middlename','lastname','generation'],
 4626: 		   $udom,$uname);
 4627:     my %names;
 4628:     if ($tmp[0] =~ m/^error:.*/) { 
 4629:         %names=(); 
 4630:     } else {
 4631:         %names = @tmp;
 4632:     }
 4633: #
 4634: # Make sure to not trash student environment if instructor does not bother
 4635: # to supply name and email information
 4636: #
 4637:     if ($first)  { $names{'firstname'}  = $first; }
 4638:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4639:     if ($last)   { $names{'lastname'}   = $last; }
 4640:     if (defined($gene))   { $names{'generation'} = $gene; }
 4641:     if ($email) {
 4642:        $email=~s/[^\w\@\.\-\,]//gs;
 4643:        if ($email=~/\@/) { $names{'notification'} = $email;
 4644: 			   $names{'critnotification'} = $email;
 4645: 			   $names{'permanentemail'} = $email; }
 4646:     }
 4647:     my $reply = &put('environment', \%names, $udom,$uname);
 4648:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4649:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4650:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4651:              $umode.', '.$first.', '.$middle.', '.
 4652: 	     $last.', '.$gene.' by '.
 4653:              $env{'user.name'}.' at '.$env{'user.domain'});
 4654:     return 'ok';
 4655: }
 4656: 
 4657: # -------------------------------------------------------------- Modify student
 4658: 
 4659: sub modifystudent {
 4660:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4661:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4662:     if (!$cid) {
 4663: 	unless ($cid=$env{'request.course.id'}) {
 4664: 	    return 'not_in_class';
 4665: 	}
 4666:     }
 4667: # --------------------------------------------------------------- Make the user
 4668:     my $reply=&modifyuser
 4669: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4670:          $desiredhome,$email);
 4671:     unless ($reply eq 'ok') { return $reply; }
 4672:     # This will cause &modify_student_enrollment to get the uid from the
 4673:     # students environment
 4674:     $uid = undef if (!$forceid);
 4675:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4676: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4677:     return $reply;
 4678: }
 4679: 
 4680: sub modify_student_enrollment {
 4681:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4682:     my ($cdom,$cnum,$chome);
 4683:     if (!$cid) {
 4684: 	unless ($cid=$env{'request.course.id'}) {
 4685: 	    return 'not_in_class';
 4686: 	}
 4687: 	$cdom=$env{'course.'.$cid.'.domain'};
 4688: 	$cnum=$env{'course.'.$cid.'.num'};
 4689:     } else {
 4690: 	($cdom,$cnum)=split(/_/,$cid);
 4691:     }
 4692:     $chome=$env{'course.'.$cid.'.home'};
 4693:     if (!$chome) {
 4694: 	$chome=&homeserver($cnum,$cdom);
 4695:     }
 4696:     if (!$chome) { return 'unknown_course'; }
 4697:     # Make sure the user exists
 4698:     my $uhome=&homeserver($uname,$udom);
 4699:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4700: 	return 'error: no such user';
 4701:     }
 4702:     # Get student data if we were not given enough information
 4703:     if (!defined($first)  || $first  eq '' || 
 4704:         !defined($last)   || $last   eq '' || 
 4705:         !defined($uid)    || $uid    eq '' || 
 4706:         !defined($middle) || $middle eq '' || 
 4707:         !defined($gene)   || $gene   eq '') {
 4708:         # They did not supply us with enough data to enroll the student, so
 4709:         # we need to pick up more information.
 4710:         my %tmp = &get('environment',
 4711:                        ['firstname','middlename','lastname', 'generation','id']
 4712:                        ,$udom,$uname);
 4713: 
 4714:         #foreach my $key (keys(%tmp)) {
 4715:         #    &logthis("key $key = ".$tmp{$key});
 4716:         #}
 4717:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4718:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4719:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4720:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4721:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4722:     }
 4723:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4724:     my $reply=cput('classlist',
 4725: 		   {"$uname:$udom" => 
 4726: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4727: 		   $cdom,$cnum);
 4728:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4729: 	return 'error: '.$reply;
 4730:     } else {
 4731: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4732:     }
 4733:     # Add student role to user
 4734:     my $uurl='/'.$cid;
 4735:     $uurl=~s/\_/\//g;
 4736:     if ($usec) {
 4737: 	$uurl.='/'.$usec;
 4738:     }
 4739:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4740: }
 4741: 
 4742: sub format_name {
 4743:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4744:     my $name;
 4745:     if ($first ne 'lastname') {
 4746: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4747:     } else {
 4748: 	if ($lastname=~/\S/) {
 4749: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4750: 	    $name=~s/\s+,/,/;
 4751: 	} else {
 4752: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4753: 	}
 4754:     }
 4755:     $name=~s/^\s+//;
 4756:     $name=~s/\s+$//;
 4757:     $name=~s/\s+/ /g;
 4758:     return $name;
 4759: }
 4760: 
 4761: # ------------------------------------------------- Write to course preferences
 4762: 
 4763: sub writecoursepref {
 4764:     my ($courseid,%prefs)=@_;
 4765:     $courseid=~s/^\///;
 4766:     $courseid=~s/\_/\//g;
 4767:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4768:     my $chome=homeserver($cnum,$cdomain);
 4769:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4770: 	return 'error: no such course';
 4771:     }
 4772:     my $cstring='';
 4773:     foreach my $pref (keys(%prefs)) {
 4774: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 4775:     }
 4776:     $cstring=~s/\&$//;
 4777:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4778: }
 4779: 
 4780: # ---------------------------------------------------------- Make/modify course
 4781: 
 4782: sub createcourse {
 4783:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4784:         $course_owner,$crstype)=@_;
 4785:     $url=&declutter($url);
 4786:     my $cid='';
 4787:     unless (&allowed('ccc',$udom)) {
 4788:         return 'refused';
 4789:     }
 4790: # ------------------------------------------------------------------- Create ID
 4791:    my $uname=int(1+rand(9)).
 4792:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4793:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4794:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4795: # ----------------------------------------------- Make sure that does not exist
 4796:    my $uhome=&homeserver($uname,$udom,'true');
 4797:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4798:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4799:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4800:        $uhome=&homeserver($uname,$udom,'true');       
 4801:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4802:            return 'error: unable to generate unique course-ID';
 4803:        } 
 4804:    }
 4805: # ------------------------------------------------ Check supplied server name
 4806:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4807:     if (! exists($libserv{$course_server})) {
 4808:         return 'error:bad server name '.$course_server;
 4809:     }
 4810: # ------------------------------------------------------------- Make the course
 4811:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4812:                       $course_server);
 4813:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4814:     $uhome=&homeserver($uname,$udom,'true');
 4815:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4816: 	return 'error: no such course';
 4817:     }
 4818: # ----------------------------------------------------------------- Course made
 4819: # log existence
 4820:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4821:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4822:                   &escape($crstype),$uhome);
 4823:     &flushcourselogs();
 4824: # set toplevel url
 4825:     my $topurl=$url;
 4826:     unless ($nonstandard) {
 4827: # ------------------------------------------ For standard courses, make top url
 4828:         my $mapurl=&clutter($url);
 4829:         if ($mapurl eq '/res/') { $mapurl=''; }
 4830:         $env{'form.initmap'}=(<<ENDINITMAP);
 4831: <map>
 4832: <resource id="1" type="start"></resource>
 4833: <resource id="2" src="$mapurl"></resource>
 4834: <resource id="3" type="finish"></resource>
 4835: <link index="1" from="1" to="2"></link>
 4836: <link index="2" from="2" to="3"></link>
 4837: </map>
 4838: ENDINITMAP
 4839:         $topurl=&declutter(
 4840:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4841:                           );
 4842:     }
 4843: # ----------------------------------------------------------- Write preferences
 4844:     &writecoursepref($udom.'_'.$uname,
 4845:                      ('description' => $description,
 4846:                       'url'         => $topurl));
 4847:     return '/'.$udom.'/'.$uname;
 4848: }
 4849: 
 4850: # ---------------------------------------------------------- Assign Custom Role
 4851: 
 4852: sub assigncustomrole {
 4853:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4854:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4855:                        $end,$start,$deleteflag);
 4856: }
 4857: 
 4858: # ----------------------------------------------------------------- Revoke Role
 4859: 
 4860: sub revokerole {
 4861:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4862:     my $now=time;
 4863:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4864: }
 4865: 
 4866: # ---------------------------------------------------------- Revoke Custom Role
 4867: 
 4868: sub revokecustomrole {
 4869:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4870:     my $now=time;
 4871:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4872:            $deleteflag);
 4873: }
 4874: 
 4875: # ------------------------------------------------------------ Disk usage
 4876: sub diskusage {
 4877:     my ($udom,$uname,$directoryRoot)=@_;
 4878:     $directoryRoot =~ s/\/$//;
 4879:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4880:     return $listing;
 4881: }
 4882: 
 4883: sub is_locked {
 4884:     my ($file_name, $domain, $user) = @_;
 4885:     my @check;
 4886:     my $is_locked;
 4887:     push @check, $file_name;
 4888:     my %locked = &get('file_permissions',\@check,
 4889: 		      $env{'user.domain'},$env{'user.name'});
 4890:     my ($tmp)=keys(%locked);
 4891:     if ($tmp=~/^error:/) { undef(%locked); }
 4892:     
 4893:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4894:         $is_locked = 'false';
 4895:         foreach my $entry (@{$locked{$file_name}}) {
 4896:            if (ref($entry) eq 'ARRAY') { 
 4897:                $is_locked = 'true';
 4898:                last;
 4899:            }
 4900:        }
 4901:     } else {
 4902:         $is_locked = 'false';
 4903:     }
 4904: }
 4905: 
 4906: sub declutter_portfile {
 4907:     my ($file) = @_;
 4908:     &logthis("got $file");
 4909:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 4910:     &logthis("ret $file");
 4911:     return $file;
 4912: }
 4913: 
 4914: # ------------------------------------------------------------- Mark as Read Only
 4915: 
 4916: sub mark_as_readonly {
 4917:     my ($domain,$user,$files,$what) = @_;
 4918:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4919:     my ($tmp)=keys(%current_permissions);
 4920:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4921:     foreach my $file (@{$files}) {
 4922: 	$file = &declutter_portfile($file);
 4923:         push(@{$current_permissions{$file}},$what);
 4924:     }
 4925:     &put('file_permissions',\%current_permissions,$domain,$user);
 4926:     return;
 4927: }
 4928: 
 4929: # ------------------------------------------------------------Save Selected Files
 4930: 
 4931: sub save_selected_files {
 4932:     my ($user, $path, @files) = @_;
 4933:     my $filename = $user."savedfiles";
 4934:     my @other_files = &files_not_in_path($user, $path);
 4935:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4936:     foreach my $file (@files) {
 4937:         print (OUT $env{'form.currentpath'}.$file."\n");
 4938:     }
 4939:     foreach my $file (@other_files) {
 4940:         print (OUT $file."\n");
 4941:     }
 4942:     close (OUT);
 4943:     return 'ok';
 4944: }
 4945: 
 4946: sub clear_selected_files {
 4947:     my ($user) = @_;
 4948:     my $filename = $user."savedfiles";
 4949:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4950:     print (OUT undef);
 4951:     close (OUT);
 4952:     return ("ok");    
 4953: }
 4954: 
 4955: sub files_in_path {
 4956:     my ($user, $path) = @_;
 4957:     my $filename = $user."savedfiles";
 4958:     my %return_files;
 4959:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4960:     while (my $line_in = <IN>) {
 4961:         chomp ($line_in);
 4962:         my @paths_and_file = split (m!/!, $line_in);
 4963:         my $file_part = pop (@paths_and_file);
 4964:         my $path_part = join ('/', @paths_and_file);
 4965:         $path_part.='/';
 4966:         my $path_and_file = $path_part.$file_part;
 4967:         if ($path_part eq $path) {
 4968:             $return_files{$file_part}= 'selected';
 4969:         }
 4970:     }
 4971:     close (IN);
 4972:     return (\%return_files);
 4973: }
 4974: 
 4975: # called in portfolio select mode, to show files selected NOT in current directory
 4976: sub files_not_in_path {
 4977:     my ($user, $path) = @_;
 4978:     my $filename = $user."savedfiles";
 4979:     my @return_files;
 4980:     my $path_part;
 4981:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4982:     while (my $line = <IN>) {
 4983:         #ok, I know it's clunky, but I want it to work
 4984:         my @paths_and_file = split(m|/|, $line);
 4985:         my $file_part = pop(@paths_and_file);
 4986:         chomp($file_part);
 4987:         my $path_part = join('/', @paths_and_file);
 4988:         $path_part .= '/';
 4989:         my $path_and_file = $path_part.$file_part;
 4990:         if ($path_part ne $path) {
 4991:             push(@return_files, ($path_and_file));
 4992:         }
 4993:     }
 4994:     close(OUT);
 4995:     return (@return_files);
 4996: }
 4997: 
 4998: #----------------------------------------------Get portfolio file permissions
 4999: 
 5000: sub get_portfile_permissions {
 5001:     my ($domain,$user) = @_;
 5002:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5003:     my ($tmp)=keys(%current_permissions);
 5004:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5005:     return \%current_permissions;
 5006: }
 5007: 
 5008: #---------------------------------------------Get portfolio file access controls
 5009: 
 5010: sub get_access_controls {
 5011:     my ($current_permissions,$group,$file) = @_;
 5012:     my %access;
 5013:     my $real_file = $file;
 5014:     $file =~ s/\.meta$//;
 5015:     if (defined($file)) {
 5016:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5017:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5018:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5019:             }
 5020:         }
 5021:     } else {
 5022:         foreach my $key (keys(%{$current_permissions})) {
 5023:             if ($key =~ /\0accesscontrol$/) {
 5024:                 if (defined($group)) {
 5025:                     if ($key !~ m-^\Q$group\E/-) {
 5026:                         next;
 5027:                     }
 5028:                 }
 5029:                 my ($fullpath) = split(/\0/,$key);
 5030:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5031:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5032:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5033:                     }
 5034:                 }
 5035:             }
 5036:         }
 5037:     }
 5038:     return %access;
 5039: }
 5040: 
 5041: sub modify_access_controls {
 5042:     my ($file_name,$changes,$domain,$user)=@_;
 5043:     my ($outcome,$deloutcome);
 5044:     my %store_permissions;
 5045:     my %new_values;
 5046:     my %new_control;
 5047:     my %translation;
 5048:     my @deletions = ();
 5049:     my $now = time;
 5050:     if (exists($$changes{'activate'})) {
 5051:         if (ref($$changes{'activate'}) eq 'HASH') {
 5052:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5053:             my $numnew = scalar(@newitems);
 5054:             for (my $i=0; $i<$numnew; $i++) {
 5055:                 my $newkey = $newitems[$i];
 5056:                 my $newid = &Apache::loncommon::get_cgi_id();
 5057:                 if ($newkey =~ /^\d+:/) { 
 5058:                     $newkey =~ s/^(\d+)/$newid/;
 5059:                     $translation{$1} = $newid;
 5060:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5061:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5062:                     $translation{$1} = $newid;
 5063:                 }
 5064:                 $new_values{$file_name."\0".$newkey} = 
 5065:                                           $$changes{'activate'}{$newitems[$i]};
 5066:                 $new_control{$newkey} = $now;
 5067:             }
 5068:         }
 5069:     }
 5070:     my %todelete;
 5071:     my %changed_items;
 5072:     foreach my $action ('delete','update') {
 5073:         if (exists($$changes{$action})) {
 5074:             if (ref($$changes{$action}) eq 'HASH') {
 5075:                 foreach my $key (keys(%{$$changes{$action}})) {
 5076:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5077:                     if ($action eq 'delete') { 
 5078:                         $todelete{$itemnum} = 1;
 5079:                     } else {
 5080:                         $changed_items{$itemnum} = $key;
 5081:                     }
 5082:                 }
 5083:             }
 5084:         }
 5085:     }
 5086:     # get lock on access controls for file.
 5087:     my $lockhash = {
 5088:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5089:                                                        ':'.$env{'user.domain'},
 5090:                    }; 
 5091:     my $tries = 0;
 5092:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5093:    
 5094:     while (($gotlock ne 'ok') && $tries <3) {
 5095:         $tries ++;
 5096:         sleep 1;
 5097:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5098:     }
 5099:     if ($gotlock eq 'ok') {
 5100:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5101:         my ($tmp)=keys(%curr_permissions);
 5102:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5103:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5104:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5105:             if (ref($curr_controls) eq 'HASH') {
 5106:                 foreach my $control_item (keys(%{$curr_controls})) {
 5107:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5108:                     if (defined($todelete{$itemnum})) {
 5109:                         push(@deletions,$file_name."\0".$control_item);
 5110:                     } else {
 5111:                         if (defined($changed_items{$itemnum})) {
 5112:                             $new_control{$changed_items{$itemnum}} = $now;
 5113:                             push(@deletions,$file_name."\0".$control_item);
 5114:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5115:                         } else {
 5116:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5117:                         }
 5118:                     }
 5119:                 }
 5120:             }
 5121:         }
 5122:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5123:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5124:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5125:         #  remove lock
 5126:         my @del_lock = ($file_name."\0".'locked_access_records');
 5127:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5128:     } else {
 5129:         $outcome = "error: could not obtain lockfile\n";  
 5130:     }
 5131:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5132: }
 5133: 
 5134: #------------------------------------------------------Get Marked as Read Only
 5135: 
 5136: sub get_marked_as_readonly {
 5137:     my ($domain,$user,$what,$group) = @_;
 5138:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5139:     my @readonly_files;
 5140:     my $cmp1=$what;
 5141:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5142:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5143:         if (defined($group)) {
 5144:             if ($file_name !~ m-^\Q$group\E/-) {
 5145:                 next;
 5146:             }
 5147:         }
 5148:         if (ref($value) eq "ARRAY"){
 5149:             foreach my $stored_what (@{$value}) {
 5150:                 my $cmp2=$stored_what;
 5151:                 if (ref($stored_what) eq 'ARRAY') {
 5152:                     $cmp2=join('',@{$stored_what});
 5153:                 }
 5154:                 if ($cmp1 eq $cmp2) {
 5155:                     push(@readonly_files, $file_name);
 5156:                     last;
 5157:                 } elsif (!defined($what)) {
 5158:                     push(@readonly_files, $file_name);
 5159:                     last;
 5160:                 }
 5161:             }
 5162:         }
 5163:     }
 5164:     return @readonly_files;
 5165: }
 5166: #-----------------------------------------------------------Get Marked as Read Only Hash
 5167: 
 5168: sub get_marked_as_readonly_hash {
 5169:     my ($current_permissions,$group,$what) = @_;
 5170:     my %readonly_files;
 5171:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5172:         if (defined($group)) {
 5173:             if ($file_name !~ m-^\Q$group\E/-) {
 5174:                 next;
 5175:             }
 5176:         }
 5177:         if (ref($value) eq "ARRAY"){
 5178:             foreach my $stored_what (@{$value}) {
 5179:                 if (ref($stored_what) eq 'ARRAY') {
 5180:                     foreach my $lock_descriptor(@{$stored_what}) {
 5181:                         if ($lock_descriptor eq 'graded') {
 5182:                             $readonly_files{$file_name} = 'graded';
 5183:                         } elsif ($lock_descriptor eq 'handback') {
 5184:                             $readonly_files{$file_name} = 'handback';
 5185:                         } else {
 5186:                             if (!exists($readonly_files{$file_name})) {
 5187:                                 $readonly_files{$file_name} = 'locked';
 5188:                             }
 5189:                         }
 5190:                     }
 5191:                 } 
 5192:             }
 5193:         } 
 5194:     }
 5195:     return %readonly_files;
 5196: }
 5197: # ------------------------------------------------------------ Unmark as Read Only
 5198: 
 5199: sub unmark_as_readonly {
 5200:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5201:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5202:     my ($domain,$user,$what,$file_name,$group) = @_;
 5203:     $file_name = &declutter_portfile($file_name);
 5204:     my $symb_crs = $what;
 5205:     if (ref($what)) { $symb_crs=join('',@$what); }
 5206:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5207:     my ($tmp)=keys(%current_permissions);
 5208:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5209:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5210:     foreach my $file (@readonly_files) {
 5211: 	my $clean_file = &declutter_portfile($file);
 5212: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5213: 	my $current_locks = $current_permissions{$file};
 5214:         my @new_locks;
 5215:         my @del_keys;
 5216:         if (ref($current_locks) eq "ARRAY"){
 5217:             foreach my $locker (@{$current_locks}) {
 5218:                 my $compare=$locker;
 5219:                 if (ref($locker) eq 'ARRAY') {
 5220:                     $compare=join('',@{$locker});
 5221:                     if ($compare ne $symb_crs) {
 5222:                         push(@new_locks, $locker);
 5223:                     }
 5224:                 }
 5225:             }
 5226:             if (scalar(@new_locks) > 0) {
 5227:                 $current_permissions{$file} = \@new_locks;
 5228:             } else {
 5229:                 push(@del_keys, $file);
 5230:                 &del('file_permissions',\@del_keys, $domain, $user);
 5231:                 delete($current_permissions{$file});
 5232:             }
 5233:         }
 5234:     }
 5235:     &put('file_permissions',\%current_permissions,$domain,$user);
 5236:     return;
 5237: }
 5238: 
 5239: # ------------------------------------------------------------ Directory lister
 5240: 
 5241: sub dirlist {
 5242:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5243: 
 5244:     $uri=~s/^\///;
 5245:     $uri=~s/\/$//;
 5246:     my ($udom, $uname);
 5247:     (undef,$udom,$uname)=split(/\//,$uri);
 5248:     if(defined($userdomain)) {
 5249:         $udom = $userdomain;
 5250:     }
 5251:     if(defined($username)) {
 5252:         $uname = $username;
 5253:     }
 5254: 
 5255:     my $dirRoot = $perlvar{'lonDocRoot'};
 5256:     if(defined($alternateDirectoryRoot)) {
 5257:         $dirRoot = $alternateDirectoryRoot;
 5258:         $dirRoot =~ s/\/$//;
 5259:     }
 5260: 
 5261:     if($udom) {
 5262:         if($uname) {
 5263:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5264: 				 &homeserver($uname,$udom));
 5265:             my @listing_results;
 5266:             if ($listing eq 'unknown_cmd') {
 5267:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5268: 				  &homeserver($uname,$udom));
 5269:                 @listing_results = split(/:/,$listing);
 5270:             } else {
 5271:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5272:             }
 5273:             return @listing_results;
 5274:         } elsif(!defined($alternateDirectoryRoot)) {
 5275:             my %allusers;
 5276:             foreach my $tryserver (keys(%libserv)) {
 5277:                 if($hostdom{$tryserver} eq $udom) {
 5278:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5279: 					 $udom, $tryserver);
 5280:                     my @listing_results;
 5281:                     if ($listing eq 'unknown_cmd') {
 5282:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5283: 					  $udom, $tryserver);
 5284:                         @listing_results = split(/:/,$listing);
 5285:                     } else {
 5286:                         @listing_results =
 5287:                             map { &unescape($_); } split(/:/,$listing);
 5288:                     }
 5289:                     if ($listing_results[0] ne 'no_such_dir' && 
 5290:                         $listing_results[0] ne 'empty'       &&
 5291:                         $listing_results[0] ne 'con_lost') {
 5292:                         foreach my $line (@listing_results) {
 5293:                             my ($entry) = split(/&/,$line,2);
 5294:                             $allusers{$entry} = 1;
 5295:                         }
 5296:                     }
 5297:                 }
 5298:             }
 5299:             my $alluserstr='';
 5300:             foreach my $user (sort(keys(%allusers))) {
 5301:                 $alluserstr.=$user.'&user:';
 5302:             }
 5303:             $alluserstr=~s/:$//;
 5304:             return split(/:/,$alluserstr);
 5305:         } else {
 5306:             return ('missing user name');
 5307:         }
 5308:     } elsif(!defined($alternateDirectoryRoot)) {
 5309:         my $tryserver;
 5310:         my %alldom=();
 5311:         foreach $tryserver (keys(%libserv)) {
 5312:             $alldom{$hostdom{$tryserver}}=1;
 5313:         }
 5314:         my $alldomstr='';
 5315:         foreach my $domain (sort(keys(%alldom))) {
 5316:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
 5317:         }
 5318:         $alldomstr=~s/:$//;
 5319:         return split(/:/,$alldomstr);       
 5320:     } else {
 5321:         return ('missing domain');
 5322:     }
 5323: }
 5324: 
 5325: # --------------------------------------------- GetFileTimestamp
 5326: # This function utilizes dirlist and returns the date stamp for
 5327: # when it was last modified.  It will also return an error of -1
 5328: # if an error occurs
 5329: 
 5330: ##
 5331: ## FIXME: This subroutine assumes its caller knows something about the
 5332: ## directory structure of the home server for the student ($root).
 5333: ## Not a good assumption to make.  Since this is for looking up files
 5334: ## in user directories, the full path should be constructed by lond, not
 5335: ## whatever machine we request data from.
 5336: ##
 5337: sub GetFileTimestamp {
 5338:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5339:     $studentDomain=~s/\W//g;
 5340:     $studentName=~s/\W//g;
 5341:     my $subdir=$studentName.'__';
 5342:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5343:     my $proname="$studentDomain/$subdir/$studentName";
 5344:     $proname .= '/'.$filename;
 5345:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5346:                                               $studentName, $root);
 5347:     my @stats = split('&', $fileStat);
 5348:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5349:         # @stats contains first the filename, then the stat output
 5350:         return $stats[10]; # so this is 10 instead of 9.
 5351:     } else {
 5352:         return -1;
 5353:     }
 5354: }
 5355: 
 5356: sub stat_file {
 5357:     my ($uri) = @_;
 5358:     $uri = &clutter_with_no_wrapper($uri);
 5359: 
 5360:     my ($udom,$uname,$file,$dir);
 5361:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5362: 	($udom,$uname,$file) =
 5363: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5364: 	$file = 'userfiles/'.$file;
 5365: 	$dir = &propath($udom,$uname);
 5366:     }
 5367:     if ($uri =~ m-^/res/-) {
 5368: 	($udom,$uname) = 
 5369: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5370: 	$file = $uri;
 5371:     }
 5372: 
 5373:     if (!$udom || !$uname || !$file) {
 5374: 	# unable to handle the uri
 5375: 	return ();
 5376:     }
 5377: 
 5378:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5379:     my @stats = split('&', $result);
 5380:     
 5381:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5382: 	shift(@stats); #filename is first
 5383: 	return @stats;
 5384:     }
 5385:     return ();
 5386: }
 5387: 
 5388: # -------------------------------------------------------- Value of a Condition
 5389: 
 5390: # gets the value of a specific preevaluated condition
 5391: #    stored in the string  $env{user.state.<cid>}
 5392: # or looks up a condition reference in the bighash and if if hasn't
 5393: # already been evaluated recurses into docondval to get the value of
 5394: # the condition, then memoizing it to 
 5395: #   $env{user.state.<cid>.<condition>}
 5396: sub directcondval {
 5397:     my $number=shift;
 5398:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5399: 	&Apache::lonuserstate::evalstate();
 5400:     }
 5401:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5402: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5403:     } elsif ($number =~ /^_/) {
 5404: 	my $sub_condition;
 5405: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5406: 		&GDBM_READER(),0640)) {
 5407: 	    $sub_condition=$bighash{'conditions'.$number};
 5408: 	    untie(%bighash);
 5409: 	}
 5410: 	my $value = &docondval($sub_condition);
 5411: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5412: 	return $value;
 5413:     }
 5414:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5415:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5416:     } else {
 5417:        return 2;
 5418:     }
 5419: }
 5420: 
 5421: # get the collection of conditions for this resource
 5422: sub condval {
 5423:     my $condidx=shift;
 5424:     my $allpathcond='';
 5425:     foreach my $cond (split(/\|/,$condidx)) {
 5426: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5427: 	    $allpathcond.=
 5428: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5429: 	}
 5430:     }
 5431:     $allpathcond=~s/\|$//;
 5432:     return &docondval($allpathcond);
 5433: }
 5434: 
 5435: #evaluates an expression of conditions
 5436: sub docondval {
 5437:     my ($allpathcond) = @_;
 5438:     my $result=0;
 5439:     if ($env{'request.course.id'}
 5440: 	&& defined($allpathcond)) {
 5441: 	my $operand='|';
 5442: 	my @stack;
 5443: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5444: 	    if ($chunk eq '(') {
 5445: 		push @stack,($operand,$result);
 5446: 	    } elsif ($chunk eq ')') {
 5447: 		my $before=pop @stack;
 5448: 		if (pop @stack eq '&') {
 5449: 		    $result=$result>$before?$before:$result;
 5450: 		} else {
 5451: 		    $result=$result>$before?$result:$before;
 5452: 		}
 5453: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5454: 		$operand=$chunk;
 5455: 	    } else {
 5456: 		my $new=directcondval($chunk);
 5457: 		if ($operand eq '&') {
 5458: 		    $result=$result>$new?$new:$result;
 5459: 		} else {
 5460: 		    $result=$result>$new?$result:$new;
 5461: 		}
 5462: 	    }
 5463: 	}
 5464:     }
 5465:     return $result;
 5466: }
 5467: 
 5468: # ---------------------------------------------------- Devalidate courseresdata
 5469: 
 5470: sub devalidatecourseresdata {
 5471:     my ($coursenum,$coursedomain)=@_;
 5472:     my $hashid=$coursenum.':'.$coursedomain;
 5473:     &devalidate_cache_new('courseres',$hashid);
 5474: }
 5475: 
 5476: 
 5477: # --------------------------------------------------- Course Resourcedata Query
 5478: 
 5479: sub get_courseresdata {
 5480:     my ($coursenum,$coursedomain)=@_;
 5481:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5482:     my $hashid=$coursenum.':'.$coursedomain;
 5483:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5484:     my %dumpreply;
 5485:     unless (defined($cached)) {
 5486: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5487: 	$result=\%dumpreply;
 5488: 	my ($tmp) = keys(%dumpreply);
 5489: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5490: 	    &do_cache_new('courseres',$hashid,$result,600);
 5491: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5492: 	    return $tmp;
 5493: 	} elsif ($tmp =~ /^(error)/) {
 5494: 	    $result=undef;
 5495: 	    &do_cache_new('courseres',$hashid,$result,600);
 5496: 	}
 5497:     }
 5498:     return $result;
 5499: }
 5500: 
 5501: sub devalidateuserresdata {
 5502:     my ($uname,$udom)=@_;
 5503:     my $hashid="$udom:$uname";
 5504:     &devalidate_cache_new('userres',$hashid);
 5505: }
 5506: 
 5507: sub get_userresdata {
 5508:     my ($uname,$udom)=@_;
 5509:     #most student don\'t have any data set, check if there is some data
 5510:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5511: 
 5512:     my $hashid="$udom:$uname";
 5513:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5514:     if (!defined($cached)) {
 5515: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5516: 	$result=\%resourcedata;
 5517: 	&do_cache_new('userres',$hashid,$result,600);
 5518:     }
 5519:     my ($tmp)=keys(%$result);
 5520:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5521: 	return $result;
 5522:     }
 5523:     #error 2 occurs when the .db doesn't exist
 5524:     if ($tmp!~/error: 2 /) {
 5525: 	&logthis("<font color=\"blue\">WARNING:".
 5526: 		 " Trying to get resource data for ".
 5527: 		 $uname." at ".$udom.": ".
 5528: 		 $tmp."</font>");
 5529:     } elsif ($tmp=~/error: 2 /) {
 5530: 	#&EXT_cache_set($udom,$uname);
 5531: 	&do_cache_new('userres',$hashid,undef,600);
 5532: 	undef($tmp); # not really an error so don't send it back
 5533:     }
 5534:     return $tmp;
 5535: }
 5536: 
 5537: sub resdata {
 5538:     my ($name,$domain,$type,@which)=@_;
 5539:     my $result;
 5540:     if ($type eq 'course') {
 5541: 	$result=&get_courseresdata($name,$domain);
 5542:     } elsif ($type eq 'user') {
 5543: 	$result=&get_userresdata($name,$domain);
 5544:     }
 5545:     if (!ref($result)) { return $result; }    
 5546:     foreach my $item (@which) {
 5547: 	if (defined($result->{$item})) {
 5548: 	    return $result->{$item};
 5549: 	}
 5550:     }
 5551:     return undef;
 5552: }
 5553: 
 5554: #
 5555: # EXT resource caching routines
 5556: #
 5557: 
 5558: sub clear_EXT_cache_status {
 5559:     &delenv('cache.EXT.');
 5560: }
 5561: 
 5562: sub EXT_cache_status {
 5563:     my ($target_domain,$target_user) = @_;
 5564:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5565:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5566:         # We know already the user has no data
 5567:         return 1;
 5568:     } else {
 5569:         return 0;
 5570:     }
 5571: }
 5572: 
 5573: sub EXT_cache_set {
 5574:     my ($target_domain,$target_user) = @_;
 5575:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5576:     #&appenv($cachename => time);
 5577: }
 5578: 
 5579: # --------------------------------------------------------- Value of a Variable
 5580: sub EXT {
 5581: 
 5582:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5583:     unless ($varname) { return ''; }
 5584:     #get real user name/domain, courseid and symb
 5585:     my $courseid;
 5586:     my $publicuser;
 5587:     if ($symbparm) {
 5588: 	$symbparm=&get_symb_from_alias($symbparm);
 5589:     }
 5590:     if (!($uname && $udom)) {
 5591:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5592:       if (!$symbparm) {	$symbparm=$cursymb; }
 5593:     } else {
 5594: 	$courseid=$env{'request.course.id'};
 5595:     }
 5596:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5597:     my $rest;
 5598:     if (defined($therest[0])) {
 5599:        $rest=join('.',@therest);
 5600:     } else {
 5601:        $rest='';
 5602:     }
 5603: 
 5604:     my $qualifierrest=$qualifier;
 5605:     if ($rest) { $qualifierrest.='.'.$rest; }
 5606:     my $spacequalifierrest=$space;
 5607:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5608:     if ($realm eq 'user') {
 5609: # --------------------------------------------------------------- user.resource
 5610: 	if ($space eq 'resource') {
 5611: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5612: 		  || defined($Apache::lonhomework::parsing_a_task))
 5613: 		 &&
 5614: 		 ($symbparm eq &symbread()) ) {	
 5615: 		# if we are in the middle of processing the resource the
 5616: 		# get the value we are planning on committing
 5617:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5618:                     return $Apache::lonhomework::results{$qualifierrest};
 5619:                 } else {
 5620:                     return $Apache::lonhomework::history{$qualifierrest};
 5621:                 }
 5622: 	    } else {
 5623: 		my %restored;
 5624: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5625: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5626: 		} else {
 5627: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5628: 		}
 5629: 		return $restored{$qualifierrest};
 5630: 	    }
 5631: # ----------------------------------------------------------------- user.access
 5632:         } elsif ($space eq 'access') {
 5633: 	    # FIXME - not supporting calls for a specific user
 5634:             return &allowed($qualifier,$rest);
 5635: # ------------------------------------------ user.preferences, user.environment
 5636:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5637: 	    if (($uname eq $env{'user.name'}) &&
 5638: 		($udom eq $env{'user.domain'})) {
 5639: 		return $env{join('.',('environment',$qualifierrest))};
 5640: 	    } else {
 5641: 		my %returnhash;
 5642: 		if (!$publicuser) {
 5643: 		    %returnhash=&userenvironment($udom,$uname,
 5644: 						 $qualifierrest);
 5645: 		}
 5646: 		return $returnhash{$qualifierrest};
 5647: 	    }
 5648: # ----------------------------------------------------------------- user.course
 5649:         } elsif ($space eq 'course') {
 5650: 	    # FIXME - not supporting calls for a specific user
 5651:             return $env{join('.',('request.course',$qualifier))};
 5652: # ------------------------------------------------------------------- user.role
 5653:         } elsif ($space eq 'role') {
 5654: 	    # FIXME - not supporting calls for a specific user
 5655:             my ($role,$where)=split(/\./,$env{'request.role'});
 5656:             if ($qualifier eq 'value') {
 5657: 		return $role;
 5658:             } elsif ($qualifier eq 'extent') {
 5659:                 return $where;
 5660:             }
 5661: # ----------------------------------------------------------------- user.domain
 5662:         } elsif ($space eq 'domain') {
 5663:             return $udom;
 5664: # ------------------------------------------------------------------- user.name
 5665:         } elsif ($space eq 'name') {
 5666:             return $uname;
 5667: # ---------------------------------------------------- Any other user namespace
 5668:         } else {
 5669: 	    my %reply;
 5670: 	    if (!$publicuser) {
 5671: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5672: 	    }
 5673: 	    return $reply{$qualifierrest};
 5674:         }
 5675:     } elsif ($realm eq 'query') {
 5676: # ---------------------------------------------- pull stuff out of query string
 5677:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5678: 						[$spacequalifierrest]);
 5679: 	return $env{'form.'.$spacequalifierrest}; 
 5680:    } elsif ($realm eq 'request') {
 5681: # ------------------------------------------------------------- request.browser
 5682:         if ($space eq 'browser') {
 5683: 	    if ($qualifier eq 'textremote') {
 5684: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5685: 		    return 1;
 5686: 		} else {
 5687: 		    return 0;
 5688: 		}
 5689: 	    } else {
 5690: 		return $env{'browser.'.$qualifier};
 5691: 	    }
 5692: # ------------------------------------------------------------ request.filename
 5693:         } else {
 5694:             return $env{'request.'.$spacequalifierrest};
 5695:         }
 5696:     } elsif ($realm eq 'course') {
 5697: # ---------------------------------------------------------- course.description
 5698:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5699:     } elsif ($realm eq 'resource') {
 5700: 
 5701: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5702: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5703: 	}
 5704: 
 5705: 	if ($space eq 'title') {
 5706: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5707: 	    return &gettitle($symbparm);
 5708: 	}
 5709: 	
 5710: 	if ($space eq 'map') {
 5711: 	    my ($map) = &decode_symb($symbparm);
 5712: 	    return &symbread($map);
 5713: 	}
 5714: 
 5715: 	my ($section, $group, @groups);
 5716: 	my ($courselevelm,$courselevel);
 5717: 	if ($symbparm && defined($courseid) && 
 5718: 	    $courseid eq $env{'request.course.id'}) {
 5719: 
 5720: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5721: 
 5722: # ----------------------------------------------------- Cascading lookup scheme
 5723: 	    my $symbp=$symbparm;
 5724: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5725: 
 5726: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5727: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5728: 
 5729: 	    if (($env{'user.name'} eq $uname) &&
 5730: 		($env{'user.domain'} eq $udom)) {
 5731: 		$section=$env{'request.course.sec'};
 5732:                 @groups = split(/:/,$env{'request.course.groups'});  
 5733:                 @groups=&sort_course_groups($courseid,@groups); 
 5734: 	    } else {
 5735: 		if (! defined($usection)) {
 5736: 		    $section=&getsection($udom,$uname,$courseid);
 5737: 		} else {
 5738: 		    $section = $usection;
 5739: 		}
 5740:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5741: 	    }
 5742: 
 5743: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5744: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5745: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5746: 
 5747: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5748: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5749: 	    $courselevelm=$courseid.'.'.$mapparm;
 5750: 
 5751: # ----------------------------------------------------------- first, check user
 5752: 
 5753: 	    my $userreply=&resdata($uname,$udom,'user',
 5754: 				       ($courselevelr,$courselevelm,
 5755: 					$courselevel));
 5756: 	    if (defined($userreply)) { return $userreply; }
 5757: 
 5758: # ------------------------------------------------ second, check some of course
 5759:             my $coursereply;
 5760:             if (@groups > 0) {
 5761:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5762:                                        $mapparm,$spacequalifierrest);
 5763:                 if (defined($coursereply)) { return $coursereply; }
 5764:             }
 5765: 
 5766: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5767: 				     $env{'course.'.$courseid.'.domain'},
 5768: 				     'course',
 5769: 				     ($seclevelr,$seclevelm,$seclevel,
 5770: 				      $courselevelr));
 5771: 	    if (defined($coursereply)) { return $coursereply; }
 5772: 
 5773: # ------------------------------------------------------ third, check map parms
 5774: 	    my %parmhash=();
 5775: 	    my $thisparm='';
 5776: 	    if (tie(%parmhash,'GDBM_File',
 5777: 		    $env{'request.course.fn'}.'_parms.db',
 5778: 		    &GDBM_READER(),0640)) {
 5779: 		$thisparm=$parmhash{$symbparm};
 5780: 		untie(%parmhash);
 5781: 	    }
 5782: 	    if ($thisparm) { return $thisparm; }
 5783: 	}
 5784: # ------------------------------------------ fourth, look in resource metadata
 5785: 
 5786: 	$spacequalifierrest=~s/\./\_/;
 5787: 	my $filename;
 5788: 	if (!$symbparm) { $symbparm=&symbread(); }
 5789: 	if ($symbparm) {
 5790: 	    $filename=(&decode_symb($symbparm))[2];
 5791: 	} else {
 5792: 	    $filename=$env{'request.filename'};
 5793: 	}
 5794: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5795: 	if (defined($metadata)) { return $metadata; }
 5796: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5797: 	if (defined($metadata)) { return $metadata; }
 5798: 
 5799: # ---------------------------------------------- fourth, look in rest pf course
 5800: 	if ($symbparm && defined($courseid) && 
 5801: 	    $courseid eq $env{'request.course.id'}) {
 5802: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5803: 				     $env{'course.'.$courseid.'.domain'},
 5804: 				     'course',
 5805: 				     ($courselevelm,$courselevel));
 5806: 	    if (defined($coursereply)) { return $coursereply; }
 5807: 	}
 5808: # ------------------------------------------------------------------ Cascade up
 5809: 	unless ($space eq '0') {
 5810: 	    my @parts=split(/_/,$space);
 5811: 	    my $id=pop(@parts);
 5812: 	    my $part=join('_',@parts);
 5813: 	    if ($part eq '') { $part='0'; }
 5814: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5815: 				 $symbparm,$udom,$uname,$section,1);
 5816: 	    if (defined($partgeneral)) { return $partgeneral; }
 5817: 	}
 5818: 	if ($recurse) { return undef; }
 5819: 	my $pack_def=&packages_tab_default($filename,$varname);
 5820: 	if (defined($pack_def)) { return $pack_def; }
 5821: 
 5822: # ---------------------------------------------------- Any other user namespace
 5823:     } elsif ($realm eq 'environment') {
 5824: # ----------------------------------------------------------------- environment
 5825: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5826: 	    return $env{'environment.'.$spacequalifierrest};
 5827: 	} else {
 5828: 	    if ($uname eq 'anonymous' && $udom eq '') {
 5829: 		return '';
 5830: 	    }
 5831: 	    my %returnhash=&userenvironment($udom,$uname,
 5832: 					    $spacequalifierrest);
 5833: 	    return $returnhash{$spacequalifierrest};
 5834: 	}
 5835:     } elsif ($realm eq 'system') {
 5836: # ----------------------------------------------------------------- system.time
 5837: 	if ($space eq 'time') {
 5838: 	    return time;
 5839:         }
 5840:     } elsif ($realm eq 'server') {
 5841: # ----------------------------------------------------------------- system.time
 5842: 	if ($space eq 'name') {
 5843: 	    return $ENV{'SERVER_NAME'};
 5844:         }
 5845:     }
 5846:     return '';
 5847: }
 5848: 
 5849: sub check_group_parms {
 5850:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5851:     my @groupitems = ();
 5852:     my $resultitem;
 5853:     my @levels = ($symbparm,$mapparm,$what);
 5854:     foreach my $group (@{$groups}) {
 5855:         foreach my $level (@levels) {
 5856:              my $item = $courseid.'.['.$group.'].'.$level;
 5857:              push(@groupitems,$item);
 5858:         }
 5859:     }
 5860:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5861:                             $env{'course.'.$courseid.'.domain'},
 5862:                                      'course',@groupitems);
 5863:     return $coursereply;
 5864: }
 5865: 
 5866: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5867:     my ($courseid,@groups) = @_;
 5868:     @groups = sort(@groups);
 5869:     return @groups;
 5870: }
 5871: 
 5872: sub packages_tab_default {
 5873:     my ($uri,$varname)=@_;
 5874:     my (undef,$part,$name)=split(/\./,$varname);
 5875: 
 5876:     my (@extension,@specifics,$do_default);
 5877:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5878: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5879: 	if ($pack_type eq 'default') {
 5880: 	    $do_default=1;
 5881: 	} elsif ($pack_type eq 'extension') {
 5882: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5883: 	} else {
 5884: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5885: 	}
 5886:     }
 5887:     # first look for a package that matches the requested part id
 5888:     foreach my $package (@specifics) {
 5889: 	my (undef,$pack_type,$pack_part)=@{$package};
 5890: 	next if ($pack_part ne $part);
 5891: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5892: 	    return $packagetab{"$pack_type&$name&default"};
 5893: 	}
 5894:     }
 5895:     # look for any possible matching non extension_ package
 5896:     foreach my $package (@specifics) {
 5897: 	my (undef,$pack_type,$pack_part)=@{$package};
 5898: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5899: 	    return $packagetab{"$pack_type&$name&default"};
 5900: 	}
 5901: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5902: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5903: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5904: 	}
 5905:     }
 5906:     # look for any posible extension_ match
 5907:     foreach my $package (@extension) {
 5908: 	my ($package,$pack_type)=@{$package};
 5909: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5910: 	    return $packagetab{"$pack_type&$name&default"};
 5911: 	}
 5912: 	if (defined($packagetab{$package."&$name&default"})) {
 5913: 	    return $packagetab{$package."&$name&default"};
 5914: 	}
 5915:     }
 5916:     # look for a global default setting
 5917:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5918: 	return $packagetab{"default&$name&default"};
 5919:     }
 5920:     return undef;
 5921: }
 5922: 
 5923: sub add_prefix_and_part {
 5924:     my ($prefix,$part)=@_;
 5925:     my $keyroot;
 5926:     if (defined($prefix) && $prefix !~ /^__/) {
 5927: 	# prefix that has a part already
 5928: 	$keyroot=$prefix;
 5929:     } elsif (defined($prefix)) {
 5930: 	# prefix that is missing a part
 5931: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 5932:     } else {
 5933: 	# no prefix at all
 5934: 	if (defined($part)) { $keyroot='_'.$part; }
 5935:     }
 5936:     return $keyroot;
 5937: }
 5938: 
 5939: # ---------------------------------------------------------------- Get metadata
 5940: 
 5941: my %metaentry;
 5942: sub metadata {
 5943:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 5944:     $uri=&declutter($uri);
 5945:     # if it is a non metadata possible uri return quickly
 5946:     if (($uri eq '') || 
 5947: 	(($uri =~ m|^/*adm/|) && 
 5948: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 5949:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 5950: 	($uri =~ m|home/[^/]+/public_html/|)) {
 5951: 	return undef;
 5952:     }
 5953:     my $filename=$uri;
 5954:     $uri=~s/\.meta$//;
 5955: #
 5956: # Is the metadata already cached?
 5957: # Look at timestamp of caching
 5958: # Everything is cached by the main uri, libraries are never directly cached
 5959: #
 5960:     if (!defined($liburi)) {
 5961: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 5962: 	if (defined($cached)) { return $result->{':'.$what}; }
 5963:     }
 5964:     {
 5965: #
 5966: # Is this a recursive call for a library?
 5967: #
 5968: #	if (! exists($metacache{$uri})) {
 5969: #	    $metacache{$uri}={};
 5970: #	}
 5971:         if ($liburi) {
 5972: 	    $liburi=&declutter($liburi);
 5973:             $filename=$liburi;
 5974:         } else {
 5975: 	    &devalidate_cache_new('meta',$uri);
 5976: 	    undef(%metaentry);
 5977: 	}
 5978:         my %metathesekeys=();
 5979:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 5980: 	my $metastring;
 5981: 	if ($uri !~ m -^(editupload)/-) {
 5982: 	    my $file=&filelocation('',&clutter($filename));
 5983: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 5984: 	    $metastring=&getfile($file);
 5985: 	}
 5986:         my $parser=HTML::LCParser->new(\$metastring);
 5987:         my $token;
 5988:         undef %metathesekeys;
 5989:         while ($token=$parser->get_token) {
 5990: 	    if ($token->[0] eq 'S') {
 5991: 		if (defined($token->[2]->{'package'})) {
 5992: #
 5993: # This is a package - get package info
 5994: #
 5995: 		    my $package=$token->[2]->{'package'};
 5996: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 5997: 		    if (defined($token->[2]->{'id'})) { 
 5998: 			$keyroot.='_'.$token->[2]->{'id'}; 
 5999: 		    }
 6000: 		    if ($metaentry{':packages'}) {
 6001: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6002: 		    } else {
 6003: 			$metaentry{':packages'}=$package.$keyroot;
 6004: 		    }
 6005: 		    foreach my $pack_entry (keys(%packagetab)) {
 6006: 			my $part=$keyroot;
 6007: 			$part=~s/^\_//;
 6008: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6009: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6010: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6011: 			    # ignore package.tab specified default values
 6012:                             # here &package_tab_default() will fetch those
 6013: 			    if ($subp eq 'default') { next; }
 6014: 			    my $value=$packagetab{$pack_entry};
 6015: 			    my $unikey;
 6016: 			    if ($pack =~ /_0$/) {
 6017: 				$unikey='parameter_0_'.$name;
 6018: 				$part=0;
 6019: 			    } else {
 6020: 				$unikey='parameter'.$keyroot.'_'.$name;
 6021: 			    }
 6022: 			    if ($subp eq 'display') {
 6023: 				$value.=' [Part: '.$part.']';
 6024: 			    }
 6025: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6026: 			    $metathesekeys{$unikey}=1;
 6027: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6028: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6029: 			    }
 6030: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6031: 				$metaentry{':'.$unikey}=
 6032: 				    $metaentry{':'.$unikey.'.default'};
 6033: 			    }
 6034: 			}
 6035: 		    }
 6036: 		} else {
 6037: #
 6038: # This is not a package - some other kind of start tag
 6039: #
 6040: 		    my $entry=$token->[1];
 6041: 		    my $unikey;
 6042: 		    if ($entry eq 'import') {
 6043: 			$unikey='';
 6044: 		    } else {
 6045: 			$unikey=$entry;
 6046: 		    }
 6047: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6048: 
 6049: 		    if (defined($token->[2]->{'id'})) { 
 6050: 			$unikey.='_'.$token->[2]->{'id'}; 
 6051: 		    }
 6052: 
 6053: 		    if ($entry eq 'import') {
 6054: #
 6055: # Importing a library here
 6056: #
 6057: 			if ($depthcount<20) {
 6058: 			    my $location=$parser->get_text('/import');
 6059: 			    my $dir=$filename;
 6060: 			    $dir=~s|[^/]*$||;
 6061: 			    $location=&filelocation($dir,$location);
 6062: 			    my $metadata = 
 6063: 				&metadata($uri,'keys', $location,$unikey,
 6064: 					  $depthcount+1);
 6065: 			    foreach my $meta (split(',',$metadata)) {
 6066: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6067: 				$metathesekeys{$meta}=1;
 6068: 			    }
 6069: 			}
 6070: 		    } else { 
 6071: 			
 6072: 			if (defined($token->[2]->{'name'})) { 
 6073: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6074: 			}
 6075: 			$metathesekeys{$unikey}=1;
 6076: 			foreach my $param (@{$token->[3]}) {
 6077: 			    $metaentry{':'.$unikey.'.'.$param} =
 6078: 				$token->[2]->{$param};
 6079: 			}
 6080: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6081: 			my $default=$metaentry{':'.$unikey.'.default'};
 6082: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6083: 		 # only ws inside the tag, and not in default, so use default
 6084: 		 # as value
 6085: 			    $metaentry{':'.$unikey}=$default;
 6086: 			} else {
 6087: 		  # either something interesting inside the tag or default
 6088:                   # uninteresting
 6089: 			    $metaentry{':'.$unikey}=$internaltext;
 6090: 			}
 6091: # end of not-a-package not-a-library import
 6092: 		    }
 6093: # end of not-a-package start tag
 6094: 		}
 6095: # the next is the end of "start tag"
 6096: 	    }
 6097: 	}
 6098: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6099: 	foreach my $key (keys(%packagetab)) {
 6100: 	    #no specific packages #how's our extension
 6101: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6102: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6103: 					 \%metathesekeys);
 6104: 	}
 6105: 	if (!exists($metaentry{':packages'})) {
 6106: 	    foreach my $key (keys(%packagetab)) {
 6107: 		#no specific packages well let's get default then
 6108: 		if ($key!~/^default&/) { next; }
 6109: 		&metadata_create_package_def($uri,$key,'default',
 6110: 					     \%metathesekeys);
 6111: 	    }
 6112: 	}
 6113: # are there custom rights to evaluate
 6114: 	if ($metaentry{':copyright'} eq 'custom') {
 6115: 
 6116:     #
 6117:     # Importing a rights file here
 6118:     #
 6119: 	    unless ($depthcount) {
 6120: 		my $location=$metaentry{':customdistributionfile'};
 6121: 		my $dir=$filename;
 6122: 		$dir=~s|[^/]*$||;
 6123: 		$location=&filelocation($dir,$location);
 6124: 		my $rights_metadata =
 6125: 		    &metadata($uri,'keys',$location,'_rights',
 6126: 			      $depthcount+1);
 6127: 		foreach my $rights (split(',',$rights_metadata)) {
 6128: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6129: 		    $metathesekeys{$rights}=1;
 6130: 		}
 6131: 	    }
 6132: 	}
 6133: 	# uniqifiy package listing
 6134: 	my %seen;
 6135: 	my @uniq_packages =
 6136: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6137: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6138: 
 6139: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6140: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6141: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6142: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6143: # this is the end of "was not already recently cached
 6144:     }
 6145:     return $metaentry{':'.$what};
 6146: }
 6147: 
 6148: sub metadata_create_package_def {
 6149:     my ($uri,$key,$package,$metathesekeys)=@_;
 6150:     my ($pack,$name,$subp)=split(/\&/,$key);
 6151:     if ($subp eq 'default') { next; }
 6152:     
 6153:     if (defined($metaentry{':packages'})) {
 6154: 	$metaentry{':packages'}.=','.$package;
 6155:     } else {
 6156: 	$metaentry{':packages'}=$package;
 6157:     }
 6158:     my $value=$packagetab{$key};
 6159:     my $unikey;
 6160:     $unikey='parameter_0_'.$name;
 6161:     $metaentry{':'.$unikey.'.part'}=0;
 6162:     $$metathesekeys{$unikey}=1;
 6163:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6164: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6165:     }
 6166:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6167: 	$metaentry{':'.$unikey}=
 6168: 	    $metaentry{':'.$unikey.'.default'};
 6169:     }
 6170: }
 6171: 
 6172: sub metadata_generate_part0 {
 6173:     my ($metadata,$metacache,$uri) = @_;
 6174:     my %allnames;
 6175:     foreach my $metakey (keys(%$metadata)) {
 6176: 	if ($metakey=~/^parameter\_(.*)/) {
 6177: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6178: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6179: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6180: 	    $allnames{$name}=$part;
 6181: 	  }
 6182: 	}
 6183:     }
 6184:     foreach my $name (keys(%allnames)) {
 6185:       $$metadata{"parameter_0_$name"}=1;
 6186:       my $key=":parameter_0_$name";
 6187:       $$metacache{"$key.part"}='0';
 6188:       $$metacache{"$key.name"}=$name;
 6189:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6190: 					   $allnames{$name}.'_'.$name.
 6191: 					   '.type'};
 6192:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6193: 			     '.display'};
 6194:       my $expr='[Part: '.$allnames{$name}.']';
 6195:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6196:       $$metacache{"$key.display"}=$olddis;
 6197:     }
 6198: }
 6199: 
 6200: # ------------------------------------------------------ Devalidate title cache
 6201: 
 6202: sub devalidate_title_cache {
 6203:     my ($url)=@_;
 6204:     if (!$env{'request.course.id'}) { return; }
 6205:     my $symb=&symbread($url);
 6206:     if (!$symb) { return; }
 6207:     my $key=$env{'request.course.id'}."\0".$symb;
 6208:     &devalidate_cache_new('title',$key);
 6209: }
 6210: 
 6211: # ------------------------------------------------- Get the title of a resource
 6212: 
 6213: sub gettitle {
 6214:     my $urlsymb=shift;
 6215:     my $symb=&symbread($urlsymb);
 6216:     if ($symb) {
 6217: 	my $key=$env{'request.course.id'}."\0".$symb;
 6218: 	my ($result,$cached)=&is_cached_new('title',$key);
 6219: 	if (defined($cached)) { 
 6220: 	    return $result;
 6221: 	}
 6222: 	my ($map,$resid,$url)=&decode_symb($symb);
 6223: 	my $title='';
 6224: 	my %bighash;
 6225: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6226: 		&GDBM_READER(),0640)) {
 6227: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6228: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6229: 	    untie %bighash;
 6230: 	}
 6231: 	$title=~s/\&colon\;/\:/gs;
 6232: 	if ($title) {
 6233: 	    return &do_cache_new('title',$key,$title,600);
 6234: 	}
 6235: 	$urlsymb=$url;
 6236:     }
 6237:     my $title=&metadata($urlsymb,'title');
 6238:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6239:     return $title;
 6240: }
 6241: 
 6242: sub get_slot {
 6243:     my ($which,$cnum,$cdom)=@_;
 6244:     if (!$cnum || !$cdom) {
 6245: 	(undef,my $courseid)=&whichuser();
 6246: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6247: 	$cnum=$env{'course.'.$courseid.'.num'};
 6248:     }
 6249:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6250:     my %slotinfo;
 6251:     if (exists($remembered{$key})) {
 6252: 	$slotinfo{$which} = $remembered{$key};
 6253:     } else {
 6254: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6255: 	&Apache::lonhomework::showhash(%slotinfo);
 6256: 	my ($tmp)=keys(%slotinfo);
 6257: 	if ($tmp=~/^error:/) { return (); }
 6258: 	$remembered{$key} = $slotinfo{$which};
 6259:     }
 6260:     if (ref($slotinfo{$which}) eq 'HASH') {
 6261: 	return %{$slotinfo{$which}};
 6262:     }
 6263:     return $slotinfo{$which};
 6264: }
 6265: # ------------------------------------------------- Update symbolic store links
 6266: 
 6267: sub symblist {
 6268:     my ($mapname,%newhash)=@_;
 6269:     $mapname=&deversion(&declutter($mapname));
 6270:     my %hash;
 6271:     if (($env{'request.course.fn'}) && (%newhash)) {
 6272:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6273:                       &GDBM_WRCREAT(),0640)) {
 6274: 	    foreach my $url (keys %newhash) {
 6275: 		next if ($url eq 'last_known'
 6276: 			 && $env{'form.no_update_last_known'});
 6277: 		$hash{declutter($url)}=&encode_symb($mapname,
 6278: 						    $newhash{$url}->[1],
 6279: 						    $newhash{$url}->[0]);
 6280:             }
 6281:             if (untie(%hash)) {
 6282: 		return 'ok';
 6283:             }
 6284:         }
 6285:     }
 6286:     return 'error';
 6287: }
 6288: 
 6289: # --------------------------------------------------------------- Verify a symb
 6290: 
 6291: sub symbverify {
 6292:     my ($symb,$thisurl)=@_;
 6293:     my $thisfn=$thisurl;
 6294:     $thisfn=&declutter($thisfn);
 6295: # direct jump to resource in page or to a sequence - will construct own symbs
 6296:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6297: # check URL part
 6298:     my ($map,$resid,$url)=&decode_symb($symb);
 6299: 
 6300:     unless ($url eq $thisfn) { return 0; }
 6301: 
 6302:     $symb=&symbclean($symb);
 6303:     $thisurl=&deversion($thisurl);
 6304:     $thisfn=&deversion($thisfn);
 6305: 
 6306:     my %bighash;
 6307:     my $okay=0;
 6308: 
 6309:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6310:                             &GDBM_READER(),0640)) {
 6311:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6312:         unless ($ids) { 
 6313:            $ids=$bighash{'ids_/'.$thisurl};
 6314:         }
 6315:         if ($ids) {
 6316: # ------------------------------------------------------------------- Has ID(s)
 6317: 	    foreach my $id (split(/\,/,$ids)) {
 6318: 	       my ($mapid,$resid)=split(/\./,$id);
 6319:                if (
 6320:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6321:    eq $symb) { 
 6322: 		   if (($env{'request.role.adv'}) ||
 6323: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6324: 		       $okay=1; 
 6325: 		   }
 6326: 	       }
 6327: 	   }
 6328:         }
 6329: 	untie(%bighash);
 6330:     }
 6331:     return $okay;
 6332: }
 6333: 
 6334: # --------------------------------------------------------------- Clean-up symb
 6335: 
 6336: sub symbclean {
 6337:     my $symb=shift;
 6338:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6339: # remove version from map
 6340:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6341: 
 6342: # remove version from URL
 6343:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6344: 
 6345: # remove wrapper
 6346: 
 6347:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6348:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6349:     return $symb;
 6350: }
 6351: 
 6352: # ---------------------------------------------- Split symb to find map and url
 6353: 
 6354: sub encode_symb {
 6355:     my ($map,$resid,$url)=@_;
 6356:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6357: }
 6358: 
 6359: sub decode_symb {
 6360:     my $symb=shift;
 6361:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6362:     my ($map,$resid,$url)=split(/___/,$symb);
 6363:     return (&fixversion($map),$resid,&fixversion($url));
 6364: }
 6365: 
 6366: sub fixversion {
 6367:     my $fn=shift;
 6368:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6369:     my %bighash;
 6370:     my $uri=&clutter($fn);
 6371:     my $key=$env{'request.course.id'}.'_'.$uri;
 6372: # is this cached?
 6373:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6374:     if (defined($cached)) { return $result; }
 6375: # unfortunately not cached, or expired
 6376:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6377: 	    &GDBM_READER(),0640)) {
 6378:  	if ($bighash{'version_'.$uri}) {
 6379:  	    my $version=$bighash{'version_'.$uri};
 6380:  	    unless (($version eq 'mostrecent') || 
 6381: 		    ($version==&getversion($uri))) {
 6382:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6383:  	    }
 6384:  	}
 6385:  	untie %bighash;
 6386:     }
 6387:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6388: }
 6389: 
 6390: sub deversion {
 6391:     my $url=shift;
 6392:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6393:     return $url;
 6394: }
 6395: 
 6396: # ------------------------------------------------------ Return symb list entry
 6397: 
 6398: sub symbread {
 6399:     my ($thisfn,$donotrecurse)=@_;
 6400:     my $cache_str='request.symbread.cached.'.$thisfn;
 6401:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6402: # no filename provided? try from environment
 6403:     unless ($thisfn) {
 6404:         if ($env{'request.symb'}) {
 6405: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6406: 	}
 6407: 	$thisfn=$env{'request.filename'};
 6408:     }
 6409:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6410: # is that filename actually a symb? Verify, clean, and return
 6411:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6412: 	if (&symbverify($thisfn,$1)) {
 6413: 	    return $env{$cache_str}=&symbclean($thisfn);
 6414: 	}
 6415:     }
 6416:     $thisfn=declutter($thisfn);
 6417:     my %hash;
 6418:     my %bighash;
 6419:     my $syval='';
 6420:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6421:         my $targetfn = $thisfn;
 6422:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6423:             $targetfn = 'adm/wrapper/'.$thisfn;
 6424:         }
 6425: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6426: 	    $targetfn=$1;
 6427: 	}
 6428:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6429:                       &GDBM_READER(),0640)) {
 6430: 	    $syval=$hash{$targetfn};
 6431:             untie(%hash);
 6432:         }
 6433: # ---------------------------------------------------------- There was an entry
 6434:         if ($syval) {
 6435: 	    #unless ($syval=~/\_\d+$/) {
 6436: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6437: 		    #&appenv('request.ambiguous' => $thisfn);
 6438: 		    #return $env{$cache_str}='';
 6439: 		#}    
 6440: 		#$syval.=$1;
 6441: 	    #}
 6442:         } else {
 6443: # ------------------------------------------------------- Was not in symb table
 6444:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6445:                             &GDBM_READER(),0640)) {
 6446: # ---------------------------------------------- Get ID(s) for current resource
 6447:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6448:               unless ($ids) { 
 6449:                  $ids=$bighash{'ids_/'.$thisfn};
 6450:               }
 6451:               unless ($ids) {
 6452: # alias?
 6453: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6454:               }
 6455:               if ($ids) {
 6456: # ------------------------------------------------------------------- Has ID(s)
 6457:                  my @possibilities=split(/\,/,$ids);
 6458:                  if ($#possibilities==0) {
 6459: # ----------------------------------------------- There is only one possibility
 6460: 		     my ($mapid,$resid)=split(/\./,$ids);
 6461: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6462: 						    $resid,$thisfn);
 6463:                  } elsif (!$donotrecurse) {
 6464: # ------------------------------------------ There is more than one possibility
 6465:                      my $realpossible=0;
 6466:                      foreach my $id (@possibilities) {
 6467: 			 my $file=$bighash{'src_'.$id};
 6468:                          if (&allowed('bre',$file)) {
 6469:          		    my ($mapid,$resid)=split(/\./,$id);
 6470:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6471: 				$realpossible++;
 6472:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6473: 						    $resid,$thisfn);
 6474:                             }
 6475: 			 }
 6476:                      }
 6477: 		     if ($realpossible!=1) { $syval=''; }
 6478:                  } else {
 6479:                      $syval='';
 6480:                  }
 6481: 	      }
 6482:               untie(%bighash)
 6483:            }
 6484:         }
 6485:         if ($syval) {
 6486: 	    return $env{$cache_str}=$syval;
 6487:         }
 6488:     }
 6489:     &appenv('request.ambiguous' => $thisfn);
 6490:     return $env{$cache_str}='';
 6491: }
 6492: 
 6493: # ---------------------------------------------------------- Return random seed
 6494: 
 6495: sub numval {
 6496:     my $txt=shift;
 6497:     $txt=~tr/A-J/0-9/;
 6498:     $txt=~tr/a-j/0-9/;
 6499:     $txt=~tr/K-T/0-9/;
 6500:     $txt=~tr/k-t/0-9/;
 6501:     $txt=~tr/U-Z/0-5/;
 6502:     $txt=~tr/u-z/0-5/;
 6503:     $txt=~s/\D//g;
 6504:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6505:     return int($txt);
 6506: }
 6507: 
 6508: sub numval2 {
 6509:     my $txt=shift;
 6510:     $txt=~tr/A-J/0-9/;
 6511:     $txt=~tr/a-j/0-9/;
 6512:     $txt=~tr/K-T/0-9/;
 6513:     $txt=~tr/k-t/0-9/;
 6514:     $txt=~tr/U-Z/0-5/;
 6515:     $txt=~tr/u-z/0-5/;
 6516:     $txt=~s/\D//g;
 6517:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6518:     my $total;
 6519:     foreach my $val (@txts) { $total+=$val; }
 6520:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6521:     return int($total);
 6522: }
 6523: 
 6524: sub numval3 {
 6525:     use integer;
 6526:     my $txt=shift;
 6527:     $txt=~tr/A-J/0-9/;
 6528:     $txt=~tr/a-j/0-9/;
 6529:     $txt=~tr/K-T/0-9/;
 6530:     $txt=~tr/k-t/0-9/;
 6531:     $txt=~tr/U-Z/0-5/;
 6532:     $txt=~tr/u-z/0-5/;
 6533:     $txt=~s/\D//g;
 6534:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6535:     my $total;
 6536:     foreach my $val (@txts) { $total+=$val; }
 6537:     if ($_64bit) { $total=(($total<<32)>>32); }
 6538:     return $total;
 6539: }
 6540: 
 6541: sub digest {
 6542:     my ($data)=@_;
 6543:     my $digest=&Digest::MD5::md5($data);
 6544:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6545:     my ($e,$f);
 6546:     {
 6547:         use integer;
 6548:         $e=($a+$b);
 6549:         $f=($c+$d);
 6550:         if ($_64bit) {
 6551:             $e=(($e<<32)>>32);
 6552:             $f=(($f<<32)>>32);
 6553:         }
 6554:     }
 6555:     if (wantarray) {
 6556: 	return ($e,$f);
 6557:     } else {
 6558: 	my $g;
 6559: 	{
 6560: 	    use integer;
 6561: 	    $g=($e+$f);
 6562: 	    if ($_64bit) {
 6563: 		$g=(($g<<32)>>32);
 6564: 	    }
 6565: 	}
 6566: 	return $g;
 6567:     }
 6568: }
 6569: 
 6570: sub latest_rnd_algorithm_id {
 6571:     return '64bit5';
 6572: }
 6573: 
 6574: sub get_rand_alg {
 6575:     my ($courseid)=@_;
 6576:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6577:     if ($courseid) {
 6578: 	return $env{"course.$courseid.rndseed"};
 6579:     }
 6580:     return &latest_rnd_algorithm_id();
 6581: }
 6582: 
 6583: sub validCODE {
 6584:     my ($CODE)=@_;
 6585:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6586:     return 0;
 6587: }
 6588: 
 6589: sub getCODE {
 6590:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6591:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6592: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6593: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6594: 	return $Apache::lonhomework::history{'resource.CODE'};
 6595:     }
 6596:     return undef;
 6597: }
 6598: 
 6599: sub rndseed {
 6600:     my ($symb,$courseid,$domain,$username)=@_;
 6601: 
 6602:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6603:     if (!$symb) {
 6604: 	unless ($symb=$wsymb) { return time; }
 6605:     }
 6606:     if (!$courseid) { $courseid=$wcourseid; }
 6607:     if (!$domain) { $domain=$wdomain; }
 6608:     if (!$username) { $username=$wusername }
 6609:     my $which=&get_rand_alg();
 6610:     if (defined(&getCODE())) {
 6611: 	if ($which eq '64bit5') {
 6612: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6613: 	} elsif ($which eq '64bit4') {
 6614: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6615: 	} else {
 6616: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6617: 	}
 6618:     } elsif ($which eq '64bit5') {
 6619: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6620:     } elsif ($which eq '64bit4') {
 6621: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6622:     } elsif ($which eq '64bit3') {
 6623: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6624:     } elsif ($which eq '64bit2') {
 6625: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6626:     } elsif ($which eq '64bit') {
 6627: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6628:     }
 6629:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6630: }
 6631: 
 6632: sub rndseed_32bit {
 6633:     my ($symb,$courseid,$domain,$username)=@_;
 6634:     {
 6635: 	use integer;
 6636: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6637: 	my $symbseed=numval($symb) << 22;
 6638: 	my $namechck=unpack("%32C*",$username) << 17;
 6639: 	my $nameseed=numval($username) << 12;
 6640: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6641: 	my $courseseed=unpack("%32C*",$courseid);
 6642: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6643: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6644: 	#&logthis("rndseed :$num:$symb");
 6645: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6646: 	return $num;
 6647:     }
 6648: }
 6649: 
 6650: sub rndseed_64bit {
 6651:     my ($symb,$courseid,$domain,$username)=@_;
 6652:     {
 6653: 	use integer;
 6654: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6655: 	my $symbseed=numval($symb) << 10;
 6656: 	my $namechck=unpack("%32S*",$username);
 6657: 	
 6658: 	my $nameseed=numval($username) << 21;
 6659: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6660: 	my $courseseed=unpack("%32S*",$courseid);
 6661: 	
 6662: 	my $num1=$symbchck+$symbseed+$namechck;
 6663: 	my $num2=$nameseed+$domainseed+$courseseed;
 6664: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6665: 	#&logthis("rndseed :$num:$symb");
 6666: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6667: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6668: 	return "$num1,$num2";
 6669:     }
 6670: }
 6671: 
 6672: sub rndseed_64bit2 {
 6673:     my ($symb,$courseid,$domain,$username)=@_;
 6674:     {
 6675: 	use integer;
 6676: 	# strings need to be an even # of cahracters long, it it is odd the
 6677:         # last characters gets thrown away
 6678: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6679: 	my $symbseed=numval($symb) << 10;
 6680: 	my $namechck=unpack("%32S*",$username.' ');
 6681: 	
 6682: 	my $nameseed=numval($username) << 21;
 6683: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6684: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6685: 	
 6686: 	my $num1=$symbchck+$symbseed+$namechck;
 6687: 	my $num2=$nameseed+$domainseed+$courseseed;
 6688: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6689: 	#&logthis("rndseed :$num:$symb");
 6690: 	return "$num1,$num2";
 6691:     }
 6692: }
 6693: 
 6694: sub rndseed_64bit3 {
 6695:     my ($symb,$courseid,$domain,$username)=@_;
 6696:     {
 6697: 	use integer;
 6698: 	# strings need to be an even # of cahracters long, it it is odd the
 6699:         # last characters gets thrown away
 6700: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6701: 	my $symbseed=numval2($symb) << 10;
 6702: 	my $namechck=unpack("%32S*",$username.' ');
 6703: 	
 6704: 	my $nameseed=numval2($username) << 21;
 6705: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6706: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6707: 	
 6708: 	my $num1=$symbchck+$symbseed+$namechck;
 6709: 	my $num2=$nameseed+$domainseed+$courseseed;
 6710: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6711: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 6712: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6713: 	
 6714: 	return "$num1:$num2";
 6715:     }
 6716: }
 6717: 
 6718: sub rndseed_64bit4 {
 6719:     my ($symb,$courseid,$domain,$username)=@_;
 6720:     {
 6721: 	use integer;
 6722: 	# strings need to be an even # of cahracters long, it it is odd the
 6723:         # last characters gets thrown away
 6724: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6725: 	my $symbseed=numval3($symb) << 10;
 6726: 	my $namechck=unpack("%32S*",$username.' ');
 6727: 	
 6728: 	my $nameseed=numval3($username) << 21;
 6729: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6730: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6731: 	
 6732: 	my $num1=$symbchck+$symbseed+$namechck;
 6733: 	my $num2=$nameseed+$domainseed+$courseseed;
 6734: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6735: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 6736: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6737: 	
 6738: 	return "$num1:$num2";
 6739:     }
 6740: }
 6741: 
 6742: sub rndseed_64bit5 {
 6743:     my ($symb,$courseid,$domain,$username)=@_;
 6744:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6745:     return "$num1:$num2";
 6746: }
 6747: 
 6748: sub rndseed_CODE_64bit {
 6749:     my ($symb,$courseid,$domain,$username)=@_;
 6750:     {
 6751: 	use integer;
 6752: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6753: 	my $symbseed=numval2($symb);
 6754: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6755: 	my $CODEseed=numval(&getCODE());
 6756: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6757: 	my $num1=$symbseed+$CODEchck;
 6758: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6759: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6760: 	#&logthis("rndseed :$num1:$num2:$symb");
 6761: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6762: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6763: 	return "$num1:$num2";
 6764:     }
 6765: }
 6766: 
 6767: sub rndseed_CODE_64bit4 {
 6768:     my ($symb,$courseid,$domain,$username)=@_;
 6769:     {
 6770: 	use integer;
 6771: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6772: 	my $symbseed=numval3($symb);
 6773: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6774: 	my $CODEseed=numval3(&getCODE());
 6775: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6776: 	my $num1=$symbseed+$CODEchck;
 6777: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6778: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6779: 	#&logthis("rndseed :$num1:$num2:$symb");
 6780: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6781: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6782: 	return "$num1:$num2";
 6783:     }
 6784: }
 6785: 
 6786: sub rndseed_CODE_64bit5 {
 6787:     my ($symb,$courseid,$domain,$username)=@_;
 6788:     my $code = &getCODE();
 6789:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6790:     return "$num1:$num2";
 6791: }
 6792: 
 6793: sub setup_random_from_rndseed {
 6794:     my ($rndseed)=@_;
 6795:     if ($rndseed =~/([,:])/) {
 6796: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6797: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6798:     } else {
 6799: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6800:     }
 6801: }
 6802: 
 6803: sub latest_receipt_algorithm_id {
 6804:     return 'receipt2';
 6805: }
 6806: 
 6807: sub recunique {
 6808:     my $fucourseid=shift;
 6809:     my $unique;
 6810:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6811: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6812:     } else {
 6813: 	$unique=$perlvar{'lonReceipt'};
 6814:     }
 6815:     return unpack("%32C*",$unique);
 6816: }
 6817: 
 6818: sub recprefix {
 6819:     my $fucourseid=shift;
 6820:     my $prefix;
 6821:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6822: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6823:     } else {
 6824: 	$prefix=$perlvar{'lonHostID'};
 6825:     }
 6826:     return unpack("%32C*",$prefix);
 6827: }
 6828: 
 6829: sub ireceipt {
 6830:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6831:     my $cuname=unpack("%32C*",$funame);
 6832:     my $cudom=unpack("%32C*",$fudom);
 6833:     my $cucourseid=unpack("%32C*",$fucourseid);
 6834:     my $cusymb=unpack("%32C*",$fusymb);
 6835:     my $cunique=&recunique($fucourseid);
 6836:     my $cpart=unpack("%32S*",$part);
 6837:     my $return =&recprefix($fucourseid).'-';
 6838:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6839: 	$env{'request.state'} eq 'construct') {
 6840: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 6841: 			       
 6842: 	$return.= ($cunique%$cuname+
 6843: 		   $cunique%$cudom+
 6844: 		   $cusymb%$cuname+
 6845: 		   $cusymb%$cudom+
 6846: 		   $cucourseid%$cuname+
 6847: 		   $cucourseid%$cudom+
 6848: 		   $cpart%$cuname+
 6849: 		   $cpart%$cudom);
 6850:     } else {
 6851: 	$return.= ($cunique%$cuname+
 6852: 		   $cunique%$cudom+
 6853: 		   $cusymb%$cuname+
 6854: 		   $cusymb%$cudom+
 6855: 		   $cucourseid%$cuname+
 6856: 		   $cucourseid%$cudom);
 6857:     }
 6858:     return $return;
 6859: }
 6860: 
 6861: sub receipt {
 6862:     my ($part)=@_;
 6863:     my ($symb,$courseid,$domain,$name) = &whichuser();
 6864:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6865: }
 6866: 
 6867: sub whichuser {
 6868:     my ($passedsymb)=@_;
 6869:     my ($symb,$courseid,$domain,$name,$publicuser);
 6870:     if (defined($env{'form.grade_symb'})) {
 6871: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 6872: 	my $allowed=&allowed('vgr',$tmp_courseid);
 6873: 	if (!$allowed &&
 6874: 	    exists($env{'request.course.sec'}) &&
 6875: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 6876: 	    $allowed=&allowed('vgr',$tmp_courseid.
 6877: 			      '/'.$env{'request.course.sec'});
 6878: 	}
 6879: 	if ($allowed) {
 6880: 	    ($symb)=&get_env_multiple('form.grade_symb');
 6881: 	    $courseid=$tmp_courseid;
 6882: 	    ($domain)=&get_env_multiple('form.grade_domain');
 6883: 	    ($name)=&get_env_multiple('form.grade_username');
 6884: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 6885: 	}
 6886:     }
 6887:     if (!$passedsymb) {
 6888: 	$symb=&symbread();
 6889:     } else {
 6890: 	$symb=$passedsymb;
 6891:     }
 6892:     $courseid=$env{'request.course.id'};
 6893:     $domain=$env{'user.domain'};
 6894:     $name=$env{'user.name'};
 6895:     if ($name eq 'public' && $domain eq 'public') {
 6896: 	if (!defined($env{'form.username'})) {
 6897: 	    $env{'form.username'}.=time.rand(10000000);
 6898: 	}
 6899: 	$name.=$env{'form.username'};
 6900:     }
 6901:     return ($symb,$courseid,$domain,$name,$publicuser);
 6902: 
 6903: }
 6904: 
 6905: # ------------------------------------------------------------ Serves up a file
 6906: # returns either the contents of the file or 
 6907: # -1 if the file doesn't exist
 6908: #
 6909: # if the target is a file that was uploaded via DOCS, 
 6910: # a check will be made to see if a current copy exists on the local server,
 6911: # if it does this will be served, otherwise a copy will be retrieved from
 6912: # the home server for the course and stored in /home/httpd/html/userfiles on
 6913: # the local server.   
 6914: 
 6915: sub getfile {
 6916:     my ($file) = @_;
 6917:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6918:     &repcopy($file);
 6919:     return &readfile($file);
 6920: }
 6921: 
 6922: sub repcopy_userfile {
 6923:     my ($file)=@_;
 6924:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6925:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 6926:     my ($cdom,$cnum,$filename) = 
 6927: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 6928:     my ($info,$rtncode);
 6929:     my $uri="/uploaded/$cdom/$cnum/$filename";
 6930:     if (-e "$file") {
 6931: 	my @fileinfo = stat($file);
 6932: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 6933: 	if ($lwpresp ne 'ok') {
 6934: 	    if ($rtncode eq '404') {
 6935: 		unlink($file);
 6936: 	    }
 6937: 	    #my $ua=new LWP::UserAgent;
 6938: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6939: 	    #my $response=$ua->request($request);
 6940: 	    #if ($response->is_success()) {
 6941: 	#	return $response->content;
 6942: 	#    } else {
 6943: 	#	return -1;
 6944: 	#    }
 6945: 	    return -1;
 6946: 	}
 6947: 	if ($info < $fileinfo[9]) {
 6948: 	    return 'ok';
 6949: 	}
 6950: 	$info = '';
 6951: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6952: 	if ($lwpresp ne 'ok') {
 6953: 	    return -1;
 6954: 	}
 6955:     } else {
 6956: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 6957: 	if ($lwpresp ne 'ok') {
 6958: 	    my $ua=new LWP::UserAgent;
 6959: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 6960: 	    my $response=$ua->request($request);
 6961: 	    if ($response->is_success()) {
 6962: 		$info=$response->content;
 6963: 	    } else {
 6964: 		return -1;
 6965: 	    }
 6966: 	}
 6967: 	my @parts = ($cdom,$cnum); 
 6968: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 6969: 	    push @parts, split(/\//,$1);
 6970: 	}
 6971: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 6972: 	foreach my $part (@parts) {
 6973: 	    $path .= '/'.$part;
 6974: 	    if (!-e $path) {
 6975: 		mkdir($path,0770);
 6976: 	    }
 6977: 	}
 6978:     }
 6979:     open(FILE,">$file");
 6980:     print FILE $info;
 6981:     close(FILE);
 6982:     return 'ok';
 6983: }
 6984: 
 6985: sub tokenwrapper {
 6986:     my $uri=shift;
 6987:     $uri=~s|^http\://([^/]+)||;
 6988:     $uri=~s|^/||;
 6989:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 6990:     my $token=$1;
 6991:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 6992:     if ($udom && $uname && $file) {
 6993: 	$file=~s|(\?\.*)*$||;
 6994:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 6995:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 6996:                (($uri=~/\?/)?'&':'?').'token='.$token.
 6997:                                '&tokenissued='.$perlvar{'lonHostID'};
 6998:     } else {
 6999:         return '/adm/notfound.html';
 7000:     }
 7001: }
 7002: 
 7003: sub getuploaded {
 7004:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7005:     $uri=~s/^\///;
 7006:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 7007:     my $ua=new LWP::UserAgent;
 7008:     my $request=new HTTP::Request($reqtype,$uri);
 7009:     my $response=$ua->request($request);
 7010:     $$rtncode = $response->code;
 7011:     if (! $response->is_success()) {
 7012: 	return 'failed';
 7013:     }      
 7014:     if ($reqtype eq 'HEAD') {
 7015: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7016:     } elsif ($reqtype eq 'GET') {
 7017: 	$$info = $response->content;
 7018:     }
 7019:     return 'ok';
 7020: }
 7021: 
 7022: sub readfile {
 7023:     my $file = shift;
 7024:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7025:     my $fh;
 7026:     open($fh,"<$file");
 7027:     my $a='';
 7028:     while (my $line = <$fh>) { $a .= $line; }
 7029:     return $a;
 7030: }
 7031: 
 7032: sub filelocation {
 7033:     my ($dir,$file) = @_;
 7034:     my $location;
 7035:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7036: 
 7037:     if ($file =~ m-^/adm/-) {
 7038: 	$file=~s-^/adm/wrapper/-/-;
 7039: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7040:     }
 7041:     if ($file=~m:^/~:) { # is a contruction space reference
 7042:         $location = $file;
 7043:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7044:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 7045: 	# is a correct contruction space reference
 7046:         $location = $file;
 7047:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7048:         my ($udom,$uname,$filename)=
 7049:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 7050:         my $home=&homeserver($uname,$udom);
 7051:         my $is_me=0;
 7052:         my @ids=&current_machine_ids();
 7053:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7054:         if ($is_me) {
 7055:   	    $location=&propath($udom,$uname).
 7056:   	      '/userfiles/'.$filename;
 7057:         } else {
 7058:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7059:   	      $udom.'/'.$uname.'/'.$filename;
 7060:         }
 7061:     } else {
 7062:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7063:         $file=~s:^/res/:/:;
 7064:         if ( !( $file =~ m:^/:) ) {
 7065:             $location = $dir. '/'.$file;
 7066:         } else {
 7067:             $location = '/home/httpd/html/res'.$file;
 7068:         }
 7069:     }
 7070:     $location=~s://+:/:g; # remove duplicate /
 7071:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7072:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7073:     return $location;
 7074: }
 7075: 
 7076: sub hreflocation {
 7077:     my ($dir,$file)=@_;
 7078:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7079: 	$file=filelocation($dir,$file);
 7080:     } elsif ($file=~m-^/adm/-) {
 7081: 	$file=~s-^/adm/wrapper/-/-;
 7082: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7083:     }
 7084:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7085: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7086:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 7087: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 7088:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7089: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 7090: 	    -/uploaded/$1/$2/-x;
 7091:     }
 7092:     return $file;
 7093: }
 7094: 
 7095: sub current_machine_domains {
 7096:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7097:     my @domains;
 7098:     while( my($id, $name) = each(%hostname)) {
 7099: #	&logthis("-$id-$name-$hostname-");
 7100: 	if ($hostname eq $name) {
 7101: 	    push(@domains,$hostdom{$id});
 7102: 	}
 7103:     }
 7104:     return @domains;
 7105: }
 7106: 
 7107: sub current_machine_ids {
 7108:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7109:     my @ids;
 7110:     while( my($id, $name) = each(%hostname)) {
 7111: #	&logthis("-$id-$name-$hostname-");
 7112: 	if ($hostname eq $name) {
 7113: 	    push(@ids,$id);
 7114: 	}
 7115:     }
 7116:     return @ids;
 7117: }
 7118: 
 7119: # ------------------------------------------------------------- Declutters URLs
 7120: 
 7121: sub declutter {
 7122:     my $thisfn=shift;
 7123:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7124:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7125:     $thisfn=~s/^\///;
 7126:     $thisfn=~s|^adm/wrapper/||;
 7127:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7128:     $thisfn=~s/^res\///;
 7129:     $thisfn=~s/\?.+$//;
 7130:     return $thisfn;
 7131: }
 7132: 
 7133: # ------------------------------------------------------------- Clutter up URLs
 7134: 
 7135: sub clutter {
 7136:     my $thisfn='/'.&declutter(shift);
 7137:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7138:        $thisfn='/res'.$thisfn; 
 7139:     }
 7140:     if ($thisfn !~m|/adm|) {
 7141: 	if ($thisfn =~ m|/ext/|) {
 7142: 	    $thisfn='/adm/wrapper'.$thisfn;
 7143: 	} else {
 7144: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7145: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7146: 	    if ($embstyle eq 'ssi'
 7147: 		|| ($embstyle eq 'hdn')
 7148: 		|| ($embstyle eq 'rat')
 7149: 		|| ($embstyle eq 'prv')
 7150: 		|| ($embstyle eq 'ign')) {
 7151: 		#do nothing with these
 7152: 	    } elsif (($embstyle eq 'img') 
 7153: 		|| ($embstyle eq 'emb')
 7154: 		|| ($embstyle eq 'wrp')) {
 7155: 		$thisfn='/adm/wrapper'.$thisfn;
 7156: 	    } elsif ($embstyle eq 'unk'
 7157: 		     && $thisfn!~/\.(sequence|page)$/) {
 7158: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7159: 	    } else {
 7160: #		&logthis("Got a blank emb style");
 7161: 	    }
 7162: 	}
 7163:     }
 7164:     return $thisfn;
 7165: }
 7166: 
 7167: sub clutter_with_no_wrapper {
 7168:     my $uri = &clutter(shift);
 7169:     if ($uri =~ m-^/adm/-) {
 7170: 	$uri =~ s-^/adm/wrapper/-/-;
 7171: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7172:     }
 7173:     return $uri;
 7174: }
 7175: 
 7176: sub freeze_escape {
 7177:     my ($value)=@_;
 7178:     if (ref($value)) {
 7179: 	$value=&nfreeze($value);
 7180: 	return '__FROZEN__'.&escape($value);
 7181:     }
 7182:     return &escape($value);
 7183: }
 7184: 
 7185: 
 7186: sub thaw_unescape {
 7187:     my ($value)=@_;
 7188:     if ($value =~ /^__FROZEN__/) {
 7189: 	substr($value,0,10,undef);
 7190: 	$value=&unescape($value);
 7191: 	return &thaw($value);
 7192:     }
 7193:     return &unescape($value);
 7194: }
 7195: 
 7196: sub correct_line_ends {
 7197:     my ($result)=@_;
 7198:     $$result =~s/\r\n/\n/mg;
 7199:     $$result =~s/\r/\n/mg;
 7200: }
 7201: # ================================================================ Main Program
 7202: 
 7203: sub goodbye {
 7204:    &logthis("Starting Shut down");
 7205: #not converted to using infrastruture and probably shouldn't be
 7206:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7207: #converted
 7208: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7209:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7210: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7211: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7212: #1.1 only
 7213: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7214: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7215: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7216: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7217:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7218:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7219:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7220:    &flushcourselogs();
 7221:    &logthis("Shutting down");
 7222: }
 7223: 
 7224: BEGIN {
 7225: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7226:     unless ($readit) {
 7227: {
 7228:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7229:     %perlvar = (%perlvar,%{$configvars});
 7230: }
 7231: 
 7232: # ------------------------------------------------------------ Read domain file
 7233: {
 7234:     %domaindescription = ();
 7235:     %domain_auth_def = ();
 7236:     %domain_auth_arg_def = ();
 7237:     my $fh;
 7238:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7239: 	while (my $line = <$fh>) {
 7240:            next if ($line =~ /^(\#|\s*$)/);
 7241: #           next if /^\#/;
 7242:            chomp $line;
 7243:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7244: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
 7245: 	   $domain_auth_def{$domain}=$def_auth;
 7246:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7247: 	   $domaindescription{$domain}=$domain_description;
 7248: 	   $domain_lang_def{$domain}=$def_lang;
 7249: 	   $domain_city{$domain}=$city;
 7250: 	   $domain_longi{$domain}=$longi;
 7251: 	   $domain_lati{$domain}=$lati;
 7252:            $domain_primary{$domain}=$primary;
 7253: 
 7254:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7255: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7256: 	}
 7257:     }
 7258:     close ($fh);
 7259: }
 7260: 
 7261: 
 7262: # ------------------------------------------------------------- Read hosts file
 7263: {
 7264:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7265: 
 7266:     while (my $configline=<$config>) {
 7267:        next if ($configline =~ /^(\#|\s*$)/);
 7268:        chomp($configline);
 7269:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7270:        $name=~s/\s//g;
 7271:        if ($id && $domain && $role && $name) {
 7272: 	 $hostname{$id}=$name;
 7273: 	 $hostdom{$id}=$domain;
 7274: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7275:        }
 7276:     }
 7277:     close($config);
 7278:     # FIXME: dev server don't want this, production servers _do_ want this
 7279:     #&get_iphost();
 7280: }
 7281: 
 7282: sub get_iphost {
 7283:     if (%iphost) { return %iphost; }
 7284:     my %name_to_ip;
 7285:     foreach my $id (keys(%hostname)) {
 7286: 	my $name=$hostname{$id};
 7287: 	my $ip;
 7288: 	if (!exists($name_to_ip{$name})) {
 7289: 	    $ip = gethostbyname($name);
 7290: 	    if (!$ip || length($ip) ne 4) {
 7291: 		&logthis("Skipping host $id name $name no IP found\n");
 7292: 		next;
 7293: 	    }
 7294: 	    $ip=inet_ntoa($ip);
 7295: 	    $name_to_ip{$name} = $ip;
 7296: 	} else {
 7297: 	    $ip = $name_to_ip{$name};
 7298: 	}
 7299: 	push(@{$iphost{$ip}},$id);
 7300:     }
 7301:     return %iphost;
 7302: }
 7303: 
 7304: # ------------------------------------------------------ Read spare server file
 7305: {
 7306:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7307: 
 7308:     while (my $configline=<$config>) {
 7309:        chomp($configline);
 7310:        if ($configline) {
 7311: 	   my ($host,$type) = split(':',$configline,2);
 7312: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7313: 	   push(@{ $spareid{$type} }, $host);
 7314:        }
 7315:     }
 7316:     close($config);
 7317: }
 7318: # ------------------------------------------------------------ Read permissions
 7319: {
 7320:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7321: 
 7322:     while (my $configline=<$config>) {
 7323: 	chomp($configline);
 7324: 	if ($configline) {
 7325: 	    my ($role,$perm)=split(/ /,$configline);
 7326: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7327: 	}
 7328:     }
 7329:     close($config);
 7330: }
 7331: 
 7332: # -------------------------------------------- Read plain texts for permissions
 7333: {
 7334:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7335: 
 7336:     while (my $configline=<$config>) {
 7337: 	chomp($configline);
 7338: 	if ($configline) {
 7339: 	    my ($short,@plain)=split(/:/,$configline);
 7340:             %{$prp{$short}} = ();
 7341: 	    if (@plain > 0) {
 7342:                 $prp{$short}{'std'} = $plain[0];
 7343:                 for (my $i=1; $i<@plain; $i++) {
 7344:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7345:                 }
 7346:             }
 7347: 	}
 7348:     }
 7349:     close($config);
 7350: }
 7351: 
 7352: # ---------------------------------------------------------- Read package table
 7353: {
 7354:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7355: 
 7356:     while (my $configline=<$config>) {
 7357: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7358: 	chomp($configline);
 7359: 	my ($short,$plain)=split(/:/,$configline);
 7360: 	my ($pack,$name)=split(/\&/,$short);
 7361: 	if ($plain ne '') {
 7362: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7363: 	    $packagetab{$short}=$plain; 
 7364: 	}
 7365:     }
 7366:     close($config);
 7367: }
 7368: 
 7369: # ------------- set up temporary directory
 7370: {
 7371:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7372: 
 7373: }
 7374: 
 7375: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7376: 				'compress_threshold'=> 20_000,
 7377:  			        });
 7378: 
 7379: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7380: $dumpcount=0;
 7381: 
 7382: &logtouch();
 7383: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7384: $readit=1;
 7385:     {
 7386: 	use integer;
 7387: 	my $test=(2**32)+1;
 7388: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7389: 	&logthis(" Detected 64bit platform ($_64bit)");
 7390:     }
 7391: }
 7392: }
 7393: 
 7394: 1;
 7395: __END__
 7396: 
 7397: =pod
 7398: 
 7399: =head1 NAME
 7400: 
 7401: Apache::lonnet - Subroutines to ask questions about things in the network.
 7402: 
 7403: =head1 SYNOPSIS
 7404: 
 7405: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7406: 
 7407:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7408: 
 7409: Common parameters:
 7410: 
 7411: =over 4
 7412: 
 7413: =item *
 7414: 
 7415: $uname : an internal username (if $cname expecting a course Id specifically)
 7416: 
 7417: =item *
 7418: 
 7419: $udom : a domain (if $cdom expecting a course's domain specifically)
 7420: 
 7421: =item *
 7422: 
 7423: $symb : a resource instance identifier
 7424: 
 7425: =item *
 7426: 
 7427: $namespace : the name of a .db file that contains the data needed or
 7428: being set.
 7429: 
 7430: =back
 7431: 
 7432: =head1 OVERVIEW
 7433: 
 7434: lonnet provides subroutines which interact with the
 7435: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7436: about classes, users, and resources.
 7437: 
 7438: For many of these objects you can also use this to store data about
 7439: them or modify them in various ways.
 7440: 
 7441: =head2 Symbs
 7442: 
 7443: To identify a specific instance of a resource, LON-CAPA uses symbols
 7444: or "symbs"X<symb>. These identifiers are built from the URL of the
 7445: map, the resource number of the resource in the map, and the URL of
 7446: the resource itself. The latter is somewhat redundant, but might help
 7447: if maps change.
 7448: 
 7449: An example is
 7450: 
 7451:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7452: 
 7453: The respective map entry is
 7454: 
 7455:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7456:   title="Problem 2">
 7457:  </resource>
 7458: 
 7459: Symbs are used by the random number generator, as well as to store and
 7460: restore data specific to a certain instance of for example a problem.
 7461: 
 7462: =head2 Storing And Retrieving Data
 7463: 
 7464: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7465: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7466: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7467: is is the non-critical message twin of cstore. These functions are for
 7468: handlers to store a perl hash to a user's permanent data space in an
 7469: easy manner, and to retrieve it again on another call. It is expected
 7470: that a handler would use this once at the beginning to retrieve data,
 7471: and then again once at the end to send only the new data back.
 7472: 
 7473: The data is stored in the user's data directory on the user's
 7474: homeserver under the ID of the course.
 7475: 
 7476: The hash that is returned by restore will have all of the previous
 7477: value for all of the elements of the hash.
 7478: 
 7479: Example:
 7480: 
 7481:  #creating a hash
 7482:  my %hash;
 7483:  $hash{'foo'}='bar';
 7484: 
 7485:  #storing it
 7486:  &Apache::lonnet::cstore(\%hash);
 7487: 
 7488:  #changing a value
 7489:  $hash{'foo'}='notbar';
 7490: 
 7491:  #adding a new value
 7492:  $hash{'bar'}='foo';
 7493:  &Apache::lonnet::cstore(\%hash);
 7494: 
 7495:  #retrieving the hash
 7496:  my %history=&Apache::lonnet::restore();
 7497: 
 7498:  #print the hash
 7499:  foreach my $key (sort(keys(%history))) {
 7500:    print("\%history{$key} = $history{$key}");
 7501:  }
 7502: 
 7503: Will print out:
 7504: 
 7505:  %history{1:foo} = bar
 7506:  %history{1:keys} = foo:timestamp
 7507:  %history{1:timestamp} = 990455579
 7508:  %history{2:bar} = foo
 7509:  %history{2:foo} = notbar
 7510:  %history{2:keys} = foo:bar:timestamp
 7511:  %history{2:timestamp} = 990455580
 7512:  %history{bar} = foo
 7513:  %history{foo} = notbar
 7514:  %history{timestamp} = 990455580
 7515:  %history{version} = 2
 7516: 
 7517: Note that the special hash entries C<keys>, C<version> and
 7518: C<timestamp> were added to the hash. C<version> will be equal to the
 7519: total number of versions of the data that have been stored. The
 7520: C<timestamp> attribute will be the UNIX time the hash was
 7521: stored. C<keys> is available in every historical section to list which
 7522: keys were added or changed at a specific historical revision of a
 7523: hash.
 7524: 
 7525: B<Warning>: do not store the hash that restore returns directly. This
 7526: will cause a mess since it will restore the historical keys as if the
 7527: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7528: 
 7529: Calling convention:
 7530: 
 7531:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7532:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7533: 
 7534: For more detailed information, see lonnet specific documentation.
 7535: 
 7536: =head1 RETURN MESSAGES
 7537: 
 7538: =over 4
 7539: 
 7540: =item * B<con_lost>: unable to contact remote host
 7541: 
 7542: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7543: when the connection is brought back up
 7544: 
 7545: =item * B<con_failed>: unable to contact remote host and unable to save message
 7546: for later delivery
 7547: 
 7548: =item * B<error:>: an error a occured, a description of the error follows the :
 7549: 
 7550: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7551: that was requested
 7552: 
 7553: =back
 7554: 
 7555: =head1 PUBLIC SUBROUTINES
 7556: 
 7557: =head2 Session Environment Functions
 7558: 
 7559: =over 4
 7560: 
 7561: =item * 
 7562: X<appenv()>
 7563: B<appenv(%hash)>: the value of %hash is written to
 7564: the user envirnoment file, and will be restored for each access this
 7565: user makes during this session, also modifies the %env for the current
 7566: process
 7567: 
 7568: =item *
 7569: X<delenv()>
 7570: B<delenv($regexp)>: removes all items from the session
 7571: environment file that matches the regular expression in $regexp. The
 7572: values are also delted from the current processes %env.
 7573: 
 7574: =item * get_env_multiple($name) 
 7575: 
 7576: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7577: values may be defined and end up as an array ref.
 7578: 
 7579: returns an array of values
 7580: 
 7581: =back
 7582: 
 7583: =head2 User Information
 7584: 
 7585: =over 4
 7586: 
 7587: =item *
 7588: X<queryauthenticate()>
 7589: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7590: authentication scheme
 7591: 
 7592: =item *
 7593: X<authenticate()>
 7594: B<authenticate($uname,$upass,$udom)>: try to
 7595: authenticate user from domain's lib servers (first use the current
 7596: one). C<$upass> should be the users password.
 7597: 
 7598: =item *
 7599: X<homeserver()>
 7600: B<homeserver($uname,$udom)>: find the server which has
 7601: the user's directory and files (there must be only one), this caches
 7602: the answer, and also caches if there is a borken connection.
 7603: 
 7604: =item *
 7605: X<idget()>
 7606: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7607: (IDs are a unique resource in a domain, there must be only 1 ID per
 7608: username, and only 1 username per ID in a specific domain) (returns
 7609: hash: id=>name,id=>name)
 7610: 
 7611: =item *
 7612: X<idrget()>
 7613: B<idrget($udom,@unames)>: find the IDs behind a list of
 7614: usernames (returns hash: name=>id,name=>id)
 7615: 
 7616: =item *
 7617: X<idput()>
 7618: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7619: 
 7620: =item *
 7621: X<rolesinit()>
 7622: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7623: 
 7624: =item *
 7625: X<getsection()>
 7626: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7627: course $cname, return section name/number or '' for "not in course"
 7628: and '-1' for "no section"
 7629: 
 7630: =item *
 7631: X<userenvironment()>
 7632: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7633: passed in @what from the requested user's environment, returns a hash
 7634: 
 7635: =back
 7636: 
 7637: =head2 User Roles
 7638: 
 7639: =over 4
 7640: 
 7641: =item *
 7642: 
 7643: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7644: actions
 7645:  F: full access
 7646:  U,I,K: authentication modes (cxx only)
 7647:  '': forbidden
 7648:  1: user needs to choose course
 7649:  2: browse allowed
 7650:  A: passphrase authentication needed
 7651: 
 7652: =item *
 7653: 
 7654: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7655: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7656: and course level
 7657: 
 7658: =item *
 7659: 
 7660: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7661: explanation of a user role term
 7662: 
 7663: =back
 7664: 
 7665: =head2 User Modification
 7666: 
 7667: =over 4
 7668: 
 7669: =item *
 7670: 
 7671: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7672: user for the level given by URL.  Optional start and end dates (leave empty
 7673: string or zero for "no date")
 7674: 
 7675: =item *
 7676: 
 7677: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7678: change a users, password, possible return values are: ok,
 7679: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7680: refused
 7681: 
 7682: =item *
 7683: 
 7684: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7685: 
 7686: =item *
 7687: 
 7688: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7689: modify user
 7690: 
 7691: =item *
 7692: 
 7693: modifystudent
 7694: 
 7695: modify a students enrollment and identification information.
 7696: The course id is resolved based on the current users environment.  
 7697: This means the envoking user must be a course coordinator or otherwise
 7698: associated with a course.
 7699: 
 7700: This call is essentially a wrapper for lonnet::modifyuser and
 7701: lonnet::modify_student_enrollment
 7702: 
 7703: Inputs: 
 7704: 
 7705: =over 4
 7706: 
 7707: =item B<$udom> Students loncapa domain
 7708: 
 7709: =item B<$uname> Students loncapa login name
 7710: 
 7711: =item B<$uid> Students id/student number
 7712: 
 7713: =item B<$umode> Students authentication mode
 7714: 
 7715: =item B<$upass> Students password
 7716: 
 7717: =item B<$first> Students first name
 7718: 
 7719: =item B<$middle> Students middle name
 7720: 
 7721: =item B<$last> Students last name
 7722: 
 7723: =item B<$gene> Students generation
 7724: 
 7725: =item B<$usec> Students section in course
 7726: 
 7727: =item B<$end> Unix time of the roles expiration
 7728: 
 7729: =item B<$start> Unix time of the roles start date
 7730: 
 7731: =item B<$forceid> If defined, allow $uid to be changed
 7732: 
 7733: =item B<$desiredhome> server to use as home server for student
 7734: 
 7735: =back
 7736: 
 7737: =item *
 7738: 
 7739: modify_student_enrollment
 7740: 
 7741: Change a students enrollment status in a class.  The environment variable
 7742: 'role.request.course' must be defined for this function to proceed.
 7743: 
 7744: Inputs:
 7745: 
 7746: =over 4
 7747: 
 7748: =item $udom, students domain
 7749: 
 7750: =item $uname, students name
 7751: 
 7752: =item $uid, students user id
 7753: 
 7754: =item $first, students first name
 7755: 
 7756: =item $middle
 7757: 
 7758: =item $last
 7759: 
 7760: =item $gene
 7761: 
 7762: =item $usec
 7763: 
 7764: =item $end
 7765: 
 7766: =item $start
 7767: 
 7768: =back
 7769: 
 7770: 
 7771: =item *
 7772: 
 7773: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7774: custom role; give a custom role to a user for the level given by URL.  Specify
 7775: name and domain of role author, and role name
 7776: 
 7777: =item *
 7778: 
 7779: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7780: 
 7781: =item *
 7782: 
 7783: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7784: 
 7785: =back
 7786: 
 7787: =head2 Course Infomation
 7788: 
 7789: =over 4
 7790: 
 7791: =item *
 7792: 
 7793: coursedescription($courseid) : returns a hash of information about the
 7794: specified course id, including all environment settings for the
 7795: course, the description of the course will be in the hash under the
 7796: key 'description'
 7797: 
 7798: =item *
 7799: 
 7800: resdata($name,$domain,$type,@which) : request for current parameter
 7801: setting for a specific $type, where $type is either 'course' or 'user',
 7802: @what should be a list of parameters to ask about. This routine caches
 7803: answers for 5 minutes.
 7804: 
 7805: =back
 7806: 
 7807: =head2 Course Modification
 7808: 
 7809: =over 4
 7810: 
 7811: =item *
 7812: 
 7813: writecoursepref($courseid,%prefs) : write preferences (environment
 7814: database) for a course
 7815: 
 7816: =item *
 7817: 
 7818: createcourse($udom,$description,$url) : make/modify course
 7819: 
 7820: =back
 7821: 
 7822: =head2 Resource Subroutines
 7823: 
 7824: =over 4
 7825: 
 7826: =item *
 7827: 
 7828: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7829: 
 7830: =item *
 7831: 
 7832: repcopy($filename) : subscribes to the requested file, and attempts to
 7833: replicate from the owning library server, Might return
 7834: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7835: 'bad_request', also attempts to grab the metadata for the
 7836: resource. Expects the local filesystem pathname
 7837: (/home/httpd/html/res/....)
 7838: 
 7839: =back
 7840: 
 7841: =head2 Resource Information
 7842: 
 7843: =over 4
 7844: 
 7845: =item *
 7846: 
 7847: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7848: a vairety of different possible values, $varname should be a request
 7849: string, and the other parameters can be used to specify who and what
 7850: one is asking about.
 7851: 
 7852: Possible values for $varname are environment.lastname (or other item
 7853: from the envirnment hash), user.name (or someother aspect about the
 7854: user), resource.0.maxtries (or some other part and parameter of a
 7855: resource)
 7856: 
 7857: =item *
 7858: 
 7859: directcondval($number) : get current value of a condition; reads from a state
 7860: string
 7861: 
 7862: =item *
 7863: 
 7864: condval($condidx) : value of condition index based on state
 7865: 
 7866: =item *
 7867: 
 7868: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7869: resource's metadata, $what should be either a specific key, or either
 7870: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7871: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7872: 
 7873: this function automatically caches all requests
 7874: 
 7875: =item *
 7876: 
 7877: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7878: network of library servers; returns file handle of where SQL and regex results
 7879: will be stored for query
 7880: 
 7881: =item *
 7882: 
 7883: symbread($filename) : return symbolic list entry (filename argument optional);
 7884: returns the data handle
 7885: 
 7886: =item *
 7887: 
 7888: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7889: a possible symb for the URL in $thisfn, and if is an encryypted
 7890: resource that the user accessed using /enc/ returns a 1 on success, 0
 7891: on failure, user must be in a course, as it assumes the existance of
 7892: the course initial hash, and uses $env('request.course.id'}
 7893: 
 7894: 
 7895: =item *
 7896: 
 7897: symbclean($symb) : removes versions numbers from a symb, returns the
 7898: cleaned symb
 7899: 
 7900: =item *
 7901: 
 7902: is_on_map($uri) : checks if the $uri is somewhere on the current
 7903: course map, user must be in a course for it to work.
 7904: 
 7905: =item *
 7906: 
 7907: numval($salt) : return random seed value (addend for rndseed)
 7908: 
 7909: =item *
 7910: 
 7911: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7912: a random seed, all arguments are optional, if they aren't sent it uses the
 7913: environment to derive them. Note: if symb isn't sent and it can't get one
 7914: from &symbread it will use the current time as its return value
 7915: 
 7916: =item *
 7917: 
 7918: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7919: unfakeable, receipt
 7920: 
 7921: =item *
 7922: 
 7923: receipt() : API to ireceipt working off of env values; given out to users
 7924: 
 7925: =item *
 7926: 
 7927: countacc($url) : count the number of accesses to a given URL
 7928: 
 7929: =item *
 7930: 
 7931: 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
 7932: 
 7933: =item *
 7934: 
 7935: 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)
 7936: 
 7937: =item *
 7938: 
 7939: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 7940: 
 7941: =item *
 7942: 
 7943: devalidate($symb) : devalidate temporary spreadsheet calculations,
 7944: forcing spreadsheet to reevaluate the resource scores next time.
 7945: 
 7946: =back
 7947: 
 7948: =head2 Storing/Retreiving Data
 7949: 
 7950: =over 4
 7951: 
 7952: =item *
 7953: 
 7954: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 7955: for this url; hashref needs to be given and should be a \%hashname; the
 7956: remaining args aren't required and if they aren't passed or are '' they will
 7957: be derived from the env
 7958: 
 7959: =item *
 7960: 
 7961: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 7962: uses critical subroutine
 7963: 
 7964: =item *
 7965: 
 7966: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 7967: all args are optional
 7968: 
 7969: =item *
 7970: 
 7971: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 7972: dumps the complete (or key matching regexp) namespace into a hash
 7973: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 7974: normally &store()ed into
 7975: 
 7976: $range should be either an integer '100' (give me the first 100
 7977:                                            matching records)
 7978:               or be  two integers sperated by a - with no spaces
 7979:                  '30-50' (give me the 30th through the 50th matching
 7980:                           records)
 7981: 
 7982: 
 7983: =item *
 7984: 
 7985: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 7986: replaces a &store() version of data with a replacement set of data
 7987: for a particular resource in a namespace passed in the $storehash hash 
 7988: reference
 7989: 
 7990: =item *
 7991: 
 7992: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 7993: works very similar to store/cstore, but all data is stored in a
 7994: temporary location and can be reset using tmpreset, $storehash should
 7995: be a hash reference, returns nothing on success
 7996: 
 7997: =item *
 7998: 
 7999: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8000: similar to restore, but all data is stored in a temporary location and
 8001: can be reset using tmpreset. Returns a hash of values on success,
 8002: error string otherwise.
 8003: 
 8004: =item *
 8005: 
 8006: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8007: deltes all keys for $symb form the temporary storage hash.
 8008: 
 8009: =item *
 8010: 
 8011: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8012: reference filled in from namesp ($udom and $uname are optional)
 8013: 
 8014: =item *
 8015: 
 8016: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8017: namesp ($udom and $uname are optional)
 8018: 
 8019: =item *
 8020: 
 8021: dump($namespace,$udom,$uname,$regexp,$range) : 
 8022: dumps the complete (or key matching regexp) namespace into a hash
 8023: ($udom, $uname, $regexp, $range are optional)
 8024: 
 8025: $range should be either an integer '100' (give me the first 100
 8026:                                            matching records)
 8027:               or be  two integers sperated by a - with no spaces
 8028:                  '30-50' (give me the 30th through the 50th matching
 8029:                           records)
 8030: =item *
 8031: 
 8032: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8033: $store can be a scalar, an array reference, or if the amount to be 
 8034: incremented is > 1, a hash reference.
 8035: 
 8036: ($udom and $uname are optional)
 8037: 
 8038: =item *
 8039: 
 8040: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8041: ($udom and $uname are optional)
 8042: 
 8043: =item *
 8044: 
 8045: cput($namespace,$storehash,$udom,$uname) : critical put
 8046: ($udom and $uname are optional)
 8047: 
 8048: =item *
 8049: 
 8050: newput($namespace,$storehash,$udom,$uname) :
 8051: 
 8052: Attempts to store the items in the $storehash, but only if they don't
 8053: currently exist, if this succeeds you can be certain that you have 
 8054: successfully created a new key value pair in the $namespace db.
 8055: 
 8056: 
 8057: Args:
 8058:  $namespace: name of database to store values to
 8059:  $storehash: hashref to store to the db
 8060:  $udom: (optional) domain of user containing the db
 8061:  $uname: (optional) name of user caontaining the db
 8062: 
 8063: Returns:
 8064:  'ok' -> succeeded in storing all keys of $storehash
 8065:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8066:                         least <key> already existed in the db (other
 8067:                         requested keys may also already exist)
 8068:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8069:  'con_lost' -> unable to contact request server
 8070:  'refused' -> action was not allowed by remote machine
 8071: 
 8072: 
 8073: =item *
 8074: 
 8075: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8076: reference filled in from namesp (encrypts the return communication)
 8077: ($udom and $uname are optional)
 8078: 
 8079: =item *
 8080: 
 8081: log($udom,$name,$home,$message) : write to permanent log for user; use
 8082: critical subroutine
 8083: 
 8084: =back
 8085: 
 8086: =head2 Network Status Functions
 8087: 
 8088: =over 4
 8089: 
 8090: =item *
 8091: 
 8092: dirlist($uri) : return directory list based on URI
 8093: 
 8094: =item *
 8095: 
 8096: spareserver() : find server with least workload from spare.tab
 8097: 
 8098: =back
 8099: 
 8100: =head2 Apache Request
 8101: 
 8102: =over 4
 8103: 
 8104: =item *
 8105: 
 8106: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8107: localhost, posts hash
 8108: 
 8109: =back
 8110: 
 8111: =head2 Data to String to Data
 8112: 
 8113: =over 4
 8114: 
 8115: =item *
 8116: 
 8117: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8118: and '&' separators, supports elements that are arrayrefs and hashrefs
 8119: 
 8120: =item *
 8121: 
 8122: hashref2str($hashref) : convert a hashref into a string complete with
 8123: escaping and '=' and '&' separators, supports elements that are
 8124: arrayrefs and hashrefs
 8125: 
 8126: =item *
 8127: 
 8128: arrayref2str($arrayref) : convert an arrayref into a string complete
 8129: with escaping and '&' separators, supports elements that are arrayrefs
 8130: and hashrefs
 8131: 
 8132: =item *
 8133: 
 8134: str2hash($string) : convert string to hash using unescaping and
 8135: splitting on '=' and '&', supports elements that are arrayrefs and
 8136: hashrefs
 8137: 
 8138: =item *
 8139: 
 8140: str2array($string) : convert string to hash using unescaping and
 8141: splitting on '&', supports elements that are arrayrefs and hashrefs
 8142: 
 8143: =back
 8144: 
 8145: =head2 Logging Routines
 8146: 
 8147: =over 4
 8148: 
 8149: These routines allow one to make log messages in the lonnet.log and
 8150: lonnet.perm logfiles.
 8151: 
 8152: =item *
 8153: 
 8154: logtouch() : make sure the logfile, lonnet.log, exists
 8155: 
 8156: =item *
 8157: 
 8158: logthis() : append message to the normal lonnet.log file, it gets
 8159: preiodically rolled over and deleted.
 8160: 
 8161: =item *
 8162: 
 8163: logperm() : append a permanent message to lonnet.perm.log, this log
 8164: file never gets deleted by any automated portion of the system, only
 8165: messages of critical importance should go in here.
 8166: 
 8167: =back
 8168: 
 8169: =head2 General File Helper Routines
 8170: 
 8171: =over 4
 8172: 
 8173: =item *
 8174: 
 8175: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8176: (a) files in /uploaded
 8177:   (i) If a local copy of the file exists - 
 8178:       compares modification date of local copy with last-modified date for 
 8179:       definitive version stored on home server for course. If local copy is 
 8180:       stale, requests a new version from the home server and stores it. 
 8181:       If the original has been removed from the home server, then local copy 
 8182:       is unlinked.
 8183:   (ii) If local copy does not exist -
 8184:       requests the file from the home server and stores it. 
 8185:   
 8186:   If $caller is 'uploadrep':  
 8187:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8188:     for request for files originally uploaded via DOCS. 
 8189:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8190:   
 8191:   Otherwise:
 8192:      This indicates a call from the content generation phase of the request.
 8193:      -  returns the entire contents of the file or -1.
 8194:      
 8195: (b) files in /res
 8196:    - returns the entire contents of a file or -1; 
 8197:    it properly subscribes to and replicates the file if neccessary.
 8198: 
 8199: 
 8200: =item *
 8201: 
 8202: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8203:                   reference
 8204: 
 8205: returns either a stat() list of data about the file or an empty list
 8206: if the file doesn't exist or couldn't find out about it (connection
 8207: problems or user unknown)
 8208: 
 8209: =item *
 8210: 
 8211: filelocation($dir,$file) : returns file system location of a file
 8212: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8213: directory that relative $file lookups are to looked in ($dir of /a/dir
 8214: and a file of ../bob will become /a/bob)
 8215: 
 8216: =item *
 8217: 
 8218: hreflocation($dir,$file) : returns file system location or a URL; same as
 8219: filelocation except for hrefs
 8220: 
 8221: =item *
 8222: 
 8223: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8224: 
 8225: =back
 8226: 
 8227: =head2 Usererfile file routines (/uploaded*)
 8228: 
 8229: =over 4
 8230: 
 8231: =item *
 8232: 
 8233: userfileupload(): main rotine for putting a file in a user or course's
 8234:                   filespace, arguments are,
 8235: 
 8236:  formname - required - this is the name of the element in $env where the
 8237:            filename, and the contents of the file to create/modifed exist
 8238:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8239:            contents of the file is located in $env{'form.'.$formname}
 8240:  coursedoc - if true, store the file in the course of the active role
 8241:              of the current user
 8242:  subdir - required - subdirectory to put the file in under ../userfiles/
 8243:          if undefined, it will be placed in "unknown"
 8244: 
 8245:  (This routine calls clean_filename() to remove any dangerous
 8246:  characters from the filename, and then calls finuserfileupload() to
 8247:  complete the transaction)
 8248: 
 8249:  returns either the url of the uploaded file (/uploaded/....) if successful
 8250:  and /adm/notfound.html if unsuccessful
 8251: 
 8252: =item *
 8253: 
 8254: clean_filename(): routine for cleaing a filename up for storage in
 8255:                  userfile space, argument is:
 8256: 
 8257:  filename - proposed filename
 8258: 
 8259: returns: the new clean filename
 8260: 
 8261: =item *
 8262: 
 8263: finishuserfileupload(): routine that creaes and sends the file to
 8264: userspace, probably shouldn't be called directly
 8265: 
 8266:   docuname: username or courseid of destination for the file
 8267:   docudom: domain of user/course of destination for the file
 8268:   formname: same as for userfileupload()
 8269:   fname: filename (inculding subdirectories) for the file
 8270: 
 8271:  returns either the url of the uploaded file (/uploaded/....) if successful
 8272:  and /adm/notfound.html if unsuccessful
 8273: 
 8274: =item *
 8275: 
 8276: renameuserfile(): renames an existing userfile to a new name
 8277: 
 8278:   Args:
 8279:    docuname: username or courseid of destination for the file
 8280:    docudom: domain of user/course of destination for the file
 8281:    old: current file name (including any subdirs under userfiles)
 8282:    new: desired file name (including any subdirs under userfiles)
 8283: 
 8284: =item *
 8285: 
 8286: mkdiruserfile(): creates a directory is a userfiles dir
 8287: 
 8288:   Args:
 8289:    docuname: username or courseid of destination for the file
 8290:    docudom: domain of user/course of destination for the file
 8291:    dir: dir to create (including any subdirs under userfiles)
 8292: 
 8293: =item *
 8294: 
 8295: removeuserfile(): removes a file that exists in userfiles
 8296: 
 8297:   Args:
 8298:    docuname: username or courseid of destination for the file
 8299:    docudom: domain of user/course of destination for the file
 8300:    fname: filname to delete (including any subdirs under userfiles)
 8301: 
 8302: =item *
 8303: 
 8304: removeuploadedurl(): convience function for removeuserfile()
 8305: 
 8306:   Args:
 8307:    url:  a full /uploaded/... url to delete
 8308: 
 8309: =item * 
 8310: 
 8311: get_portfile_permissions():
 8312:   Args:
 8313:     domain: domain of user or course contain the portfolio files
 8314:     user: name of user or num of course contain the portfolio files
 8315:   Returns:
 8316:     hashref of a dump of the proper file_permissions.db
 8317:    
 8318: 
 8319: =item * 
 8320: 
 8321: get_access_controls():
 8322: 
 8323: Args:
 8324:   current_permissions: the hash ref returned from get_portfile_permissions()
 8325:   group: (optional) the group you want the files associated with
 8326:   file: (optional) the file you want access info on
 8327: 
 8328: Returns:
 8329:     a hash (keys are file names) of hashes containing
 8330:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8331:         values are XML containing access control settings (see below) 
 8332: 
 8333: Internal notes:
 8334: 
 8335:  access controls are stored in file_permissions.db as key=value pairs.
 8336:     key -> path to file/file_name\0uniqueID:scope_end_start
 8337:         where scope -> public,guest,course,group,domains or users.
 8338:               end -> UNIX time for end of access (0 -> no end date)
 8339:               start -> UNIX time for start of access
 8340: 
 8341:     value -> XML description of access control
 8342:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8343:             <start></start>
 8344:             <end></end>
 8345: 
 8346:             <password></password>  for scope type = guest
 8347: 
 8348:             <domain></domain>     for scope type = course or group
 8349:             <number></number>
 8350:             <roles id="">
 8351:              <role></role>
 8352:              <access></access>
 8353:              <section></section>
 8354:              <group></group>
 8355:             </roles>
 8356: 
 8357:             <dom></dom>         for scope type = domains
 8358: 
 8359:             <users>             for scope type = users
 8360:              <user>
 8361:               <uname></uname>
 8362:               <udom></udom>
 8363:              </user>
 8364:             </users>
 8365:            </scope> 
 8366:               
 8367:  Access data is also aggregated for each file in an additional key=value pair:
 8368:  key -> path to file/file_name\0accesscontrol 
 8369:  value -> reference to hash
 8370:           hash contains key = value pairs
 8371:           where key = uniqueID:scope_end_start
 8372:                 value = UNIX time record was last updated
 8373: 
 8374:           Used to improve speed of look-ups of access controls for each file.  
 8375:  
 8376:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8377: 
 8378: modify_access_controls():
 8379: 
 8380: Modifies access controls for a portfolio file
 8381: Args
 8382: 1. file name
 8383: 2. reference to hash of required changes,
 8384: 3. domain
 8385: 4. username
 8386:   where domain,username are the domain of the portfolio owner 
 8387:   (either a user or a course) 
 8388: 
 8389: Returns:
 8390: 1. result of additions or updates ('ok' or 'error', with error message). 
 8391: 2. result of deletions ('ok' or 'error', with error message).
 8392: 3. reference to hash of any new or updated access controls.
 8393: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8394:    key = integer (inbound ID)
 8395:    value = uniqueID  
 8396: 
 8397: =back
 8398: 
 8399: =head2 HTTP Helper Routines
 8400: 
 8401: =over 4
 8402: 
 8403: =item *
 8404: 
 8405: escape() : unpack non-word characters into CGI-compatible hex codes
 8406: 
 8407: =item *
 8408: 
 8409: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8410: 
 8411: =back
 8412: 
 8413: =head1 PRIVATE SUBROUTINES
 8414: 
 8415: =head2 Underlying communication routines (Shouldn't call)
 8416: 
 8417: =over 4
 8418: 
 8419: =item *
 8420: 
 8421: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8422: 
 8423: =item *
 8424: 
 8425: reply() : uses subreply to send a message to remote machine, logs all failures
 8426: 
 8427: =item *
 8428: 
 8429: critical() : passes a critical message to another server; if cannot
 8430: get through then place message in connection buffer directory and
 8431: returns con_delayed, if incapable of saving message, returns
 8432: con_failed
 8433: 
 8434: =item *
 8435: 
 8436: reconlonc() : tries to reconnect lonc client processes.
 8437: 
 8438: =back
 8439: 
 8440: =head2 Resource Access Logging
 8441: 
 8442: =over 4
 8443: 
 8444: =item *
 8445: 
 8446: flushcourselogs() : flush (save) buffer logs and access logs
 8447: 
 8448: =item *
 8449: 
 8450: courselog($what) : save message for course in hash
 8451: 
 8452: =item *
 8453: 
 8454: courseacclog($what) : save message for course using &courselog().  Perform
 8455: special processing for specific resource types (problems, exams, quizzes, etc).
 8456: 
 8457: =item *
 8458: 
 8459: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8460: as a PerlChildExitHandler
 8461: 
 8462: =back
 8463: 
 8464: =head2 Other
 8465: 
 8466: =over 4
 8467: 
 8468: =item *
 8469: 
 8470: symblist($mapname,%newhash) : update symbolic storage links
 8471: 
 8472: =back
 8473: 
 8474: =cut

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