Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.849

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.849   ! albertel    4: # $Id: lonnet.pm,v 1.848 2007/03/14 23:36:10 albertel Exp $
1.178     www         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: #
1.169     harris41   28: ###
                     29: 
1.1       albertel   30: package Apache::lonnet;
                     31: 
                     32: use strict;
1.8       www        33: use LWP::UserAgent();
1.15      www        34: use HTTP::Headers;
1.486     www        35: use HTTP::Date;
                     36: # use Date::Parse;
1.11      www        37: use vars 
1.847     albertel   38: qw(%perlvar %badServerCache %spareid 
1.845     albertel   39:    %pr %prp $memcache %packagetab 
1.662     raeburn    40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
1.741     raeburn    41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %coursetypebuf
1.685     raeburn    42:    $tmpdir $_64bit %env);
1.403     www        43: 
1.1       albertel   44: use IO::Socket;
1.31      www        45: use GDBM_File;
1.208     albertel   46: use HTML::LCParser;
1.637     raeburn    47: use HTML::Parser;
1.88      www        48: use Fcntl qw(:flock);
1.557     albertel   49: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
1.539     albertel   50: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   51: use Cache::Memcached;
1.676     albertel   52: use Digest::MD5;
1.790     albertel   53: use Math::Random;
1.807     albertel   54: use LONCAPA qw(:DEFAULT :match);
1.740     www        55: use LONCAPA::Configuration;
1.676     albertel   56: 
1.195     www        57: my $readit;
1.550     foxr       58: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel   59: 
1.619     albertel   60: require Exporter;
                     61: 
                     62: our @ISA = qw (Exporter);
                     63: our @EXPORT = qw(%env);
                     64: 
1.449     matthew    65: =pod
                     66: 
                     67: =head1 Package Variables
                     68: 
                     69: These are largely undocumented, so if you decipher one please note it here.
                     70: 
                     71: =over 4
                     72: 
                     73: =item $processmarker
                     74: 
                     75: Contains the time this process was started and this servers host id.
                     76: 
                     77: =item $dumpcount
                     78: 
                     79: Counts the number of times a message log flush has been attempted (regardless
                     80: of success) by this process.  Used as part of the filename when messages are
                     81: delayed.
                     82: 
                     83: =back
                     84: 
                     85: =cut
                     86: 
                     87: 
1.1       albertel   88: # --------------------------------------------------------------------- Logging
1.729     www        89: {
                     90:     my $logid;
                     91:     sub instructor_log {
                     92: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
                     93: 	$logid++;
                     94: 	my $id=time().'00000'.$$.'00000'.$logid;
                     95: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www        96: 				    { $id => {
                     97: 					'exe_uname' => $env{'user.name'},
                     98: 					'exe_udom'  => $env{'user.domain'},
                     99: 					'exe_time'  => time(),
                    100: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    101: 					'delflag'   => $delflag,
                    102: 					'logentry'  => $storehash,
                    103: 					'uname'     => $uname,
                    104: 					'udom'      => $udom,
                    105: 				    }
                    106: 				  },
1.729     www       107: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
                    108: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
                    109: 				    );
                    110:     }
                    111: }
1.1       albertel  112: 
1.163     harris41  113: sub logtouch {
                    114:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  115:     unless (-e "$execdir/logs/lonnet.log") {	
                    116: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  117: 	close $fh;
                    118:     }
                    119:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    120:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    121: }
                    122: 
1.1       albertel  123: sub logthis {
                    124:     my $message=shift;
                    125:     my $execdir=$perlvar{'lonDaemons'};
                    126:     my $now=time;
                    127:     my $local=localtime($now);
1.448     albertel  128:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
                    129: 	print $fh "$local ($$): $message\n";
                    130: 	close($fh);
                    131:     }
1.1       albertel  132:     return 1;
                    133: }
                    134: 
                    135: sub logperm {
                    136:     my $message=shift;
                    137:     my $execdir=$perlvar{'lonDaemons'};
                    138:     my $now=time;
                    139:     my $local=localtime($now);
1.448     albertel  140:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    141: 	print $fh "$now:$message:$local\n";
                    142: 	close($fh);
                    143:     }
1.1       albertel  144:     return 1;
                    145: }
                    146: 
                    147: # -------------------------------------------------- Non-critical communication
                    148: sub subreply {
                    149:     my ($cmd,$server)=@_;
1.838     albertel  150:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      151:     #
                    152:     #  With loncnew process trimming, there's a timing hole between lonc server
                    153:     #  process exit and the master server picking up the listen on the AF_UNIX
                    154:     #  socket.  In that time interval, a lock file will exist:
                    155: 
                    156:     my $lockfile=$peerfile.".lock";
                    157:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    158: 	sleep(1);
                    159:     }
                    160:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      161:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      162:     #
1.550     foxr      163:     #   We'll give the connection a few tries before abandoning it.  If
                    164:     #   connection is not possible, we'll con_lost back to the client.
                    165:     #   
                    166:     my $client;
                    167:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    168: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    169: 				      Type    => SOCK_STREAM,
                    170: 				      Timeout => 10);
                    171: 	if($client) {
                    172: 	    last;		# Connected!
                    173: 	}
                    174: 	sleep(1);		# Try again later if failed connection.
                    175:     }
                    176:     my $answer;
                    177:     if ($client) {
1.704     albertel  178: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      179: 	$answer=<$client>;
                    180: 	if (!$answer) { $answer="con_lost"; }
                    181: 	chomp($answer);
                    182:     } else {
                    183: 	$answer = 'con_lost';	# Failed connection.
                    184:     }
1.1       albertel  185:     return $answer;
                    186: }
                    187: 
                    188: sub reply {
                    189:     my ($cmd,$server)=@_;
1.838     albertel  190:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  191:     my $answer=subreply($cmd,$server);
1.65      www       192:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  193:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       194:                 " $cmd to $server returned $answer</font>");
                    195:     }
1.1       albertel  196:     return $answer;
                    197: }
                    198: 
                    199: # ----------------------------------------------------------- Send USR1 to lonc
                    200: 
                    201: sub reconlonc {
1.836     www       202:     &logthis("Trying to reconnect lonc");
1.1       albertel  203:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  204:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  205: 	my $loncpid=<$fh>;
                    206:         chomp($loncpid);
                    207:         if (kill 0 => $loncpid) {
                    208: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    209:             kill USR1 => $loncpid;
                    210:             sleep 1;
1.836     www       211:          } else {
1.12      www       212: 	    &logthis(
1.672     albertel  213:                "<font color=\"blue\">WARNING:".
1.12      www       214:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  215:         }
                    216:     } else {
1.836     www       217: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  218:     }
                    219: }
                    220: 
                    221: # ------------------------------------------------------ Critical communication
1.12      www       222: 
1.1       albertel  223: sub critical {
                    224:     my ($cmd,$server)=@_;
1.838     albertel  225:     unless (&hostname($server)) {
1.672     albertel  226:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       227:                " Critical message to unknown server ($server)</font>");
                    228:         return 'no_such_host';
                    229:     }
1.1       albertel  230:     my $answer=reply($cmd,$server);
                    231:     if ($answer eq 'con_lost') {
                    232: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  233: 	my $answer=reply($cmd,$server);
1.1       albertel  234:         if ($answer eq 'con_lost') {
                    235:             my $now=time;
                    236:             my $middlename=$cmd;
1.5       www       237:             $middlename=substr($middlename,0,16);
1.1       albertel  238:             $middlename=~s/\W//g;
                    239:             my $dfilename=
1.305     www       240:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    241:             $dumpcount++;
1.1       albertel  242:             {
1.448     albertel  243: 		my $dfh;
                    244: 		if (open($dfh,">$dfilename")) {
                    245: 		    print $dfh "$cmd\n"; 
                    246: 		    close($dfh);
                    247: 		}
1.1       albertel  248:             }
                    249:             sleep 2;
                    250:             my $wcmd='';
                    251:             {
1.448     albertel  252: 		my $dfh;
                    253: 		if (open($dfh,"<$dfilename")) {
                    254: 		    $wcmd=<$dfh>; 
                    255: 		    close($dfh);
                    256: 		}
1.1       albertel  257:             }
                    258:             chomp($wcmd);
1.7       www       259:             if ($wcmd eq $cmd) {
1.672     albertel  260: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       261:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  262:                 &logperm("D:$server:$cmd");
                    263: 	        return 'con_delayed';
                    264:             } else {
1.672     albertel  265:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       266:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  267:                 &logperm("F:$server:$cmd");
                    268:                 return 'con_failed';
                    269:             }
                    270:         }
                    271:     }
                    272:     return $answer;
1.405     albertel  273: }
                    274: 
1.755     albertel  275: # ------------------------------------------- check if return value is an error
                    276: 
                    277: sub error {
                    278:     my ($result) = @_;
1.756     albertel  279:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  280: 	if ($2 == 2) { return undef; }
                    281: 	return $1;
                    282:     }
                    283:     return undef;
                    284: }
                    285: 
1.783     albertel  286: sub convert_and_load_session_env {
                    287:     my ($lonidsdir,$handle)=@_;
                    288:     my @profile;
                    289:     {
                    290: 	open(my $idf,"$lonidsdir/$handle.id");
                    291: 	flock($idf,LOCK_SH);
                    292: 	@profile=<$idf>;
                    293: 	close($idf);
                    294:     }
                    295:     my %temp_env;
                    296:     foreach my $line (@profile) {
1.786     albertel  297: 	if ($line !~ m/=/) {
                    298: 	    return 0;
                    299: 	}
1.783     albertel  300: 	chomp($line);
                    301: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    302: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    303:     }
                    304:     unlink("$lonidsdir/$handle.id");
                    305:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    306: 	    0640)) {
                    307: 	%disk_env = %temp_env;
                    308: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    309: 	untie(%disk_env);
                    310:     }
1.786     albertel  311:     return 1;
1.783     albertel  312: }
                    313: 
1.374     www       314: # ------------------------------------------- Transfer profile into environment
1.780     albertel  315: my $env_loaded;
                    316: sub transfer_profile_to_env {
1.788     albertel  317:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    318:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       319: 
1.720     albertel  320:     if (!defined($lonidsdir)) {
                    321: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    322:     }
                    323:     if (!defined($handle)) {
                    324:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    325:     }
                    326: 
1.786     albertel  327:     my $convert;
                    328:     {
                    329:     	open(my $idf,"$lonidsdir/$handle.id");
                    330: 	flock($idf,LOCK_SH);
                    331: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    332: 		&GDBM_READER(),0640)) {
                    333: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    334: 	    untie(%disk_env);
                    335: 	} else {
                    336: 	    $convert = 1;
                    337: 	}
                    338:     }
                    339:     if ($convert) {
                    340: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    341: 	    &logthis("Failed to load session, or convert session.");
                    342: 	}
1.374     www       343:     }
1.783     albertel  344: 
1.786     albertel  345:     my %remove;
1.783     albertel  346:     while ( my $envname = each(%env) ) {
1.433     matthew   347:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    348:             if ($time < time-300) {
1.783     albertel  349:                 $remove{$key}++;
1.433     matthew   350:             }
                    351:         }
                    352:     }
1.783     albertel  353: 
1.619     albertel  354:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  355:     $env_loaded=1;
1.783     albertel  356:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   357:         &delenv($expired_key);
1.374     www       358:     }
1.1       albertel  359: }
                    360: 
1.830     albertel  361: sub timed_flock {
                    362:     my ($file,$lock_type) = @_;
                    363:     my $failed=0;
                    364:     eval {
                    365: 	local $SIG{__DIE__}='DEFAULT';
                    366: 	local $SIG{ALRM}=sub {
                    367: 	    $failed=1;
                    368: 	    die("failed lock");
                    369: 	};
                    370: 	alarm(13);
                    371: 	flock($file,$lock_type);
                    372: 	alarm(0);
                    373:     };
                    374:     if ($failed) {
                    375: 	return undef;
                    376:     } else {
                    377: 	return 1;
                    378:     }
                    379: }
                    380: 
1.5       www       381: # ---------------------------------------------------------- Append Environment
                    382: 
                    383: sub appenv {
1.6       www       384:     my %newenv=@_;
1.692     albertel  385:     foreach my $key (keys(%newenv)) {
                    386: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
1.672     albertel  387:             &logthis("<font color=\"blue\">WARNING: ".
1.692     albertel  388:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
1.151     www       389:                 .'</font>');
1.692     albertel  390: 	    delete($newenv{$key});
1.35      www       391:         } else {
1.692     albertel  392:             $env{$key}=$newenv{$key};
1.35      www       393:         }
1.191     harris41  394:     }
1.830     albertel  395:     open(my $env_file,$env{'user.environment'});
                    396:     if (&timed_flock($env_file,LOCK_EX)
                    397: 	&&
                    398: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    399: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  400: 	while (my ($key,$value) = each(%newenv)) {
                    401: 	    $disk_env{$key} = $value;
1.448     albertel  402: 	}
1.783     albertel  403: 	untie(%disk_env);
1.56      www       404:     }
                    405:     return 'ok';
                    406: }
                    407: # ----------------------------------------------------- Delete from Environment
                    408: 
                    409: sub delenv {
                    410:     my $delthis=shift;
                    411:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
1.672     albertel  412:         &logthis("<font color=\"blue\">WARNING: ".
1.56      www       413:                 "Attempt to delete from environment ".$delthis);
                    414:         return 'error';
                    415:     }
1.830     albertel  416:     open(my $env_file,$env{'user.environment'});
                    417:     if (&timed_flock($env_file,LOCK_EX)
                    418: 	&&
                    419: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    420: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  421: 	foreach my $key (keys(%disk_env)) {
                    422: 	    if ($key=~/^$delthis/) { 
1.619     albertel  423:                 delete($env{$key});
1.783     albertel  424:                 delete($disk_env{$key});
1.473     matthew   425:             }
1.448     albertel  426: 	}
1.783     albertel  427: 	untie(%disk_env);
1.5       www       428:     }
                    429:     return 'ok';
1.369     albertel  430: }
                    431: 
1.790     albertel  432: sub get_env_multiple {
                    433:     my ($name) = @_;
                    434:     my @values;
                    435:     if (defined($env{$name})) {
                    436:         # exists is it an array
                    437:         if (ref($env{$name})) {
                    438:             @values=@{ $env{$name} };
                    439:         } else {
                    440:             $values[0]=$env{$name};
                    441:         }
                    442:     }
                    443:     return(@values);
                    444: }
                    445: 
1.369     albertel  446: # ------------------------------------------ Find out current server userload
                    447: # there is a copy in lond
                    448: sub userload {
                    449:     my $numusers=0;
                    450:     {
                    451: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    452: 	my $filename;
                    453: 	my $curtime=time;
                    454: 	while ($filename=readdir(LONIDS)) {
                    455: 	    if ($filename eq '.' || $filename eq '..') {next;}
1.404     albertel  456: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  457: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  458: 	}
                    459: 	closedir(LONIDS);
                    460:     }
                    461:     my $userloadpercent=0;
                    462:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    463:     if ($maxuserload) {
1.371     albertel  464: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  465:     }
1.372     albertel  466:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  467:     return $userloadpercent;
1.283     www       468: }
                    469: 
                    470: # ------------------------------------------ Fight off request when overloaded
                    471: 
                    472: sub overloaderror {
                    473:     my ($r,$checkserver)=@_;
                    474:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
                    475:     my $loadavg;
                    476:     if ($checkserver eq $perlvar{'lonHostID'}) {
1.448     albertel  477:        open(my $loadfile,'/proc/loadavg');
1.283     www       478:        $loadavg=<$loadfile>;
                    479:        $loadavg =~ s/\s.*//g;
1.285     matthew   480:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
1.448     albertel  481:        close($loadfile);
1.283     www       482:     } else {
                    483:        $loadavg=&reply('load',$checkserver);
                    484:     }
1.285     matthew   485:     my $overload=$loadavg-100;
1.283     www       486:     if ($overload>0) {
1.285     matthew   487: 	$r->err_headers_out->{'Retry-After'}=$overload;
1.283     www       488:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
1.554     www       489:         return 413;
1.283     www       490:     }    
                    491:     return '';
1.5       www       492: }
1.1       albertel  493: 
                    494: # ------------------------------ Find server with least workload from spare.tab
1.11      www       495: 
1.1       albertel  496: sub spareserver {
1.670     albertel  497:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
1.784     albertel  498:     my $spare_server;
1.370     albertel  499:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  500:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    501:                                                      :  $userloadpercent;
                    502:     
                    503:     foreach my $try_server (@{ $spareid{'primary'} }) {
                    504: 	($spare_server, $lowest_load) =
                    505: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
                    506:     }
                    507: 
                    508:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    509: 
                    510:     if (!$found_server) {
                    511: 	foreach my $try_server (@{ $spareid{'default'} }) {
                    512: 	    ($spare_server, $lowest_load) =
                    513: 		&compare_server_load($try_server, $spare_server, $lowest_load);
                    514: 	}
                    515:     }
                    516: 
                    517:     if (!$want_server_name) {
1.838     albertel  518: 	$spare_server="http://".&hostname($spare_server);
1.784     albertel  519:     }
                    520:     return $spare_server;
                    521: }
                    522: 
                    523: sub compare_server_load {
                    524:     my ($try_server, $spare_server, $lowest_load) = @_;
                    525: 
                    526:     my $loadans     = &reply('load',    $try_server);
                    527:     my $userloadans = &reply('userload',$try_server);
                    528: 
                    529:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
                    530: 	next; #didn't get a number from the server
                    531:     }
                    532: 
                    533:     my $load;
                    534:     if ($loadans =~ /\d/) {
                    535: 	if ($userloadans =~ /\d/) {
                    536: 	    #both are numbers, pick the bigger one
                    537: 	    $load = ($loadans > $userloadans) ? $loadans 
                    538: 		                              : $userloadans;
1.411     albertel  539: 	} else {
1.784     albertel  540: 	    $load = $loadans;
1.411     albertel  541: 	}
1.784     albertel  542:     } else {
                    543: 	$load = $userloadans;
                    544:     }
                    545: 
                    546:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    547: 	$spare_server = $try_server;
                    548: 	$lowest_load  = $load;
1.370     albertel  549:     }
1.784     albertel  550:     return ($spare_server,$lowest_load);
1.202     matthew   551: }
                    552: # --------------------------------------------- Try to change a user's password
                    553: 
                    554: sub changepass {
1.799     raeburn   555:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   556:     $currentpass = &escape($currentpass);
                    557:     $newpass     = &escape($newpass);
1.799     raeburn   558:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
1.202     matthew   559: 		       $server);
                    560:     if (! $answer) {
                    561: 	&logthis("No reply on password change request to $server ".
                    562: 		 "by $uname in domain $udom.");
                    563:     } elsif ($answer =~ "^ok") {
                    564:         &logthis("$uname in $udom successfully changed their password ".
                    565: 		 "on $server.");
                    566:     } elsif ($answer =~ "^pwchange_failure") {
                    567: 	&logthis("$uname in $udom was unable to change their password ".
                    568: 		 "on $server.  The action was blocked by either lcpasswd ".
                    569: 		 "or pwchange");
                    570:     } elsif ($answer =~ "^non_authorized") {
                    571:         &logthis("$uname in $udom did not get their password correct when ".
                    572: 		 "attempting to change it on $server.");
                    573:     } elsif ($answer =~ "^auth_mode_error") {
                    574:         &logthis("$uname in $udom attempted to change their password despite ".
                    575: 		 "not being locally or internally authenticated on $server.");
                    576:     } elsif ($answer =~ "^unknown_user") {
                    577:         &logthis("$uname in $udom attempted to change their password ".
                    578: 		 "on $server but were unable to because $server is not ".
                    579: 		 "their home server.");
                    580:     } elsif ($answer =~ "^refused") {
                    581: 	&logthis("$server refused to change $uname in $udom password because ".
                    582: 		 "it was sent an unencrypted request to change the password.");
                    583:     }
                    584:     return $answer;
1.1       albertel  585: }
                    586: 
1.169     harris41  587: # ----------------------- Try to determine user's current authentication scheme
                    588: 
                    589: sub queryauthenticate {
                    590:     my ($uname,$udom)=@_;
1.456     albertel  591:     my $uhome=&homeserver($uname,$udom);
                    592:     if (!$uhome) {
                    593: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                    594: 	return 'no_host';
                    595:     }
                    596:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                    597:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                    598: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41  599:     }
1.456     albertel  600:     return $answer;
1.169     harris41  601: }
                    602: 
1.1       albertel  603: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www       604: 
1.1       albertel  605: sub authenticate {
                    606:     my ($uname,$upass,$udom)=@_;
1.807     albertel  607:     $upass=&escape($upass);
                    608:     $uname= &LONCAPA::clean_username($uname);
1.836     www       609:     my $uhome=&homeserver($uname,$udom,1);
                    610:     if ((!$uhome) || ($uhome eq 'no_host')) {
                    611: # Maybe the machine was offline and only re-appeared again recently?
                    612:         &reconlonc();
                    613: # One more
                    614: 	my $uhome=&homeserver($uname,$udom,1);
                    615: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                    616: 	    &logthis("User $uname at $udom is unknown in authenticate");
                    617: 	}
1.471     albertel  618: 	return 'no_host';
1.1       albertel  619:     }
1.471     albertel  620:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
                    621:     if ($answer eq 'authorized') {
                    622: 	&logthis("User $uname at $udom authorized by $uhome"); 
                    623: 	return $uhome; 
                    624:     }
                    625:     if ($answer eq 'non_authorized') {
                    626: 	&logthis("User $uname at $udom rejected by $uhome");
                    627: 	return 'no_host'; 
1.9       www       628:     }
1.471     albertel  629:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel  630:     return 'no_host';
                    631: }
                    632: 
                    633: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www       634: 
1.599     albertel  635: my %homecache;
1.1       albertel  636: sub homeserver {
1.230     stredwic  637:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel  638:     my $index="$uname:$udom";
1.426     albertel  639: 
1.599     albertel  640:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel  641: 
                    642:     my %servers = &get_servers($udom,'library');
                    643:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic  644:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic  645: 		 exists($badServerCache{$tryserver}));
1.841     albertel  646: 
                    647: 	my $answer=reply("home:$udom:$uname",$tryserver);
                    648: 	if ($answer eq 'found') {
                    649: 	    delete($badServerCache{$tryserver}); 
                    650: 	    return $homecache{$index}=$tryserver;
                    651: 	} elsif ($answer eq 'no_host') {
                    652: 	    $badServerCache{$tryserver}=1;
                    653: 	}
1.1       albertel  654:     }    
                    655:     return 'no_host';
1.70      www       656: }
                    657: 
                    658: # ------------------------------------- Find the usernames behind a list of IDs
                    659: 
                    660: sub idget {
                    661:     my ($udom,@ids)=@_;
                    662:     my %returnhash=();
                    663:     
1.841     albertel  664:     my %servers = &get_servers($udom,'library');
                    665:     foreach my $tryserver (keys(%servers)) {
                    666: 	my $idlist=join('&',@ids);
                    667: 	$idlist=~tr/A-Z/a-z/; 
                    668: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                    669: 	my @answer=();
                    670: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                    671: 	    @answer=split(/\&/,$reply);
                    672: 	}                    ;
                    673: 	my $i;
                    674: 	for ($i=0;$i<=$#ids;$i++) {
                    675: 	    if ($answer[$i]) {
                    676: 		$returnhash{$ids[$i]}=$answer[$i];
                    677: 	    } 
                    678: 	}
                    679:     } 
1.70      www       680:     return %returnhash;
                    681: }
                    682: 
                    683: # ------------------------------------- Find the IDs behind a list of usernames
                    684: 
                    685: sub idrget {
                    686:     my ($udom,@unames)=@_;
                    687:     my %returnhash=();
1.800     albertel  688:     foreach my $uname (@unames) {
                    689:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41  690:     }
1.70      www       691:     return %returnhash;
                    692: }
                    693: 
                    694: # ------------------------------- Store away a list of names and associated IDs
                    695: 
                    696: sub idput {
                    697:     my ($udom,%ids)=@_;
                    698:     my %servers=();
1.800     albertel  699:     foreach my $uname (keys(%ids)) {
                    700: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                    701:         my $uhom=&homeserver($uname,$udom);
1.70      www       702:         if ($uhom ne 'no_host') {
1.800     albertel  703:             my $id=&escape($ids{$uname});
1.70      www       704:             $id=~tr/A-Z/a-z/;
1.800     albertel  705:             my $esc_unam=&escape($uname);
1.70      www       706: 	    if ($servers{$uhom}) {
1.800     albertel  707: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www       708:             } else {
1.800     albertel  709:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www       710:             }
                    711:         }
1.191     harris41  712:     }
1.800     albertel  713:     foreach my $server (keys(%servers)) {
                    714:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41  715:     }
1.344     www       716: }
                    717: 
1.806     raeburn   718: # ------------------------------------------- get items from domain db files   
                    719: 
                    720: sub get_dom {
                    721:     my ($namespace,$storearr,$udom)=@_;
                    722:     my $items='';
                    723:     foreach my $item (@$storearr) {
                    724:         $items.=&escape($item).'&';
                    725:     }
                    726:     $items=~s/\&$//;
                    727:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  728:     if (defined(&domain($udom,'primary'))) {
                    729:         my $uhome=&domain($udom,'primary');
1.806     raeburn   730:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                    731:         my @pairs=split(/\&/,$rep);
                    732:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                    733:             return @pairs;
                    734:         }
                    735:         my %returnhash=();
                    736:         my $i=0;
                    737:         foreach my $item (@$storearr) {
                    738:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                    739:             $i++;
                    740:         }
                    741:         return %returnhash;
                    742:     } else {
                    743:         &logthis("get_dom failed - no primary domain server for $udom");
                    744:     }
                    745: }
                    746: 
                    747: # -------------------------------------------- put items in domain db files 
                    748: 
                    749: sub put_dom {
                    750:     my ($namespace,$storehash,$udom)=@_;
                    751:     if (!$udom) { $udom=$env{'user.domain'}; }
1.846     albertel  752:     if (defined(&domain($udom,'primary'))) {
                    753:         my $uhome=&domain($udom,'primary');
1.806     raeburn   754:         my $items='';
                    755:         foreach my $item (keys(%$storehash)) {
                    756:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                    757:         }
                    758:         $items=~s/\&$//;
                    759:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                    760:     } else {
                    761:         &logthis("put_dom failed - no primary domain server for $udom");
                    762:     }
                    763: }
                    764: 
1.837     raeburn   765: sub retrieve_inst_usertypes {
                    766:     my ($udom) = @_;
                    767:     my (%returnhash,@order);
1.846     albertel  768:     if (defined(&domain($udom,'primary'))) {
                    769:         my $uhome=&domain($udom,'primary');
1.837     raeburn   770:         my $rep=&reply("inst_usertypes:$udom",$uhome);
                    771:         my ($hashitems,$orderitems) = split(/:/,$rep); 
                    772:         my @pairs=split(/\&/,$hashitems);
                    773:         foreach my $item (@pairs) {
                    774:             my ($key,$value)=split(/=/,$item,2);
                    775:             $key = &unescape($key);
                    776:             next if ($key =~ /^error: 2 /);
                    777:             $returnhash{$key}=&thaw_unescape($value);
                    778:         }
                    779:         my @esc_order = split(/\&/,$orderitems);
                    780:         foreach my $item (@esc_order) {
                    781:             push(@order,&unescape($item));
                    782:         }
                    783:     } else {
                    784:         &logthis("get_dom failed - no primary domain server for $udom");
                    785:     }
                    786:     return (\%returnhash,\@order);
                    787: }
                    788: 
1.344     www       789: # --------------------------------------------------- Assign a key to a student
                    790: 
                    791: sub assign_access_key {
1.364     www       792: #
                    793: # a valid key looks like uname:udom#comments
                    794: # comments are being appended
                    795: #
1.498     www       796:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                    797:     $kdom=
1.620     albertel  798:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www       799:     $knum=
1.620     albertel  800:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www       801:     $cdom=
1.620     albertel  802:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       803:     $cnum=
1.620     albertel  804:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    805:     $udom=$env{'user.name'} unless (defined($udom));
                    806:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www       807:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www       808:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel  809:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www       810:                                                   # assigned to this person
                    811:                                                   # - this should not happen,
1.345     www       812:                                                   # unless something went wrong
                    813:                                                   # the first time around
                    814: # ready to assign
1.364     www       815:         $logentry=$1.'; '.$logentry;
1.496     www       816:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www       817:                                                  $kdom,$knum) eq 'ok') {
1.345     www       818: # key now belongs to user
1.346     www       819: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www       820:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
                    821:                 &appenv('environment.'.$envkey => $ckey);
                    822:                 return 'ok';
                    823:             } else {
                    824:                 return 
                    825:   'error: Count not permanently assign key, will need to be re-entered later.';
                    826: 	    }
                    827:         } else {
                    828:             return 'error: Could not assign key, try again later.';
                    829:         }
1.364     www       830:     } elsif (!$existing{$ckey}) {
1.345     www       831: # the key does not exist
                    832: 	return 'error: The key does not exist';
                    833:     } else {
                    834: # the key is somebody else's
                    835: 	return 'error: The key is already in use';
                    836:     }
1.344     www       837: }
                    838: 
1.364     www       839: # ------------------------------------------ put an additional comment on a key
                    840: 
                    841: sub comment_access_key {
                    842: #
                    843: # a valid key looks like uname:udom#comments
                    844: # comments are being appended
                    845: #
                    846:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                    847:     $cdom=
1.620     albertel  848:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www       849:     $cnum=
1.620     albertel  850:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www       851:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                    852:     if ($existing{$ckey}) {
                    853:         $existing{$ckey}.='; '.$logentry;
                    854: # ready to assign
1.367     www       855:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www       856:                                                  $cdom,$cnum) eq 'ok') {
                    857: 	    return 'ok';
                    858:         } else {
                    859: 	    return 'error: Count not store comment.';
                    860:         }
                    861:     } else {
                    862: # the key does not exist
                    863: 	return 'error: The key does not exist';
                    864:     }
                    865: }
                    866: 
1.344     www       867: # ------------------------------------------------------ Generate a set of keys
                    868: 
                    869: sub generate_access_keys {
1.364     www       870:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www       871:     $cdom=
1.620     albertel  872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       873:     $cnum=
1.620     albertel  874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www       875:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www       876:     unless (($cdom) && ($cnum)) { return 0; }
                    877:     if ($number>10000) { return 0; }
                    878:     sleep(2); # make sure don't get same seed twice
                    879:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                    880:     my $total=0;
                    881:     for (my $i=1;$i<=$number;$i++) {
                    882:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                    883:                   sprintf("%lx",int(100000*rand)).'-'.
                    884:                   sprintf("%lx",int(100000*rand));
                    885:        $newkey=~s/1/g/g; # folks mix up 1 and l
                    886:        $newkey=~s/0/h/g; # and also 0 and O
                    887:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                    888:        if ($existing{$newkey}) {
                    889:            $i--;
                    890:        } else {
1.364     www       891: 	  if (&put('accesskeys',
                    892:               { $newkey => '# generated '.localtime().
1.620     albertel  893:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www       894:                            '; '.$logentry },
                    895: 		   $cdom,$cnum) eq 'ok') {
1.344     www       896:               $total++;
                    897: 	  }
                    898:        }
                    899:     }
1.620     albertel  900:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www       901:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                    902:     return $total;
                    903: }
                    904: 
                    905: # ------------------------------------------------------- Validate an accesskey
                    906: 
                    907: sub validate_access_key {
                    908:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                    909:     $cdom=
1.620     albertel  910:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www       911:     $cnum=
1.620     albertel  912:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                    913:     $udom=$env{'user.domain'} unless (defined($udom));
                    914:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www       915:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel  916:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www       917: }
                    918: 
                    919: # ------------------------------------- Find the section of student in a course
1.652     albertel  920: sub devalidate_getsection_cache {
                    921:     my ($udom,$unam,$courseid)=@_;
                    922:     my $hashid="$udom:$unam:$courseid";
                    923:     &devalidate_cache_new('getsection',$hashid);
                    924: }
1.298     matthew   925: 
1.815     albertel  926: sub courseid_to_courseurl {
                    927:     my ($courseid) = @_;
                    928:     #already url style courseid
                    929:     return $courseid if ($courseid =~ m{^/});
                    930: 
                    931:     if (exists($env{'course.'.$courseid.'.num'})) {
                    932: 	my $cnum = $env{'course.'.$courseid.'.num'};
                    933: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                    934: 	return "/$cdom/$cnum";
                    935:     }
                    936: 
                    937:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                    938:     if (exists($courseinfo{'num'})) {
                    939: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                    940:     }
                    941: 
                    942:     return undef;
                    943: }
                    944: 
1.298     matthew   945: sub getsection {
                    946:     my ($udom,$unam,$courseid)=@_;
1.599     albertel  947:     my $cachetime=1800;
1.551     albertel  948: 
                    949:     my $hashid="$udom:$unam:$courseid";
1.599     albertel  950:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel  951:     if (defined($cached)) { return $result; }
                    952: 
1.298     matthew   953:     my %Pending; 
                    954:     my %Expired;
                    955:     #
                    956:     # Each role can either have not started yet (pending), be active, 
                    957:     #    or have expired.
                    958:     #
                    959:     # If there is an active role, we are done.
                    960:     #
                    961:     # If there is more than one role which has not started yet, 
                    962:     #     choose the one which will start sooner
                    963:     # If there is one role which has not started yet, return it.
                    964:     #
                    965:     # If there is more than one expired role, choose the one which ended last.
                    966:     # If there is a role which has expired, return it.
                    967:     #
1.815     albertel  968:     $courseid = &courseid_to_courseurl($courseid);
1.817     raeburn   969:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
                    970:     foreach my $key (keys(%roleshash)) {
1.479     albertel  971:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew   972:         my $section=$1;
                    973:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn   974:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew   975:         my $now=time;
1.548     albertel  976:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew   977:             $Expired{$end}=$section;
                    978:             next;
                    979:         }
1.548     albertel  980:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew   981:             $Pending{$start}=$section;
                    982:             next;
                    983:         }
1.599     albertel  984:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew   985:     }
                    986:     #
                    987:     # Presumedly there will be few matching roles from the above
                    988:     # loop and the sorting time will be negligible.
                    989:     if (scalar(keys(%Pending))) {
                    990:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel  991:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew   992:     } 
                    993:     if (scalar(keys(%Expired))) {
                    994:         my @sorted = sort {$a <=> $b} keys(%Expired);
                    995:         my $time = pop(@sorted);
1.599     albertel  996:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew   997:     }
1.599     albertel  998:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew   999: }
1.70      www      1000: 
1.599     albertel 1001: sub save_cache {
                   1002:     &purge_remembered();
1.722     albertel 1003:     #&Apache::loncommon::validate_page();
1.620     albertel 1004:     undef(%env);
1.780     albertel 1005:     undef($env_loaded);
1.599     albertel 1006: }
1.452     albertel 1007: 
1.599     albertel 1008: my $to_remember=-1;
                   1009: my %remembered;
                   1010: my %accessed;
                   1011: my $kicks=0;
                   1012: my $hits=0;
1.849   ! albertel 1013: sub make_key {
        !          1014:     my ($name,$id) = @_;
        !          1015:     if (length($id) > 200) { $id=length($id).':'.&Digest::MD5::md5_hex($id); }
        !          1016:     return &escape($name.':'.$id);
        !          1017: }
        !          1018: 
1.599     albertel 1019: sub devalidate_cache_new {
                   1020:     my ($name,$id,$debug) = @_;
                   1021:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849   ! albertel 1022:     $id=&make_key($name,$id);
1.599     albertel 1023:     $memcache->delete($id);
                   1024:     delete($remembered{$id});
                   1025:     delete($accessed{$id});
                   1026: }
                   1027: 
                   1028: sub is_cached_new {
                   1029:     my ($name,$id,$debug) = @_;
1.849   ! albertel 1030:     $id=&make_key($name,$id);
1.599     albertel 1031:     if (exists($remembered{$id})) {
                   1032: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   1033: 	$accessed{$id}=[&gettimeofday()];
                   1034: 	$hits++;
                   1035: 	return ($remembered{$id},1);
                   1036:     }
                   1037:     my $value = $memcache->get($id);
                   1038:     if (!(defined($value))) {
                   1039: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 1040: 	return (undef,undef);
1.416     albertel 1041:     }
1.599     albertel 1042:     if ($value eq '__undef__') {
                   1043: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   1044: 	$value=undef;
                   1045:     }
                   1046:     &make_room($id,$value,$debug);
                   1047:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   1048:     return ($value,1);
                   1049: }
                   1050: 
                   1051: sub do_cache_new {
                   1052:     my ($name,$id,$value,$time,$debug) = @_;
1.849   ! albertel 1053:     $id=&make_key($name,$id);
1.599     albertel 1054:     my $setvalue=$value;
                   1055:     if (!defined($setvalue)) {
                   1056: 	$setvalue='__undef__';
                   1057:     }
1.623     albertel 1058:     if (!defined($time) ) {
                   1059: 	$time=600;
                   1060:     }
1.599     albertel 1061:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.600     albertel 1062:     $memcache->set($id,$setvalue,$time);
                   1063:     # need to make a copy of $value
                   1064:     #&make_room($id,$value,$debug);
1.599     albertel 1065:     return $value;
                   1066: }
                   1067: 
                   1068: sub make_room {
                   1069:     my ($id,$value,$debug)=@_;
                   1070:     $remembered{$id}=$value;
                   1071:     if ($to_remember<0) { return; }
                   1072:     $accessed{$id}=[&gettimeofday()];
                   1073:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   1074:     my $to_kick;
                   1075:     my $max_time=0;
                   1076:     foreach my $other (keys(%accessed)) {
                   1077: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   1078: 	    $to_kick=$other;
                   1079: 	    $max_time=&tv_interval($accessed{$other});
                   1080: 	}
                   1081:     }
                   1082:     delete($remembered{$to_kick});
                   1083:     delete($accessed{$to_kick});
                   1084:     $kicks++;
                   1085:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 1086:     return;
                   1087: }
                   1088: 
1.599     albertel 1089: sub purge_remembered {
1.604     albertel 1090:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   1091:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 1092:     undef(%remembered);
                   1093:     undef(%accessed);
1.428     albertel 1094: }
1.70      www      1095: # ------------------------------------- Read an entry from a user's environment
                   1096: 
                   1097: sub userenvironment {
                   1098:     my ($udom,$unam,@what)=@_;
                   1099:     my %returnhash=();
                   1100:     my @answer=split(/\&/,
                   1101:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
                   1102:                       &homeserver($unam,$udom)));
                   1103:     my $i;
                   1104:     for ($i=0;$i<=$#what;$i++) {
                   1105: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
                   1106:     }
                   1107:     return %returnhash;
1.1       albertel 1108: }
                   1109: 
1.617     albertel 1110: # ---------------------------------------------------------- Get a studentphoto
                   1111: sub studentphoto {
                   1112:     my ($udom,$unam,$ext) = @_;
                   1113:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  1114:     if (defined($env{'request.course.id'})) {
1.708     raeburn  1115:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  1116:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   1117:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   1118:             } else {
                   1119:                 my ($result,$perm_reqd)=
1.707     albertel 1120: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1121:                 if ($result eq 'ok') {
                   1122:                     if (!($perm_reqd eq 'yes')) {
                   1123:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   1124:                     }
                   1125:                 }
                   1126:             }
                   1127:         }
                   1128:     } else {
                   1129:         my ($result,$perm_reqd) = 
1.707     albertel 1130: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  1131:         if ($result eq 'ok') {
                   1132:             if (!($perm_reqd eq 'yes')) {
                   1133:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   1134:             }
                   1135:         }
                   1136:     }
                   1137:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   1138: }
                   1139: 
                   1140: sub retrievestudentphoto {
                   1141:     my ($udom,$unam,$ext,$type) = @_;
                   1142:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   1143:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   1144:     if ($ret eq 'ok') {
                   1145:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   1146:         if ($type eq 'thumbnail') {
                   1147:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   1148:         }
                   1149:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   1150:         return $tokenurl;
                   1151:     } else {
                   1152:         if ($type eq 'thumbnail') {
                   1153:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   1154:         } else { 
                   1155:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   1156:         }
1.617     albertel 1157:     }
                   1158: }
                   1159: 
1.263     www      1160: # -------------------------------------------------------------------- New chat
                   1161: 
                   1162: sub chatsend {
1.724     raeburn  1163:     my ($newentry,$anon,$group)=@_;
1.620     albertel 1164:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1165:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1166:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      1167:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 1168: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  1169: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      1170: }
                   1171: 
                   1172: # ------------------------------------------ Find current version of a resource
                   1173: 
                   1174: sub getversion {
                   1175:     my $fname=&clutter(shift);
                   1176:     unless ($fname=~/^\/res\//) { return -1; }
                   1177:     return &currentversion(&filelocation('',$fname));
                   1178: }
                   1179: 
                   1180: sub currentversion {
                   1181:     my $fname=shift;
1.599     albertel 1182:     my ($result,$cached)=&is_cached_new('resversion',$fname);
1.440     www      1183:     if (defined($cached)) { return $result; }
1.292     www      1184:     my $author=$fname;
                   1185:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1186:     my ($udom,$uname)=split(/\//,$author);
                   1187:     my $home=homeserver($uname,$udom);
                   1188:     if ($home eq 'no_host') { 
                   1189:         return -1; 
                   1190:     }
                   1191:     my $answer=reply("currentversion:$fname",$home);
                   1192:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1193: 	return -1;
                   1194:     }
1.599     albertel 1195:     return &do_cache_new('resversion',$fname,$answer,600);
1.263     www      1196: }
                   1197: 
1.1       albertel 1198: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      1199: 
1.1       albertel 1200: sub subscribe {
                   1201:     my $fname=shift;
1.761     raeburn  1202:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 1203:     $fname=~s/[\n\r]//g;
1.1       albertel 1204:     my $author=$fname;
                   1205:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1206:     my ($udom,$uname)=split(/\//,$author);
                   1207:     my $home=homeserver($uname,$udom);
1.335     albertel 1208:     if ($home eq 'no_host') {
                   1209:         return 'not_found';
1.1       albertel 1210:     }
                   1211:     my $answer=reply("sub:$fname",$home);
1.64      www      1212:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   1213: 	$answer.=' by '.$home;
                   1214:     }
1.1       albertel 1215:     return $answer;
                   1216: }
                   1217:     
1.8       www      1218: # -------------------------------------------------------------- Replicate file
                   1219: 
                   1220: sub repcopy {
                   1221:     my $filename=shift;
1.23      www      1222:     $filename=~s/\/+/\//g;
1.607     raeburn  1223:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   1224:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 1225:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 1226: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 1227: 	return &repcopy_userfile($filename);
                   1228:     }
1.532     albertel 1229:     $filename=~s/[\n\r]//g;
1.8       www      1230:     my $transname="$filename.in.transfer";
1.828     www      1231: # FIXME: this should flock
1.607     raeburn  1232:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      1233:     my $remoteurl=subscribe($filename);
1.64      www      1234:     if ($remoteurl =~ /^con_lost by/) {
                   1235: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1236:            return 'unavailable';
1.8       www      1237:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 1238: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  1239: 	   return 'not_found';
1.64      www      1240:     } elsif ($remoteurl =~ /^rejected by/) {
                   1241: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  1242:            return 'forbidden';
1.20      www      1243:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  1244:            return 'ok';
1.8       www      1245:     } else {
1.290     www      1246:         my $author=$filename;
                   1247:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   1248:         my ($udom,$uname)=split(/\//,$author);
                   1249:         my $home=homeserver($uname,$udom);
                   1250:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      1251:            my @parts=split(/\//,$filename);
                   1252:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   1253:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   1254:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  1255: 	       return 'bad_request';
1.8       www      1256:            }
                   1257:            my $count;
                   1258:            for ($count=5;$count<$#parts;$count++) {
                   1259:                $path.="/$parts[$count]";
                   1260:                if ((-e $path)!=1) {
                   1261: 		   mkdir($path,0777);
                   1262:                }
                   1263:            }
                   1264:            my $ua=new LWP::UserAgent;
                   1265:            my $request=new HTTP::Request('GET',"$remoteurl");
                   1266:            my $response=$ua->request($request,$transname);
                   1267:            if ($response->is_error()) {
                   1268: 	       unlink($transname);
                   1269:                my $message=$response->status_line;
1.672     albertel 1270:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      1271:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  1272:                return 'unavailable';
1.8       www      1273:            } else {
1.16      www      1274: 	       if ($remoteurl!~/\.meta$/) {
                   1275:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   1276:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   1277:                   if ($mresponse->is_error()) {
                   1278: 		      unlink($filename.'.meta');
                   1279:                       &logthis(
1.672     albertel 1280:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      1281:                   }
                   1282: 	       }
1.8       www      1283:                rename($transname,$filename);
1.607     raeburn  1284:                return 'ok';
1.8       www      1285:            }
1.290     www      1286:        }
1.8       www      1287:     }
1.330     www      1288: }
                   1289: 
                   1290: # ------------------------------------------------ Get server side include body
                   1291: sub ssi_body {
1.381     albertel 1292:     my ($filelink,%form)=@_;
1.606     matthew  1293:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   1294:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   1295:     }
1.330     www      1296:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
1.381     albertel 1297:                                      &ssi($filelink,%form));
1.778     albertel 1298:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 1299:     $output=~s/^.*?\<body[^\>]*\>//si;
                   1300:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
1.330     www      1301:     return $output;
1.8       www      1302: }
                   1303: 
1.15      www      1304: # --------------------------------------------------------- Server Side Include
                   1305: 
1.782     albertel 1306: sub absolute_url {
                   1307:     my ($host_name) = @_;
                   1308:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   1309:     if ($host_name eq '') {
                   1310: 	$host_name = $ENV{'SERVER_NAME'};
                   1311:     }
                   1312:     return $protocol.$host_name;
                   1313: }
                   1314: 
1.15      www      1315: sub ssi {
                   1316: 
1.23      www      1317:     my ($fn,%form)=@_;
1.15      www      1318: 
                   1319:     my $ua=new LWP::UserAgent;
1.23      www      1320:     
                   1321:     my $request;
1.711     albertel 1322: 
                   1323:     $form{'no_update_last_known'}=1;
                   1324: 
1.23      www      1325:     if (%form) {
1.782     albertel 1326:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.201     albertel 1327:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1.23      www      1328:     } else {
1.782     albertel 1329:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      1330:     }
                   1331: 
1.15      www      1332:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   1333:     my $response=$ua->request($request);
                   1334: 
1.324     www      1335:     return $response->content;
                   1336: }
                   1337: 
                   1338: sub externalssi {
                   1339:     my ($url)=@_;
                   1340:     my $ua=new LWP::UserAgent;
                   1341:     my $request=new HTTP::Request('GET',$url);
                   1342:     my $response=$ua->request($request);
1.15      www      1343:     return $response->content;
                   1344: }
1.254     www      1345: 
1.492     albertel 1346: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   1347: 
                   1348: sub allowuploaded {
                   1349:     my ($srcurl,$url)=@_;
                   1350:     $url=&clutter(&declutter($url));
                   1351:     my $dir=$url;
                   1352:     $dir=~s/\/[^\/]+$//;
                   1353:     my %httpref=();
                   1354:     my $httpurl=&hreflocation('',$url);
                   1355:     $httpref{'httpref.'.$httpurl}=$srcurl;
                   1356:     &Apache::lonnet::appenv(%httpref);
1.254     www      1357: }
1.477     raeburn  1358: 
1.478     albertel 1359: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 1360: # input: action, courseID, current domain, intended
1.637     raeburn  1361: #        path to file, source of file, instruction to parse file for objects,
                   1362: #        ref to hash for embedded objects,
                   1363: #        ref to hash for codebase of java objects.
                   1364: #
1.485     raeburn  1365: # output: url to file (if action was uploaddoc), 
                   1366: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  1367: #
1.478     albertel 1368: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   1369: # course.
1.477     raeburn  1370: #
1.478     albertel 1371: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1372: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   1373: #          course's home server.
1.477     raeburn  1374: #
1.478     albertel 1375: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   1376: #          be copied from $source (current location) to 
                   1377: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1378: #         and will then be copied to
                   1379: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   1380: #         course's home server.
1.485     raeburn  1381: #
1.481     raeburn  1382: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 1383: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  1384: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   1385: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   1386: #         in course's home server.
1.637     raeburn  1387: #
1.477     raeburn  1388: 
                   1389: sub process_coursefile {
1.638     albertel 1390:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1.477     raeburn  1391:     my $fetchresult;
1.638     albertel 1392:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  1393:     if ($action eq 'propagate') {
1.638     albertel 1394:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   1395: 			     $home);
1.481     raeburn  1396:     } else {
1.477     raeburn  1397:         my $fpath = '';
                   1398:         my $fname = $file;
1.478     albertel 1399:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  1400:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  1401:         my $filepath = &build_filepath($fpath);
1.481     raeburn  1402:         if ($action eq 'copy') {
                   1403:             if ($source eq '') {
                   1404:                 $fetchresult = 'no source file';
                   1405:                 return $fetchresult;
                   1406:             } else {
                   1407:                 my $destination = $filepath.'/'.$fname;
                   1408:                 rename($source,$destination);
                   1409:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1410:                                  $home);
1.481     raeburn  1411:             }
                   1412:         } elsif ($action eq 'uploaddoc') {
                   1413:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 1414:             print $fh $env{'form.'.$source};
1.481     raeburn  1415:             close($fh);
1.637     raeburn  1416:             if ($parser eq 'parse') {
                   1417:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
                   1418:                 unless ($parse_result eq 'ok') {
                   1419:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   1420:                 }
                   1421:             }
1.477     raeburn  1422:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1423:                                  $home);
1.481     raeburn  1424:             if ($fetchresult eq 'ok') {
                   1425:                 return '/uploaded/'.$fpath.'/'.$fname;
                   1426:             } else {
                   1427:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1428:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  1429:                 return '/adm/notfound.html';
                   1430:             }
1.477     raeburn  1431:         }
                   1432:     }
1.485     raeburn  1433:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  1434:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 1435:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  1436:     }
                   1437:     return $fetchresult;
                   1438: }
                   1439: 
1.637     raeburn  1440: sub build_filepath {
                   1441:     my ($fpath) = @_;
                   1442:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   1443:     unless ($fpath eq '') {
                   1444:         my @parts=split('/',$fpath);
                   1445:         foreach my $part (@parts) {
                   1446:             $filepath.= '/'.$part;
                   1447:             if ((-e $filepath)!=1) {
                   1448:                 mkdir($filepath,0777);
                   1449:             }
                   1450:         }
                   1451:     }
                   1452:     return $filepath;
                   1453: }
                   1454: 
                   1455: sub store_edited_file {
1.638     albertel 1456:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  1457:     my $file = $primary_url;
                   1458:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   1459:     my $fpath = '';
                   1460:     my $fname = $file;
                   1461:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   1462:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   1463:     my $filepath = &build_filepath($fpath);
                   1464:     open(my $fh,'>'.$filepath.'/'.$fname);
                   1465:     print $fh $content;
                   1466:     close($fh);
1.638     albertel 1467:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  1468:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 1469: 			  $home);
1.637     raeburn  1470:     if ($$fetchresult eq 'ok') {
                   1471:         return '/uploaded/'.$fpath.'/'.$fname;
                   1472:     } else {
1.638     albertel 1473:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   1474: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  1475:         return '/adm/notfound.html';
                   1476:     }
                   1477: }
                   1478: 
1.531     albertel 1479: sub clean_filename {
1.831     albertel 1480:     my ($fname,$args)=@_;
1.315     www      1481: # Replace Windows backslashes by forward slashes
1.257     www      1482:     $fname=~s/\\/\//g;
1.831     albertel 1483:     if (!$args->{'keep_path'}) {
                   1484:         # Get rid of everything but the actual filename
                   1485: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   1486:     }
1.315     www      1487: # Replace spaces by underscores
                   1488:     $fname=~s/\s+/\_/g;
                   1489: # Replace all other weird characters by nothing
1.831     albertel 1490:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 1491: # Replace all .\d. sequences with _\d. so they no longer look like version
                   1492: # numbers
                   1493:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 1494:     return $fname;
                   1495: }
                   1496: 
1.608     albertel 1497: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 1498: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.719     banghart 1499: #                    the desired filenam is in $env{"form.$formname.filename"}
1.686     albertel 1500: #        $coursedoc - if true up to the current course
                   1501: #                     if false
                   1502: #        $subdir - directory in userfile to store the file into
                   1503: #        $parser, $allfiles, $codebase - unknown
                   1504: #
                   1505: # output: url of file in userspace, or error: <message> 
                   1506: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 1507: 
                   1508: 
1.531     albertel 1509: sub userfileupload {
1.719     banghart 1510:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,$destudom)=@_;
1.531     albertel 1511:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 1512:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 1513:     $fname=&clean_filename($fname);
1.315     www      1514: # See if there is anything left
1.257     www      1515:     unless ($fname) { return 'error: no uploaded file'; }
1.620     albertel 1516:     chop($env{'form.'.$formname});
1.523     raeburn  1517:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
                   1518:         my $now = time;
                   1519:         my $filepath = 'tmp/helprequests/'.$now;
                   1520:         my @parts=split(/\//,$filepath);
                   1521:         my $fullpath = $perlvar{'lonDaemons'};
                   1522:         for (my $i=0;$i<@parts;$i++) {
                   1523:             $fullpath .= '/'.$parts[$i];
                   1524:             if ((-e $fullpath)!=1) {
                   1525:                 mkdir($fullpath,0777);
                   1526:             }
                   1527:         }
                   1528:         open(my $fh,'>'.$fullpath.'/'.$fname);
1.620     albertel 1529:         print $fh $env{'form.'.$formname};
1.523     raeburn  1530:         close($fh);
1.741     raeburn  1531:         return $fullpath.'/'.$fname;
                   1532:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
                   1533:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   1534:                        '_'.$env{'user.domain'}.'/pending';
                   1535:         my @parts=split(/\//,$filepath);
                   1536:         my $fullpath = $perlvar{'lonDaemons'};
                   1537:         for (my $i=0;$i<@parts;$i++) {
                   1538:             $fullpath .= '/'.$parts[$i];
                   1539:             if ((-e $fullpath)!=1) {
                   1540:                 mkdir($fullpath,0777);
                   1541:             }
                   1542:         }
                   1543:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   1544:         print $fh $env{'form.'.$formname};
                   1545:         close($fh);
                   1546:         return $fullpath.'/'.$fname;
1.523     raeburn  1547:     }
1.719     banghart 1548:     
1.258     www      1549: # Create the directory if not present
1.493     albertel 1550:     $fname="$subdir/$fname";
1.259     www      1551:     if ($coursedoc) {
1.638     albertel 1552: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1553: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  1554:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 1555:             return &finishuserfileupload($docuname,$docudom,
                   1556: 					 $formname,$fname,$parser,$allfiles,
                   1557: 					 $codebase);
1.481     raeburn  1558:         } else {
1.620     albertel 1559:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 1560:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   1561: 				       $fname,$formname,$parser,
                   1562: 				       $allfiles,$codebase);
1.481     raeburn  1563:         }
1.719     banghart 1564:     } elsif (defined($destuname)) {
                   1565:         my $docuname=$destuname;
                   1566:         my $docudom=$destudom;
                   1567: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1568: 				     $fname,$parser,$allfiles,$codebase);
                   1569:         
1.259     www      1570:     } else {
1.638     albertel 1571:         my $docuname=$env{'user.name'};
                   1572:         my $docudom=$env{'user.domain'};
1.714     raeburn  1573:         if (exists($env{'form.group'})) {
                   1574:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   1575:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   1576:         }
1.638     albertel 1577: 	return &finishuserfileupload($docuname,$docudom,$formname,
                   1578: 				     $fname,$parser,$allfiles,$codebase);
1.259     www      1579:     }
1.271     www      1580: }
                   1581: 
                   1582: sub finishuserfileupload {
1.638     albertel 1583:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
1.477     raeburn  1584:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      1585:     my $filepath=$perlvar{'lonDocRoot'};
1.494     albertel 1586:     my ($fnamepath,$file);
                   1587:     $file=$fname;
                   1588:     if ($fname=~m|/|) {
                   1589:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   1590: 	$path.=$fnamepath.'/';
                   1591:     }
1.259     www      1592:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      1593:     my $count;
                   1594:     for ($count=4;$count<=$#parts;$count++) {
                   1595:         $filepath.="/$parts[$count]";
                   1596:         if ((-e $filepath)!=1) {
                   1597: 	    mkdir($filepath,0777);
                   1598:         }
                   1599:     }
                   1600: # Save the file
                   1601:     {
1.701     albertel 1602: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   1603: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   1604: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   1605: 	    return '/adm/notfound.html';
                   1606: 	}
                   1607: 	if (!print FH ($env{'form.'.$formname})) {
                   1608: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   1609: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   1610: 	    return '/adm/notfound.html';
                   1611: 	}
1.570     albertel 1612: 	close(FH);
1.258     www      1613:     }
1.637     raeburn  1614:     if ($parser eq 'parse') {
1.638     albertel 1615:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
                   1616: 						   $codebase);
1.637     raeburn  1617:         unless ($parse_result eq 'ok') {
1.638     albertel 1618:             &logthis('Failed to parse '.$filepath.$file.
                   1619: 		     ' for embedded media: '.$parse_result); 
1.637     raeburn  1620:         }
                   1621:     }
1.259     www      1622: # Notify homeserver to grep it
                   1623: #
1.638     albertel 1624:     my $docuhome=&homeserver($docuname,$docudom);
1.494     albertel 1625:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      1626:     if ($fetchresult eq 'ok') {
1.259     www      1627: #
1.258     www      1628: # Return the URL to it
1.494     albertel 1629:         return '/uploaded/'.$path.$file;
1.263     www      1630:     } else {
1.494     albertel 1631:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   1632: 		 ': '.$fetchresult);
1.263     www      1633:         return '/adm/notfound.html';
                   1634:     }    
1.493     albertel 1635: }
                   1636: 
1.637     raeburn  1637: sub extract_embedded_items {
1.648     raeburn  1638:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
1.637     raeburn  1639:     my @state = ();
                   1640:     my %javafiles = (
                   1641:                       codebase => '',
                   1642:                       code => '',
                   1643:                       archive => ''
                   1644:                     );
                   1645:     my %mediafiles = (
                   1646:                       src => '',
                   1647:                       movie => '',
                   1648:                      );
1.648     raeburn  1649:     my $p;
                   1650:     if ($content) {
                   1651:         $p = HTML::LCParser->new($content);
                   1652:     } else {
                   1653:         $p = HTML::LCParser->new($filepath.'/'.$file);
                   1654:     }
1.641     albertel 1655:     while (my $t=$p->get_token()) {
1.640     albertel 1656: 	if ($t->[0] eq 'S') {
                   1657: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
                   1658: 	    push (@state, $tagname);
1.648     raeburn  1659:             if (lc($tagname) eq 'allow') {
                   1660:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   1661:             }
1.640     albertel 1662: 	    if (lc($tagname) eq 'img') {
                   1663: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   1664: 	    }
1.645     raeburn  1665:             if (lc($tagname) eq 'script') {
                   1666:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   1667:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   1668:                 } else {
                   1669:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   1670:                 }
                   1671:             }
                   1672:             if (lc($tagname) eq 'link') {
                   1673:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   1674:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   1675:                 }
                   1676:             }
1.640     albertel 1677: 	    if (lc($tagname) eq 'object' ||
                   1678: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   1679: 		foreach my $item (keys(%javafiles)) {
                   1680: 		    $javafiles{$item} = '';
                   1681: 		}
                   1682: 	    }
                   1683: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   1684: 		my $name = lc($attr->{'name'});
                   1685: 		foreach my $item (keys(%javafiles)) {
                   1686: 		    if ($name eq $item) {
                   1687: 			$javafiles{$item} = $attr->{'value'};
                   1688: 			last;
                   1689: 		    }
                   1690: 		}
                   1691: 		foreach my $item (keys(%mediafiles)) {
                   1692: 		    if ($name eq $item) {
                   1693: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   1694: 			last;
                   1695: 		    }
                   1696: 		}
                   1697: 	    }
                   1698: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   1699: 		foreach my $item (keys(%javafiles)) {
                   1700: 		    if ($attr->{$item}) {
                   1701: 			$javafiles{$item} = $attr->{$item};
                   1702: 			last;
                   1703: 		    }
                   1704: 		}
                   1705: 		foreach my $item (keys(%mediafiles)) {
                   1706: 		    if ($attr->{$item}) {
                   1707: 			&add_filetype($allfiles,$attr->{$item},$item);
                   1708: 			last;
                   1709: 		    }
                   1710: 		}
                   1711: 	    }
                   1712: 	} elsif ($t->[0] eq 'E') {
                   1713: 	    my ($tagname) = ($t->[1]);
                   1714: 	    if ($javafiles{'codebase'} ne '') {
                   1715: 		$javafiles{'codebase'} .= '/';
                   1716: 	    }  
                   1717: 	    if (lc($tagname) eq 'applet' ||
                   1718: 		lc($tagname) eq 'object' ||
                   1719: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   1720: 		) {
                   1721: 		foreach my $item (keys(%javafiles)) {
                   1722: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   1723: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   1724: 			&add_filetype($allfiles,$file,$item);
                   1725: 		    }
                   1726: 		}
                   1727: 	    } 
                   1728: 	    pop @state;
                   1729: 	}
                   1730:     }
1.637     raeburn  1731:     return 'ok';
                   1732: }
                   1733: 
1.639     albertel 1734: sub add_filetype {
                   1735:     my ($allfiles,$file,$type)=@_;
                   1736:     if (exists($allfiles->{$file})) {
                   1737: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   1738: 	    push(@{$allfiles->{$file}}, &escape($type));
                   1739: 	}
                   1740:     } else {
                   1741: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  1742:     }
                   1743: }
                   1744: 
1.493     albertel 1745: sub removeuploadedurl {
                   1746:     my ($url)=@_;
                   1747:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613     albertel 1748:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 1749: }
                   1750: 
                   1751: sub removeuserfile {
                   1752:     my ($docuname,$docudom,$fname)=@_;
                   1753:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1754:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
                   1755:     if ($result eq 'ok') {
                   1756:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   1757:             my $metafile = $fname.'.meta';
                   1758:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 1759: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
                   1760:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1761:             my $sqlresult = 
1.823     albertel 1762:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1763:                                         'portfolio_metadata',$group,
                   1764:                                         'delete');
1.798     raeburn  1765:         }
                   1766:     }
                   1767:     return $result;
1.257     www      1768: }
1.15      www      1769: 
1.530     albertel 1770: sub mkdiruserfile {
                   1771:     my ($docuname,$docudom,$dir)=@_;
                   1772:     my $home=&homeserver($docuname,$docudom);
                   1773:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   1774: }
                   1775: 
1.531     albertel 1776: sub renameuserfile {
                   1777:     my ($docuname,$docudom,$old,$new)=@_;
                   1778:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  1779:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   1780:                         &escape("$old").':'.&escape("$new"),$home);
                   1781:     if ($result eq 'ok') {
                   1782:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   1783:             my $oldmeta = $old.'.meta';
                   1784:             my $newmeta = $new.'.meta';
                   1785:             my $metaresult = 
                   1786:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 1787: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   1788:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  1789:             my $sqlresult = 
1.823     albertel 1790:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  1791:                                         'portfolio_metadata',$group,
                   1792:                                         'delete');
1.798     raeburn  1793:         }
                   1794:     }
                   1795:     return $result;
1.531     albertel 1796: }
                   1797: 
1.14      www      1798: # ------------------------------------------------------------------------- Log
                   1799: 
                   1800: sub log {
                   1801:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      1802:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      1803: }
                   1804: 
                   1805: # ------------------------------------------------------------------ Course Log
1.352     www      1806: #
                   1807: # This routine flushes several buffers of non-mission-critical nature
                   1808: #
1.157     www      1809: 
                   1810: sub flushcourselogs {
1.352     www      1811:     &logthis('Flushing log buffers');
                   1812: #
                   1813: # course logs
                   1814: # This is a log of all transactions in a course, which can be used
                   1815: # for data mining purposes
                   1816: #
                   1817: # It also collects the courseid database, which lists last transaction
                   1818: # times and course titles for all courseids
                   1819: #
                   1820:     my %courseidbuffer=();
1.800     albertel 1821:     foreach my $crsid (keys %courselogs) {
1.352     www      1822:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      1823: 		          &escape($courselogs{$crsid}),
                   1824: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      1825: 	    delete $courselogs{$crsid};
                   1826:         } else {
                   1827:             &logthis('Failed to flush log buffer for '.$crsid);
                   1828:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 1829:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      1830:                         " exceeded maximum size, deleting.</font>");
                   1831:                delete $courselogs{$crsid};
                   1832:             }
1.352     www      1833:         }
                   1834:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
                   1835:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
1.516     raeburn  1836: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1837:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.352     www      1838:         } else {
                   1839:            $courseidbuffer{$coursehombuf{$crsid}}=
1.516     raeburn  1840: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
1.741     raeburn  1841:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
1.571     raeburn  1842:         }
1.191     harris41 1843:     }
1.352     www      1844: #
                   1845: # Write course id database (reverse lookup) to homeserver of courses 
                   1846: # Is used in pickcourse
                   1847: #
1.840     albertel 1848:     foreach my $crs_home (keys(%courseidbuffer)) {
1.844     albertel 1849:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
1.840     albertel 1850: 		     $crs_home);
1.352     www      1851:     }
                   1852: #
                   1853: # File accesses
                   1854: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   1855: #
1.449     matthew  1856:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  1857:         if ($entry =~ /___count$/) {
                   1858:             my ($dom,$name);
1.807     albertel 1859:             ($dom,$name,undef)=
1.811     albertel 1860: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  1861:             if (! defined($dom) || $dom eq '' || 
                   1862:                 ! defined($name) || $name eq '') {
1.620     albertel 1863:                 my $cid = $env{'request.course.id'};
                   1864:                 $dom  = $env{'request.'.$cid.'.domain'};
                   1865:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  1866:             }
1.450     matthew  1867:             my $value = $accesshash{$entry};
                   1868:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   1869:             my %temphash=($url => $value);
1.449     matthew  1870:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   1871:             if ($result eq 'ok') {
                   1872:                 delete $accesshash{$entry};
                   1873:             } elsif ($result eq 'unknown_cmd') {
                   1874:                 # Target server has old code running on it.
1.450     matthew  1875:                 my %temphash=($entry => $value);
1.449     matthew  1876:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1877:                     delete $accesshash{$entry};
                   1878:                 }
                   1879:             }
                   1880:         } else {
1.811     albertel 1881:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  1882:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  1883:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   1884:                 delete $accesshash{$entry};
                   1885:             }
1.185     www      1886:         }
1.191     harris41 1887:     }
1.352     www      1888: #
                   1889: # Roles
                   1890: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   1891: #
1.800     albertel 1892:     foreach my $entry (keys(%userrolehash)) {
1.351     www      1893:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      1894: 	    split(/\:/,$entry);
                   1895:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      1896:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      1897:                 $rudom,$runame) eq 'ok') {
                   1898: 	    delete $userrolehash{$entry};
                   1899:         }
                   1900:     }
1.662     raeburn  1901: #
                   1902: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   1903: #
                   1904:     my %domrolebuffer = ();
                   1905:     foreach my $entry (keys %domainrolehash) {
                   1906:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
                   1907:         if ($domrolebuffer{$rudom}) {
                   1908:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   1909:                       '='.&escape($domainrolehash{$entry});
                   1910:         } else {
                   1911:             $domrolebuffer{$rudom}.=&escape($entry).
                   1912:                       '='.&escape($domainrolehash{$entry});
                   1913:         }
                   1914:         delete $domainrolehash{$entry};
                   1915:     }
                   1916:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 1917: 	my %servers = &get_servers($dom,'library');
                   1918: 	foreach my $tryserver (keys(%servers)) {
                   1919: 	    unless (&reply('domroleput:'.$dom.':'.
                   1920: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   1921: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   1922: 	    }
1.662     raeburn  1923:         }
                   1924:     }
1.186     www      1925:     $dumpcount++;
1.157     www      1926: }
                   1927: 
                   1928: sub courselog {
                   1929:     my $what=shift;
1.158     www      1930:     $what=time.':'.$what;
1.620     albertel 1931:     unless ($env{'request.course.id'}) { return ''; }
                   1932:     $coursedombuf{$env{'request.course.id'}}=
                   1933:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1934:     $coursenumbuf{$env{'request.course.id'}}=
                   1935:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   1936:     $coursehombuf{$env{'request.course.id'}}=
                   1937:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   1938:     $coursedescrbuf{$env{'request.course.id'}}=
                   1939:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   1940:     $courseinstcodebuf{$env{'request.course.id'}}=
                   1941:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   1942:     $courseownerbuf{$env{'request.course.id'}}=
                   1943:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  1944:     $coursetypebuf{$env{'request.course.id'}}=
                   1945:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 1946:     if (defined $courselogs{$env{'request.course.id'}}) {
                   1947: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      1948:     } else {
1.620     albertel 1949: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      1950:     }
1.620     albertel 1951:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      1952: 	&flushcourselogs();
                   1953:     }
1.158     www      1954: }
                   1955: 
                   1956: sub courseacclog {
                   1957:     my $fnsymb=shift;
1.620     albertel 1958:     unless ($env{'request.course.id'}) { return ''; }
                   1959:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 1960:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      1961:         $what.=':POST';
1.583     matthew  1962:         # FIXME: Probably ought to escape things....
1.800     albertel 1963: 	foreach my $key (keys(%env)) {
                   1964:             if ($key=~/^form\.(.*)/) {
                   1965: 		$what.=':'.$1.'='.$env{$key};
1.158     www      1966:             }
1.191     harris41 1967:         }
1.583     matthew  1968:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   1969:         # FIXME: We should not be depending on a form parameter that someone
                   1970:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 1971:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  1972:             $what.= ':POST';
                   1973:             # FIXME: Probably ought to escape things....
                   1974:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   1975:                                  'crsdiscuss') {
1.620     albertel 1976:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  1977:             }
                   1978:         }
1.158     www      1979:     }
                   1980:     &courselog($what);
1.149     www      1981: }
                   1982: 
1.185     www      1983: sub countacc {
                   1984:     my $url=&declutter(shift);
1.458     matthew  1985:     return if (! defined($url) || $url eq '');
1.620     albertel 1986:     unless ($env{'request.course.id'}) { return ''; }
                   1987:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      1988:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  1989:     $accesshash{$key}++;
1.185     www      1990: }
1.349     www      1991: 
1.361     www      1992: sub linklog {
                   1993:     my ($from,$to)=@_;
                   1994:     $from=&declutter($from);
                   1995:     $to=&declutter($to);
                   1996:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   1997:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   1998: }
                   1999:   
1.349     www      2000: sub userrolelog {
                   2001:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  2002:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  2003:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  2004:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
                   2005:         ($trole=~/^ta/)) {
1.350     www      2006:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2007:        $userrolehash
                   2008:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      2009:                     =$tend.':'.$tstart;
1.662     raeburn  2010:     }
                   2011:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   2012:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   2013:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   2014:         ($trole=~/^sc/)) {
                   2015:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   2016:        $domainrolehash
                   2017:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   2018:                     = $tend.':'.$tstart;
                   2019:     }
1.351     www      2020: }
                   2021: 
                   2022: sub get_course_adv_roles {
                   2023:     my $cid=shift;
1.620     albertel 2024:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      2025:     my %coursehash=&coursedescription($cid);
1.470     www      2026:     my %nothide=();
1.800     albertel 2027:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   2028: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
1.470     www      2029:     }
1.351     www      2030:     my %returnhash=();
                   2031:     my %dumphash=
                   2032:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   2033:     my $now=time;
1.800     albertel 2034:     foreach my $entry (keys %dumphash) {
                   2035: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      2036:         if (($tstart) && ($tstart<0)) { next; }
                   2037:         if (($tend) && ($tend<$now)) { next; }
                   2038:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 2039:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 2040: 	if ($username eq '' || $domain eq '') { next; }
1.470     www      2041: 	if ((&privileged($username,$domain)) && 
                   2042: 	    (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 2043: 	if ($role eq 'cr') { next; }
1.351     www      2044:         my $key=&plaintext($role);
                   2045:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
                   2046:         if ($returnhash{$key}) {
                   2047: 	    $returnhash{$key}.=','.$username.':'.$domain;
                   2048:         } else {
                   2049:             $returnhash{$key}=$username.':'.$domain;
                   2050:         }
1.400     www      2051:      }
                   2052:     return %returnhash;
                   2053: }
                   2054: 
                   2055: sub get_my_roles {
1.832     raeburn  2056:     my ($uname,$udom,$types,$roles,$roledoms)=@_;
1.620     albertel 2057:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   2058:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.400     www      2059:     my %dumphash=
                   2060:             &dump('nohist_userroles',$udom,$uname);
                   2061:     my %returnhash=();
                   2062:     my $now=time;
1.800     albertel 2063:     foreach my $entry (keys(%dumphash)) {
                   2064: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.400     www      2065:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  2066:         my $status = 'active';
                   2067:         if (($tend) && ($tend<$now)) {
                   2068:             $status = 'previous';
                   2069:         } 
                   2070:         if (($tstart) && ($now<$tstart)) {
                   2071:             $status = 'future';
                   2072:         }
                   2073:         if (ref($types) eq 'ARRAY') {
                   2074:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   2075:                 next;
                   2076:             } 
                   2077:         } else {
                   2078:             if ($status ne 'active') {
                   2079:                 next;
                   2080:             }
                   2081:         }
1.800     albertel 2082:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.832     raeburn  2083:         if (ref($roledoms) eq 'ARRAY') {
                   2084:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   2085:                 next;
                   2086:             }
                   2087:         }
                   2088:         if (ref($roles) eq 'ARRAY') {
                   2089:             if (!grep(/^\Q$role\E$/,@{$roles})) {
                   2090:                 next;
                   2091:             }
                   2092:         } 
1.400     www      2093: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
1.832     raeburn  2094:     }
1.373     www      2095:     return %returnhash;
1.399     www      2096: }
                   2097: 
                   2098: # ----------------------------------------------------- Frontpage Announcements
                   2099: #
                   2100: #
                   2101: 
                   2102: sub postannounce {
                   2103:     my ($server,$text)=@_;
1.844     albertel 2104:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      2105:     unless ($text=~/\w/) { $text=''; }
                   2106:     return &reply('setannounce:'.&escape($text),$server);
                   2107: }
                   2108: 
                   2109: sub getannounce {
1.448     albertel 2110: 
                   2111:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      2112: 	my $announcement='';
1.800     albertel 2113: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 2114: 	close($fh);
1.399     www      2115: 	if ($announcement=~/\w/) { 
                   2116: 	    return 
                   2117:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 2118:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      2119: 	} else {
                   2120: 	    return '';
                   2121: 	}
                   2122:     } else {
                   2123: 	return '';
                   2124:     }
1.351     www      2125: }
1.353     www      2126: 
                   2127: # ---------------------------------------------------------- Course ID routines
                   2128: # Deal with domain's nohist_courseid.db files
                   2129: #
                   2130: 
                   2131: sub courseidput {
                   2132:     my ($domain,$what,$coursehome)=@_;
                   2133:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   2134: }
                   2135: 
                   2136: sub courseiddump {
1.791     raeburn  2137:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
1.353     www      2138:     my %returnhash=();
1.355     www      2139:     unless ($domfilter) { $domfilter=''; }
1.845     albertel 2140:     my %libserv = &all_library();
                   2141:     foreach my $tryserver (keys(%libserv)) {
                   2142:         if ( (  $hostidflag == 1 
                   2143: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   2144: 	     || (!defined($hostidflag)) ) {
                   2145: 
                   2146: 	    if ($domfilter eq ''
                   2147: 		|| (&host_domain($tryserver) eq $domfilter)) {
1.800     albertel 2148: 	        foreach my $line (
1.844     albertel 2149:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
1.571     raeburn  2150: 			       $sincefilter.':'.&escape($descfilter).':'.
1.791     raeburn  2151:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
1.354     www      2152:                                $tryserver))) {
1.800     albertel 2153: 		    my ($key,$value)=split(/\=/,$line,2);
1.506     raeburn  2154:                     if (($key) && ($value)) {
1.516     raeburn  2155: 		        $returnhash{&unescape($key)}=$value;
1.506     raeburn  2156:                     }
1.353     www      2157:                 }
                   2158:             }
                   2159:         }
                   2160:     }
                   2161:     return %returnhash;
                   2162: }
                   2163: 
1.658     raeburn  2164: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  2165: 
                   2166: sub dcmailput {
1.685     raeburn  2167:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  2168:     my $status = &Apache::lonnet::critical(
1.740     www      2169:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   2170:        &escape($message),$server);
1.662     raeburn  2171:     return $status;
                   2172: }
                   2173: 
1.658     raeburn  2174: sub dcmaildump {
                   2175:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  2176:     my %returnhash=();
1.846     albertel 2177: 
                   2178:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  2179:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   2180:                                                          &escape($enddate).':';
                   2181: 	my @esc_senders=map { &escape($_)} @$senders;
                   2182: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 2183: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 2184:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  2185:             if (($key) && ($value)) {
                   2186:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  2187:             }
                   2188:         }
                   2189:     }
                   2190:     return %returnhash;
                   2191: }
1.662     raeburn  2192: # ---------------------------------------------------------- Domain roles
                   2193: 
                   2194: sub get_domain_roles {
                   2195:     my ($dom,$roles,$startdate,$enddate)=@_;
                   2196:     if (undef($startdate) || $startdate eq '') {
                   2197:         $startdate = '.';
                   2198:     }
                   2199:     if (undef($enddate) || $enddate eq '') {
                   2200:         $enddate = '.';
                   2201:     }
                   2202:     my $rolelist = join(':',@{$roles});
                   2203:     my %personnel = ();
1.841     albertel 2204: 
                   2205:     my %servers = &get_servers($dom,'library');
                   2206:     foreach my $tryserver (keys(%servers)) {
                   2207: 	%{$personnel{$tryserver}}=();
                   2208: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   2209: 					    &escape($startdate).':'.
                   2210: 					    &escape($enddate).':'.
                   2211: 					    &escape($rolelist), $tryserver))) {
                   2212: 	    my ($key,$value) = split(/\=/,$line,2);
                   2213: 	    if (($key) && ($value)) {
                   2214: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   2215: 	    }
                   2216: 	}
1.662     raeburn  2217:     }
                   2218:     return %personnel;
                   2219: }
1.658     raeburn  2220: 
1.149     www      2221: # ----------------------------------------------------------- Check out an item
                   2222: 
1.504     albertel 2223: sub get_first_access {
                   2224:     my ($type,$argsymb)=@_;
1.790     albertel 2225:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2226:     if ($argsymb) { $symb=$argsymb; }
                   2227:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2228:     if ($type eq 'map') {
                   2229: 	$res=&symbread($map);
                   2230:     } else {
                   2231: 	$res=$symb;
                   2232:     }
                   2233:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   2234:     return $times{"$courseid\0$res"};
1.504     albertel 2235: }
                   2236: 
                   2237: sub set_first_access {
                   2238:     my ($type)=@_;
1.790     albertel 2239:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 2240:     my ($map,$id,$res)=&decode_symb($symb);
1.588     albertel 2241:     if ($type eq 'map') {
                   2242: 	$res=&symbread($map);
                   2243:     } else {
                   2244: 	$res=$symb;
                   2245:     }
                   2246:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 2247:     if (!$firstaccess) {
1.588     albertel 2248: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 2249:     }
                   2250:     return 'already_set';
1.504     albertel 2251: }
                   2252: 
1.149     www      2253: sub checkout {
                   2254:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   2255:     my $now=time;
                   2256:     my $lonhost=$perlvar{'lonHostID'};
                   2257:     my $infostr=&escape(
1.234     www      2258:                  'CHECKOUTTOKEN&'.
1.149     www      2259:                  $tuname.'&'.
                   2260:                  $tudom.'&'.
                   2261:                  $tcrsid.'&'.
                   2262:                  $symb.'&'.
                   2263: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
                   2264:     my $token=&reply('tmpput:'.$infostr,$lonhost);
1.151     www      2265:     if ($token=~/^error\:/) { 
1.672     albertel 2266:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2267:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2268:                  "</font>");
                   2269:         return ''; 
                   2270:     }
                   2271: 
1.149     www      2272:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   2273:     $token=~tr/a-z/A-Z/;
                   2274: 
1.153     www      2275:     my %infohash=('resource.0.outtoken' => $token,
                   2276:                   'resource.0.checkouttime' => $now,
                   2277:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
1.149     www      2278: 
                   2279:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2280:        return '';
1.151     www      2281:     } else {
1.672     albertel 2282:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2283:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2284:                  "</font>");
1.149     www      2285:     }    
                   2286: 
                   2287:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2288:                          &escape('Checkout '.$infostr.' - '.
                   2289:                                                  $token)) ne 'ok') {
                   2290: 	return '';
1.151     www      2291:     } else {
1.672     albertel 2292:         &logthis("<font color=\"blue\">WARNING: ".
1.151     www      2293:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   2294:                  "</font>");
1.149     www      2295:     }
1.151     www      2296:     return $token;
1.149     www      2297: }
                   2298: 
                   2299: # ------------------------------------------------------------ Check in an item
                   2300: 
                   2301: sub checkin {
                   2302:     my $token=shift;
1.150     www      2303:     my $now=time;
                   2304:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   2305:     $lonhost=~tr/A-Z/a-z/;
1.838     albertel 2306:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
1.150     www      2307:     $dtoken=~s/\W/\_/g;
1.234     www      2308:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
1.150     www      2309:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   2310: 
1.154     www      2311:     unless (($tuname) && ($tudom)) {
                   2312:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   2313:         return '';
                   2314:     }
                   2315:     
                   2316:     unless (&allowed('mgr',$tcrsid)) {
                   2317:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
1.620     albertel 2318:                  $env{'user.name'}.' - '.$env{'user.domain'});
1.154     www      2319:         return '';
                   2320:     }
                   2321: 
1.153     www      2322:     my %infohash=('resource.0.intoken' => $token,
                   2323:                   'resource.0.checkintime' => $now,
                   2324:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
1.150     www      2325: 
                   2326:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   2327:        return '';
                   2328:     }    
                   2329: 
                   2330:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   2331:                          &escape('Checkin - '.$token)) ne 'ok') {
                   2332: 	return '';
                   2333:     }
                   2334: 
                   2335:     return ($symb,$tuname,$tudom,$tcrsid);    
1.110     www      2336: }
                   2337: 
                   2338: # --------------------------------------------- Set Expire Date for Spreadsheet
                   2339: 
                   2340: sub expirespread {
                   2341:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 2342:     my $cid=$env{'request.course.id'}; 
1.110     www      2343:     if ($cid) {
                   2344:        my $now=time;
                   2345:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 2346:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   2347:                             $env{'course.'.$cid.'.num'}.
1.110     www      2348: 	        	    ':nohist_expirationdates:'.
                   2349:                             &escape($key).'='.$now,
1.620     albertel 2350:                             $env{'course.'.$cid.'.home'})
1.110     www      2351:     }
                   2352:     return 'ok';
1.14      www      2353: }
                   2354: 
1.109     www      2355: # ----------------------------------------------------- Devalidate Spreadsheets
                   2356: 
                   2357: sub devalidate {
1.325     www      2358:     my ($symb,$uname,$udom)=@_;
1.620     albertel 2359:     my $cid=$env{'request.course.id'}; 
1.109     www      2360:     if ($cid) {
1.391     matthew  2361:         # delete the stored spreadsheets for
                   2362:         # - the student level sheet of this user in course's homespace
                   2363:         # - the assessment level sheet for this resource 
                   2364:         #   for this user in user's homespace
1.553     albertel 2365: 	# - current conditional state info
1.325     www      2366: 	my $key=$uname.':'.$udom.':';
1.109     www      2367:         my $status=
1.299     matthew  2368: 	    &del('nohist_calculatedsheets',
1.391     matthew  2369: 		 [$key.'studentcalc:'],
1.620     albertel 2370: 		 $env{'course.'.$cid.'.domain'},
                   2371: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 2372: 		.' '.
                   2373: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  2374: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      2375:         unless ($status eq 'ok ok') {
                   2376:            &logthis('Could not devalidate spreadsheet '.
1.325     www      2377:                     $uname.' at '.$udom.' for '.
1.109     www      2378: 		    $symb.': '.$status);
1.133     albertel 2379:         }
1.553     albertel 2380: 	&delenv('user.state.'.$cid);
1.109     www      2381:     }
                   2382: }
                   2383: 
1.265     albertel 2384: sub get_scalar {
                   2385:     my ($string,$end) = @_;
                   2386:     my $value;
                   2387:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   2388: 	$value = $1;
                   2389:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   2390: 	$value = $1;
                   2391:     }
                   2392:     return &unescape($value);
                   2393: }
                   2394: 
                   2395: sub array2str {
                   2396:   my (@array) = @_;
                   2397:   my $result=&arrayref2str(\@array);
                   2398:   $result=~s/^__ARRAY_REF__//;
                   2399:   $result=~s/__END_ARRAY_REF__$//;
                   2400:   return $result;
                   2401: }
                   2402: 
1.204     albertel 2403: sub arrayref2str {
                   2404:   my ($arrayref) = @_;
1.265     albertel 2405:   my $result='__ARRAY_REF__';
1.204     albertel 2406:   foreach my $elem (@$arrayref) {
1.265     albertel 2407:     if(ref($elem) eq 'ARRAY') {
                   2408:       $result.=&arrayref2str($elem).'&';
                   2409:     } elsif(ref($elem) eq 'HASH') {
                   2410:       $result.=&hashref2str($elem).'&';
                   2411:     } elsif(ref($elem)) {
                   2412:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 2413:     } else {
                   2414:       $result.=&escape($elem).'&';
                   2415:     }
                   2416:   }
                   2417:   $result=~s/\&$//;
1.265     albertel 2418:   $result .= '__END_ARRAY_REF__';
1.204     albertel 2419:   return $result;
                   2420: }
                   2421: 
1.168     albertel 2422: sub hash2str {
1.204     albertel 2423:   my (%hash) = @_;
                   2424:   my $result=&hashref2str(\%hash);
1.265     albertel 2425:   $result=~s/^__HASH_REF__//;
                   2426:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 2427:   return $result;
                   2428: }
                   2429: 
                   2430: sub hashref2str {
                   2431:   my ($hashref)=@_;
1.265     albertel 2432:   my $result='__HASH_REF__';
1.800     albertel 2433:   foreach my $key (sort(keys(%$hashref))) {
                   2434:     if (ref($key) eq 'ARRAY') {
                   2435:       $result.=&arrayref2str($key).'=';
                   2436:     } elsif (ref($key) eq 'HASH') {
                   2437:       $result.=&hashref2str($key).'=';
                   2438:     } elsif (ref($key)) {
1.265     albertel 2439:       $result.='=';
1.800     albertel 2440:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 2441:     } else {
1.800     albertel 2442: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 2443:     }
                   2444: 
1.800     albertel 2445:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   2446:       $result.=&arrayref2str($hashref->{$key}).'&';
                   2447:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   2448:       $result.=&hashref2str($hashref->{$key}).'&';
                   2449:     } elsif(ref($hashref->{$key})) {
1.265     albertel 2450:        $result.='&';
1.800     albertel 2451:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 2452:     } else {
1.800     albertel 2453:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 2454:     }
                   2455:   }
1.168     albertel 2456:   $result=~s/\&$//;
1.265     albertel 2457:   $result .= '__END_HASH_REF__';
1.168     albertel 2458:   return $result;
                   2459: }
                   2460: 
                   2461: sub str2hash {
1.265     albertel 2462:     my ($string)=@_;
                   2463:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   2464:     return %$hash;
                   2465: }
                   2466: 
                   2467: sub str2hashref {
1.168     albertel 2468:   my ($string) = @_;
1.265     albertel 2469: 
                   2470:   my %hash;
                   2471: 
                   2472:   if($string !~ /^__HASH_REF__/) {
                   2473:       if (! ($string eq '' || !defined($string))) {
                   2474: 	  $hash{'error'}='Not hash reference';
                   2475:       }
                   2476:       return (\%hash, $string);
                   2477:   }
                   2478: 
                   2479:   $string =~ s/^__HASH_REF__//;
                   2480: 
                   2481:   while($string !~ /^__END_HASH_REF__/) {
                   2482:       #key
                   2483:       my $key='';
                   2484:       if($string =~ /^__HASH_REF__/) {
                   2485:           ($key, $string)=&str2hashref($string);
                   2486:           if(defined($key->{'error'})) {
                   2487:               $hash{'error'}='Bad data';
                   2488:               return (\%hash, $string);
                   2489:           }
                   2490:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2491:           ($key, $string)=&str2arrayref($string);
                   2492:           if($key->[0] eq 'Array reference error') {
                   2493:               $hash{'error'}='Bad data';
                   2494:               return (\%hash, $string);
                   2495:           }
                   2496:       } else {
                   2497:           $string =~ s/^(.*?)=//;
1.267     albertel 2498: 	  $key=&unescape($1);
1.265     albertel 2499:       }
                   2500:       $string =~ s/^=//;
                   2501: 
                   2502:       #value
                   2503:       my $value='';
                   2504:       if($string =~ /^__HASH_REF__/) {
                   2505:           ($value, $string)=&str2hashref($string);
                   2506:           if(defined($value->{'error'})) {
                   2507:               $hash{'error'}='Bad data';
                   2508:               return (\%hash, $string);
                   2509:           }
                   2510:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2511:           ($value, $string)=&str2arrayref($string);
                   2512:           if($value->[0] eq 'Array reference error') {
                   2513:               $hash{'error'}='Bad data';
                   2514:               return (\%hash, $string);
                   2515:           }
                   2516:       } else {
                   2517: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   2518:       }
                   2519:       $string =~ s/^&//;
                   2520: 
                   2521:       $hash{$key}=$value;
1.204     albertel 2522:   }
1.265     albertel 2523: 
                   2524:   $string =~ s/^__END_HASH_REF__//;
                   2525: 
                   2526:   return (\%hash, $string);
1.204     albertel 2527: }
                   2528: 
                   2529: sub str2array {
1.265     albertel 2530:     my ($string)=@_;
                   2531:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   2532:     return @$array;
                   2533: }
                   2534: 
                   2535: sub str2arrayref {
1.204     albertel 2536:   my ($string) = @_;
1.265     albertel 2537:   my @array;
                   2538: 
                   2539:   if($string !~ /^__ARRAY_REF__/) {
                   2540:       if (! ($string eq '' || !defined($string))) {
                   2541: 	  $array[0]='Array reference error';
                   2542:       }
                   2543:       return (\@array, $string);
                   2544:   }
                   2545: 
                   2546:   $string =~ s/^__ARRAY_REF__//;
                   2547: 
                   2548:   while($string !~ /^__END_ARRAY_REF__/) {
                   2549:       my $value='';
                   2550:       if($string =~ /^__HASH_REF__/) {
                   2551:           ($value, $string)=&str2hashref($string);
                   2552:           if(defined($value->{'error'})) {
                   2553:               $array[0] ='Array reference error';
                   2554:               return (\@array, $string);
                   2555:           }
                   2556:       } elsif($string =~ /^__ARRAY_REF__/) {
                   2557:           ($value, $string)=&str2arrayref($string);
                   2558:           if($value->[0] eq 'Array reference error') {
                   2559:               $array[0] ='Array reference error';
                   2560:               return (\@array, $string);
                   2561:           }
                   2562:       } else {
                   2563: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   2564:       }
                   2565:       $string =~ s/^&//;
                   2566: 
                   2567:       push(@array, $value);
1.191     harris41 2568:   }
1.265     albertel 2569: 
                   2570:   $string =~ s/^__END_ARRAY_REF__//;
                   2571: 
                   2572:   return (\@array, $string);
1.168     albertel 2573: }
                   2574: 
1.167     albertel 2575: # -------------------------------------------------------------------Temp Store
                   2576: 
1.168     albertel 2577: sub tmpreset {
                   2578:   my ($symb,$namespace,$domain,$stuname) = @_;
                   2579:   if (!$symb) {
                   2580:     $symb=&symbread();
1.620     albertel 2581:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2582:   }
                   2583:   $symb=escape($symb);
                   2584: 
1.620     albertel 2585:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 2586:   $namespace=~s/\//\_/g;
                   2587:   $namespace=~s/\W//g;
                   2588: 
1.620     albertel 2589:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2590:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2591:   if ($domain eq 'public' && $stuname eq 'public') {
                   2592:       $stuname=$ENV{'REMOTE_ADDR'};
                   2593:   }
1.168     albertel 2594:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2595:   my %hash;
                   2596:   if (tie(%hash,'GDBM_File',
                   2597: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2598: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2599:     foreach my $key (keys %hash) {
1.180     albertel 2600:       if ($key=~ /:$symb/) {
1.168     albertel 2601: 	delete($hash{$key});
                   2602:       }
                   2603:     }
                   2604:   }
                   2605: }
                   2606: 
1.167     albertel 2607: sub tmpstore {
1.168     albertel 2608:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2609: 
                   2610:   if (!$symb) {
                   2611:     $symb=&symbread();
1.620     albertel 2612:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2613:   }
                   2614:   $symb=escape($symb);
                   2615: 
                   2616:   if (!$namespace) {
                   2617:     # I don't think we would ever want to store this for a course.
                   2618:     # it seems this will only be used if we don't have a course.
1.620     albertel 2619:     #$namespace=$env{'request.course.id'};
1.168     albertel 2620:     #if (!$namespace) {
1.620     albertel 2621:       $namespace=$env{'request.state'};
1.168     albertel 2622:     #}
                   2623:   }
                   2624:   $namespace=~s/\//\_/g;
                   2625:   $namespace=~s/\W//g;
1.620     albertel 2626:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2627:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2628:   if ($domain eq 'public' && $stuname eq 'public') {
                   2629:       $stuname=$ENV{'REMOTE_ADDR'};
                   2630:   }
1.168     albertel 2631:   my $now=time;
                   2632:   my %hash;
                   2633:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2634:   if (tie(%hash,'GDBM_File',
                   2635: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2636: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 2637:     $hash{"version:$symb"}++;
                   2638:     my $version=$hash{"version:$symb"};
                   2639:     my $allkeys=''; 
                   2640:     foreach my $key (keys(%$storehash)) {
                   2641:       $allkeys.=$key.':';
1.591     albertel 2642:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 2643:     }
                   2644:     $hash{"$version:$symb:timestamp"}=$now;
                   2645:     $allkeys.='timestamp';
                   2646:     $hash{"$version:keys:$symb"}=$allkeys;
                   2647:     if (untie(%hash)) {
                   2648:       return 'ok';
                   2649:     } else {
                   2650:       return "error:$!";
                   2651:     }
                   2652:   } else {
                   2653:     return "error:$!";
                   2654:   }
                   2655: }
1.167     albertel 2656: 
1.168     albertel 2657: # -----------------------------------------------------------------Temp Restore
1.167     albertel 2658: 
1.168     albertel 2659: sub tmprestore {
                   2660:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 2661: 
1.168     albertel 2662:   if (!$symb) {
                   2663:     $symb=&symbread();
1.620     albertel 2664:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 2665:   }
                   2666:   $symb=escape($symb);
                   2667: 
1.620     albertel 2668:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 2669: 
1.620     albertel 2670:   if (!$domain) { $domain=$env{'user.domain'}; }
                   2671:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 2672:   if ($domain eq 'public' && $stuname eq 'public') {
                   2673:       $stuname=$ENV{'REMOTE_ADDR'};
                   2674:   }
1.168     albertel 2675:   my %returnhash;
                   2676:   $namespace=~s/\//\_/g;
                   2677:   $namespace=~s/\W//g;
                   2678:   my %hash;
                   2679:   my $path=$perlvar{'lonDaemons'}.'/tmp';
                   2680:   if (tie(%hash,'GDBM_File',
                   2681: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 2682: 	  &GDBM_READER(),0640)) {
1.168     albertel 2683:     my $version=$hash{"version:$symb"};
                   2684:     $returnhash{'version'}=$version;
                   2685:     my $scope;
                   2686:     for ($scope=1;$scope<=$version;$scope++) {
                   2687:       my $vkeys=$hash{"$scope:keys:$symb"};
                   2688:       my @keys=split(/:/,$vkeys);
                   2689:       my $key;
                   2690:       $returnhash{"$scope:keys"}=$vkeys;
                   2691:       foreach $key (@keys) {
1.591     albertel 2692: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   2693: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 2694:       }
                   2695:     }
1.168     albertel 2696:     if (!(untie(%hash))) {
                   2697:       return "error:$!";
                   2698:     }
                   2699:   } else {
                   2700:     return "error:$!";
                   2701:   }
                   2702:   return %returnhash;
1.167     albertel 2703: }
                   2704: 
1.9       www      2705: # ----------------------------------------------------------------------- Store
                   2706: 
                   2707: sub store {
1.124     www      2708:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2709:     my $home='';
                   2710: 
1.168     albertel 2711:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2712: 
1.213     www      2713:     $symb=&symbclean($symb);
1.122     albertel 2714:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2715: 
1.620     albertel 2716:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2717:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2718: 
                   2719:     &devalidate($symb,$stuname,$domain);
1.109     www      2720: 
                   2721:     $symb=escape($symb);
1.187     www      2722:     if (!$namespace) { 
1.620     albertel 2723:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2724:           return ''; 
                   2725:        } 
                   2726:     }
1.620     albertel 2727:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2728: 
                   2729:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2730:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2731: 
1.12      www      2732:     my $namevalue='';
1.800     albertel 2733:     foreach my $key (keys(%$storehash)) {
                   2734:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2735:     }
1.12      www      2736:     $namevalue=~s/\&$//;
1.187     www      2737:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      2738:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      2739: }
                   2740: 
1.47      www      2741: # -------------------------------------------------------------- Critical Store
                   2742: 
                   2743: sub cstore {
1.124     www      2744:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   2745:     my $home='';
                   2746: 
1.168     albertel 2747:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2748: 
1.213     www      2749:     $symb=&symbclean($symb);
1.122     albertel 2750:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      2751: 
1.620     albertel 2752:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2753:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      2754: 
                   2755:     &devalidate($symb,$stuname,$domain);
1.109     www      2756: 
                   2757:     $symb=escape($symb);
1.187     www      2758:     if (!$namespace) { 
1.620     albertel 2759:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      2760:           return ''; 
                   2761:        } 
                   2762:     }
1.620     albertel 2763:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      2764: 
                   2765:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   2766:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 2767: 
1.47      www      2768:     my $namevalue='';
1.800     albertel 2769:     foreach my $key (keys(%$storehash)) {
                   2770:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 2771:     }
1.47      www      2772:     $namevalue=~s/\&$//;
1.187     www      2773:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      2774:     return critical
                   2775:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      2776: }
                   2777: 
1.9       www      2778: # --------------------------------------------------------------------- Restore
                   2779: 
                   2780: sub restore {
1.124     www      2781:     my ($symb,$namespace,$domain,$stuname) = @_;
                   2782:     my $home='';
                   2783: 
1.168     albertel 2784:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      2785: 
1.122     albertel 2786:     if (!$symb) {
                   2787:       unless ($symb=escape(&symbread())) { return ''; }
                   2788:     } else {
1.213     www      2789:       $symb=&escape(&symbclean($symb));
1.122     albertel 2790:     }
1.188     www      2791:     if (!$namespace) { 
1.620     albertel 2792:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      2793:           return ''; 
                   2794:        } 
                   2795:     }
1.620     albertel 2796:     if (!$domain) { $domain=$env{'user.domain'}; }
                   2797:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   2798:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 2799:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   2800: 
1.12      www      2801:     my %returnhash=();
1.800     albertel 2802:     foreach my $line (split(/\&/,$answer)) {
                   2803: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 2804:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 2805:     }
1.75      www      2806:     my $version;
                   2807:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 2808:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2809:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 2810:        }
1.75      www      2811:     }
1.13      www      2812:     return %returnhash;
1.34      www      2813: }
                   2814: 
                   2815: # ---------------------------------------------------------- Course Description
                   2816: 
                   2817: sub coursedescription {
1.731     albertel 2818:     my ($courseid,$args)=@_;
1.34      www      2819:     $courseid=~s/^\///;
1.49      www      2820:     $courseid=~s/\_/\//g;
1.34      www      2821:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 2822:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 2823:     my $normalid=$cdomain.'_'.$cnum;
                   2824:     # need to always cache even if we get errors otherwise we keep 
                   2825:     # trying and trying and trying to get the course description.
                   2826:     my %envhash=();
                   2827:     my %returnhash=();
1.731     albertel 2828:     
                   2829:     my $expiretime=600;
                   2830:     if ($env{'request.course.id'} eq $normalid) {
                   2831: 	$expiretime=120;
                   2832:     }
                   2833: 
                   2834:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   2835:     if (!$args->{'freshen_cache'}
                   2836: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   2837: 	foreach my $key (keys(%env)) {
                   2838: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   2839: 	    my ($setting) = $1;
                   2840: 	    $returnhash{$setting} = $env{$key};
                   2841: 	}
                   2842: 	return %returnhash;
                   2843:     }
                   2844: 
                   2845:     # get the data agin
                   2846:     if (!$args->{'one_time'}) {
                   2847: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   2848:     }
1.811     albertel 2849: 
1.34      www      2850:     if ($chome ne 'no_host') {
1.302     albertel 2851:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 2852:        if (!exists($returnhash{'con_lost'})) {
                   2853:            $returnhash{'home'}= $chome;
                   2854: 	   $returnhash{'domain'} = $cdomain;
                   2855: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  2856:            if (!defined($returnhash{'type'})) {
                   2857:                $returnhash{'type'} = 'Course';
                   2858:            }
1.130     albertel 2859:            while (my ($name,$value) = each %returnhash) {
1.53      www      2860:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 2861:            }
1.270     www      2862:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.34      www      2863:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
1.620     albertel 2864: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
1.60      www      2865:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   2866:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   2867:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      2868:        }
                   2869:     }
1.731     albertel 2870:     if (!$args->{'one_time'}) {
                   2871: 	&appenv(%envhash);
                   2872:     }
1.302     albertel 2873:     return %returnhash;
1.461     www      2874: }
                   2875: 
                   2876: # -------------------------------------------------See if a user is privileged
                   2877: 
                   2878: sub privileged {
                   2879:     my ($username,$domain)=@_;
                   2880:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   2881: 			&homeserver($username,$domain));
                   2882:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
                   2883:     my $now=time;
                   2884:     if ($rolesdump ne '') {
1.800     albertel 2885:         foreach my $entry (split(/&/,$rolesdump)) {
                   2886: 	    if ($entry!~/^rolesdef_/) {
                   2887: 		my ($area,$role)=split(/=/,$entry);
1.461     www      2888: 		$area=~s/\_\w\w$//;
                   2889: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   2890: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   2891: 		    my $active=1;
                   2892: 		    if ($tend) {
                   2893: 			if ($tend<$now) { $active=0; }
                   2894: 		    }
                   2895: 		    if ($tstart) {
                   2896: 			if ($tstart>$now) { $active=0; }
                   2897: 		    }
                   2898: 		    if ($active) { return 1; }
                   2899: 		}
                   2900: 	    }
                   2901: 	}
                   2902:     }
                   2903:     return 0;
1.9       www      2904: }
1.1       albertel 2905: 
1.103     harris41 2906: # -------------------------------------------------------- Get user privileges
1.11      www      2907: 
                   2908: sub rolesinit {
                   2909:     my ($domain,$username,$authhost)=@_;
                   2910:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
1.12      www      2911:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
1.11      www      2912:     my %allroles=();
1.678     raeburn  2913:     my %allgroups=();   
1.11      www      2914:     my $now=time;
1.743     albertel 2915:     my %userroles = ('user.login.time' => $now);
1.678     raeburn  2916:     my $group_privs;
1.11      www      2917: 
                   2918:     if ($rolesdump ne '') {
1.800     albertel 2919:         foreach my $entry (split(/&/,$rolesdump)) {
                   2920: 	  if ($entry!~/^rolesdef_/) {
                   2921:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 2922: 	    $area=~s/\_\w\w$//;
1.678     raeburn  2923:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 2924: 	    if ($role=~/^cr/) { 
1.807     albertel 2925: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   2926: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 2927: 		    ($tend,$tstart)=split('_',$trest);
                   2928: 		} else {
                   2929: 		    $trole=$role;
                   2930: 		}
1.678     raeburn  2931:             } elsif ($role =~ m|^gr/|) {
                   2932:                 ($trole,$tend,$tstart) = split(/_/,$role);
                   2933:                 ($trole,$group_privs) = split(/\//,$trole);
                   2934:                 $group_privs = &unescape($group_privs);
1.587     albertel 2935: 	    } else {
                   2936: 		($trole,$tend,$tstart)=split(/_/,$role);
                   2937: 	    }
1.743     albertel 2938: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   2939: 					 $username);
                   2940: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  2941:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   2942:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      2943:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 2944: 		my $spec=$trole.'.'.$area;
                   2945: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   2946: 		if ($trole =~ /^cr\//) {
1.567     raeburn  2947:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  2948:                 } elsif ($trole eq 'gr') {
                   2949:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 2950: 		} else {
1.567     raeburn  2951:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 2952: 		}
1.12      www      2953:             }
1.662     raeburn  2954:           }
1.191     harris41 2955:         }
1.743     albertel 2956:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   2957:         $userroles{'user.adv'}    = $adv;
                   2958: 	$userroles{'user.author'} = $author;
1.620     albertel 2959:         $env{'user.adv'}=$adv;
1.11      www      2960:     }
1.743     albertel 2961:     return \%userroles;  
1.11      www      2962: }
                   2963: 
1.567     raeburn  2964: sub set_arearole {
                   2965:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   2966: # log the associated role with the area
                   2967:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 2968:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  2969: }
                   2970: 
                   2971: sub custom_roleprivs {
                   2972:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   2973:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   2974:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 2975:     if (&hostname($homsvr) ne '') {
1.567     raeburn  2976:         my ($rdummy,$roledef)=
                   2977:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   2978:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   2979:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   2980:             if (defined($syspriv)) {
                   2981:                 $$allroles{'cm./'}.=':'.$syspriv;
                   2982:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   2983:             }
                   2984:             if ($tdomain ne '') {
                   2985:                 if (defined($dompriv)) {
                   2986:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   2987:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   2988:                 }
                   2989:                 if (($trest ne '') && (defined($coursepriv))) {
                   2990:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   2991:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   2992:                 }
                   2993:             }
                   2994:         }
                   2995:     }
                   2996: }
                   2997: 
1.678     raeburn  2998: sub group_roleprivs {
                   2999:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   3000:     my $access = 1;
                   3001:     my $now = time;
                   3002:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   3003:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   3004:     if ($access) {
1.811     albertel 3005:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  3006:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   3007:     }
                   3008: }
1.567     raeburn  3009: 
                   3010: sub standard_roleprivs {
                   3011:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   3012:     if (defined($pr{$trole.':s'})) {
                   3013:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   3014:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   3015:     }
                   3016:     if ($tdomain ne '') {
                   3017:         if (defined($pr{$trole.':d'})) {
                   3018:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3019:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   3020:         }
                   3021:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   3022:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   3023:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   3024:         }
                   3025:     }
                   3026: }
                   3027: 
                   3028: sub set_userprivs {
1.678     raeburn  3029:     my ($userroles,$allroles,$allgroups) = @_; 
1.567     raeburn  3030:     my $author=0;
                   3031:     my $adv=0;
1.678     raeburn  3032:     my %grouproles = ();
                   3033:     if (keys(%{$allgroups}) > 0) {
                   3034:         foreach my $role (keys %{$allroles}) {
1.681     raeburn  3035:             my ($trole,$area,$sec,$extendedarea);
1.811     albertel 3036:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)-) {
1.678     raeburn  3037:                 $trole = $1;
                   3038:                 $area = $2;
1.681     raeburn  3039:                 $sec = $3;
                   3040:                 $extendedarea = $area.$sec;
                   3041:                 if (exists($$allgroups{$area})) {
                   3042:                     foreach my $group (keys(%{$$allgroups{$area}})) {
                   3043:                         my $spec = $trole.'.'.$extendedarea;
                   3044:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
                   3045:                                                 $$allgroups{$area}{$group};
1.678     raeburn  3046:                     }
                   3047:                 }
                   3048:             }
                   3049:         }
                   3050:     }
1.800     albertel 3051:     foreach my $group (keys(%grouproles)) {
                   3052:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  3053:     }
1.800     albertel 3054:     foreach my $role (keys(%{$allroles})) {
                   3055:         my %thesepriv;
                   3056:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
                   3057:         foreach my $item (split(/:/,$$allroles{$role})) {
                   3058:             if ($item ne '') {
                   3059:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  3060:                 if ($restrictions eq '') {
                   3061:                     $thesepriv{$privilege}='F';
                   3062:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   3063:                     $thesepriv{$privilege}.=$restrictions;
                   3064:                 }
                   3065:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   3066:             }
                   3067:         }
                   3068:         my $thesestr='';
1.800     albertel 3069:         foreach my $priv (keys(%thesepriv)) {
                   3070: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   3071: 	}
                   3072:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  3073:     }
                   3074:     return ($author,$adv);
                   3075: }
                   3076: 
1.12      www      3077: # --------------------------------------------------------------- get interface
                   3078: 
                   3079: sub get {
1.131     albertel 3080:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3081:    my $items='';
1.800     albertel 3082:    foreach my $item (@$storearr) {
                   3083:        $items.=&escape($item).'&';
1.191     harris41 3084:    }
1.12      www      3085:    $items=~s/\&$//;
1.620     albertel 3086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3087:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 3088:    my $uhome=&homeserver($uname,$udomain);
                   3089: 
1.133     albertel 3090:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3091:    my @pairs=split(/\&/,$rep);
1.273     albertel 3092:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   3093:      return @pairs;
                   3094:    }
1.15      www      3095:    my %returnhash=();
1.42      www      3096:    my $i=0;
1.800     albertel 3097:    foreach my $item (@$storearr) {
                   3098:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3099:       $i++;
1.191     harris41 3100:    }
1.15      www      3101:    return %returnhash;
1.27      www      3102: }
                   3103: 
                   3104: # --------------------------------------------------------------- del interface
                   3105: 
                   3106: sub del {
1.133     albertel 3107:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      3108:    my $items='';
1.800     albertel 3109:    foreach my $item (@$storearr) {
                   3110:        $items.=&escape($item).'&';
1.191     harris41 3111:    }
1.27      www      3112:    $items=~s/\&$//;
1.620     albertel 3113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3114:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3115:    my $uhome=&homeserver($uname,$udomain);
                   3116: 
                   3117:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      3118: }
                   3119: 
                   3120: # -------------------------------------------------------------- dump interface
                   3121: 
                   3122: sub dump {
1.755     albertel 3123:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
                   3124:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3125:     if (!$uname) { $uname=$env{'user.name'}; }
                   3126:     my $uhome=&homeserver($uname,$udomain);
                   3127:     if ($regexp) {
                   3128: 	$regexp=&escape($regexp);
                   3129:     } else {
                   3130: 	$regexp='.';
                   3131:     }
                   3132:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3133:     my @pairs=split(/\&/,$rep);
                   3134:     my %returnhash=();
                   3135:     foreach my $item (@pairs) {
                   3136: 	my ($key,$value)=split(/=/,$item,2);
                   3137: 	$key = &unescape($key);
                   3138: 	next if ($key =~ /^error: 2 /);
                   3139: 	$returnhash{$key}=&thaw_unescape($value);
                   3140:     }
                   3141:     return %returnhash;
1.407     www      3142: }
                   3143: 
1.717     albertel 3144: # --------------------------------------------------------- dumpstore interface
                   3145: 
                   3146: sub dumpstore {
                   3147:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 3148:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3149:    if (!$uname) { $uname=$env{'user.name'}; }
                   3150:    my $uhome=&homeserver($uname,$udomain);
                   3151:    if ($regexp) {
                   3152:        $regexp=&escape($regexp);
                   3153:    } else {
                   3154:        $regexp='.';
                   3155:    }
                   3156:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   3157:    my @pairs=split(/\&/,$rep);
                   3158:    my %returnhash=();
                   3159:    foreach my $item (@pairs) {
                   3160:        my ($key,$value)=split(/=/,$item,2);
                   3161:        next if ($key =~ /^error: 2 /);
                   3162:        $returnhash{$key}=&thaw_unescape($value);
                   3163:    }
                   3164:    return %returnhash;
1.717     albertel 3165: }
                   3166: 
1.407     www      3167: # -------------------------------------------------------------- keys interface
                   3168: 
                   3169: sub getkeys {
                   3170:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 3171:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3172:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      3173:    my $uhome=&homeserver($uname,$udomain);
                   3174:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   3175:    my @keyarray=();
1.800     albertel 3176:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  3177:       next if ($key =~ /^error: 2 /);
1.800     albertel 3178:       push(@keyarray,&unescape($key));
1.407     www      3179:    }
                   3180:    return @keyarray;
1.318     matthew  3181: }
                   3182: 
1.319     matthew  3183: # --------------------------------------------------------------- currentdump
                   3184: sub currentdump {
1.328     matthew  3185:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 3186:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   3187:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   3188:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  3189:    my $uhome = &homeserver($sname,$sdom);
                   3190:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  3191:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  3192:    #
1.318     matthew  3193:    my %returnhash=();
1.319     matthew  3194:    #
                   3195:    if ($rep eq "unknown_cmd") { 
                   3196:        # an old lond will not know currentdump
                   3197:        # Do a dump and make it look like a currentdump
1.822     albertel 3198:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  3199:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   3200:        my %hash = @tmp;
                   3201:        @tmp=();
1.424     matthew  3202:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  3203:    } else {
                   3204:        my @pairs=split(/\&/,$rep);
1.800     albertel 3205:        foreach my $pair (@pairs) {
                   3206:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  3207:            my ($symb,$param) = split(/:/,$key);
                   3208:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 3209:                                                         &thaw_unescape($value);
1.319     matthew  3210:        }
1.191     harris41 3211:    }
1.12      www      3212:    return %returnhash;
1.424     matthew  3213: }
                   3214: 
                   3215: sub convert_dump_to_currentdump{
                   3216:     my %hash = %{shift()};
                   3217:     my %returnhash;
                   3218:     # Code ripped from lond, essentially.  The only difference
                   3219:     # here is the unescaping done by lonnet::dump().  Conceivably
                   3220:     # we might run in to problems with parameter names =~ /^v\./
                   3221:     while (my ($key,$value) = each(%hash)) {
                   3222:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 3223: 	$symb  = &unescape($symb);
                   3224: 	$param = &unescape($param);
1.424     matthew  3225:         next if ($v eq 'version' || $symb eq 'keys');
                   3226:         next if (exists($returnhash{$symb}) &&
                   3227:                  exists($returnhash{$symb}->{$param}) &&
                   3228:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   3229:         $returnhash{$symb}->{$param}=$value;
                   3230:         $returnhash{$symb}->{'v.'.$param}=$v;
                   3231:     }
                   3232:     #
                   3233:     # Remove all of the keys in the hashes which keep track of
                   3234:     # the version of the parameter.
                   3235:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   3236:         # use a foreach because we are going to delete from the hash.
                   3237:         foreach my $key (keys(%$param_hash)) {
                   3238:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   3239:         }
                   3240:     }
                   3241:     return \%returnhash;
1.12      www      3242: }
                   3243: 
1.627     albertel 3244: # ------------------------------------------------------ critical inc interface
                   3245: 
                   3246: sub cinc {
                   3247:     return &inc(@_,'critical');
                   3248: }
                   3249: 
1.449     matthew  3250: # --------------------------------------------------------------- inc interface
                   3251: 
                   3252: sub inc {
1.627     albertel 3253:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 3254:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3255:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  3256:     my $uhome=&homeserver($uname,$udomain);
                   3257:     my $items='';
                   3258:     if (! ref($store)) {
                   3259:         # got a single value, so use that instead
                   3260:         $items = &escape($store).'=&';
                   3261:     } elsif (ref($store) eq 'SCALAR') {
                   3262:         $items = &escape($$store).'=&';        
                   3263:     } elsif (ref($store) eq 'ARRAY') {
                   3264:         $items = join('=&',map {&escape($_);} @{$store});
                   3265:     } elsif (ref($store) eq 'HASH') {
                   3266:         while (my($key,$value) = each(%{$store})) {
                   3267:             $items.= &escape($key).'='.&escape($value).'&';
                   3268:         }
                   3269:     }
                   3270:     $items=~s/\&$//;
1.627     albertel 3271:     if ($critical) {
                   3272: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3273:     } else {
                   3274: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   3275:     }
1.449     matthew  3276: }
                   3277: 
1.12      www      3278: # --------------------------------------------------------------- put interface
                   3279: 
                   3280: sub put {
1.134     albertel 3281:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3282:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3283:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3284:    my $uhome=&homeserver($uname,$udomain);
1.12      www      3285:    my $items='';
1.800     albertel 3286:    foreach my $item (keys(%$storehash)) {
                   3287:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3288:    }
1.12      www      3289:    $items=~s/\&$//;
1.134     albertel 3290:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      3291: }
                   3292: 
1.631     albertel 3293: # ------------------------------------------------------------ newput interface
                   3294: 
                   3295: sub newput {
                   3296:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   3297:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3298:    if (!$uname) { $uname=$env{'user.name'}; }
                   3299:    my $uhome=&homeserver($uname,$udomain);
                   3300:    my $items='';
                   3301:    foreach my $key (keys(%$storehash)) {
                   3302:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   3303:    }
                   3304:    $items=~s/\&$//;
                   3305:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   3306: }
                   3307: 
                   3308: # ---------------------------------------------------------  putstore interface
                   3309: 
1.524     raeburn  3310: sub putstore {
1.715     albertel 3311:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 3312:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3313:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  3314:    my $uhome=&homeserver($uname,$udomain);
                   3315:    my $items='';
1.715     albertel 3316:    foreach my $key (keys(%$storehash)) {
                   3317:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  3318:    }
1.715     albertel 3319:    $items=~s/\&$//;
1.716     albertel 3320:    my $esc_symb=&escape($symb);
                   3321:    my $esc_v=&escape($version);
1.715     albertel 3322:    my $reply =
1.716     albertel 3323:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 3324: 	      $uhome);
                   3325:    if ($reply eq 'unknown_cmd') {
1.716     albertel 3326:        # gfall back to way things use to be done
1.715     albertel 3327:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   3328: 			    $uname);
1.524     raeburn  3329:    }
1.715     albertel 3330:    return $reply;
                   3331: }
                   3332: 
                   3333: sub old_putstore {
1.716     albertel 3334:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   3335:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3336:     if (!$uname) { $uname=$env{'user.name'}; }
                   3337:     my $uhome=&homeserver($uname,$udomain);
                   3338:     my %newstorehash;
1.800     albertel 3339:     foreach my $item (keys(%$storehash)) {
                   3340: 	my $key = $version.':'.&escape($symb).':'.$item;
                   3341: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 3342:     }
                   3343:     my $items='';
                   3344:     my %allitems = ();
1.800     albertel 3345:     foreach my $item (keys(%newstorehash)) {
                   3346: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 3347: 	    my $key = $1.':keys:'.$2;
                   3348: 	    $allitems{$key} .= $3.':';
                   3349: 	}
1.800     albertel 3350: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 3351:     }
1.800     albertel 3352:     foreach my $item (keys(%allitems)) {
                   3353: 	$allitems{$item} =~ s/\:$//;
                   3354: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 3355:     }
                   3356:     $items=~s/\&$//;
                   3357:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  3358: }
                   3359: 
1.47      www      3360: # ------------------------------------------------------ critical put interface
                   3361: 
                   3362: sub cput {
1.134     albertel 3363:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 3364:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3365:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 3366:    my $uhome=&homeserver($uname,$udomain);
1.47      www      3367:    my $items='';
1.800     albertel 3368:    foreach my $item (keys(%$storehash)) {
                   3369:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 3370:    }
1.47      www      3371:    $items=~s/\&$//;
1.134     albertel 3372:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3373: }
                   3374: 
                   3375: # -------------------------------------------------------------- eget interface
                   3376: 
                   3377: sub eget {
1.133     albertel 3378:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      3379:    my $items='';
1.800     albertel 3380:    foreach my $item (@$storearr) {
                   3381:        $items.=&escape($item).'&';
1.191     harris41 3382:    }
1.12      www      3383:    $items=~s/\&$//;
1.620     albertel 3384:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   3385:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 3386:    my $uhome=&homeserver($uname,$udomain);
                   3387:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      3388:    my @pairs=split(/\&/,$rep);
                   3389:    my %returnhash=();
1.42      www      3390:    my $i=0;
1.800     albertel 3391:    foreach my $item (@$storearr) {
                   3392:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      3393:       $i++;
1.191     harris41 3394:    }
1.12      www      3395:    return %returnhash;
                   3396: }
                   3397: 
1.667     albertel 3398: # ------------------------------------------------------------ tmpput interface
                   3399: sub tmpput {
1.802     raeburn  3400:     my ($storehash,$server,$context)=@_;
1.667     albertel 3401:     my $items='';
1.800     albertel 3402:     foreach my $item (keys(%$storehash)) {
                   3403: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 3404:     }
                   3405:     $items=~s/\&$//;
1.802     raeburn  3406:     if (defined($context)) {
                   3407:         $items .= ':'.&escape($context);
                   3408:     }
1.667     albertel 3409:     return &reply("tmpput:$items",$server);
                   3410: }
                   3411: 
                   3412: # ------------------------------------------------------------ tmpget interface
                   3413: sub tmpget {
1.688     albertel 3414:     my ($token,$server)=@_;
                   3415:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3416:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 3417:     my %returnhash;
                   3418:     foreach my $item (split(/\&/,$rep)) {
                   3419: 	my ($key,$value)=split(/=/,$item);
                   3420: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   3421:     }
                   3422:     return %returnhash;
                   3423: }
                   3424: 
1.688     albertel 3425: # ------------------------------------------------------------ tmpget interface
                   3426: sub tmpdel {
                   3427:     my ($token,$server)=@_;
                   3428:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   3429:     return &reply("tmpdel:$token",$server);
                   3430: }
                   3431: 
1.765     albertel 3432: # -------------------------------------------------- portfolio access checking
                   3433: 
                   3434: sub portfolio_access {
1.766     albertel 3435:     my ($requrl) = @_;
1.765     albertel 3436:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   3437:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  3438:     if ($result) {
                   3439:         my %setters;
                   3440:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3441:             my ($startblock,$endblock) =
                   3442:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   3443:             if ($startblock && $endblock) {
                   3444:                 return 'B';
                   3445:             }
                   3446:         } else {
                   3447:             my ($startblock,$endblock) =
                   3448:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   3449:             if ($startblock && $endblock) {
                   3450:                 return 'B';
                   3451:             }
                   3452:         }
                   3453:     }
1.765     albertel 3454:     if ($result eq 'ok') {
1.766     albertel 3455:        return 'F';
1.765     albertel 3456:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 3457:        return 'A';
1.765     albertel 3458:     }
1.766     albertel 3459:     return '';
1.765     albertel 3460: }
                   3461: 
                   3462: sub get_portfolio_access {
1.767     albertel 3463:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   3464: 
                   3465:     if (!ref($access_hash)) {
                   3466: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   3467: 	my %access_controls = &get_access_controls($current_perms,$group,
                   3468: 						   $file_name);
                   3469: 	$access_hash = $access_controls{$file_name};
                   3470:     }
                   3471: 
1.765     albertel 3472:     my ($public,$guest,@domains,@users,@courses,@groups);
                   3473:     my $now = time;
                   3474:     if (ref($access_hash) eq 'HASH') {
                   3475:         foreach my $key (keys(%{$access_hash})) {
                   3476:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   3477:             if ($start > $now) {
                   3478:                 next;
                   3479:             }
                   3480:             if ($end && $end<$now) {
                   3481:                 next;
                   3482:             }
                   3483:             if ($scope eq 'public') {
                   3484:                 $public = $key;
                   3485:                 last;
                   3486:             } elsif ($scope eq 'guest') {
                   3487:                 $guest = $key;
                   3488:             } elsif ($scope eq 'domains') {
                   3489:                 push(@domains,$key);
                   3490:             } elsif ($scope eq 'users') {
                   3491:                 push(@users,$key);
                   3492:             } elsif ($scope eq 'course') {
                   3493:                 push(@courses,$key);
                   3494:             } elsif ($scope eq 'group') {
                   3495:                 push(@groups,$key);
                   3496:             }
                   3497:         }
                   3498:         if ($public) {
                   3499:             return 'ok';
                   3500:         }
                   3501:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   3502:             if ($guest) {
                   3503:                 return $guest;
                   3504:             }
                   3505:         } else {
                   3506:             if (@domains > 0) {
                   3507:                 foreach my $domkey (@domains) {
                   3508:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   3509:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   3510:                             return 'ok';
                   3511:                         }
                   3512:                     }
                   3513:                 }
                   3514:             }
                   3515:             if (@users > 0) {
                   3516:                 foreach my $userkey (@users) {
                   3517:                     if (exists($access_hash->{$userkey}{'users'}{$env{'user.name'}.':'.$env{'user.domain'}})) {
                   3518:                         return 'ok';
                   3519:                     }
                   3520:                 }
                   3521:             }
                   3522:             my %roleshash;
                   3523:             my @courses_and_groups = @courses;
                   3524:             push(@courses_and_groups,@groups); 
                   3525:             if (@courses_and_groups > 0) {
                   3526:                 my (%allgroups,%allroles); 
                   3527:                 my ($start,$end,$role,$sec,$group);
                   3528:                 foreach my $envkey (%env) {
1.811     albertel 3529:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3530:                         my $cid = $2.'_'.$3; 
                   3531:                         if ($1 eq 'gr') {
                   3532:                             $group = $4;
                   3533:                             $allgroups{$cid}{$group} = $env{$envkey};
                   3534:                         } else {
                   3535:                             if ($4 eq '') {
                   3536:                                 $sec = 'none';
                   3537:                             } else {
                   3538:                                 $sec = $4;
                   3539:                             }
                   3540:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3541:                         }
1.811     albertel 3542:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 3543:                         my $cid = $2.'_'.$3;
                   3544:                         if ($4 eq '') {
                   3545:                             $sec = 'none';
                   3546:                         } else {
                   3547:                             $sec = $4;
                   3548:                         }
                   3549:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   3550:                     }
                   3551:                 }
                   3552:                 if (keys(%allroles) == 0) {
                   3553:                     return;
                   3554:                 }
                   3555:                 foreach my $key (@courses_and_groups) {
                   3556:                     my %content = %{$$access_hash{$key}};
                   3557:                     my $cnum = $content{'number'};
                   3558:                     my $cdom = $content{'domain'};
                   3559:                     my $cid = $cdom.'_'.$cnum;
                   3560:                     if (!exists($allroles{$cid})) {
                   3561:                         next;
                   3562:                     }    
                   3563:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   3564:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   3565:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   3566:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   3567:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   3568:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   3569:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   3570:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   3571:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   3572:                                         if (grep/^all$/,@sections) {
                   3573:                                             return 'ok';
                   3574:                                         } else {
                   3575:                                             if (grep/^$sec$/,@sections) {
                   3576:                                                 return 'ok';
                   3577:                                             }
                   3578:                                         }
                   3579:                                     }
                   3580:                                 }
                   3581:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   3582:                                     if (grep/^none$/,@groups) {
                   3583:                                         return 'ok';
                   3584:                                     }
                   3585:                                 } else {
                   3586:                                     if (grep/^all$/,@groups) {
                   3587:                                         return 'ok';
                   3588:                                     } 
                   3589:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   3590:                                         if (grep/^$group$/,@groups) {
                   3591:                                             return 'ok';
                   3592:                                         }
                   3593:                                     }
                   3594:                                 } 
                   3595:                             }
                   3596:                         }
                   3597:                     }
                   3598:                 }
                   3599:             }
                   3600:             if ($guest) {
                   3601:                 return $guest;
                   3602:             }
                   3603:         }
                   3604:     }
                   3605:     return;
                   3606: }
                   3607: 
                   3608: sub course_group_datechecker {
                   3609:     my ($dates,$now,$status) = @_;
                   3610:     my ($start,$end) = split(/\./,$dates);
                   3611:     if (!$start && !$end) {
                   3612:         return 'ok';
                   3613:     }
                   3614:     if (grep/^active$/,@{$status}) {
                   3615:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   3616:             return 'ok';
                   3617:         }
                   3618:     }
                   3619:     if (grep/^previous$/,@{$status}) {
                   3620:         if ($end > $now ) {
                   3621:             return 'ok';
                   3622:         }
                   3623:     }
                   3624:     if (grep/^future$/,@{$status}) {
                   3625:         if ($start > $now) {
                   3626:             return 'ok';
                   3627:         }
                   3628:     }
                   3629:     return; 
                   3630: }
                   3631: 
                   3632: sub parse_portfolio_url {
                   3633:     my ($url) = @_;
                   3634: 
                   3635:     my ($type,$udom,$unum,$group,$file_name);
                   3636:     
1.823     albertel 3637:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 3638: 	$type = 1;
                   3639:         $udom = $1;
                   3640:         $unum = $2;
                   3641:         $file_name = $3;
1.823     albertel 3642:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 3643: 	$type = 2;
                   3644:         $udom = $1;
                   3645:         $unum = $2;
                   3646:         $group = $3;
                   3647:         $file_name = $3.'/'.$4;
                   3648:     }
                   3649:     if (wantarray) {
                   3650: 	return ($type,$udom,$unum,$file_name,$group);
                   3651:     }
                   3652:     return $type;
                   3653: }
                   3654: 
                   3655: sub is_portfolio_url {
                   3656:     my ($url) = @_;
                   3657:     return scalar(&parse_portfolio_url($url));
                   3658: }
                   3659: 
1.798     raeburn  3660: sub is_portfolio_file {
                   3661:     my ($file) = @_;
1.820     raeburn  3662:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  3663:         return 1;
                   3664:     }
                   3665:     return;
                   3666: }
                   3667: 
                   3668: 
1.341     www      3669: # ---------------------------------------------- Custom access rule evaluation
                   3670: 
                   3671: sub customaccess {
                   3672:     my ($priv,$uri)=@_;
1.807     albertel 3673:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      3674:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 3675:     $udom = &LONCAPA::clean_domain($udom);
                   3676:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      3677:     my $access=0;
1.800     albertel 3678:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
                   3679: 	my ($effect,$realm,$role)=split(/\:/,$right);
1.343     www      3680:         if ($role) {
                   3681: 	   if ($role ne $urole) { next; }
                   3682:         }
1.800     albertel 3683:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   3684:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
1.343     www      3685:             if ($tdom) {
                   3686: 		if ($tdom ne $udom) { next; }
                   3687:             }
                   3688:             if ($tcrs) {
                   3689: 		if ($tcrs ne $ucrs) { next; }
                   3690:             }
                   3691:             if ($tsec) {
                   3692: 		if ($tsec ne $usec) { next; }
                   3693:             }
                   3694:             $access=($effect eq 'allow');
                   3695:             last;
1.342     www      3696:         }
1.402     bowersj2 3697: 	if ($realm eq '' && $role eq '') {
                   3698:             $access=($effect eq 'allow');
                   3699: 	}
1.341     www      3700:     }
                   3701:     return $access;
                   3702: }
                   3703: 
1.103     harris41 3704: # ------------------------------------------------- Check for a user privilege
1.12      www      3705: 
                   3706: sub allowed {
1.810     raeburn  3707:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 3708:     my $ver_orguri=$uri;
1.439     www      3709:     $uri=&deversion($uri);
1.152     www      3710:     my $orguri=$uri;
1.52      www      3711:     $uri=&declutter($uri);
1.809     raeburn  3712: 
1.810     raeburn  3713:     if ($priv eq 'evb') {
                   3714: # Evade communication block restrictions for specified role in a course
                   3715:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   3716:             return $1;
                   3717:         } else {
                   3718:             return;
                   3719:         }
                   3720:     }
                   3721: 
1.620     albertel 3722:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      3723: # Free bre access to adm and meta resources
1.775     albertel 3724:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 3725: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   3726: 	&& ($priv eq 'bre')) {
1.14      www      3727: 	return 'F';
1.159     www      3728:     }
                   3729: 
1.545     banghart 3730: # Free bre access to user's own portfolio contents
1.714     raeburn  3731:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  3732:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  3733: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  3734:         my %setters;
                   3735:         my ($startblock,$endblock) = 
                   3736:             &Apache::loncommon::blockcheck(\%setters,'port');
                   3737:         if ($startblock && $endblock) {
                   3738:             return 'B';
                   3739:         } else {
                   3740:             return 'F';
                   3741:         }
1.545     banghart 3742:     }
                   3743: 
1.762     raeburn  3744: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  3745:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   3746:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   3747:         if (exists($env{'request.course.id'})) {
                   3748:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3749:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3750:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   3751:                 my $courseprivid=$env{'request.course.id'};
                   3752:                 $courseprivid=~s/\_/\//;
                   3753:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   3754:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   3755:                     return $1; 
1.762     raeburn  3756:                 } else {
                   3757:                     if ($env{'request.course.sec'}) {
                   3758:                         $courseprivid.='/'.$env{'request.course.sec'};
                   3759:                     }
                   3760:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   3761:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   3762:                         return $2;
                   3763:                     }
1.714     raeburn  3764:                 }
                   3765:             }
                   3766:         }
                   3767:     }
                   3768: 
1.159     www      3769: # Free bre to public access
                   3770: 
                   3771:     if ($priv eq 'bre') {
1.238     www      3772:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 3773: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      3774:            return 'F'; 
                   3775:         }
1.238     www      3776:         if ($copyright eq 'priv') {
                   3777:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3778: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      3779: 		return '';
                   3780:             }
                   3781:         }
                   3782:         if ($copyright eq 'domain') {
                   3783:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 3784: 	    unless (($env{'user.domain'} eq $1) ||
                   3785:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      3786: 		return '';
                   3787:             }
1.262     matthew  3788:         }
1.620     albertel 3789:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  3790:             # Library role, so allow browsing of resources in this domain.
                   3791:             return 'F';
1.238     www      3792:         }
1.341     www      3793:         if ($copyright eq 'custom') {
                   3794: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   3795:         }
1.14      www      3796:     }
1.264     matthew  3797:     # Domain coordinator is trying to create a course
1.620     albertel 3798:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  3799:         # uri is the requested domain in this case.
                   3800:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  3801:         # a role of dc for the domain in question.
1.620     albertel 3802:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  3803:     }
1.29      www      3804: 
1.52      www      3805:     my $thisallowed='';
                   3806:     my $statecond=0;
                   3807:     my $courseprivid='';
                   3808: 
                   3809: # Course
                   3810: 
1.620     albertel 3811:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3812:        $thisallowed.=$1;
                   3813:     }
1.29      www      3814: 
1.52      www      3815: # Domain
                   3816: 
1.620     albertel 3817:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 3818:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3819:        $thisallowed.=$1;
                   3820:     }
1.52      www      3821: 
                   3822: # Course: uri itself is a course
1.66      www      3823:     my $courseuri=$uri;
                   3824:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      3825:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      3826: 
1.620     albertel 3827:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 3828:        =~/\Q$priv\E\&([^\:]*)/) {
1.12      www      3829:        $thisallowed.=$1;
                   3830:     }
1.29      www      3831: 
1.665     albertel 3832: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 3833: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 3834:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 3835: 	$thisallowed='';
1.671     raeburn  3836:         my ($match)=&is_on_map($uri);
                   3837:         if ($match) {
                   3838:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   3839:                   =~/\Q$priv\E\&([^\:]*)/) {
                   3840:                 $thisallowed.=$1;
                   3841:             }
                   3842:         } else {
1.705     albertel 3843:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  3844:             if ($refuri) {
                   3845:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  3846:                     $thisallowed='F';
1.671     raeburn  3847:                 } else {
                   3848:                     $refuri=&declutter($refuri);
                   3849:                     my ($match) = &is_on_map($refuri);
                   3850:                     if ($match) {
                   3851:                         $thisallowed='F';
                   3852:                     }
1.669     raeburn  3853:                 }
1.671     raeburn  3854:             }
                   3855:         }
1.314     www      3856:     }
1.492     albertel 3857: 
1.766     albertel 3858:     if ($priv eq 'bre'
                   3859: 	&& $thisallowed ne 'F' 
                   3860: 	&& $thisallowed ne '2'
                   3861: 	&& &is_portfolio_url($uri)) {
                   3862: 	$thisallowed = &portfolio_access($uri);
                   3863:     }
                   3864:     
1.52      www      3865: # Full access at system, domain or course-wide level? Exit.
1.29      www      3866: 
                   3867:     if ($thisallowed=~/F/) {
                   3868: 	return 'F';
                   3869:     }
                   3870: 
1.52      www      3871: # If this is generating or modifying users, exit with special codes
1.29      www      3872: 
1.643     www      3873:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   3874: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 3875: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      3876: # no author name given, so this just checks on the general right to make a co-author in this domain
                   3877: 	    unless ($auname) { return $thisallowed; }
                   3878: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 3879: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   3880: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   3881: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   3882: 	}
1.52      www      3883: 	return $thisallowed;
                   3884:     }
                   3885: #
1.103     harris41 3886: # Gathered so far: system, domain and course wide privileges
1.52      www      3887: #
                   3888: # Course: See if uri or referer is an individual resource that is part of 
                   3889: # the course
                   3890: 
1.620     albertel 3891:     if ($env{'request.course.id'}) {
1.232     www      3892: 
1.620     albertel 3893:        $courseprivid=$env{'request.course.id'};
                   3894:        if ($env{'request.course.sec'}) {
                   3895:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      3896:        }
                   3897:        $courseprivid=~s/\_/\//;
                   3898:        my $checkreferer=1;
1.232     www      3899:        my ($match,$cond)=&is_on_map($uri);
                   3900:        if ($match) {
                   3901:            $statecond=$cond;
1.620     albertel 3902:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3903:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3904:                $thisallowed.=$1;
                   3905:                $checkreferer=0;
                   3906:            }
1.29      www      3907:        }
1.83      www      3908:        
1.148     www      3909:        if ($checkreferer) {
1.620     albertel 3910: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      3911:             unless ($refuri) {
1.800     albertel 3912:                 foreach my $key (keys(%env)) {
                   3913: 		    if ($key=~/^httpref\..*\*/) {
                   3914: 			my $pattern=$key;
1.156     www      3915:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      3916:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   3917:                         $pattern=~s/\//\\\//g;
1.152     www      3918:                         if ($orguri=~/$pattern/) {
1.800     albertel 3919: 			    $refuri=$env{$key};
1.148     www      3920:                         }
                   3921:                     }
1.191     harris41 3922:                 }
1.148     www      3923:             }
1.232     www      3924: 
1.148     www      3925:          if ($refuri) { 
1.152     www      3926: 	  $refuri=&declutter($refuri);
1.232     www      3927:           my ($match,$cond)=&is_on_map($refuri);
                   3928:             if ($match) {
                   3929:               my $refstatecond=$cond;
1.620     albertel 3930:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 3931:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      3932:                   $thisallowed.=$1;
1.53      www      3933:                   $uri=$refuri;
                   3934:                   $statecond=$refstatecond;
1.52      www      3935:               }
                   3936:           }
1.148     www      3937:         }
1.29      www      3938:        }
1.52      www      3939:    }
1.29      www      3940: 
1.52      www      3941: #
1.103     harris41 3942: # Gathered now: all privileges that could apply, and condition number
1.52      www      3943: # 
                   3944: #
                   3945: # Full or no access?
                   3946: #
1.29      www      3947: 
1.52      www      3948:     if ($thisallowed=~/F/) {
                   3949: 	return 'F';
                   3950:     }
1.29      www      3951: 
1.52      www      3952:     unless ($thisallowed) {
                   3953:         return '';
                   3954:     }
1.29      www      3955: 
1.52      www      3956: # Restrictions exist, deal with them
                   3957: #
                   3958: #   C:according to course preferences
                   3959: #   R:according to resource settings
                   3960: #   L:unless locked
                   3961: #   X:according to user session state
                   3962: #
                   3963: 
                   3964: # Possibly locked functionality, check all courses
1.54      www      3965: # Locks might take effect only after 10 minutes cache expiration for other
                   3966: # courses, and 2 minutes for current course
1.52      www      3967: 
                   3968:     my $envkey;
                   3969:     if ($thisallowed=~/L/) {
1.620     albertel 3970:         foreach $envkey (keys %env) {
1.54      www      3971:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   3972:                my $courseid=$2;
                   3973:                my $roleid=$1.'.'.$2;
1.92      www      3974:                $courseid=~s/^\///;
1.54      www      3975:                my $expiretime=600;
1.620     albertel 3976:                if ($env{'request.role'} eq $roleid) {
1.54      www      3977: 		  $expiretime=120;
                   3978:                }
                   3979: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   3980:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 3981:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 3982: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      3983:                }
1.620     albertel 3984:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3985:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   3986: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   3987:                        &log($env{'user.domain'},$env{'user.name'},
                   3988:                             $env{'user.home'},
1.57      www      3989:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      3990:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 3991:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      3992: 		       return '';
                   3993:                    }
                   3994:                }
1.620     albertel 3995:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   3996:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   3997: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   3998:                        &log($env{'user.domain'},$env{'user.name'},
                   3999:                             $env{'user.home'},
1.57      www      4000:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      4001:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 4002:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      4003: 		       return '';
                   4004:                    }
                   4005:                }
                   4006: 	   }
1.29      www      4007:        }
1.52      www      4008:     }
                   4009:    
                   4010: #
                   4011: # Rest of the restrictions depend on selected course
                   4012: #
                   4013: 
1.620     albertel 4014:     unless ($env{'request.course.id'}) {
1.766     albertel 4015: 	if ($thisallowed eq 'A') {
                   4016: 	    return 'A';
1.814     raeburn  4017:         } elsif ($thisallowed eq 'B') {
                   4018:             return 'B';
1.766     albertel 4019: 	} else {
                   4020: 	    return '1';
                   4021: 	}
1.52      www      4022:     }
1.29      www      4023: 
1.52      www      4024: #
                   4025: # Now user is definitely in a course
                   4026: #
1.53      www      4027: 
                   4028: 
                   4029: # Course preferences
                   4030: 
                   4031:    if ($thisallowed=~/C/) {
1.620     albertel 4032:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   4033:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   4034:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 4035: 	   =~/\Q$rolecode\E/) {
1.689     albertel 4036: 	   if ($priv ne 'pch') { 
                   4037: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4038: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   4039: 			$env{'request.course.id'});
                   4040: 	   }
1.237     www      4041:            return '';
                   4042:        }
                   4043: 
1.620     albertel 4044:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 4045: 	   =~/\Q$unamedom\E/) {
1.689     albertel 4046: 	   if ($priv ne 'pch') { 
                   4047: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   4048: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   4049: 			$env{'request.course.id'});
                   4050: 	   }
1.54      www      4051:            return '';
                   4052:        }
1.53      www      4053:    }
                   4054: 
                   4055: # Resource preferences
                   4056: 
                   4057:    if ($thisallowed=~/R/) {
1.620     albertel 4058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 4059:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.689     albertel 4060: 	   if ($priv ne 'pch') { 
                   4061: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   4062: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   4063: 	   }
                   4064: 	   return '';
1.54      www      4065:        }
1.53      www      4066:    }
1.30      www      4067: 
1.246     www      4068: # Restricted by state or randomout?
1.30      www      4069: 
1.52      www      4070:    if ($thisallowed=~/X/) {
1.620     albertel 4071:       if ($env{'acc.randomout'}) {
1.579     albertel 4072: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 4073:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      4074:             return ''; 
                   4075:          }
1.247     www      4076:       }
                   4077:       if (&condval($statecond)) {
1.52      www      4078: 	 return '2';
                   4079:       } else {
                   4080:          return '';
                   4081:       }
                   4082:    }
1.30      www      4083: 
1.766     albertel 4084:     if ($thisallowed eq 'A') {
                   4085: 	return 'A';
1.814     raeburn  4086:     } elsif ($thisallowed eq 'B') {
                   4087:         return 'B';
1.766     albertel 4088:     }
1.52      www      4089:    return 'F';
1.232     www      4090: }
                   4091: 
1.710     albertel 4092: sub split_uri_for_cond {
                   4093:     my $uri=&deversion(&declutter(shift));
                   4094:     my @uriparts=split(/\//,$uri);
                   4095:     my $filename=pop(@uriparts);
                   4096:     my $pathname=join('/',@uriparts);
                   4097:     return ($pathname,$filename);
                   4098: }
1.232     www      4099: # --------------------------------------------------- Is a resource on the map?
                   4100: 
                   4101: sub is_on_map {
1.710     albertel 4102:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 4103:     #Trying to find the conditional for the file
1.620     albertel 4104:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 4105: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      4106:     if ($match) {
1.289     bowersj2 4107: 	return (1,$1);
                   4108:     } else {
1.434     www      4109: 	return (0,0);
1.289     bowersj2 4110:     }
1.12      www      4111: }
                   4112: 
1.427     www      4113: # --------------------------------------------------------- Get symb from alias
                   4114: 
                   4115: sub get_symb_from_alias {
                   4116:     my $symb=shift;
                   4117:     my ($map,$resid,$url)=&decode_symb($symb);
                   4118: # Already is a symb
                   4119:     if ($url) { return $symb; }
                   4120: # Must be an alias
                   4121:     my $aliassymb='';
                   4122:     my %bighash;
1.620     albertel 4123:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      4124:                             &GDBM_READER(),0640)) {
                   4125:         my $rid=$bighash{'mapalias_'.$symb};
                   4126: 	if ($rid) {
                   4127: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 4128: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   4129: 				    $resid,$bighash{'src_'.$rid});
1.427     www      4130: 	}
                   4131:         untie %bighash;
                   4132:     }
                   4133:     return $aliassymb;
                   4134: }
                   4135: 
1.12      www      4136: # ----------------------------------------------------------------- Define Role
                   4137: 
                   4138: sub definerole {
                   4139:   if (allowed('mcr','/')) {
                   4140:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 4141:     foreach my $role (split(':',$sysrole)) {
                   4142: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4143:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   4144:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   4145: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4146:                return "refused:s:$crole&$cqual"; 
                   4147:             }
                   4148:         }
1.191     harris41 4149:     }
1.800     albertel 4150:     foreach my $role (split(':',$domrole)) {
                   4151: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4152:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   4153:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   4154: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      4155:                return "refused:d:$crole&$cqual"; 
                   4156:             }
                   4157:         }
1.191     harris41 4158:     }
1.800     albertel 4159:     foreach my $role (split(':',$courole)) {
                   4160: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 4161:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   4162:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   4163: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      4164:                return "refused:c:$crole&$cqual"; 
                   4165:             }
                   4166:         }
1.191     harris41 4167:     }
1.620     albertel 4168:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   4169:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4170: 	        "rolesdef_$rolename=".
                   4171:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 4172:     return reply($command,$env{'user.home'});
1.12      www      4173:   } else {
                   4174:     return 'refused';
                   4175:   }
1.105     harris41 4176: }
                   4177: 
                   4178: # ---------------- Make a metadata query against the network of library servers
                   4179: 
                   4180: sub metadata_query {
1.244     matthew  4181:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 4182:     my %rhash;
1.845     albertel 4183:     my %libserv = &all_library();
1.244     matthew  4184:     my @server_list = (defined($server_array) ? @$server_array
                   4185:                                               : keys(%libserv) );
                   4186:     for my $server (@server_list) {
1.118     harris41 4187: 	unless ($custom or $customshow) {
                   4188: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   4189: 	    $rhash{$server}=$reply;
                   4190: 	}
                   4191: 	else {
                   4192: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   4193: 			     &escape($custom).':'.&escape($customshow),
                   4194: 			     $server);
                   4195: 	    $rhash{$server}=$reply;
                   4196: 	}
1.112     harris41 4197:     }
1.118     harris41 4198:     return \%rhash;
1.240     www      4199: }
                   4200: 
                   4201: # ----------------------------------------- Send log queries and wait for reply
                   4202: 
                   4203: sub log_query {
                   4204:     my ($uname,$udom,$query,%filters)=@_;
                   4205:     my $uhome=&homeserver($uname,$udom);
                   4206:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 4207:     my $uhost=&hostname($uhome);
1.800     albertel 4208:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      4209:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   4210:                        $uhome);
1.479     albertel 4211:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      4212:     return get_query_reply($queryid);
                   4213: }
                   4214: 
1.818     raeburn  4215: # -------------------------- Update MySQL table for portfolio file
                   4216: 
                   4217: sub update_portfolio_table {
1.821     raeburn  4218:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.818     raeburn  4219:     my $homeserver = &homeserver($uname,$udom);
                   4220:     my $queryid=
1.821     raeburn  4221:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   4222:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  4223:     my $reply = &get_query_reply($queryid);
                   4224:     return $reply;
                   4225: }
                   4226: 
1.508     raeburn  4227: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  4228: 
                   4229: sub fetch_enrollment_query {
1.511     raeburn  4230:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  4231:     my $homeserver;
1.547     raeburn  4232:     my $maxtries = 1;
1.508     raeburn  4233:     if ($context eq 'automated') {
                   4234:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  4235:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  4236:     } else {
                   4237:         $homeserver = &homeserver($cnum,$dom);
                   4238:     }
1.838     albertel 4239:     my $host=&hostname($homeserver);
1.506     raeburn  4240:     my $cmd = '';
1.800     albertel 4241:     foreach my $affiliate (keys %{$affiliatesref}) {
                   4242:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  4243:     }
                   4244:     $cmd =~ s/%%$//;
                   4245:     $cmd = &escape($cmd);
                   4246:     my $query = 'fetchenrollment';
1.620     albertel 4247:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  4248:     unless ($queryid=~/^\Q$host\E\_/) { 
                   4249:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   4250:         return 'error: '.$queryid;
                   4251:     }
1.506     raeburn  4252:     my $reply = &get_query_reply($queryid);
1.547     raeburn  4253:     my $tries = 1;
                   4254:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4255:         $reply = &get_query_reply($queryid);
                   4256:         $tries ++;
                   4257:     }
1.526     raeburn  4258:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 4259:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  4260:     } else {
1.515     raeburn  4261:         my @responses = split/:/,$reply;
                   4262:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 4263:             foreach my $line (@responses) {
                   4264:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  4265:                 $$replyref{$key} = $value;
                   4266:             }
                   4267:         } else {
1.506     raeburn  4268:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
1.800     albertel 4269:             foreach my $line (@responses) {
                   4270:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  4271:                 $$replyref{$key} = $value;
                   4272:                 if ($value > 0) {
1.800     albertel 4273:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   4274:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  4275:                         my $destname = $pathname.'/'.$filename;
                   4276:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  4277:                         if ($xml_classlist =~ /^error/) {
                   4278:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   4279:                         } else {
1.506     raeburn  4280:                             if ( open(FILE,">$destname") ) {
                   4281:                                 print FILE &unescape($xml_classlist);
                   4282:                                 close(FILE);
1.526     raeburn  4283:                             } else {
                   4284:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  4285:                             }
                   4286:                         }
                   4287:                     }
                   4288:                 }
                   4289:             }
                   4290:         }
                   4291:         return 'ok';
                   4292:     }
                   4293:     return 'error';
                   4294: }
                   4295: 
1.242     www      4296: sub get_query_reply {
                   4297:     my $queryid=shift;
1.240     www      4298:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
                   4299:     my $reply='';
                   4300:     for (1..100) {
                   4301: 	sleep 2;
                   4302:         if (-e $replyfile.'.end') {
1.448     albertel 4303: 	    if (open(my $fh,$replyfile)) {
1.240     www      4304:                $reply.=<$fh>;
1.448     albertel 4305:                close($fh);
1.240     www      4306: 	   } else { return 'error: reply_file_error'; }
1.242     www      4307:            return &unescape($reply);
                   4308: 	}
1.240     www      4309:     }
1.242     www      4310:     return 'timeout:'.$queryid;
1.240     www      4311: }
                   4312: 
                   4313: sub courselog_query {
1.241     www      4314: #
                   4315: # possible filters:
                   4316: # url: url or symb
                   4317: # username
                   4318: # domain
                   4319: # action: view, submit, grade
                   4320: # start: timestamp
                   4321: # end: timestamp
                   4322: #
1.240     www      4323:     my (%filters)=@_;
1.620     albertel 4324:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      4325:     if ($filters{'url'}) {
                   4326: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   4327:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   4328:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   4329:     }
1.620     albertel 4330:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4331:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      4332:     return &log_query($cname,$cdom,'courselog',%filters);
                   4333: }
                   4334: 
                   4335: sub userlog_query {
                   4336:     my ($uname,$udom,%filters)=@_;
                   4337:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      4338: }
                   4339: 
1.506     raeburn  4340: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   4341: 
                   4342: sub auto_run {
1.508     raeburn  4343:     my ($cnum,$cdom) = @_;
                   4344:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4345:     my $response = &reply('autorun:'.$cdom,$homeserver);
1.506     raeburn  4346:     return $response;
                   4347: }
1.776     albertel 4348: 
1.506     raeburn  4349: sub auto_get_sections {
1.508     raeburn  4350:     my ($cnum,$cdom,$inst_coursecode) = @_;
                   4351:     my $homeserver = &homeserver($cnum,$cdom);
1.506     raeburn  4352:     my @secs = ();
1.511     raeburn  4353:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
1.506     raeburn  4354:     unless ($response eq 'refused') {
                   4355:         @secs = split/:/,$response;
                   4356:     }
                   4357:     return @secs;
                   4358: }
1.776     albertel 4359: 
1.506     raeburn  4360: sub auto_new_course {
1.508     raeburn  4361:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
                   4362:     my $homeserver = &homeserver($cnum,$cdom);
1.515     raeburn  4363:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
1.506     raeburn  4364:     return $response;
                   4365: }
1.776     albertel 4366: 
1.506     raeburn  4367: sub auto_validate_courseID {
1.508     raeburn  4368:     my ($cnum,$cdom,$inst_course_id) = @_;
                   4369:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  4370:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  4371:     return $response;
                   4372: }
1.776     albertel 4373: 
1.506     raeburn  4374: sub auto_create_password {
1.508     raeburn  4375:     my ($cnum,$cdom,$authparam) = @_;
                   4376:     my $homeserver = &homeserver($cnum,$cdom); 
1.506     raeburn  4377:     my $create_passwd = 0;
                   4378:     my $authchk = '';
1.511     raeburn  4379:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
1.506     raeburn  4380:     if ($response eq 'refused') {
                   4381:         $authchk = 'refused';
                   4382:     } else {
                   4383:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
                   4384:     }
                   4385:     return ($authparam,$create_passwd,$authchk);
                   4386: }
                   4387: 
1.706     raeburn  4388: sub auto_photo_permission {
                   4389:     my ($cnum,$cdom,$students) = @_;
                   4390:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 4391:     my ($outcome,$perm_reqd,$conditions) = 
                   4392: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 4393:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4394: 	return (undef,undef);
                   4395:     }
1.706     raeburn  4396:     return ($outcome,$perm_reqd,$conditions);
                   4397: }
                   4398: 
                   4399: sub auto_checkphotos {
                   4400:     my ($uname,$udom,$pid) = @_;
                   4401:     my $homeserver = &homeserver($uname,$udom);
                   4402:     my ($result,$resulttype);
                   4403:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 4404: 				   &escape($uname).':'.&escape($pid),
                   4405: 				   $homeserver));
1.709     albertel 4406:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4407: 	return (undef,undef);
                   4408:     }
1.706     raeburn  4409:     if ($outcome) {
                   4410:         ($result,$resulttype) = split(/:/,$outcome);
                   4411:     } 
                   4412:     return ($result,$resulttype);
                   4413: }
                   4414: 
                   4415: sub auto_photochoice {
                   4416:     my ($cnum,$cdom) = @_;
                   4417:     my $homeserver = &homeserver($cnum,$cdom);
                   4418:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 4419: 						       &escape($cdom),
                   4420: 						       $homeserver)));
1.709     albertel 4421:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   4422: 	return (undef,undef);
                   4423:     }
1.706     raeburn  4424:     return ($update,$comment);
                   4425: }
                   4426: 
                   4427: sub auto_photoupdate {
                   4428:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   4429:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 4430:     my $host=&hostname($homeserver);
1.706     raeburn  4431:     my $cmd = '';
                   4432:     my $maxtries = 1;
1.800     albertel 4433:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   4434:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  4435:     }
                   4436:     $cmd =~ s/%%$//;
                   4437:     $cmd = &escape($cmd);
                   4438:     my $query = 'institutionalphotos';
                   4439:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   4440:     unless ($queryid=~/^\Q$host\E\_/) {
                   4441:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   4442:         return 'error: '.$queryid;
                   4443:     }
                   4444:     my $reply = &get_query_reply($queryid);
                   4445:     my $tries = 1;
                   4446:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   4447:         $reply = &get_query_reply($queryid);
                   4448:         $tries ++;
                   4449:     }
                   4450:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   4451:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   4452:     } else {
                   4453:         my @responses = split(/:/,$reply);
                   4454:         my $outcome = shift(@responses); 
                   4455:         foreach my $item (@responses) {
                   4456:             my ($key,$value) = split(/=/,$item);
                   4457:             $$photo{$key} = $value;
                   4458:         }
                   4459:         return $outcome;
                   4460:     }
                   4461:     return 'error';
                   4462: }
                   4463: 
1.521     raeburn  4464: sub auto_instcode_format {
1.793     albertel 4465:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   4466: 	$cat_order) = @_;
1.521     raeburn  4467:     my $courses = '';
1.772     raeburn  4468:     my @homeservers;
1.521     raeburn  4469:     if ($caller eq 'global') {
1.841     albertel 4470: 	my %servers = &get_servers($codedom,'library');
                   4471: 	foreach my $tryserver (keys(%servers)) {
                   4472: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4473: 		push(@homeservers,$tryserver);
                   4474: 	    }
1.584     raeburn  4475:         }
1.521     raeburn  4476:     } else {
1.772     raeburn  4477:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  4478:     }
1.793     albertel 4479:     foreach my $code (keys(%{$instcodes})) {
                   4480:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  4481:     }
                   4482:     chop($courses);
1.772     raeburn  4483:     my $ok_response = 0;
                   4484:     my $response;
                   4485:     while (@homeservers > 0 && $ok_response == 0) {
                   4486:         my $server = shift(@homeservers); 
                   4487:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   4488:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   4489:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.793     albertel 4490: 		split/:/,$response;
1.772     raeburn  4491:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   4492:             push(@{$codetitles},&str2array($codetitles_str));
                   4493:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   4494:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   4495:             $ok_response = 1;
                   4496:         }
                   4497:     }
                   4498:     if ($ok_response) {
1.521     raeburn  4499:         return 'ok';
1.772     raeburn  4500:     } else {
                   4501:         return $response;
1.521     raeburn  4502:     }
                   4503: }
                   4504: 
1.792     raeburn  4505: sub auto_instcode_defaults {
                   4506:     my ($domain,$returnhash,$code_order) = @_;
                   4507:     my @homeservers;
1.841     albertel 4508: 
                   4509:     my %servers = &get_servers($domain,'library');
                   4510:     foreach my $tryserver (keys(%servers)) {
                   4511: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   4512: 	    push(@homeservers,$tryserver);
                   4513: 	}
1.792     raeburn  4514:     }
1.841     albertel 4515: 
1.792     raeburn  4516:     my $response;
1.841     albertel 4517:     foreach my $server (@homeservers) {
1.792     raeburn  4518:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 4519:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   4520: 	
                   4521: 	foreach my $pair (split(/\&/,$response)) {
                   4522: 	    my ($name,$value)=split(/\=/,$pair);
                   4523: 	    if ($name eq 'code_order') {
                   4524: 		@{$code_order} = split(/\&/,&unescape($value));
                   4525: 	    } else {
                   4526: 		$returnhash->{&unescape($name)}=&unescape($value);
                   4527: 	    }
                   4528: 	}
                   4529: 	return 'ok';
1.792     raeburn  4530:     }
1.841     albertel 4531: 
                   4532:     return $response;
1.792     raeburn  4533: } 
                   4534: 
1.777     albertel 4535: sub auto_validate_class_sec {
1.773     raeburn  4536:     my ($cdom,$cnum,$owner,$inst_class) = @_;
                   4537:     my $homeserver = &homeserver($cnum,$cdom);
                   4538:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.774     banghart 4539:                         &escape($owner).':'.$cdom,$homeserver);
1.773     raeburn  4540:     return $response;
                   4541: }
                   4542: 
1.679     raeburn  4543: # ------------------------------------------------------- Course Group routines
                   4544: 
                   4545: sub get_coursegroups {
1.809     raeburn  4546:     my ($cdom,$cnum,$group,$namespace) = @_;
                   4547:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  4548: }
                   4549: 
1.679     raeburn  4550: sub modify_coursegroup {
                   4551:     my ($cdom,$cnum,$groupsettings) = @_;
                   4552:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   4553: }
                   4554: 
1.809     raeburn  4555: sub toggle_coursegroup_status {
                   4556:     my ($cdom,$cnum,$group,$action) = @_;
                   4557:     my ($from_namespace,$to_namespace);
                   4558:     if ($action eq 'delete') {
                   4559:         $from_namespace = 'coursegroups';
                   4560:         $to_namespace = 'deleted_groups';
                   4561:     } else {
                   4562:         $from_namespace = 'deleted_groups';
                   4563:         $to_namespace = 'coursegroups';
                   4564:     }
                   4565:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  4566:     if (my $tmp = &error(%curr_group)) {
                   4567:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   4568:         return ('read error',$tmp);
                   4569:     } else {
                   4570:         my %savedsettings = %curr_group; 
1.809     raeburn  4571:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  4572:         my $deloutcome;
                   4573:         if ($result eq 'ok') {
1.809     raeburn  4574:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  4575:         } else {
                   4576:             return ('write error',$result);
                   4577:         }
                   4578:         if ($deloutcome eq 'ok') {
                   4579:             return 'ok';
                   4580:         } else {
                   4581:             return ('delete error',$deloutcome);
                   4582:         }
                   4583:     }
                   4584: }
                   4585: 
1.679     raeburn  4586: sub modify_group_roles {
                   4587:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
                   4588:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   4589:     my $role = 'gr/'.&escape($userprivs);
                   4590:     my ($uname,$udom) = split(/:/,$user);
                   4591:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
1.684     raeburn  4592:     if ($result eq 'ok') {
                   4593:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   4594:     }
1.679     raeburn  4595:     return $result;
                   4596: }
                   4597: 
                   4598: sub modify_coursegroup_membership {
                   4599:     my ($cdom,$cnum,$membership) = @_;
                   4600:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   4601:     return $result;
                   4602: }
                   4603: 
1.682     raeburn  4604: sub get_active_groups {
                   4605:     my ($udom,$uname,$cdom,$cnum) = @_;
                   4606:     my $now = time;
                   4607:     my %groups = ();
                   4608:     foreach my $key (keys(%env)) {
1.811     albertel 4609:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  4610:             my ($start,$end) = split(/\./,$env{$key});
                   4611:             if (($end!=0) && ($end<$now)) { next; }
                   4612:             if (($start!=0) && ($start>$now)) { next; }
                   4613:             if ($1 eq $cdom && $2 eq $cnum) {
                   4614:                 $groups{$3} = $env{$key} ;
                   4615:             }
                   4616:         }
                   4617:     }
                   4618:     return %groups;
                   4619: }
                   4620: 
1.683     raeburn  4621: sub get_group_membership {
                   4622:     my ($cdom,$cnum,$group) = @_;
                   4623:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   4624: }
                   4625: 
                   4626: sub get_users_groups {
                   4627:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  4628:     my @usersgroups;
1.683     raeburn  4629:     my $cachetime=1800;
                   4630: 
                   4631:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  4632:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   4633:     if (defined($cached)) {
1.734     albertel 4634:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  4635:     } else {  
                   4636:         $grouplist = '';
1.816     raeburn  4637:         my $courseurl = &courseid_to_courseurl($courseid);
                   4638:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  4639:         my $access_end = $env{'course.'.$courseid.
                   4640:                               '.default_enrollment_end_date'};
                   4641:         my $now = time;
                   4642:         foreach my $key (keys(%roleshash)) {
                   4643:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   4644:                 my $group = $1;
                   4645:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   4646:                     my $start = $2;
                   4647:                     my $end = $1;
                   4648:                     if ($start == -1) { next; } # deleted from group
                   4649:                     if (($start!=0) && ($start>$now)) { next; }
                   4650:                     if (($end!=0) && ($end<$now)) {
                   4651:                         if ($access_end && $access_end < $now) {
                   4652:                             if ($access_end - $end < 86400) {
                   4653:                                 push(@usersgroups,$group);
1.733     raeburn  4654:                             }
                   4655:                         }
1.817     raeburn  4656:                         next;
1.733     raeburn  4657:                     }
1.817     raeburn  4658:                     push(@usersgroups,$group);
1.683     raeburn  4659:                 }
                   4660:             }
                   4661:         }
1.817     raeburn  4662:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   4663:         $grouplist = join(':',@usersgroups);
                   4664:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  4665:     }
1.733     raeburn  4666:     return @usersgroups;
1.683     raeburn  4667: }
                   4668: 
                   4669: sub devalidate_getgroups_cache {
                   4670:     my ($udom,$uname,$cdom,$cnum)=@_;
                   4671:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 4672: 
1.683     raeburn  4673:     my $hashid="$udom:$uname:$courseid";
                   4674:     &devalidate_cache_new('getgroups',$hashid);
                   4675: }
                   4676: 
1.12      www      4677: # ------------------------------------------------------------------ Plain Text
                   4678: 
                   4679: sub plaintext {
1.742     raeburn  4680:     my ($short,$type,$cid) = @_;
1.758     albertel 4681:     if ($short =~ /^cr/) {
                   4682: 	return (split('/',$short))[-1];
                   4683:     }
1.742     raeburn  4684:     if (!defined($cid)) {
                   4685:         $cid = $env{'request.course.id'};
                   4686:     }
                   4687:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
                   4688:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
                   4689:                                           '.plaintext'});
                   4690:     }
                   4691:     my %rolenames = (
                   4692:                       Course => 'std',
                   4693:                       Group => 'alt1',
                   4694:                     );
                   4695:     if (defined($type) && 
                   4696:          defined($rolenames{$type}) && 
                   4697:          defined($prp{$short}{$rolenames{$type}})) {
                   4698:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
                   4699:     } else {
                   4700:         return &Apache::lonlocal::mt($prp{$short}{'std'});
                   4701:     }
1.12      www      4702: }
                   4703: 
                   4704: # ----------------------------------------------------------------- Assign Role
                   4705: 
                   4706: sub assignrole {
1.357     www      4707:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
1.21      www      4708:     my $mrole;
                   4709:     if ($role =~ /^cr\//) {
1.393     www      4710:         my $cwosec=$url;
1.811     albertel 4711:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      4712: 	unless (&allowed('ccr',$cwosec)) {
1.104     www      4713:            &logthis('Refused custom assignrole: '.
                   4714:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4715: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4716:            return 'refused'; 
                   4717:         }
1.21      www      4718:         $mrole='cr';
1.678     raeburn  4719:     } elsif ($role =~ /^gr\//) {
                   4720:         my $cwogrp=$url;
1.811     albertel 4721:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  4722:         unless (&allowed('mdg',$cwogrp)) {
                   4723:             &logthis('Refused group assignrole: '.
                   4724:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   4725:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   4726:             return 'refused';
                   4727:         }
                   4728:         $mrole='gr';
1.21      www      4729:     } else {
1.82      www      4730:         my $cwosec=$url;
1.811     albertel 4731:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.373     www      4732:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
1.104     www      4733:            &logthis('Refused assignrole: '.
                   4734:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
1.620     albertel 4735: 		    $env{'user.name'}.' at '.$env{'user.domain'});
1.104     www      4736:            return 'refused'; 
                   4737:         }
1.21      www      4738:         $mrole=$role;
                   4739:     }
1.620     albertel 4740:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      4741:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      4742:     if ($end) { $command.='_'.$end; }
1.21      www      4743:     if ($start) {
                   4744: 	if ($end) { 
1.81      www      4745:            $command.='_'.$start; 
1.21      www      4746:         } else {
1.81      www      4747:            $command.='_0_'.$start;
1.21      www      4748:         }
                   4749:     }
1.739     raeburn  4750:     my $origstart = $start;
                   4751:     my $origend = $end;
1.357     www      4752: # actually delete
                   4753:     if ($deleteflag) {
1.373     www      4754: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      4755: # modify command to delete the role
1.620     albertel 4756:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      4757:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 4758: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      4759: # set start and finish to negative values for userrolelog
                   4760:            $start=-1;
                   4761:            $end=-1;
                   4762:         }
                   4763:     }
                   4764: # send command
1.349     www      4765:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      4766: # log new user role if status is ok
1.349     www      4767:     if ($answer eq 'ok') {
1.663     raeburn  4768: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  4769: # for course roles, perform group memberships changes triggered by role change.
                   4770:         unless ($role =~ /^gr/) {
                   4771:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   4772:                                              $origstart);
                   4773:         }
1.349     www      4774:     }
                   4775:     return $answer;
1.169     harris41 4776: }
                   4777: 
                   4778: # -------------------------------------------------- Modify user authentication
1.197     www      4779: # Overrides without validation
                   4780: 
1.169     harris41 4781: sub modifyuserauth {
                   4782:     my ($udom,$uname,$umode,$upass)=@_;
                   4783:     my $uhome=&homeserver($uname,$udom);
1.197     www      4784:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   4785:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 4786:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4787:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 4788:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   4789: 		     &escape($upass),$uhome);
1.620     albertel 4790:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      4791:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   4792:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   4793:     &log($udom,,$uname,$uhome,
1.620     albertel 4794:         'Authentication changed by '.$env{'user.domain'}.', '.
                   4795:                                      $env{'user.name'}.', '.$umode.
1.197     www      4796:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 4797:     unless ($reply eq 'ok') {
1.197     www      4798:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 4799: 	return 'error: '.$reply;
                   4800:     }   
1.170     harris41 4801:     return 'ok';
1.80      www      4802: }
                   4803: 
1.81      www      4804: # --------------------------------------------------------------- Modify a user
1.80      www      4805: 
1.81      www      4806: sub modifyuser {
1.206     matthew  4807:     my ($udom,    $uname, $uid,
                   4808:         $umode,   $upass, $first,
                   4809:         $middle,  $last,  $gene,
1.387     www      4810:         $forceid, $desiredhome, $email)=@_;
1.807     albertel 4811:     $udom= &LONCAPA::clean_domain($udom);
                   4812:     $uname=&LONCAPA::clean_username($uname);
1.81      www      4813:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4814:              $umode.', '.$first.', '.$middle.', '.
1.206     matthew  4815: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
                   4816:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   4817:                                      ' desiredhome not specified'). 
1.620     albertel 4818:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   4819:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 4820:     my $uhome=&homeserver($uname,$udom,'true');
1.80      www      4821: # ----------------------------------------------------------------- Create User
1.406     albertel 4822:     if (($uhome eq 'no_host') && 
                   4823: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      4824:         my $unhome='';
1.844     albertel 4825:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  4826:             $unhome = $desiredhome;
1.620     albertel 4827: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   4828: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  4829:         } else { # load balancing routine for determining $unhome
1.81      www      4830:             my $loadm=10000000;
1.841     albertel 4831: 	    my %servers = &get_servers($udom,'library');
                   4832: 	    foreach my $tryserver (keys(%servers)) {
                   4833: 		my $answer=reply('load',$tryserver);
                   4834: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   4835: 		    $loadm=$answer;
                   4836: 		    $unhome=$tryserver;
                   4837: 		}
1.80      www      4838: 	    }
                   4839:         }
                   4840:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  4841: 	    return 'error: unable to find a home server for '.$uname.
                   4842:                    ' in domain '.$udom;
1.80      www      4843:         }
                   4844:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   4845:                          &escape($upass),$unhome);
                   4846: 	unless ($reply eq 'ok') {
                   4847:             return 'error: '.$reply;
                   4848:         }   
1.230     stredwic 4849:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      4850:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  4851: 	    return 'error: unable verify users home machine.';
1.80      www      4852:         }
1.209     matthew  4853:     }   # End of creation of new user
1.80      www      4854: # ---------------------------------------------------------------------- Add ID
                   4855:     if ($uid) {
                   4856:        $uid=~tr/A-Z/a-z/;
                   4857:        my %uidhash=&idrget($udom,$uname);
1.196     www      4858:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   4859:          && (!$forceid)) {
1.80      www      4860: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  4861: 	      return 'error: user id "'.$uid.'" does not match '.
                   4862:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      4863:           }
                   4864:        } else {
                   4865: 	  &idput($udom,($uname => $uid));
                   4866:        }
                   4867:     }
                   4868: # -------------------------------------------------------------- Add names, etc
1.313     matthew  4869:     my @tmp=&get('environment',
1.134     albertel 4870: 		   ['firstname','middlename','lastname','generation'],
                   4871: 		   $udom,$uname);
1.313     matthew  4872:     my %names;
                   4873:     if ($tmp[0] =~ m/^error:.*/) { 
                   4874:         %names=(); 
                   4875:     } else {
                   4876:         %names = @tmp;
                   4877:     }
1.388     www      4878: #
                   4879: # Make sure to not trash student environment if instructor does not bother
                   4880: # to supply name and email information
                   4881: #
                   4882:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  4883:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      4884:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  4885:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      4886:     if ($email) {
                   4887:        $email=~s/[^\w\@\.\-\,]//gs;
                   4888:        if ($email=~/\@/) { $names{'notification'} = $email;
                   4889: 			   $names{'critnotification'} = $email;
                   4890: 			   $names{'permanentemail'} = $email; }
                   4891:     }
1.134     albertel 4892:     my $reply = &put('environment', \%names, $udom,$uname);
                   4893:     if ($reply ne 'ok') { return 'error: '.$reply; }
1.680     www      4894:     &devalidate_cache_new('namescache',$uname.':'.$udom);
1.81      www      4895:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      4896:              $umode.', '.$first.', '.$middle.', '.
                   4897: 	     $last.', '.$gene.' by '.
1.620     albertel 4898:              $env{'user.name'}.' at '.$env{'user.domain'});
1.134     albertel 4899:     return 'ok';
1.80      www      4900: }
                   4901: 
1.81      www      4902: # -------------------------------------------------------------- Modify student
1.80      www      4903: 
1.81      www      4904: sub modifystudent {
                   4905:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.515     raeburn  4906:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
1.455     albertel 4907:     if (!$cid) {
1.620     albertel 4908: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4909: 	    return 'not_in_class';
                   4910: 	}
1.80      www      4911:     }
                   4912: # --------------------------------------------------------------- Make the user
1.81      www      4913:     my $reply=&modifyuser
1.209     matthew  4914: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.387     www      4915:          $desiredhome,$email);
1.80      www      4916:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  4917:     # This will cause &modify_student_enrollment to get the uid from the
                   4918:     # students environment
                   4919:     $uid = undef if (!$forceid);
1.455     albertel 4920:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.515     raeburn  4921: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
1.297     matthew  4922:     return $reply;
                   4923: }
                   4924: 
                   4925: sub modify_student_enrollment {
1.515     raeburn  4926:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
1.455     albertel 4927:     my ($cdom,$cnum,$chome);
                   4928:     if (!$cid) {
1.620     albertel 4929: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 4930: 	    return 'not_in_class';
                   4931: 	}
1.620     albertel 4932: 	$cdom=$env{'course.'.$cid.'.domain'};
                   4933: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 4934:     } else {
                   4935: 	($cdom,$cnum)=split(/_/,$cid);
                   4936:     }
1.620     albertel 4937:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 4938:     if (!$chome) {
1.457     raeburn  4939: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  4940:     }
1.455     albertel 4941:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  4942:     # Make sure the user exists
1.81      www      4943:     my $uhome=&homeserver($uname,$udom);
                   4944:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   4945: 	return 'error: no such user';
                   4946:     }
1.297     matthew  4947:     # Get student data if we were not given enough information
                   4948:     if (!defined($first)  || $first  eq '' || 
                   4949:         !defined($last)   || $last   eq '' || 
                   4950:         !defined($uid)    || $uid    eq '' || 
                   4951:         !defined($middle) || $middle eq '' || 
                   4952:         !defined($gene)   || $gene   eq '') {
1.294     matthew  4953:         # They did not supply us with enough data to enroll the student, so
                   4954:         # we need to pick up more information.
1.297     matthew  4955:         my %tmp = &get('environment',
1.294     matthew  4956:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  4957:                        ,$udom,$uname);
                   4958: 
1.800     albertel 4959:         #foreach my $key (keys(%tmp)) {
                   4960:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 4961:         #}
1.294     matthew  4962:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   4963:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   4964:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  4965:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  4966:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   4967:     }
1.556     albertel 4968:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 4969:     my $reply=cput('classlist',
                   4970: 		   {"$uname:$udom" => 
1.515     raeburn  4971: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 4972: 		   $cdom,$cnum);
1.81      www      4973:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   4974: 	return 'error: '.$reply;
1.652     albertel 4975:     } else {
                   4976: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      4977:     }
1.297     matthew  4978:     # Add student role to user
1.83      www      4979:     my $uurl='/'.$cid;
1.81      www      4980:     $uurl=~s/\_/\//g;
                   4981:     if ($usec) {
                   4982: 	$uurl.='/'.$usec;
                   4983:     }
                   4984:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
1.21      www      4985: }
                   4986: 
1.556     albertel 4987: sub format_name {
                   4988:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   4989:     my $name;
                   4990:     if ($first ne 'lastname') {
                   4991: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   4992:     } else {
                   4993: 	if ($lastname=~/\S/) {
                   4994: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   4995: 	    $name=~s/\s+,/,/;
                   4996: 	} else {
                   4997: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   4998: 	}
                   4999:     }
                   5000:     $name=~s/^\s+//;
                   5001:     $name=~s/\s+$//;
                   5002:     $name=~s/\s+/ /g;
                   5003:     return $name;
                   5004: }
                   5005: 
1.84      www      5006: # ------------------------------------------------- Write to course preferences
                   5007: 
                   5008: sub writecoursepref {
                   5009:     my ($courseid,%prefs)=@_;
                   5010:     $courseid=~s/^\///;
                   5011:     $courseid=~s/\_/\//g;
                   5012:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   5013:     my $chome=homeserver($cnum,$cdomain);
                   5014:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   5015: 	return 'error: no such course';
                   5016:     }
                   5017:     my $cstring='';
1.800     albertel 5018:     foreach my $pref (keys(%prefs)) {
                   5019: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 5020:     }
1.84      www      5021:     $cstring=~s/\&$//;
                   5022:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   5023: }
                   5024: 
                   5025: # ---------------------------------------------------------- Make/modify course
                   5026: 
                   5027: sub createcourse {
1.741     raeburn  5028:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
                   5029:         $course_owner,$crstype)=@_;
1.84      www      5030:     $url=&declutter($url);
                   5031:     my $cid='';
1.264     matthew  5032:     unless (&allowed('ccc',$udom)) {
1.84      www      5033:         return 'refused';
                   5034:     }
                   5035: # ------------------------------------------------------------------- Create ID
1.674     www      5036:    my $uname=int(1+rand(9)).
                   5037:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   5038:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
1.84      www      5039:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   5040: # ----------------------------------------------- Make sure that does not exist
1.230     stredwic 5041:    my $uhome=&homeserver($uname,$udom,'true');
1.84      www      5042:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5043:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   5044:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
1.230     stredwic 5045:        $uhome=&homeserver($uname,$udom,'true');       
1.84      www      5046:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   5047:            return 'error: unable to generate unique course-ID';
                   5048:        } 
                   5049:    }
1.264     matthew  5050: # ------------------------------------------------ Check supplied server name
1.620     albertel 5051:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
1.845     albertel 5052:     if (! &is_library($course_server)) {
1.264     matthew  5053:         return 'error:bad server name '.$course_server;
                   5054:     }
1.84      www      5055: # ------------------------------------------------------------- Make the course
                   5056:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  5057:                       $course_server);
1.84      www      5058:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.230     stredwic 5059:     $uhome=&homeserver($uname,$udom,'true');
1.84      www      5060:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   5061: 	return 'error: no such course';
                   5062:     }
1.271     www      5063: # ----------------------------------------------------------------- Course made
1.516     raeburn  5064: # log existence
                   5065:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
1.741     raeburn  5066:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
                   5067:                   &escape($crstype),$uhome);
1.358     www      5068:     &flushcourselogs();
                   5069: # set toplevel url
1.271     www      5070:     my $topurl=$url;
                   5071:     unless ($nonstandard) {
                   5072: # ------------------------------------------ For standard courses, make top url
                   5073:         my $mapurl=&clutter($url);
1.278     www      5074:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 5075:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      5076: <map>
                   5077: <resource id="1" type="start"></resource>
                   5078: <resource id="2" src="$mapurl"></resource>
                   5079: <resource id="3" type="finish"></resource>
                   5080: <link index="1" from="1" to="2"></link>
                   5081: <link index="2" from="2" to="3"></link>
                   5082: </map>
                   5083: ENDINITMAP
                   5084:         $topurl=&declutter(
1.638     albertel 5085:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      5086:                           );
                   5087:     }
                   5088: # ----------------------------------------------------------- Write preferences
1.84      www      5089:     &writecoursepref($udom.'_'.$uname,
                   5090:                      ('description' => $description,
1.271     www      5091:                       'url'         => $topurl));
1.84      www      5092:     return '/'.$udom.'/'.$uname;
                   5093: }
                   5094: 
1.813     albertel 5095: sub is_course {
                   5096:     my ($cdom,$cnum) = @_;
                   5097:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
                   5098: 				undef,'.');
                   5099:     if (exists($courses{$cdom.'_'.$cnum})) {
                   5100:         return 1;
                   5101:     }
                   5102:     return 0;
                   5103: }
                   5104: 
1.21      www      5105: # ---------------------------------------------------------- Assign Custom Role
                   5106: 
                   5107: sub assigncustomrole {
1.357     www      5108:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
1.21      www      5109:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.357     www      5110:                        $end,$start,$deleteflag);
1.21      www      5111: }
                   5112: 
                   5113: # ----------------------------------------------------------------- Revoke Role
                   5114: 
                   5115: sub revokerole {
1.357     www      5116:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
1.21      www      5117:     my $now=time;
1.357     www      5118:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
1.21      www      5119: }
                   5120: 
                   5121: # ---------------------------------------------------------- Revoke Custom Role
                   5122: 
                   5123: sub revokecustomrole {
1.357     www      5124:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
1.21      www      5125:     my $now=time;
1.357     www      5126:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
                   5127:            $deleteflag);
1.17      www      5128: }
                   5129: 
1.533     banghart 5130: # ------------------------------------------------------------ Disk usage
1.535     albertel 5131: sub diskusage {
1.533     banghart 5132:     my ($udom,$uname,$directoryRoot)=@_;
                   5133:     $directoryRoot =~ s/\/$//;
1.535     albertel 5134:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
1.514     albertel 5135:     return $listing;
1.512     banghart 5136: }
                   5137: 
1.566     banghart 5138: sub is_locked {
                   5139:     my ($file_name, $domain, $user) = @_;
                   5140:     my @check;
                   5141:     my $is_locked;
                   5142:     push @check, $file_name;
1.613     albertel 5143:     my %locked = &get('file_permissions',\@check,
1.620     albertel 5144: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 5145:     my ($tmp)=keys(%locked);
                   5146:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  5147:     
1.566     banghart 5148:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  5149:         $is_locked = 'false';
                   5150:         foreach my $entry (@{$locked{$file_name}}) {
                   5151:            if (ref($entry) eq 'ARRAY') { 
1.746     raeburn  5152:                $is_locked = 'true';
                   5153:                last;
1.745     raeburn  5154:            }
                   5155:        }
1.566     banghart 5156:     } else {
                   5157:         $is_locked = 'false';
                   5158:     }
                   5159: }
                   5160: 
1.759     albertel 5161: sub declutter_portfile {
                   5162:     my ($file) = @_;
1.833     albertel 5163:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 5164:     return $file;
                   5165: }
                   5166: 
1.559     banghart 5167: # ------------------------------------------------------------- Mark as Read Only
                   5168: 
                   5169: sub mark_as_readonly {
                   5170:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 5171:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5172:     my ($tmp)=keys(%current_permissions);
                   5173:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 5174:     foreach my $file (@{$files}) {
1.759     albertel 5175: 	$file = &declutter_portfile($file);
1.561     banghart 5176:         push(@{$current_permissions{$file}},$what);
1.559     banghart 5177:     }
1.613     albertel 5178:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5179:     return;
                   5180: }
                   5181: 
1.572     banghart 5182: # ------------------------------------------------------------Save Selected Files
                   5183: 
                   5184: sub save_selected_files {
                   5185:     my ($user, $path, @files) = @_;
                   5186:     my $filename = $user."savedfiles";
1.573     banghart 5187:     my @other_files = &files_not_in_path($user, $path);
1.574     banghart 5188:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5189:     foreach my $file (@files) {
1.620     albertel 5190:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 5191:     }
                   5192:     foreach my $file (@other_files) {
1.574     banghart 5193:         print (OUT $file."\n");
1.572     banghart 5194:     }
1.574     banghart 5195:     close (OUT);
1.572     banghart 5196:     return 'ok';
                   5197: }
                   5198: 
1.574     banghart 5199: sub clear_selected_files {
                   5200:     my ($user) = @_;
                   5201:     my $filename = $user."savedfiles";
                   5202:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5203:     print (OUT undef);
                   5204:     close (OUT);
                   5205:     return ("ok");    
                   5206: }
                   5207: 
1.572     banghart 5208: sub files_in_path {
                   5209:     my ($user, $path) = @_;
                   5210:     my $filename = $user."savedfiles";
                   5211:     my %return_files;
1.574     banghart 5212:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
1.573     banghart 5213:     while (my $line_in = <IN>) {
1.574     banghart 5214:         chomp ($line_in);
                   5215:         my @paths_and_file = split (m!/!, $line_in);
                   5216:         my $file_part = pop (@paths_and_file);
                   5217:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 5218:         $path_part.='/';
                   5219:         my $path_and_file = $path_part.$file_part;
                   5220:         if ($path_part eq $path) {
                   5221:             $return_files{$file_part}= 'selected';
                   5222:         }
                   5223:     }
1.574     banghart 5224:     close (IN);
                   5225:     return (\%return_files);
1.572     banghart 5226: }
                   5227: 
                   5228: # called in portfolio select mode, to show files selected NOT in current directory
                   5229: sub files_not_in_path {
                   5230:     my ($user, $path) = @_;
                   5231:     my $filename = $user."savedfiles";
                   5232:     my @return_files;
                   5233:     my $path_part;
1.800     albertel 5234:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
                   5235:     while (my $line = <IN>) {
1.572     banghart 5236:         #ok, I know it's clunky, but I want it to work
1.800     albertel 5237:         my @paths_and_file = split(m|/|, $line);
                   5238:         my $file_part = pop(@paths_and_file);
                   5239:         chomp($file_part);
                   5240:         my $path_part = join('/', @paths_and_file);
1.572     banghart 5241:         $path_part .= '/';
                   5242:         my $path_and_file = $path_part.$file_part;
                   5243:         if ($path_part ne $path) {
1.800     albertel 5244:             push(@return_files, ($path_and_file));
1.572     banghart 5245:         }
                   5246:     }
1.800     albertel 5247:     close(OUT);
1.574     banghart 5248:     return (@return_files);
1.572     banghart 5249: }
                   5250: 
1.745     raeburn  5251: #----------------------------------------------Get portfolio file permissions
1.629     banghart 5252: 
1.745     raeburn  5253: sub get_portfile_permissions {
                   5254:     my ($domain,$user) = @_;
1.613     albertel 5255:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 5256:     my ($tmp)=keys(%current_permissions);
                   5257:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5258:     return \%current_permissions;
                   5259: }
                   5260: 
                   5261: #---------------------------------------------Get portfolio file access controls
                   5262: 
1.749     raeburn  5263: sub get_access_controls {
1.745     raeburn  5264:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 5265:     my %access;
                   5266:     my $real_file = $file;
                   5267:     $file =~ s/\.meta$//;
1.745     raeburn  5268:     if (defined($file)) {
1.749     raeburn  5269:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   5270:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 5271:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  5272:             }
                   5273:         }
1.745     raeburn  5274:     } else {
1.749     raeburn  5275:         foreach my $key (keys(%{$current_permissions})) {
                   5276:             if ($key =~ /\0accesscontrol$/) {
                   5277:                 if (defined($group)) {
                   5278:                     if ($key !~ m-^\Q$group\E/-) {
                   5279:                         next;
                   5280:                     }
                   5281:                 }
                   5282:                 my ($fullpath) = split(/\0/,$key);
                   5283:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   5284:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   5285:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   5286:                     }
                   5287:                 }
                   5288:             }
                   5289:         }
                   5290:     }
                   5291:     return %access;
                   5292: }
                   5293: 
                   5294: sub modify_access_controls {
                   5295:     my ($file_name,$changes,$domain,$user)=@_;
                   5296:     my ($outcome,$deloutcome);
                   5297:     my %store_permissions;
                   5298:     my %new_values;
                   5299:     my %new_control;
                   5300:     my %translation;
                   5301:     my @deletions = ();
                   5302:     my $now = time;
                   5303:     if (exists($$changes{'activate'})) {
                   5304:         if (ref($$changes{'activate'}) eq 'HASH') {
                   5305:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   5306:             my $numnew = scalar(@newitems);
                   5307:             for (my $i=0; $i<$numnew; $i++) {
                   5308:                 my $newkey = $newitems[$i];
                   5309:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  5310:                 if ($newkey =~ /^\d+:/) { 
                   5311:                     $newkey =~ s/^(\d+)/$newid/;
                   5312:                     $translation{$1} = $newid;
                   5313:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   5314:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   5315:                     $translation{$1} = $newid;
                   5316:                 }
1.749     raeburn  5317:                 $new_values{$file_name."\0".$newkey} = 
                   5318:                                           $$changes{'activate'}{$newitems[$i]};
                   5319:                 $new_control{$newkey} = $now;
                   5320:             }
                   5321:         }
                   5322:     }
                   5323:     my %todelete;
                   5324:     my %changed_items;
                   5325:     foreach my $action ('delete','update') {
                   5326:         if (exists($$changes{$action})) {
                   5327:             if (ref($$changes{$action}) eq 'HASH') {
                   5328:                 foreach my $key (keys(%{$$changes{$action}})) {
                   5329:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   5330:                     if ($action eq 'delete') { 
                   5331:                         $todelete{$itemnum} = 1;
                   5332:                     } else {
                   5333:                         $changed_items{$itemnum} = $key;
                   5334:                     }
                   5335:                 }
1.745     raeburn  5336:             }
                   5337:         }
1.749     raeburn  5338:     }
                   5339:     # get lock on access controls for file.
                   5340:     my $lockhash = {
                   5341:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   5342:                                                        ':'.$env{'user.domain'},
                   5343:                    }; 
                   5344:     my $tries = 0;
                   5345:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5346:    
                   5347:     while (($gotlock ne 'ok') && $tries <3) {
                   5348:         $tries ++;
                   5349:         sleep 1;
                   5350:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   5351:     }
                   5352:     if ($gotlock eq 'ok') {
                   5353:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   5354:         my ($tmp)=keys(%curr_permissions);
                   5355:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   5356:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   5357:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   5358:             if (ref($curr_controls) eq 'HASH') {
                   5359:                 foreach my $control_item (keys(%{$curr_controls})) {
                   5360:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   5361:                     if (defined($todelete{$itemnum})) {
                   5362:                         push(@deletions,$file_name."\0".$control_item);
                   5363:                     } else {
                   5364:                         if (defined($changed_items{$itemnum})) {
                   5365:                             $new_control{$changed_items{$itemnum}} = $now;
                   5366:                             push(@deletions,$file_name."\0".$control_item);
                   5367:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   5368:                         } else {
                   5369:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   5370:                         }
                   5371:                     }
1.745     raeburn  5372:                 }
                   5373:             }
                   5374:         }
1.749     raeburn  5375:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   5376:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   5377:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   5378:         #  remove lock
                   5379:         my @del_lock = ($file_name."\0".'locked_access_records');
                   5380:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  5381:         my ($file,$group);
                   5382:         if (&is_course($domain,$user)) {
                   5383:             ($group,$file) = split(/\//,$file_name,2);
                   5384:         } else {
                   5385:             $file = $file_name;
                   5386:         }
                   5387:         my $sqlresult =
                   5388:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
                   5389:                                     $group);
1.749     raeburn  5390:     } else {
                   5391:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  5392:     }
1.749     raeburn  5393:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  5394: }
                   5395: 
1.827     raeburn  5396: sub make_public_indefinitely {
                   5397:     my ($requrl) = @_;
                   5398:     my $now = time;
                   5399:     my $action = 'activate';
                   5400:     my $aclnum = 0;
                   5401:     if (&is_portfolio_url($requrl)) {
                   5402:         my (undef,$udom,$unum,$file_name,$group) =
                   5403:             &parse_portfolio_url($requrl);
                   5404:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   5405:         my %access_controls = &get_access_controls($current_perms,
                   5406:                                                    $group,$file_name);
                   5407:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   5408:             my ($num,$scope,$end,$start) = 
                   5409:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5410:             if ($scope eq 'public') {
                   5411:                 if ($start <= $now && $end == 0) {
                   5412:                     $action = 'none';
                   5413:                 } else {
                   5414:                     $action = 'update';
                   5415:                     $aclnum = $num;
                   5416:                 }
                   5417:                 last;
                   5418:             }
                   5419:         }
                   5420:         if ($action eq 'none') {
                   5421:              return 'ok';
                   5422:         } else {
                   5423:             my %changes;
                   5424:             my $newend = 0;
                   5425:             my $newstart = $now;
                   5426:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   5427:             $changes{$action}{$newkey} = {
                   5428:                 type => 'public',
                   5429:                 time => {
                   5430:                     start => $newstart,
                   5431:                     end   => $newend,
                   5432:                 },
                   5433:             };
                   5434:             my ($outcome,$deloutcome,$new_values,$translation) =
                   5435:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   5436:             return $outcome;
                   5437:         }
                   5438:     } else {
                   5439:         return 'invalid';
                   5440:     }
                   5441: }
                   5442: 
1.745     raeburn  5443: #------------------------------------------------------Get Marked as Read Only
                   5444: 
                   5445: sub get_marked_as_readonly {
                   5446:     my ($domain,$user,$what,$group) = @_;
                   5447:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 5448:     my @readonly_files;
1.629     banghart 5449:     my $cmp1=$what;
                   5450:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  5451:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5452:         if (defined($group)) {
                   5453:             if ($file_name !~ m-^\Q$group\E/-) {
                   5454:                 next;
                   5455:             }
                   5456:         }
1.561     banghart 5457:         if (ref($value) eq "ARRAY"){
                   5458:             foreach my $stored_what (@{$value}) {
1.629     banghart 5459:                 my $cmp2=$stored_what;
1.759     albertel 5460:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  5461:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  5462:                 }
1.629     banghart 5463:                 if ($cmp1 eq $cmp2) {
1.561     banghart 5464:                     push(@readonly_files, $file_name);
1.745     raeburn  5465:                     last;
1.563     banghart 5466:                 } elsif (!defined($what)) {
                   5467:                     push(@readonly_files, $file_name);
1.745     raeburn  5468:                     last;
1.561     banghart 5469:                 }
                   5470:             }
1.745     raeburn  5471:         }
1.561     banghart 5472:     }
                   5473:     return @readonly_files;
                   5474: }
1.577     banghart 5475: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 5476: 
1.577     banghart 5477: sub get_marked_as_readonly_hash {
1.745     raeburn  5478:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 5479:     my %readonly_files;
1.745     raeburn  5480:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   5481:         if (defined($group)) {
                   5482:             if ($file_name !~ m-^\Q$group\E/-) {
                   5483:                 next;
                   5484:             }
                   5485:         }
1.577     banghart 5486:         if (ref($value) eq "ARRAY"){
                   5487:             foreach my $stored_what (@{$value}) {
1.745     raeburn  5488:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 5489:                     foreach my $lock_descriptor(@{$stored_what}) {
                   5490:                         if ($lock_descriptor eq 'graded') {
                   5491:                             $readonly_files{$file_name} = 'graded';
                   5492:                         } elsif ($lock_descriptor eq 'handback') {
                   5493:                             $readonly_files{$file_name} = 'handback';
                   5494:                         } else {
                   5495:                             if (!exists($readonly_files{$file_name})) {
                   5496:                                 $readonly_files{$file_name} = 'locked';
                   5497:                             }
                   5498:                         }
1.745     raeburn  5499:                     }
1.750     banghart 5500:                 } 
1.577     banghart 5501:             }
                   5502:         } 
                   5503:     }
                   5504:     return %readonly_files;
                   5505: }
1.559     banghart 5506: # ------------------------------------------------------------ Unmark as Read Only
                   5507: 
                   5508: sub unmark_as_readonly {
1.629     banghart 5509:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   5510:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  5511:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 5512:     $file_name = &declutter_portfile($file_name);
1.634     albertel 5513:     my $symb_crs = $what;
                   5514:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  5515:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 5516:     my ($tmp)=keys(%current_permissions);
                   5517:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  5518:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 5519:     foreach my $file (@readonly_files) {
1.759     albertel 5520: 	my $clean_file = &declutter_portfile($file);
                   5521: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 5522: 	my $current_locks = $current_permissions{$file};
1.563     banghart 5523:         my @new_locks;
                   5524:         my @del_keys;
                   5525:         if (ref($current_locks) eq "ARRAY"){
                   5526:             foreach my $locker (@{$current_locks}) {
1.632     albertel 5527:                 my $compare=$locker;
1.749     raeburn  5528:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  5529:                     $compare=join('',@{$locker});
1.746     raeburn  5530:                     if ($compare ne $symb_crs) {
                   5531:                         push(@new_locks, $locker);
                   5532:                     }
1.563     banghart 5533:                 }
                   5534:             }
1.650     albertel 5535:             if (scalar(@new_locks) > 0) {
1.563     banghart 5536:                 $current_permissions{$file} = \@new_locks;
                   5537:             } else {
                   5538:                 push(@del_keys, $file);
1.613     albertel 5539:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 5540:                 delete($current_permissions{$file});
1.563     banghart 5541:             }
                   5542:         }
1.561     banghart 5543:     }
1.613     albertel 5544:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 5545:     return;
                   5546: }
1.512     banghart 5547: 
1.17      www      5548: # ------------------------------------------------------------ Directory lister
                   5549: 
                   5550: sub dirlist {
1.253     stredwic 5551:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
                   5552: 
1.18      www      5553:     $uri=~s/^\///;
                   5554:     $uri=~s/\/$//;
1.253     stredwic 5555:     my ($udom, $uname);
                   5556:     (undef,$udom,$uname)=split(/\//,$uri);
                   5557:     if(defined($userdomain)) {
                   5558:         $udom = $userdomain;
                   5559:     }
                   5560:     if(defined($username)) {
                   5561:         $uname = $username;
                   5562:     }
                   5563: 
                   5564:     my $dirRoot = $perlvar{'lonDocRoot'};
                   5565:     if(defined($alternateDirectoryRoot)) {
                   5566:         $dirRoot = $alternateDirectoryRoot;
                   5567:         $dirRoot =~ s/\/$//;
1.751     banghart 5568:     }
1.253     stredwic 5569: 
                   5570:     if($udom) {
                   5571:         if($uname) {
1.800     albertel 5572:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   5573: 				 &homeserver($uname,$udom));
1.605     matthew  5574:             my @listing_results;
                   5575:             if ($listing eq 'unknown_cmd') {
1.800     albertel 5576:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   5577: 				  &homeserver($uname,$udom));
1.605     matthew  5578:                 @listing_results = split(/:/,$listing);
                   5579:             } else {
                   5580:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   5581:             }
                   5582:             return @listing_results;
1.253     stredwic 5583:         } elsif(!defined($alternateDirectoryRoot)) {
1.800     albertel 5584:             my %allusers;
1.841     albertel 5585: 	    my %servers = &get_servers($udom,'library');
                   5586: 	    foreach my $tryserver (keys(%servers)) {
                   5587: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5588: 				     $udom, $tryserver);
                   5589: 		my @listing_results;
                   5590: 		if ($listing eq 'unknown_cmd') {
                   5591: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   5592: 				      $udom, $tryserver);
                   5593: 		    @listing_results = split(/:/,$listing);
                   5594: 		} else {
                   5595: 		    @listing_results =
                   5596: 			map { &unescape($_); } split(/:/,$listing);
                   5597: 		}
                   5598: 		if ($listing_results[0] ne 'no_such_dir' && 
                   5599: 		    $listing_results[0] ne 'empty'       &&
                   5600: 		    $listing_results[0] ne 'con_lost') {
                   5601: 		    foreach my $line (@listing_results) {
                   5602: 			my ($entry) = split(/&/,$line,2);
                   5603: 			$allusers{$entry} = 1;
                   5604: 		    }
                   5605: 		}
1.253     stredwic 5606:             }
                   5607:             my $alluserstr='';
1.800     albertel 5608:             foreach my $user (sort(keys(%allusers))) {
                   5609:                 $alluserstr.=$user.'&user:';
1.253     stredwic 5610:             }
                   5611:             $alluserstr=~s/:$//;
                   5612:             return split(/:/,$alluserstr);
                   5613:         } else {
1.800     albertel 5614:             return ('missing user name');
1.253     stredwic 5615:         }
                   5616:     } elsif(!defined($alternateDirectoryRoot)) {
1.841     albertel 5617:         my @all_domains = sort(&all_domains());
                   5618:          foreach my $domain (@all_domains) {
                   5619:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   5620:          }
                   5621:          return @all_domains;
                   5622:      } else {
1.800     albertel 5623:         return ('missing domain');
1.275     stredwic 5624:     }
                   5625: }
                   5626: 
                   5627: # --------------------------------------------- GetFileTimestamp
                   5628: # This function utilizes dirlist and returns the date stamp for
                   5629: # when it was last modified.  It will also return an error of -1
                   5630: # if an error occurs
                   5631: 
1.410     matthew  5632: ##
                   5633: ## FIXME: This subroutine assumes its caller knows something about the
                   5634: ## directory structure of the home server for the student ($root).
                   5635: ## Not a good assumption to make.  Since this is for looking up files
                   5636: ## in user directories, the full path should be constructed by lond, not
                   5637: ## whatever machine we request data from.
                   5638: ##
1.275     stredwic 5639: sub GetFileTimestamp {
                   5640:     my ($studentDomain,$studentName,$filename,$root)=@_;
1.807     albertel 5641:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   5642:     $studentName   = &LONCAPA::clean_username($studentName);
1.275     stredwic 5643:     my $subdir=$studentName.'__';
                   5644:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   5645:     my $proname="$studentDomain/$subdir/$studentName";
                   5646:     $proname .= '/'.$filename;
1.375     matthew  5647:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
                   5648:                                               $studentName, $root);
1.275     stredwic 5649:     my @stats = split('&', $fileStat);
                   5650:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  5651:         # @stats contains first the filename, then the stat output
                   5652:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 5653:     } else {
                   5654:         return -1;
1.253     stredwic 5655:     }
1.26      www      5656: }
                   5657: 
1.712     albertel 5658: sub stat_file {
                   5659:     my ($uri) = @_;
1.787     albertel 5660:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 5661: 
1.712     albertel 5662:     my ($udom,$uname,$file,$dir);
                   5663:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   5664: 	($udom,$uname,$file) =
1.811     albertel 5665: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 5666: 	$file = 'userfiles/'.$file;
1.740     www      5667: 	$dir = &propath($udom,$uname);
1.712     albertel 5668:     }
                   5669:     if ($uri =~ m-^/res/-) {
                   5670: 	($udom,$uname) = 
1.807     albertel 5671: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 5672: 	$file = $uri;
                   5673:     }
                   5674: 
                   5675:     if (!$udom || !$uname || !$file) {
                   5676: 	# unable to handle the uri
                   5677: 	return ();
                   5678:     }
                   5679: 
                   5680:     my ($result) = &dirlist($file,$udom,$uname,$dir);
                   5681:     my @stats = split('&', $result);
1.721     banghart 5682:     
1.712     albertel 5683:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   5684: 	shift(@stats); #filename is first
                   5685: 	return @stats;
                   5686:     }
                   5687:     return ();
                   5688: }
                   5689: 
1.26      www      5690: # -------------------------------------------------------- Value of a Condition
                   5691: 
1.713     albertel 5692: # gets the value of a specific preevaluated condition
                   5693: #    stored in the string  $env{user.state.<cid>}
                   5694: # or looks up a condition reference in the bighash and if if hasn't
                   5695: # already been evaluated recurses into docondval to get the value of
                   5696: # the condition, then memoizing it to 
                   5697: #   $env{user.state.<cid>.<condition>}
1.40      www      5698: sub directcondval {
                   5699:     my $number=shift;
1.620     albertel 5700:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 5701: 	&Apache::lonuserstate::evalstate();
                   5702:     }
1.713     albertel 5703:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   5704: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   5705:     } elsif ($number =~ /^_/) {
                   5706: 	my $sub_condition;
                   5707: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   5708: 		&GDBM_READER(),0640)) {
                   5709: 	    $sub_condition=$bighash{'conditions'.$number};
                   5710: 	    untie(%bighash);
                   5711: 	}
                   5712: 	my $value = &docondval($sub_condition);
                   5713: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
                   5714: 	return $value;
                   5715:     }
1.620     albertel 5716:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   5717:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      5718:     } else {
                   5719:        return 2;
                   5720:     }
                   5721: }
                   5722: 
1.713     albertel 5723: # get the collection of conditions for this resource
1.26      www      5724: sub condval {
                   5725:     my $condidx=shift;
1.54      www      5726:     my $allpathcond='';
1.713     albertel 5727:     foreach my $cond (split(/\|/,$condidx)) {
                   5728: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   5729: 	    $allpathcond.=
                   5730: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   5731: 	}
1.191     harris41 5732:     }
1.54      www      5733:     $allpathcond=~s/\|$//;
1.713     albertel 5734:     return &docondval($allpathcond);
                   5735: }
                   5736: 
                   5737: #evaluates an expression of conditions
                   5738: sub docondval {
                   5739:     my ($allpathcond) = @_;
                   5740:     my $result=0;
                   5741:     if ($env{'request.course.id'}
                   5742: 	&& defined($allpathcond)) {
                   5743: 	my $operand='|';
                   5744: 	my @stack;
                   5745: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   5746: 	    if ($chunk eq '(') {
                   5747: 		push @stack,($operand,$result);
                   5748: 	    } elsif ($chunk eq ')') {
                   5749: 		my $before=pop @stack;
                   5750: 		if (pop @stack eq '&') {
                   5751: 		    $result=$result>$before?$before:$result;
                   5752: 		} else {
                   5753: 		    $result=$result>$before?$result:$before;
                   5754: 		}
                   5755: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   5756: 		$operand=$chunk;
                   5757: 	    } else {
                   5758: 		my $new=directcondval($chunk);
                   5759: 		if ($operand eq '&') {
                   5760: 		    $result=$result>$new?$new:$result;
                   5761: 		} else {
                   5762: 		    $result=$result>$new?$result:$new;
                   5763: 		}
                   5764: 	    }
                   5765: 	}
1.26      www      5766:     }
                   5767:     return $result;
1.421     albertel 5768: }
                   5769: 
                   5770: # ---------------------------------------------------- Devalidate courseresdata
                   5771: 
                   5772: sub devalidatecourseresdata {
                   5773:     my ($coursenum,$coursedomain)=@_;
                   5774:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5775:     &devalidate_cache_new('courseres',$hashid);
1.28      www      5776: }
                   5777: 
1.763     www      5778: 
1.200     www      5779: # --------------------------------------------------- Course Resourcedata Query
                   5780: 
1.624     albertel 5781: sub get_courseresdata {
                   5782:     my ($coursenum,$coursedomain)=@_;
1.200     www      5783:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   5784:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 5785:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 5786:     my %dumpreply;
1.417     albertel 5787:     unless (defined($cached)) {
1.624     albertel 5788: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 5789: 	$result=\%dumpreply;
1.251     albertel 5790: 	my ($tmp) = keys(%dumpreply);
                   5791: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 5792: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 5793: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   5794: 	    return $tmp;
1.416     albertel 5795: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 5796: 	    $result=undef;
1.599     albertel 5797: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 5798: 	}
                   5799:     }
1.624     albertel 5800:     return $result;
                   5801: }
                   5802: 
1.633     albertel 5803: sub devalidateuserresdata {
                   5804:     my ($uname,$udom)=@_;
                   5805:     my $hashid="$udom:$uname";
                   5806:     &devalidate_cache_new('userres',$hashid);
                   5807: }
                   5808: 
1.624     albertel 5809: sub get_userresdata {
                   5810:     my ($uname,$udom)=@_;
                   5811:     #most student don\'t have any data set, check if there is some data
                   5812:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   5813: 
                   5814:     my $hashid="$udom:$uname";
                   5815:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   5816:     if (!defined($cached)) {
                   5817: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   5818: 	$result=\%resourcedata;
                   5819: 	&do_cache_new('userres',$hashid,$result,600);
                   5820:     }
                   5821:     my ($tmp)=keys(%$result);
                   5822:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   5823: 	return $result;
                   5824:     }
                   5825:     #error 2 occurs when the .db doesn't exist
                   5826:     if ($tmp!~/error: 2 /) {
1.672     albertel 5827: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 5828: 		 " Trying to get resource data for ".
                   5829: 		 $uname." at ".$udom.": ".
                   5830: 		 $tmp."</font>");
                   5831:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 5832: 	#&EXT_cache_set($udom,$uname);
                   5833: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 5834: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 5835:     }
                   5836:     return $tmp;
                   5837: }
                   5838: 
                   5839: sub resdata {
                   5840:     my ($name,$domain,$type,@which)=@_;
                   5841:     my $result;
                   5842:     if ($type eq 'course') {
                   5843: 	$result=&get_courseresdata($name,$domain);
                   5844:     } elsif ($type eq 'user') {
                   5845: 	$result=&get_userresdata($name,$domain);
                   5846:     }
                   5847:     if (!ref($result)) { return $result; }    
1.251     albertel 5848:     foreach my $item (@which) {
1.417     albertel 5849: 	if (defined($result->{$item})) {
                   5850: 	    return $result->{$item};
1.251     albertel 5851: 	}
1.250     albertel 5852:     }
1.291     albertel 5853:     return undef;
1.200     www      5854: }
                   5855: 
1.379     matthew  5856: #
                   5857: # EXT resource caching routines
                   5858: #
                   5859: 
                   5860: sub clear_EXT_cache_status {
1.383     albertel 5861:     &delenv('cache.EXT.');
1.379     matthew  5862: }
                   5863: 
                   5864: sub EXT_cache_status {
                   5865:     my ($target_domain,$target_user) = @_;
1.383     albertel 5866:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 5867:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  5868:         # We know already the user has no data
                   5869:         return 1;
                   5870:     } else {
                   5871:         return 0;
                   5872:     }
                   5873: }
                   5874: 
                   5875: sub EXT_cache_set {
                   5876:     my ($target_domain,$target_user) = @_;
1.383     albertel 5877:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.633     albertel 5878:     #&appenv($cachename => time);
1.379     matthew  5879: }
                   5880: 
1.28      www      5881: # --------------------------------------------------------- Value of a Variable
1.58      www      5882: sub EXT {
1.715     albertel 5883: 
1.395     albertel 5884:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      5885:     unless ($varname) { return ''; }
1.218     albertel 5886:     #get real user name/domain, courseid and symb
                   5887:     my $courseid;
1.359     albertel 5888:     my $publicuser;
1.427     www      5889:     if ($symbparm) {
                   5890: 	$symbparm=&get_symb_from_alias($symbparm);
                   5891:     }
1.218     albertel 5892:     if (!($uname && $udom)) {
1.790     albertel 5893:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 5894:       if (!$symbparm) {	$symbparm=$cursymb; }
                   5895:     } else {
1.620     albertel 5896: 	$courseid=$env{'request.course.id'};
1.218     albertel 5897:     }
1.48      www      5898:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   5899:     my $rest;
1.320     albertel 5900:     if (defined($therest[0])) {
1.48      www      5901:        $rest=join('.',@therest);
                   5902:     } else {
                   5903:        $rest='';
                   5904:     }
1.320     albertel 5905: 
1.57      www      5906:     my $qualifierrest=$qualifier;
                   5907:     if ($rest) { $qualifierrest.='.'.$rest; }
                   5908:     my $spacequalifierrest=$space;
                   5909:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      5910:     if ($realm eq 'user') {
1.48      www      5911: # --------------------------------------------------------------- user.resource
                   5912: 	if ($space eq 'resource') {
1.651     albertel 5913: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   5914: 		  || defined($Apache::lonhomework::parsing_a_task))
                   5915: 		 &&
1.744     albertel 5916: 		 ($symbparm eq &symbread()) ) {	
                   5917: 		# if we are in the middle of processing the resource the
                   5918: 		# get the value we are planning on committing
                   5919:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   5920:                     return $Apache::lonhomework::results{$qualifierrest};
                   5921:                 } else {
                   5922:                     return $Apache::lonhomework::history{$qualifierrest};
                   5923:                 }
1.335     albertel 5924: 	    } else {
1.359     albertel 5925: 		my %restored;
1.620     albertel 5926: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 5927: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   5928: 		} else {
                   5929: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   5930: 		}
1.335     albertel 5931: 		return $restored{$qualifierrest};
                   5932: 	    }
1.48      www      5933: # ----------------------------------------------------------------- user.access
                   5934:         } elsif ($space eq 'access') {
1.218     albertel 5935: 	    # FIXME - not supporting calls for a specific user
1.48      www      5936:             return &allowed($qualifier,$rest);
                   5937: # ------------------------------------------ user.preferences, user.environment
                   5938:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 5939: 	    if (($uname eq $env{'user.name'}) &&
                   5940: 		($udom eq $env{'user.domain'})) {
                   5941: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 5942: 	    } else {
1.359     albertel 5943: 		my %returnhash;
                   5944: 		if (!$publicuser) {
                   5945: 		    %returnhash=&userenvironment($udom,$uname,
                   5946: 						 $qualifierrest);
                   5947: 		}
1.218     albertel 5948: 		return $returnhash{$qualifierrest};
                   5949: 	    }
1.48      www      5950: # ----------------------------------------------------------------- user.course
                   5951:         } elsif ($space eq 'course') {
1.218     albertel 5952: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5953:             return $env{join('.',('request.course',$qualifier))};
1.48      www      5954: # ------------------------------------------------------------------- user.role
                   5955:         } elsif ($space eq 'role') {
1.218     albertel 5956: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 5957:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      5958:             if ($qualifier eq 'value') {
                   5959: 		return $role;
                   5960:             } elsif ($qualifier eq 'extent') {
                   5961:                 return $where;
                   5962:             }
                   5963: # ----------------------------------------------------------------- user.domain
                   5964:         } elsif ($space eq 'domain') {
1.218     albertel 5965:             return $udom;
1.48      www      5966: # ------------------------------------------------------------------- user.name
                   5967:         } elsif ($space eq 'name') {
1.218     albertel 5968:             return $uname;
1.48      www      5969: # ---------------------------------------------------- Any other user namespace
1.29      www      5970:         } else {
1.359     albertel 5971: 	    my %reply;
                   5972: 	    if (!$publicuser) {
                   5973: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   5974: 	    }
                   5975: 	    return $reply{$qualifierrest};
1.48      www      5976:         }
1.236     www      5977:     } elsif ($realm eq 'query') {
                   5978: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 5979:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   5980: 						[$spacequalifierrest]);
1.620     albertel 5981: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      5982:    } elsif ($realm eq 'request') {
1.48      www      5983: # ------------------------------------------------------------- request.browser
                   5984:         if ($space eq 'browser') {
1.430     www      5985: 	    if ($qualifier eq 'textremote') {
1.676     albertel 5986: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      5987: 		    return 1;
                   5988: 		} else {
                   5989: 		    return 0;
                   5990: 		}
                   5991: 	    } else {
1.620     albertel 5992: 		return $env{'browser.'.$qualifier};
1.430     www      5993: 	    }
1.57      www      5994: # ------------------------------------------------------------ request.filename
                   5995:         } else {
1.620     albertel 5996:             return $env{'request.'.$spacequalifierrest};
1.29      www      5997:         }
1.28      www      5998:     } elsif ($realm eq 'course') {
1.48      www      5999: # ---------------------------------------------------------- course.description
1.620     albertel 6000:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      6001:     } elsif ($realm eq 'resource') {
1.165     www      6002: 
1.620     albertel 6003: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 6004: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   6005: 	}
1.693     albertel 6006: 
                   6007: 	if ($space eq 'title') {
                   6008: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   6009: 	    return &gettitle($symbparm);
                   6010: 	}
                   6011: 	
                   6012: 	if ($space eq 'map') {
                   6013: 	    my ($map) = &decode_symb($symbparm);
                   6014: 	    return &symbread($map);
                   6015: 	}
                   6016: 
                   6017: 	my ($section, $group, @groups);
1.593     albertel 6018: 	my ($courselevelm,$courselevel);
1.539     albertel 6019: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6020: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      6021: 
1.218     albertel 6022: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      6023: 
1.60      www      6024: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 6025: 	    my $symbp=$symbparm;
1.735     albertel 6026: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 6027: 
                   6028: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   6029: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   6030: 
1.620     albertel 6031: 	    if (($env{'user.name'} eq $uname) &&
                   6032: 		($env{'user.domain'} eq $udom)) {
                   6033: 		$section=$env{'request.course.sec'};
1.733     raeburn  6034:                 @groups = split(/:/,$env{'request.course.groups'});  
                   6035:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 6036: 	    } else {
1.539     albertel 6037: 		if (! defined($usection)) {
1.551     albertel 6038: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 6039: 		} else {
                   6040: 		    $section = $usection;
                   6041: 		}
1.733     raeburn  6042:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 6043: 	    }
                   6044: 
                   6045: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   6046: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   6047: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   6048: 
1.593     albertel 6049: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 6050: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 6051: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      6052: 
1.60      www      6053: # ----------------------------------------------------------- first, check user
1.624     albertel 6054: 
                   6055: 	    my $userreply=&resdata($uname,$udom,'user',
                   6056: 				       ($courselevelr,$courselevelm,
                   6057: 					$courselevel));
                   6058: 	    if (defined($userreply)) { return $userreply; }
1.95      www      6059: 
1.594     albertel 6060: # ------------------------------------------------ second, check some of course
1.684     raeburn  6061:             my $coursereply;
1.691     raeburn  6062:             if (@groups > 0) {
                   6063:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   6064:                                        $mapparm,$spacequalifierrest);
1.684     raeburn  6065:                 if (defined($coursereply)) { return $coursereply; }
                   6066:             }
1.96      www      6067: 
1.684     raeburn  6068: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.624     albertel 6069: 				     $env{'course.'.$courseid.'.domain'},
                   6070: 				     'course',
                   6071: 				     ($seclevelr,$seclevelm,$seclevel,
                   6072: 				      $courselevelr));
1.287     albertel 6073: 	    if (defined($coursereply)) { return $coursereply; }
1.200     www      6074: 
1.60      www      6075: # ------------------------------------------------------ third, check map parms
1.218     albertel 6076: 	    my %parmhash=();
                   6077: 	    my $thisparm='';
                   6078: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 6079: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 6080: 		    &GDBM_READER(),0640)) {
1.218     albertel 6081: 		$thisparm=$parmhash{$symbparm};
                   6082: 		untie(%parmhash);
                   6083: 	    }
                   6084: 	    if ($thisparm) { return $thisparm; }
                   6085: 	}
1.594     albertel 6086: # ------------------------------------------ fourth, look in resource metadata
1.71      www      6087: 
1.218     albertel 6088: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 6089: 	my $filename;
                   6090: 	if (!$symbparm) { $symbparm=&symbread(); }
                   6091: 	if ($symbparm) {
1.409     www      6092: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 6093: 	} else {
1.620     albertel 6094: 	    $filename=$env{'request.filename'};
1.282     albertel 6095: 	}
                   6096: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.288     albertel 6097: 	if (defined($metadata)) { return $metadata; }
1.282     albertel 6098: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.288     albertel 6099: 	if (defined($metadata)) { return $metadata; }
1.142     www      6100: 
1.594     albertel 6101: # ---------------------------------------------- fourth, look in rest pf course
1.593     albertel 6102: 	if ($symbparm && defined($courseid) && 
1.620     albertel 6103: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 6104: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   6105: 				     $env{'course.'.$courseid.'.domain'},
                   6106: 				     'course',
                   6107: 				     ($courselevelm,$courselevel));
1.593     albertel 6108: 	    if (defined($coursereply)) { return $coursereply; }
                   6109: 	}
1.145     www      6110: # ------------------------------------------------------------------ Cascade up
1.218     albertel 6111: 	unless ($space eq '0') {
1.336     albertel 6112: 	    my @parts=split(/_/,$space);
                   6113: 	    my $id=pop(@parts);
                   6114: 	    my $part=join('_',@parts);
                   6115: 	    if ($part eq '') { $part='0'; }
                   6116: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 6117: 				 $symbparm,$udom,$uname,$section,1);
1.337     albertel 6118: 	    if (defined($partgeneral)) { return $partgeneral; }
1.218     albertel 6119: 	}
1.395     albertel 6120: 	if ($recurse) { return undef; }
                   6121: 	my $pack_def=&packages_tab_default($filename,$varname);
                   6122: 	if (defined($pack_def)) { return $pack_def; }
1.71      www      6123: 
1.48      www      6124: # ---------------------------------------------------- Any other user namespace
                   6125:     } elsif ($realm eq 'environment') {
                   6126: # ----------------------------------------------------------------- environment
1.620     albertel 6127: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   6128: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 6129: 	} else {
1.770     albertel 6130: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   6131: 		return '';
                   6132: 	    }
1.219     albertel 6133: 	    my %returnhash=&userenvironment($udom,$uname,
                   6134: 					    $spacequalifierrest);
                   6135: 	    return $returnhash{$spacequalifierrest};
                   6136: 	}
1.28      www      6137:     } elsif ($realm eq 'system') {
1.48      www      6138: # ----------------------------------------------------------------- system.time
                   6139: 	if ($space eq 'time') {
                   6140: 	    return time;
                   6141:         }
1.696     albertel 6142:     } elsif ($realm eq 'server') {
                   6143: # ----------------------------------------------------------------- system.time
                   6144: 	if ($space eq 'name') {
                   6145: 	    return $ENV{'SERVER_NAME'};
                   6146:         }
1.28      www      6147:     }
1.48      www      6148:     return '';
1.61      www      6149: }
                   6150: 
1.691     raeburn  6151: sub check_group_parms {
                   6152:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   6153:     my @groupitems = ();
                   6154:     my $resultitem;
                   6155:     my @levels = ($symbparm,$mapparm,$what);
                   6156:     foreach my $group (@{$groups}) {
                   6157:         foreach my $level (@levels) {
                   6158:              my $item = $courseid.'.['.$group.'].'.$level;
                   6159:              push(@groupitems,$item);
                   6160:         }
                   6161:     }
                   6162:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   6163:                             $env{'course.'.$courseid.'.domain'},
                   6164:                                      'course',@groupitems);
                   6165:     return $coursereply;
                   6166: }
                   6167: 
                   6168: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  6169:     my ($courseid,@groups) = @_;
                   6170:     @groups = sort(@groups);
1.691     raeburn  6171:     return @groups;
                   6172: }
                   6173: 
1.395     albertel 6174: sub packages_tab_default {
                   6175:     my ($uri,$varname)=@_;
                   6176:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 6177: 
                   6178:     my (@extension,@specifics,$do_default);
                   6179:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 6180: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 6181: 	if ($pack_type eq 'default') {
                   6182: 	    $do_default=1;
                   6183: 	} elsif ($pack_type eq 'extension') {
                   6184: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.848     albertel 6185: 	} elsif ($pack_part eq $part) {
                   6186: 	    # only look at packages defaults for packages that this id is
1.738     albertel 6187: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   6188: 	}
                   6189:     }
                   6190:     # first look for a package that matches the requested part id
                   6191:     foreach my $package (@specifics) {
                   6192: 	my (undef,$pack_type,$pack_part)=@{$package};
                   6193: 	next if ($pack_part ne $part);
                   6194: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6195: 	    return $packagetab{"$pack_type&$name&default"};
                   6196: 	}
                   6197:     }
                   6198:     # look for any possible matching non extension_ package
                   6199:     foreach my $package (@specifics) {
                   6200: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 6201: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6202: 	    return $packagetab{"$pack_type&$name&default"};
                   6203: 	}
1.585     albertel 6204: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 6205: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   6206: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 6207: 	}
                   6208:     }
1.738     albertel 6209:     # look for any posible extension_ match
                   6210:     foreach my $package (@extension) {
                   6211: 	my ($package,$pack_type)=@{$package};
                   6212: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   6213: 	    return $packagetab{"$pack_type&$name&default"};
                   6214: 	}
                   6215: 	if (defined($packagetab{$package."&$name&default"})) {
                   6216: 	    return $packagetab{$package."&$name&default"};
                   6217: 	}
                   6218:     }
                   6219:     # look for a global default setting
                   6220:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   6221: 	return $packagetab{"default&$name&default"};
                   6222:     }
1.395     albertel 6223:     return undef;
                   6224: }
                   6225: 
1.334     albertel 6226: sub add_prefix_and_part {
                   6227:     my ($prefix,$part)=@_;
                   6228:     my $keyroot;
                   6229:     if (defined($prefix) && $prefix !~ /^__/) {
                   6230: 	# prefix that has a part already
                   6231: 	$keyroot=$prefix;
                   6232:     } elsif (defined($prefix)) {
                   6233: 	# prefix that is missing a part
                   6234: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   6235:     } else {
                   6236: 	# no prefix at all
                   6237: 	if (defined($part)) { $keyroot='_'.$part; }
                   6238:     }
                   6239:     return $keyroot;
                   6240: }
                   6241: 
1.71      www      6242: # ---------------------------------------------------------------- Get metadata
                   6243: 
1.599     albertel 6244: my %metaentry;
1.71      www      6245: sub metadata {
1.176     www      6246:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      6247:     $uri=&declutter($uri);
1.288     albertel 6248:     # if it is a non metadata possible uri return quickly
1.529     albertel 6249:     if (($uri eq '') || 
                   6250: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 6251: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.423     albertel 6252:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
1.807     albertel 6253: 	($uri =~ m|home/$match_username/public_html/|)) {
1.468     albertel 6254: 	return undef;
1.288     albertel 6255:     }
1.73      www      6256:     my $filename=$uri;
                   6257:     $uri=~s/\.meta$//;
1.172     www      6258: #
                   6259: # Is the metadata already cached?
1.177     www      6260: # Look at timestamp of caching
1.172     www      6261: # Everything is cached by the main uri, libraries are never directly cached
                   6262: #
1.428     albertel 6263:     if (!defined($liburi)) {
1.599     albertel 6264: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 6265: 	if (defined($cached)) { return $result->{':'.$what}; }
                   6266:     }
                   6267:     {
1.172     www      6268: #
                   6269: # Is this a recursive call for a library?
                   6270: #
1.599     albertel 6271: #	if (! exists($metacache{$uri})) {
                   6272: #	    $metacache{$uri}={};
                   6273: #	}
1.171     www      6274:         if ($liburi) {
                   6275: 	    $liburi=&declutter($liburi);
                   6276:             $filename=$liburi;
1.401     bowersj2 6277:         } else {
1.599     albertel 6278: 	    &devalidate_cache_new('meta',$uri);
                   6279: 	    undef(%metaentry);
1.401     bowersj2 6280: 	}
1.140     www      6281:         my %metathesekeys=();
1.73      www      6282:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 6283: 	my $metastring;
1.768     albertel 6284: 	if ($uri !~ m -^(editupload)/-) {
1.543     albertel 6285: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 6286: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 6287: 	    $metastring=&getfile($file);
1.489     albertel 6288: 	}
1.208     albertel 6289:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      6290:         my $token;
1.140     www      6291:         undef %metathesekeys;
1.71      www      6292:         while ($token=$parser->get_token) {
1.339     albertel 6293: 	    if ($token->[0] eq 'S') {
                   6294: 		if (defined($token->[2]->{'package'})) {
1.172     www      6295: #
                   6296: # This is a package - get package info
                   6297: #
1.339     albertel 6298: 		    my $package=$token->[2]->{'package'};
                   6299: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6300: 		    if (defined($token->[2]->{'id'})) { 
                   6301: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   6302: 		    }
1.599     albertel 6303: 		    if ($metaentry{':packages'}) {
                   6304: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 6305: 		    } else {
1.599     albertel 6306: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 6307: 		    }
1.736     albertel 6308: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 6309: 			my $part=$keyroot;
                   6310: 			$part=~s/^\_//;
1.736     albertel 6311: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   6312: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   6313: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 6314: 			    # ignore package.tab specified default values
                   6315:                             # here &package_tab_default() will fetch those
                   6316: 			    if ($subp eq 'default') { next; }
1.736     albertel 6317: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 6318: 			    my $unikey;
                   6319: 			    if ($pack =~ /_0$/) {
                   6320: 				$unikey='parameter_0_'.$name;
                   6321: 				$part=0;
                   6322: 			    } else {
                   6323: 				$unikey='parameter'.$keyroot.'_'.$name;
                   6324: 			    }
1.339     albertel 6325: 			    if ($subp eq 'display') {
                   6326: 				$value.=' [Part: '.$part.']';
                   6327: 			    }
1.599     albertel 6328: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 6329: 			    $metathesekeys{$unikey}=1;
1.599     albertel 6330: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6331: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 6332: 			    }
1.599     albertel 6333: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   6334: 				$metaentry{':'.$unikey}=
                   6335: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 6336: 			    }
1.339     albertel 6337: 			}
                   6338: 		    }
                   6339: 		} else {
1.172     www      6340: #
                   6341: # This is not a package - some other kind of start tag
1.339     albertel 6342: #
                   6343: 		    my $entry=$token->[1];
                   6344: 		    my $unikey;
                   6345: 		    if ($entry eq 'import') {
                   6346: 			$unikey='';
                   6347: 		    } else {
                   6348: 			$unikey=$entry;
                   6349: 		    }
                   6350: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   6351: 
                   6352: 		    if (defined($token->[2]->{'id'})) { 
                   6353: 			$unikey.='_'.$token->[2]->{'id'}; 
                   6354: 		    }
1.175     www      6355: 
1.339     albertel 6356: 		    if ($entry eq 'import') {
1.175     www      6357: #
                   6358: # Importing a library here
1.339     albertel 6359: #
                   6360: 			if ($depthcount<20) {
                   6361: 			    my $location=$parser->get_text('/import');
                   6362: 			    my $dir=$filename;
                   6363: 			    $dir=~s|[^/]*$||;
                   6364: 			    $location=&filelocation($dir,$location);
1.736     albertel 6365: 			    my $metadata = 
                   6366: 				&metadata($uri,'keys', $location,$unikey,
                   6367: 					  $depthcount+1);
                   6368: 			    foreach my $meta (split(',',$metadata)) {
                   6369: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   6370: 				$metathesekeys{$meta}=1;
1.339     albertel 6371: 			    }
                   6372: 			}
                   6373: 		    } else { 
                   6374: 			
                   6375: 			if (defined($token->[2]->{'name'})) { 
                   6376: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   6377: 			}
                   6378: 			$metathesekeys{$unikey}=1;
1.736     albertel 6379: 			foreach my $param (@{$token->[3]}) {
                   6380: 			    $metaentry{':'.$unikey.'.'.$param} =
                   6381: 				$token->[2]->{$param};
1.339     albertel 6382: 			}
                   6383: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 6384: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 6385: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   6386: 		 # only ws inside the tag, and not in default, so use default
                   6387: 		 # as value
1.599     albertel 6388: 			    $metaentry{':'.$unikey}=$default;
1.339     albertel 6389: 			} else {
1.321     albertel 6390: 		  # either something interesting inside the tag or default
                   6391:                   # uninteresting
1.599     albertel 6392: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 6393: 			}
1.172     www      6394: # end of not-a-package not-a-library import
1.339     albertel 6395: 		    }
1.172     www      6396: # end of not-a-package start tag
1.339     albertel 6397: 		}
1.172     www      6398: # the next is the end of "start tag"
1.339     albertel 6399: 	    }
                   6400: 	}
1.483     albertel 6401: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.737     albertel 6402: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 6403: 	    #no specific packages #how's our extension
                   6404: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 6405: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 6406: 					 \%metathesekeys);
                   6407: 	}
1.599     albertel 6408: 	if (!exists($metaentry{':packages'})) {
1.737     albertel 6409: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 6410: 		#no specific packages well let's get default then
                   6411: 		if ($key!~/^default&/) { next; }
1.488     albertel 6412: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 6413: 					     \%metathesekeys);
                   6414: 	    }
                   6415: 	}
1.338     www      6416: # are there custom rights to evaluate
1.599     albertel 6417: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 6418: 
1.338     www      6419:     #
                   6420:     # Importing a rights file here
1.339     albertel 6421:     #
                   6422: 	    unless ($depthcount) {
1.599     albertel 6423: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 6424: 		my $dir=$filename;
                   6425: 		$dir=~s|[^/]*$||;
                   6426: 		$location=&filelocation($dir,$location);
1.736     albertel 6427: 		my $rights_metadata =
                   6428: 		    &metadata($uri,'keys',$location,'_rights',
                   6429: 			      $depthcount+1);
                   6430: 		foreach my $rights (split(',',$rights_metadata)) {
                   6431: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   6432: 		    $metathesekeys{$rights}=1;
1.339     albertel 6433: 		}
                   6434: 	    }
                   6435: 	}
1.737     albertel 6436: 	# uniqifiy package listing
                   6437: 	my %seen;
                   6438: 	my @uniq_packages =
                   6439: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   6440: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   6441: 
                   6442: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 6443: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   6444: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.699     albertel 6445: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
1.177     www      6446: # this is the end of "was not already recently cached
1.71      www      6447:     }
1.599     albertel 6448:     return $metaentry{':'.$what};
1.261     albertel 6449: }
                   6450: 
1.488     albertel 6451: sub metadata_create_package_def {
1.483     albertel 6452:     my ($uri,$key,$package,$metathesekeys)=@_;
                   6453:     my ($pack,$name,$subp)=split(/\&/,$key);
                   6454:     if ($subp eq 'default') { next; }
                   6455:     
1.599     albertel 6456:     if (defined($metaentry{':packages'})) {
                   6457: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 6458:     } else {
1.599     albertel 6459: 	$metaentry{':packages'}=$package;
1.483     albertel 6460:     }
                   6461:     my $value=$packagetab{$key};
                   6462:     my $unikey;
                   6463:     $unikey='parameter_0_'.$name;
1.599     albertel 6464:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 6465:     $$metathesekeys{$unikey}=1;
1.599     albertel 6466:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   6467: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 6468:     }
1.599     albertel 6469:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   6470: 	$metaentry{':'.$unikey}=
                   6471: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 6472:     }
                   6473: }
                   6474: 
1.261     albertel 6475: sub metadata_generate_part0 {
                   6476:     my ($metadata,$metacache,$uri) = @_;
                   6477:     my %allnames;
1.737     albertel 6478:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 6479: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 6480: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   6481: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 6482: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 6483: 	    $allnames{$name}=$part;
                   6484: 	  }
                   6485: 	}
                   6486:     }
                   6487:     foreach my $name (keys(%allnames)) {
                   6488:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 6489:       my $key=":parameter_0_$name";
1.261     albertel 6490:       $$metacache{"$key.part"}='0';
                   6491:       $$metacache{"$key.name"}=$name;
1.428     albertel 6492:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 6493: 					   $allnames{$name}.'_'.$name.
                   6494: 					   '.type'};
1.428     albertel 6495:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 6496: 			     '.display'};
1.644     www      6497:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 6498:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 6499:       $$metacache{"$key.display"}=$olddis;
                   6500:     }
1.71      www      6501: }
                   6502: 
1.764     albertel 6503: # ------------------------------------------------------ Devalidate title cache
                   6504: 
                   6505: sub devalidate_title_cache {
                   6506:     my ($url)=@_;
                   6507:     if (!$env{'request.course.id'}) { return; }
                   6508:     my $symb=&symbread($url);
                   6509:     if (!$symb) { return; }
                   6510:     my $key=$env{'request.course.id'}."\0".$symb;
                   6511:     &devalidate_cache_new('title',$key);
                   6512: }
                   6513: 
1.301     www      6514: # ------------------------------------------------- Get the title of a resource
                   6515: 
                   6516: sub gettitle {
                   6517:     my $urlsymb=shift;
                   6518:     my $symb=&symbread($urlsymb);
1.534     albertel 6519:     if ($symb) {
1.620     albertel 6520: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 6521: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 6522: 	if (defined($cached)) { 
                   6523: 	    return $result;
                   6524: 	}
1.534     albertel 6525: 	my ($map,$resid,$url)=&decode_symb($symb);
                   6526: 	my $title='';
                   6527: 	my %bighash;
1.620     albertel 6528: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.534     albertel 6529: 		&GDBM_READER(),0640)) {
                   6530: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   6531: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
                   6532: 	    untie %bighash;
                   6533: 	}
                   6534: 	$title=~s/\&colon\;/\:/gs;
                   6535: 	if ($title) {
1.599     albertel 6536: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 6537: 	}
                   6538: 	$urlsymb=$url;
                   6539:     }
                   6540:     my $title=&metadata($urlsymb,'title');
                   6541:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   6542:     return $title;
1.301     www      6543: }
1.613     albertel 6544: 
1.614     albertel 6545: sub get_slot {
                   6546:     my ($which,$cnum,$cdom)=@_;
                   6547:     if (!$cnum || !$cdom) {
1.790     albertel 6548: 	(undef,my $courseid)=&whichuser();
1.620     albertel 6549: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   6550: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 6551:     }
1.703     albertel 6552:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   6553:     my %slotinfo;
                   6554:     if (exists($remembered{$key})) {
                   6555: 	$slotinfo{$which} = $remembered{$key};
                   6556:     } else {
                   6557: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   6558: 	&Apache::lonhomework::showhash(%slotinfo);
                   6559: 	my ($tmp)=keys(%slotinfo);
                   6560: 	if ($tmp=~/^error:/) { return (); }
                   6561: 	$remembered{$key} = $slotinfo{$which};
                   6562:     }
1.616     albertel 6563:     if (ref($slotinfo{$which}) eq 'HASH') {
                   6564: 	return %{$slotinfo{$which}};
                   6565:     }
                   6566:     return $slotinfo{$which};
1.614     albertel 6567: }
1.31      www      6568: # ------------------------------------------------- Update symbolic store links
                   6569: 
                   6570: sub symblist {
                   6571:     my ($mapname,%newhash)=@_;
1.438     www      6572:     $mapname=&deversion(&declutter($mapname));
1.31      www      6573:     my %hash;
1.620     albertel 6574:     if (($env{'request.course.fn'}) && (%newhash)) {
                   6575:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6576:                       &GDBM_WRCREAT(),0640)) {
1.711     albertel 6577: 	    foreach my $url (keys %newhash) {
                   6578: 		next if ($url eq 'last_known'
                   6579: 			 && $env{'form.no_update_last_known'});
                   6580: 		$hash{declutter($url)}=&encode_symb($mapname,
                   6581: 						    $newhash{$url}->[1],
                   6582: 						    $newhash{$url}->[0]);
1.191     harris41 6583:             }
1.31      www      6584:             if (untie(%hash)) {
                   6585: 		return 'ok';
                   6586:             }
                   6587:         }
                   6588:     }
                   6589:     return 'error';
1.212     www      6590: }
                   6591: 
                   6592: # --------------------------------------------------------------- Verify a symb
                   6593: 
                   6594: sub symbverify {
1.510     www      6595:     my ($symb,$thisurl)=@_;
                   6596:     my $thisfn=$thisurl;
1.439     www      6597:     $thisfn=&declutter($thisfn);
1.215     www      6598: # direct jump to resource in page or to a sequence - will construct own symbs
                   6599:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   6600: # check URL part
1.409     www      6601:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      6602: 
1.431     www      6603:     unless ($url eq $thisfn) { return 0; }
1.213     www      6604: 
1.216     www      6605:     $symb=&symbclean($symb);
1.510     www      6606:     $thisurl=&deversion($thisurl);
1.439     www      6607:     $thisfn=&deversion($thisfn);
1.213     www      6608: 
                   6609:     my %bighash;
                   6610:     my $okay=0;
1.431     www      6611: 
1.620     albertel 6612:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6613:                             &GDBM_READER(),0640)) {
1.510     www      6614:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.216     www      6615:         unless ($ids) { 
1.510     www      6616:            $ids=$bighash{'ids_/'.$thisurl};
1.216     www      6617:         }
                   6618:         if ($ids) {
                   6619: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 6620: 	    foreach my $id (split(/\,/,$ids)) {
                   6621: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      6622:                if (
                   6623:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   6624:    eq $symb) { 
1.620     albertel 6625: 		   if (($env{'request.role.adv'}) ||
1.800     albertel 6626: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
1.582     albertel 6627: 		       $okay=1; 
                   6628: 		   }
                   6629: 	       }
1.216     www      6630: 	   }
                   6631:         }
1.213     www      6632: 	untie(%bighash);
                   6633:     }
                   6634:     return $okay;
1.31      www      6635: }
                   6636: 
1.210     www      6637: # --------------------------------------------------------------- Clean-up symb
                   6638: 
                   6639: sub symbclean {
                   6640:     my $symb=shift;
1.568     albertel 6641:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      6642: # remove version from map
                   6643:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      6644: 
1.210     www      6645: # remove version from URL
                   6646:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      6647: 
1.507     www      6648: # remove wrapper
                   6649: 
1.510     www      6650:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 6651:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      6652:     return $symb;
1.409     www      6653: }
                   6654: 
                   6655: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 6656: 
                   6657: sub encode_symb {
                   6658:     my ($map,$resid,$url)=@_;
                   6659:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   6660: }
1.409     www      6661: 
                   6662: sub decode_symb {
1.568     albertel 6663:     my $symb=shift;
                   6664:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   6665:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      6666:     return (&fixversion($map),$resid,&fixversion($url));
                   6667: }
                   6668: 
                   6669: sub fixversion {
                   6670:     my $fn=shift;
1.609     banghart 6671:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      6672:     my %bighash;
                   6673:     my $uri=&clutter($fn);
1.620     albertel 6674:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      6675: # is this cached?
1.599     albertel 6676:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      6677:     if (defined($cached)) { return $result; }
                   6678: # unfortunately not cached, or expired
1.620     albertel 6679:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      6680: 	    &GDBM_READER(),0640)) {
                   6681:  	if ($bighash{'version_'.$uri}) {
                   6682:  	    my $version=$bighash{'version_'.$uri};
1.444     www      6683:  	    unless (($version eq 'mostrecent') || 
                   6684: 		    ($version==&getversion($uri))) {
1.440     www      6685:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   6686:  	    }
                   6687:  	}
                   6688:  	untie %bighash;
1.413     www      6689:     }
1.599     albertel 6690:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      6691: }
                   6692: 
                   6693: sub deversion {
                   6694:     my $url=shift;
                   6695:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   6696:     return $url;
1.210     www      6697: }
                   6698: 
1.31      www      6699: # ------------------------------------------------------ Return symb list entry
                   6700: 
                   6701: sub symbread {
1.249     www      6702:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 6703:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 6704:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      6705: # no filename provided? try from environment
1.44      www      6706:     unless ($thisfn) {
1.620     albertel 6707:         if ($env{'request.symb'}) {
                   6708: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 6709: 	}
1.620     albertel 6710: 	$thisfn=$env{'request.filename'};
1.44      www      6711:     }
1.569     albertel 6712:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      6713: # is that filename actually a symb? Verify, clean, and return
                   6714:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 6715: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 6716: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 6717: 	}
1.242     www      6718:     }
1.44      www      6719:     $thisfn=declutter($thisfn);
1.31      www      6720:     my %hash;
1.37      www      6721:     my %bighash;
                   6722:     my $syval='';
1.620     albertel 6723:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  6724:         my $targetfn = $thisfn;
1.609     banghart 6725:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  6726:             $targetfn = 'adm/wrapper/'.$thisfn;
                   6727:         }
1.687     albertel 6728: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   6729: 	    $targetfn=$1;
                   6730: 	}
1.620     albertel 6731:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 6732:                       &GDBM_READER(),0640)) {
1.481     raeburn  6733: 	    $syval=$hash{$targetfn};
1.37      www      6734:             untie(%hash);
                   6735:         }
                   6736: # ---------------------------------------------------------- There was an entry
                   6737:         if ($syval) {
1.601     albertel 6738: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 6739: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.601     albertel 6740: 		    #&appenv('request.ambiguous' => $thisfn);
1.620     albertel 6741: 		    #return $env{$cache_str}='';
1.601     albertel 6742: 		#}    
                   6743: 		#$syval.=$1;
                   6744: 	    #}
1.37      www      6745:         } else {
                   6746: # ------------------------------------------------------- Was not in symb table
1.620     albertel 6747:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 6748:                             &GDBM_READER(),0640)) {
1.37      www      6749: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      6750:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      6751:               unless ($ids) { 
                   6752:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      6753:               }
                   6754:               unless ($ids) {
                   6755: # alias?
                   6756: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      6757:               }
1.37      www      6758:               if ($ids) {
                   6759: # ------------------------------------------------------------------- Has ID(s)
                   6760:                  my @possibilities=split(/\,/,$ids);
1.39      www      6761:                  if ($#possibilities==0) {
                   6762: # ----------------------------------------------- There is only one possibility
1.37      www      6763: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 6764: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6765: 						    $resid,$thisfn);
1.249     www      6766:                  } elsif (!$donotrecurse) {
1.39      www      6767: # ------------------------------------------ There is more than one possibility
                   6768:                      my $realpossible=0;
1.800     albertel 6769:                      foreach my $id (@possibilities) {
                   6770: 			 my $file=$bighash{'src_'.$id};
1.39      www      6771:                          if (&allowed('bre',$file)) {
1.800     albertel 6772:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      6773:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   6774: 				$realpossible++;
1.626     albertel 6775:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   6776: 						    $resid,$thisfn);
1.39      www      6777:                             }
                   6778: 			 }
1.191     harris41 6779:                      }
1.39      www      6780: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      6781:                  } else {
                   6782:                      $syval='';
1.37      www      6783:                  }
                   6784: 	      }
                   6785:               untie(%bighash)
1.481     raeburn  6786:            }
1.31      www      6787:         }
1.62      www      6788:         if ($syval) {
1.620     albertel 6789: 	    return $env{$cache_str}=$syval;
1.62      www      6790:         }
1.31      www      6791:     }
1.44      www      6792:     &appenv('request.ambiguous' => $thisfn);
1.620     albertel 6793:     return $env{$cache_str}='';
1.31      www      6794: }
                   6795: 
                   6796: # ---------------------------------------------------------- Return random seed
                   6797: 
1.32      www      6798: sub numval {
                   6799:     my $txt=shift;
                   6800:     $txt=~tr/A-J/0-9/;
                   6801:     $txt=~tr/a-j/0-9/;
                   6802:     $txt=~tr/K-T/0-9/;
                   6803:     $txt=~tr/k-t/0-9/;
                   6804:     $txt=~tr/U-Z/0-5/;
                   6805:     $txt=~tr/u-z/0-5/;
                   6806:     $txt=~s/\D//g;
1.564     albertel 6807:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      6808:     return int($txt);
1.368     albertel 6809: }
                   6810: 
1.484     albertel 6811: sub numval2 {
                   6812:     my $txt=shift;
                   6813:     $txt=~tr/A-J/0-9/;
                   6814:     $txt=~tr/a-j/0-9/;
                   6815:     $txt=~tr/K-T/0-9/;
                   6816:     $txt=~tr/k-t/0-9/;
                   6817:     $txt=~tr/U-Z/0-5/;
                   6818:     $txt=~tr/u-z/0-5/;
                   6819:     $txt=~s/\D//g;
                   6820:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6821:     my $total;
                   6822:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 6823:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 6824:     return int($total);
                   6825: }
                   6826: 
1.575     albertel 6827: sub numval3 {
                   6828:     use integer;
                   6829:     my $txt=shift;
                   6830:     $txt=~tr/A-J/0-9/;
                   6831:     $txt=~tr/a-j/0-9/;
                   6832:     $txt=~tr/K-T/0-9/;
                   6833:     $txt=~tr/k-t/0-9/;
                   6834:     $txt=~tr/U-Z/0-5/;
                   6835:     $txt=~tr/u-z/0-5/;
                   6836:     $txt=~s/\D//g;
                   6837:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   6838:     my $total;
                   6839:     foreach my $val (@txts) { $total+=$val; }
                   6840:     if ($_64bit) { $total=(($total<<32)>>32); }
                   6841:     return $total;
                   6842: }
                   6843: 
1.675     albertel 6844: sub digest {
                   6845:     my ($data)=@_;
                   6846:     my $digest=&Digest::MD5::md5($data);
                   6847:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   6848:     my ($e,$f);
                   6849:     {
                   6850:         use integer;
                   6851:         $e=($a+$b);
                   6852:         $f=($c+$d);
                   6853:         if ($_64bit) {
                   6854:             $e=(($e<<32)>>32);
                   6855:             $f=(($f<<32)>>32);
                   6856:         }
                   6857:     }
                   6858:     if (wantarray) {
                   6859: 	return ($e,$f);
                   6860:     } else {
                   6861: 	my $g;
                   6862: 	{
                   6863: 	    use integer;
                   6864: 	    $g=($e+$f);
                   6865: 	    if ($_64bit) {
                   6866: 		$g=(($g<<32)>>32);
                   6867: 	    }
                   6868: 	}
                   6869: 	return $g;
                   6870:     }
                   6871: }
                   6872: 
1.368     albertel 6873: sub latest_rnd_algorithm_id {
1.675     albertel 6874:     return '64bit5';
1.366     albertel 6875: }
1.32      www      6876: 
1.503     albertel 6877: sub get_rand_alg {
                   6878:     my ($courseid)=@_;
1.790     albertel 6879:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 6880:     if ($courseid) {
1.620     albertel 6881: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 6882:     }
                   6883:     return &latest_rnd_algorithm_id();
                   6884: }
                   6885: 
1.562     albertel 6886: sub validCODE {
                   6887:     my ($CODE)=@_;
                   6888:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   6889:     return 0;
                   6890: }
                   6891: 
1.491     albertel 6892: sub getCODE {
1.620     albertel 6893:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 6894:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   6895: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   6896: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 6897: 	return $Apache::lonhomework::history{'resource.CODE'};
                   6898:     }
                   6899:     return undef;
                   6900: }
                   6901: 
1.31      www      6902: sub rndseed {
1.155     albertel 6903:     my ($symb,$courseid,$domain,$username)=@_;
1.366     albertel 6904: 
1.790     albertel 6905:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.155     albertel 6906:     if (!$symb) {
1.366     albertel 6907: 	unless ($symb=$wsymb) { return time; }
                   6908:     }
                   6909:     if (!$courseid) { $courseid=$wcourseid; }
                   6910:     if (!$domain) { $domain=$wdomain; }
                   6911:     if (!$username) { $username=$wusername }
1.503     albertel 6912:     my $which=&get_rand_alg();
1.803     albertel 6913: 
1.491     albertel 6914:     if (defined(&getCODE())) {
1.675     albertel 6915: 	if ($which eq '64bit5') {
                   6916: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   6917: 	} elsif ($which eq '64bit4') {
1.575     albertel 6918: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   6919: 	} else {
                   6920: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   6921: 	}
1.675     albertel 6922:     } elsif ($which eq '64bit5') {
                   6923: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 6924:     } elsif ($which eq '64bit4') {
                   6925: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 6926:     } elsif ($which eq '64bit3') {
                   6927: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 6928:     } elsif ($which eq '64bit2') {
                   6929: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 6930:     } elsif ($which eq '64bit') {
                   6931: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   6932:     }
                   6933:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   6934: }
                   6935: 
                   6936: sub rndseed_32bit {
                   6937:     my ($symb,$courseid,$domain,$username)=@_;
                   6938:     {
                   6939: 	use integer;
                   6940: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   6941: 	my $symbseed=numval($symb) << 22;
                   6942: 	my $namechck=unpack("%32C*",$username) << 17;
                   6943: 	my $nameseed=numval($username) << 12;
                   6944: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   6945: 	my $courseseed=unpack("%32C*",$courseid);
                   6946: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 6947: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6948: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6949: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 6950: 	return $num;
                   6951:     }
                   6952: }
                   6953: 
                   6954: sub rndseed_64bit {
                   6955:     my ($symb,$courseid,$domain,$username)=@_;
                   6956:     {
                   6957: 	use integer;
                   6958: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   6959: 	my $symbseed=numval($symb) << 10;
                   6960: 	my $namechck=unpack("%32S*",$username);
                   6961: 	
                   6962: 	my $nameseed=numval($username) << 21;
                   6963: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   6964: 	my $courseseed=unpack("%32S*",$courseid);
                   6965: 	
                   6966: 	my $num1=$symbchck+$symbseed+$namechck;
                   6967: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6968: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6969: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 6970: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 6971: 	return "$num1,$num2";
1.155     albertel 6972:     }
1.366     albertel 6973: }
                   6974: 
1.443     albertel 6975: sub rndseed_64bit2 {
                   6976:     my ($symb,$courseid,$domain,$username)=@_;
                   6977:     {
                   6978: 	use integer;
                   6979: 	# strings need to be an even # of cahracters long, it it is odd the
                   6980:         # last characters gets thrown away
                   6981: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   6982: 	my $symbseed=numval($symb) << 10;
                   6983: 	my $namechck=unpack("%32S*",$username.' ');
                   6984: 	
                   6985: 	my $nameseed=numval($username) << 21;
1.501     albertel 6986: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   6987: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   6988: 	
                   6989: 	my $num1=$symbchck+$symbseed+$namechck;
                   6990: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 6991: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   6992: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 6993: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 6994: 	return "$num1,$num2";
                   6995:     }
                   6996: }
                   6997: 
                   6998: sub rndseed_64bit3 {
                   6999:     my ($symb,$courseid,$domain,$username)=@_;
                   7000:     {
                   7001: 	use integer;
                   7002: 	# strings need to be an even # of cahracters long, it it is odd the
                   7003:         # last characters gets thrown away
                   7004: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7005: 	my $symbseed=numval2($symb) << 10;
                   7006: 	my $namechck=unpack("%32S*",$username.' ');
                   7007: 	
                   7008: 	my $nameseed=numval2($username) << 21;
1.443     albertel 7009: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7010: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7011: 	
                   7012: 	my $num1=$symbchck+$symbseed+$namechck;
                   7013: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7014: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7015: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 7016: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7017: 	
1.503     albertel 7018: 	return "$num1:$num2";
1.443     albertel 7019:     }
                   7020: }
                   7021: 
1.575     albertel 7022: sub rndseed_64bit4 {
                   7023:     my ($symb,$courseid,$domain,$username)=@_;
                   7024:     {
                   7025: 	use integer;
                   7026: 	# strings need to be an even # of cahracters long, it it is odd the
                   7027:         # last characters gets thrown away
                   7028: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   7029: 	my $symbseed=numval3($symb) << 10;
                   7030: 	my $namechck=unpack("%32S*",$username.' ');
                   7031: 	
                   7032: 	my $nameseed=numval3($username) << 21;
                   7033: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   7034: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7035: 	
                   7036: 	my $num1=$symbchck+$symbseed+$namechck;
                   7037: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 7038: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   7039: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 7040: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
                   7041: 	
                   7042: 	return "$num1:$num2";
                   7043:     }
                   7044: }
                   7045: 
1.675     albertel 7046: sub rndseed_64bit5 {
                   7047:     my ($symb,$courseid,$domain,$username)=@_;
                   7048:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   7049:     return "$num1:$num2";
                   7050: }
                   7051: 
1.366     albertel 7052: sub rndseed_CODE_64bit {
                   7053:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 7054:     {
1.366     albertel 7055: 	use integer;
1.443     albertel 7056: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 7057: 	my $symbseed=numval2($symb);
1.491     albertel 7058: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7059: 	my $CODEseed=numval(&getCODE());
1.443     albertel 7060: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 7061: 	my $num1=$symbseed+$CODEchck;
                   7062: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7063: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7064: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 7065: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7066: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 7067: 	return "$num1:$num2";
1.366     albertel 7068:     }
                   7069: }
                   7070: 
1.575     albertel 7071: sub rndseed_CODE_64bit4 {
                   7072:     my ($symb,$courseid,$domain,$username)=@_;
                   7073:     {
                   7074: 	use integer;
                   7075: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   7076: 	my $symbseed=numval3($symb);
                   7077: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   7078: 	my $CODEseed=numval3(&getCODE());
                   7079: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   7080: 	my $num1=$symbseed+$CODEchck;
                   7081: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 7082: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   7083: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 7084: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   7085: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   7086: 	return "$num1:$num2";
                   7087:     }
                   7088: }
                   7089: 
1.675     albertel 7090: sub rndseed_CODE_64bit5 {
                   7091:     my ($symb,$courseid,$domain,$username)=@_;
                   7092:     my $code = &getCODE();
                   7093:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   7094:     return "$num1:$num2";
                   7095: }
                   7096: 
1.366     albertel 7097: sub setup_random_from_rndseed {
                   7098:     my ($rndseed)=@_;
1.503     albertel 7099:     if ($rndseed =~/([,:])/) {
                   7100: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 7101: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   7102:     } else {
                   7103: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 7104:     }
1.36      albertel 7105: }
                   7106: 
1.474     albertel 7107: sub latest_receipt_algorithm_id {
1.835     albertel 7108:     return 'receipt3';
1.474     albertel 7109: }
                   7110: 
1.480     www      7111: sub recunique {
                   7112:     my $fucourseid=shift;
                   7113:     my $unique;
1.835     albertel 7114:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   7115: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7116: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      7117:     } else {
                   7118: 	$unique=$perlvar{'lonReceipt'};
                   7119:     }
                   7120:     return unpack("%32C*",$unique);
                   7121: }
                   7122: 
                   7123: sub recprefix {
                   7124:     my $fucourseid=shift;
                   7125:     my $prefix;
1.835     albertel 7126:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   7127: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 7128: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      7129:     } else {
                   7130: 	$prefix=$perlvar{'lonHostID'};
                   7131:     }
                   7132:     return unpack("%32C*",$prefix);
                   7133: }
                   7134: 
1.76      www      7135: sub ireceipt {
1.474     albertel 7136:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 7137: 
                   7138:     my $return =&recprefix($fucourseid).'-';
                   7139: 
                   7140:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   7141: 	$env{'request.state'} eq 'construct') {
                   7142: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   7143: 	return $return;
                   7144:     }
                   7145: 
1.76      www      7146:     my $cuname=unpack("%32C*",$funame);
                   7147:     my $cudom=unpack("%32C*",$fudom);
                   7148:     my $cucourseid=unpack("%32C*",$fucourseid);
                   7149:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      7150:     my $cunique=&recunique($fucourseid);
1.474     albertel 7151:     my $cpart=unpack("%32S*",$part);
1.835     albertel 7152:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   7153: 
1.790     albertel 7154: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 7155: 			       
                   7156: 	$return.= ($cunique%$cuname+
                   7157: 		   $cunique%$cudom+
                   7158: 		   $cusymb%$cuname+
                   7159: 		   $cusymb%$cudom+
                   7160: 		   $cucourseid%$cuname+
                   7161: 		   $cucourseid%$cudom+
                   7162: 		   $cpart%$cuname+
                   7163: 		   $cpart%$cudom);
                   7164:     } else {
                   7165: 	$return.= ($cunique%$cuname+
                   7166: 		   $cunique%$cudom+
                   7167: 		   $cusymb%$cuname+
                   7168: 		   $cusymb%$cudom+
                   7169: 		   $cucourseid%$cuname+
                   7170: 		   $cucourseid%$cudom);
                   7171:     }
                   7172:     return $return;
1.76      www      7173: }
                   7174: 
                   7175: sub receipt {
1.474     albertel 7176:     my ($part)=@_;
1.790     albertel 7177:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 7178:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      7179: }
1.260     ng       7180: 
1.790     albertel 7181: sub whichuser {
                   7182:     my ($passedsymb)=@_;
                   7183:     my ($symb,$courseid,$domain,$name,$publicuser);
                   7184:     if (defined($env{'form.grade_symb'})) {
                   7185: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   7186: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   7187: 	if (!$allowed &&
                   7188: 	    exists($env{'request.course.sec'}) &&
                   7189: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   7190: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   7191: 			      '/'.$env{'request.course.sec'});
                   7192: 	}
                   7193: 	if ($allowed) {
                   7194: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   7195: 	    $courseid=$tmp_courseid;
                   7196: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   7197: 	    ($name)=&get_env_multiple('form.grade_username');
                   7198: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   7199: 	}
                   7200:     }
                   7201:     if (!$passedsymb) {
                   7202: 	$symb=&symbread();
                   7203:     } else {
                   7204: 	$symb=$passedsymb;
                   7205:     }
                   7206:     $courseid=$env{'request.course.id'};
                   7207:     $domain=$env{'user.domain'};
                   7208:     $name=$env{'user.name'};
                   7209:     if ($name eq 'public' && $domain eq 'public') {
                   7210: 	if (!defined($env{'form.username'})) {
                   7211: 	    $env{'form.username'}.=time.rand(10000000);
                   7212: 	}
                   7213: 	$name.=$env{'form.username'};
                   7214:     }
                   7215:     return ($symb,$courseid,$domain,$name,$publicuser);
                   7216: 
                   7217: }
                   7218: 
1.36      albertel 7219: # ------------------------------------------------------------ Serves up a file
1.472     albertel 7220: # returns either the contents of the file or 
                   7221: # -1 if the file doesn't exist
1.481     raeburn  7222: #
                   7223: # if the target is a file that was uploaded via DOCS, 
                   7224: # a check will be made to see if a current copy exists on the local server,
                   7225: # if it does this will be served, otherwise a copy will be retrieved from
                   7226: # the home server for the course and stored in /home/httpd/html/userfiles on
                   7227: # the local server.   
1.472     albertel 7228: 
1.36      albertel 7229: sub getfile {
1.538     albertel 7230:     my ($file) = @_;
1.609     banghart 7231:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 7232:     &repcopy($file);
                   7233:     return &readfile($file);
                   7234: }
                   7235: 
                   7236: sub repcopy_userfile {
                   7237:     my ($file)=@_;
1.609     banghart 7238:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 7239:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 7240:     my ($cdom,$cnum,$filename) = 
1.811     albertel 7241: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 7242:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   7243:     if (-e "$file") {
1.828     www      7244: # we already have a local copy, check it out
1.538     albertel 7245: 	my @fileinfo = stat($file);
1.828     www      7246: 	my $rtncode;
                   7247: 	my $info;
1.538     albertel 7248: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 7249: 	if ($lwpresp ne 'ok') {
1.828     www      7250: # there is no such file anymore, even though we had a local copy
1.482     albertel 7251: 	    if ($rtncode eq '404') {
1.538     albertel 7252: 		unlink($file);
1.482     albertel 7253: 	    }
                   7254: 	    return -1;
                   7255: 	}
                   7256: 	if ($info < $fileinfo[9]) {
1.828     www      7257: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  7258: 	    return 'ok';
1.828     www      7259: 	} else {
                   7260: # the file is outdated, get rid of it
                   7261: 	    unlink($file);
1.482     albertel 7262: 	}
1.828     www      7263:     }
                   7264: # one way or the other, at this point, we don't have the file
                   7265: # construct the correct path for the file
                   7266:     my @parts = ($cdom,$cnum); 
                   7267:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   7268: 	push @parts, split(/\//,$1);
                   7269:     }
                   7270:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   7271:     foreach my $part (@parts) {
                   7272: 	$path .= '/'.$part;
                   7273: 	if (!-e $path) {
                   7274: 	    mkdir($path,0770);
1.482     albertel 7275: 	}
                   7276:     }
1.828     www      7277: # now the path exists for sure
                   7278: # get a user agent
                   7279:     my $ua=new LWP::UserAgent;
                   7280:     my $transferfile=$file.'.in.transfer';
                   7281: # FIXME: this should flock
                   7282:     if (-e $transferfile) { return 'ok'; }
                   7283:     my $request;
                   7284:     $uri=~s/^\///;
1.838     albertel 7285:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
1.828     www      7286:     my $response=$ua->request($request,$transferfile);
                   7287: # did it work?
                   7288:     if ($response->is_error()) {
                   7289: 	unlink($transferfile);
                   7290: 	&logthis("Userfile repcopy failed for $uri");
                   7291: 	return -1;
                   7292:     }
                   7293: # worked, rename the transfer file
                   7294:     rename($transferfile,$file);
1.607     raeburn  7295:     return 'ok';
1.481     raeburn  7296: }
                   7297: 
1.517     albertel 7298: sub tokenwrapper {
                   7299:     my $uri=shift;
1.552     albertel 7300:     $uri=~s|^http\://([^/]+)||;
                   7301:     $uri=~s|^/||;
1.620     albertel 7302:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 7303:     my $token=$1;
1.552     albertel 7304:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   7305:     if ($udom && $uname && $file) {
                   7306: 	$file=~s|(\?\.*)*$||;
1.620     albertel 7307:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
1.838     albertel 7308:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
1.517     albertel 7309:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   7310:                                '&tokenissued='.$perlvar{'lonHostID'};
                   7311:     } else {
                   7312:         return '/adm/notfound.html';
                   7313:     }
                   7314: }
                   7315: 
1.828     www      7316: # call with reqtype HEAD: get last modification time
                   7317: # call with reqtype GET: get the file contents
                   7318: # Do not call this with reqtype GET for large files! It loads everything into memory
                   7319: #
1.481     raeburn  7320: sub getuploaded {
                   7321:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   7322:     $uri=~s/^\///;
1.838     albertel 7323:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
1.481     raeburn  7324:     my $ua=new LWP::UserAgent;
                   7325:     my $request=new HTTP::Request($reqtype,$uri);
                   7326:     my $response=$ua->request($request);
                   7327:     $$rtncode = $response->code;
1.482     albertel 7328:     if (! $response->is_success()) {
                   7329: 	return 'failed';
                   7330:     }      
                   7331:     if ($reqtype eq 'HEAD') {
1.486     www      7332: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 7333:     } elsif ($reqtype eq 'GET') {
                   7334: 	$$info = $response->content;
1.472     albertel 7335:     }
1.482     albertel 7336:     return 'ok';
1.36      albertel 7337: }
                   7338: 
1.481     raeburn  7339: sub readfile {
                   7340:     my $file = shift;
                   7341:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   7342:     my $fh;
                   7343:     open($fh,"<$file");
                   7344:     my $a='';
1.800     albertel 7345:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  7346:     return $a;
                   7347: }
                   7348: 
1.36      albertel 7349: sub filelocation {
1.590     banghart 7350:     my ($dir,$file) = @_;
                   7351:     my $location;
                   7352:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 7353: 
                   7354:     if ($file =~ m-^/adm/-) {
                   7355: 	$file=~s-^/adm/wrapper/-/-;
                   7356: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   7357:     }
1.590     banghart 7358:     if ($file=~m:^/~:) { # is a contruction space reference
                   7359:         $location = $file;
                   7360:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 7361:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 7362: 	# is a correct contruction space reference
                   7363:         $location = $file;
1.609     banghart 7364:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 7365:         my ($udom,$uname,$filename)=
1.811     albertel 7366:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 7367:         my $home=&homeserver($uname,$udom);
                   7368:         my $is_me=0;
                   7369:         my @ids=&current_machine_ids();
                   7370:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   7371:         if ($is_me) {
1.740     www      7372:   	    $location=&propath($udom,$uname).
1.590     banghart 7373:   	      '/userfiles/'.$filename;
                   7374:         } else {
                   7375:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   7376:   	      $udom.'/'.$uname.'/'.$filename;
                   7377:         }
                   7378:     } else {
                   7379:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   7380:         $file=~s:^/res/:/:;
                   7381:         if ( !( $file =~ m:^/:) ) {
                   7382:             $location = $dir. '/'.$file;
                   7383:         } else {
                   7384:             $location = '/home/httpd/html/res'.$file;
                   7385:         }
1.59      albertel 7386:     }
1.590     banghart 7387:     $location=~s://+:/:g; # remove duplicate /
                   7388:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
                   7389:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   7390:     return $location;
1.46      www      7391: }
1.36      albertel 7392: 
1.46      www      7393: sub hreflocation {
                   7394:     my ($dir,$file)=@_;
1.460     albertel 7395:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
1.666     albertel 7396: 	$file=filelocation($dir,$file);
1.700     albertel 7397:     } elsif ($file=~m-^/adm/-) {
                   7398: 	$file=~s-^/adm/wrapper/-/-;
                   7399: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 7400:     }
                   7401:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   7402: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 7403:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   7404: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 7405:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 7406: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 7407: 	    -/uploaded/$1/$2/-x;
1.46      www      7408:     }
1.462     albertel 7409:     return $file;
1.465     albertel 7410: }
                   7411: 
                   7412: sub current_machine_domains {
1.838     albertel 7413:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7414:     my @domains;
1.838     albertel 7415:     my %hostname = &all_hostnames();
1.465     albertel 7416:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7417: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7418: 	if ($hostname eq $name) {
1.844     albertel 7419: 	    push(@domains,&host_domain($id));
1.465     albertel 7420: 	}
                   7421:     }
                   7422:     return @domains;
                   7423: }
                   7424: 
                   7425: sub current_machine_ids {
1.838     albertel 7426:     my $hostname=&hostname($perlvar{'lonHostID'});
1.465     albertel 7427:     my @ids;
1.838     albertel 7428:     my %hostname = &all_hostnames();
1.465     albertel 7429:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  7430: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 7431: 	if ($hostname eq $name) {
                   7432: 	    push(@ids,$id);
                   7433: 	}
                   7434:     }
                   7435:     return @ids;
1.31      www      7436: }
                   7437: 
1.824     raeburn  7438: sub additional_machine_domains {
                   7439:     my @domains;
                   7440:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   7441:     while( my $line = <$fh>) {
                   7442:         $line =~ s/\s//g;
                   7443:         push(@domains,$line);
                   7444:     }
                   7445:     return @domains;
                   7446: }
                   7447: 
                   7448: sub default_login_domain {
                   7449:     my $domain = $perlvar{'lonDefDomain'};
                   7450:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   7451:     foreach my $posdom (&current_machine_domains(),
                   7452:                         &additional_machine_domains()) {
                   7453:         if (lc($posdom) eq lc($testdomain)) {
                   7454:             $domain=$posdom;
                   7455:             last;
                   7456:         }
                   7457:     }
                   7458:     return $domain;
                   7459: }
                   7460: 
1.31      www      7461: # ------------------------------------------------------------- Declutters URLs
                   7462: 
                   7463: sub declutter {
                   7464:     my $thisfn=shift;
1.569     albertel 7465:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 7466:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      7467:     $thisfn=~s/^\///;
1.697     albertel 7468:     $thisfn=~s|^adm/wrapper/||;
                   7469:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      7470:     $thisfn=~s/^res\///;
1.235     www      7471:     $thisfn=~s/\?.+$//;
1.268     www      7472:     return $thisfn;
                   7473: }
                   7474: 
                   7475: # ------------------------------------------------------------- Clutter up URLs
                   7476: 
                   7477: sub clutter {
                   7478:     my $thisfn='/'.&declutter(shift);
1.609     banghart 7479:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
1.270     www      7480:        $thisfn='/res'.$thisfn; 
                   7481:     }
1.694     albertel 7482:     if ($thisfn !~m|/adm|) {
1.695     albertel 7483: 	if ($thisfn =~ m|/ext/|) {
1.694     albertel 7484: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 7485: 	} else {
                   7486: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   7487: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 7488: 	    if ($embstyle eq 'ssi'
                   7489: 		|| ($embstyle eq 'hdn')
                   7490: 		|| ($embstyle eq 'rat')
                   7491: 		|| ($embstyle eq 'prv')
                   7492: 		|| ($embstyle eq 'ign')) {
                   7493: 		#do nothing with these
                   7494: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 7495: 		|| ($embstyle eq 'emb')
                   7496: 		|| ($embstyle eq 'wrp')) {
                   7497: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 7498: 	    } elsif ($embstyle eq 'unk'
                   7499: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 7500: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 7501: 	    } else {
1.718     www      7502: #		&logthis("Got a blank emb style");
1.695     albertel 7503: 	    }
1.694     albertel 7504: 	}
                   7505:     }
1.31      www      7506:     return $thisfn;
1.12      www      7507: }
                   7508: 
1.787     albertel 7509: sub clutter_with_no_wrapper {
                   7510:     my $uri = &clutter(shift);
                   7511:     if ($uri =~ m-^/adm/-) {
                   7512: 	$uri =~ s-^/adm/wrapper/-/-;
                   7513: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   7514:     }
                   7515:     return $uri;
                   7516: }
                   7517: 
1.557     albertel 7518: sub freeze_escape {
                   7519:     my ($value)=@_;
                   7520:     if (ref($value)) {
                   7521: 	$value=&nfreeze($value);
                   7522: 	return '__FROZEN__'.&escape($value);
                   7523:     }
                   7524:     return &escape($value);
                   7525: }
                   7526: 
1.11      www      7527: 
1.557     albertel 7528: sub thaw_unescape {
                   7529:     my ($value)=@_;
                   7530:     if ($value =~ /^__FROZEN__/) {
                   7531: 	substr($value,0,10,undef);
                   7532: 	$value=&unescape($value);
                   7533: 	return &thaw($value);
                   7534:     }
                   7535:     return &unescape($value);
                   7536: }
                   7537: 
1.436     albertel 7538: sub correct_line_ends {
                   7539:     my ($result)=@_;
                   7540:     $$result =~s/\r\n/\n/mg;
                   7541:     $$result =~s/\r/\n/mg;
1.415     albertel 7542: }
1.1       albertel 7543: # ================================================================ Main Program
                   7544: 
1.184     www      7545: sub goodbye {
1.204     albertel 7546:    &logthis("Starting Shut down");
1.443     albertel 7547: #not converted to using infrastruture and probably shouldn't be
1.599     albertel 7548:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
1.443     albertel 7549: #converted
1.599     albertel 7550: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
                   7551:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
                   7552: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
                   7553: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
1.425     albertel 7554: #1.1 only
1.599     albertel 7555: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
                   7556: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
                   7557: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
                   7558: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
                   7559:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
                   7560:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   7561:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      7562:    &flushcourselogs();
                   7563:    &logthis("Shutting down");
                   7564: }
                   7565: 
1.179     www      7566: BEGIN {
1.228     harris41 7567: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
1.195     www      7568:     unless ($readit) {
1.217     harris41 7569: {
1.781     raeburn  7570:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   7571:     %perlvar = (%perlvar,%{$configvars});
1.227     harris41 7572: }
1.1       albertel 7573: 
1.327     albertel 7574: # ------------------------------------------------------------ Read domain file
                   7575: {
1.846     albertel 7576:     my %domain;
                   7577: 
1.448     albertel 7578:     my $fh;
                   7579:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
1.800     albertel 7580: 	while (my $line = <$fh>) {
1.846     albertel 7581: 	    next if ($line =~ /^(\#|\s*$ )/);
1.403     www      7582: 
1.846     albertel 7583: 	    chomp($line);
                   7584: 	    my ($name,@elements) =  split(/:/,$line,9);
                   7585: 	    my %this_domain;
                   7586: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   7587: 			       'lang_def', 'city', 'longi', 'lati',
                   7588: 			       'primary') {
                   7589: 		$this_domain{$field} = shift(@elements);
                   7590: 	    }
                   7591: 	    $domain{$name} = \%this_domain;
1.327     albertel 7592: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
1.448     albertel 7593: 	}
1.327     albertel 7594:     }
1.448     albertel 7595:     close ($fh);
1.846     albertel 7596: 
                   7597:     sub domain {
                   7598: 	my ($name,$what) = @_;
                   7599: 	return if ( !exists($domain{$name}) );
                   7600: 
                   7601: 	if (!$what) {
                   7602: 	    return $domain{$name}{'description'};
                   7603: 	}
                   7604: 	return $domain{$name}{$what};
                   7605:     }
1.327     albertel 7606: }
                   7607: 
                   7608: 
1.1       albertel 7609: # ------------------------------------------------------------- Read hosts file
                   7610: {
1.838     albertel 7611:     my %hostname;
1.844     albertel 7612:     my %hostdom;
1.845     albertel 7613:     my %libserv;
1.448     albertel 7614:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
1.1       albertel 7615: 
                   7616:     while (my $configline=<$config>) {
1.303     matthew  7617:        next if ($configline =~ /^(\#|\s*$)/);
1.154     www      7618:        chomp($configline);
1.595     albertel 7619:        my ($id,$domain,$role,$name)=split(/:/,$configline);
1.597     albertel 7620:        $name=~s/\s//g;
1.595     albertel 7621:        if ($id && $domain && $role && $name) {
1.252     albertel 7622: 	 $hostname{$id}=$name;
                   7623: 	 $hostdom{$id}=$domain;
                   7624: 	 if ($role eq 'library') { $libserv{$id}=$name; }
1.245     www      7625:        }
1.1       albertel 7626:     }
1.448     albertel 7627:     close($config);
1.619     albertel 7628:     # FIXME: dev server don't want this, production servers _do_ want this
1.654     albertel 7629:     #&get_iphost();
1.838     albertel 7630: 
                   7631:     sub hostname {
                   7632: 	my ($lonid) = @_;
                   7633: 	return $hostname{$lonid};
                   7634:     }
1.845     albertel 7635: 
1.838     albertel 7636:     sub all_hostnames {
                   7637: 	return %hostname;
                   7638:     }
1.845     albertel 7639: 
                   7640:     sub is_library {
                   7641: 	return exists($libserv{$_[0]});
                   7642:     }
                   7643: 
                   7644:     sub all_library {
                   7645: 	return %libserv;
                   7646:     }
                   7647: 
1.841     albertel 7648:     sub get_servers {
                   7649: 	my ($domain,$type) = @_;
                   7650: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   7651: 	                                          : %hostname;
                   7652: 	my %result;
1.842     albertel 7653: 	if (ref($domain) eq 'ARRAY') {
                   7654: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 7655: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 7656: 		    $result{$host} = $hostname;
                   7657: 		}
                   7658: 	    }
                   7659: 	} else {
                   7660: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   7661: 		if ($hostdom{$host} eq $domain) {
                   7662: 		    $result{$host} = $hostname;
                   7663: 		}
1.841     albertel 7664: 	    }
                   7665: 	}
                   7666: 	return %result;
                   7667:     }
1.845     albertel 7668: 
1.844     albertel 7669:     sub host_domain {
                   7670: 	my ($lonid) = @_;
                   7671: 	return $hostdom{$lonid};
                   7672:     }
                   7673: 
1.841     albertel 7674:     sub all_domains {
                   7675: 	my %seen;
                   7676: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   7677: 	return @uniq;
                   7678:     }
1.1       albertel 7679: }
                   7680: 
1.847     albertel 7681: { 
                   7682:     my %iphost;
                   7683:     sub get_hosts_from_ip {
                   7684: 	my ($ip) = @_;
                   7685: 	my %iphosts = &get_iphost();
                   7686: 	if (ref($iphosts{$ip})) {
                   7687: 	    return @{$iphosts{$ip}};
                   7688: 	}
                   7689: 	return;
1.839     albertel 7690:     }
1.847     albertel 7691:     
                   7692:     sub get_iphost {
                   7693: 	if (%iphost) { return %iphost; }
                   7694: 	my %name_to_ip;
                   7695: 	my %hostname = &all_hostnames();
                   7696: 	foreach my $id (keys(%hostname)) {
                   7697: 	    my $name=$hostname{$id};
                   7698: 	    my $ip;
                   7699: 	    if (!exists($name_to_ip{$name})) {
                   7700: 		$ip = gethostbyname($name);
                   7701: 		if (!$ip || length($ip) ne 4) {
                   7702: 		    &logthis("Skipping host $id name $name no IP found");
                   7703: 		    next;
                   7704: 		}
                   7705: 		$ip=inet_ntoa($ip);
                   7706: 		$name_to_ip{$name} = $ip;
                   7707: 	    } else {
                   7708: 		$ip = $name_to_ip{$name};
1.653     albertel 7709: 	    }
1.847     albertel 7710: 	    push(@{$iphost{$ip}},$id);
1.598     albertel 7711: 	}
1.847     albertel 7712: 	return %iphost;
1.598     albertel 7713:     }
                   7714: }
                   7715: 
1.1       albertel 7716: # ------------------------------------------------------ Read spare server file
                   7717: {
1.448     albertel 7718:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 7719: 
                   7720:     while (my $configline=<$config>) {
                   7721:        chomp($configline);
1.284     matthew  7722:        if ($configline) {
1.784     albertel 7723: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 7724: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 7725: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 7726:        }
                   7727:     }
1.448     albertel 7728:     close($config);
1.1       albertel 7729: }
1.11      www      7730: # ------------------------------------------------------------ Read permissions
                   7731: {
1.448     albertel 7732:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      7733: 
                   7734:     while (my $configline=<$config>) {
1.448     albertel 7735: 	chomp($configline);
                   7736: 	if ($configline) {
                   7737: 	    my ($role,$perm)=split(/ /,$configline);
                   7738: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   7739: 	}
1.11      www      7740:     }
1.448     albertel 7741:     close($config);
1.11      www      7742: }
                   7743: 
                   7744: # -------------------------------------------- Read plain texts for permissions
                   7745: {
1.448     albertel 7746:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      7747: 
                   7748:     while (my $configline=<$config>) {
1.448     albertel 7749: 	chomp($configline);
                   7750: 	if ($configline) {
1.742     raeburn  7751: 	    my ($short,@plain)=split(/:/,$configline);
                   7752:             %{$prp{$short}} = ();
                   7753: 	    if (@plain > 0) {
                   7754:                 $prp{$short}{'std'} = $plain[0];
                   7755:                 for (my $i=1; $i<@plain; $i++) {
                   7756:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   7757:                 }
                   7758:             }
1.448     albertel 7759: 	}
1.135     www      7760:     }
1.448     albertel 7761:     close($config);
1.135     www      7762: }
                   7763: 
                   7764: # ---------------------------------------------------------- Read package table
                   7765: {
1.448     albertel 7766:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      7767: 
                   7768:     while (my $configline=<$config>) {
1.483     albertel 7769: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 7770: 	chomp($configline);
                   7771: 	my ($short,$plain)=split(/:/,$configline);
                   7772: 	my ($pack,$name)=split(/\&/,$short);
                   7773: 	if ($plain ne '') {
                   7774: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   7775: 	    $packagetab{$short}=$plain; 
                   7776: 	}
1.11      www      7777:     }
1.448     albertel 7778:     close($config);
1.329     matthew  7779: }
                   7780: 
                   7781: # ------------- set up temporary directory
                   7782: {
                   7783:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
                   7784: 
1.11      www      7785: }
                   7786: 
1.794     albertel 7787: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   7788: 				'compress_threshold'=> 20_000,
                   7789:  			        });
1.185     www      7790: 
1.281     www      7791: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      7792: $dumpcount=0;
1.22      www      7793: 
1.163     harris41 7794: &logtouch();
1.672     albertel 7795: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      7796: $readit=1;
1.564     albertel 7797:     {
                   7798: 	use integer;
                   7799: 	my $test=(2**32)+1;
1.568     albertel 7800: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 7801: 	&logthis(" Detected 64bit platform ($_64bit)");
                   7802:     }
1.195     www      7803: }
1.1       albertel 7804: }
1.179     www      7805: 
1.1       albertel 7806: 1;
1.191     harris41 7807: __END__
                   7808: 
1.243     albertel 7809: =pod
                   7810: 
1.191     harris41 7811: =head1 NAME
                   7812: 
1.243     albertel 7813: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 7814: 
                   7815: =head1 SYNOPSIS
                   7816: 
1.243     albertel 7817: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 7818: 
                   7819:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   7820: 
1.243     albertel 7821: Common parameters:
                   7822: 
                   7823: =over 4
                   7824: 
                   7825: =item *
                   7826: 
                   7827: $uname : an internal username (if $cname expecting a course Id specifically)
                   7828: 
                   7829: =item *
                   7830: 
                   7831: $udom : a domain (if $cdom expecting a course's domain specifically)
                   7832: 
                   7833: =item *
                   7834: 
                   7835: $symb : a resource instance identifier
                   7836: 
                   7837: =item *
                   7838: 
                   7839: $namespace : the name of a .db file that contains the data needed or
                   7840: being set.
                   7841: 
                   7842: =back
                   7843: 
1.394     bowersj2 7844: =head1 OVERVIEW
1.191     harris41 7845: 
1.394     bowersj2 7846: lonnet provides subroutines which interact with the
                   7847: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   7848: about classes, users, and resources.
1.243     albertel 7849: 
                   7850: For many of these objects you can also use this to store data about
                   7851: them or modify them in various ways.
1.191     harris41 7852: 
1.394     bowersj2 7853: =head2 Symbs
1.191     harris41 7854: 
1.394     bowersj2 7855: To identify a specific instance of a resource, LON-CAPA uses symbols
                   7856: or "symbs"X<symb>. These identifiers are built from the URL of the
                   7857: map, the resource number of the resource in the map, and the URL of
                   7858: the resource itself. The latter is somewhat redundant, but might help
                   7859: if maps change.
                   7860: 
                   7861: An example is
                   7862: 
                   7863:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   7864: 
                   7865: The respective map entry is
                   7866: 
                   7867:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   7868:   title="Problem 2">
                   7869:  </resource>
                   7870: 
                   7871: Symbs are used by the random number generator, as well as to store and
                   7872: restore data specific to a certain instance of for example a problem.
                   7873: 
                   7874: =head2 Storing And Retrieving Data
                   7875: 
                   7876: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   7877: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   7878: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   7879: is is the non-critical message twin of cstore. These functions are for
                   7880: handlers to store a perl hash to a user's permanent data space in an
                   7881: easy manner, and to retrieve it again on another call. It is expected
                   7882: that a handler would use this once at the beginning to retrieve data,
                   7883: and then again once at the end to send only the new data back.
                   7884: 
                   7885: The data is stored in the user's data directory on the user's
                   7886: homeserver under the ID of the course.
                   7887: 
                   7888: The hash that is returned by restore will have all of the previous
                   7889: value for all of the elements of the hash.
                   7890: 
                   7891: Example:
                   7892: 
                   7893:  #creating a hash
                   7894:  my %hash;
                   7895:  $hash{'foo'}='bar';
                   7896: 
                   7897:  #storing it
                   7898:  &Apache::lonnet::cstore(\%hash);
                   7899: 
                   7900:  #changing a value
                   7901:  $hash{'foo'}='notbar';
                   7902: 
                   7903:  #adding a new value
                   7904:  $hash{'bar'}='foo';
                   7905:  &Apache::lonnet::cstore(\%hash);
                   7906: 
                   7907:  #retrieving the hash
                   7908:  my %history=&Apache::lonnet::restore();
                   7909: 
                   7910:  #print the hash
                   7911:  foreach my $key (sort(keys(%history))) {
                   7912:    print("\%history{$key} = $history{$key}");
                   7913:  }
                   7914: 
                   7915: Will print out:
1.191     harris41 7916: 
1.394     bowersj2 7917:  %history{1:foo} = bar
                   7918:  %history{1:keys} = foo:timestamp
                   7919:  %history{1:timestamp} = 990455579
                   7920:  %history{2:bar} = foo
                   7921:  %history{2:foo} = notbar
                   7922:  %history{2:keys} = foo:bar:timestamp
                   7923:  %history{2:timestamp} = 990455580
                   7924:  %history{bar} = foo
                   7925:  %history{foo} = notbar
                   7926:  %history{timestamp} = 990455580
                   7927:  %history{version} = 2
                   7928: 
                   7929: Note that the special hash entries C<keys>, C<version> and
                   7930: C<timestamp> were added to the hash. C<version> will be equal to the
                   7931: total number of versions of the data that have been stored. The
                   7932: C<timestamp> attribute will be the UNIX time the hash was
                   7933: stored. C<keys> is available in every historical section to list which
                   7934: keys were added or changed at a specific historical revision of a
                   7935: hash.
                   7936: 
                   7937: B<Warning>: do not store the hash that restore returns directly. This
                   7938: will cause a mess since it will restore the historical keys as if the
                   7939: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 7940: 
1.394     bowersj2 7941: Calling convention:
1.191     harris41 7942: 
1.394     bowersj2 7943:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   7944:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 7945: 
1.394     bowersj2 7946: For more detailed information, see lonnet specific documentation.
1.191     harris41 7947: 
1.394     bowersj2 7948: =head1 RETURN MESSAGES
1.191     harris41 7949: 
1.394     bowersj2 7950: =over 4
1.191     harris41 7951: 
1.394     bowersj2 7952: =item * B<con_lost>: unable to contact remote host
1.191     harris41 7953: 
1.394     bowersj2 7954: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   7955: when the connection is brought back up
1.191     harris41 7956: 
1.394     bowersj2 7957: =item * B<con_failed>: unable to contact remote host and unable to save message
                   7958: for later delivery
1.191     harris41 7959: 
1.394     bowersj2 7960: =item * B<error:>: an error a occured, a description of the error follows the :
1.191     harris41 7961: 
1.394     bowersj2 7962: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 7963: that was requested
1.191     harris41 7964: 
1.243     albertel 7965: =back
1.191     harris41 7966: 
1.243     albertel 7967: =head1 PUBLIC SUBROUTINES
1.191     harris41 7968: 
1.243     albertel 7969: =head2 Session Environment Functions
1.191     harris41 7970: 
1.243     albertel 7971: =over 4
1.191     harris41 7972: 
1.394     bowersj2 7973: =item * 
                   7974: X<appenv()>
                   7975: B<appenv(%hash)>: the value of %hash is written to
                   7976: the user envirnoment file, and will be restored for each access this
1.620     albertel 7977: user makes during this session, also modifies the %env for the current
1.394     bowersj2 7978: process
1.191     harris41 7979: 
                   7980: =item *
1.394     bowersj2 7981: X<delenv()>
                   7982: B<delenv($regexp)>: removes all items from the session
                   7983: environment file that matches the regular expression in $regexp. The
1.620     albertel 7984: values are also delted from the current processes %env.
1.191     harris41 7985: 
1.795     albertel 7986: =item * get_env_multiple($name) 
                   7987: 
                   7988: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   7989: values may be defined and end up as an array ref.
                   7990: 
                   7991: returns an array of values
                   7992: 
1.243     albertel 7993: =back
                   7994: 
                   7995: =head2 User Information
1.191     harris41 7996: 
1.243     albertel 7997: =over 4
1.191     harris41 7998: 
                   7999: =item *
1.394     bowersj2 8000: X<queryauthenticate()>
                   8001: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 8002: authentication scheme
                   8003: 
                   8004: =item *
1.394     bowersj2 8005: X<authenticate()>
                   8006: B<authenticate($uname,$upass,$udom)>: try to
                   8007: authenticate user from domain's lib servers (first use the current
                   8008: one). C<$upass> should be the users password.
1.191     harris41 8009: 
                   8010: =item *
1.394     bowersj2 8011: X<homeserver()>
                   8012: B<homeserver($uname,$udom)>: find the server which has
                   8013: the user's directory and files (there must be only one), this caches
                   8014: the answer, and also caches if there is a borken connection.
1.191     harris41 8015: 
                   8016: =item *
1.394     bowersj2 8017: X<idget()>
                   8018: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   8019: (IDs are a unique resource in a domain, there must be only 1 ID per
                   8020: username, and only 1 username per ID in a specific domain) (returns
                   8021: hash: id=>name,id=>name)
1.191     harris41 8022: 
                   8023: =item *
1.394     bowersj2 8024: X<idrget()>
                   8025: B<idrget($udom,@unames)>: find the IDs behind a list of
                   8026: usernames (returns hash: name=>id,name=>id)
1.191     harris41 8027: 
                   8028: =item *
1.394     bowersj2 8029: X<idput()>
                   8030: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 8031: 
                   8032: =item *
1.394     bowersj2 8033: X<rolesinit()>
                   8034: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 8035: 
                   8036: =item *
1.551     albertel 8037: X<getsection()>
                   8038: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 8039: course $cname, return section name/number or '' for "not in course"
                   8040: and '-1' for "no section"
                   8041: 
                   8042: =item *
1.394     bowersj2 8043: X<userenvironment()>
                   8044: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 8045: passed in @what from the requested user's environment, returns a hash
                   8046: 
                   8047: =back
                   8048: 
                   8049: =head2 User Roles
                   8050: 
                   8051: =over 4
                   8052: 
                   8053: =item *
                   8054: 
1.810     raeburn  8055: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 8056:  F: full access
                   8057:  U,I,K: authentication modes (cxx only)
                   8058:  '': forbidden
                   8059:  1: user needs to choose course
                   8060:  2: browse allowed
1.766     albertel 8061:  A: passphrase authentication needed
1.243     albertel 8062: 
                   8063: =item *
                   8064: 
                   8065: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   8066: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   8067: and course level
                   8068: 
                   8069: =item *
                   8070: 
                   8071: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
                   8072: explanation of a user role term
                   8073: 
1.832     raeburn  8074: =item *
                   8075: 
1.834     albertel 8076: get_my_roles($uname,$udom,$types,$roles,$roledoms) : All arguments are
                   8077: optional.  Returns a hash of a user's roles, with keys set to
                   8078: colon-sparated $uname,$udom,and $role, and value set to
                   8079: colon-separated start and end times for the role. If no username and
                   8080: domain are specified, will default to current user/domain. Types,
                   8081: roles, and roledoms are references to arrays, of role statuses
                   8082: (active, future or previous), roles (e.g., cc,in, st etc.) and domains
                   8083: of the roles which can be used to restrict the list if roles
                   8084: reported. If no array ref is provided for types, will default to
                   8085: return only active roles.
                   8086: 
1.243     albertel 8087: =back
                   8088: 
                   8089: =head2 User Modification
                   8090: 
                   8091: =over 4
                   8092: 
                   8093: =item *
                   8094: 
                   8095: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
                   8096: user for the level given by URL.  Optional start and end dates (leave empty
                   8097: string or zero for "no date")
1.191     harris41 8098: 
                   8099: =item *
                   8100: 
1.243     albertel 8101: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   8102: change a users, password, possible return values are: ok,
                   8103: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   8104: refused
1.191     harris41 8105: 
                   8106: =item *
                   8107: 
1.243     albertel 8108: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 8109: 
                   8110: =item *
                   8111: 
1.243     albertel 8112: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
                   8113: modify user
1.191     harris41 8114: 
                   8115: =item *
                   8116: 
1.286     matthew  8117: modifystudent
                   8118: 
                   8119: modify a students enrollment and identification information.
                   8120: The course id is resolved based on the current users environment.  
                   8121: This means the envoking user must be a course coordinator or otherwise
                   8122: associated with a course.
                   8123: 
1.297     matthew  8124: This call is essentially a wrapper for lonnet::modifyuser and
                   8125: lonnet::modify_student_enrollment
1.286     matthew  8126: 
                   8127: Inputs: 
                   8128: 
                   8129: =over 4
                   8130: 
                   8131: =item B<$udom> Students loncapa domain
                   8132: 
                   8133: =item B<$uname> Students loncapa login name
                   8134: 
                   8135: =item B<$uid> Students id/student number
                   8136: 
                   8137: =item B<$umode> Students authentication mode
                   8138: 
                   8139: =item B<$upass> Students password
                   8140: 
                   8141: =item B<$first> Students first name
                   8142: 
                   8143: =item B<$middle> Students middle name
                   8144: 
                   8145: =item B<$last> Students last name
                   8146: 
                   8147: =item B<$gene> Students generation
                   8148: 
                   8149: =item B<$usec> Students section in course
                   8150: 
                   8151: =item B<$end> Unix time of the roles expiration
                   8152: 
                   8153: =item B<$start> Unix time of the roles start date
                   8154: 
                   8155: =item B<$forceid> If defined, allow $uid to be changed
                   8156: 
                   8157: =item B<$desiredhome> server to use as home server for student
                   8158: 
                   8159: =back
1.297     matthew  8160: 
                   8161: =item *
                   8162: 
                   8163: modify_student_enrollment
                   8164: 
                   8165: Change a students enrollment status in a class.  The environment variable
                   8166: 'role.request.course' must be defined for this function to proceed.
                   8167: 
                   8168: Inputs:
                   8169: 
                   8170: =over 4
                   8171: 
                   8172: =item $udom, students domain
                   8173: 
                   8174: =item $uname, students name
                   8175: 
                   8176: =item $uid, students user id
                   8177: 
                   8178: =item $first, students first name
                   8179: 
                   8180: =item $middle
                   8181: 
                   8182: =item $last
                   8183: 
                   8184: =item $gene
                   8185: 
                   8186: =item $usec
                   8187: 
                   8188: =item $end
                   8189: 
                   8190: =item $start
                   8191: 
                   8192: =back
                   8193: 
1.191     harris41 8194: 
                   8195: =item *
                   8196: 
1.243     albertel 8197: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   8198: custom role; give a custom role to a user for the level given by URL.  Specify
                   8199: name and domain of role author, and role name
1.191     harris41 8200: 
                   8201: =item *
                   8202: 
1.243     albertel 8203: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 8204: 
                   8205: =item *
                   8206: 
1.243     albertel 8207: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   8208: 
                   8209: =back
                   8210: 
                   8211: =head2 Course Infomation
                   8212: 
                   8213: =over 4
1.191     harris41 8214: 
                   8215: =item *
                   8216: 
1.631     albertel 8217: coursedescription($courseid) : returns a hash of information about the
                   8218: specified course id, including all environment settings for the
                   8219: course, the description of the course will be in the hash under the
                   8220: key 'description'
1.191     harris41 8221: 
                   8222: =item *
                   8223: 
1.624     albertel 8224: resdata($name,$domain,$type,@which) : request for current parameter
                   8225: setting for a specific $type, where $type is either 'course' or 'user',
                   8226: @what should be a list of parameters to ask about. This routine caches
                   8227: answers for 5 minutes.
1.243     albertel 8228: 
                   8229: =back
                   8230: 
                   8231: =head2 Course Modification
                   8232: 
                   8233: =over 4
1.191     harris41 8234: 
                   8235: =item *
                   8236: 
1.243     albertel 8237: writecoursepref($courseid,%prefs) : write preferences (environment
                   8238: database) for a course
1.191     harris41 8239: 
                   8240: =item *
                   8241: 
1.243     albertel 8242: createcourse($udom,$description,$url) : make/modify course
                   8243: 
                   8244: =back
                   8245: 
                   8246: =head2 Resource Subroutines
                   8247: 
                   8248: =over 4
1.191     harris41 8249: 
                   8250: =item *
                   8251: 
1.243     albertel 8252: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 8253: 
                   8254: =item *
                   8255: 
1.243     albertel 8256: repcopy($filename) : subscribes to the requested file, and attempts to
                   8257: replicate from the owning library server, Might return
1.607     raeburn  8258: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   8259: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 8260: resource. Expects the local filesystem pathname
                   8261: (/home/httpd/html/res/....)
                   8262: 
                   8263: =back
                   8264: 
                   8265: =head2 Resource Information
                   8266: 
                   8267: =over 4
1.191     harris41 8268: 
                   8269: =item *
                   8270: 
1.243     albertel 8271: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   8272: a vairety of different possible values, $varname should be a request
                   8273: string, and the other parameters can be used to specify who and what
                   8274: one is asking about.
                   8275: 
                   8276: Possible values for $varname are environment.lastname (or other item
                   8277: from the envirnment hash), user.name (or someother aspect about the
                   8278: user), resource.0.maxtries (or some other part and parameter of a
                   8279: resource)
1.204     albertel 8280: 
                   8281: =item *
                   8282: 
1.243     albertel 8283: directcondval($number) : get current value of a condition; reads from a state
                   8284: string
1.204     albertel 8285: 
                   8286: =item *
                   8287: 
1.243     albertel 8288: condval($condidx) : value of condition index based on state
1.204     albertel 8289: 
                   8290: =item *
                   8291: 
1.243     albertel 8292: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   8293: resource's metadata, $what should be either a specific key, or either
                   8294: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   8295: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   8296: 
                   8297: this function automatically caches all requests
1.191     harris41 8298: 
                   8299: =item *
                   8300: 
1.243     albertel 8301: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   8302: network of library servers; returns file handle of where SQL and regex results
                   8303: will be stored for query
1.191     harris41 8304: 
                   8305: =item *
                   8306: 
1.243     albertel 8307: symbread($filename) : return symbolic list entry (filename argument optional);
                   8308: returns the data handle
1.191     harris41 8309: 
                   8310: =item *
                   8311: 
1.243     albertel 8312: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 8313: a possible symb for the URL in $thisfn, and if is an encryypted
                   8314: resource that the user accessed using /enc/ returns a 1 on success, 0
                   8315: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 8316: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 8317: 
1.191     harris41 8318: 
                   8319: =item *
                   8320: 
1.243     albertel 8321: symbclean($symb) : removes versions numbers from a symb, returns the
                   8322: cleaned symb
1.191     harris41 8323: 
                   8324: =item *
                   8325: 
1.243     albertel 8326: is_on_map($uri) : checks if the $uri is somewhere on the current
                   8327: course map, user must be in a course for it to work.
1.191     harris41 8328: 
                   8329: =item *
                   8330: 
1.243     albertel 8331: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 8332: 
                   8333: =item *
                   8334: 
1.243     albertel 8335: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   8336: a random seed, all arguments are optional, if they aren't sent it uses the
                   8337: environment to derive them. Note: if symb isn't sent and it can't get one
                   8338: from &symbread it will use the current time as its return value
1.191     harris41 8339: 
                   8340: =item *
                   8341: 
1.243     albertel 8342: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   8343: unfakeable, receipt
1.191     harris41 8344: 
                   8345: =item *
                   8346: 
1.620     albertel 8347: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 8348: 
                   8349: =item *
                   8350: 
1.243     albertel 8351: countacc($url) : count the number of accesses to a given URL
1.191     harris41 8352: 
                   8353: =item *
                   8354: 
1.243     albertel 8355: 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
1.191     harris41 8356: 
                   8357: =item *
                   8358: 
1.243     albertel 8359: 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)
1.191     harris41 8360: 
                   8361: =item *
                   8362: 
1.243     albertel 8363: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 8364: 
                   8365: =item *
                   8366: 
1.243     albertel 8367: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   8368: forcing spreadsheet to reevaluate the resource scores next time.
                   8369: 
                   8370: =back
                   8371: 
                   8372: =head2 Storing/Retreiving Data
                   8373: 
                   8374: =over 4
1.191     harris41 8375: 
                   8376: =item *
                   8377: 
1.243     albertel 8378: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   8379: for this url; hashref needs to be given and should be a \%hashname; the
                   8380: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 8381: be derived from the env
1.191     harris41 8382: 
                   8383: =item *
                   8384: 
1.243     albertel 8385: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   8386: uses critical subroutine
1.191     harris41 8387: 
                   8388: =item *
                   8389: 
1.243     albertel 8390: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   8391: all args are optional
1.191     harris41 8392: 
                   8393: =item *
                   8394: 
1.717     albertel 8395: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   8396: dumps the complete (or key matching regexp) namespace into a hash
                   8397: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   8398: normally &store()ed into
                   8399: 
                   8400: $range should be either an integer '100' (give me the first 100
                   8401:                                            matching records)
                   8402:               or be  two integers sperated by a - with no spaces
                   8403:                  '30-50' (give me the 30th through the 50th matching
                   8404:                           records)
                   8405: 
                   8406: 
                   8407: =item *
                   8408: 
                   8409: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   8410: replaces a &store() version of data with a replacement set of data
                   8411: for a particular resource in a namespace passed in the $storehash hash 
                   8412: reference
                   8413: 
                   8414: =item *
                   8415: 
1.243     albertel 8416: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   8417: works very similar to store/cstore, but all data is stored in a
                   8418: temporary location and can be reset using tmpreset, $storehash should
                   8419: be a hash reference, returns nothing on success
1.191     harris41 8420: 
                   8421: =item *
                   8422: 
1.243     albertel 8423: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   8424: similar to restore, but all data is stored in a temporary location and
                   8425: can be reset using tmpreset. Returns a hash of values on success,
                   8426: error string otherwise.
1.191     harris41 8427: 
                   8428: =item *
                   8429: 
1.243     albertel 8430: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   8431: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 8432: 
                   8433: =item *
                   8434: 
1.243     albertel 8435: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8436: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 8437: 
                   8438: =item *
                   8439: 
1.243     albertel 8440: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   8441: namesp ($udom and $uname are optional)
1.191     harris41 8442: 
                   8443: =item *
                   8444: 
1.702     albertel 8445: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 8446: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 8447: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  8448: 
1.702     albertel 8449: $range should be either an integer '100' (give me the first 100
                   8450:                                            matching records)
                   8451:               or be  two integers sperated by a - with no spaces
                   8452:                  '30-50' (give me the 30th through the 50th matching
                   8453:                           records)
1.449     matthew  8454: =item *
                   8455: 
                   8456: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   8457: $store can be a scalar, an array reference, or if the amount to be 
                   8458: incremented is > 1, a hash reference.
                   8459: 
                   8460: ($udom and $uname are optional)
1.191     harris41 8461: 
                   8462: =item *
                   8463: 
1.243     albertel 8464: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   8465: ($udom and $uname are optional)
1.191     harris41 8466: 
                   8467: =item *
                   8468: 
1.243     albertel 8469: cput($namespace,$storehash,$udom,$uname) : critical put
                   8470: ($udom and $uname are optional)
1.191     harris41 8471: 
                   8472: =item *
                   8473: 
1.748     albertel 8474: newput($namespace,$storehash,$udom,$uname) :
                   8475: 
                   8476: Attempts to store the items in the $storehash, but only if they don't
                   8477: currently exist, if this succeeds you can be certain that you have 
                   8478: successfully created a new key value pair in the $namespace db.
                   8479: 
                   8480: 
                   8481: Args:
                   8482:  $namespace: name of database to store values to
                   8483:  $storehash: hashref to store to the db
                   8484:  $udom: (optional) domain of user containing the db
                   8485:  $uname: (optional) name of user caontaining the db
                   8486: 
                   8487: Returns:
                   8488:  'ok' -> succeeded in storing all keys of $storehash
                   8489:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   8490:                         least <key> already existed in the db (other
                   8491:                         requested keys may also already exist)
                   8492:  'error: <msg>' -> unable to tie the DB or other erorr occured
                   8493:  'con_lost' -> unable to contact request server
                   8494:  'refused' -> action was not allowed by remote machine
                   8495: 
                   8496: 
                   8497: =item *
                   8498: 
1.243     albertel 8499: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   8500: reference filled in from namesp (encrypts the return communication)
                   8501: ($udom and $uname are optional)
1.191     harris41 8502: 
                   8503: =item *
                   8504: 
1.243     albertel 8505: log($udom,$name,$home,$message) : write to permanent log for user; use
                   8506: critical subroutine
                   8507: 
1.806     raeburn  8508: =item *
                   8509: 
                   8510: get_dom($namespace,$storearr,$udomain) : returns hash with keys from array
                   8511: reference filled in from namespace found in domain level on primary domain server ($udomain is optional)
                   8512: 
                   8513: =item *
                   8514: 
                   8515: put_dom($namespace,$storehash,$udomain) :  stores hash in namespace at domain level on primary domain server ($udomain is optional)
                   8516: 
1.243     albertel 8517: =back
                   8518: 
                   8519: =head2 Network Status Functions
                   8520: 
                   8521: =over 4
1.191     harris41 8522: 
                   8523: =item *
                   8524: 
                   8525: dirlist($uri) : return directory list based on URI
                   8526: 
                   8527: =item *
                   8528: 
1.243     albertel 8529: spareserver() : find server with least workload from spare.tab
                   8530: 
                   8531: =back
                   8532: 
                   8533: =head2 Apache Request
                   8534: 
                   8535: =over 4
1.191     harris41 8536: 
                   8537: =item *
                   8538: 
1.243     albertel 8539: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   8540: localhost, posts hash
                   8541: 
                   8542: =back
                   8543: 
                   8544: =head2 Data to String to Data
                   8545: 
                   8546: =over 4
1.191     harris41 8547: 
                   8548: =item *
                   8549: 
1.243     albertel 8550: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   8551: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 8552: 
                   8553: =item *
                   8554: 
1.243     albertel 8555: hashref2str($hashref) : convert a hashref into a string complete with
                   8556: escaping and '=' and '&' separators, supports elements that are
                   8557: arrayrefs and hashrefs
1.191     harris41 8558: 
                   8559: =item *
                   8560: 
1.243     albertel 8561: arrayref2str($arrayref) : convert an arrayref into a string complete
                   8562: with escaping and '&' separators, supports elements that are arrayrefs
                   8563: and hashrefs
1.191     harris41 8564: 
                   8565: =item *
                   8566: 
1.243     albertel 8567: str2hash($string) : convert string to hash using unescaping and
                   8568: splitting on '=' and '&', supports elements that are arrayrefs and
                   8569: hashrefs
1.191     harris41 8570: 
                   8571: =item *
                   8572: 
1.243     albertel 8573: str2array($string) : convert string to hash using unescaping and
                   8574: splitting on '&', supports elements that are arrayrefs and hashrefs
                   8575: 
                   8576: =back
                   8577: 
                   8578: =head2 Logging Routines
                   8579: 
                   8580: =over 4
                   8581: 
                   8582: These routines allow one to make log messages in the lonnet.log and
                   8583: lonnet.perm logfiles.
1.191     harris41 8584: 
                   8585: =item *
                   8586: 
1.243     albertel 8587: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 8588: 
                   8589: =item *
                   8590: 
1.243     albertel 8591: logthis() : append message to the normal lonnet.log file, it gets
                   8592: preiodically rolled over and deleted.
1.191     harris41 8593: 
                   8594: =item *
                   8595: 
1.243     albertel 8596: logperm() : append a permanent message to lonnet.perm.log, this log
                   8597: file never gets deleted by any automated portion of the system, only
                   8598: messages of critical importance should go in here.
                   8599: 
                   8600: =back
                   8601: 
                   8602: =head2 General File Helper Routines
                   8603: 
                   8604: =over 4
1.191     harris41 8605: 
                   8606: =item *
                   8607: 
1.481     raeburn  8608: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   8609: (a) files in /uploaded
                   8610:   (i) If a local copy of the file exists - 
                   8611:       compares modification date of local copy with last-modified date for 
                   8612:       definitive version stored on home server for course. If local copy is 
                   8613:       stale, requests a new version from the home server and stores it. 
                   8614:       If the original has been removed from the home server, then local copy 
                   8615:       is unlinked.
                   8616:   (ii) If local copy does not exist -
                   8617:       requests the file from the home server and stores it. 
                   8618:   
                   8619:   If $caller is 'uploadrep':  
                   8620:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   8621:     for request for files originally uploaded via DOCS. 
                   8622:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   8623:   
                   8624:   Otherwise:
                   8625:      This indicates a call from the content generation phase of the request.
                   8626:      -  returns the entire contents of the file or -1.
                   8627:      
                   8628: (b) files in /res
                   8629:    - returns the entire contents of a file or -1; 
                   8630:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 8631: 
1.712     albertel 8632: 
                   8633: =item *
                   8634: 
                   8635: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   8636:                   reference
                   8637: 
                   8638: returns either a stat() list of data about the file or an empty list
                   8639: if the file doesn't exist or couldn't find out about it (connection
                   8640: problems or user unknown)
                   8641: 
1.191     harris41 8642: =item *
                   8643: 
1.243     albertel 8644: filelocation($dir,$file) : returns file system location of a file
                   8645: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   8646: directory that relative $file lookups are to looked in ($dir of /a/dir
                   8647: and a file of ../bob will become /a/bob)
1.191     harris41 8648: 
                   8649: =item *
                   8650: 
                   8651: hreflocation($dir,$file) : returns file system location or a URL; same as
                   8652: filelocation except for hrefs
                   8653: 
                   8654: =item *
                   8655: 
                   8656: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   8657: 
1.243     albertel 8658: =back
                   8659: 
1.608     albertel 8660: =head2 Usererfile file routines (/uploaded*)
                   8661: 
                   8662: =over 4
                   8663: 
                   8664: =item *
                   8665: 
                   8666: userfileupload(): main rotine for putting a file in a user or course's
                   8667:                   filespace, arguments are,
                   8668: 
1.620     albertel 8669:  formname - required - this is the name of the element in $env where the
1.608     albertel 8670:            filename, and the contents of the file to create/modifed exist
1.620     albertel 8671:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   8672:            contents of the file is located in $env{'form.'.$formname}
1.608     albertel 8673:  coursedoc - if true, store the file in the course of the active role
                   8674:              of the current user
                   8675:  subdir - required - subdirectory to put the file in under ../userfiles/
                   8676:          if undefined, it will be placed in "unknown"
                   8677: 
                   8678:  (This routine calls clean_filename() to remove any dangerous
                   8679:  characters from the filename, and then calls finuserfileupload() to
                   8680:  complete the transaction)
                   8681: 
                   8682:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8683:  and /adm/notfound.html if unsuccessful
                   8684: 
                   8685: =item *
                   8686: 
                   8687: clean_filename(): routine for cleaing a filename up for storage in
                   8688:                  userfile space, argument is:
                   8689: 
                   8690:  filename - proposed filename
                   8691: 
                   8692: returns: the new clean filename
                   8693: 
                   8694: =item *
                   8695: 
                   8696: finishuserfileupload(): routine that creaes and sends the file to
                   8697: userspace, probably shouldn't be called directly
                   8698: 
                   8699:   docuname: username or courseid of destination for the file
                   8700:   docudom: domain of user/course of destination for the file
                   8701:   formname: same as for userfileupload()
                   8702:   fname: filename (inculding subdirectories) for the file
                   8703: 
                   8704:  returns either the url of the uploaded file (/uploaded/....) if successful
                   8705:  and /adm/notfound.html if unsuccessful
                   8706: 
                   8707: =item *
                   8708: 
                   8709: renameuserfile(): renames an existing userfile to a new name
                   8710: 
                   8711:   Args:
                   8712:    docuname: username or courseid of destination for the file
                   8713:    docudom: domain of user/course of destination for the file
                   8714:    old: current file name (including any subdirs under userfiles)
                   8715:    new: desired file name (including any subdirs under userfiles)
                   8716: 
                   8717: =item *
                   8718: 
                   8719: mkdiruserfile(): creates a directory is a userfiles dir
                   8720: 
                   8721:   Args:
                   8722:    docuname: username or courseid of destination for the file
                   8723:    docudom: domain of user/course of destination for the file
                   8724:    dir: dir to create (including any subdirs under userfiles)
                   8725: 
                   8726: =item *
                   8727: 
                   8728: removeuserfile(): removes a file that exists in userfiles
                   8729: 
                   8730:   Args:
                   8731:    docuname: username or courseid of destination for the file
                   8732:    docudom: domain of user/course of destination for the file
                   8733:    fname: filname to delete (including any subdirs under userfiles)
                   8734: 
                   8735: =item *
                   8736: 
                   8737: removeuploadedurl(): convience function for removeuserfile()
                   8738: 
                   8739:   Args:
                   8740:    url:  a full /uploaded/... url to delete
                   8741: 
1.747     albertel 8742: =item * 
                   8743: 
                   8744: get_portfile_permissions():
                   8745:   Args:
                   8746:     domain: domain of user or course contain the portfolio files
                   8747:     user: name of user or num of course contain the portfolio files
                   8748:   Returns:
                   8749:     hashref of a dump of the proper file_permissions.db
                   8750:    
                   8751: 
                   8752: =item * 
                   8753: 
                   8754: get_access_controls():
                   8755: 
                   8756: Args:
                   8757:   current_permissions: the hash ref returned from get_portfile_permissions()
                   8758:   group: (optional) the group you want the files associated with
                   8759:   file: (optional) the file you want access info on
                   8760: 
                   8761: Returns:
1.749     raeburn  8762:     a hash (keys are file names) of hashes containing
                   8763:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   8764:         values are XML containing access control settings (see below) 
1.747     albertel 8765: 
                   8766: Internal notes:
                   8767: 
1.749     raeburn  8768:  access controls are stored in file_permissions.db as key=value pairs.
                   8769:     key -> path to file/file_name\0uniqueID:scope_end_start
                   8770:         where scope -> public,guest,course,group,domains or users.
                   8771:               end -> UNIX time for end of access (0 -> no end date)
                   8772:               start -> UNIX time for start of access
                   8773: 
                   8774:     value -> XML description of access control
                   8775:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   8776:             <start></start>
                   8777:             <end></end>
                   8778: 
                   8779:             <password></password>  for scope type = guest
                   8780: 
                   8781:             <domain></domain>     for scope type = course or group
                   8782:             <number></number>
                   8783:             <roles id="">
                   8784:              <role></role>
                   8785:              <access></access>
                   8786:              <section></section>
                   8787:              <group></group>
                   8788:             </roles>
                   8789: 
                   8790:             <dom></dom>         for scope type = domains
                   8791: 
                   8792:             <users>             for scope type = users
                   8793:              <user>
                   8794:               <uname></uname>
                   8795:               <udom></udom>
                   8796:              </user>
                   8797:             </users>
                   8798:            </scope> 
                   8799:               
                   8800:  Access data is also aggregated for each file in an additional key=value pair:
                   8801:  key -> path to file/file_name\0accesscontrol 
                   8802:  value -> reference to hash
                   8803:           hash contains key = value pairs
                   8804:           where key = uniqueID:scope_end_start
                   8805:                 value = UNIX time record was last updated
                   8806: 
                   8807:           Used to improve speed of look-ups of access controls for each file.  
                   8808:  
                   8809:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   8810: 
                   8811: modify_access_controls():
                   8812: 
                   8813: Modifies access controls for a portfolio file
                   8814: Args
                   8815: 1. file name
                   8816: 2. reference to hash of required changes,
                   8817: 3. domain
                   8818: 4. username
                   8819:   where domain,username are the domain of the portfolio owner 
                   8820:   (either a user or a course) 
                   8821: 
                   8822: Returns:
                   8823: 1. result of additions or updates ('ok' or 'error', with error message). 
                   8824: 2. result of deletions ('ok' or 'error', with error message).
                   8825: 3. reference to hash of any new or updated access controls.
                   8826: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   8827:    key = integer (inbound ID)
                   8828:    value = uniqueID  
1.747     albertel 8829: 
1.608     albertel 8830: =back
                   8831: 
1.243     albertel 8832: =head2 HTTP Helper Routines
                   8833: 
                   8834: =over 4
                   8835: 
1.191     harris41 8836: =item *
                   8837: 
                   8838: escape() : unpack non-word characters into CGI-compatible hex codes
                   8839: 
                   8840: =item *
                   8841: 
                   8842: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   8843: 
1.243     albertel 8844: =back
                   8845: 
                   8846: =head1 PRIVATE SUBROUTINES
                   8847: 
                   8848: =head2 Underlying communication routines (Shouldn't call)
                   8849: 
                   8850: =over 4
                   8851: 
                   8852: =item *
                   8853: 
                   8854: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   8855: 
                   8856: =item *
                   8857: 
                   8858: reply() : uses subreply to send a message to remote machine, logs all failures
                   8859: 
                   8860: =item *
                   8861: 
                   8862: critical() : passes a critical message to another server; if cannot
                   8863: get through then place message in connection buffer directory and
                   8864: returns con_delayed, if incapable of saving message, returns
                   8865: con_failed
                   8866: 
                   8867: =item *
                   8868: 
                   8869: reconlonc() : tries to reconnect lonc client processes.
                   8870: 
                   8871: =back
                   8872: 
                   8873: =head2 Resource Access Logging
                   8874: 
                   8875: =over 4
                   8876: 
                   8877: =item *
                   8878: 
                   8879: flushcourselogs() : flush (save) buffer logs and access logs
                   8880: 
                   8881: =item *
                   8882: 
                   8883: courselog($what) : save message for course in hash
                   8884: 
                   8885: =item *
                   8886: 
                   8887: courseacclog($what) : save message for course using &courselog().  Perform
                   8888: special processing for specific resource types (problems, exams, quizzes, etc).
                   8889: 
1.191     harris41 8890: =item *
                   8891: 
                   8892: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   8893: as a PerlChildExitHandler
1.243     albertel 8894: 
                   8895: =back
                   8896: 
                   8897: =head2 Other
                   8898: 
                   8899: =over 4
                   8900: 
                   8901: =item *
                   8902: 
                   8903: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 8904: 
                   8905: =back
                   8906: 
                   8907: =cut

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