File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.806: download - view: text, annotated - select for diffs
Tue Nov 21 20:58:06 2006 UTC (17 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Put and get data in specified db files at the domain level of the primary domain server (e.g., domain configuration settings in configuration.db).

This is the same location as used currently for ids.db, nohist_courseids.db, and nohist_domainroles.db and nohist_dcmail.db.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.806 2006/11/21 20:58:06 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: # ------------------------------------------- get items from domain db files   
  698: 
  699: sub get_dom {
  700:     my ($namespace,$storearr,$udom)=@_;
  701:     my $items='';
  702:     foreach my $item (@$storearr) {
  703:         $items.=&escape($item).'&';
  704:     }
  705:     $items=~s/\&$//;
  706:     if (!$udom) { $udom=$env{'user.domain'}; }
  707:     if (exists($domain_primary{$udom})) {
  708:         my $uhome=$domain_primary{$udom};
  709:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  710:         my @pairs=split(/\&/,$rep);
  711:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  712:             return @pairs;
  713:         }
  714:         my %returnhash=();
  715:         my $i=0;
  716:         foreach my $item (@$storearr) {
  717:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  718:             $i++;
  719:         }
  720:         return %returnhash;
  721:     } else {
  722:         &logthis("get_dom failed - no primary domain server for $udom");
  723:     }
  724: }
  725: 
  726: # -------------------------------------------- put items in domain db files 
  727: 
  728: sub put_dom {
  729:     my ($namespace,$storehash,$udom)=@_;
  730:     if (!$udom) { $udom=$env{'user.domain'}; }
  731:     if (exists($domain_primary{$udom})) {
  732:         my $uhome=$domain_primary{$udom};
  733:         my $items='';
  734:         foreach my $item (keys(%$storehash)) {
  735:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  736:         }
  737:         $items=~s/\&$//;
  738:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  739:     } else {
  740:         &logthis("put_dom failed - no primary domain server for $udom");
  741:     }
  742: }
  743: 
  744: # --------------------------------------------------- Assign a key to a student
  745: 
  746: sub assign_access_key {
  747: #
  748: # a valid key looks like uname:udom#comments
  749: # comments are being appended
  750: #
  751:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  752:     $kdom=
  753:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  754:     $knum=
  755:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  756:     $cdom=
  757:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  758:     $cnum=
  759:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  760:     $udom=$env{'user.name'} unless (defined($udom));
  761:     $uname=$env{'user.domain'} unless (defined($uname));
  762:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  763:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  764:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  765:                                                   # assigned to this person
  766:                                                   # - this should not happen,
  767:                                                   # unless something went wrong
  768:                                                   # the first time around
  769: # ready to assign
  770:         $logentry=$1.'; '.$logentry;
  771:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  772:                                                  $kdom,$knum) eq 'ok') {
  773: # key now belongs to user
  774: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  775:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  776:                 &appenv('environment.'.$envkey => $ckey);
  777:                 return 'ok';
  778:             } else {
  779:                 return 
  780:   'error: Count not permanently assign key, will need to be re-entered later.';
  781: 	    }
  782:         } else {
  783:             return 'error: Could not assign key, try again later.';
  784:         }
  785:     } elsif (!$existing{$ckey}) {
  786: # the key does not exist
  787: 	return 'error: The key does not exist';
  788:     } else {
  789: # the key is somebody else's
  790: 	return 'error: The key is already in use';
  791:     }
  792: }
  793: 
  794: # ------------------------------------------ put an additional comment on a key
  795: 
  796: sub comment_access_key {
  797: #
  798: # a valid key looks like uname:udom#comments
  799: # comments are being appended
  800: #
  801:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  802:     $cdom=
  803:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  804:     $cnum=
  805:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  806:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  807:     if ($existing{$ckey}) {
  808:         $existing{$ckey}.='; '.$logentry;
  809: # ready to assign
  810:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  811:                                                  $cdom,$cnum) eq 'ok') {
  812: 	    return 'ok';
  813:         } else {
  814: 	    return 'error: Count not store comment.';
  815:         }
  816:     } else {
  817: # the key does not exist
  818: 	return 'error: The key does not exist';
  819:     }
  820: }
  821: 
  822: # ------------------------------------------------------ Generate a set of keys
  823: 
  824: sub generate_access_keys {
  825:     my ($number,$cdom,$cnum,$logentry)=@_;
  826:     $cdom=
  827:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  828:     $cnum=
  829:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  830:     unless (&allowed('mky',$cdom)) { return 0; }
  831:     unless (($cdom) && ($cnum)) { return 0; }
  832:     if ($number>10000) { return 0; }
  833:     sleep(2); # make sure don't get same seed twice
  834:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  835:     my $total=0;
  836:     for (my $i=1;$i<=$number;$i++) {
  837:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  838:                   sprintf("%lx",int(100000*rand)).'-'.
  839:                   sprintf("%lx",int(100000*rand));
  840:        $newkey=~s/1/g/g; # folks mix up 1 and l
  841:        $newkey=~s/0/h/g; # and also 0 and O
  842:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  843:        if ($existing{$newkey}) {
  844:            $i--;
  845:        } else {
  846: 	  if (&put('accesskeys',
  847:               { $newkey => '# generated '.localtime().
  848:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  849:                            '; '.$logentry },
  850: 		   $cdom,$cnum) eq 'ok') {
  851:               $total++;
  852: 	  }
  853:        }
  854:     }
  855:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  856:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  857:     return $total;
  858: }
  859: 
  860: # ------------------------------------------------------- Validate an accesskey
  861: 
  862: sub validate_access_key {
  863:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  864:     $cdom=
  865:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  866:     $cnum=
  867:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  868:     $udom=$env{'user.domain'} unless (defined($udom));
  869:     $uname=$env{'user.name'} unless (defined($uname));
  870:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  871:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  872: }
  873: 
  874: # ------------------------------------- Find the section of student in a course
  875: sub devalidate_getsection_cache {
  876:     my ($udom,$unam,$courseid)=@_;
  877:     $courseid=~s/\_/\//g;
  878:     $courseid=~s/^(\w)/\/$1/;
  879:     my $hashid="$udom:$unam:$courseid";
  880:     &devalidate_cache_new('getsection',$hashid);
  881: }
  882: 
  883: sub getsection {
  884:     my ($udom,$unam,$courseid)=@_;
  885:     my $cachetime=1800;
  886:     $courseid=~s/\_/\//g;
  887:     $courseid=~s/^(\w)/\/$1/;
  888: 
  889:     my $hashid="$udom:$unam:$courseid";
  890:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  891:     if (defined($cached)) { return $result; }
  892: 
  893:     my %Pending; 
  894:     my %Expired;
  895:     #
  896:     # Each role can either have not started yet (pending), be active, 
  897:     #    or have expired.
  898:     #
  899:     # If there is an active role, we are done.
  900:     #
  901:     # If there is more than one role which has not started yet, 
  902:     #     choose the one which will start sooner
  903:     # If there is one role which has not started yet, return it.
  904:     #
  905:     # If there is more than one expired role, choose the one which ended last.
  906:     # If there is a role which has expired, return it.
  907:     #
  908:     foreach my $line (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  909: 					&homeserver($unam,$udom)))) {
  910:         my ($key,$value)=split(/\=/,$line,2);
  911:         $key=&unescape($key);
  912:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  913:         my $section=$1;
  914:         if ($key eq $courseid.'_st') { $section=''; }
  915:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  916:         my $now=time;
  917:         if (defined($end) && $end && ($now > $end)) {
  918:             $Expired{$end}=$section;
  919:             next;
  920:         }
  921:         if (defined($start) && $start && ($now < $start)) {
  922:             $Pending{$start}=$section;
  923:             next;
  924:         }
  925:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  926:     }
  927:     #
  928:     # Presumedly there will be few matching roles from the above
  929:     # loop and the sorting time will be negligible.
  930:     if (scalar(keys(%Pending))) {
  931:         my ($time) = sort {$a <=> $b} keys(%Pending);
  932:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  933:     } 
  934:     if (scalar(keys(%Expired))) {
  935:         my @sorted = sort {$a <=> $b} keys(%Expired);
  936:         my $time = pop(@sorted);
  937:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  938:     }
  939:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  940: }
  941: 
  942: sub save_cache {
  943:     &purge_remembered();
  944:     #&Apache::loncommon::validate_page();
  945:     undef(%env);
  946:     undef($env_loaded);
  947: }
  948: 
  949: my $to_remember=-1;
  950: my %remembered;
  951: my %accessed;
  952: my $kicks=0;
  953: my $hits=0;
  954: sub devalidate_cache_new {
  955:     my ($name,$id,$debug) = @_;
  956:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  957:     $id=&escape($name.':'.$id);
  958:     $memcache->delete($id);
  959:     delete($remembered{$id});
  960:     delete($accessed{$id});
  961: }
  962: 
  963: sub is_cached_new {
  964:     my ($name,$id,$debug) = @_;
  965:     $id=&escape($name.':'.$id);
  966:     if (exists($remembered{$id})) {
  967: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  968: 	$accessed{$id}=[&gettimeofday()];
  969: 	$hits++;
  970: 	return ($remembered{$id},1);
  971:     }
  972:     my $value = $memcache->get($id);
  973:     if (!(defined($value))) {
  974: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  975: 	return (undef,undef);
  976:     }
  977:     if ($value eq '__undef__') {
  978: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  979: 	$value=undef;
  980:     }
  981:     &make_room($id,$value,$debug);
  982:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  983:     return ($value,1);
  984: }
  985: 
  986: sub do_cache_new {
  987:     my ($name,$id,$value,$time,$debug) = @_;
  988:     $id=&escape($name.':'.$id);
  989:     my $setvalue=$value;
  990:     if (!defined($setvalue)) {
  991: 	$setvalue='__undef__';
  992:     }
  993:     if (!defined($time) ) {
  994: 	$time=600;
  995:     }
  996:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  997:     $memcache->set($id,$setvalue,$time);
  998:     # need to make a copy of $value
  999:     #&make_room($id,$value,$debug);
 1000:     return $value;
 1001: }
 1002: 
 1003: sub make_room {
 1004:     my ($id,$value,$debug)=@_;
 1005:     $remembered{$id}=$value;
 1006:     if ($to_remember<0) { return; }
 1007:     $accessed{$id}=[&gettimeofday()];
 1008:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1009:     my $to_kick;
 1010:     my $max_time=0;
 1011:     foreach my $other (keys(%accessed)) {
 1012: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1013: 	    $to_kick=$other;
 1014: 	    $max_time=&tv_interval($accessed{$other});
 1015: 	}
 1016:     }
 1017:     delete($remembered{$to_kick});
 1018:     delete($accessed{$to_kick});
 1019:     $kicks++;
 1020:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1021:     return;
 1022: }
 1023: 
 1024: sub purge_remembered {
 1025:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1026:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1027:     undef(%remembered);
 1028:     undef(%accessed);
 1029: }
 1030: # ------------------------------------- Read an entry from a user's environment
 1031: 
 1032: sub userenvironment {
 1033:     my ($udom,$unam,@what)=@_;
 1034:     my %returnhash=();
 1035:     my @answer=split(/\&/,
 1036:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1037:                       &homeserver($unam,$udom)));
 1038:     my $i;
 1039:     for ($i=0;$i<=$#what;$i++) {
 1040: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1041:     }
 1042:     return %returnhash;
 1043: }
 1044: 
 1045: # ---------------------------------------------------------- Get a studentphoto
 1046: sub studentphoto {
 1047:     my ($udom,$unam,$ext) = @_;
 1048:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1049:     if (defined($env{'request.course.id'})) {
 1050:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1051:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1052:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1053:             } else {
 1054:                 my ($result,$perm_reqd)=
 1055: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1056:                 if ($result eq 'ok') {
 1057:                     if (!($perm_reqd eq 'yes')) {
 1058:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1059:                     }
 1060:                 }
 1061:             }
 1062:         }
 1063:     } else {
 1064:         my ($result,$perm_reqd) = 
 1065: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1066:         if ($result eq 'ok') {
 1067:             if (!($perm_reqd eq 'yes')) {
 1068:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1069:             }
 1070:         }
 1071:     }
 1072:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1073: }
 1074: 
 1075: sub retrievestudentphoto {
 1076:     my ($udom,$unam,$ext,$type) = @_;
 1077:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1078:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1079:     if ($ret eq 'ok') {
 1080:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1081:         if ($type eq 'thumbnail') {
 1082:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1083:         }
 1084:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1085:         return $tokenurl;
 1086:     } else {
 1087:         if ($type eq 'thumbnail') {
 1088:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1089:         } else { 
 1090:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1091:         }
 1092:     }
 1093: }
 1094: 
 1095: # -------------------------------------------------------------------- New chat
 1096: 
 1097: sub chatsend {
 1098:     my ($newentry,$anon,$group)=@_;
 1099:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1100:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1101:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1102:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1103: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1104: 		   &escape($newentry)).':'.$group,$chome);
 1105: }
 1106: 
 1107: # ------------------------------------------ Find current version of a resource
 1108: 
 1109: sub getversion {
 1110:     my $fname=&clutter(shift);
 1111:     unless ($fname=~/^\/res\//) { return -1; }
 1112:     return &currentversion(&filelocation('',$fname));
 1113: }
 1114: 
 1115: sub currentversion {
 1116:     my $fname=shift;
 1117:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1118:     if (defined($cached)) { return $result; }
 1119:     my $author=$fname;
 1120:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1121:     my ($udom,$uname)=split(/\//,$author);
 1122:     my $home=homeserver($uname,$udom);
 1123:     if ($home eq 'no_host') { 
 1124:         return -1; 
 1125:     }
 1126:     my $answer=reply("currentversion:$fname",$home);
 1127:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1128: 	return -1;
 1129:     }
 1130:     return &do_cache_new('resversion',$fname,$answer,600);
 1131: }
 1132: 
 1133: # ----------------------------- Subscribe to a resource, return URL if possible
 1134: 
 1135: sub subscribe {
 1136:     my $fname=shift;
 1137:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1138:     $fname=~s/[\n\r]//g;
 1139:     my $author=$fname;
 1140:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1141:     my ($udom,$uname)=split(/\//,$author);
 1142:     my $home=homeserver($uname,$udom);
 1143:     if ($home eq 'no_host') {
 1144:         return 'not_found';
 1145:     }
 1146:     my $answer=reply("sub:$fname",$home);
 1147:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1148: 	$answer.=' by '.$home;
 1149:     }
 1150:     return $answer;
 1151: }
 1152:     
 1153: # -------------------------------------------------------------- Replicate file
 1154: 
 1155: sub repcopy {
 1156:     my $filename=shift;
 1157:     $filename=~s/\/+/\//g;
 1158:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1159:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1160:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1161: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1162: 	return &repcopy_userfile($filename);
 1163:     }
 1164:     $filename=~s/[\n\r]//g;
 1165:     my $transname="$filename.in.transfer";
 1166:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1167:     my $remoteurl=subscribe($filename);
 1168:     if ($remoteurl =~ /^con_lost by/) {
 1169: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1170:            return 'unavailable';
 1171:     } elsif ($remoteurl eq 'not_found') {
 1172: 	   #&logthis("Subscribe returned not_found: $filename");
 1173: 	   return 'not_found';
 1174:     } elsif ($remoteurl =~ /^rejected by/) {
 1175: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1176:            return 'forbidden';
 1177:     } elsif ($remoteurl eq 'directory') {
 1178:            return 'ok';
 1179:     } else {
 1180:         my $author=$filename;
 1181:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1182:         my ($udom,$uname)=split(/\//,$author);
 1183:         my $home=homeserver($uname,$udom);
 1184:         unless ($home eq $perlvar{'lonHostID'}) {
 1185:            my @parts=split(/\//,$filename);
 1186:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1187:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1188:                &logthis("Malconfiguration for replication: $filename");
 1189: 	       return 'bad_request';
 1190:            }
 1191:            my $count;
 1192:            for ($count=5;$count<$#parts;$count++) {
 1193:                $path.="/$parts[$count]";
 1194:                if ((-e $path)!=1) {
 1195: 		   mkdir($path,0777);
 1196:                }
 1197:            }
 1198:            my $ua=new LWP::UserAgent;
 1199:            my $request=new HTTP::Request('GET',"$remoteurl");
 1200:            my $response=$ua->request($request,$transname);
 1201:            if ($response->is_error()) {
 1202: 	       unlink($transname);
 1203:                my $message=$response->status_line;
 1204:                &logthis("<font color=\"blue\">WARNING:"
 1205:                        ." LWP get: $message: $filename</font>");
 1206:                return 'unavailable';
 1207:            } else {
 1208: 	       if ($remoteurl!~/\.meta$/) {
 1209:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1210:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1211:                   if ($mresponse->is_error()) {
 1212: 		      unlink($filename.'.meta');
 1213:                       &logthis(
 1214:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1215:                   }
 1216: 	       }
 1217:                rename($transname,$filename);
 1218:                return 'ok';
 1219:            }
 1220:        }
 1221:     }
 1222: }
 1223: 
 1224: # ------------------------------------------------ Get server side include body
 1225: sub ssi_body {
 1226:     my ($filelink,%form)=@_;
 1227:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1228:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1229:     }
 1230:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1231:                                      &ssi($filelink,%form));
 1232:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1233:     $output=~s/^.*?\<body[^\>]*\>//si;
 1234:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1235:     return $output;
 1236: }
 1237: 
 1238: # --------------------------------------------------------- Server Side Include
 1239: 
 1240: sub absolute_url {
 1241:     my ($host_name) = @_;
 1242:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1243:     if ($host_name eq '') {
 1244: 	$host_name = $ENV{'SERVER_NAME'};
 1245:     }
 1246:     return $protocol.$host_name;
 1247: }
 1248: 
 1249: sub ssi {
 1250: 
 1251:     my ($fn,%form)=@_;
 1252: 
 1253:     my $ua=new LWP::UserAgent;
 1254:     
 1255:     my $request;
 1256: 
 1257:     $form{'no_update_last_known'}=1;
 1258: 
 1259:     if (%form) {
 1260:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1261:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1262:     } else {
 1263:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1264:     }
 1265: 
 1266:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1267:     my $response=$ua->request($request);
 1268: 
 1269:     return $response->content;
 1270: }
 1271: 
 1272: sub externalssi {
 1273:     my ($url)=@_;
 1274:     my $ua=new LWP::UserAgent;
 1275:     my $request=new HTTP::Request('GET',$url);
 1276:     my $response=$ua->request($request);
 1277:     return $response->content;
 1278: }
 1279: 
 1280: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1281: 
 1282: sub allowuploaded {
 1283:     my ($srcurl,$url)=@_;
 1284:     $url=&clutter(&declutter($url));
 1285:     my $dir=$url;
 1286:     $dir=~s/\/[^\/]+$//;
 1287:     my %httpref=();
 1288:     my $httpurl=&hreflocation('',$url);
 1289:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1290:     &Apache::lonnet::appenv(%httpref);
 1291: }
 1292: 
 1293: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1294: # input: action, courseID, current domain, intended
 1295: #        path to file, source of file, instruction to parse file for objects,
 1296: #        ref to hash for embedded objects,
 1297: #        ref to hash for codebase of java objects.
 1298: #
 1299: # output: url to file (if action was uploaddoc), 
 1300: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1301: #
 1302: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1303: # course.
 1304: #
 1305: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1306: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1307: #          course's home server.
 1308: #
 1309: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1310: #          be copied from $source (current location) to 
 1311: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1312: #         and will then be copied to
 1313: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1314: #         course's home server.
 1315: #
 1316: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1317: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1318: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1319: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1320: #         in course's home server.
 1321: #
 1322: 
 1323: sub process_coursefile {
 1324:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1325:     my $fetchresult;
 1326:     my $home=&homeserver($docuname,$docudom);
 1327:     if ($action eq 'propagate') {
 1328:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1329: 			     $home);
 1330:     } else {
 1331:         my $fpath = '';
 1332:         my $fname = $file;
 1333:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1334:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1335:         my $filepath = &build_filepath($fpath);
 1336:         if ($action eq 'copy') {
 1337:             if ($source eq '') {
 1338:                 $fetchresult = 'no source file';
 1339:                 return $fetchresult;
 1340:             } else {
 1341:                 my $destination = $filepath.'/'.$fname;
 1342:                 rename($source,$destination);
 1343:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1344:                                  $home);
 1345:             }
 1346:         } elsif ($action eq 'uploaddoc') {
 1347:             open(my $fh,'>'.$filepath.'/'.$fname);
 1348:             print $fh $env{'form.'.$source};
 1349:             close($fh);
 1350:             if ($parser eq 'parse') {
 1351:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1352:                 unless ($parse_result eq 'ok') {
 1353:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1354:                 }
 1355:             }
 1356:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1357:                                  $home);
 1358:             if ($fetchresult eq 'ok') {
 1359:                 return '/uploaded/'.$fpath.'/'.$fname;
 1360:             } else {
 1361:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1362:                         ' to host '.$home.': '.$fetchresult);
 1363:                 return '/adm/notfound.html';
 1364:             }
 1365:         }
 1366:     }
 1367:     unless ( $fetchresult eq 'ok') {
 1368:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1369:              ' to host '.$home.': '.$fetchresult);
 1370:     }
 1371:     return $fetchresult;
 1372: }
 1373: 
 1374: sub build_filepath {
 1375:     my ($fpath) = @_;
 1376:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1377:     unless ($fpath eq '') {
 1378:         my @parts=split('/',$fpath);
 1379:         foreach my $part (@parts) {
 1380:             $filepath.= '/'.$part;
 1381:             if ((-e $filepath)!=1) {
 1382:                 mkdir($filepath,0777);
 1383:             }
 1384:         }
 1385:     }
 1386:     return $filepath;
 1387: }
 1388: 
 1389: sub store_edited_file {
 1390:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1391:     my $file = $primary_url;
 1392:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1393:     my $fpath = '';
 1394:     my $fname = $file;
 1395:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1396:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1397:     my $filepath = &build_filepath($fpath);
 1398:     open(my $fh,'>'.$filepath.'/'.$fname);
 1399:     print $fh $content;
 1400:     close($fh);
 1401:     my $home=&homeserver($docuname,$docudom);
 1402:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1403: 			  $home);
 1404:     if ($$fetchresult eq 'ok') {
 1405:         return '/uploaded/'.$fpath.'/'.$fname;
 1406:     } else {
 1407:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1408: 		 ' to host '.$home.': '.$$fetchresult);
 1409:         return '/adm/notfound.html';
 1410:     }
 1411: }
 1412: 
 1413: sub clean_filename {
 1414:     my ($fname)=@_;
 1415: # Replace Windows backslashes by forward slashes
 1416:     $fname=~s/\\/\//g;
 1417: # Get rid of everything but the actual filename
 1418:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1419: # Replace spaces by underscores
 1420:     $fname=~s/\s+/\_/g;
 1421: # Replace all other weird characters by nothing
 1422:     $fname=~s/[^\w\.\-]//g;
 1423: # Replace all .\d. sequences with _\d. so they no longer look like version
 1424: # numbers
 1425:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1426:     return $fname;
 1427: }
 1428: 
 1429: # --------------- Take an uploaded file and put it into the userfiles directory
 1430: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1431: #                    the desired filenam is in $env{"form.$formname.filename"}
 1432: #        $coursedoc - if true up to the current course
 1433: #                     if false
 1434: #        $subdir - directory in userfile to store the file into
 1435: #        $parser, $allfiles, $codebase - unknown
 1436: #
 1437: # output: url of file in userspace, or error: <message> 
 1438: #             or /adm/notfound.html if failure to upload occurse
 1439: 
 1440: 
 1441: sub userfileupload {
 1442:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
 1443:     if (!defined($subdir)) { $subdir='unknown'; }
 1444:     my $fname=$env{'form.'.$formname.'.filename'};
 1445:     $fname=&clean_filename($fname);
 1446: # See if there is anything left
 1447:     unless ($fname) { return 'error: no uploaded file'; }
 1448:     chop($env{'form.'.$formname});
 1449:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1450:         my $now = time;
 1451:         my $filepath = 'tmp/helprequests/'.$now;
 1452:         my @parts=split(/\//,$filepath);
 1453:         my $fullpath = $perlvar{'lonDaemons'};
 1454:         for (my $i=0;$i<@parts;$i++) {
 1455:             $fullpath .= '/'.$parts[$i];
 1456:             if ((-e $fullpath)!=1) {
 1457:                 mkdir($fullpath,0777);
 1458:             }
 1459:         }
 1460:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1461:         print $fh $env{'form.'.$formname};
 1462:         close($fh);
 1463:         return $fullpath.'/'.$fname;
 1464:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1465:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1466:                        '_'.$env{'user.domain'}.'/pending';
 1467:         my @parts=split(/\//,$filepath);
 1468:         my $fullpath = $perlvar{'lonDaemons'};
 1469:         for (my $i=0;$i<@parts;$i++) {
 1470:             $fullpath .= '/'.$parts[$i];
 1471:             if ((-e $fullpath)!=1) {
 1472:                 mkdir($fullpath,0777);
 1473:             }
 1474:         }
 1475:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1476:         print $fh $env{'form.'.$formname};
 1477:         close($fh);
 1478:         return $fullpath.'/'.$fname;
 1479:     }
 1480:     
 1481: # Create the directory if not present
 1482:     $fname="$subdir/$fname";
 1483:     if ($coursedoc) {
 1484: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1485: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1486:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1487:             return &finishuserfileupload($docuname,$docudom,
 1488: 					 $formname,$fname,$parser,$allfiles,
 1489: 					 $codebase);
 1490:         } else {
 1491:             $fname=$env{'form.folder'}.'/'.$fname;
 1492:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1493: 				       $fname,$formname,$parser,
 1494: 				       $allfiles,$codebase);
 1495:         }
 1496:     } elsif (defined($destuname)) {
 1497:         my $docuname=$destuname;
 1498:         my $docudom=$destudom;
 1499: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1500: 				     $fname,$parser,$allfiles,$codebase);
 1501:         
 1502:     } else {
 1503:         my $docuname=$env{'user.name'};
 1504:         my $docudom=$env{'user.domain'};
 1505:         if (exists($env{'form.group'})) {
 1506:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1507:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1508:         }
 1509: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1510: 				     $fname,$parser,$allfiles,$codebase);
 1511:     }
 1512: }
 1513: 
 1514: sub finishuserfileupload {
 1515:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1516:     my $path=$docudom.'/'.$docuname.'/';
 1517:     my $filepath=$perlvar{'lonDocRoot'};
 1518:     my ($fnamepath,$file);
 1519:     $file=$fname;
 1520:     if ($fname=~m|/|) {
 1521:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1522: 	$path.=$fnamepath.'/';
 1523:     }
 1524:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1525:     my $count;
 1526:     for ($count=4;$count<=$#parts;$count++) {
 1527:         $filepath.="/$parts[$count]";
 1528:         if ((-e $filepath)!=1) {
 1529: 	    mkdir($filepath,0777);
 1530:         }
 1531:     }
 1532: # Save the file
 1533:     {
 1534: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1535: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1536: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1537: 	    return '/adm/notfound.html';
 1538: 	}
 1539: 	if (!print FH ($env{'form.'.$formname})) {
 1540: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1541: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1542: 	    return '/adm/notfound.html';
 1543: 	}
 1544: 	close(FH);
 1545:     }
 1546:     if ($parser eq 'parse') {
 1547:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1548: 						   $codebase);
 1549:         unless ($parse_result eq 'ok') {
 1550:             &logthis('Failed to parse '.$filepath.$file.
 1551: 		     ' for embedded media: '.$parse_result); 
 1552:         }
 1553:     }
 1554: # Notify homeserver to grep it
 1555: #
 1556:     my $docuhome=&homeserver($docuname,$docudom);
 1557:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1558:     if ($fetchresult eq 'ok') {
 1559: #
 1560: # Return the URL to it
 1561:         return '/uploaded/'.$path.$file;
 1562:     } else {
 1563:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1564: 		 ': '.$fetchresult);
 1565:         return '/adm/notfound.html';
 1566:     }    
 1567: }
 1568: 
 1569: sub extract_embedded_items {
 1570:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1571:     my @state = ();
 1572:     my %javafiles = (
 1573:                       codebase => '',
 1574:                       code => '',
 1575:                       archive => ''
 1576:                     );
 1577:     my %mediafiles = (
 1578:                       src => '',
 1579:                       movie => '',
 1580:                      );
 1581:     my $p;
 1582:     if ($content) {
 1583:         $p = HTML::LCParser->new($content);
 1584:     } else {
 1585:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1586:     }
 1587:     while (my $t=$p->get_token()) {
 1588: 	if ($t->[0] eq 'S') {
 1589: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1590: 	    push (@state, $tagname);
 1591:             if (lc($tagname) eq 'allow') {
 1592:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1593:             }
 1594: 	    if (lc($tagname) eq 'img') {
 1595: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1596: 	    }
 1597:             if (lc($tagname) eq 'script') {
 1598:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1599:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1600:                 } else {
 1601:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1602:                 }
 1603:             }
 1604:             if (lc($tagname) eq 'link') {
 1605:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1606:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1607:                 }
 1608:             }
 1609: 	    if (lc($tagname) eq 'object' ||
 1610: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1611: 		foreach my $item (keys(%javafiles)) {
 1612: 		    $javafiles{$item} = '';
 1613: 		}
 1614: 	    }
 1615: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1616: 		my $name = lc($attr->{'name'});
 1617: 		foreach my $item (keys(%javafiles)) {
 1618: 		    if ($name eq $item) {
 1619: 			$javafiles{$item} = $attr->{'value'};
 1620: 			last;
 1621: 		    }
 1622: 		}
 1623: 		foreach my $item (keys(%mediafiles)) {
 1624: 		    if ($name eq $item) {
 1625: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1626: 			last;
 1627: 		    }
 1628: 		}
 1629: 	    }
 1630: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1631: 		foreach my $item (keys(%javafiles)) {
 1632: 		    if ($attr->{$item}) {
 1633: 			$javafiles{$item} = $attr->{$item};
 1634: 			last;
 1635: 		    }
 1636: 		}
 1637: 		foreach my $item (keys(%mediafiles)) {
 1638: 		    if ($attr->{$item}) {
 1639: 			&add_filetype($allfiles,$attr->{$item},$item);
 1640: 			last;
 1641: 		    }
 1642: 		}
 1643: 	    }
 1644: 	} elsif ($t->[0] eq 'E') {
 1645: 	    my ($tagname) = ($t->[1]);
 1646: 	    if ($javafiles{'codebase'} ne '') {
 1647: 		$javafiles{'codebase'} .= '/';
 1648: 	    }  
 1649: 	    if (lc($tagname) eq 'applet' ||
 1650: 		lc($tagname) eq 'object' ||
 1651: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1652: 		) {
 1653: 		foreach my $item (keys(%javafiles)) {
 1654: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1655: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1656: 			&add_filetype($allfiles,$file,$item);
 1657: 		    }
 1658: 		}
 1659: 	    } 
 1660: 	    pop @state;
 1661: 	}
 1662:     }
 1663:     return 'ok';
 1664: }
 1665: 
 1666: sub add_filetype {
 1667:     my ($allfiles,$file,$type)=@_;
 1668:     if (exists($allfiles->{$file})) {
 1669: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1670: 	    push(@{$allfiles->{$file}}, &escape($type));
 1671: 	}
 1672:     } else {
 1673: 	@{$allfiles->{$file}} = (&escape($type));
 1674:     }
 1675: }
 1676: 
 1677: sub removeuploadedurl {
 1678:     my ($url)=@_;
 1679:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1680:     return &removeuserfile($uname,$udom,$fname);
 1681: }
 1682: 
 1683: sub removeuserfile {
 1684:     my ($docuname,$docudom,$fname)=@_;
 1685:     my $home=&homeserver($docuname,$docudom);
 1686:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1687:     if ($result eq 'ok') {
 1688:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1689:             my $metafile = $fname.'.meta';
 1690:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1691:         }
 1692:     }
 1693:     return $result;
 1694: }
 1695: 
 1696: sub mkdiruserfile {
 1697:     my ($docuname,$docudom,$dir)=@_;
 1698:     my $home=&homeserver($docuname,$docudom);
 1699:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1700: }
 1701: 
 1702: sub renameuserfile {
 1703:     my ($docuname,$docudom,$old,$new)=@_;
 1704:     my $home=&homeserver($docuname,$docudom);
 1705:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1706:                         &escape("$old").':'.&escape("$new"),$home);
 1707:     if ($result eq 'ok') {
 1708:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1709:             my $oldmeta = $old.'.meta';
 1710:             my $newmeta = $new.'.meta';
 1711:             my $metaresult = 
 1712:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1713:         }
 1714:     }
 1715:     return $result;
 1716: }
 1717: 
 1718: # ------------------------------------------------------------------------- Log
 1719: 
 1720: sub log {
 1721:     my ($dom,$nam,$hom,$what)=@_;
 1722:     return critical("log:$dom:$nam:$what",$hom);
 1723: }
 1724: 
 1725: # ------------------------------------------------------------------ Course Log
 1726: #
 1727: # This routine flushes several buffers of non-mission-critical nature
 1728: #
 1729: 
 1730: sub flushcourselogs {
 1731:     &logthis('Flushing log buffers');
 1732: #
 1733: # course logs
 1734: # This is a log of all transactions in a course, which can be used
 1735: # for data mining purposes
 1736: #
 1737: # It also collects the courseid database, which lists last transaction
 1738: # times and course titles for all courseids
 1739: #
 1740:     my %courseidbuffer=();
 1741:     foreach my $crsid (keys %courselogs) {
 1742:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1743: 		          &escape($courselogs{$crsid}),
 1744: 		          $coursehombuf{$crsid}) eq 'ok') {
 1745: 	    delete $courselogs{$crsid};
 1746:         } else {
 1747:             &logthis('Failed to flush log buffer for '.$crsid);
 1748:             if (length($courselogs{$crsid})>40000) {
 1749:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1750:                         " exceeded maximum size, deleting.</font>");
 1751:                delete $courselogs{$crsid};
 1752:             }
 1753:         }
 1754:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1755:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1756: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1757:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1758:         } else {
 1759:            $courseidbuffer{$coursehombuf{$crsid}}=
 1760: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1761:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1762:         }
 1763:     }
 1764: #
 1765: # Write course id database (reverse lookup) to homeserver of courses 
 1766: # Is used in pickcourse
 1767: #
 1768:     foreach my $crsid (keys(%courseidbuffer)) {
 1769:         &courseidput($hostdom{$crsid},$courseidbuffer{$crsid},$crsid);
 1770:     }
 1771: #
 1772: # File accesses
 1773: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1774: #
 1775:     foreach my $entry (keys(%accesshash)) {
 1776:         if ($entry =~ /___count$/) {
 1777:             my ($dom,$name);
 1778:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1779:             if (! defined($dom) || $dom eq '' || 
 1780:                 ! defined($name) || $name eq '') {
 1781:                 my $cid = $env{'request.course.id'};
 1782:                 $dom  = $env{'request.'.$cid.'.domain'};
 1783:                 $name = $env{'request.'.$cid.'.num'};
 1784:             }
 1785:             my $value = $accesshash{$entry};
 1786:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1787:             my %temphash=($url => $value);
 1788:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1789:             if ($result eq 'ok') {
 1790:                 delete $accesshash{$entry};
 1791:             } elsif ($result eq 'unknown_cmd') {
 1792:                 # Target server has old code running on it.
 1793:                 my %temphash=($entry => $value);
 1794:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1795:                     delete $accesshash{$entry};
 1796:                 }
 1797:             }
 1798:         } else {
 1799:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1800:             my %temphash=($entry => $accesshash{$entry});
 1801:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1802:                 delete $accesshash{$entry};
 1803:             }
 1804:         }
 1805:     }
 1806: #
 1807: # Roles
 1808: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1809: #
 1810:     foreach my $entry (keys(%userrolehash)) {
 1811:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1812: 	    split(/\:/,$entry);
 1813:         if (&Apache::lonnet::put('nohist_userroles',
 1814:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1815:                 $rudom,$runame) eq 'ok') {
 1816: 	    delete $userrolehash{$entry};
 1817:         }
 1818:     }
 1819: #
 1820: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1821: #
 1822:     my %domrolebuffer = ();
 1823:     foreach my $entry (keys %domainrolehash) {
 1824:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1825:         if ($domrolebuffer{$rudom}) {
 1826:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1827:                       '='.&escape($domainrolehash{$entry});
 1828:         } else {
 1829:             $domrolebuffer{$rudom}.=&escape($entry).
 1830:                       '='.&escape($domainrolehash{$entry});
 1831:         }
 1832:         delete $domainrolehash{$entry};
 1833:     }
 1834:     foreach my $dom (keys(%domrolebuffer)) {
 1835:         foreach my $tryserver (keys %libserv) {
 1836:             if ($hostdom{$tryserver} eq $dom) {
 1837:                 unless (&reply('domroleput:'.$dom.':'.
 1838:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1839:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1840:                 }
 1841:             }
 1842:         }
 1843:     }
 1844:     $dumpcount++;
 1845: }
 1846: 
 1847: sub courselog {
 1848:     my $what=shift;
 1849:     $what=time.':'.$what;
 1850:     unless ($env{'request.course.id'}) { return ''; }
 1851:     $coursedombuf{$env{'request.course.id'}}=
 1852:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1853:     $coursenumbuf{$env{'request.course.id'}}=
 1854:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1855:     $coursehombuf{$env{'request.course.id'}}=
 1856:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1857:     $coursedescrbuf{$env{'request.course.id'}}=
 1858:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1859:     $courseinstcodebuf{$env{'request.course.id'}}=
 1860:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1861:     $courseownerbuf{$env{'request.course.id'}}=
 1862:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1863:     $coursetypebuf{$env{'request.course.id'}}=
 1864:        $env{'course.'.$env{'request.course.id'}.'.type'};
 1865:     if (defined $courselogs{$env{'request.course.id'}}) {
 1866: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1867:     } else {
 1868: 	$courselogs{$env{'request.course.id'}}.=$what;
 1869:     }
 1870:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1871: 	&flushcourselogs();
 1872:     }
 1873: }
 1874: 
 1875: sub courseacclog {
 1876:     my $fnsymb=shift;
 1877:     unless ($env{'request.course.id'}) { return ''; }
 1878:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1879:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1880:         $what.=':POST';
 1881:         # FIXME: Probably ought to escape things....
 1882: 	foreach my $key (keys(%env)) {
 1883:             if ($key=~/^form\.(.*)/) {
 1884: 		$what.=':'.$1.'='.$env{$key};
 1885:             }
 1886:         }
 1887:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1888:         # FIXME: We should not be depending on a form parameter that someone
 1889:         # editing lonsearchcat.pm might change in the future.
 1890:         if ($env{'form.phase'} eq 'course_search') {
 1891:             $what.= ':POST';
 1892:             # FIXME: Probably ought to escape things....
 1893:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1894:                                  'crsdiscuss') {
 1895:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1896:             }
 1897:         }
 1898:     }
 1899:     &courselog($what);
 1900: }
 1901: 
 1902: sub countacc {
 1903:     my $url=&declutter(shift);
 1904:     return if (! defined($url) || $url eq '');
 1905:     unless ($env{'request.course.id'}) { return ''; }
 1906:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1907:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1908:     $accesshash{$key}++;
 1909: }
 1910: 
 1911: sub linklog {
 1912:     my ($from,$to)=@_;
 1913:     $from=&declutter($from);
 1914:     $to=&declutter($to);
 1915:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1916:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1917: }
 1918:   
 1919: sub userrolelog {
 1920:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1921:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1922:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1923:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1924:         ($trole=~/^ta/)) {
 1925:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1926:        $userrolehash
 1927:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1928:                     =$tend.':'.$tstart;
 1929:     }
 1930:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1931:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1932:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1933:         ($trole=~/^sc/)) {
 1934:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1935:        $domainrolehash
 1936:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1937:                     = $tend.':'.$tstart;
 1938:     }
 1939: }
 1940: 
 1941: sub get_course_adv_roles {
 1942:     my $cid=shift;
 1943:     $cid=$env{'request.course.id'} unless (defined($cid));
 1944:     my %coursehash=&coursedescription($cid);
 1945:     my %nothide=();
 1946:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1947: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 1948:     }
 1949:     my %returnhash=();
 1950:     my %dumphash=
 1951:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1952:     my $now=time;
 1953:     foreach my $entry (keys %dumphash) {
 1954: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 1955:         if (($tstart) && ($tstart<0)) { next; }
 1956:         if (($tend) && ($tend<$now)) { next; }
 1957:         if (($tstart) && ($now<$tstart)) { next; }
 1958:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 1959: 	if ($username eq '' || $domain eq '') { next; }
 1960: 	if ((&privileged($username,$domain)) && 
 1961: 	    (!$nothide{$username.':'.$domain})) { next; }
 1962: 	if ($role eq 'cr') { next; }
 1963:         my $key=&plaintext($role);
 1964:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1965:         if ($returnhash{$key}) {
 1966: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1967:         } else {
 1968:             $returnhash{$key}=$username.':'.$domain;
 1969:         }
 1970:      }
 1971:     return %returnhash;
 1972: }
 1973: 
 1974: sub get_my_roles {
 1975:     my ($uname,$udom)=@_;
 1976:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1977:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1978:     my %dumphash=
 1979:             &dump('nohist_userroles',$udom,$uname);
 1980:     my %returnhash=();
 1981:     my $now=time;
 1982:     foreach my $entry (keys(%dumphash)) {
 1983: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 1984:         if (($tstart) && ($tstart<0)) { next; }
 1985:         if (($tend) && ($tend<$now)) { next; }
 1986:         if (($tstart) && ($now<$tstart)) { next; }
 1987:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 1988: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1989:      }
 1990:     return %returnhash;
 1991: }
 1992: 
 1993: # ----------------------------------------------------- Frontpage Announcements
 1994: #
 1995: #
 1996: 
 1997: sub postannounce {
 1998:     my ($server,$text)=@_;
 1999:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 2000:     unless ($text=~/\w/) { $text=''; }
 2001:     return &reply('setannounce:'.&escape($text),$server);
 2002: }
 2003: 
 2004: sub getannounce {
 2005: 
 2006:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2007: 	my $announcement='';
 2008: 	while (my $line = <$fh>) { $announcement .= $line; }
 2009: 	close($fh);
 2010: 	if ($announcement=~/\w/) { 
 2011: 	    return 
 2012:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2013:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2014: 	} else {
 2015: 	    return '';
 2016: 	}
 2017:     } else {
 2018: 	return '';
 2019:     }
 2020: }
 2021: 
 2022: # ---------------------------------------------------------- Course ID routines
 2023: # Deal with domain's nohist_courseid.db files
 2024: #
 2025: 
 2026: sub courseidput {
 2027:     my ($domain,$what,$coursehome)=@_;
 2028:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2029: }
 2030: 
 2031: sub courseiddump {
 2032:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2033:     my %returnhash=();
 2034:     unless ($domfilter) { $domfilter=''; }
 2035:     foreach my $tryserver (keys %libserv) {
 2036:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 2037: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 2038: 	        foreach my $line (
 2039:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 2040: 			       $sincefilter.':'.&escape($descfilter).':'.
 2041:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2042:                                $tryserver))) {
 2043: 		    my ($key,$value)=split(/\=/,$line,2);
 2044:                     if (($key) && ($value)) {
 2045: 		        $returnhash{&unescape($key)}=$value;
 2046:                     }
 2047:                 }
 2048:             }
 2049:         }
 2050:     }
 2051:     return %returnhash;
 2052: }
 2053: 
 2054: # ---------------------------------------------------------- DC e-mail
 2055: 
 2056: sub dcmailput {
 2057:     my ($domain,$msgid,$message,$server)=@_;
 2058:     my $status = &Apache::lonnet::critical(
 2059:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2060:        &escape($message),$server);
 2061:     return $status;
 2062: }
 2063: 
 2064: sub dcmaildump {
 2065:     my ($dom,$startdate,$enddate,$senders) = @_;
 2066:     my %returnhash=();
 2067:     if (exists($domain_primary{$dom})) {
 2068:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2069:                                                          &escape($enddate).':';
 2070: 	my @esc_senders=map { &escape($_)} @$senders;
 2071: 	$cmd.=&escape(join('&',@esc_senders));
 2072: 	foreach my $line (split(/\&/,&reply($cmd,$domain_primary{$dom}))) {
 2073:             my ($key,$value) = split(/\=/,$line,2);
 2074:             if (($key) && ($value)) {
 2075:                 $returnhash{&unescape($key)} = &unescape($value);
 2076:             }
 2077:         }
 2078:     }
 2079:     return %returnhash;
 2080: }
 2081: # ---------------------------------------------------------- Domain roles
 2082: 
 2083: sub get_domain_roles {
 2084:     my ($dom,$roles,$startdate,$enddate)=@_;
 2085:     if (undef($startdate) || $startdate eq '') {
 2086:         $startdate = '.';
 2087:     }
 2088:     if (undef($enddate) || $enddate eq '') {
 2089:         $enddate = '.';
 2090:     }
 2091:     my $rolelist = join(':',@{$roles});
 2092:     my %personnel = ();
 2093:     foreach my $tryserver (keys(%libserv)) {
 2094:         if ($hostdom{$tryserver} eq $dom) {
 2095:             %{$personnel{$tryserver}}=();
 2096:             foreach my $line (
 2097:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2098:                    &escape($startdate).':'.&escape($enddate).':'.
 2099:                    &escape($rolelist), $tryserver))) {
 2100:                 my ($key,$value) = split(/\=/,$line,2);
 2101:                 if (($key) && ($value)) {
 2102:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2103:                 }
 2104:             }
 2105:         }
 2106:     }
 2107:     return %personnel;
 2108: }
 2109: 
 2110: # ----------------------------------------------------------- Check out an item
 2111: 
 2112: sub get_first_access {
 2113:     my ($type,$argsymb)=@_;
 2114:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2115:     if ($argsymb) { $symb=$argsymb; }
 2116:     my ($map,$id,$res)=&decode_symb($symb);
 2117:     if ($type eq 'map') {
 2118: 	$res=&symbread($map);
 2119:     } else {
 2120: 	$res=$symb;
 2121:     }
 2122:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2123:     return $times{"$courseid\0$res"};
 2124: }
 2125: 
 2126: sub set_first_access {
 2127:     my ($type)=@_;
 2128:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2129:     my ($map,$id,$res)=&decode_symb($symb);
 2130:     if ($type eq 'map') {
 2131: 	$res=&symbread($map);
 2132:     } else {
 2133: 	$res=$symb;
 2134:     }
 2135:     my $firstaccess=&get_first_access($type,$symb);
 2136:     if (!$firstaccess) {
 2137: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2138:     }
 2139:     return 'already_set';
 2140: }
 2141: 
 2142: sub checkout {
 2143:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2144:     my $now=time;
 2145:     my $lonhost=$perlvar{'lonHostID'};
 2146:     my $infostr=&escape(
 2147:                  'CHECKOUTTOKEN&'.
 2148:                  $tuname.'&'.
 2149:                  $tudom.'&'.
 2150:                  $tcrsid.'&'.
 2151:                  $symb.'&'.
 2152: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2153:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2154:     if ($token=~/^error\:/) { 
 2155:         &logthis("<font color=\"blue\">WARNING: ".
 2156:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2157:                  "</font>");
 2158:         return ''; 
 2159:     }
 2160: 
 2161:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2162:     $token=~tr/a-z/A-Z/;
 2163: 
 2164:     my %infohash=('resource.0.outtoken' => $token,
 2165:                   'resource.0.checkouttime' => $now,
 2166:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2167: 
 2168:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2169:        return '';
 2170:     } else {
 2171:         &logthis("<font color=\"blue\">WARNING: ".
 2172:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2173:                  "</font>");
 2174:     }    
 2175: 
 2176:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2177:                          &escape('Checkout '.$infostr.' - '.
 2178:                                                  $token)) ne 'ok') {
 2179: 	return '';
 2180:     } else {
 2181:         &logthis("<font color=\"blue\">WARNING: ".
 2182:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2183:                  "</font>");
 2184:     }
 2185:     return $token;
 2186: }
 2187: 
 2188: # ------------------------------------------------------------ Check in an item
 2189: 
 2190: sub checkin {
 2191:     my $token=shift;
 2192:     my $now=time;
 2193:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2194:     $lonhost=~tr/A-Z/a-z/;
 2195:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 2196:     $dtoken=~s/\W/\_/g;
 2197:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2198:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2199: 
 2200:     unless (($tuname) && ($tudom)) {
 2201:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2202:         return '';
 2203:     }
 2204:     
 2205:     unless (&allowed('mgr',$tcrsid)) {
 2206:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2207:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2208:         return '';
 2209:     }
 2210: 
 2211:     my %infohash=('resource.0.intoken' => $token,
 2212:                   'resource.0.checkintime' => $now,
 2213:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2214: 
 2215:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2216:        return '';
 2217:     }    
 2218: 
 2219:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2220:                          &escape('Checkin - '.$token)) ne 'ok') {
 2221: 	return '';
 2222:     }
 2223: 
 2224:     return ($symb,$tuname,$tudom,$tcrsid);    
 2225: }
 2226: 
 2227: # --------------------------------------------- Set Expire Date for Spreadsheet
 2228: 
 2229: sub expirespread {
 2230:     my ($uname,$udom,$stype,$usymb)=@_;
 2231:     my $cid=$env{'request.course.id'}; 
 2232:     if ($cid) {
 2233:        my $now=time;
 2234:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2235:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2236:                             $env{'course.'.$cid.'.num'}.
 2237: 	        	    ':nohist_expirationdates:'.
 2238:                             &escape($key).'='.$now,
 2239:                             $env{'course.'.$cid.'.home'})
 2240:     }
 2241:     return 'ok';
 2242: }
 2243: 
 2244: # ----------------------------------------------------- Devalidate Spreadsheets
 2245: 
 2246: sub devalidate {
 2247:     my ($symb,$uname,$udom)=@_;
 2248:     my $cid=$env{'request.course.id'}; 
 2249:     if ($cid) {
 2250:         # delete the stored spreadsheets for
 2251:         # - the student level sheet of this user in course's homespace
 2252:         # - the assessment level sheet for this resource 
 2253:         #   for this user in user's homespace
 2254: 	# - current conditional state info
 2255: 	my $key=$uname.':'.$udom.':';
 2256:         my $status=
 2257: 	    &del('nohist_calculatedsheets',
 2258: 		 [$key.'studentcalc:'],
 2259: 		 $env{'course.'.$cid.'.domain'},
 2260: 		 $env{'course.'.$cid.'.num'})
 2261: 		.' '.
 2262: 	    &del('nohist_calculatedsheets_'.$cid,
 2263: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2264:         unless ($status eq 'ok ok') {
 2265:            &logthis('Could not devalidate spreadsheet '.
 2266:                     $uname.' at '.$udom.' for '.
 2267: 		    $symb.': '.$status);
 2268:         }
 2269: 	&delenv('user.state.'.$cid);
 2270:     }
 2271: }
 2272: 
 2273: sub get_scalar {
 2274:     my ($string,$end) = @_;
 2275:     my $value;
 2276:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2277: 	$value = $1;
 2278:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2279: 	$value = $1;
 2280:     }
 2281:     return &unescape($value);
 2282: }
 2283: 
 2284: sub array2str {
 2285:   my (@array) = @_;
 2286:   my $result=&arrayref2str(\@array);
 2287:   $result=~s/^__ARRAY_REF__//;
 2288:   $result=~s/__END_ARRAY_REF__$//;
 2289:   return $result;
 2290: }
 2291: 
 2292: sub arrayref2str {
 2293:   my ($arrayref) = @_;
 2294:   my $result='__ARRAY_REF__';
 2295:   foreach my $elem (@$arrayref) {
 2296:     if(ref($elem) eq 'ARRAY') {
 2297:       $result.=&arrayref2str($elem).'&';
 2298:     } elsif(ref($elem) eq 'HASH') {
 2299:       $result.=&hashref2str($elem).'&';
 2300:     } elsif(ref($elem)) {
 2301:       #print("Got a ref of ".(ref($elem))." skipping.");
 2302:     } else {
 2303:       $result.=&escape($elem).'&';
 2304:     }
 2305:   }
 2306:   $result=~s/\&$//;
 2307:   $result .= '__END_ARRAY_REF__';
 2308:   return $result;
 2309: }
 2310: 
 2311: sub hash2str {
 2312:   my (%hash) = @_;
 2313:   my $result=&hashref2str(\%hash);
 2314:   $result=~s/^__HASH_REF__//;
 2315:   $result=~s/__END_HASH_REF__$//;
 2316:   return $result;
 2317: }
 2318: 
 2319: sub hashref2str {
 2320:   my ($hashref)=@_;
 2321:   my $result='__HASH_REF__';
 2322:   foreach my $key (sort(keys(%$hashref))) {
 2323:     if (ref($key) eq 'ARRAY') {
 2324:       $result.=&arrayref2str($key).'=';
 2325:     } elsif (ref($key) eq 'HASH') {
 2326:       $result.=&hashref2str($key).'=';
 2327:     } elsif (ref($key)) {
 2328:       $result.='=';
 2329:       #print("Got a ref of ".(ref($key))." skipping.");
 2330:     } else {
 2331: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2332:     }
 2333: 
 2334:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2335:       $result.=&arrayref2str($hashref->{$key}).'&';
 2336:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2337:       $result.=&hashref2str($hashref->{$key}).'&';
 2338:     } elsif(ref($hashref->{$key})) {
 2339:        $result.='&';
 2340:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2341:     } else {
 2342:       $result.=&escape($hashref->{$key}).'&';
 2343:     }
 2344:   }
 2345:   $result=~s/\&$//;
 2346:   $result .= '__END_HASH_REF__';
 2347:   return $result;
 2348: }
 2349: 
 2350: sub str2hash {
 2351:     my ($string)=@_;
 2352:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2353:     return %$hash;
 2354: }
 2355: 
 2356: sub str2hashref {
 2357:   my ($string) = @_;
 2358: 
 2359:   my %hash;
 2360: 
 2361:   if($string !~ /^__HASH_REF__/) {
 2362:       if (! ($string eq '' || !defined($string))) {
 2363: 	  $hash{'error'}='Not hash reference';
 2364:       }
 2365:       return (\%hash, $string);
 2366:   }
 2367: 
 2368:   $string =~ s/^__HASH_REF__//;
 2369: 
 2370:   while($string !~ /^__END_HASH_REF__/) {
 2371:       #key
 2372:       my $key='';
 2373:       if($string =~ /^__HASH_REF__/) {
 2374:           ($key, $string)=&str2hashref($string);
 2375:           if(defined($key->{'error'})) {
 2376:               $hash{'error'}='Bad data';
 2377:               return (\%hash, $string);
 2378:           }
 2379:       } elsif($string =~ /^__ARRAY_REF__/) {
 2380:           ($key, $string)=&str2arrayref($string);
 2381:           if($key->[0] eq 'Array reference error') {
 2382:               $hash{'error'}='Bad data';
 2383:               return (\%hash, $string);
 2384:           }
 2385:       } else {
 2386:           $string =~ s/^(.*?)=//;
 2387: 	  $key=&unescape($1);
 2388:       }
 2389:       $string =~ s/^=//;
 2390: 
 2391:       #value
 2392:       my $value='';
 2393:       if($string =~ /^__HASH_REF__/) {
 2394:           ($value, $string)=&str2hashref($string);
 2395:           if(defined($value->{'error'})) {
 2396:               $hash{'error'}='Bad data';
 2397:               return (\%hash, $string);
 2398:           }
 2399:       } elsif($string =~ /^__ARRAY_REF__/) {
 2400:           ($value, $string)=&str2arrayref($string);
 2401:           if($value->[0] eq 'Array reference error') {
 2402:               $hash{'error'}='Bad data';
 2403:               return (\%hash, $string);
 2404:           }
 2405:       } else {
 2406: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2407:       }
 2408:       $string =~ s/^&//;
 2409: 
 2410:       $hash{$key}=$value;
 2411:   }
 2412: 
 2413:   $string =~ s/^__END_HASH_REF__//;
 2414: 
 2415:   return (\%hash, $string);
 2416: }
 2417: 
 2418: sub str2array {
 2419:     my ($string)=@_;
 2420:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2421:     return @$array;
 2422: }
 2423: 
 2424: sub str2arrayref {
 2425:   my ($string) = @_;
 2426:   my @array;
 2427: 
 2428:   if($string !~ /^__ARRAY_REF__/) {
 2429:       if (! ($string eq '' || !defined($string))) {
 2430: 	  $array[0]='Array reference error';
 2431:       }
 2432:       return (\@array, $string);
 2433:   }
 2434: 
 2435:   $string =~ s/^__ARRAY_REF__//;
 2436: 
 2437:   while($string !~ /^__END_ARRAY_REF__/) {
 2438:       my $value='';
 2439:       if($string =~ /^__HASH_REF__/) {
 2440:           ($value, $string)=&str2hashref($string);
 2441:           if(defined($value->{'error'})) {
 2442:               $array[0] ='Array reference error';
 2443:               return (\@array, $string);
 2444:           }
 2445:       } elsif($string =~ /^__ARRAY_REF__/) {
 2446:           ($value, $string)=&str2arrayref($string);
 2447:           if($value->[0] eq 'Array reference error') {
 2448:               $array[0] ='Array reference error';
 2449:               return (\@array, $string);
 2450:           }
 2451:       } else {
 2452: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2453:       }
 2454:       $string =~ s/^&//;
 2455: 
 2456:       push(@array, $value);
 2457:   }
 2458: 
 2459:   $string =~ s/^__END_ARRAY_REF__//;
 2460: 
 2461:   return (\@array, $string);
 2462: }
 2463: 
 2464: # -------------------------------------------------------------------Temp Store
 2465: 
 2466: sub tmpreset {
 2467:   my ($symb,$namespace,$domain,$stuname) = @_;
 2468:   if (!$symb) {
 2469:     $symb=&symbread();
 2470:     if (!$symb) { $symb= $env{'request.url'}; }
 2471:   }
 2472:   $symb=escape($symb);
 2473: 
 2474:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2475:   $namespace=~s/\//\_/g;
 2476:   $namespace=~s/\W//g;
 2477: 
 2478:   if (!$domain) { $domain=$env{'user.domain'}; }
 2479:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2480:   if ($domain eq 'public' && $stuname eq 'public') {
 2481:       $stuname=$ENV{'REMOTE_ADDR'};
 2482:   }
 2483:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2484:   my %hash;
 2485:   if (tie(%hash,'GDBM_File',
 2486: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2487: 	  &GDBM_WRCREAT(),0640)) {
 2488:     foreach my $key (keys %hash) {
 2489:       if ($key=~ /:$symb/) {
 2490: 	delete($hash{$key});
 2491:       }
 2492:     }
 2493:   }
 2494: }
 2495: 
 2496: sub tmpstore {
 2497:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2498: 
 2499:   if (!$symb) {
 2500:     $symb=&symbread();
 2501:     if (!$symb) { $symb= $env{'request.url'}; }
 2502:   }
 2503:   $symb=escape($symb);
 2504: 
 2505:   if (!$namespace) {
 2506:     # I don't think we would ever want to store this for a course.
 2507:     # it seems this will only be used if we don't have a course.
 2508:     #$namespace=$env{'request.course.id'};
 2509:     #if (!$namespace) {
 2510:       $namespace=$env{'request.state'};
 2511:     #}
 2512:   }
 2513:   $namespace=~s/\//\_/g;
 2514:   $namespace=~s/\W//g;
 2515:   if (!$domain) { $domain=$env{'user.domain'}; }
 2516:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2517:   if ($domain eq 'public' && $stuname eq 'public') {
 2518:       $stuname=$ENV{'REMOTE_ADDR'};
 2519:   }
 2520:   my $now=time;
 2521:   my %hash;
 2522:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2523:   if (tie(%hash,'GDBM_File',
 2524: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2525: 	  &GDBM_WRCREAT(),0640)) {
 2526:     $hash{"version:$symb"}++;
 2527:     my $version=$hash{"version:$symb"};
 2528:     my $allkeys=''; 
 2529:     foreach my $key (keys(%$storehash)) {
 2530:       $allkeys.=$key.':';
 2531:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2532:     }
 2533:     $hash{"$version:$symb:timestamp"}=$now;
 2534:     $allkeys.='timestamp';
 2535:     $hash{"$version:keys:$symb"}=$allkeys;
 2536:     if (untie(%hash)) {
 2537:       return 'ok';
 2538:     } else {
 2539:       return "error:$!";
 2540:     }
 2541:   } else {
 2542:     return "error:$!";
 2543:   }
 2544: }
 2545: 
 2546: # -----------------------------------------------------------------Temp Restore
 2547: 
 2548: sub tmprestore {
 2549:   my ($symb,$namespace,$domain,$stuname) = @_;
 2550: 
 2551:   if (!$symb) {
 2552:     $symb=&symbread();
 2553:     if (!$symb) { $symb= $env{'request.url'}; }
 2554:   }
 2555:   $symb=escape($symb);
 2556: 
 2557:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2558: 
 2559:   if (!$domain) { $domain=$env{'user.domain'}; }
 2560:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2561:   if ($domain eq 'public' && $stuname eq 'public') {
 2562:       $stuname=$ENV{'REMOTE_ADDR'};
 2563:   }
 2564:   my %returnhash;
 2565:   $namespace=~s/\//\_/g;
 2566:   $namespace=~s/\W//g;
 2567:   my %hash;
 2568:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2569:   if (tie(%hash,'GDBM_File',
 2570: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2571: 	  &GDBM_READER(),0640)) {
 2572:     my $version=$hash{"version:$symb"};
 2573:     $returnhash{'version'}=$version;
 2574:     my $scope;
 2575:     for ($scope=1;$scope<=$version;$scope++) {
 2576:       my $vkeys=$hash{"$scope:keys:$symb"};
 2577:       my @keys=split(/:/,$vkeys);
 2578:       my $key;
 2579:       $returnhash{"$scope:keys"}=$vkeys;
 2580:       foreach $key (@keys) {
 2581: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2582: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2583:       }
 2584:     }
 2585:     if (!(untie(%hash))) {
 2586:       return "error:$!";
 2587:     }
 2588:   } else {
 2589:     return "error:$!";
 2590:   }
 2591:   return %returnhash;
 2592: }
 2593: 
 2594: # ----------------------------------------------------------------------- Store
 2595: 
 2596: sub store {
 2597:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2598:     my $home='';
 2599: 
 2600:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2601: 
 2602:     $symb=&symbclean($symb);
 2603:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2604: 
 2605:     if (!$domain) { $domain=$env{'user.domain'}; }
 2606:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2607: 
 2608:     &devalidate($symb,$stuname,$domain);
 2609: 
 2610:     $symb=escape($symb);
 2611:     if (!$namespace) { 
 2612:        unless ($namespace=$env{'request.course.id'}) { 
 2613:           return ''; 
 2614:        } 
 2615:     }
 2616:     if (!$home) { $home=$env{'user.home'}; }
 2617: 
 2618:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2619:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2620: 
 2621:     my $namevalue='';
 2622:     foreach my $key (keys(%$storehash)) {
 2623:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2624:     }
 2625:     $namevalue=~s/\&$//;
 2626:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2627:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2628: }
 2629: 
 2630: # -------------------------------------------------------------- Critical Store
 2631: 
 2632: sub cstore {
 2633:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2634:     my $home='';
 2635: 
 2636:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2637: 
 2638:     $symb=&symbclean($symb);
 2639:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2640: 
 2641:     if (!$domain) { $domain=$env{'user.domain'}; }
 2642:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2643: 
 2644:     &devalidate($symb,$stuname,$domain);
 2645: 
 2646:     $symb=escape($symb);
 2647:     if (!$namespace) { 
 2648:        unless ($namespace=$env{'request.course.id'}) { 
 2649:           return ''; 
 2650:        } 
 2651:     }
 2652:     if (!$home) { $home=$env{'user.home'}; }
 2653: 
 2654:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2655:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2656: 
 2657:     my $namevalue='';
 2658:     foreach my $key (keys(%$storehash)) {
 2659:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2660:     }
 2661:     $namevalue=~s/\&$//;
 2662:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2663:     return critical
 2664:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2665: }
 2666: 
 2667: # --------------------------------------------------------------------- Restore
 2668: 
 2669: sub restore {
 2670:     my ($symb,$namespace,$domain,$stuname) = @_;
 2671:     my $home='';
 2672: 
 2673:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2674: 
 2675:     if (!$symb) {
 2676:       unless ($symb=escape(&symbread())) { return ''; }
 2677:     } else {
 2678:       $symb=&escape(&symbclean($symb));
 2679:     }
 2680:     if (!$namespace) { 
 2681:        unless ($namespace=$env{'request.course.id'}) { 
 2682:           return ''; 
 2683:        } 
 2684:     }
 2685:     if (!$domain) { $domain=$env{'user.domain'}; }
 2686:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2687:     if (!$home) { $home=$env{'user.home'}; }
 2688:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2689: 
 2690:     my %returnhash=();
 2691:     foreach my $line (split(/\&/,$answer)) {
 2692: 	my ($name,$value)=split(/\=/,$line);
 2693:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2694:     }
 2695:     my $version;
 2696:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2697:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2698:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2699:        }
 2700:     }
 2701:     return %returnhash;
 2702: }
 2703: 
 2704: # ---------------------------------------------------------- Course Description
 2705: 
 2706: sub coursedescription {
 2707:     my ($courseid,$args)=@_;
 2708:     $courseid=~s/^\///;
 2709:     $courseid=~s/\_/\//g;
 2710:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2711:     my $chome=&homeserver($cnum,$cdomain);
 2712:     my $normalid=$cdomain.'_'.$cnum;
 2713:     # need to always cache even if we get errors otherwise we keep 
 2714:     # trying and trying and trying to get the course description.
 2715:     my %envhash=();
 2716:     my %returnhash=();
 2717:     
 2718:     my $expiretime=600;
 2719:     if ($env{'request.course.id'} eq $normalid) {
 2720: 	$expiretime=120;
 2721:     }
 2722: 
 2723:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2724:     if (!$args->{'freshen_cache'}
 2725: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2726: 	foreach my $key (keys(%env)) {
 2727: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2728: 	    my ($setting) = $1;
 2729: 	    $returnhash{$setting} = $env{$key};
 2730: 	}
 2731: 	return %returnhash;
 2732:     }
 2733: 
 2734:     # get the data agin
 2735:     if (!$args->{'one_time'}) {
 2736: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2737:     }
 2738:     if ($chome ne 'no_host') {
 2739:        %returnhash=&dump('environment',$cdomain,$cnum);
 2740:        if (!exists($returnhash{'con_lost'})) {
 2741:            $returnhash{'home'}= $chome;
 2742: 	   $returnhash{'domain'} = $cdomain;
 2743: 	   $returnhash{'num'} = $cnum;
 2744:            if (!defined($returnhash{'type'})) {
 2745:                $returnhash{'type'} = 'Course';
 2746:            }
 2747:            while (my ($name,$value) = each %returnhash) {
 2748:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2749:            }
 2750:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2751:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2752: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2753:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2754:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2755:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2756:        }
 2757:     }
 2758:     if (!$args->{'one_time'}) {
 2759: 	&appenv(%envhash);
 2760:     }
 2761:     return %returnhash;
 2762: }
 2763: 
 2764: # -------------------------------------------------See if a user is privileged
 2765: 
 2766: sub privileged {
 2767:     my ($username,$domain)=@_;
 2768:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2769: 			&homeserver($username,$domain));
 2770:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2771:     my $now=time;
 2772:     if ($rolesdump ne '') {
 2773:         foreach my $entry (split(/&/,$rolesdump)) {
 2774: 	    if ($entry!~/^rolesdef_/) {
 2775: 		my ($area,$role)=split(/=/,$entry);
 2776: 		$area=~s/\_\w\w$//;
 2777: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2778: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2779: 		    my $active=1;
 2780: 		    if ($tend) {
 2781: 			if ($tend<$now) { $active=0; }
 2782: 		    }
 2783: 		    if ($tstart) {
 2784: 			if ($tstart>$now) { $active=0; }
 2785: 		    }
 2786: 		    if ($active) { return 1; }
 2787: 		}
 2788: 	    }
 2789: 	}
 2790:     }
 2791:     return 0;
 2792: }
 2793: 
 2794: # -------------------------------------------------------- Get user privileges
 2795: 
 2796: sub rolesinit {
 2797:     my ($domain,$username,$authhost)=@_;
 2798:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2799:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2800:     my %allroles=();
 2801:     my %allgroups=();   
 2802:     my $now=time;
 2803:     my %userroles = ('user.login.time' => $now);
 2804:     my $group_privs;
 2805: 
 2806:     if ($rolesdump ne '') {
 2807:         foreach my $entry (split(/&/,$rolesdump)) {
 2808: 	  if ($entry!~/^rolesdef_/) {
 2809:             my ($area,$role)=split(/=/,$entry);
 2810: 	    $area=~s/\_\w\w$//;
 2811:             my ($trole,$tend,$tstart,$group_privs);
 2812: 	    if ($role=~/^cr/) { 
 2813: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2814: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2815: 		    ($tend,$tstart)=split('_',$trest);
 2816: 		} else {
 2817: 		    $trole=$role;
 2818: 		}
 2819:             } elsif ($role =~ m|^gr/|) {
 2820:                 ($trole,$tend,$tstart) = split(/_/,$role);
 2821:                 ($trole,$group_privs) = split(/\//,$trole);
 2822:                 $group_privs = &unescape($group_privs);
 2823: 	    } else {
 2824: 		($trole,$tend,$tstart)=split(/_/,$role);
 2825: 	    }
 2826: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 2827: 					 $username);
 2828: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 2829:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2830:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2831:             if (($area ne '') && ($trole ne '')) {
 2832: 		my $spec=$trole.'.'.$area;
 2833: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2834: 		if ($trole =~ /^cr\//) {
 2835:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2836:                 } elsif ($trole eq 'gr') {
 2837:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 2838: 		} else {
 2839:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2840: 		}
 2841:             }
 2842:           }
 2843:         }
 2844:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 2845:         $userroles{'user.adv'}    = $adv;
 2846: 	$userroles{'user.author'} = $author;
 2847:         $env{'user.adv'}=$adv;
 2848:     }
 2849:     return \%userroles;  
 2850: }
 2851: 
 2852: sub set_arearole {
 2853:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2854: # log the associated role with the area
 2855:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2856:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 2857: }
 2858: 
 2859: sub custom_roleprivs {
 2860:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2861:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2862:     my $homsvr=homeserver($rauthor,$rdomain);
 2863:     if ($hostname{$homsvr} ne '') {
 2864:         my ($rdummy,$roledef)=
 2865:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2866:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2867:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2868:             if (defined($syspriv)) {
 2869:                 $$allroles{'cm./'}.=':'.$syspriv;
 2870:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2871:             }
 2872:             if ($tdomain ne '') {
 2873:                 if (defined($dompriv)) {
 2874:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2875:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2876:                 }
 2877:                 if (($trest ne '') && (defined($coursepriv))) {
 2878:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2879:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2880:                 }
 2881:             }
 2882:         }
 2883:     }
 2884: }
 2885: 
 2886: sub group_roleprivs {
 2887:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 2888:     my $access = 1;
 2889:     my $now = time;
 2890:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 2891:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 2892:     if ($access) {
 2893:         my ($course,$group) = ($area =~ m|(/\w+/\w+)/([^/]+)$|);
 2894:         $$allgroups{$course}{$group} .=':'.$group_privs;
 2895:     }
 2896: }
 2897: 
 2898: sub standard_roleprivs {
 2899:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2900:     if (defined($pr{$trole.':s'})) {
 2901:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2902:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2903:     }
 2904:     if ($tdomain ne '') {
 2905:         if (defined($pr{$trole.':d'})) {
 2906:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2907:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2908:         }
 2909:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2910:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2911:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2912:         }
 2913:     }
 2914: }
 2915: 
 2916: sub set_userprivs {
 2917:     my ($userroles,$allroles,$allgroups) = @_; 
 2918:     my $author=0;
 2919:     my $adv=0;
 2920:     my %grouproles = ();
 2921:     if (keys(%{$allgroups}) > 0) {
 2922:         foreach my $role (keys %{$allroles}) {
 2923:             my ($trole,$area,$sec,$extendedarea);
 2924:             if ($role =~ m-^(\w+|cr/\w+/\w+/\w+)\.(/\w+/\w+)(/?\w*)-) {
 2925:                 $trole = $1;
 2926:                 $area = $2;
 2927:                 $sec = $3;
 2928:                 $extendedarea = $area.$sec;
 2929:                 if (exists($$allgroups{$area})) {
 2930:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 2931:                         my $spec = $trole.'.'.$extendedarea;
 2932:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 2933:                                                 $$allgroups{$area}{$group};
 2934:                     }
 2935:                 }
 2936:             }
 2937:         }
 2938:     }
 2939:     foreach my $group (keys(%grouproles)) {
 2940:         $$allroles{$group} = $grouproles{$group};
 2941:     }
 2942:     foreach my $role (keys(%{$allroles})) {
 2943:         my %thesepriv;
 2944:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 2945:         foreach my $item (split(/:/,$$allroles{$role})) {
 2946:             if ($item ne '') {
 2947:                 my ($privilege,$restrictions)=split(/&/,$item);
 2948:                 if ($restrictions eq '') {
 2949:                     $thesepriv{$privilege}='F';
 2950:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2951:                     $thesepriv{$privilege}.=$restrictions;
 2952:                 }
 2953:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2954:             }
 2955:         }
 2956:         my $thesestr='';
 2957:         foreach my $priv (keys(%thesepriv)) {
 2958: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 2959: 	}
 2960:         $userroles->{'user.priv.'.$role} = $thesestr;
 2961:     }
 2962:     return ($author,$adv);
 2963: }
 2964: 
 2965: # --------------------------------------------------------------- get interface
 2966: 
 2967: sub get {
 2968:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2969:    my $items='';
 2970:    foreach my $item (@$storearr) {
 2971:        $items.=&escape($item).'&';
 2972:    }
 2973:    $items=~s/\&$//;
 2974:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2975:    if (!$uname) { $uname=$env{'user.name'}; }
 2976:    my $uhome=&homeserver($uname,$udomain);
 2977: 
 2978:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2979:    my @pairs=split(/\&/,$rep);
 2980:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2981:      return @pairs;
 2982:    }
 2983:    my %returnhash=();
 2984:    my $i=0;
 2985:    foreach my $item (@$storearr) {
 2986:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 2987:       $i++;
 2988:    }
 2989:    return %returnhash;
 2990: }
 2991: 
 2992: # --------------------------------------------------------------- del interface
 2993: 
 2994: sub del {
 2995:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2996:    my $items='';
 2997:    foreach my $item (@$storearr) {
 2998:        $items.=&escape($item).'&';
 2999:    }
 3000:    $items=~s/\&$//;
 3001:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3002:    if (!$uname) { $uname=$env{'user.name'}; }
 3003:    my $uhome=&homeserver($uname,$udomain);
 3004: 
 3005:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3006: }
 3007: 
 3008: # -------------------------------------------------------------- dump interface
 3009: 
 3010: sub dump {
 3011:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3012:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3013:     if (!$uname) { $uname=$env{'user.name'}; }
 3014:     my $uhome=&homeserver($uname,$udomain);
 3015:     if ($regexp) {
 3016: 	$regexp=&escape($regexp);
 3017:     } else {
 3018: 	$regexp='.';
 3019:     }
 3020:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3021:     my @pairs=split(/\&/,$rep);
 3022:     my %returnhash=();
 3023:     foreach my $item (@pairs) {
 3024: 	my ($key,$value)=split(/=/,$item,2);
 3025: 	$key = &unescape($key);
 3026: 	next if ($key =~ /^error: 2 /);
 3027: 	$returnhash{$key}=&thaw_unescape($value);
 3028:     }
 3029:     return %returnhash;
 3030: }
 3031: 
 3032: # --------------------------------------------------------- dumpstore interface
 3033: 
 3034: sub dumpstore {
 3035:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3036:    return &dump($namespace,$udomain,$uname,$regexp,$range);
 3037: }
 3038: 
 3039: # -------------------------------------------------------------- keys interface
 3040: 
 3041: sub getkeys {
 3042:    my ($namespace,$udomain,$uname)=@_;
 3043:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3044:    if (!$uname) { $uname=$env{'user.name'}; }
 3045:    my $uhome=&homeserver($uname,$udomain);
 3046:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3047:    my @keyarray=();
 3048:    foreach my $key (split(/\&/,$rep)) {
 3049:       push(@keyarray,&unescape($key));
 3050:    }
 3051:    return @keyarray;
 3052: }
 3053: 
 3054: # --------------------------------------------------------------- currentdump
 3055: sub currentdump {
 3056:    my ($courseid,$sdom,$sname)=@_;
 3057:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3058:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3059:    $sname    = $env{'user.name'}         if (! defined($sname));
 3060:    my $uhome = &homeserver($sname,$sdom);
 3061:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3062:    return if ($rep =~ /^(error:|no_such_host)/);
 3063:    #
 3064:    my %returnhash=();
 3065:    #
 3066:    if ($rep eq "unknown_cmd") { 
 3067:        # an old lond will not know currentdump
 3068:        # Do a dump and make it look like a currentdump
 3069:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 3070:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3071:        my %hash = @tmp;
 3072:        @tmp=();
 3073:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3074:    } else {
 3075:        my @pairs=split(/\&/,$rep);
 3076:        foreach my $pair (@pairs) {
 3077:            my ($key,$value)=split(/=/,$pair,2);
 3078:            my ($symb,$param) = split(/:/,$key);
 3079:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3080:                                                         &thaw_unescape($value);
 3081:        }
 3082:    }
 3083:    return %returnhash;
 3084: }
 3085: 
 3086: sub convert_dump_to_currentdump{
 3087:     my %hash = %{shift()};
 3088:     my %returnhash;
 3089:     # Code ripped from lond, essentially.  The only difference
 3090:     # here is the unescaping done by lonnet::dump().  Conceivably
 3091:     # we might run in to problems with parameter names =~ /^v\./
 3092:     while (my ($key,$value) = each(%hash)) {
 3093:         my ($v,$symb,$param) = split(/:/,$key);
 3094:         next if ($v eq 'version' || $symb eq 'keys');
 3095:         next if (exists($returnhash{$symb}) &&
 3096:                  exists($returnhash{$symb}->{$param}) &&
 3097:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3098:         $returnhash{$symb}->{$param}=$value;
 3099:         $returnhash{$symb}->{'v.'.$param}=$v;
 3100:     }
 3101:     #
 3102:     # Remove all of the keys in the hashes which keep track of
 3103:     # the version of the parameter.
 3104:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3105:         # use a foreach because we are going to delete from the hash.
 3106:         foreach my $key (keys(%$param_hash)) {
 3107:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3108:         }
 3109:     }
 3110:     return \%returnhash;
 3111: }
 3112: 
 3113: # ------------------------------------------------------ critical inc interface
 3114: 
 3115: sub cinc {
 3116:     return &inc(@_,'critical');
 3117: }
 3118: 
 3119: # --------------------------------------------------------------- inc interface
 3120: 
 3121: sub inc {
 3122:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3123:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3124:     if (!$uname) { $uname=$env{'user.name'}; }
 3125:     my $uhome=&homeserver($uname,$udomain);
 3126:     my $items='';
 3127:     if (! ref($store)) {
 3128:         # got a single value, so use that instead
 3129:         $items = &escape($store).'=&';
 3130:     } elsif (ref($store) eq 'SCALAR') {
 3131:         $items = &escape($$store).'=&';        
 3132:     } elsif (ref($store) eq 'ARRAY') {
 3133:         $items = join('=&',map {&escape($_);} @{$store});
 3134:     } elsif (ref($store) eq 'HASH') {
 3135:         while (my($key,$value) = each(%{$store})) {
 3136:             $items.= &escape($key).'='.&escape($value).'&';
 3137:         }
 3138:     }
 3139:     $items=~s/\&$//;
 3140:     if ($critical) {
 3141: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3142:     } else {
 3143: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3144:     }
 3145: }
 3146: 
 3147: # --------------------------------------------------------------- put interface
 3148: 
 3149: sub put {
 3150:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3152:    if (!$uname) { $uname=$env{'user.name'}; }
 3153:    my $uhome=&homeserver($uname,$udomain);
 3154:    my $items='';
 3155:    foreach my $item (keys(%$storehash)) {
 3156:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3157:    }
 3158:    $items=~s/\&$//;
 3159:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3160: }
 3161: 
 3162: # ------------------------------------------------------------ newput interface
 3163: 
 3164: sub newput {
 3165:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3166:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3167:    if (!$uname) { $uname=$env{'user.name'}; }
 3168:    my $uhome=&homeserver($uname,$udomain);
 3169:    my $items='';
 3170:    foreach my $key (keys(%$storehash)) {
 3171:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3172:    }
 3173:    $items=~s/\&$//;
 3174:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3175: }
 3176: 
 3177: # ---------------------------------------------------------  putstore interface
 3178: 
 3179: sub putstore {
 3180:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3182:    if (!$uname) { $uname=$env{'user.name'}; }
 3183:    my $uhome=&homeserver($uname,$udomain);
 3184:    my $items='';
 3185:    foreach my $key (keys(%$storehash)) {
 3186:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3187:    }
 3188:    $items=~s/\&$//;
 3189:    my $esc_symb=&escape($symb);
 3190:    my $esc_v=&escape($version);
 3191:    my $reply =
 3192:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3193: 	      $uhome);
 3194:    if ($reply eq 'unknown_cmd') {
 3195:        # gfall back to way things use to be done
 3196:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3197: 			    $uname);
 3198:    }
 3199:    return $reply;
 3200: }
 3201: 
 3202: sub old_putstore {
 3203:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3204:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3205:     if (!$uname) { $uname=$env{'user.name'}; }
 3206:     my $uhome=&homeserver($uname,$udomain);
 3207:     my %newstorehash;
 3208:     foreach my $item (keys(%$storehash)) {
 3209: 	my $key = $version.':'.&escape($symb).':'.$item;
 3210: 	$newstorehash{$key} = $storehash->{$item};
 3211:     }
 3212:     my $items='';
 3213:     my %allitems = ();
 3214:     foreach my $item (keys(%newstorehash)) {
 3215: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3216: 	    my $key = $1.':keys:'.$2;
 3217: 	    $allitems{$key} .= $3.':';
 3218: 	}
 3219: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3220:     }
 3221:     foreach my $item (keys(%allitems)) {
 3222: 	$allitems{$item} =~ s/\:$//;
 3223: 	$items.= $item.'='.$allitems{$item}.'&';
 3224:     }
 3225:     $items=~s/\&$//;
 3226:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3227: }
 3228: 
 3229: # ------------------------------------------------------ critical put interface
 3230: 
 3231: sub cput {
 3232:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3233:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3234:    if (!$uname) { $uname=$env{'user.name'}; }
 3235:    my $uhome=&homeserver($uname,$udomain);
 3236:    my $items='';
 3237:    foreach my $item (keys(%$storehash)) {
 3238:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3239:    }
 3240:    $items=~s/\&$//;
 3241:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3242: }
 3243: 
 3244: # -------------------------------------------------------------- eget interface
 3245: 
 3246: sub eget {
 3247:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3248:    my $items='';
 3249:    foreach my $item (@$storearr) {
 3250:        $items.=&escape($item).'&';
 3251:    }
 3252:    $items=~s/\&$//;
 3253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3254:    if (!$uname) { $uname=$env{'user.name'}; }
 3255:    my $uhome=&homeserver($uname,$udomain);
 3256:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3257:    my @pairs=split(/\&/,$rep);
 3258:    my %returnhash=();
 3259:    my $i=0;
 3260:    foreach my $item (@$storearr) {
 3261:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3262:       $i++;
 3263:    }
 3264:    return %returnhash;
 3265: }
 3266: 
 3267: # ------------------------------------------------------------ tmpput interface
 3268: sub tmpput {
 3269:     my ($storehash,$server,$context)=@_;
 3270:     my $items='';
 3271:     foreach my $item (keys(%$storehash)) {
 3272: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3273:     }
 3274:     $items=~s/\&$//;
 3275:     if (defined($context)) {
 3276:         $items .= ':'.&escape($context);
 3277:     }
 3278:     return &reply("tmpput:$items",$server);
 3279: }
 3280: 
 3281: # ------------------------------------------------------------ tmpget interface
 3282: sub tmpget {
 3283:     my ($token,$server)=@_;
 3284:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3285:     my $rep=&reply("tmpget:$token",$server);
 3286:     my %returnhash;
 3287:     foreach my $item (split(/\&/,$rep)) {
 3288: 	my ($key,$value)=split(/=/,$item);
 3289: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3290:     }
 3291:     return %returnhash;
 3292: }
 3293: 
 3294: # ------------------------------------------------------------ tmpget interface
 3295: sub tmpdel {
 3296:     my ($token,$server)=@_;
 3297:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3298:     return &reply("tmpdel:$token",$server);
 3299: }
 3300: 
 3301: # -------------------------------------------------- portfolio access checking
 3302: 
 3303: sub portfolio_access {
 3304:     my ($requrl) = @_;
 3305:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3306:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3307:     if ($result eq 'ok') {
 3308:        return 'F';
 3309:     } elsif ($result =~ /^[^:]+:guest_/) {
 3310:        return 'A';
 3311:     }
 3312:     return '';
 3313: }
 3314: 
 3315: sub get_portfolio_access {
 3316:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3317: 
 3318:     if (!ref($access_hash)) {
 3319: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3320: 	my %access_controls = &get_access_controls($current_perms,$group,
 3321: 						   $file_name);
 3322: 	$access_hash = $access_controls{$file_name};
 3323:     }
 3324: 
 3325:     my ($public,$guest,@domains,@users,@courses,@groups);
 3326:     my $now = time;
 3327:     if (ref($access_hash) eq 'HASH') {
 3328:         foreach my $key (keys(%{$access_hash})) {
 3329:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3330:             if ($start > $now) {
 3331:                 next;
 3332:             }
 3333:             if ($end && $end<$now) {
 3334:                 next;
 3335:             }
 3336:             if ($scope eq 'public') {
 3337:                 $public = $key;
 3338:                 last;
 3339:             } elsif ($scope eq 'guest') {
 3340:                 $guest = $key;
 3341:             } elsif ($scope eq 'domains') {
 3342:                 push(@domains,$key);
 3343:             } elsif ($scope eq 'users') {
 3344:                 push(@users,$key);
 3345:             } elsif ($scope eq 'course') {
 3346:                 push(@courses,$key);
 3347:             } elsif ($scope eq 'group') {
 3348:                 push(@groups,$key);
 3349:             }
 3350:         }
 3351:         if ($public) {
 3352:             return 'ok';
 3353:         }
 3354:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3355:             if ($guest) {
 3356:                 return $guest;
 3357:             }
 3358:         } else {
 3359:             if (@domains > 0) {
 3360:                 foreach my $domkey (@domains) {
 3361:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3362:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3363:                             return 'ok';
 3364:                         }
 3365:                     }
 3366:                 }
 3367:             }
 3368:             if (@users > 0) {
 3369:                 foreach my $userkey (@users) {
 3370:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
 3371:                         return 'ok';
 3372:                     }
 3373:                 }
 3374:             }
 3375:             my %roleshash;
 3376:             my @courses_and_groups = @courses;
 3377:             push(@courses_and_groups,@groups); 
 3378:             if (@courses_and_groups > 0) {
 3379:                 my (%allgroups,%allroles); 
 3380:                 my ($start,$end,$role,$sec,$group);
 3381:                 foreach my $envkey (%env) {
 3382:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./([^/]+)/([^/]+)/?([^/]*)$-) {
 3383:                         my $cid = $2.'_'.$3; 
 3384:                         if ($1 eq 'gr') {
 3385:                             $group = $4;
 3386:                             $allgroups{$cid}{$group} = $env{$envkey};
 3387:                         } else {
 3388:                             if ($4 eq '') {
 3389:                                 $sec = 'none';
 3390:                             } else {
 3391:                                 $sec = $4;
 3392:                             }
 3393:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3394:                         }
 3395:                     } elsif ($envkey =~ m-^user\.role\./cr/(\w+/\w+/\w*)./([^/]+)/([^/]+)/?([^/]*)$-) {
 3396:                         my $cid = $2.'_'.$3;
 3397:                         if ($4 eq '') {
 3398:                             $sec = 'none';
 3399:                         } else {
 3400:                             $sec = $4;
 3401:                         }
 3402:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3403:                     }
 3404:                 }
 3405:                 if (keys(%allroles) == 0) {
 3406:                     return;
 3407:                 }
 3408:                 foreach my $key (@courses_and_groups) {
 3409:                     my %content = %{$$access_hash{$key}};
 3410:                     my $cnum = $content{'number'};
 3411:                     my $cdom = $content{'domain'};
 3412:                     my $cid = $cdom.'_'.$cnum;
 3413:                     if (!exists($allroles{$cid})) {
 3414:                         next;
 3415:                     }    
 3416:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3417:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3418:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3419:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3420:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3421:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3422:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3423:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3424:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3425:                                         if (grep/^all$/,@sections) {
 3426:                                             return 'ok';
 3427:                                         } else {
 3428:                                             if (grep/^$sec$/,@sections) {
 3429:                                                 return 'ok';
 3430:                                             }
 3431:                                         }
 3432:                                     }
 3433:                                 }
 3434:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3435:                                     if (grep/^none$/,@groups) {
 3436:                                         return 'ok';
 3437:                                     }
 3438:                                 } else {
 3439:                                     if (grep/^all$/,@groups) {
 3440:                                         return 'ok';
 3441:                                     } 
 3442:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3443:                                         if (grep/^$group$/,@groups) {
 3444:                                             return 'ok';
 3445:                                         }
 3446:                                     }
 3447:                                 } 
 3448:                             }
 3449:                         }
 3450:                     }
 3451:                 }
 3452:             }
 3453:             if ($guest) {
 3454:                 return $guest;
 3455:             }
 3456:         }
 3457:     }
 3458:     return;
 3459: }
 3460: 
 3461: sub course_group_datechecker {
 3462:     my ($dates,$now,$status) = @_;
 3463:     my ($start,$end) = split(/\./,$dates);
 3464:     if (!$start && !$end) {
 3465:         return 'ok';
 3466:     }
 3467:     if (grep/^active$/,@{$status}) {
 3468:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3469:             return 'ok';
 3470:         }
 3471:     }
 3472:     if (grep/^previous$/,@{$status}) {
 3473:         if ($end > $now ) {
 3474:             return 'ok';
 3475:         }
 3476:     }
 3477:     if (grep/^future$/,@{$status}) {
 3478:         if ($start > $now) {
 3479:             return 'ok';
 3480:         }
 3481:     }
 3482:     return; 
 3483: }
 3484: 
 3485: sub parse_portfolio_url {
 3486:     my ($url) = @_;
 3487: 
 3488:     my ($type,$udom,$unum,$group,$file_name);
 3489:     
 3490:     if ($url =~  m-^/*uploaded/([^/]+)/([^/]+)/portfolio(/.+)$-) {
 3491: 	$type = 1;
 3492:         $udom = $1;
 3493:         $unum = $2;
 3494:         $file_name = $3;
 3495:     } elsif ($url =~ m-^/*uploaded/([^/]+)/([^/]+)/groups/([^/]+)/portfolio/(.+)$-) {
 3496: 	$type = 2;
 3497:         $udom = $1;
 3498:         $unum = $2;
 3499:         $group = $3;
 3500:         $file_name = $3.'/'.$4;
 3501:     }
 3502:     if (wantarray) {
 3503: 	return ($type,$udom,$unum,$file_name,$group);
 3504:     }
 3505:     return $type;
 3506: }
 3507: 
 3508: sub is_portfolio_url {
 3509:     my ($url) = @_;
 3510:     return scalar(&parse_portfolio_url($url));
 3511: }
 3512: 
 3513: sub is_portfolio_file {
 3514:     my ($file) = @_;
 3515:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3516:         return 1;
 3517:     }
 3518:     return;
 3519: }
 3520: 
 3521: 
 3522: # ---------------------------------------------- Custom access rule evaluation
 3523: 
 3524: sub customaccess {
 3525:     my ($priv,$uri)=@_;
 3526:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 3527:     $urealm=~s/^\W//;
 3528:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 3529:     my $access=0;
 3530:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3531: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3532:         if ($role) {
 3533: 	   if ($role ne $urole) { next; }
 3534:         }
 3535:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3536:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3537:             if ($tdom) {
 3538: 		if ($tdom ne $udom) { next; }
 3539:             }
 3540:             if ($tcrs) {
 3541: 		if ($tcrs ne $ucrs) { next; }
 3542:             }
 3543:             if ($tsec) {
 3544: 		if ($tsec ne $usec) { next; }
 3545:             }
 3546:             $access=($effect eq 'allow');
 3547:             last;
 3548:         }
 3549: 	if ($realm eq '' && $role eq '') {
 3550:             $access=($effect eq 'allow');
 3551: 	}
 3552:     }
 3553:     return $access;
 3554: }
 3555: 
 3556: # ------------------------------------------------- Check for a user privilege
 3557: 
 3558: sub allowed {
 3559:     my ($priv,$uri,$symb)=@_;
 3560:     my $ver_orguri=$uri;
 3561:     $uri=&deversion($uri);
 3562:     my $orguri=$uri;
 3563:     $uri=&declutter($uri);
 3564:     
 3565:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3566: # Free bre access to adm and meta resources
 3567:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3568: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3569: 	&& ($priv eq 'bre')) {
 3570: 	return 'F';
 3571:     }
 3572: 
 3573: # Free bre access to user's own portfolio contents
 3574:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3575:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3576: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3577:         return 'F';
 3578:     }
 3579: 
 3580: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3581:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3582:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3583:         if (exists($env{'request.course.id'})) {
 3584:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3585:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3586:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3587:                 my $courseprivid=$env{'request.course.id'};
 3588:                 $courseprivid=~s/\_/\//;
 3589:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3590:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3591:                     return $1; 
 3592:                 } else {
 3593:                     if ($env{'request.course.sec'}) {
 3594:                         $courseprivid.='/'.$env{'request.course.sec'};
 3595:                     }
 3596:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3597:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3598:                         return $2;
 3599:                     }
 3600:                 }
 3601:             }
 3602:         }
 3603:     }
 3604: 
 3605: # Free bre to public access
 3606: 
 3607:     if ($priv eq 'bre') {
 3608:         my $copyright=&metadata($uri,'copyright');
 3609: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3610:            return 'F'; 
 3611:         }
 3612:         if ($copyright eq 'priv') {
 3613:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3614: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3615: 		return '';
 3616:             }
 3617:         }
 3618:         if ($copyright eq 'domain') {
 3619:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3620: 	    unless (($env{'user.domain'} eq $1) ||
 3621:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3622: 		return '';
 3623:             }
 3624:         }
 3625:         if ($env{'request.role'}=~ /li\.\//) {
 3626:             # Library role, so allow browsing of resources in this domain.
 3627:             return 'F';
 3628:         }
 3629:         if ($copyright eq 'custom') {
 3630: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3631:         }
 3632:     }
 3633:     # Domain coordinator is trying to create a course
 3634:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3635:         # uri is the requested domain in this case.
 3636:         # comparison to 'request.role.domain' shows if the user has selected
 3637:         # a role of dc for the domain in question.
 3638:         return 'F' if ($uri eq $env{'request.role.domain'});
 3639:     }
 3640: 
 3641:     my $thisallowed='';
 3642:     my $statecond=0;
 3643:     my $courseprivid='';
 3644: 
 3645: # Course
 3646: 
 3647:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3648:        $thisallowed.=$1;
 3649:     }
 3650: 
 3651: # Domain
 3652: 
 3653:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3654:        =~/\Q$priv\E\&([^\:]*)/) {
 3655:        $thisallowed.=$1;
 3656:     }
 3657: 
 3658: # Course: uri itself is a course
 3659:     my $courseuri=$uri;
 3660:     $courseuri=~s/\_(\d)/\/$1/;
 3661:     $courseuri=~s/^([^\/])/\/$1/;
 3662: 
 3663:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3664:        =~/\Q$priv\E\&([^\:]*)/) {
 3665:        $thisallowed.=$1;
 3666:     }
 3667: 
 3668: # URI is an uploaded document for this course, default permissions don't matter
 3669: # not allowing 'edit' access (editupload) to uploaded course docs
 3670:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3671: 	$thisallowed='';
 3672:         my ($match)=&is_on_map($uri);
 3673:         if ($match) {
 3674:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3675:                   =~/\Q$priv\E\&([^\:]*)/) {
 3676:                 $thisallowed.=$1;
 3677:             }
 3678:         } else {
 3679:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3680:             if ($refuri) {
 3681:                 if ($refuri =~ m|^/adm/|) {
 3682:                     $thisallowed='F';
 3683:                 } else {
 3684:                     $refuri=&declutter($refuri);
 3685:                     my ($match) = &is_on_map($refuri);
 3686:                     if ($match) {
 3687:                         $thisallowed='F';
 3688:                     }
 3689:                 }
 3690:             }
 3691:         }
 3692:     }
 3693: 
 3694:     if ($priv eq 'bre'
 3695: 	&& $thisallowed ne 'F' 
 3696: 	&& $thisallowed ne '2'
 3697: 	&& &is_portfolio_url($uri)) {
 3698: 	$thisallowed = &portfolio_access($uri);
 3699:     }
 3700:     
 3701: # Full access at system, domain or course-wide level? Exit.
 3702: 
 3703:     if ($thisallowed=~/F/) {
 3704: 	return 'F';
 3705:     }
 3706: 
 3707: # If this is generating or modifying users, exit with special codes
 3708: 
 3709:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3710: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3711: 	    my ($audom,$auname)=split('/',$uri);
 3712: # no author name given, so this just checks on the general right to make a co-author in this domain
 3713: 	    unless ($auname) { return $thisallowed; }
 3714: # an author name is given, so we are about to actually make a co-author for a certain account
 3715: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3716: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3717: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3718: 	}
 3719: 	return $thisallowed;
 3720:     }
 3721: #
 3722: # Gathered so far: system, domain and course wide privileges
 3723: #
 3724: # Course: See if uri or referer is an individual resource that is part of 
 3725: # the course
 3726: 
 3727:     if ($env{'request.course.id'}) {
 3728: 
 3729:        $courseprivid=$env{'request.course.id'};
 3730:        if ($env{'request.course.sec'}) {
 3731:           $courseprivid.='/'.$env{'request.course.sec'};
 3732:        }
 3733:        $courseprivid=~s/\_/\//;
 3734:        my $checkreferer=1;
 3735:        my ($match,$cond)=&is_on_map($uri);
 3736:        if ($match) {
 3737:            $statecond=$cond;
 3738:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3739:                =~/\Q$priv\E\&([^\:]*)/) {
 3740:                $thisallowed.=$1;
 3741:                $checkreferer=0;
 3742:            }
 3743:        }
 3744:        
 3745:        if ($checkreferer) {
 3746: 	  my $refuri=$env{'httpref.'.$orguri};
 3747:             unless ($refuri) {
 3748:                 foreach my $key (keys(%env)) {
 3749: 		    if ($key=~/^httpref\..*\*/) {
 3750: 			my $pattern=$key;
 3751:                         $pattern=~s/^httpref\.\/res\///;
 3752:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3753:                         $pattern=~s/\//\\\//g;
 3754:                         if ($orguri=~/$pattern/) {
 3755: 			    $refuri=$env{$key};
 3756:                         }
 3757:                     }
 3758:                 }
 3759:             }
 3760: 
 3761:          if ($refuri) { 
 3762: 	  $refuri=&declutter($refuri);
 3763:           my ($match,$cond)=&is_on_map($refuri);
 3764:             if ($match) {
 3765:               my $refstatecond=$cond;
 3766:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3767:                   =~/\Q$priv\E\&([^\:]*)/) {
 3768:                   $thisallowed.=$1;
 3769:                   $uri=$refuri;
 3770:                   $statecond=$refstatecond;
 3771:               }
 3772:           }
 3773:         }
 3774:        }
 3775:    }
 3776: 
 3777: #
 3778: # Gathered now: all privileges that could apply, and condition number
 3779: # 
 3780: #
 3781: # Full or no access?
 3782: #
 3783: 
 3784:     if ($thisallowed=~/F/) {
 3785: 	return 'F';
 3786:     }
 3787: 
 3788:     unless ($thisallowed) {
 3789:         return '';
 3790:     }
 3791: 
 3792: # Restrictions exist, deal with them
 3793: #
 3794: #   C:according to course preferences
 3795: #   R:according to resource settings
 3796: #   L:unless locked
 3797: #   X:according to user session state
 3798: #
 3799: 
 3800: # Possibly locked functionality, check all courses
 3801: # Locks might take effect only after 10 minutes cache expiration for other
 3802: # courses, and 2 minutes for current course
 3803: 
 3804:     my $envkey;
 3805:     if ($thisallowed=~/L/) {
 3806:         foreach $envkey (keys %env) {
 3807:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3808:                my $courseid=$2;
 3809:                my $roleid=$1.'.'.$2;
 3810:                $courseid=~s/^\///;
 3811:                my $expiretime=600;
 3812:                if ($env{'request.role'} eq $roleid) {
 3813: 		  $expiretime=120;
 3814:                }
 3815: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3816:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3817:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3818: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 3819:                }
 3820:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3821:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3822: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3823:                        &log($env{'user.domain'},$env{'user.name'},
 3824:                             $env{'user.home'},
 3825:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3826:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3827:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3828: 		       return '';
 3829:                    }
 3830:                }
 3831:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3832:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3833: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3834:                        &log($env{'user.domain'},$env{'user.name'},
 3835:                             $env{'user.home'},
 3836:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3837:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3838:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3839: 		       return '';
 3840:                    }
 3841:                }
 3842: 	   }
 3843:        }
 3844:     }
 3845:    
 3846: #
 3847: # Rest of the restrictions depend on selected course
 3848: #
 3849: 
 3850:     unless ($env{'request.course.id'}) {
 3851: 	if ($thisallowed eq 'A') {
 3852: 	    return 'A';
 3853: 	} else {
 3854: 	    return '1';
 3855: 	}
 3856:     }
 3857: 
 3858: #
 3859: # Now user is definitely in a course
 3860: #
 3861: 
 3862: 
 3863: # Course preferences
 3864: 
 3865:    if ($thisallowed=~/C/) {
 3866:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3867:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3868:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3869: 	   =~/\Q$rolecode\E/) {
 3870: 	   if ($priv ne 'pch') { 
 3871: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3872: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3873: 			$env{'request.course.id'});
 3874: 	   }
 3875:            return '';
 3876:        }
 3877: 
 3878:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3879: 	   =~/\Q$unamedom\E/) {
 3880: 	   if ($priv ne 'pch') { 
 3881: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 3882: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3883: 			$env{'request.course.id'});
 3884: 	   }
 3885:            return '';
 3886:        }
 3887:    }
 3888: 
 3889: # Resource preferences
 3890: 
 3891:    if ($thisallowed=~/R/) {
 3892:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3893:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3894: 	   if ($priv ne 'pch') { 
 3895: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 3896: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3897: 	   }
 3898: 	   return '';
 3899:        }
 3900:    }
 3901: 
 3902: # Restricted by state or randomout?
 3903: 
 3904:    if ($thisallowed=~/X/) {
 3905:       if ($env{'acc.randomout'}) {
 3906: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3907:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3908:             return ''; 
 3909:          }
 3910:       }
 3911:       if (&condval($statecond)) {
 3912: 	 return '2';
 3913:       } else {
 3914:          return '';
 3915:       }
 3916:    }
 3917: 
 3918:     if ($thisallowed eq 'A') {
 3919: 	return 'A';
 3920:     }
 3921:    return 'F';
 3922: }
 3923: 
 3924: sub split_uri_for_cond {
 3925:     my $uri=&deversion(&declutter(shift));
 3926:     my @uriparts=split(/\//,$uri);
 3927:     my $filename=pop(@uriparts);
 3928:     my $pathname=join('/',@uriparts);
 3929:     return ($pathname,$filename);
 3930: }
 3931: # --------------------------------------------------- Is a resource on the map?
 3932: 
 3933: sub is_on_map {
 3934:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 3935:     #Trying to find the conditional for the file
 3936:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3937: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3938:     if ($match) {
 3939: 	return (1,$1);
 3940:     } else {
 3941: 	return (0,0);
 3942:     }
 3943: }
 3944: 
 3945: # --------------------------------------------------------- Get symb from alias
 3946: 
 3947: sub get_symb_from_alias {
 3948:     my $symb=shift;
 3949:     my ($map,$resid,$url)=&decode_symb($symb);
 3950: # Already is a symb
 3951:     if ($url) { return $symb; }
 3952: # Must be an alias
 3953:     my $aliassymb='';
 3954:     my %bighash;
 3955:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3956:                             &GDBM_READER(),0640)) {
 3957:         my $rid=$bighash{'mapalias_'.$symb};
 3958: 	if ($rid) {
 3959: 	    my ($mapid,$resid)=split(/\./,$rid);
 3960: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3961: 				    $resid,$bighash{'src_'.$rid});
 3962: 	}
 3963:         untie %bighash;
 3964:     }
 3965:     return $aliassymb;
 3966: }
 3967: 
 3968: # ----------------------------------------------------------------- Define Role
 3969: 
 3970: sub definerole {
 3971:   if (allowed('mcr','/')) {
 3972:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3973:     foreach my $role (split(':',$sysrole)) {
 3974: 	my ($crole,$cqual)=split(/\&/,$role);
 3975:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3976:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3977: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3978:                return "refused:s:$crole&$cqual"; 
 3979:             }
 3980:         }
 3981:     }
 3982:     foreach my $role (split(':',$domrole)) {
 3983: 	my ($crole,$cqual)=split(/\&/,$role);
 3984:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3985:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3986: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3987:                return "refused:d:$crole&$cqual"; 
 3988:             }
 3989:         }
 3990:     }
 3991:     foreach my $role (split(':',$courole)) {
 3992: 	my ($crole,$cqual)=split(/\&/,$role);
 3993:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3994:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3995: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3996:                return "refused:c:$crole&$cqual"; 
 3997:             }
 3998:         }
 3999:     }
 4000:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4001:                 "$env{'user.domain'}:$env{'user.name'}:".
 4002: 	        "rolesdef_$rolename=".
 4003:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4004:     return reply($command,$env{'user.home'});
 4005:   } else {
 4006:     return 'refused';
 4007:   }
 4008: }
 4009: 
 4010: # ---------------- Make a metadata query against the network of library servers
 4011: 
 4012: sub metadata_query {
 4013:     my ($query,$custom,$customshow,$server_array)=@_;
 4014:     my %rhash;
 4015:     my @server_list = (defined($server_array) ? @$server_array
 4016:                                               : keys(%libserv) );
 4017:     for my $server (@server_list) {
 4018: 	unless ($custom or $customshow) {
 4019: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4020: 	    $rhash{$server}=$reply;
 4021: 	}
 4022: 	else {
 4023: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4024: 			     &escape($custom).':'.&escape($customshow),
 4025: 			     $server);
 4026: 	    $rhash{$server}=$reply;
 4027: 	}
 4028:     }
 4029:     return \%rhash;
 4030: }
 4031: 
 4032: # ----------------------------------------- Send log queries and wait for reply
 4033: 
 4034: sub log_query {
 4035:     my ($uname,$udom,$query,%filters)=@_;
 4036:     my $uhome=&homeserver($uname,$udom);
 4037:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4038:     my $uhost=$hostname{$uhome};
 4039:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4040:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4041:                        $uhome);
 4042:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4043:     return get_query_reply($queryid);
 4044: }
 4045: 
 4046: # ------- Request retrieval of institutional classlists for course(s)
 4047: 
 4048: sub fetch_enrollment_query {
 4049:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4050:     my $homeserver;
 4051:     my $maxtries = 1;
 4052:     if ($context eq 'automated') {
 4053:         $homeserver = $perlvar{'lonHostID'};
 4054:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4055:     } else {
 4056:         $homeserver = &homeserver($cnum,$dom);
 4057:     }
 4058:     my $host=$hostname{$homeserver};
 4059:     my $cmd = '';
 4060:     foreach my $affiliate (keys %{$affiliatesref}) {
 4061:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4062:     }
 4063:     $cmd =~ s/%%$//;
 4064:     $cmd = &escape($cmd);
 4065:     my $query = 'fetchenrollment';
 4066:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4067:     unless ($queryid=~/^\Q$host\E\_/) { 
 4068:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4069:         return 'error: '.$queryid;
 4070:     }
 4071:     my $reply = &get_query_reply($queryid);
 4072:     my $tries = 1;
 4073:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4074:         $reply = &get_query_reply($queryid);
 4075:         $tries ++;
 4076:     }
 4077:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4078:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4079:     } else {
 4080:         my @responses = split/:/,$reply;
 4081:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4082:             foreach my $line (@responses) {
 4083:                 my ($key,$value) = split(/=/,$line,2);
 4084:                 $$replyref{$key} = $value;
 4085:             }
 4086:         } else {
 4087:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4088:             foreach my $line (@responses) {
 4089:                 my ($key,$value) = split(/=/,$line);
 4090:                 $$replyref{$key} = $value;
 4091:                 if ($value > 0) {
 4092:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4093:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4094:                         my $destname = $pathname.'/'.$filename;
 4095:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4096:                         if ($xml_classlist =~ /^error/) {
 4097:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4098:                         } else {
 4099:                             if ( open(FILE,">$destname") ) {
 4100:                                 print FILE &unescape($xml_classlist);
 4101:                                 close(FILE);
 4102:                             } else {
 4103:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4104:                             }
 4105:                         }
 4106:                     }
 4107:                 }
 4108:             }
 4109:         }
 4110:         return 'ok';
 4111:     }
 4112:     return 'error';
 4113: }
 4114: 
 4115: sub get_query_reply {
 4116:     my $queryid=shift;
 4117:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4118:     my $reply='';
 4119:     for (1..100) {
 4120: 	sleep 2;
 4121:         if (-e $replyfile.'.end') {
 4122: 	    if (open(my $fh,$replyfile)) {
 4123:                $reply.=<$fh>;
 4124:                close($fh);
 4125: 	   } else { return 'error: reply_file_error'; }
 4126:            return &unescape($reply);
 4127: 	}
 4128:     }
 4129:     return 'timeout:'.$queryid;
 4130: }
 4131: 
 4132: sub courselog_query {
 4133: #
 4134: # possible filters:
 4135: # url: url or symb
 4136: # username
 4137: # domain
 4138: # action: view, submit, grade
 4139: # start: timestamp
 4140: # end: timestamp
 4141: #
 4142:     my (%filters)=@_;
 4143:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4144:     if ($filters{'url'}) {
 4145: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4146:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4147:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4148:     }
 4149:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4150:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4151:     return &log_query($cname,$cdom,'courselog',%filters);
 4152: }
 4153: 
 4154: sub userlog_query {
 4155:     my ($uname,$udom,%filters)=@_;
 4156:     return &log_query($uname,$udom,'userlog',%filters);
 4157: }
 4158: 
 4159: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4160: 
 4161: sub auto_run {
 4162:     my ($cnum,$cdom) = @_;
 4163:     my $homeserver = &homeserver($cnum,$cdom);
 4164:     my $response = &reply('autorun:'.$cdom,$homeserver);
 4165:     return $response;
 4166: }
 4167: 
 4168: sub auto_get_sections {
 4169:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4170:     my $homeserver = &homeserver($cnum,$cdom);
 4171:     my @secs = ();
 4172:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4173:     unless ($response eq 'refused') {
 4174:         @secs = split/:/,$response;
 4175:     }
 4176:     return @secs;
 4177: }
 4178: 
 4179: sub auto_new_course {
 4180:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4181:     my $homeserver = &homeserver($cnum,$cdom);
 4182:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4183:     return $response;
 4184: }
 4185: 
 4186: sub auto_validate_courseID {
 4187:     my ($cnum,$cdom,$inst_course_id) = @_;
 4188:     my $homeserver = &homeserver($cnum,$cdom);
 4189:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4190:     return $response;
 4191: }
 4192: 
 4193: sub auto_create_password {
 4194:     my ($cnum,$cdom,$authparam) = @_;
 4195:     my $homeserver = &homeserver($cnum,$cdom); 
 4196:     my $create_passwd = 0;
 4197:     my $authchk = '';
 4198:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4199:     if ($response eq 'refused') {
 4200:         $authchk = 'refused';
 4201:     } else {
 4202:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4203:     }
 4204:     return ($authparam,$create_passwd,$authchk);
 4205: }
 4206: 
 4207: sub auto_photo_permission {
 4208:     my ($cnum,$cdom,$students) = @_;
 4209:     my $homeserver = &homeserver($cnum,$cdom);
 4210:     my ($outcome,$perm_reqd,$conditions) = 
 4211: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4212:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4213: 	return (undef,undef);
 4214:     }
 4215:     return ($outcome,$perm_reqd,$conditions);
 4216: }
 4217: 
 4218: sub auto_checkphotos {
 4219:     my ($uname,$udom,$pid) = @_;
 4220:     my $homeserver = &homeserver($uname,$udom);
 4221:     my ($result,$resulttype);
 4222:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4223: 				   &escape($uname).':'.&escape($pid),
 4224: 				   $homeserver));
 4225:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4226: 	return (undef,undef);
 4227:     }
 4228:     if ($outcome) {
 4229:         ($result,$resulttype) = split(/:/,$outcome);
 4230:     } 
 4231:     return ($result,$resulttype);
 4232: }
 4233: 
 4234: sub auto_photochoice {
 4235:     my ($cnum,$cdom) = @_;
 4236:     my $homeserver = &homeserver($cnum,$cdom);
 4237:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4238: 						       &escape($cdom),
 4239: 						       $homeserver)));
 4240:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4241: 	return (undef,undef);
 4242:     }
 4243:     return ($update,$comment);
 4244: }
 4245: 
 4246: sub auto_photoupdate {
 4247:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4248:     my $homeserver = &homeserver($cnum,$dom);
 4249:     my $host=$hostname{$homeserver};
 4250:     my $cmd = '';
 4251:     my $maxtries = 1;
 4252:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4253:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4254:     }
 4255:     $cmd =~ s/%%$//;
 4256:     $cmd = &escape($cmd);
 4257:     my $query = 'institutionalphotos';
 4258:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4259:     unless ($queryid=~/^\Q$host\E\_/) {
 4260:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4261:         return 'error: '.$queryid;
 4262:     }
 4263:     my $reply = &get_query_reply($queryid);
 4264:     my $tries = 1;
 4265:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4266:         $reply = &get_query_reply($queryid);
 4267:         $tries ++;
 4268:     }
 4269:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4270:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4271:     } else {
 4272:         my @responses = split(/:/,$reply);
 4273:         my $outcome = shift(@responses); 
 4274:         foreach my $item (@responses) {
 4275:             my ($key,$value) = split(/=/,$item);
 4276:             $$photo{$key} = $value;
 4277:         }
 4278:         return $outcome;
 4279:     }
 4280:     return 'error';
 4281: }
 4282: 
 4283: sub auto_instcode_format {
 4284:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4285: 	$cat_order) = @_;
 4286:     my $courses = '';
 4287:     my @homeservers;
 4288:     if ($caller eq 'global') {
 4289:         foreach my $tryserver (keys(%libserv)) {
 4290:             if ($hostdom{$tryserver} eq $codedom) {
 4291:                 if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4292:                     push(@homeservers,$tryserver);
 4293:                 }
 4294:             }
 4295:         }
 4296:     } else {
 4297:         push(@homeservers,&homeserver($caller,$codedom));
 4298:     }
 4299:     foreach my $code (keys(%{$instcodes})) {
 4300:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4301:     }
 4302:     chop($courses);
 4303:     my $ok_response = 0;
 4304:     my $response;
 4305:     while (@homeservers > 0 && $ok_response == 0) {
 4306:         my $server = shift(@homeservers); 
 4307:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4308:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4309:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4310: 		split/:/,$response;
 4311:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4312:             push(@{$codetitles},&str2array($codetitles_str));
 4313:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4314:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4315:             $ok_response = 1;
 4316:         }
 4317:     }
 4318:     if ($ok_response) {
 4319:         return 'ok';
 4320:     } else {
 4321:         return $response;
 4322:     }
 4323: }
 4324: 
 4325: sub auto_instcode_defaults {
 4326:     my ($domain,$returnhash,$code_order) = @_;
 4327:     my @homeservers;
 4328:     foreach my $tryserver (keys(%libserv)) {
 4329:         if ($hostdom{$tryserver} eq $domain) {
 4330:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4331:                 push(@homeservers,$tryserver);
 4332:             }
 4333:         }
 4334:     }
 4335:     my $ok_response = 0;
 4336:     my $response;
 4337:     while (@homeservers > 0 && $ok_response == 0) {
 4338:         my $server = shift(@homeservers);
 4339:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4340:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4341:             foreach my $pair (split(/\&/,$response)) {
 4342:                 my ($name,$value)=split(/\=/,$pair);
 4343:                 if ($name eq 'code_order') {
 4344:                     @{$code_order} = split(/\&/,&unescape($value));
 4345:                 } else {
 4346:                     $returnhash->{&unescape($name)}=&unescape($value);
 4347:                 }
 4348:             }
 4349:             $ok_response = 1;
 4350:         }
 4351:     }
 4352:     if ($ok_response) {
 4353:         return 'ok';
 4354:     } else {
 4355:         return $response;
 4356:     }
 4357: } 
 4358: 
 4359: sub auto_validate_class_sec {
 4360:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4361:     my $homeserver = &homeserver($cnum,$cdom);
 4362:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4363:                         &escape($owner).':'.$cdom,$homeserver);
 4364:     return $response;
 4365: }
 4366: 
 4367: # ------------------------------------------------------- Course Group routines
 4368: 
 4369: sub get_coursegroups {
 4370:     my ($cdom,$cnum,$group) = @_;
 4371:     return(&dump('coursegroups',$cdom,$cnum,$group));
 4372: }
 4373: 
 4374: sub get_deleted_groups {
 4375:     my ($cdom,$cnum,$group) = @_;
 4376:     return(&dump('deleted_groups',$cdom,$cnum,$group));
 4377: }
 4378: 
 4379: sub modify_coursegroup {
 4380:     my ($cdom,$cnum,$groupsettings) = @_;
 4381:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4382: }
 4383: 
 4384: sub delete_coursegroup {
 4385:     my ($cdom,$cnum,$group) = @_;
 4386:     my %curr_group = &get_coursegroups($cdom,$cnum,$group);
 4387:     if (my $tmp = &error(%curr_group)) {
 4388:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4389:         return ('read error',$tmp);
 4390:     } else {
 4391:         my %savedsettings = %curr_group; 
 4392:         my $result = &put('deleted_groups',\%savedsettings,$cdom,$cnum);
 4393:         my $deloutcome;
 4394:         if ($result eq 'ok') {
 4395:             $deloutcome = &del('coursegroups',[$group],$cdom,$cnum);
 4396:         } else {
 4397:             return ('write error',$result);
 4398:         }
 4399:         if ($deloutcome eq 'ok') {
 4400:             return 'ok';
 4401:         } else {
 4402:             return ('delete error',$deloutcome);
 4403:         }
 4404:     }
 4405: }
 4406: 
 4407: sub modify_group_roles {
 4408:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4409:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4410:     my $role = 'gr/'.&escape($userprivs);
 4411:     my ($uname,$udom) = split(/:/,$user);
 4412:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4413:     if ($result eq 'ok') {
 4414:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4415:     }
 4416:     return $result;
 4417: }
 4418: 
 4419: sub modify_coursegroup_membership {
 4420:     my ($cdom,$cnum,$membership) = @_;
 4421:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4422:     return $result;
 4423: }
 4424: 
 4425: sub get_active_groups {
 4426:     my ($udom,$uname,$cdom,$cnum) = @_;
 4427:     my $now = time;
 4428:     my %groups = ();
 4429:     foreach my $key (keys(%env)) {
 4430:         if ($key =~ m-user\.role\.gr\./([^/]+)/([^/]+)/(\w+)$-) {
 4431:             my ($start,$end) = split(/\./,$env{$key});
 4432:             if (($end!=0) && ($end<$now)) { next; }
 4433:             if (($start!=0) && ($start>$now)) { next; }
 4434:             if ($1 eq $cdom && $2 eq $cnum) {
 4435:                 $groups{$3} = $env{$key} ;
 4436:             }
 4437:         }
 4438:     }
 4439:     return %groups;
 4440: }
 4441: 
 4442: sub get_group_membership {
 4443:     my ($cdom,$cnum,$group) = @_;
 4444:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4445: }
 4446: 
 4447: sub get_users_groups {
 4448:     my ($udom,$uname,$courseid) = @_;
 4449:     my @usersgroups;
 4450:     my $cachetime=1800;
 4451:     $courseid=~s/\_/\//g;
 4452:     $courseid=~s/^(\w)/\/$1/;
 4453: 
 4454:     my $hashid="$udom:$uname:$courseid";
 4455:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4456:     if (defined($cached)) {
 4457:         @usersgroups = split(/:/,$grouplist);
 4458:     } else {  
 4459:         $grouplist = '';
 4460:         my %roleshash = &dump('roles',$udom,$uname,$courseid);
 4461:         my ($tmp) = keys(%roleshash);
 4462:         if ($tmp=~/^error:/) {
 4463:             &logthis('Error retrieving roles: '.$tmp.' for '.$uname.':'.$udom);
 4464:         } else {
 4465:             my $access_end = $env{'course.'.$courseid.
 4466:                                   '.default_enrollment_end_date'};
 4467:             my $now = time;
 4468:             foreach my $key (keys(%roleshash)) {
 4469:                 if ($key =~ /^\Q$courseid\E\/(\w+)\_gr$/) {
 4470:                     my $group = $1;
 4471:                     if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4472:                         my $start = $2;
 4473:                         my $end = $1;
 4474:                         if ($start == -1) { next; } # deleted from group
 4475:                         if (($start!=0) && ($start>$now)) { next; }
 4476:                         if (($end!=0) && ($end<$now)) {
 4477:                             if ($access_end && $access_end < $now) {
 4478:                                 if ($access_end - $end < 86400) {
 4479:                                     push(@usersgroups,$group);
 4480:                                 }
 4481:                             }
 4482:                             next;
 4483:                         }
 4484:                         push(@usersgroups,$group);
 4485:                     }
 4486:                 }
 4487:             }
 4488:             @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4489:             $grouplist = join(':',@usersgroups);
 4490:             &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4491:         }
 4492:     }
 4493:     return @usersgroups;
 4494: }
 4495: 
 4496: sub devalidate_getgroups_cache {
 4497:     my ($udom,$uname,$cdom,$cnum)=@_;
 4498:     my $courseid = $cdom.'_'.$cnum;
 4499:     $courseid=~s/\_/\//g;
 4500:     $courseid=~s/^(\w)/\/$1/;
 4501:     my $hashid="$udom:$uname:$courseid";
 4502:     &devalidate_cache_new('getgroups',$hashid);
 4503: }
 4504: 
 4505: # ------------------------------------------------------------------ Plain Text
 4506: 
 4507: sub plaintext {
 4508:     my ($short,$type,$cid) = @_;
 4509:     if ($short =~ /^cr/) {
 4510: 	return (split('/',$short))[-1];
 4511:     }
 4512:     if (!defined($cid)) {
 4513:         $cid = $env{'request.course.id'};
 4514:     }
 4515:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4516:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4517:                                           '.plaintext'});
 4518:     }
 4519:     my %rolenames = (
 4520:                       Course => 'std',
 4521:                       Group => 'alt1',
 4522:                     );
 4523:     if (defined($type) && 
 4524:          defined($rolenames{$type}) && 
 4525:          defined($prp{$short}{$rolenames{$type}})) {
 4526:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4527:     } else {
 4528:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4529:     }
 4530: }
 4531: 
 4532: # ----------------------------------------------------------------- Assign Role
 4533: 
 4534: sub assignrole {
 4535:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4536:     my $mrole;
 4537:     if ($role =~ /^cr\//) {
 4538:         my $cwosec=$url;
 4539:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4540: 	unless (&allowed('ccr',$cwosec)) {
 4541:            &logthis('Refused custom assignrole: '.
 4542:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4543: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4544:            return 'refused'; 
 4545:         }
 4546:         $mrole='cr';
 4547:     } elsif ($role =~ /^gr\//) {
 4548:         my $cwogrp=$url;
 4549:         $cwogrp=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4550:         unless (&allowed('mdg',$cwogrp)) {
 4551:             &logthis('Refused group assignrole: '.
 4552:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4553:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4554:             return 'refused';
 4555:         }
 4556:         $mrole='gr';
 4557:     } else {
 4558:         my $cwosec=$url;
 4559:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 4560:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4561:            &logthis('Refused assignrole: '.
 4562:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4563: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4564:            return 'refused'; 
 4565:         }
 4566:         $mrole=$role;
 4567:     }
 4568:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4569:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4570:     if ($end) { $command.='_'.$end; }
 4571:     if ($start) {
 4572: 	if ($end) { 
 4573:            $command.='_'.$start; 
 4574:         } else {
 4575:            $command.='_0_'.$start;
 4576:         }
 4577:     }
 4578:     my $origstart = $start;
 4579:     my $origend = $end;
 4580: # actually delete
 4581:     if ($deleteflag) {
 4582: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4583: # modify command to delete the role
 4584:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4585:                 "$udom:$uname:$url".'_'."$mrole";
 4586: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4587: # set start and finish to negative values for userrolelog
 4588:            $start=-1;
 4589:            $end=-1;
 4590:         }
 4591:     }
 4592: # send command
 4593:     my $answer=&reply($command,&homeserver($uname,$udom));
 4594: # log new user role if status is ok
 4595:     if ($answer eq 'ok') {
 4596: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4597: # for course roles, perform group memberships changes triggered by role change.
 4598:         unless ($role =~ /^gr/) {
 4599:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4600:                                              $origstart);
 4601:         }
 4602:     }
 4603:     return $answer;
 4604: }
 4605: 
 4606: # -------------------------------------------------- Modify user authentication
 4607: # Overrides without validation
 4608: 
 4609: sub modifyuserauth {
 4610:     my ($udom,$uname,$umode,$upass)=@_;
 4611:     my $uhome=&homeserver($uname,$udom);
 4612:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4613:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4614:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4615:              ' in domain '.$env{'request.role.domain'});  
 4616:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4617: 		     &escape($upass),$uhome);
 4618:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4619:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4620:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4621:     &log($udom,,$uname,$uhome,
 4622:         'Authentication changed by '.$env{'user.domain'}.', '.
 4623:                                      $env{'user.name'}.', '.$umode.
 4624:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4625:     unless ($reply eq 'ok') {
 4626:         &logthis('Authentication mode error: '.$reply);
 4627: 	return 'error: '.$reply;
 4628:     }   
 4629:     return 'ok';
 4630: }
 4631: 
 4632: # --------------------------------------------------------------- Modify a user
 4633: 
 4634: sub modifyuser {
 4635:     my ($udom,    $uname, $uid,
 4636:         $umode,   $upass, $first,
 4637:         $middle,  $last,  $gene,
 4638:         $forceid, $desiredhome, $email)=@_;
 4639:     $udom=~s/\W//g;
 4640:     $uname=~s/\W//g;
 4641:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4642:              $umode.', '.$first.', '.$middle.', '.
 4643: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4644:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4645:                                      ' desiredhome not specified'). 
 4646:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4647:              ' in domain '.$env{'request.role.domain'});
 4648:     my $uhome=&homeserver($uname,$udom,'true');
 4649: # ----------------------------------------------------------------- Create User
 4650:     if (($uhome eq 'no_host') && 
 4651: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4652:         my $unhome='';
 4653:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 4654:             $unhome = $desiredhome;
 4655: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4656: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4657:         } else { # load balancing routine for determining $unhome
 4658:             my $tryserver;
 4659:             my $loadm=10000000;
 4660:             foreach $tryserver (keys %libserv) {
 4661: 	       if ($hostdom{$tryserver} eq $udom) {
 4662:                   my $answer=reply('load',$tryserver);
 4663:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 4664: 		      $loadm=$answer;
 4665:                       $unhome=$tryserver;
 4666:                   }
 4667: 	       }
 4668: 	    }
 4669:         }
 4670:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4671: 	    return 'error: unable to find a home server for '.$uname.
 4672:                    ' in domain '.$udom;
 4673:         }
 4674:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 4675:                          &escape($upass),$unhome);
 4676: 	unless ($reply eq 'ok') {
 4677:             return 'error: '.$reply;
 4678:         }   
 4679:         $uhome=&homeserver($uname,$udom,'true');
 4680:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 4681: 	    return 'error: unable verify users home machine.';
 4682:         }
 4683:     }   # End of creation of new user
 4684: # ---------------------------------------------------------------------- Add ID
 4685:     if ($uid) {
 4686:        $uid=~tr/A-Z/a-z/;
 4687:        my %uidhash=&idrget($udom,$uname);
 4688:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 4689:          && (!$forceid)) {
 4690: 	  unless ($uid eq $uidhash{$uname}) {
 4691: 	      return 'error: user id "'.$uid.'" does not match '.
 4692:                   'current user id "'.$uidhash{$uname}.'".';
 4693:           }
 4694:        } else {
 4695: 	  &idput($udom,($uname => $uid));
 4696:        }
 4697:     }
 4698: # -------------------------------------------------------------- Add names, etc
 4699:     my @tmp=&get('environment',
 4700: 		   ['firstname','middlename','lastname','generation'],
 4701: 		   $udom,$uname);
 4702:     my %names;
 4703:     if ($tmp[0] =~ m/^error:.*/) { 
 4704:         %names=(); 
 4705:     } else {
 4706:         %names = @tmp;
 4707:     }
 4708: #
 4709: # Make sure to not trash student environment if instructor does not bother
 4710: # to supply name and email information
 4711: #
 4712:     if ($first)  { $names{'firstname'}  = $first; }
 4713:     if (defined($middle)) { $names{'middlename'} = $middle; }
 4714:     if ($last)   { $names{'lastname'}   = $last; }
 4715:     if (defined($gene))   { $names{'generation'} = $gene; }
 4716:     if ($email) {
 4717:        $email=~s/[^\w\@\.\-\,]//gs;
 4718:        if ($email=~/\@/) { $names{'notification'} = $email;
 4719: 			   $names{'critnotification'} = $email;
 4720: 			   $names{'permanentemail'} = $email; }
 4721:     }
 4722:     my $reply = &put('environment', \%names, $udom,$uname);
 4723:     if ($reply ne 'ok') { return 'error: '.$reply; }
 4724:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 4725:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 4726:              $umode.', '.$first.', '.$middle.', '.
 4727: 	     $last.', '.$gene.' by '.
 4728:              $env{'user.name'}.' at '.$env{'user.domain'});
 4729:     return 'ok';
 4730: }
 4731: 
 4732: # -------------------------------------------------------------- Modify student
 4733: 
 4734: sub modifystudent {
 4735:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 4736:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 4737:     if (!$cid) {
 4738: 	unless ($cid=$env{'request.course.id'}) {
 4739: 	    return 'not_in_class';
 4740: 	}
 4741:     }
 4742: # --------------------------------------------------------------- Make the user
 4743:     my $reply=&modifyuser
 4744: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 4745:          $desiredhome,$email);
 4746:     unless ($reply eq 'ok') { return $reply; }
 4747:     # This will cause &modify_student_enrollment to get the uid from the
 4748:     # students environment
 4749:     $uid = undef if (!$forceid);
 4750:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 4751: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 4752:     return $reply;
 4753: }
 4754: 
 4755: sub modify_student_enrollment {
 4756:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 4757:     my ($cdom,$cnum,$chome);
 4758:     if (!$cid) {
 4759: 	unless ($cid=$env{'request.course.id'}) {
 4760: 	    return 'not_in_class';
 4761: 	}
 4762: 	$cdom=$env{'course.'.$cid.'.domain'};
 4763: 	$cnum=$env{'course.'.$cid.'.num'};
 4764:     } else {
 4765: 	($cdom,$cnum)=split(/_/,$cid);
 4766:     }
 4767:     $chome=$env{'course.'.$cid.'.home'};
 4768:     if (!$chome) {
 4769: 	$chome=&homeserver($cnum,$cdom);
 4770:     }
 4771:     if (!$chome) { return 'unknown_course'; }
 4772:     # Make sure the user exists
 4773:     my $uhome=&homeserver($uname,$udom);
 4774:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4775: 	return 'error: no such user';
 4776:     }
 4777:     # Get student data if we were not given enough information
 4778:     if (!defined($first)  || $first  eq '' || 
 4779:         !defined($last)   || $last   eq '' || 
 4780:         !defined($uid)    || $uid    eq '' || 
 4781:         !defined($middle) || $middle eq '' || 
 4782:         !defined($gene)   || $gene   eq '') {
 4783:         # They did not supply us with enough data to enroll the student, so
 4784:         # we need to pick up more information.
 4785:         my %tmp = &get('environment',
 4786:                        ['firstname','middlename','lastname', 'generation','id']
 4787:                        ,$udom,$uname);
 4788: 
 4789:         #foreach my $key (keys(%tmp)) {
 4790:         #    &logthis("key $key = ".$tmp{$key});
 4791:         #}
 4792:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 4793:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 4794:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 4795:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 4796:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 4797:     }
 4798:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 4799:     my $reply=cput('classlist',
 4800: 		   {"$uname:$udom" => 
 4801: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 4802: 		   $cdom,$cnum);
 4803:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 4804: 	return 'error: '.$reply;
 4805:     } else {
 4806: 	&devalidate_getsection_cache($udom,$uname,$cid);
 4807:     }
 4808:     # Add student role to user
 4809:     my $uurl='/'.$cid;
 4810:     $uurl=~s/\_/\//g;
 4811:     if ($usec) {
 4812: 	$uurl.='/'.$usec;
 4813:     }
 4814:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 4815: }
 4816: 
 4817: sub format_name {
 4818:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 4819:     my $name;
 4820:     if ($first ne 'lastname') {
 4821: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 4822:     } else {
 4823: 	if ($lastname=~/\S/) {
 4824: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 4825: 	    $name=~s/\s+,/,/;
 4826: 	} else {
 4827: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 4828: 	}
 4829:     }
 4830:     $name=~s/^\s+//;
 4831:     $name=~s/\s+$//;
 4832:     $name=~s/\s+/ /g;
 4833:     return $name;
 4834: }
 4835: 
 4836: # ------------------------------------------------- Write to course preferences
 4837: 
 4838: sub writecoursepref {
 4839:     my ($courseid,%prefs)=@_;
 4840:     $courseid=~s/^\///;
 4841:     $courseid=~s/\_/\//g;
 4842:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4843:     my $chome=homeserver($cnum,$cdomain);
 4844:     if (($chome eq '') || ($chome eq 'no_host')) { 
 4845: 	return 'error: no such course';
 4846:     }
 4847:     my $cstring='';
 4848:     foreach my $pref (keys(%prefs)) {
 4849: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 4850:     }
 4851:     $cstring=~s/\&$//;
 4852:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 4853: }
 4854: 
 4855: # ---------------------------------------------------------- Make/modify course
 4856: 
 4857: sub createcourse {
 4858:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 4859:         $course_owner,$crstype)=@_;
 4860:     $url=&declutter($url);
 4861:     my $cid='';
 4862:     unless (&allowed('ccc',$udom)) {
 4863:         return 'refused';
 4864:     }
 4865: # ------------------------------------------------------------------- Create ID
 4866:    my $uname=int(1+rand(9)).
 4867:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 4868:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4869:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4870: # ----------------------------------------------- Make sure that does not exist
 4871:    my $uhome=&homeserver($uname,$udom,'true');
 4872:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4873:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 4874:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 4875:        $uhome=&homeserver($uname,$udom,'true');       
 4876:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 4877:            return 'error: unable to generate unique course-ID';
 4878:        } 
 4879:    }
 4880: # ------------------------------------------------ Check supplied server name
 4881:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 4882:     if (! exists($libserv{$course_server})) {
 4883:         return 'error:bad server name '.$course_server;
 4884:     }
 4885: # ------------------------------------------------------------- Make the course
 4886:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 4887:                       $course_server);
 4888:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 4889:     $uhome=&homeserver($uname,$udom,'true');
 4890:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 4891: 	return 'error: no such course';
 4892:     }
 4893: # ----------------------------------------------------------------- Course made
 4894: # log existence
 4895:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 4896:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 4897:                   &escape($crstype),$uhome);
 4898:     &flushcourselogs();
 4899: # set toplevel url
 4900:     my $topurl=$url;
 4901:     unless ($nonstandard) {
 4902: # ------------------------------------------ For standard courses, make top url
 4903:         my $mapurl=&clutter($url);
 4904:         if ($mapurl eq '/res/') { $mapurl=''; }
 4905:         $env{'form.initmap'}=(<<ENDINITMAP);
 4906: <map>
 4907: <resource id="1" type="start"></resource>
 4908: <resource id="2" src="$mapurl"></resource>
 4909: <resource id="3" type="finish"></resource>
 4910: <link index="1" from="1" to="2"></link>
 4911: <link index="2" from="2" to="3"></link>
 4912: </map>
 4913: ENDINITMAP
 4914:         $topurl=&declutter(
 4915:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 4916:                           );
 4917:     }
 4918: # ----------------------------------------------------------- Write preferences
 4919:     &writecoursepref($udom.'_'.$uname,
 4920:                      ('description' => $description,
 4921:                       'url'         => $topurl));
 4922:     return '/'.$udom.'/'.$uname;
 4923: }
 4924: 
 4925: # ---------------------------------------------------------- Assign Custom Role
 4926: 
 4927: sub assigncustomrole {
 4928:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 4929:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 4930:                        $end,$start,$deleteflag);
 4931: }
 4932: 
 4933: # ----------------------------------------------------------------- Revoke Role
 4934: 
 4935: sub revokerole {
 4936:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4937:     my $now=time;
 4938:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4939: }
 4940: 
 4941: # ---------------------------------------------------------- Revoke Custom Role
 4942: 
 4943: sub revokecustomrole {
 4944:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4945:     my $now=time;
 4946:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4947:            $deleteflag);
 4948: }
 4949: 
 4950: # ------------------------------------------------------------ Disk usage
 4951: sub diskusage {
 4952:     my ($udom,$uname,$directoryRoot)=@_;
 4953:     $directoryRoot =~ s/\/$//;
 4954:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4955:     return $listing;
 4956: }
 4957: 
 4958: sub is_locked {
 4959:     my ($file_name, $domain, $user) = @_;
 4960:     my @check;
 4961:     my $is_locked;
 4962:     push @check, $file_name;
 4963:     my %locked = &get('file_permissions',\@check,
 4964: 		      $env{'user.domain'},$env{'user.name'});
 4965:     my ($tmp)=keys(%locked);
 4966:     if ($tmp=~/^error:/) { undef(%locked); }
 4967:     
 4968:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4969:         $is_locked = 'false';
 4970:         foreach my $entry (@{$locked{$file_name}}) {
 4971:            if (ref($entry) eq 'ARRAY') { 
 4972:                $is_locked = 'true';
 4973:                last;
 4974:            }
 4975:        }
 4976:     } else {
 4977:         $is_locked = 'false';
 4978:     }
 4979: }
 4980: 
 4981: sub declutter_portfile {
 4982:     my ($file) = @_;
 4983:     &logthis("got $file");
 4984:     $file =~ s-^(/portfolio/|portfolio/)-/-;
 4985:     &logthis("ret $file");
 4986:     return $file;
 4987: }
 4988: 
 4989: # ------------------------------------------------------------- Mark as Read Only
 4990: 
 4991: sub mark_as_readonly {
 4992:     my ($domain,$user,$files,$what) = @_;
 4993:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4994:     my ($tmp)=keys(%current_permissions);
 4995:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4996:     foreach my $file (@{$files}) {
 4997: 	$file = &declutter_portfile($file);
 4998:         push(@{$current_permissions{$file}},$what);
 4999:     }
 5000:     &put('file_permissions',\%current_permissions,$domain,$user);
 5001:     return;
 5002: }
 5003: 
 5004: # ------------------------------------------------------------Save Selected Files
 5005: 
 5006: sub save_selected_files {
 5007:     my ($user, $path, @files) = @_;
 5008:     my $filename = $user."savedfiles";
 5009:     my @other_files = &files_not_in_path($user, $path);
 5010:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5011:     foreach my $file (@files) {
 5012:         print (OUT $env{'form.currentpath'}.$file."\n");
 5013:     }
 5014:     foreach my $file (@other_files) {
 5015:         print (OUT $file."\n");
 5016:     }
 5017:     close (OUT);
 5018:     return 'ok';
 5019: }
 5020: 
 5021: sub clear_selected_files {
 5022:     my ($user) = @_;
 5023:     my $filename = $user."savedfiles";
 5024:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5025:     print (OUT undef);
 5026:     close (OUT);
 5027:     return ("ok");    
 5028: }
 5029: 
 5030: sub files_in_path {
 5031:     my ($user, $path) = @_;
 5032:     my $filename = $user."savedfiles";
 5033:     my %return_files;
 5034:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5035:     while (my $line_in = <IN>) {
 5036:         chomp ($line_in);
 5037:         my @paths_and_file = split (m!/!, $line_in);
 5038:         my $file_part = pop (@paths_and_file);
 5039:         my $path_part = join ('/', @paths_and_file);
 5040:         $path_part.='/';
 5041:         my $path_and_file = $path_part.$file_part;
 5042:         if ($path_part eq $path) {
 5043:             $return_files{$file_part}= 'selected';
 5044:         }
 5045:     }
 5046:     close (IN);
 5047:     return (\%return_files);
 5048: }
 5049: 
 5050: # called in portfolio select mode, to show files selected NOT in current directory
 5051: sub files_not_in_path {
 5052:     my ($user, $path) = @_;
 5053:     my $filename = $user."savedfiles";
 5054:     my @return_files;
 5055:     my $path_part;
 5056:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5057:     while (my $line = <IN>) {
 5058:         #ok, I know it's clunky, but I want it to work
 5059:         my @paths_and_file = split(m|/|, $line);
 5060:         my $file_part = pop(@paths_and_file);
 5061:         chomp($file_part);
 5062:         my $path_part = join('/', @paths_and_file);
 5063:         $path_part .= '/';
 5064:         my $path_and_file = $path_part.$file_part;
 5065:         if ($path_part ne $path) {
 5066:             push(@return_files, ($path_and_file));
 5067:         }
 5068:     }
 5069:     close(OUT);
 5070:     return (@return_files);
 5071: }
 5072: 
 5073: #----------------------------------------------Get portfolio file permissions
 5074: 
 5075: sub get_portfile_permissions {
 5076:     my ($domain,$user) = @_;
 5077:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5078:     my ($tmp)=keys(%current_permissions);
 5079:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5080:     return \%current_permissions;
 5081: }
 5082: 
 5083: #---------------------------------------------Get portfolio file access controls
 5084: 
 5085: sub get_access_controls {
 5086:     my ($current_permissions,$group,$file) = @_;
 5087:     my %access;
 5088:     my $real_file = $file;
 5089:     $file =~ s/\.meta$//;
 5090:     if (defined($file)) {
 5091:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5092:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5093:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5094:             }
 5095:         }
 5096:     } else {
 5097:         foreach my $key (keys(%{$current_permissions})) {
 5098:             if ($key =~ /\0accesscontrol$/) {
 5099:                 if (defined($group)) {
 5100:                     if ($key !~ m-^\Q$group\E/-) {
 5101:                         next;
 5102:                     }
 5103:                 }
 5104:                 my ($fullpath) = split(/\0/,$key);
 5105:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5106:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5107:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5108:                     }
 5109:                 }
 5110:             }
 5111:         }
 5112:     }
 5113:     return %access;
 5114: }
 5115: 
 5116: sub modify_access_controls {
 5117:     my ($file_name,$changes,$domain,$user)=@_;
 5118:     my ($outcome,$deloutcome);
 5119:     my %store_permissions;
 5120:     my %new_values;
 5121:     my %new_control;
 5122:     my %translation;
 5123:     my @deletions = ();
 5124:     my $now = time;
 5125:     if (exists($$changes{'activate'})) {
 5126:         if (ref($$changes{'activate'}) eq 'HASH') {
 5127:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5128:             my $numnew = scalar(@newitems);
 5129:             for (my $i=0; $i<$numnew; $i++) {
 5130:                 my $newkey = $newitems[$i];
 5131:                 my $newid = &Apache::loncommon::get_cgi_id();
 5132:                 if ($newkey =~ /^\d+:/) { 
 5133:                     $newkey =~ s/^(\d+)/$newid/;
 5134:                     $translation{$1} = $newid;
 5135:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5136:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5137:                     $translation{$1} = $newid;
 5138:                 }
 5139:                 $new_values{$file_name."\0".$newkey} = 
 5140:                                           $$changes{'activate'}{$newitems[$i]};
 5141:                 $new_control{$newkey} = $now;
 5142:             }
 5143:         }
 5144:     }
 5145:     my %todelete;
 5146:     my %changed_items;
 5147:     foreach my $action ('delete','update') {
 5148:         if (exists($$changes{$action})) {
 5149:             if (ref($$changes{$action}) eq 'HASH') {
 5150:                 foreach my $key (keys(%{$$changes{$action}})) {
 5151:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5152:                     if ($action eq 'delete') { 
 5153:                         $todelete{$itemnum} = 1;
 5154:                     } else {
 5155:                         $changed_items{$itemnum} = $key;
 5156:                     }
 5157:                 }
 5158:             }
 5159:         }
 5160:     }
 5161:     # get lock on access controls for file.
 5162:     my $lockhash = {
 5163:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5164:                                                        ':'.$env{'user.domain'},
 5165:                    }; 
 5166:     my $tries = 0;
 5167:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5168:    
 5169:     while (($gotlock ne 'ok') && $tries <3) {
 5170:         $tries ++;
 5171:         sleep 1;
 5172:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5173:     }
 5174:     if ($gotlock eq 'ok') {
 5175:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5176:         my ($tmp)=keys(%curr_permissions);
 5177:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5178:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5179:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5180:             if (ref($curr_controls) eq 'HASH') {
 5181:                 foreach my $control_item (keys(%{$curr_controls})) {
 5182:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5183:                     if (defined($todelete{$itemnum})) {
 5184:                         push(@deletions,$file_name."\0".$control_item);
 5185:                     } else {
 5186:                         if (defined($changed_items{$itemnum})) {
 5187:                             $new_control{$changed_items{$itemnum}} = $now;
 5188:                             push(@deletions,$file_name."\0".$control_item);
 5189:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5190:                         } else {
 5191:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5192:                         }
 5193:                     }
 5194:                 }
 5195:             }
 5196:         }
 5197:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5198:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5199:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5200:         #  remove lock
 5201:         my @del_lock = ($file_name."\0".'locked_access_records');
 5202:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5203:     } else {
 5204:         $outcome = "error: could not obtain lockfile\n";  
 5205:     }
 5206:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5207: }
 5208: 
 5209: #------------------------------------------------------Get Marked as Read Only
 5210: 
 5211: sub get_marked_as_readonly {
 5212:     my ($domain,$user,$what,$group) = @_;
 5213:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5214:     my @readonly_files;
 5215:     my $cmp1=$what;
 5216:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5217:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5218:         if (defined($group)) {
 5219:             if ($file_name !~ m-^\Q$group\E/-) {
 5220:                 next;
 5221:             }
 5222:         }
 5223:         if (ref($value) eq "ARRAY"){
 5224:             foreach my $stored_what (@{$value}) {
 5225:                 my $cmp2=$stored_what;
 5226:                 if (ref($stored_what) eq 'ARRAY') {
 5227:                     $cmp2=join('',@{$stored_what});
 5228:                 }
 5229:                 if ($cmp1 eq $cmp2) {
 5230:                     push(@readonly_files, $file_name);
 5231:                     last;
 5232:                 } elsif (!defined($what)) {
 5233:                     push(@readonly_files, $file_name);
 5234:                     last;
 5235:                 }
 5236:             }
 5237:         }
 5238:     }
 5239:     return @readonly_files;
 5240: }
 5241: #-----------------------------------------------------------Get Marked as Read Only Hash
 5242: 
 5243: sub get_marked_as_readonly_hash {
 5244:     my ($current_permissions,$group,$what) = @_;
 5245:     my %readonly_files;
 5246:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5247:         if (defined($group)) {
 5248:             if ($file_name !~ m-^\Q$group\E/-) {
 5249:                 next;
 5250:             }
 5251:         }
 5252:         if (ref($value) eq "ARRAY"){
 5253:             foreach my $stored_what (@{$value}) {
 5254:                 if (ref($stored_what) eq 'ARRAY') {
 5255:                     foreach my $lock_descriptor(@{$stored_what}) {
 5256:                         if ($lock_descriptor eq 'graded') {
 5257:                             $readonly_files{$file_name} = 'graded';
 5258:                         } elsif ($lock_descriptor eq 'handback') {
 5259:                             $readonly_files{$file_name} = 'handback';
 5260:                         } else {
 5261:                             if (!exists($readonly_files{$file_name})) {
 5262:                                 $readonly_files{$file_name} = 'locked';
 5263:                             }
 5264:                         }
 5265:                     }
 5266:                 } 
 5267:             }
 5268:         } 
 5269:     }
 5270:     return %readonly_files;
 5271: }
 5272: # ------------------------------------------------------------ Unmark as Read Only
 5273: 
 5274: sub unmark_as_readonly {
 5275:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5276:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5277:     my ($domain,$user,$what,$file_name,$group) = @_;
 5278:     $file_name = &declutter_portfile($file_name);
 5279:     my $symb_crs = $what;
 5280:     if (ref($what)) { $symb_crs=join('',@$what); }
 5281:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5282:     my ($tmp)=keys(%current_permissions);
 5283:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5284:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5285:     foreach my $file (@readonly_files) {
 5286: 	my $clean_file = &declutter_portfile($file);
 5287: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5288: 	my $current_locks = $current_permissions{$file};
 5289:         my @new_locks;
 5290:         my @del_keys;
 5291:         if (ref($current_locks) eq "ARRAY"){
 5292:             foreach my $locker (@{$current_locks}) {
 5293:                 my $compare=$locker;
 5294:                 if (ref($locker) eq 'ARRAY') {
 5295:                     $compare=join('',@{$locker});
 5296:                     if ($compare ne $symb_crs) {
 5297:                         push(@new_locks, $locker);
 5298:                     }
 5299:                 }
 5300:             }
 5301:             if (scalar(@new_locks) > 0) {
 5302:                 $current_permissions{$file} = \@new_locks;
 5303:             } else {
 5304:                 push(@del_keys, $file);
 5305:                 &del('file_permissions',\@del_keys, $domain, $user);
 5306:                 delete($current_permissions{$file});
 5307:             }
 5308:         }
 5309:     }
 5310:     &put('file_permissions',\%current_permissions,$domain,$user);
 5311:     return;
 5312: }
 5313: 
 5314: # ------------------------------------------------------------ Directory lister
 5315: 
 5316: sub dirlist {
 5317:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5318: 
 5319:     $uri=~s/^\///;
 5320:     $uri=~s/\/$//;
 5321:     my ($udom, $uname);
 5322:     (undef,$udom,$uname)=split(/\//,$uri);
 5323:     if(defined($userdomain)) {
 5324:         $udom = $userdomain;
 5325:     }
 5326:     if(defined($username)) {
 5327:         $uname = $username;
 5328:     }
 5329: 
 5330:     my $dirRoot = $perlvar{'lonDocRoot'};
 5331:     if(defined($alternateDirectoryRoot)) {
 5332:         $dirRoot = $alternateDirectoryRoot;
 5333:         $dirRoot =~ s/\/$//;
 5334:     }
 5335: 
 5336:     if($udom) {
 5337:         if($uname) {
 5338:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5339: 				 &homeserver($uname,$udom));
 5340:             my @listing_results;
 5341:             if ($listing eq 'unknown_cmd') {
 5342:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5343: 				  &homeserver($uname,$udom));
 5344:                 @listing_results = split(/:/,$listing);
 5345:             } else {
 5346:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5347:             }
 5348:             return @listing_results;
 5349:         } elsif(!defined($alternateDirectoryRoot)) {
 5350:             my %allusers;
 5351:             foreach my $tryserver (keys(%libserv)) {
 5352:                 if($hostdom{$tryserver} eq $udom) {
 5353:                     my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5354: 					 $udom, $tryserver);
 5355:                     my @listing_results;
 5356:                     if ($listing eq 'unknown_cmd') {
 5357:                         $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5358: 					  $udom, $tryserver);
 5359:                         @listing_results = split(/:/,$listing);
 5360:                     } else {
 5361:                         @listing_results =
 5362:                             map { &unescape($_); } split(/:/,$listing);
 5363:                     }
 5364:                     if ($listing_results[0] ne 'no_such_dir' && 
 5365:                         $listing_results[0] ne 'empty'       &&
 5366:                         $listing_results[0] ne 'con_lost') {
 5367:                         foreach my $line (@listing_results) {
 5368:                             my ($entry) = split(/&/,$line,2);
 5369:                             $allusers{$entry} = 1;
 5370:                         }
 5371:                     }
 5372:                 }
 5373:             }
 5374:             my $alluserstr='';
 5375:             foreach my $user (sort(keys(%allusers))) {
 5376:                 $alluserstr.=$user.'&user:';
 5377:             }
 5378:             $alluserstr=~s/:$//;
 5379:             return split(/:/,$alluserstr);
 5380:         } else {
 5381:             return ('missing user name');
 5382:         }
 5383:     } elsif(!defined($alternateDirectoryRoot)) {
 5384:         my $tryserver;
 5385:         my %alldom=();
 5386:         foreach $tryserver (keys(%libserv)) {
 5387:             $alldom{$hostdom{$tryserver}}=1;
 5388:         }
 5389:         my $alldomstr='';
 5390:         foreach my $domain (sort(keys(%alldom))) {
 5391:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain:';
 5392:         }
 5393:         $alldomstr=~s/:$//;
 5394:         return split(/:/,$alldomstr);       
 5395:     } else {
 5396:         return ('missing domain');
 5397:     }
 5398: }
 5399: 
 5400: # --------------------------------------------- GetFileTimestamp
 5401: # This function utilizes dirlist and returns the date stamp for
 5402: # when it was last modified.  It will also return an error of -1
 5403: # if an error occurs
 5404: 
 5405: ##
 5406: ## FIXME: This subroutine assumes its caller knows something about the
 5407: ## directory structure of the home server for the student ($root).
 5408: ## Not a good assumption to make.  Since this is for looking up files
 5409: ## in user directories, the full path should be constructed by lond, not
 5410: ## whatever machine we request data from.
 5411: ##
 5412: sub GetFileTimestamp {
 5413:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5414:     $studentDomain=~s/\W//g;
 5415:     $studentName=~s/\W//g;
 5416:     my $subdir=$studentName.'__';
 5417:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5418:     my $proname="$studentDomain/$subdir/$studentName";
 5419:     $proname .= '/'.$filename;
 5420:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5421:                                               $studentName, $root);
 5422:     my @stats = split('&', $fileStat);
 5423:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5424:         # @stats contains first the filename, then the stat output
 5425:         return $stats[10]; # so this is 10 instead of 9.
 5426:     } else {
 5427:         return -1;
 5428:     }
 5429: }
 5430: 
 5431: sub stat_file {
 5432:     my ($uri) = @_;
 5433:     $uri = &clutter_with_no_wrapper($uri);
 5434: 
 5435:     my ($udom,$uname,$file,$dir);
 5436:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5437: 	($udom,$uname,$file) =
 5438: 	    ($uri =~ m-/(?:uploaded|editupload)/?([^/]*)/?([^/]*)/?(.*)-);
 5439: 	$file = 'userfiles/'.$file;
 5440: 	$dir = &propath($udom,$uname);
 5441:     }
 5442:     if ($uri =~ m-^/res/-) {
 5443: 	($udom,$uname) = 
 5444: 	    ($uri =~ m-/(?:res)/?([^/]*)/?([^/]*)/-);
 5445: 	$file = $uri;
 5446:     }
 5447: 
 5448:     if (!$udom || !$uname || !$file) {
 5449: 	# unable to handle the uri
 5450: 	return ();
 5451:     }
 5452: 
 5453:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5454:     my @stats = split('&', $result);
 5455:     
 5456:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5457: 	shift(@stats); #filename is first
 5458: 	return @stats;
 5459:     }
 5460:     return ();
 5461: }
 5462: 
 5463: # -------------------------------------------------------- Value of a Condition
 5464: 
 5465: # gets the value of a specific preevaluated condition
 5466: #    stored in the string  $env{user.state.<cid>}
 5467: # or looks up a condition reference in the bighash and if if hasn't
 5468: # already been evaluated recurses into docondval to get the value of
 5469: # the condition, then memoizing it to 
 5470: #   $env{user.state.<cid>.<condition>}
 5471: sub directcondval {
 5472:     my $number=shift;
 5473:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5474: 	&Apache::lonuserstate::evalstate();
 5475:     }
 5476:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5477: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5478:     } elsif ($number =~ /^_/) {
 5479: 	my $sub_condition;
 5480: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5481: 		&GDBM_READER(),0640)) {
 5482: 	    $sub_condition=$bighash{'conditions'.$number};
 5483: 	    untie(%bighash);
 5484: 	}
 5485: 	my $value = &docondval($sub_condition);
 5486: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5487: 	return $value;
 5488:     }
 5489:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5490:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5491:     } else {
 5492:        return 2;
 5493:     }
 5494: }
 5495: 
 5496: # get the collection of conditions for this resource
 5497: sub condval {
 5498:     my $condidx=shift;
 5499:     my $allpathcond='';
 5500:     foreach my $cond (split(/\|/,$condidx)) {
 5501: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5502: 	    $allpathcond.=
 5503: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5504: 	}
 5505:     }
 5506:     $allpathcond=~s/\|$//;
 5507:     return &docondval($allpathcond);
 5508: }
 5509: 
 5510: #evaluates an expression of conditions
 5511: sub docondval {
 5512:     my ($allpathcond) = @_;
 5513:     my $result=0;
 5514:     if ($env{'request.course.id'}
 5515: 	&& defined($allpathcond)) {
 5516: 	my $operand='|';
 5517: 	my @stack;
 5518: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5519: 	    if ($chunk eq '(') {
 5520: 		push @stack,($operand,$result);
 5521: 	    } elsif ($chunk eq ')') {
 5522: 		my $before=pop @stack;
 5523: 		if (pop @stack eq '&') {
 5524: 		    $result=$result>$before?$before:$result;
 5525: 		} else {
 5526: 		    $result=$result>$before?$result:$before;
 5527: 		}
 5528: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5529: 		$operand=$chunk;
 5530: 	    } else {
 5531: 		my $new=directcondval($chunk);
 5532: 		if ($operand eq '&') {
 5533: 		    $result=$result>$new?$new:$result;
 5534: 		} else {
 5535: 		    $result=$result>$new?$result:$new;
 5536: 		}
 5537: 	    }
 5538: 	}
 5539:     }
 5540:     return $result;
 5541: }
 5542: 
 5543: # ---------------------------------------------------- Devalidate courseresdata
 5544: 
 5545: sub devalidatecourseresdata {
 5546:     my ($coursenum,$coursedomain)=@_;
 5547:     my $hashid=$coursenum.':'.$coursedomain;
 5548:     &devalidate_cache_new('courseres',$hashid);
 5549: }
 5550: 
 5551: 
 5552: # --------------------------------------------------- Course Resourcedata Query
 5553: 
 5554: sub get_courseresdata {
 5555:     my ($coursenum,$coursedomain)=@_;
 5556:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5557:     my $hashid=$coursenum.':'.$coursedomain;
 5558:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5559:     my %dumpreply;
 5560:     unless (defined($cached)) {
 5561: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5562: 	$result=\%dumpreply;
 5563: 	my ($tmp) = keys(%dumpreply);
 5564: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5565: 	    &do_cache_new('courseres',$hashid,$result,600);
 5566: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5567: 	    return $tmp;
 5568: 	} elsif ($tmp =~ /^(error)/) {
 5569: 	    $result=undef;
 5570: 	    &do_cache_new('courseres',$hashid,$result,600);
 5571: 	}
 5572:     }
 5573:     return $result;
 5574: }
 5575: 
 5576: sub devalidateuserresdata {
 5577:     my ($uname,$udom)=@_;
 5578:     my $hashid="$udom:$uname";
 5579:     &devalidate_cache_new('userres',$hashid);
 5580: }
 5581: 
 5582: sub get_userresdata {
 5583:     my ($uname,$udom)=@_;
 5584:     #most student don\'t have any data set, check if there is some data
 5585:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5586: 
 5587:     my $hashid="$udom:$uname";
 5588:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5589:     if (!defined($cached)) {
 5590: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5591: 	$result=\%resourcedata;
 5592: 	&do_cache_new('userres',$hashid,$result,600);
 5593:     }
 5594:     my ($tmp)=keys(%$result);
 5595:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5596: 	return $result;
 5597:     }
 5598:     #error 2 occurs when the .db doesn't exist
 5599:     if ($tmp!~/error: 2 /) {
 5600: 	&logthis("<font color=\"blue\">WARNING:".
 5601: 		 " Trying to get resource data for ".
 5602: 		 $uname." at ".$udom.": ".
 5603: 		 $tmp."</font>");
 5604:     } elsif ($tmp=~/error: 2 /) {
 5605: 	#&EXT_cache_set($udom,$uname);
 5606: 	&do_cache_new('userres',$hashid,undef,600);
 5607: 	undef($tmp); # not really an error so don't send it back
 5608:     }
 5609:     return $tmp;
 5610: }
 5611: 
 5612: sub resdata {
 5613:     my ($name,$domain,$type,@which)=@_;
 5614:     my $result;
 5615:     if ($type eq 'course') {
 5616: 	$result=&get_courseresdata($name,$domain);
 5617:     } elsif ($type eq 'user') {
 5618: 	$result=&get_userresdata($name,$domain);
 5619:     }
 5620:     if (!ref($result)) { return $result; }    
 5621:     foreach my $item (@which) {
 5622: 	if (defined($result->{$item})) {
 5623: 	    return $result->{$item};
 5624: 	}
 5625:     }
 5626:     return undef;
 5627: }
 5628: 
 5629: #
 5630: # EXT resource caching routines
 5631: #
 5632: 
 5633: sub clear_EXT_cache_status {
 5634:     &delenv('cache.EXT.');
 5635: }
 5636: 
 5637: sub EXT_cache_status {
 5638:     my ($target_domain,$target_user) = @_;
 5639:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5640:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 5641:         # We know already the user has no data
 5642:         return 1;
 5643:     } else {
 5644:         return 0;
 5645:     }
 5646: }
 5647: 
 5648: sub EXT_cache_set {
 5649:     my ($target_domain,$target_user) = @_;
 5650:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 5651:     #&appenv($cachename => time);
 5652: }
 5653: 
 5654: # --------------------------------------------------------- Value of a Variable
 5655: sub EXT {
 5656: 
 5657:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 5658:     unless ($varname) { return ''; }
 5659:     #get real user name/domain, courseid and symb
 5660:     my $courseid;
 5661:     my $publicuser;
 5662:     if ($symbparm) {
 5663: 	$symbparm=&get_symb_from_alias($symbparm);
 5664:     }
 5665:     if (!($uname && $udom)) {
 5666:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 5667:       if (!$symbparm) {	$symbparm=$cursymb; }
 5668:     } else {
 5669: 	$courseid=$env{'request.course.id'};
 5670:     }
 5671:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 5672:     my $rest;
 5673:     if (defined($therest[0])) {
 5674:        $rest=join('.',@therest);
 5675:     } else {
 5676:        $rest='';
 5677:     }
 5678: 
 5679:     my $qualifierrest=$qualifier;
 5680:     if ($rest) { $qualifierrest.='.'.$rest; }
 5681:     my $spacequalifierrest=$space;
 5682:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 5683:     if ($realm eq 'user') {
 5684: # --------------------------------------------------------------- user.resource
 5685: 	if ($space eq 'resource') {
 5686: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 5687: 		  || defined($Apache::lonhomework::parsing_a_task))
 5688: 		 &&
 5689: 		 ($symbparm eq &symbread()) ) {	
 5690: 		# if we are in the middle of processing the resource the
 5691: 		# get the value we are planning on committing
 5692:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 5693:                     return $Apache::lonhomework::results{$qualifierrest};
 5694:                 } else {
 5695:                     return $Apache::lonhomework::history{$qualifierrest};
 5696:                 }
 5697: 	    } else {
 5698: 		my %restored;
 5699: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 5700: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 5701: 		} else {
 5702: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 5703: 		}
 5704: 		return $restored{$qualifierrest};
 5705: 	    }
 5706: # ----------------------------------------------------------------- user.access
 5707:         } elsif ($space eq 'access') {
 5708: 	    # FIXME - not supporting calls for a specific user
 5709:             return &allowed($qualifier,$rest);
 5710: # ------------------------------------------ user.preferences, user.environment
 5711:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 5712: 	    if (($uname eq $env{'user.name'}) &&
 5713: 		($udom eq $env{'user.domain'})) {
 5714: 		return $env{join('.',('environment',$qualifierrest))};
 5715: 	    } else {
 5716: 		my %returnhash;
 5717: 		if (!$publicuser) {
 5718: 		    %returnhash=&userenvironment($udom,$uname,
 5719: 						 $qualifierrest);
 5720: 		}
 5721: 		return $returnhash{$qualifierrest};
 5722: 	    }
 5723: # ----------------------------------------------------------------- user.course
 5724:         } elsif ($space eq 'course') {
 5725: 	    # FIXME - not supporting calls for a specific user
 5726:             return $env{join('.',('request.course',$qualifier))};
 5727: # ------------------------------------------------------------------- user.role
 5728:         } elsif ($space eq 'role') {
 5729: 	    # FIXME - not supporting calls for a specific user
 5730:             my ($role,$where)=split(/\./,$env{'request.role'});
 5731:             if ($qualifier eq 'value') {
 5732: 		return $role;
 5733:             } elsif ($qualifier eq 'extent') {
 5734:                 return $where;
 5735:             }
 5736: # ----------------------------------------------------------------- user.domain
 5737:         } elsif ($space eq 'domain') {
 5738:             return $udom;
 5739: # ------------------------------------------------------------------- user.name
 5740:         } elsif ($space eq 'name') {
 5741:             return $uname;
 5742: # ---------------------------------------------------- Any other user namespace
 5743:         } else {
 5744: 	    my %reply;
 5745: 	    if (!$publicuser) {
 5746: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 5747: 	    }
 5748: 	    return $reply{$qualifierrest};
 5749:         }
 5750:     } elsif ($realm eq 'query') {
 5751: # ---------------------------------------------- pull stuff out of query string
 5752:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 5753: 						[$spacequalifierrest]);
 5754: 	return $env{'form.'.$spacequalifierrest}; 
 5755:    } elsif ($realm eq 'request') {
 5756: # ------------------------------------------------------------- request.browser
 5757:         if ($space eq 'browser') {
 5758: 	    if ($qualifier eq 'textremote') {
 5759: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 5760: 		    return 1;
 5761: 		} else {
 5762: 		    return 0;
 5763: 		}
 5764: 	    } else {
 5765: 		return $env{'browser.'.$qualifier};
 5766: 	    }
 5767: # ------------------------------------------------------------ request.filename
 5768:         } else {
 5769:             return $env{'request.'.$spacequalifierrest};
 5770:         }
 5771:     } elsif ($realm eq 'course') {
 5772: # ---------------------------------------------------------- course.description
 5773:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 5774:     } elsif ($realm eq 'resource') {
 5775: 
 5776: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 5777: 	    if (!$symbparm) { $symbparm=&symbread(); }
 5778: 	}
 5779: 
 5780: 	if ($space eq 'title') {
 5781: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 5782: 	    return &gettitle($symbparm);
 5783: 	}
 5784: 	
 5785: 	if ($space eq 'map') {
 5786: 	    my ($map) = &decode_symb($symbparm);
 5787: 	    return &symbread($map);
 5788: 	}
 5789: 
 5790: 	my ($section, $group, @groups);
 5791: 	my ($courselevelm,$courselevel);
 5792: 	if ($symbparm && defined($courseid) && 
 5793: 	    $courseid eq $env{'request.course.id'}) {
 5794: 
 5795: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 5796: 
 5797: # ----------------------------------------------------- Cascading lookup scheme
 5798: 	    my $symbp=$symbparm;
 5799: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 5800: 
 5801: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 5802: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 5803: 
 5804: 	    if (($env{'user.name'} eq $uname) &&
 5805: 		($env{'user.domain'} eq $udom)) {
 5806: 		$section=$env{'request.course.sec'};
 5807:                 @groups = split(/:/,$env{'request.course.groups'});  
 5808:                 @groups=&sort_course_groups($courseid,@groups); 
 5809: 	    } else {
 5810: 		if (! defined($usection)) {
 5811: 		    $section=&getsection($udom,$uname,$courseid);
 5812: 		} else {
 5813: 		    $section = $usection;
 5814: 		}
 5815:                 @groups = &get_users_groups($udom,$uname,$courseid);
 5816: 	    }
 5817: 
 5818: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 5819: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 5820: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 5821: 
 5822: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 5823: 	    my $courselevelr=$courseid.'.'.$symbparm;
 5824: 	    $courselevelm=$courseid.'.'.$mapparm;
 5825: 
 5826: # ----------------------------------------------------------- first, check user
 5827: 
 5828: 	    my $userreply=&resdata($uname,$udom,'user',
 5829: 				       ($courselevelr,$courselevelm,
 5830: 					$courselevel));
 5831: 	    if (defined($userreply)) { return $userreply; }
 5832: 
 5833: # ------------------------------------------------ second, check some of course
 5834:             my $coursereply;
 5835:             if (@groups > 0) {
 5836:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 5837:                                        $mapparm,$spacequalifierrest);
 5838:                 if (defined($coursereply)) { return $coursereply; }
 5839:             }
 5840: 
 5841: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5842: 				     $env{'course.'.$courseid.'.domain'},
 5843: 				     'course',
 5844: 				     ($seclevelr,$seclevelm,$seclevel,
 5845: 				      $courselevelr));
 5846: 	    if (defined($coursereply)) { return $coursereply; }
 5847: 
 5848: # ------------------------------------------------------ third, check map parms
 5849: 	    my %parmhash=();
 5850: 	    my $thisparm='';
 5851: 	    if (tie(%parmhash,'GDBM_File',
 5852: 		    $env{'request.course.fn'}.'_parms.db',
 5853: 		    &GDBM_READER(),0640)) {
 5854: 		$thisparm=$parmhash{$symbparm};
 5855: 		untie(%parmhash);
 5856: 	    }
 5857: 	    if ($thisparm) { return $thisparm; }
 5858: 	}
 5859: # ------------------------------------------ fourth, look in resource metadata
 5860: 
 5861: 	$spacequalifierrest=~s/\./\_/;
 5862: 	my $filename;
 5863: 	if (!$symbparm) { $symbparm=&symbread(); }
 5864: 	if ($symbparm) {
 5865: 	    $filename=(&decode_symb($symbparm))[2];
 5866: 	} else {
 5867: 	    $filename=$env{'request.filename'};
 5868: 	}
 5869: 	my $metadata=&metadata($filename,$spacequalifierrest);
 5870: 	if (defined($metadata)) { return $metadata; }
 5871: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 5872: 	if (defined($metadata)) { return $metadata; }
 5873: 
 5874: # ---------------------------------------------- fourth, look in rest pf course
 5875: 	if ($symbparm && defined($courseid) && 
 5876: 	    $courseid eq $env{'request.course.id'}) {
 5877: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 5878: 				     $env{'course.'.$courseid.'.domain'},
 5879: 				     'course',
 5880: 				     ($courselevelm,$courselevel));
 5881: 	    if (defined($coursereply)) { return $coursereply; }
 5882: 	}
 5883: # ------------------------------------------------------------------ Cascade up
 5884: 	unless ($space eq '0') {
 5885: 	    my @parts=split(/_/,$space);
 5886: 	    my $id=pop(@parts);
 5887: 	    my $part=join('_',@parts);
 5888: 	    if ($part eq '') { $part='0'; }
 5889: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 5890: 				 $symbparm,$udom,$uname,$section,1);
 5891: 	    if (defined($partgeneral)) { return $partgeneral; }
 5892: 	}
 5893: 	if ($recurse) { return undef; }
 5894: 	my $pack_def=&packages_tab_default($filename,$varname);
 5895: 	if (defined($pack_def)) { return $pack_def; }
 5896: 
 5897: # ---------------------------------------------------- Any other user namespace
 5898:     } elsif ($realm eq 'environment') {
 5899: # ----------------------------------------------------------------- environment
 5900: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 5901: 	    return $env{'environment.'.$spacequalifierrest};
 5902: 	} else {
 5903: 	    if ($uname eq 'anonymous' && $udom eq '') {
 5904: 		return '';
 5905: 	    }
 5906: 	    my %returnhash=&userenvironment($udom,$uname,
 5907: 					    $spacequalifierrest);
 5908: 	    return $returnhash{$spacequalifierrest};
 5909: 	}
 5910:     } elsif ($realm eq 'system') {
 5911: # ----------------------------------------------------------------- system.time
 5912: 	if ($space eq 'time') {
 5913: 	    return time;
 5914:         }
 5915:     } elsif ($realm eq 'server') {
 5916: # ----------------------------------------------------------------- system.time
 5917: 	if ($space eq 'name') {
 5918: 	    return $ENV{'SERVER_NAME'};
 5919:         }
 5920:     }
 5921:     return '';
 5922: }
 5923: 
 5924: sub check_group_parms {
 5925:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 5926:     my @groupitems = ();
 5927:     my $resultitem;
 5928:     my @levels = ($symbparm,$mapparm,$what);
 5929:     foreach my $group (@{$groups}) {
 5930:         foreach my $level (@levels) {
 5931:              my $item = $courseid.'.['.$group.'].'.$level;
 5932:              push(@groupitems,$item);
 5933:         }
 5934:     }
 5935:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 5936:                             $env{'course.'.$courseid.'.domain'},
 5937:                                      'course',@groupitems);
 5938:     return $coursereply;
 5939: }
 5940: 
 5941: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 5942:     my ($courseid,@groups) = @_;
 5943:     @groups = sort(@groups);
 5944:     return @groups;
 5945: }
 5946: 
 5947: sub packages_tab_default {
 5948:     my ($uri,$varname)=@_;
 5949:     my (undef,$part,$name)=split(/\./,$varname);
 5950: 
 5951:     my (@extension,@specifics,$do_default);
 5952:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 5953: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 5954: 	if ($pack_type eq 'default') {
 5955: 	    $do_default=1;
 5956: 	} elsif ($pack_type eq 'extension') {
 5957: 	    push(@extension,[$package,$pack_type,$pack_part]);
 5958: 	} else {
 5959: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 5960: 	}
 5961:     }
 5962:     # first look for a package that matches the requested part id
 5963:     foreach my $package (@specifics) {
 5964: 	my (undef,$pack_type,$pack_part)=@{$package};
 5965: 	next if ($pack_part ne $part);
 5966: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5967: 	    return $packagetab{"$pack_type&$name&default"};
 5968: 	}
 5969:     }
 5970:     # look for any possible matching non extension_ package
 5971:     foreach my $package (@specifics) {
 5972: 	my (undef,$pack_type,$pack_part)=@{$package};
 5973: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5974: 	    return $packagetab{"$pack_type&$name&default"};
 5975: 	}
 5976: 	if ($pack_type eq 'part') { $pack_part='0'; }
 5977: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 5978: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 5979: 	}
 5980:     }
 5981:     # look for any posible extension_ match
 5982:     foreach my $package (@extension) {
 5983: 	my ($package,$pack_type)=@{$package};
 5984: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 5985: 	    return $packagetab{"$pack_type&$name&default"};
 5986: 	}
 5987: 	if (defined($packagetab{$package."&$name&default"})) {
 5988: 	    return $packagetab{$package."&$name&default"};
 5989: 	}
 5990:     }
 5991:     # look for a global default setting
 5992:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 5993: 	return $packagetab{"default&$name&default"};
 5994:     }
 5995:     return undef;
 5996: }
 5997: 
 5998: sub add_prefix_and_part {
 5999:     my ($prefix,$part)=@_;
 6000:     my $keyroot;
 6001:     if (defined($prefix) && $prefix !~ /^__/) {
 6002: 	# prefix that has a part already
 6003: 	$keyroot=$prefix;
 6004:     } elsif (defined($prefix)) {
 6005: 	# prefix that is missing a part
 6006: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6007:     } else {
 6008: 	# no prefix at all
 6009: 	if (defined($part)) { $keyroot='_'.$part; }
 6010:     }
 6011:     return $keyroot;
 6012: }
 6013: 
 6014: # ---------------------------------------------------------------- Get metadata
 6015: 
 6016: my %metaentry;
 6017: sub metadata {
 6018:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6019:     $uri=&declutter($uri);
 6020:     # if it is a non metadata possible uri return quickly
 6021:     if (($uri eq '') || 
 6022: 	(($uri =~ m|^/*adm/|) && 
 6023: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6024:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6025: 	($uri =~ m|home/[^/]+/public_html/|)) {
 6026: 	return undef;
 6027:     }
 6028:     my $filename=$uri;
 6029:     $uri=~s/\.meta$//;
 6030: #
 6031: # Is the metadata already cached?
 6032: # Look at timestamp of caching
 6033: # Everything is cached by the main uri, libraries are never directly cached
 6034: #
 6035:     if (!defined($liburi)) {
 6036: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6037: 	if (defined($cached)) { return $result->{':'.$what}; }
 6038:     }
 6039:     {
 6040: #
 6041: # Is this a recursive call for a library?
 6042: #
 6043: #	if (! exists($metacache{$uri})) {
 6044: #	    $metacache{$uri}={};
 6045: #	}
 6046:         if ($liburi) {
 6047: 	    $liburi=&declutter($liburi);
 6048:             $filename=$liburi;
 6049:         } else {
 6050: 	    &devalidate_cache_new('meta',$uri);
 6051: 	    undef(%metaentry);
 6052: 	}
 6053:         my %metathesekeys=();
 6054:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6055: 	my $metastring;
 6056: 	if ($uri !~ m -^(editupload)/-) {
 6057: 	    my $file=&filelocation('',&clutter($filename));
 6058: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6059: 	    $metastring=&getfile($file);
 6060: 	}
 6061:         my $parser=HTML::LCParser->new(\$metastring);
 6062:         my $token;
 6063:         undef %metathesekeys;
 6064:         while ($token=$parser->get_token) {
 6065: 	    if ($token->[0] eq 'S') {
 6066: 		if (defined($token->[2]->{'package'})) {
 6067: #
 6068: # This is a package - get package info
 6069: #
 6070: 		    my $package=$token->[2]->{'package'};
 6071: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6072: 		    if (defined($token->[2]->{'id'})) { 
 6073: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6074: 		    }
 6075: 		    if ($metaentry{':packages'}) {
 6076: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6077: 		    } else {
 6078: 			$metaentry{':packages'}=$package.$keyroot;
 6079: 		    }
 6080: 		    foreach my $pack_entry (keys(%packagetab)) {
 6081: 			my $part=$keyroot;
 6082: 			$part=~s/^\_//;
 6083: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6084: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6085: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6086: 			    # ignore package.tab specified default values
 6087:                             # here &package_tab_default() will fetch those
 6088: 			    if ($subp eq 'default') { next; }
 6089: 			    my $value=$packagetab{$pack_entry};
 6090: 			    my $unikey;
 6091: 			    if ($pack =~ /_0$/) {
 6092: 				$unikey='parameter_0_'.$name;
 6093: 				$part=0;
 6094: 			    } else {
 6095: 				$unikey='parameter'.$keyroot.'_'.$name;
 6096: 			    }
 6097: 			    if ($subp eq 'display') {
 6098: 				$value.=' [Part: '.$part.']';
 6099: 			    }
 6100: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6101: 			    $metathesekeys{$unikey}=1;
 6102: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6103: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6104: 			    }
 6105: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6106: 				$metaentry{':'.$unikey}=
 6107: 				    $metaentry{':'.$unikey.'.default'};
 6108: 			    }
 6109: 			}
 6110: 		    }
 6111: 		} else {
 6112: #
 6113: # This is not a package - some other kind of start tag
 6114: #
 6115: 		    my $entry=$token->[1];
 6116: 		    my $unikey;
 6117: 		    if ($entry eq 'import') {
 6118: 			$unikey='';
 6119: 		    } else {
 6120: 			$unikey=$entry;
 6121: 		    }
 6122: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6123: 
 6124: 		    if (defined($token->[2]->{'id'})) { 
 6125: 			$unikey.='_'.$token->[2]->{'id'}; 
 6126: 		    }
 6127: 
 6128: 		    if ($entry eq 'import') {
 6129: #
 6130: # Importing a library here
 6131: #
 6132: 			if ($depthcount<20) {
 6133: 			    my $location=$parser->get_text('/import');
 6134: 			    my $dir=$filename;
 6135: 			    $dir=~s|[^/]*$||;
 6136: 			    $location=&filelocation($dir,$location);
 6137: 			    my $metadata = 
 6138: 				&metadata($uri,'keys', $location,$unikey,
 6139: 					  $depthcount+1);
 6140: 			    foreach my $meta (split(',',$metadata)) {
 6141: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6142: 				$metathesekeys{$meta}=1;
 6143: 			    }
 6144: 			}
 6145: 		    } else { 
 6146: 			
 6147: 			if (defined($token->[2]->{'name'})) { 
 6148: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6149: 			}
 6150: 			$metathesekeys{$unikey}=1;
 6151: 			foreach my $param (@{$token->[3]}) {
 6152: 			    $metaentry{':'.$unikey.'.'.$param} =
 6153: 				$token->[2]->{$param};
 6154: 			}
 6155: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6156: 			my $default=$metaentry{':'.$unikey.'.default'};
 6157: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6158: 		 # only ws inside the tag, and not in default, so use default
 6159: 		 # as value
 6160: 			    $metaentry{':'.$unikey}=$default;
 6161: 			} else {
 6162: 		  # either something interesting inside the tag or default
 6163:                   # uninteresting
 6164: 			    $metaentry{':'.$unikey}=$internaltext;
 6165: 			}
 6166: # end of not-a-package not-a-library import
 6167: 		    }
 6168: # end of not-a-package start tag
 6169: 		}
 6170: # the next is the end of "start tag"
 6171: 	    }
 6172: 	}
 6173: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6174: 	foreach my $key (keys(%packagetab)) {
 6175: 	    #no specific packages #how's our extension
 6176: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6177: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6178: 					 \%metathesekeys);
 6179: 	}
 6180: 	if (!exists($metaentry{':packages'})) {
 6181: 	    foreach my $key (keys(%packagetab)) {
 6182: 		#no specific packages well let's get default then
 6183: 		if ($key!~/^default&/) { next; }
 6184: 		&metadata_create_package_def($uri,$key,'default',
 6185: 					     \%metathesekeys);
 6186: 	    }
 6187: 	}
 6188: # are there custom rights to evaluate
 6189: 	if ($metaentry{':copyright'} eq 'custom') {
 6190: 
 6191:     #
 6192:     # Importing a rights file here
 6193:     #
 6194: 	    unless ($depthcount) {
 6195: 		my $location=$metaentry{':customdistributionfile'};
 6196: 		my $dir=$filename;
 6197: 		$dir=~s|[^/]*$||;
 6198: 		$location=&filelocation($dir,$location);
 6199: 		my $rights_metadata =
 6200: 		    &metadata($uri,'keys',$location,'_rights',
 6201: 			      $depthcount+1);
 6202: 		foreach my $rights (split(',',$rights_metadata)) {
 6203: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6204: 		    $metathesekeys{$rights}=1;
 6205: 		}
 6206: 	    }
 6207: 	}
 6208: 	# uniqifiy package listing
 6209: 	my %seen;
 6210: 	my @uniq_packages =
 6211: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6212: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6213: 
 6214: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6215: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6216: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6217: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6218: # this is the end of "was not already recently cached
 6219:     }
 6220:     return $metaentry{':'.$what};
 6221: }
 6222: 
 6223: sub metadata_create_package_def {
 6224:     my ($uri,$key,$package,$metathesekeys)=@_;
 6225:     my ($pack,$name,$subp)=split(/\&/,$key);
 6226:     if ($subp eq 'default') { next; }
 6227:     
 6228:     if (defined($metaentry{':packages'})) {
 6229: 	$metaentry{':packages'}.=','.$package;
 6230:     } else {
 6231: 	$metaentry{':packages'}=$package;
 6232:     }
 6233:     my $value=$packagetab{$key};
 6234:     my $unikey;
 6235:     $unikey='parameter_0_'.$name;
 6236:     $metaentry{':'.$unikey.'.part'}=0;
 6237:     $$metathesekeys{$unikey}=1;
 6238:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6239: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6240:     }
 6241:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6242: 	$metaentry{':'.$unikey}=
 6243: 	    $metaentry{':'.$unikey.'.default'};
 6244:     }
 6245: }
 6246: 
 6247: sub metadata_generate_part0 {
 6248:     my ($metadata,$metacache,$uri) = @_;
 6249:     my %allnames;
 6250:     foreach my $metakey (keys(%$metadata)) {
 6251: 	if ($metakey=~/^parameter\_(.*)/) {
 6252: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6253: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6254: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6255: 	    $allnames{$name}=$part;
 6256: 	  }
 6257: 	}
 6258:     }
 6259:     foreach my $name (keys(%allnames)) {
 6260:       $$metadata{"parameter_0_$name"}=1;
 6261:       my $key=":parameter_0_$name";
 6262:       $$metacache{"$key.part"}='0';
 6263:       $$metacache{"$key.name"}=$name;
 6264:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6265: 					   $allnames{$name}.'_'.$name.
 6266: 					   '.type'};
 6267:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6268: 			     '.display'};
 6269:       my $expr='[Part: '.$allnames{$name}.']';
 6270:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6271:       $$metacache{"$key.display"}=$olddis;
 6272:     }
 6273: }
 6274: 
 6275: # ------------------------------------------------------ Devalidate title cache
 6276: 
 6277: sub devalidate_title_cache {
 6278:     my ($url)=@_;
 6279:     if (!$env{'request.course.id'}) { return; }
 6280:     my $symb=&symbread($url);
 6281:     if (!$symb) { return; }
 6282:     my $key=$env{'request.course.id'}."\0".$symb;
 6283:     &devalidate_cache_new('title',$key);
 6284: }
 6285: 
 6286: # ------------------------------------------------- Get the title of a resource
 6287: 
 6288: sub gettitle {
 6289:     my $urlsymb=shift;
 6290:     my $symb=&symbread($urlsymb);
 6291:     if ($symb) {
 6292: 	my $key=$env{'request.course.id'}."\0".$symb;
 6293: 	my ($result,$cached)=&is_cached_new('title',$key);
 6294: 	if (defined($cached)) { 
 6295: 	    return $result;
 6296: 	}
 6297: 	my ($map,$resid,$url)=&decode_symb($symb);
 6298: 	my $title='';
 6299: 	my %bighash;
 6300: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6301: 		&GDBM_READER(),0640)) {
 6302: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6303: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6304: 	    untie %bighash;
 6305: 	}
 6306: 	$title=~s/\&colon\;/\:/gs;
 6307: 	if ($title) {
 6308: 	    return &do_cache_new('title',$key,$title,600);
 6309: 	}
 6310: 	$urlsymb=$url;
 6311:     }
 6312:     my $title=&metadata($urlsymb,'title');
 6313:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6314:     return $title;
 6315: }
 6316: 
 6317: sub get_slot {
 6318:     my ($which,$cnum,$cdom)=@_;
 6319:     if (!$cnum || !$cdom) {
 6320: 	(undef,my $courseid)=&whichuser();
 6321: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6322: 	$cnum=$env{'course.'.$courseid.'.num'};
 6323:     }
 6324:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6325:     my %slotinfo;
 6326:     if (exists($remembered{$key})) {
 6327: 	$slotinfo{$which} = $remembered{$key};
 6328:     } else {
 6329: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6330: 	&Apache::lonhomework::showhash(%slotinfo);
 6331: 	my ($tmp)=keys(%slotinfo);
 6332: 	if ($tmp=~/^error:/) { return (); }
 6333: 	$remembered{$key} = $slotinfo{$which};
 6334:     }
 6335:     if (ref($slotinfo{$which}) eq 'HASH') {
 6336: 	return %{$slotinfo{$which}};
 6337:     }
 6338:     return $slotinfo{$which};
 6339: }
 6340: # ------------------------------------------------- Update symbolic store links
 6341: 
 6342: sub symblist {
 6343:     my ($mapname,%newhash)=@_;
 6344:     $mapname=&deversion(&declutter($mapname));
 6345:     my %hash;
 6346:     if (($env{'request.course.fn'}) && (%newhash)) {
 6347:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6348:                       &GDBM_WRCREAT(),0640)) {
 6349: 	    foreach my $url (keys %newhash) {
 6350: 		next if ($url eq 'last_known'
 6351: 			 && $env{'form.no_update_last_known'});
 6352: 		$hash{declutter($url)}=&encode_symb($mapname,
 6353: 						    $newhash{$url}->[1],
 6354: 						    $newhash{$url}->[0]);
 6355:             }
 6356:             if (untie(%hash)) {
 6357: 		return 'ok';
 6358:             }
 6359:         }
 6360:     }
 6361:     return 'error';
 6362: }
 6363: 
 6364: # --------------------------------------------------------------- Verify a symb
 6365: 
 6366: sub symbverify {
 6367:     my ($symb,$thisurl)=@_;
 6368:     my $thisfn=$thisurl;
 6369:     $thisfn=&declutter($thisfn);
 6370: # direct jump to resource in page or to a sequence - will construct own symbs
 6371:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6372: # check URL part
 6373:     my ($map,$resid,$url)=&decode_symb($symb);
 6374: 
 6375:     unless ($url eq $thisfn) { return 0; }
 6376: 
 6377:     $symb=&symbclean($symb);
 6378:     $thisurl=&deversion($thisurl);
 6379:     $thisfn=&deversion($thisfn);
 6380: 
 6381:     my %bighash;
 6382:     my $okay=0;
 6383: 
 6384:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6385:                             &GDBM_READER(),0640)) {
 6386:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6387:         unless ($ids) { 
 6388:            $ids=$bighash{'ids_/'.$thisurl};
 6389:         }
 6390:         if ($ids) {
 6391: # ------------------------------------------------------------------- Has ID(s)
 6392: 	    foreach my $id (split(/\,/,$ids)) {
 6393: 	       my ($mapid,$resid)=split(/\./,$id);
 6394:                if (
 6395:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6396:    eq $symb) { 
 6397: 		   if (($env{'request.role.adv'}) ||
 6398: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6399: 		       $okay=1; 
 6400: 		   }
 6401: 	       }
 6402: 	   }
 6403:         }
 6404: 	untie(%bighash);
 6405:     }
 6406:     return $okay;
 6407: }
 6408: 
 6409: # --------------------------------------------------------------- Clean-up symb
 6410: 
 6411: sub symbclean {
 6412:     my $symb=shift;
 6413:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6414: # remove version from map
 6415:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6416: 
 6417: # remove version from URL
 6418:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6419: 
 6420: # remove wrapper
 6421: 
 6422:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6423:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6424:     return $symb;
 6425: }
 6426: 
 6427: # ---------------------------------------------- Split symb to find map and url
 6428: 
 6429: sub encode_symb {
 6430:     my ($map,$resid,$url)=@_;
 6431:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6432: }
 6433: 
 6434: sub decode_symb {
 6435:     my $symb=shift;
 6436:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6437:     my ($map,$resid,$url)=split(/___/,$symb);
 6438:     return (&fixversion($map),$resid,&fixversion($url));
 6439: }
 6440: 
 6441: sub fixversion {
 6442:     my $fn=shift;
 6443:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6444:     my %bighash;
 6445:     my $uri=&clutter($fn);
 6446:     my $key=$env{'request.course.id'}.'_'.$uri;
 6447: # is this cached?
 6448:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6449:     if (defined($cached)) { return $result; }
 6450: # unfortunately not cached, or expired
 6451:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6452: 	    &GDBM_READER(),0640)) {
 6453:  	if ($bighash{'version_'.$uri}) {
 6454:  	    my $version=$bighash{'version_'.$uri};
 6455:  	    unless (($version eq 'mostrecent') || 
 6456: 		    ($version==&getversion($uri))) {
 6457:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6458:  	    }
 6459:  	}
 6460:  	untie %bighash;
 6461:     }
 6462:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6463: }
 6464: 
 6465: sub deversion {
 6466:     my $url=shift;
 6467:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6468:     return $url;
 6469: }
 6470: 
 6471: # ------------------------------------------------------ Return symb list entry
 6472: 
 6473: sub symbread {
 6474:     my ($thisfn,$donotrecurse)=@_;
 6475:     my $cache_str='request.symbread.cached.'.$thisfn;
 6476:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6477: # no filename provided? try from environment
 6478:     unless ($thisfn) {
 6479:         if ($env{'request.symb'}) {
 6480: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6481: 	}
 6482: 	$thisfn=$env{'request.filename'};
 6483:     }
 6484:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6485: # is that filename actually a symb? Verify, clean, and return
 6486:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6487: 	if (&symbverify($thisfn,$1)) {
 6488: 	    return $env{$cache_str}=&symbclean($thisfn);
 6489: 	}
 6490:     }
 6491:     $thisfn=declutter($thisfn);
 6492:     my %hash;
 6493:     my %bighash;
 6494:     my $syval='';
 6495:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6496:         my $targetfn = $thisfn;
 6497:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6498:             $targetfn = 'adm/wrapper/'.$thisfn;
 6499:         }
 6500: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6501: 	    $targetfn=$1;
 6502: 	}
 6503:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6504:                       &GDBM_READER(),0640)) {
 6505: 	    $syval=$hash{$targetfn};
 6506:             untie(%hash);
 6507:         }
 6508: # ---------------------------------------------------------- There was an entry
 6509:         if ($syval) {
 6510: 	    #unless ($syval=~/\_\d+$/) {
 6511: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6512: 		    #&appenv('request.ambiguous' => $thisfn);
 6513: 		    #return $env{$cache_str}='';
 6514: 		#}    
 6515: 		#$syval.=$1;
 6516: 	    #}
 6517:         } else {
 6518: # ------------------------------------------------------- Was not in symb table
 6519:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6520:                             &GDBM_READER(),0640)) {
 6521: # ---------------------------------------------- Get ID(s) for current resource
 6522:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6523:               unless ($ids) { 
 6524:                  $ids=$bighash{'ids_/'.$thisfn};
 6525:               }
 6526:               unless ($ids) {
 6527: # alias?
 6528: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6529:               }
 6530:               if ($ids) {
 6531: # ------------------------------------------------------------------- Has ID(s)
 6532:                  my @possibilities=split(/\,/,$ids);
 6533:                  if ($#possibilities==0) {
 6534: # ----------------------------------------------- There is only one possibility
 6535: 		     my ($mapid,$resid)=split(/\./,$ids);
 6536: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6537: 						    $resid,$thisfn);
 6538:                  } elsif (!$donotrecurse) {
 6539: # ------------------------------------------ There is more than one possibility
 6540:                      my $realpossible=0;
 6541:                      foreach my $id (@possibilities) {
 6542: 			 my $file=$bighash{'src_'.$id};
 6543:                          if (&allowed('bre',$file)) {
 6544:          		    my ($mapid,$resid)=split(/\./,$id);
 6545:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6546: 				$realpossible++;
 6547:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6548: 						    $resid,$thisfn);
 6549:                             }
 6550: 			 }
 6551:                      }
 6552: 		     if ($realpossible!=1) { $syval=''; }
 6553:                  } else {
 6554:                      $syval='';
 6555:                  }
 6556: 	      }
 6557:               untie(%bighash)
 6558:            }
 6559:         }
 6560:         if ($syval) {
 6561: 	    return $env{$cache_str}=$syval;
 6562:         }
 6563:     }
 6564:     &appenv('request.ambiguous' => $thisfn);
 6565:     return $env{$cache_str}='';
 6566: }
 6567: 
 6568: # ---------------------------------------------------------- Return random seed
 6569: 
 6570: sub numval {
 6571:     my $txt=shift;
 6572:     $txt=~tr/A-J/0-9/;
 6573:     $txt=~tr/a-j/0-9/;
 6574:     $txt=~tr/K-T/0-9/;
 6575:     $txt=~tr/k-t/0-9/;
 6576:     $txt=~tr/U-Z/0-5/;
 6577:     $txt=~tr/u-z/0-5/;
 6578:     $txt=~s/\D//g;
 6579:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6580:     return int($txt);
 6581: }
 6582: 
 6583: sub numval2 {
 6584:     my $txt=shift;
 6585:     $txt=~tr/A-J/0-9/;
 6586:     $txt=~tr/a-j/0-9/;
 6587:     $txt=~tr/K-T/0-9/;
 6588:     $txt=~tr/k-t/0-9/;
 6589:     $txt=~tr/U-Z/0-5/;
 6590:     $txt=~tr/u-z/0-5/;
 6591:     $txt=~s/\D//g;
 6592:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6593:     my $total;
 6594:     foreach my $val (@txts) { $total+=$val; }
 6595:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 6596:     return int($total);
 6597: }
 6598: 
 6599: sub numval3 {
 6600:     use integer;
 6601:     my $txt=shift;
 6602:     $txt=~tr/A-J/0-9/;
 6603:     $txt=~tr/a-j/0-9/;
 6604:     $txt=~tr/K-T/0-9/;
 6605:     $txt=~tr/k-t/0-9/;
 6606:     $txt=~tr/U-Z/0-5/;
 6607:     $txt=~tr/u-z/0-5/;
 6608:     $txt=~s/\D//g;
 6609:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 6610:     my $total;
 6611:     foreach my $val (@txts) { $total+=$val; }
 6612:     if ($_64bit) { $total=(($total<<32)>>32); }
 6613:     return $total;
 6614: }
 6615: 
 6616: sub digest {
 6617:     my ($data)=@_;
 6618:     my $digest=&Digest::MD5::md5($data);
 6619:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 6620:     my ($e,$f);
 6621:     {
 6622:         use integer;
 6623:         $e=($a+$b);
 6624:         $f=($c+$d);
 6625:         if ($_64bit) {
 6626:             $e=(($e<<32)>>32);
 6627:             $f=(($f<<32)>>32);
 6628:         }
 6629:     }
 6630:     if (wantarray) {
 6631: 	return ($e,$f);
 6632:     } else {
 6633: 	my $g;
 6634: 	{
 6635: 	    use integer;
 6636: 	    $g=($e+$f);
 6637: 	    if ($_64bit) {
 6638: 		$g=(($g<<32)>>32);
 6639: 	    }
 6640: 	}
 6641: 	return $g;
 6642:     }
 6643: }
 6644: 
 6645: sub latest_rnd_algorithm_id {
 6646:     return '64bit5';
 6647: }
 6648: 
 6649: sub get_rand_alg {
 6650:     my ($courseid)=@_;
 6651:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 6652:     if ($courseid) {
 6653: 	return $env{"course.$courseid.rndseed"};
 6654:     }
 6655:     return &latest_rnd_algorithm_id();
 6656: }
 6657: 
 6658: sub validCODE {
 6659:     my ($CODE)=@_;
 6660:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 6661:     return 0;
 6662: }
 6663: 
 6664: sub getCODE {
 6665:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 6666:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 6667: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 6668: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 6669: 	return $Apache::lonhomework::history{'resource.CODE'};
 6670:     }
 6671:     return undef;
 6672: }
 6673: 
 6674: sub rndseed {
 6675:     my ($symb,$courseid,$domain,$username)=@_;
 6676: 
 6677:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 6678:     if (!$symb) {
 6679: 	unless ($symb=$wsymb) { return time; }
 6680:     }
 6681:     if (!$courseid) { $courseid=$wcourseid; }
 6682:     if (!$domain) { $domain=$wdomain; }
 6683:     if (!$username) { $username=$wusername }
 6684:     my $which=&get_rand_alg();
 6685: 
 6686:     if (defined(&getCODE())) {
 6687: 	if ($which eq '64bit5') {
 6688: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 6689: 	} elsif ($which eq '64bit4') {
 6690: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 6691: 	} else {
 6692: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 6693: 	}
 6694:     } elsif ($which eq '64bit5') {
 6695: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 6696:     } elsif ($which eq '64bit4') {
 6697: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 6698:     } elsif ($which eq '64bit3') {
 6699: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 6700:     } elsif ($which eq '64bit2') {
 6701: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 6702:     } elsif ($which eq '64bit') {
 6703: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 6704:     }
 6705:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 6706: }
 6707: 
 6708: sub rndseed_32bit {
 6709:     my ($symb,$courseid,$domain,$username)=@_;
 6710:     {
 6711: 	use integer;
 6712: 	my $symbchck=unpack("%32C*",$symb) << 27;
 6713: 	my $symbseed=numval($symb) << 22;
 6714: 	my $namechck=unpack("%32C*",$username) << 17;
 6715: 	my $nameseed=numval($username) << 12;
 6716: 	my $domainseed=unpack("%32C*",$domain) << 7;
 6717: 	my $courseseed=unpack("%32C*",$courseid);
 6718: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 6719: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6720: 	#&logthis("rndseed :$num:$symb");
 6721: 	if ($_64bit) { $num=(($num<<32)>>32); }
 6722: 	return $num;
 6723:     }
 6724: }
 6725: 
 6726: sub rndseed_64bit {
 6727:     my ($symb,$courseid,$domain,$username)=@_;
 6728:     {
 6729: 	use integer;
 6730: 	my $symbchck=unpack("%32S*",$symb) << 21;
 6731: 	my $symbseed=numval($symb) << 10;
 6732: 	my $namechck=unpack("%32S*",$username);
 6733: 	
 6734: 	my $nameseed=numval($username) << 21;
 6735: 	my $domainseed=unpack("%32S*",$domain) << 10;
 6736: 	my $courseseed=unpack("%32S*",$courseid);
 6737: 	
 6738: 	my $num1=$symbchck+$symbseed+$namechck;
 6739: 	my $num2=$nameseed+$domainseed+$courseseed;
 6740: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6741: 	#&logthis("rndseed :$num:$symb");
 6742: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6743: 	return "$num1,$num2";
 6744:     }
 6745: }
 6746: 
 6747: sub rndseed_64bit2 {
 6748:     my ($symb,$courseid,$domain,$username)=@_;
 6749:     {
 6750: 	use integer;
 6751: 	# strings need to be an even # of cahracters long, it it is odd the
 6752:         # last characters gets thrown away
 6753: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6754: 	my $symbseed=numval($symb) << 10;
 6755: 	my $namechck=unpack("%32S*",$username.' ');
 6756: 	
 6757: 	my $nameseed=numval($username) << 21;
 6758: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6759: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6760: 	
 6761: 	my $num1=$symbchck+$symbseed+$namechck;
 6762: 	my $num2=$nameseed+$domainseed+$courseseed;
 6763: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6764: 	#&logthis("rndseed :$num:$symb");
 6765: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6766: 	return "$num1,$num2";
 6767:     }
 6768: }
 6769: 
 6770: sub rndseed_64bit3 {
 6771:     my ($symb,$courseid,$domain,$username)=@_;
 6772:     {
 6773: 	use integer;
 6774: 	# strings need to be an even # of cahracters long, it it is odd the
 6775:         # last characters gets thrown away
 6776: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6777: 	my $symbseed=numval2($symb) << 10;
 6778: 	my $namechck=unpack("%32S*",$username.' ');
 6779: 	
 6780: 	my $nameseed=numval2($username) << 21;
 6781: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6782: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6783: 	
 6784: 	my $num1=$symbchck+$symbseed+$namechck;
 6785: 	my $num2=$nameseed+$domainseed+$courseseed;
 6786: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6787: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 6788: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6789: 	
 6790: 	return "$num1:$num2";
 6791:     }
 6792: }
 6793: 
 6794: sub rndseed_64bit4 {
 6795:     my ($symb,$courseid,$domain,$username)=@_;
 6796:     {
 6797: 	use integer;
 6798: 	# strings need to be an even # of cahracters long, it it is odd the
 6799:         # last characters gets thrown away
 6800: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 6801: 	my $symbseed=numval3($symb) << 10;
 6802: 	my $namechck=unpack("%32S*",$username.' ');
 6803: 	
 6804: 	my $nameseed=numval3($username) << 21;
 6805: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 6806: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6807: 	
 6808: 	my $num1=$symbchck+$symbseed+$namechck;
 6809: 	my $num2=$nameseed+$domainseed+$courseseed;
 6810: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 6811: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 6812: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 6813: 	
 6814: 	return "$num1:$num2";
 6815:     }
 6816: }
 6817: 
 6818: sub rndseed_64bit5 {
 6819:     my ($symb,$courseid,$domain,$username)=@_;
 6820:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 6821:     return "$num1:$num2";
 6822: }
 6823: 
 6824: sub rndseed_CODE_64bit {
 6825:     my ($symb,$courseid,$domain,$username)=@_;
 6826:     {
 6827: 	use integer;
 6828: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6829: 	my $symbseed=numval2($symb);
 6830: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6831: 	my $CODEseed=numval(&getCODE());
 6832: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6833: 	my $num1=$symbseed+$CODEchck;
 6834: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6835: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6836: 	#&logthis("rndseed :$num1:$num2:$symb");
 6837: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6838: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6839: 	return "$num1:$num2";
 6840:     }
 6841: }
 6842: 
 6843: sub rndseed_CODE_64bit4 {
 6844:     my ($symb,$courseid,$domain,$username)=@_;
 6845:     {
 6846: 	use integer;
 6847: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 6848: 	my $symbseed=numval3($symb);
 6849: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 6850: 	my $CODEseed=numval3(&getCODE());
 6851: 	my $courseseed=unpack("%32S*",$courseid.' ');
 6852: 	my $num1=$symbseed+$CODEchck;
 6853: 	my $num2=$CODEseed+$courseseed+$symbchck;
 6854: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 6855: 	#&logthis("rndseed :$num1:$num2:$symb");
 6856: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 6857: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 6858: 	return "$num1:$num2";
 6859:     }
 6860: }
 6861: 
 6862: sub rndseed_CODE_64bit5 {
 6863:     my ($symb,$courseid,$domain,$username)=@_;
 6864:     my $code = &getCODE();
 6865:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 6866:     return "$num1:$num2";
 6867: }
 6868: 
 6869: sub setup_random_from_rndseed {
 6870:     my ($rndseed)=@_;
 6871:     if ($rndseed =~/([,:])/) {
 6872: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 6873: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 6874:     } else {
 6875: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 6876:     }
 6877: }
 6878: 
 6879: sub latest_receipt_algorithm_id {
 6880:     return 'receipt2';
 6881: }
 6882: 
 6883: sub recunique {
 6884:     my $fucourseid=shift;
 6885:     my $unique;
 6886:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6887: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 6888:     } else {
 6889: 	$unique=$perlvar{'lonReceipt'};
 6890:     }
 6891:     return unpack("%32C*",$unique);
 6892: }
 6893: 
 6894: sub recprefix {
 6895:     my $fucourseid=shift;
 6896:     my $prefix;
 6897:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 6898: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 6899:     } else {
 6900: 	$prefix=$perlvar{'lonHostID'};
 6901:     }
 6902:     return unpack("%32C*",$prefix);
 6903: }
 6904: 
 6905: sub ireceipt {
 6906:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 6907:     my $cuname=unpack("%32C*",$funame);
 6908:     my $cudom=unpack("%32C*",$fudom);
 6909:     my $cucourseid=unpack("%32C*",$fucourseid);
 6910:     my $cusymb=unpack("%32C*",$fusymb);
 6911:     my $cunique=&recunique($fucourseid);
 6912:     my $cpart=unpack("%32S*",$part);
 6913:     my $return =&recprefix($fucourseid).'-';
 6914:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 6915: 	$env{'request.state'} eq 'construct') {
 6916: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 6917: 			       
 6918: 	$return.= ($cunique%$cuname+
 6919: 		   $cunique%$cudom+
 6920: 		   $cusymb%$cuname+
 6921: 		   $cusymb%$cudom+
 6922: 		   $cucourseid%$cuname+
 6923: 		   $cucourseid%$cudom+
 6924: 		   $cpart%$cuname+
 6925: 		   $cpart%$cudom);
 6926:     } else {
 6927: 	$return.= ($cunique%$cuname+
 6928: 		   $cunique%$cudom+
 6929: 		   $cusymb%$cuname+
 6930: 		   $cusymb%$cudom+
 6931: 		   $cucourseid%$cuname+
 6932: 		   $cucourseid%$cudom);
 6933:     }
 6934:     return $return;
 6935: }
 6936: 
 6937: sub receipt {
 6938:     my ($part)=@_;
 6939:     my ($symb,$courseid,$domain,$name) = &whichuser();
 6940:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 6941: }
 6942: 
 6943: sub whichuser {
 6944:     my ($passedsymb)=@_;
 6945:     my ($symb,$courseid,$domain,$name,$publicuser);
 6946:     if (defined($env{'form.grade_symb'})) {
 6947: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 6948: 	my $allowed=&allowed('vgr',$tmp_courseid);
 6949: 	if (!$allowed &&
 6950: 	    exists($env{'request.course.sec'}) &&
 6951: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 6952: 	    $allowed=&allowed('vgr',$tmp_courseid.
 6953: 			      '/'.$env{'request.course.sec'});
 6954: 	}
 6955: 	if ($allowed) {
 6956: 	    ($symb)=&get_env_multiple('form.grade_symb');
 6957: 	    $courseid=$tmp_courseid;
 6958: 	    ($domain)=&get_env_multiple('form.grade_domain');
 6959: 	    ($name)=&get_env_multiple('form.grade_username');
 6960: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 6961: 	}
 6962:     }
 6963:     if (!$passedsymb) {
 6964: 	$symb=&symbread();
 6965:     } else {
 6966: 	$symb=$passedsymb;
 6967:     }
 6968:     $courseid=$env{'request.course.id'};
 6969:     $domain=$env{'user.domain'};
 6970:     $name=$env{'user.name'};
 6971:     if ($name eq 'public' && $domain eq 'public') {
 6972: 	if (!defined($env{'form.username'})) {
 6973: 	    $env{'form.username'}.=time.rand(10000000);
 6974: 	}
 6975: 	$name.=$env{'form.username'};
 6976:     }
 6977:     return ($symb,$courseid,$domain,$name,$publicuser);
 6978: 
 6979: }
 6980: 
 6981: # ------------------------------------------------------------ Serves up a file
 6982: # returns either the contents of the file or 
 6983: # -1 if the file doesn't exist
 6984: #
 6985: # if the target is a file that was uploaded via DOCS, 
 6986: # a check will be made to see if a current copy exists on the local server,
 6987: # if it does this will be served, otherwise a copy will be retrieved from
 6988: # the home server for the course and stored in /home/httpd/html/userfiles on
 6989: # the local server.   
 6990: 
 6991: sub getfile {
 6992:     my ($file) = @_;
 6993:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 6994:     &repcopy($file);
 6995:     return &readfile($file);
 6996: }
 6997: 
 6998: sub repcopy_userfile {
 6999:     my ($file)=@_;
 7000:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7001:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7002:     my ($cdom,$cnum,$filename) = 
 7003: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 7004:     my ($info,$rtncode);
 7005:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7006:     if (-e "$file") {
 7007: 	my @fileinfo = stat($file);
 7008: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7009: 	if ($lwpresp ne 'ok') {
 7010: 	    if ($rtncode eq '404') {
 7011: 		unlink($file);
 7012: 	    }
 7013: 	    #my $ua=new LWP::UserAgent;
 7014: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 7015: 	    #my $response=$ua->request($request);
 7016: 	    #if ($response->is_success()) {
 7017: 	#	return $response->content;
 7018: 	#    } else {
 7019: 	#	return -1;
 7020: 	#    }
 7021: 	    return -1;
 7022: 	}
 7023: 	if ($info < $fileinfo[9]) {
 7024: 	    return 'ok';
 7025: 	}
 7026: 	$info = '';
 7027: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 7028: 	if ($lwpresp ne 'ok') {
 7029: 	    return -1;
 7030: 	}
 7031:     } else {
 7032: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 7033: 	if ($lwpresp ne 'ok') {
 7034: 	    my $ua=new LWP::UserAgent;
 7035: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 7036: 	    my $response=$ua->request($request);
 7037: 	    if ($response->is_success()) {
 7038: 		$info=$response->content;
 7039: 	    } else {
 7040: 		return -1;
 7041: 	    }
 7042: 	}
 7043: 	my @parts = ($cdom,$cnum); 
 7044: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 7045: 	    push @parts, split(/\//,$1);
 7046: 	}
 7047: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7048: 	foreach my $part (@parts) {
 7049: 	    $path .= '/'.$part;
 7050: 	    if (!-e $path) {
 7051: 		mkdir($path,0770);
 7052: 	    }
 7053: 	}
 7054:     }
 7055:     open(FILE,">$file");
 7056:     print FILE $info;
 7057:     close(FILE);
 7058:     return 'ok';
 7059: }
 7060: 
 7061: sub tokenwrapper {
 7062:     my $uri=shift;
 7063:     $uri=~s|^http\://([^/]+)||;
 7064:     $uri=~s|^/||;
 7065:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7066:     my $token=$1;
 7067:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7068:     if ($udom && $uname && $file) {
 7069: 	$file=~s|(\?\.*)*$||;
 7070:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7071:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 7072:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7073:                                '&tokenissued='.$perlvar{'lonHostID'};
 7074:     } else {
 7075:         return '/adm/notfound.html';
 7076:     }
 7077: }
 7078: 
 7079: sub getuploaded {
 7080:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7081:     $uri=~s/^\///;
 7082:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 7083:     my $ua=new LWP::UserAgent;
 7084:     my $request=new HTTP::Request($reqtype,$uri);
 7085:     my $response=$ua->request($request);
 7086:     $$rtncode = $response->code;
 7087:     if (! $response->is_success()) {
 7088: 	return 'failed';
 7089:     }      
 7090:     if ($reqtype eq 'HEAD') {
 7091: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7092:     } elsif ($reqtype eq 'GET') {
 7093: 	$$info = $response->content;
 7094:     }
 7095:     return 'ok';
 7096: }
 7097: 
 7098: sub readfile {
 7099:     my $file = shift;
 7100:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7101:     my $fh;
 7102:     open($fh,"<$file");
 7103:     my $a='';
 7104:     while (my $line = <$fh>) { $a .= $line; }
 7105:     return $a;
 7106: }
 7107: 
 7108: sub filelocation {
 7109:     my ($dir,$file) = @_;
 7110:     my $location;
 7111:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7112: 
 7113:     if ($file =~ m-^/adm/-) {
 7114: 	$file=~s-^/adm/wrapper/-/-;
 7115: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7116:     }
 7117:     if ($file=~m:^/~:) { # is a contruction space reference
 7118:         $location = $file;
 7119:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7120:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 7121: 	# is a correct contruction space reference
 7122:         $location = $file;
 7123:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7124:         my ($udom,$uname,$filename)=
 7125:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 7126:         my $home=&homeserver($uname,$udom);
 7127:         my $is_me=0;
 7128:         my @ids=&current_machine_ids();
 7129:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7130:         if ($is_me) {
 7131:   	    $location=&propath($udom,$uname).
 7132:   	      '/userfiles/'.$filename;
 7133:         } else {
 7134:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7135:   	      $udom.'/'.$uname.'/'.$filename;
 7136:         }
 7137:     } else {
 7138:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7139:         $file=~s:^/res/:/:;
 7140:         if ( !( $file =~ m:^/:) ) {
 7141:             $location = $dir. '/'.$file;
 7142:         } else {
 7143:             $location = '/home/httpd/html/res'.$file;
 7144:         }
 7145:     }
 7146:     $location=~s://+:/:g; # remove duplicate /
 7147:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7148:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7149:     return $location;
 7150: }
 7151: 
 7152: sub hreflocation {
 7153:     my ($dir,$file)=@_;
 7154:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7155: 	$file=filelocation($dir,$file);
 7156:     } elsif ($file=~m-^/adm/-) {
 7157: 	$file=~s-^/adm/wrapper/-/-;
 7158: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7159:     }
 7160:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7161: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7162:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 7163: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 7164:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7165: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 7166: 	    -/uploaded/$1/$2/-x;
 7167:     }
 7168:     return $file;
 7169: }
 7170: 
 7171: sub current_machine_domains {
 7172:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7173:     my @domains;
 7174:     while( my($id, $name) = each(%hostname)) {
 7175: #	&logthis("-$id-$name-$hostname-");
 7176: 	if ($hostname eq $name) {
 7177: 	    push(@domains,$hostdom{$id});
 7178: 	}
 7179:     }
 7180:     return @domains;
 7181: }
 7182: 
 7183: sub current_machine_ids {
 7184:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 7185:     my @ids;
 7186:     while( my($id, $name) = each(%hostname)) {
 7187: #	&logthis("-$id-$name-$hostname-");
 7188: 	if ($hostname eq $name) {
 7189: 	    push(@ids,$id);
 7190: 	}
 7191:     }
 7192:     return @ids;
 7193: }
 7194: 
 7195: # ------------------------------------------------------------- Declutters URLs
 7196: 
 7197: sub declutter {
 7198:     my $thisfn=shift;
 7199:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7200:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7201:     $thisfn=~s/^\///;
 7202:     $thisfn=~s|^adm/wrapper/||;
 7203:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7204:     $thisfn=~s/^res\///;
 7205:     $thisfn=~s/\?.+$//;
 7206:     return $thisfn;
 7207: }
 7208: 
 7209: # ------------------------------------------------------------- Clutter up URLs
 7210: 
 7211: sub clutter {
 7212:     my $thisfn='/'.&declutter(shift);
 7213:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 7214:        $thisfn='/res'.$thisfn; 
 7215:     }
 7216:     if ($thisfn !~m|/adm|) {
 7217: 	if ($thisfn =~ m|/ext/|) {
 7218: 	    $thisfn='/adm/wrapper'.$thisfn;
 7219: 	} else {
 7220: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7221: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7222: 	    if ($embstyle eq 'ssi'
 7223: 		|| ($embstyle eq 'hdn')
 7224: 		|| ($embstyle eq 'rat')
 7225: 		|| ($embstyle eq 'prv')
 7226: 		|| ($embstyle eq 'ign')) {
 7227: 		#do nothing with these
 7228: 	    } elsif (($embstyle eq 'img') 
 7229: 		|| ($embstyle eq 'emb')
 7230: 		|| ($embstyle eq 'wrp')) {
 7231: 		$thisfn='/adm/wrapper'.$thisfn;
 7232: 	    } elsif ($embstyle eq 'unk'
 7233: 		     && $thisfn!~/\.(sequence|page)$/) {
 7234: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7235: 	    } else {
 7236: #		&logthis("Got a blank emb style");
 7237: 	    }
 7238: 	}
 7239:     }
 7240:     return $thisfn;
 7241: }
 7242: 
 7243: sub clutter_with_no_wrapper {
 7244:     my $uri = &clutter(shift);
 7245:     if ($uri =~ m-^/adm/-) {
 7246: 	$uri =~ s-^/adm/wrapper/-/-;
 7247: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7248:     }
 7249:     return $uri;
 7250: }
 7251: 
 7252: sub freeze_escape {
 7253:     my ($value)=@_;
 7254:     if (ref($value)) {
 7255: 	$value=&nfreeze($value);
 7256: 	return '__FROZEN__'.&escape($value);
 7257:     }
 7258:     return &escape($value);
 7259: }
 7260: 
 7261: 
 7262: sub thaw_unescape {
 7263:     my ($value)=@_;
 7264:     if ($value =~ /^__FROZEN__/) {
 7265: 	substr($value,0,10,undef);
 7266: 	$value=&unescape($value);
 7267: 	return &thaw($value);
 7268:     }
 7269:     return &unescape($value);
 7270: }
 7271: 
 7272: sub correct_line_ends {
 7273:     my ($result)=@_;
 7274:     $$result =~s/\r\n/\n/mg;
 7275:     $$result =~s/\r/\n/mg;
 7276: }
 7277: # ================================================================ Main Program
 7278: 
 7279: sub goodbye {
 7280:    &logthis("Starting Shut down");
 7281: #not converted to using infrastruture and probably shouldn't be
 7282:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 7283: #converted
 7284: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7285:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 7286: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 7287: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 7288: #1.1 only
 7289: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 7290: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 7291: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 7292: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 7293:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 7294:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7295:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7296:    &flushcourselogs();
 7297:    &logthis("Shutting down");
 7298: }
 7299: 
 7300: BEGIN {
 7301: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 7302:     unless ($readit) {
 7303: {
 7304:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 7305:     %perlvar = (%perlvar,%{$configvars});
 7306: }
 7307: 
 7308: # ------------------------------------------------------------ Read domain file
 7309: {
 7310:     %domaindescription = ();
 7311:     %domain_auth_def = ();
 7312:     %domain_auth_arg_def = ();
 7313:     my $fh;
 7314:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 7315: 	while (my $line = <$fh>) {
 7316:            next if ($line =~ /^(\#|\s*$)/);
 7317: #           next if /^\#/;
 7318:            chomp $line;
 7319:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 7320: 	       $def_lang, $city, $longi, $lati, $primary) = split(/:/,$line,9);
 7321: 	   $domain_auth_def{$domain}=$def_auth;
 7322:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 7323: 	   $domaindescription{$domain}=$domain_description;
 7324: 	   $domain_lang_def{$domain}=$def_lang;
 7325: 	   $domain_city{$domain}=$city;
 7326: 	   $domain_longi{$domain}=$longi;
 7327: 	   $domain_lati{$domain}=$lati;
 7328:            $domain_primary{$domain}=$primary;
 7329: 
 7330:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 7331: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 7332: 	}
 7333:     }
 7334:     close ($fh);
 7335: }
 7336: 
 7337: 
 7338: # ------------------------------------------------------------- Read hosts file
 7339: {
 7340:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7341: 
 7342:     while (my $configline=<$config>) {
 7343:        next if ($configline =~ /^(\#|\s*$)/);
 7344:        chomp($configline);
 7345:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 7346:        $name=~s/\s//g;
 7347:        if ($id && $domain && $role && $name) {
 7348: 	 $hostname{$id}=$name;
 7349: 	 $hostdom{$id}=$domain;
 7350: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 7351:        }
 7352:     }
 7353:     close($config);
 7354:     # FIXME: dev server don't want this, production servers _do_ want this
 7355:     #&get_iphost();
 7356: }
 7357: 
 7358: sub get_iphost {
 7359:     if (%iphost) { return %iphost; }
 7360:     my %name_to_ip;
 7361:     foreach my $id (keys(%hostname)) {
 7362: 	my $name=$hostname{$id};
 7363: 	my $ip;
 7364: 	if (!exists($name_to_ip{$name})) {
 7365: 	    $ip = gethostbyname($name);
 7366: 	    if (!$ip || length($ip) ne 4) {
 7367: 		&logthis("Skipping host $id name $name no IP found\n");
 7368: 		next;
 7369: 	    }
 7370: 	    $ip=inet_ntoa($ip);
 7371: 	    $name_to_ip{$name} = $ip;
 7372: 	} else {
 7373: 	    $ip = $name_to_ip{$name};
 7374: 	}
 7375: 	push(@{$iphost{$ip}},$id);
 7376:     }
 7377:     return %iphost;
 7378: }
 7379: 
 7380: # ------------------------------------------------------ Read spare server file
 7381: {
 7382:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 7383: 
 7384:     while (my $configline=<$config>) {
 7385:        chomp($configline);
 7386:        if ($configline) {
 7387: 	   my ($host,$type) = split(':',$configline,2);
 7388: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 7389: 	   push(@{ $spareid{$type} }, $host);
 7390:        }
 7391:     }
 7392:     close($config);
 7393: }
 7394: # ------------------------------------------------------------ Read permissions
 7395: {
 7396:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 7397: 
 7398:     while (my $configline=<$config>) {
 7399: 	chomp($configline);
 7400: 	if ($configline) {
 7401: 	    my ($role,$perm)=split(/ /,$configline);
 7402: 	    if ($perm ne '') { $pr{$role}=$perm; }
 7403: 	}
 7404:     }
 7405:     close($config);
 7406: }
 7407: 
 7408: # -------------------------------------------- Read plain texts for permissions
 7409: {
 7410:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 7411: 
 7412:     while (my $configline=<$config>) {
 7413: 	chomp($configline);
 7414: 	if ($configline) {
 7415: 	    my ($short,@plain)=split(/:/,$configline);
 7416:             %{$prp{$short}} = ();
 7417: 	    if (@plain > 0) {
 7418:                 $prp{$short}{'std'} = $plain[0];
 7419:                 for (my $i=1; $i<@plain; $i++) {
 7420:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 7421:                 }
 7422:             }
 7423: 	}
 7424:     }
 7425:     close($config);
 7426: }
 7427: 
 7428: # ---------------------------------------------------------- Read package table
 7429: {
 7430:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 7431: 
 7432:     while (my $configline=<$config>) {
 7433: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 7434: 	chomp($configline);
 7435: 	my ($short,$plain)=split(/:/,$configline);
 7436: 	my ($pack,$name)=split(/\&/,$short);
 7437: 	if ($plain ne '') {
 7438: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 7439: 	    $packagetab{$short}=$plain; 
 7440: 	}
 7441:     }
 7442:     close($config);
 7443: }
 7444: 
 7445: # ------------- set up temporary directory
 7446: {
 7447:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 7448: 
 7449: }
 7450: 
 7451: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 7452: 				'compress_threshold'=> 20_000,
 7453:  			        });
 7454: 
 7455: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 7456: $dumpcount=0;
 7457: 
 7458: &logtouch();
 7459: &logthis('<font color="yellow">INFO: Read configuration</font>');
 7460: $readit=1;
 7461:     {
 7462: 	use integer;
 7463: 	my $test=(2**32)+1;
 7464: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 7465: 	&logthis(" Detected 64bit platform ($_64bit)");
 7466:     }
 7467: }
 7468: }
 7469: 
 7470: 1;
 7471: __END__
 7472: 
 7473: =pod
 7474: 
 7475: =head1 NAME
 7476: 
 7477: Apache::lonnet - Subroutines to ask questions about things in the network.
 7478: 
 7479: =head1 SYNOPSIS
 7480: 
 7481: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 7482: 
 7483:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 7484: 
 7485: Common parameters:
 7486: 
 7487: =over 4
 7488: 
 7489: =item *
 7490: 
 7491: $uname : an internal username (if $cname expecting a course Id specifically)
 7492: 
 7493: =item *
 7494: 
 7495: $udom : a domain (if $cdom expecting a course's domain specifically)
 7496: 
 7497: =item *
 7498: 
 7499: $symb : a resource instance identifier
 7500: 
 7501: =item *
 7502: 
 7503: $namespace : the name of a .db file that contains the data needed or
 7504: being set.
 7505: 
 7506: =back
 7507: 
 7508: =head1 OVERVIEW
 7509: 
 7510: lonnet provides subroutines which interact with the
 7511: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 7512: about classes, users, and resources.
 7513: 
 7514: For many of these objects you can also use this to store data about
 7515: them or modify them in various ways.
 7516: 
 7517: =head2 Symbs
 7518: 
 7519: To identify a specific instance of a resource, LON-CAPA uses symbols
 7520: or "symbs"X<symb>. These identifiers are built from the URL of the
 7521: map, the resource number of the resource in the map, and the URL of
 7522: the resource itself. The latter is somewhat redundant, but might help
 7523: if maps change.
 7524: 
 7525: An example is
 7526: 
 7527:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 7528: 
 7529: The respective map entry is
 7530: 
 7531:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 7532:   title="Problem 2">
 7533:  </resource>
 7534: 
 7535: Symbs are used by the random number generator, as well as to store and
 7536: restore data specific to a certain instance of for example a problem.
 7537: 
 7538: =head2 Storing And Retrieving Data
 7539: 
 7540: X<store()>X<cstore()>X<restore()>Three of the most important functions
 7541: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 7542: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 7543: is is the non-critical message twin of cstore. These functions are for
 7544: handlers to store a perl hash to a user's permanent data space in an
 7545: easy manner, and to retrieve it again on another call. It is expected
 7546: that a handler would use this once at the beginning to retrieve data,
 7547: and then again once at the end to send only the new data back.
 7548: 
 7549: The data is stored in the user's data directory on the user's
 7550: homeserver under the ID of the course.
 7551: 
 7552: The hash that is returned by restore will have all of the previous
 7553: value for all of the elements of the hash.
 7554: 
 7555: Example:
 7556: 
 7557:  #creating a hash
 7558:  my %hash;
 7559:  $hash{'foo'}='bar';
 7560: 
 7561:  #storing it
 7562:  &Apache::lonnet::cstore(\%hash);
 7563: 
 7564:  #changing a value
 7565:  $hash{'foo'}='notbar';
 7566: 
 7567:  #adding a new value
 7568:  $hash{'bar'}='foo';
 7569:  &Apache::lonnet::cstore(\%hash);
 7570: 
 7571:  #retrieving the hash
 7572:  my %history=&Apache::lonnet::restore();
 7573: 
 7574:  #print the hash
 7575:  foreach my $key (sort(keys(%history))) {
 7576:    print("\%history{$key} = $history{$key}");
 7577:  }
 7578: 
 7579: Will print out:
 7580: 
 7581:  %history{1:foo} = bar
 7582:  %history{1:keys} = foo:timestamp
 7583:  %history{1:timestamp} = 990455579
 7584:  %history{2:bar} = foo
 7585:  %history{2:foo} = notbar
 7586:  %history{2:keys} = foo:bar:timestamp
 7587:  %history{2:timestamp} = 990455580
 7588:  %history{bar} = foo
 7589:  %history{foo} = notbar
 7590:  %history{timestamp} = 990455580
 7591:  %history{version} = 2
 7592: 
 7593: Note that the special hash entries C<keys>, C<version> and
 7594: C<timestamp> were added to the hash. C<version> will be equal to the
 7595: total number of versions of the data that have been stored. The
 7596: C<timestamp> attribute will be the UNIX time the hash was
 7597: stored. C<keys> is available in every historical section to list which
 7598: keys were added or changed at a specific historical revision of a
 7599: hash.
 7600: 
 7601: B<Warning>: do not store the hash that restore returns directly. This
 7602: will cause a mess since it will restore the historical keys as if the
 7603: were new keys. I.E. 1:foo will become 1:1:foo etc.
 7604: 
 7605: Calling convention:
 7606: 
 7607:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 7608:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 7609: 
 7610: For more detailed information, see lonnet specific documentation.
 7611: 
 7612: =head1 RETURN MESSAGES
 7613: 
 7614: =over 4
 7615: 
 7616: =item * B<con_lost>: unable to contact remote host
 7617: 
 7618: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 7619: when the connection is brought back up
 7620: 
 7621: =item * B<con_failed>: unable to contact remote host and unable to save message
 7622: for later delivery
 7623: 
 7624: =item * B<error:>: an error a occured, a description of the error follows the :
 7625: 
 7626: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 7627: that was requested
 7628: 
 7629: =back
 7630: 
 7631: =head1 PUBLIC SUBROUTINES
 7632: 
 7633: =head2 Session Environment Functions
 7634: 
 7635: =over 4
 7636: 
 7637: =item * 
 7638: X<appenv()>
 7639: B<appenv(%hash)>: the value of %hash is written to
 7640: the user envirnoment file, and will be restored for each access this
 7641: user makes during this session, also modifies the %env for the current
 7642: process
 7643: 
 7644: =item *
 7645: X<delenv()>
 7646: B<delenv($regexp)>: removes all items from the session
 7647: environment file that matches the regular expression in $regexp. The
 7648: values are also delted from the current processes %env.
 7649: 
 7650: =item * get_env_multiple($name) 
 7651: 
 7652: gets $name from the %env hash, it seemlessly handles the cases where multiple
 7653: values may be defined and end up as an array ref.
 7654: 
 7655: returns an array of values
 7656: 
 7657: =back
 7658: 
 7659: =head2 User Information
 7660: 
 7661: =over 4
 7662: 
 7663: =item *
 7664: X<queryauthenticate()>
 7665: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 7666: authentication scheme
 7667: 
 7668: =item *
 7669: X<authenticate()>
 7670: B<authenticate($uname,$upass,$udom)>: try to
 7671: authenticate user from domain's lib servers (first use the current
 7672: one). C<$upass> should be the users password.
 7673: 
 7674: =item *
 7675: X<homeserver()>
 7676: B<homeserver($uname,$udom)>: find the server which has
 7677: the user's directory and files (there must be only one), this caches
 7678: the answer, and also caches if there is a borken connection.
 7679: 
 7680: =item *
 7681: X<idget()>
 7682: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 7683: (IDs are a unique resource in a domain, there must be only 1 ID per
 7684: username, and only 1 username per ID in a specific domain) (returns
 7685: hash: id=>name,id=>name)
 7686: 
 7687: =item *
 7688: X<idrget()>
 7689: B<idrget($udom,@unames)>: find the IDs behind a list of
 7690: usernames (returns hash: name=>id,name=>id)
 7691: 
 7692: =item *
 7693: X<idput()>
 7694: B<idput($udom,%ids)>: store away a list of names and associated IDs
 7695: 
 7696: =item *
 7697: X<rolesinit()>
 7698: B<rolesinit($udom,$username,$authhost)>: get user privileges
 7699: 
 7700: =item *
 7701: X<getsection()>
 7702: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 7703: course $cname, return section name/number or '' for "not in course"
 7704: and '-1' for "no section"
 7705: 
 7706: =item *
 7707: X<userenvironment()>
 7708: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 7709: passed in @what from the requested user's environment, returns a hash
 7710: 
 7711: =back
 7712: 
 7713: =head2 User Roles
 7714: 
 7715: =over 4
 7716: 
 7717: =item *
 7718: 
 7719: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 7720: actions
 7721:  F: full access
 7722:  U,I,K: authentication modes (cxx only)
 7723:  '': forbidden
 7724:  1: user needs to choose course
 7725:  2: browse allowed
 7726:  A: passphrase authentication needed
 7727: 
 7728: =item *
 7729: 
 7730: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 7731: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 7732: and course level
 7733: 
 7734: =item *
 7735: 
 7736: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 7737: explanation of a user role term
 7738: 
 7739: =back
 7740: 
 7741: =head2 User Modification
 7742: 
 7743: =over 4
 7744: 
 7745: =item *
 7746: 
 7747: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 7748: user for the level given by URL.  Optional start and end dates (leave empty
 7749: string or zero for "no date")
 7750: 
 7751: =item *
 7752: 
 7753: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 7754: change a users, password, possible return values are: ok,
 7755: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 7756: refused
 7757: 
 7758: =item *
 7759: 
 7760: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 7761: 
 7762: =item *
 7763: 
 7764: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 7765: modify user
 7766: 
 7767: =item *
 7768: 
 7769: modifystudent
 7770: 
 7771: modify a students enrollment and identification information.
 7772: The course id is resolved based on the current users environment.  
 7773: This means the envoking user must be a course coordinator or otherwise
 7774: associated with a course.
 7775: 
 7776: This call is essentially a wrapper for lonnet::modifyuser and
 7777: lonnet::modify_student_enrollment
 7778: 
 7779: Inputs: 
 7780: 
 7781: =over 4
 7782: 
 7783: =item B<$udom> Students loncapa domain
 7784: 
 7785: =item B<$uname> Students loncapa login name
 7786: 
 7787: =item B<$uid> Students id/student number
 7788: 
 7789: =item B<$umode> Students authentication mode
 7790: 
 7791: =item B<$upass> Students password
 7792: 
 7793: =item B<$first> Students first name
 7794: 
 7795: =item B<$middle> Students middle name
 7796: 
 7797: =item B<$last> Students last name
 7798: 
 7799: =item B<$gene> Students generation
 7800: 
 7801: =item B<$usec> Students section in course
 7802: 
 7803: =item B<$end> Unix time of the roles expiration
 7804: 
 7805: =item B<$start> Unix time of the roles start date
 7806: 
 7807: =item B<$forceid> If defined, allow $uid to be changed
 7808: 
 7809: =item B<$desiredhome> server to use as home server for student
 7810: 
 7811: =back
 7812: 
 7813: =item *
 7814: 
 7815: modify_student_enrollment
 7816: 
 7817: Change a students enrollment status in a class.  The environment variable
 7818: 'role.request.course' must be defined for this function to proceed.
 7819: 
 7820: Inputs:
 7821: 
 7822: =over 4
 7823: 
 7824: =item $udom, students domain
 7825: 
 7826: =item $uname, students name
 7827: 
 7828: =item $uid, students user id
 7829: 
 7830: =item $first, students first name
 7831: 
 7832: =item $middle
 7833: 
 7834: =item $last
 7835: 
 7836: =item $gene
 7837: 
 7838: =item $usec
 7839: 
 7840: =item $end
 7841: 
 7842: =item $start
 7843: 
 7844: =back
 7845: 
 7846: 
 7847: =item *
 7848: 
 7849: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 7850: custom role; give a custom role to a user for the level given by URL.  Specify
 7851: name and domain of role author, and role name
 7852: 
 7853: =item *
 7854: 
 7855: revokerole($udom,$uname,$url,$role) : revoke a role for url
 7856: 
 7857: =item *
 7858: 
 7859: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 7860: 
 7861: =back
 7862: 
 7863: =head2 Course Infomation
 7864: 
 7865: =over 4
 7866: 
 7867: =item *
 7868: 
 7869: coursedescription($courseid) : returns a hash of information about the
 7870: specified course id, including all environment settings for the
 7871: course, the description of the course will be in the hash under the
 7872: key 'description'
 7873: 
 7874: =item *
 7875: 
 7876: resdata($name,$domain,$type,@which) : request for current parameter
 7877: setting for a specific $type, where $type is either 'course' or 'user',
 7878: @what should be a list of parameters to ask about. This routine caches
 7879: answers for 5 minutes.
 7880: 
 7881: =back
 7882: 
 7883: =head2 Course Modification
 7884: 
 7885: =over 4
 7886: 
 7887: =item *
 7888: 
 7889: writecoursepref($courseid,%prefs) : write preferences (environment
 7890: database) for a course
 7891: 
 7892: =item *
 7893: 
 7894: createcourse($udom,$description,$url) : make/modify course
 7895: 
 7896: =back
 7897: 
 7898: =head2 Resource Subroutines
 7899: 
 7900: =over 4
 7901: 
 7902: =item *
 7903: 
 7904: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 7905: 
 7906: =item *
 7907: 
 7908: repcopy($filename) : subscribes to the requested file, and attempts to
 7909: replicate from the owning library server, Might return
 7910: 'unavailable', 'not_found', 'forbidden', 'ok', or
 7911: 'bad_request', also attempts to grab the metadata for the
 7912: resource. Expects the local filesystem pathname
 7913: (/home/httpd/html/res/....)
 7914: 
 7915: =back
 7916: 
 7917: =head2 Resource Information
 7918: 
 7919: =over 4
 7920: 
 7921: =item *
 7922: 
 7923: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 7924: a vairety of different possible values, $varname should be a request
 7925: string, and the other parameters can be used to specify who and what
 7926: one is asking about.
 7927: 
 7928: Possible values for $varname are environment.lastname (or other item
 7929: from the envirnment hash), user.name (or someother aspect about the
 7930: user), resource.0.maxtries (or some other part and parameter of a
 7931: resource)
 7932: 
 7933: =item *
 7934: 
 7935: directcondval($number) : get current value of a condition; reads from a state
 7936: string
 7937: 
 7938: =item *
 7939: 
 7940: condval($condidx) : value of condition index based on state
 7941: 
 7942: =item *
 7943: 
 7944: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 7945: resource's metadata, $what should be either a specific key, or either
 7946: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 7947: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 7948: 
 7949: this function automatically caches all requests
 7950: 
 7951: =item *
 7952: 
 7953: metadata_query($query,$custom,$customshow) : make a metadata query against the
 7954: network of library servers; returns file handle of where SQL and regex results
 7955: will be stored for query
 7956: 
 7957: =item *
 7958: 
 7959: symbread($filename) : return symbolic list entry (filename argument optional);
 7960: returns the data handle
 7961: 
 7962: =item *
 7963: 
 7964: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 7965: a possible symb for the URL in $thisfn, and if is an encryypted
 7966: resource that the user accessed using /enc/ returns a 1 on success, 0
 7967: on failure, user must be in a course, as it assumes the existance of
 7968: the course initial hash, and uses $env('request.course.id'}
 7969: 
 7970: 
 7971: =item *
 7972: 
 7973: symbclean($symb) : removes versions numbers from a symb, returns the
 7974: cleaned symb
 7975: 
 7976: =item *
 7977: 
 7978: is_on_map($uri) : checks if the $uri is somewhere on the current
 7979: course map, user must be in a course for it to work.
 7980: 
 7981: =item *
 7982: 
 7983: numval($salt) : return random seed value (addend for rndseed)
 7984: 
 7985: =item *
 7986: 
 7987: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 7988: a random seed, all arguments are optional, if they aren't sent it uses the
 7989: environment to derive them. Note: if symb isn't sent and it can't get one
 7990: from &symbread it will use the current time as its return value
 7991: 
 7992: =item *
 7993: 
 7994: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 7995: unfakeable, receipt
 7996: 
 7997: =item *
 7998: 
 7999: receipt() : API to ireceipt working off of env values; given out to users
 8000: 
 8001: =item *
 8002: 
 8003: countacc($url) : count the number of accesses to a given URL
 8004: 
 8005: =item *
 8006: 
 8007: 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
 8008: 
 8009: =item *
 8010: 
 8011: 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)
 8012: 
 8013: =item *
 8014: 
 8015: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8016: 
 8017: =item *
 8018: 
 8019: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8020: forcing spreadsheet to reevaluate the resource scores next time.
 8021: 
 8022: =back
 8023: 
 8024: =head2 Storing/Retreiving Data
 8025: 
 8026: =over 4
 8027: 
 8028: =item *
 8029: 
 8030: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8031: for this url; hashref needs to be given and should be a \%hashname; the
 8032: remaining args aren't required and if they aren't passed or are '' they will
 8033: be derived from the env
 8034: 
 8035: =item *
 8036: 
 8037: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8038: uses critical subroutine
 8039: 
 8040: =item *
 8041: 
 8042: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8043: all args are optional
 8044: 
 8045: =item *
 8046: 
 8047: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8048: dumps the complete (or key matching regexp) namespace into a hash
 8049: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8050: normally &store()ed into
 8051: 
 8052: $range should be either an integer '100' (give me the first 100
 8053:                                            matching records)
 8054:               or be  two integers sperated by a - with no spaces
 8055:                  '30-50' (give me the 30th through the 50th matching
 8056:                           records)
 8057: 
 8058: 
 8059: =item *
 8060: 
 8061: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8062: replaces a &store() version of data with a replacement set of data
 8063: for a particular resource in a namespace passed in the $storehash hash 
 8064: reference
 8065: 
 8066: =item *
 8067: 
 8068: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8069: works very similar to store/cstore, but all data is stored in a
 8070: temporary location and can be reset using tmpreset, $storehash should
 8071: be a hash reference, returns nothing on success
 8072: 
 8073: =item *
 8074: 
 8075: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8076: similar to restore, but all data is stored in a temporary location and
 8077: can be reset using tmpreset. Returns a hash of values on success,
 8078: error string otherwise.
 8079: 
 8080: =item *
 8081: 
 8082: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8083: deltes all keys for $symb form the temporary storage hash.
 8084: 
 8085: =item *
 8086: 
 8087: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8088: reference filled in from namesp ($udom and $uname are optional)
 8089: 
 8090: =item *
 8091: 
 8092: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8093: namesp ($udom and $uname are optional)
 8094: 
 8095: =item *
 8096: 
 8097: dump($namespace,$udom,$uname,$regexp,$range) : 
 8098: dumps the complete (or key matching regexp) namespace into a hash
 8099: ($udom, $uname, $regexp, $range are optional)
 8100: 
 8101: $range should be either an integer '100' (give me the first 100
 8102:                                            matching records)
 8103:               or be  two integers sperated by a - with no spaces
 8104:                  '30-50' (give me the 30th through the 50th matching
 8105:                           records)
 8106: =item *
 8107: 
 8108: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8109: $store can be a scalar, an array reference, or if the amount to be 
 8110: incremented is > 1, a hash reference.
 8111: 
 8112: ($udom and $uname are optional)
 8113: 
 8114: =item *
 8115: 
 8116: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8117: ($udom and $uname are optional)
 8118: 
 8119: =item *
 8120: 
 8121: cput($namespace,$storehash,$udom,$uname) : critical put
 8122: ($udom and $uname are optional)
 8123: 
 8124: =item *
 8125: 
 8126: newput($namespace,$storehash,$udom,$uname) :
 8127: 
 8128: Attempts to store the items in the $storehash, but only if they don't
 8129: currently exist, if this succeeds you can be certain that you have 
 8130: successfully created a new key value pair in the $namespace db.
 8131: 
 8132: 
 8133: Args:
 8134:  $namespace: name of database to store values to
 8135:  $storehash: hashref to store to the db
 8136:  $udom: (optional) domain of user containing the db
 8137:  $uname: (optional) name of user caontaining the db
 8138: 
 8139: Returns:
 8140:  'ok' -> succeeded in storing all keys of $storehash
 8141:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8142:                         least <key> already existed in the db (other
 8143:                         requested keys may also already exist)
 8144:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8145:  'con_lost' -> unable to contact request server
 8146:  'refused' -> action was not allowed by remote machine
 8147: 
 8148: 
 8149: =item *
 8150: 
 8151: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8152: reference filled in from namesp (encrypts the return communication)
 8153: ($udom and $uname are optional)
 8154: 
 8155: =item *
 8156: 
 8157: log($udom,$name,$home,$message) : write to permanent log for user; use
 8158: critical subroutine
 8159: 
 8160: =item *
 8161: 
 8162: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
 8163: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
 8164: 
 8165: =item *
 8166: 
 8167: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
 8168: 
 8169: =back
 8170: 
 8171: =head2 Network Status Functions
 8172: 
 8173: =over 4
 8174: 
 8175: =item *
 8176: 
 8177: dirlist($uri) : return directory list based on URI
 8178: 
 8179: =item *
 8180: 
 8181: spareserver() : find server with least workload from spare.tab
 8182: 
 8183: =back
 8184: 
 8185: =head2 Apache Request
 8186: 
 8187: =over 4
 8188: 
 8189: =item *
 8190: 
 8191: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8192: localhost, posts hash
 8193: 
 8194: =back
 8195: 
 8196: =head2 Data to String to Data
 8197: 
 8198: =over 4
 8199: 
 8200: =item *
 8201: 
 8202: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8203: and '&' separators, supports elements that are arrayrefs and hashrefs
 8204: 
 8205: =item *
 8206: 
 8207: hashref2str($hashref) : convert a hashref into a string complete with
 8208: escaping and '=' and '&' separators, supports elements that are
 8209: arrayrefs and hashrefs
 8210: 
 8211: =item *
 8212: 
 8213: arrayref2str($arrayref) : convert an arrayref into a string complete
 8214: with escaping and '&' separators, supports elements that are arrayrefs
 8215: and hashrefs
 8216: 
 8217: =item *
 8218: 
 8219: str2hash($string) : convert string to hash using unescaping and
 8220: splitting on '=' and '&', supports elements that are arrayrefs and
 8221: hashrefs
 8222: 
 8223: =item *
 8224: 
 8225: str2array($string) : convert string to hash using unescaping and
 8226: splitting on '&', supports elements that are arrayrefs and hashrefs
 8227: 
 8228: =back
 8229: 
 8230: =head2 Logging Routines
 8231: 
 8232: =over 4
 8233: 
 8234: These routines allow one to make log messages in the lonnet.log and
 8235: lonnet.perm logfiles.
 8236: 
 8237: =item *
 8238: 
 8239: logtouch() : make sure the logfile, lonnet.log, exists
 8240: 
 8241: =item *
 8242: 
 8243: logthis() : append message to the normal lonnet.log file, it gets
 8244: preiodically rolled over and deleted.
 8245: 
 8246: =item *
 8247: 
 8248: logperm() : append a permanent message to lonnet.perm.log, this log
 8249: file never gets deleted by any automated portion of the system, only
 8250: messages of critical importance should go in here.
 8251: 
 8252: =back
 8253: 
 8254: =head2 General File Helper Routines
 8255: 
 8256: =over 4
 8257: 
 8258: =item *
 8259: 
 8260: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8261: (a) files in /uploaded
 8262:   (i) If a local copy of the file exists - 
 8263:       compares modification date of local copy with last-modified date for 
 8264:       definitive version stored on home server for course. If local copy is 
 8265:       stale, requests a new version from the home server and stores it. 
 8266:       If the original has been removed from the home server, then local copy 
 8267:       is unlinked.
 8268:   (ii) If local copy does not exist -
 8269:       requests the file from the home server and stores it. 
 8270:   
 8271:   If $caller is 'uploadrep':  
 8272:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8273:     for request for files originally uploaded via DOCS. 
 8274:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8275:   
 8276:   Otherwise:
 8277:      This indicates a call from the content generation phase of the request.
 8278:      -  returns the entire contents of the file or -1.
 8279:      
 8280: (b) files in /res
 8281:    - returns the entire contents of a file or -1; 
 8282:    it properly subscribes to and replicates the file if neccessary.
 8283: 
 8284: 
 8285: =item *
 8286: 
 8287: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8288:                   reference
 8289: 
 8290: returns either a stat() list of data about the file or an empty list
 8291: if the file doesn't exist or couldn't find out about it (connection
 8292: problems or user unknown)
 8293: 
 8294: =item *
 8295: 
 8296: filelocation($dir,$file) : returns file system location of a file
 8297: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 8298: directory that relative $file lookups are to looked in ($dir of /a/dir
 8299: and a file of ../bob will become /a/bob)
 8300: 
 8301: =item *
 8302: 
 8303: hreflocation($dir,$file) : returns file system location or a URL; same as
 8304: filelocation except for hrefs
 8305: 
 8306: =item *
 8307: 
 8308: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 8309: 
 8310: =back
 8311: 
 8312: =head2 Usererfile file routines (/uploaded*)
 8313: 
 8314: =over 4
 8315: 
 8316: =item *
 8317: 
 8318: userfileupload(): main rotine for putting a file in a user or course's
 8319:                   filespace, arguments are,
 8320: 
 8321:  formname - required - this is the name of the element in $env where the
 8322:            filename, and the contents of the file to create/modifed exist
 8323:            the filename is in $env{'form.'.$formname.'.filename'} and the
 8324:            contents of the file is located in $env{'form.'.$formname}
 8325:  coursedoc - if true, store the file in the course of the active role
 8326:              of the current user
 8327:  subdir - required - subdirectory to put the file in under ../userfiles/
 8328:          if undefined, it will be placed in "unknown"
 8329: 
 8330:  (This routine calls clean_filename() to remove any dangerous
 8331:  characters from the filename, and then calls finuserfileupload() to
 8332:  complete the transaction)
 8333: 
 8334:  returns either the url of the uploaded file (/uploaded/....) if successful
 8335:  and /adm/notfound.html if unsuccessful
 8336: 
 8337: =item *
 8338: 
 8339: clean_filename(): routine for cleaing a filename up for storage in
 8340:                  userfile space, argument is:
 8341: 
 8342:  filename - proposed filename
 8343: 
 8344: returns: the new clean filename
 8345: 
 8346: =item *
 8347: 
 8348: finishuserfileupload(): routine that creaes and sends the file to
 8349: userspace, probably shouldn't be called directly
 8350: 
 8351:   docuname: username or courseid of destination for the file
 8352:   docudom: domain of user/course of destination for the file
 8353:   formname: same as for userfileupload()
 8354:   fname: filename (inculding subdirectories) for the file
 8355: 
 8356:  returns either the url of the uploaded file (/uploaded/....) if successful
 8357:  and /adm/notfound.html if unsuccessful
 8358: 
 8359: =item *
 8360: 
 8361: renameuserfile(): renames an existing userfile to a new name
 8362: 
 8363:   Args:
 8364:    docuname: username or courseid of destination for the file
 8365:    docudom: domain of user/course of destination for the file
 8366:    old: current file name (including any subdirs under userfiles)
 8367:    new: desired file name (including any subdirs under userfiles)
 8368: 
 8369: =item *
 8370: 
 8371: mkdiruserfile(): creates a directory is a userfiles dir
 8372: 
 8373:   Args:
 8374:    docuname: username or courseid of destination for the file
 8375:    docudom: domain of user/course of destination for the file
 8376:    dir: dir to create (including any subdirs under userfiles)
 8377: 
 8378: =item *
 8379: 
 8380: removeuserfile(): removes a file that exists in userfiles
 8381: 
 8382:   Args:
 8383:    docuname: username or courseid of destination for the file
 8384:    docudom: domain of user/course of destination for the file
 8385:    fname: filname to delete (including any subdirs under userfiles)
 8386: 
 8387: =item *
 8388: 
 8389: removeuploadedurl(): convience function for removeuserfile()
 8390: 
 8391:   Args:
 8392:    url:  a full /uploaded/... url to delete
 8393: 
 8394: =item * 
 8395: 
 8396: get_portfile_permissions():
 8397:   Args:
 8398:     domain: domain of user or course contain the portfolio files
 8399:     user: name of user or num of course contain the portfolio files
 8400:   Returns:
 8401:     hashref of a dump of the proper file_permissions.db
 8402:    
 8403: 
 8404: =item * 
 8405: 
 8406: get_access_controls():
 8407: 
 8408: Args:
 8409:   current_permissions: the hash ref returned from get_portfile_permissions()
 8410:   group: (optional) the group you want the files associated with
 8411:   file: (optional) the file you want access info on
 8412: 
 8413: Returns:
 8414:     a hash (keys are file names) of hashes containing
 8415:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 8416:         values are XML containing access control settings (see below) 
 8417: 
 8418: Internal notes:
 8419: 
 8420:  access controls are stored in file_permissions.db as key=value pairs.
 8421:     key -> path to file/file_name\0uniqueID:scope_end_start
 8422:         where scope -> public,guest,course,group,domains or users.
 8423:               end -> UNIX time for end of access (0 -> no end date)
 8424:               start -> UNIX time for start of access
 8425: 
 8426:     value -> XML description of access control
 8427:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 8428:             <start></start>
 8429:             <end></end>
 8430: 
 8431:             <password></password>  for scope type = guest
 8432: 
 8433:             <domain></domain>     for scope type = course or group
 8434:             <number></number>
 8435:             <roles id="">
 8436:              <role></role>
 8437:              <access></access>
 8438:              <section></section>
 8439:              <group></group>
 8440:             </roles>
 8441: 
 8442:             <dom></dom>         for scope type = domains
 8443: 
 8444:             <users>             for scope type = users
 8445:              <user>
 8446:               <uname></uname>
 8447:               <udom></udom>
 8448:              </user>
 8449:             </users>
 8450:            </scope> 
 8451:               
 8452:  Access data is also aggregated for each file in an additional key=value pair:
 8453:  key -> path to file/file_name\0accesscontrol 
 8454:  value -> reference to hash
 8455:           hash contains key = value pairs
 8456:           where key = uniqueID:scope_end_start
 8457:                 value = UNIX time record was last updated
 8458: 
 8459:           Used to improve speed of look-ups of access controls for each file.  
 8460:  
 8461:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 8462: 
 8463: modify_access_controls():
 8464: 
 8465: Modifies access controls for a portfolio file
 8466: Args
 8467: 1. file name
 8468: 2. reference to hash of required changes,
 8469: 3. domain
 8470: 4. username
 8471:   where domain,username are the domain of the portfolio owner 
 8472:   (either a user or a course) 
 8473: 
 8474: Returns:
 8475: 1. result of additions or updates ('ok' or 'error', with error message). 
 8476: 2. result of deletions ('ok' or 'error', with error message).
 8477: 3. reference to hash of any new or updated access controls.
 8478: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 8479:    key = integer (inbound ID)
 8480:    value = uniqueID  
 8481: 
 8482: =back
 8483: 
 8484: =head2 HTTP Helper Routines
 8485: 
 8486: =over 4
 8487: 
 8488: =item *
 8489: 
 8490: escape() : unpack non-word characters into CGI-compatible hex codes
 8491: 
 8492: =item *
 8493: 
 8494: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 8495: 
 8496: =back
 8497: 
 8498: =head1 PRIVATE SUBROUTINES
 8499: 
 8500: =head2 Underlying communication routines (Shouldn't call)
 8501: 
 8502: =over 4
 8503: 
 8504: =item *
 8505: 
 8506: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 8507: 
 8508: =item *
 8509: 
 8510: reply() : uses subreply to send a message to remote machine, logs all failures
 8511: 
 8512: =item *
 8513: 
 8514: critical() : passes a critical message to another server; if cannot
 8515: get through then place message in connection buffer directory and
 8516: returns con_delayed, if incapable of saving message, returns
 8517: con_failed
 8518: 
 8519: =item *
 8520: 
 8521: reconlonc() : tries to reconnect lonc client processes.
 8522: 
 8523: =back
 8524: 
 8525: =head2 Resource Access Logging
 8526: 
 8527: =over 4
 8528: 
 8529: =item *
 8530: 
 8531: flushcourselogs() : flush (save) buffer logs and access logs
 8532: 
 8533: =item *
 8534: 
 8535: courselog($what) : save message for course in hash
 8536: 
 8537: =item *
 8538: 
 8539: courseacclog($what) : save message for course using &courselog().  Perform
 8540: special processing for specific resource types (problems, exams, quizzes, etc).
 8541: 
 8542: =item *
 8543: 
 8544: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 8545: as a PerlChildExitHandler
 8546: 
 8547: =back
 8548: 
 8549: =head2 Other
 8550: 
 8551: =over 4
 8552: 
 8553: =item *
 8554: 
 8555: symblist($mapname,%newhash) : update symbolic storage links
 8556: 
 8557: =back
 8558: 
 8559: =cut

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